123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627 |
- using System.Collections;
- using System.Globalization;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using Jint.Native;
- using Jint.Native.Function;
- using Jint.Runtime;
- using Jint.Runtime.Interop;
- using Jint.Tests.Runtime.Converters;
- using Jint.Tests.Runtime.Domain;
- using Jint.Tests.Runtime.TestClasses;
- using MongoDB.Bson;
- using Shapes;
- namespace Jint.Tests.Runtime;
- public partial class InteropTests : IDisposable
- {
- private readonly Engine _engine;
- public InteropTests()
- {
- _engine = new Engine(cfg => cfg.AllowClr(
- typeof(Shape).GetTypeInfo().Assembly,
- typeof(Console).GetTypeInfo().Assembly,
- typeof(File).GetTypeInfo().Assembly))
- .SetValue("log", new Action<object>(Console.WriteLine))
- .SetValue("assert", new Action<bool>(Assert.True))
- .SetValue("equal", new Action<object, object>(Assert.Equal))
- ;
- }
- void IDisposable.Dispose()
- {
- }
- private void RunTest(string source)
- {
- _engine.Execute(source);
- }
- public class Foo
- {
- public static Bar GetBar()
- {
- return new Bar();
- }
- }
- public class Bar
- {
- public string Test { get; set; } = "123";
- }
- [Fact]
- public void ShouldStringifyNetObjects()
- {
- _engine.SetValue("foo", new Foo());
- var json = _engine.Evaluate("JSON.stringify(foo.GetBar())").AsString();
- Assert.Equal("{\"Test\":\"123\"}", json);
- }
- [Fact]
- public void EngineShouldStringifyADictionary()
- {
- var engine = new Engine();
- var d = new Hashtable();
- d["Values"] = 1;
- engine.SetValue("d", d);
- Assert.Equal("{\"Values\":1}", engine.Evaluate($"JSON.stringify(d)").AsString());
- }
- [Fact]
- public void EngineShouldStringifyADictionaryOfStringAndObjectCorrectly()
- {
- var engine = new Engine();
- var dictionary = new Dictionary<string, object>
- {
- { "foo", 5 },
- { "bar", "A string" }
- };
- engine.SetValue(nameof(dictionary), dictionary);
- var result = engine.Evaluate($"JSON.stringify({nameof(dictionary)})").AsString();
- Assert.Equal("{\"foo\":5,\"bar\":\"A string\"}", result);
- }
- [Fact]
- public void EngineShouldRoundtripParsedJSONBackToStringCorrectly()
- {
- var engine = new Engine();
- const string json = "{\"foo\":5,\"bar\":\"A string\"}";
- var parsed = engine.Evaluate($"JSON.parse('{json}')").ToObject();
- engine.SetValue(nameof(parsed), parsed);
- var result = engine.Evaluate($"JSON.stringify({nameof(parsed)})").AsString();
- Assert.Equal(json, result);
- }
- [Fact]
- public void PrimitiveTypesCanBeSet()
- {
- _engine.SetValue("x", 10);
- _engine.SetValue("y", true);
- _engine.SetValue("z", "foo");
- RunTest(@"
- assert(x === 10);
- assert(y === true);
- assert(z === 'foo');
- ");
- }
- [Fact]
- public void TypePropertyAccess()
- {
- var userClass = new Person();
- var result = new Engine()
- .SetValue("userclass", userClass)
- .Evaluate("userclass.TypeProperty.Name;")
- .AsString();
- Assert.Equal("Person", result);
- }
- [Fact]
- public void CanAccessMemberNamedItem()
- {
- _engine.Execute(@"
- function item2(arg) {
- return arg.item2
- }
- function item1(arg) {
- return arg.item
- }
- function item3(arg) {
- return arg.Item
- }
- ");
- var argument = new Dictionary<string, object>
- {
- { "item2", "item2 value" },
- { "item", "item value" },
- { "Item", "Item value" }
- };
- Assert.Equal("item2 value", _engine.Invoke("item2", argument));
- Assert.Equal("item value", _engine.Invoke("item1", argument));
- Assert.Equal("Item value", _engine.Invoke("item3", argument));
- var company = new Company("Acme Ltd");
- _engine.SetValue("c", company);
- Assert.Equal("item thingie", _engine.Evaluate("c.Item"));
- Assert.Equal("item thingie", _engine.Evaluate("c.item"));
- Assert.Equal("value", _engine.Evaluate("c['key']"));
- }
- [Fact]
- public void DelegatesCanBeSet()
- {
- _engine.SetValue("square", new Func<double, double>(x => x * x));
- RunTest(@"
- assert(square(10) === 100);
- ");
- }
- [Fact]
- public void DelegateWithNullableParameterCanBePassedANull()
- {
- _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
- RunTest(@"
- assert(isnull(null) === true);
- ");
- }
- [Fact]
- public void DelegateWithObjectParameterCanBePassedANull()
- {
- _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
- RunTest(@"
- assert(isnull(null) === true);
- ");
- }
- [Fact]
- public void DelegateWithNullableParameterCanBePassedAnUndefined()
- {
- _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
- RunTest(@"
- assert(isnull(undefined) === true);
- ");
- }
- [Fact]
- public void DelegateWithObjectParameterCanBePassedAnUndefined()
- {
- _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
- RunTest(@"
- assert(isnull(undefined) === true);
- ");
- }
- [Fact]
- public void DelegateWithNullableParameterCanBeExcluded()
- {
- _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
- RunTest(@"
- assert(isnull() === true);
- ");
- }
- [Fact]
- public void DelegateWithObjectParameterCanBeExcluded()
- {
- _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
- RunTest(@"
- assert(isnull() === true);
- ");
- }
- [Fact]
- public void DynamicDelegateCanBeSet()
- {
- #if NETFRAMEWORK
- var parameters = new[]
- {
- System.Linq.Expressions.Expression.Parameter(typeof(int)),
- System.Linq.Expressions.Expression.Parameter(typeof(int))
- };
- var exp = System.Linq.Expressions.Expression.Add(parameters[0], parameters[1]);
- var del = System.Linq.Expressions.Expression.Lambda(exp, parameters).Compile();
- _engine.SetValue("add", del);
- RunTest(@"
- assert(add(1,1) === 2);
- ");
- #endif
- }
- [Fact]
- public void ExtraParametersAreIgnored()
- {
- _engine.SetValue("passNumber", new Func<int, int>(x => x));
- RunTest(@"
- assert(passNumber(123,'test',{},[],null) === 123);
- ");
- }
- private delegate string callParams(params object[] values);
- private delegate string callArgumentAndParams(string firstParam, params object[] values);
- [Fact]
- public void DelegatesWithParamsParameterCanBeInvoked()
- {
- var a = new A();
- _engine.SetValue("callParams", new callParams(a.Call13));
- _engine.SetValue("callArgumentAndParams", new callArgumentAndParams(a.Call14));
- RunTest(@"
- assert(callParams('1','2','3') === '1,2,3');
- assert(callParams('1') === '1');
- assert(callParams() === '');
- assert(callArgumentAndParams('a','1','2','3') === 'a:1,2,3');
- assert(callArgumentAndParams('a','1') === 'a:1');
- assert(callArgumentAndParams('a') === 'a:');
- assert(callArgumentAndParams() === ':');
- ");
- }
- [Fact]
- public void CanGetObjectProperties()
- {
- var p = new Person
- {
- Name = "Mickey Mouse"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Name === 'Mickey Mouse');
- ");
- }
- [Fact]
- public void CanInvokeObjectMethods()
- {
- var p = new Person
- {
- Name = "Mickey Mouse"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.ToString() === 'Mickey Mouse');
- ");
- }
- [Fact]
- public void CanInvokeObjectMethodsWithPascalCase()
- {
- var p = new Person
- {
- Name = "Mickey Mouse"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.toString() === 'Mickey Mouse');
- ");
- }
- [Fact]
- public void CanSetObjectProperties()
- {
- var p = new Person
- {
- Name = "Mickey Mouse"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- p.Name = 'Donald Duck';
- assert(p.Name === 'Donald Duck');
- ");
- Assert.Equal("Donald Duck", p.Name);
- }
- [Fact]
- public void CanGetIndexUsingStringKey()
- {
- var dictionary = new Dictionary<string, Person>();
- dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
- dictionary.Add("person2", new Person { Name = "Goofy" });
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- assert(dictionary['person1'].Name === 'Mickey Mouse');
- assert(dictionary['person2'].Name === 'Goofy');
- ");
- }
- [Fact]
- public void CanSetIndexUsingStringKey()
- {
- var dictionary = new Dictionary<string, Person>();
- dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
- dictionary.Add("person2", new Person { Name = "Goofy" });
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- dictionary['person2'].Name = 'Donald Duck';
- assert(dictionary['person2'].Name === 'Donald Duck');
- ");
- Assert.Equal("Donald Duck", dictionary["person2"].Name);
- }
- [Fact]
- public void CanGetIndexUsingIntegerKey()
- {
- var dictionary = new Dictionary<int, string>();
- dictionary.Add(1, "Mickey Mouse");
- dictionary.Add(2, "Goofy");
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- assert(dictionary[1] === 'Mickey Mouse');
- assert(dictionary[2] === 'Goofy');
- ");
- }
- [Fact]
- public void CanSetIndexUsingIntegerKey()
- {
- var dictionary = new Dictionary<int, string>();
- dictionary.Add(1, "Mickey Mouse");
- dictionary.Add(2, "Goofy");
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- dictionary[2] = 'Donald Duck';
- assert(dictionary[2] === 'Donald Duck');
- ");
- Assert.Equal("Mickey Mouse", dictionary[1]);
- Assert.Equal("Donald Duck", dictionary[2]);
- }
- private class DoubleIndexedClass
- {
- public int this[int index] => index;
- public string this[string index] => index;
- }
- [Fact]
- public void CanGetIndexUsingBothIntAndStringIndex()
- {
- var dictionary = new DoubleIndexedClass();
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- assert(dictionary[1] === 1);
- assert(dictionary['test'] === 'test');
- ");
- }
- [Fact]
- public void CanUseGenericMethods()
- {
- var dictionary = new Dictionary<int, string>();
- dictionary.Add(1, "Mickey Mouse");
- _engine.SetValue("dictionary", dictionary);
- RunTest(@"
- dictionary.Add(2, 'Goofy');
- assert(dictionary[2] === 'Goofy');
- ");
- Assert.Equal("Mickey Mouse", dictionary[1]);
- Assert.Equal("Goofy", dictionary[2]);
- }
- [Fact]
- public void CanUseMultiGenericTypes()
- {
- RunTest(@"
- var type = System.Collections.Generic.Dictionary(System.Int32, System.String);
- var dictionary = new type();
- dictionary.Add(1, 'Mickey Mouse');
- dictionary.Add(2, 'Goofy');
- assert(dictionary[2] === 'Goofy');
- ");
- }
- [Fact]
- public void CanUseIndexOnCollection()
- {
- var collection = new System.Collections.ObjectModel.Collection<string>();
- collection.Add("Mickey Mouse");
- collection.Add("Goofy");
- _engine.SetValue("dictionary", collection);
- RunTest(@"
- dictionary[1] = 'Donald Duck';
- assert(dictionary[1] === 'Donald Duck');
- ");
- Assert.Equal("Mickey Mouse", collection[0]);
- Assert.Equal("Donald Duck", collection[1]);
- }
- [Fact]
- public void CanUseIndexOnList()
- {
- var list = new List<object>(2);
- list.Add("Mickey Mouse");
- list.Add("Goofy");
- _engine.SetValue("list", list);
- _engine.Evaluate("list[1] = 'Donald Duck';");
- Assert.Equal("Donald Duck", _engine.Evaluate("list[1]").AsString());
- Assert.Equal("Mickey Mouse", list[0]);
- Assert.Equal("Donald Duck", list[1]);
- }
- [Fact]
- public void ShouldForOfOnLists()
- {
- _engine.SetValue("list", new List<string> { "a", "b" });
- var result = _engine.Evaluate("var l = ''; for (var x of list) l += x; return l;").AsString();
- Assert.Equal("ab", result);
- }
- [Fact]
- public void ShouldForOfOnArrays()
- {
- _engine.SetValue("arr", new[] { "a", "b" });
- var result = _engine.Evaluate("var l = ''; for (var x of arr) l += x; return l;").AsString();
- Assert.Equal("ab", result);
- }
- [Fact]
- public void ShouldForOfOnDictionaries()
- {
- _engine.SetValue("dict", new Dictionary<string, string> { { "a", "1" }, { "b", "2" } });
- var result = _engine.Evaluate("var l = ''; for (var x of dict) l += x; return l;").AsString();
- Assert.Equal("a,1b,2", result);
- }
- [Fact]
- public void ShouldForOfOnEnumerable()
- {
- _engine.SetValue("c", new Company("name"));
- var result = _engine.Evaluate("var l = ''; for (var x of c.getNameChars()) l += x + ','; return l;").AsString();
- Assert.Equal("n,a,m,e,", result);
- }
- [Fact]
- public void ShouldThrowWhenForOfOnObject()
- {
- // normal objects are not iterable in javascript
- var o = new { A = 1, B = 2 };
- _engine.SetValue("anonymous", o);
- var ex = Assert.Throws<JavaScriptException>(() => _engine.Evaluate("for (var x of anonymous) {}"));
- Assert.Equal("The value is not iterable", ex.Message);
- }
- [Fact]
- public void CanAccessAnonymousObject()
- {
- var p = new
- {
- Name = "Mickey Mouse"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Name === 'Mickey Mouse');
- ");
- }
- [Fact]
- public void CanAccessAnonymousObjectProperties()
- {
- var p = new
- {
- Address = new
- {
- City = "Mouseton"
- }
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Address.City === 'Mouseton');
- ");
- }
- [Fact]
- public void PocosCanReturnJsValueDirectly()
- {
- var o = new
- {
- x = new JsNumber(1),
- y = new JsString("string")
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.x === 1);
- assert(o.y === 'string');
- ");
- }
- [Fact]
- public void PocosCanReturnObjectInstanceDirectly()
- {
- var x = new JsObject(_engine);
- x.Set("foo", new JsString("bar"));
- var o = new
- {
- x
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.x.foo === 'bar');
- ");
- }
- [Fact]
- public void DateTimeIsConvertedToDate()
- {
- var o = new
- {
- z = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.z.valueOf() === 0);
- ");
- }
- [Fact]
- public void DateTimeOffsetIsConvertedToDate()
- {
- var o = new
- {
- z = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan())
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.z.valueOf() === 0);
- ");
- }
- [Fact]
- public void EcmaValuesAreAutomaticallyConvertedWhenSetInPoco()
- {
- var p = new Person
- {
- Name = "foo"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Name === 'foo');
- assert(p.Age === 0);
- p.Name = 'bar';
- p.Age = 10;
- ");
- Assert.Equal("bar", p.Name);
- Assert.Equal(10, p.Age);
- }
- [Fact]
- public void EcmaValuesAreAutomaticallyConvertedToBestMatchWhenSetInPoco()
- {
- var p = new Person
- {
- Name = "foo"
- };
- _engine.SetValue("p", p);
- RunTest(@"
- p.Name = 10;
- p.Age = '20';
- ");
- Assert.Equal("10", p.Name);
- Assert.Equal(20, p.Age);
- }
- [Fact]
- public void ShouldCallInstanceMethodWithoutArgument()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call1() === 0);
- ");
- }
- [Fact]
- public void ShouldCallInstanceMethodOverloadArgument()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call1(1) === 1);
- ");
- }
- [Fact]
- public void ShouldCallInstanceMethodWithString()
- {
- var p = new Person();
- _engine.SetValue("a", new A());
- _engine.SetValue("p", p);
- RunTest(@"
- p.Name = a.Call2('foo');
- assert(p.Name === 'foo');
- ");
- Assert.Equal("foo", p.Name);
- }
- [Fact]
- public void CanUseTrim()
- {
- var p = new Person { Name = "Mickey Mouse " };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Name === 'Mickey Mouse ');
- p.Name = p.Name.trim();
- assert(p.Name === 'Mickey Mouse');
- ");
- Assert.Equal("Mickey Mouse", p.Name);
- }
- [Fact]
- public void CanUseMathFloor()
- {
- var p = new Person();
- _engine.SetValue("p", p);
- RunTest(@"
- p.Age = Math.floor(1.6);p
- assert(p.Age === 1);
- ");
- Assert.Equal(1, p.Age);
- }
- [Fact]
- public void CanUseDelegateAsFunction()
- {
- var even = new Func<int, bool>(x => x % 2 == 0);
- _engine.SetValue("even", even);
- RunTest(@"
- assert(even(2) === true);
- ");
- }
- private struct TestStruct
- {
- public int Value;
- public TestStruct(int value)
- {
- Value = value;
- }
- }
- private class TestClass
- {
- public string String { get; set; }
- public int Int { get; set; }
- public int? NullableInt { get; set; }
- public DateTime? NullableDate { get; set; }
- public bool? NullableBool { get; set; }
- public bool Bool { get; set; }
- public TestEnumInt32? NullableEnum { get; set; }
- public TestStruct? NullableStruct { get; set; }
- public void SetBool(bool value)
- {
- Bool = value;
- }
- public void SetInt(int value)
- {
- Int = value;
- }
- public void SetString(string value)
- {
- String = value;
- }
- }
- [Fact]
- public void CanSetNullablePropertiesOnPocos()
- {
- var instance = new TestClass();
- _engine.SetValue("instance", instance);
- _engine.SetValue("TestStruct", typeof(TestStruct));
- RunTest(@"
- instance.NullableInt = 2;
- instance.NullableDate = new Date();
- instance.NullableBool = true;
- instance.NullableEnum = 1;
- instance.NullableStruct = new TestStruct(5);
- assert(instance.NullableInt===2);
- assert(instance.NullableDate!=null);
- assert(instance.NullableBool===true);
- assert(instance.NullableEnum===1);
- assert(instance.NullableStruct.Value===5);
- ");
- }
- private class ReadOnlyList : IReadOnlyList<Person>
- {
- private readonly Person[] _data;
- public ReadOnlyList(params Person[] data)
- {
- _data = data;
- }
- public IEnumerator<Person> GetEnumerator()
- {
- return ((IEnumerable<Person>) _data).GetEnumerator();
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return _data.GetEnumerator();
- }
- public int Count => _data.Length;
- public Person this[int index] => _data[index];
- }
- [Fact]
- public void CanAddArrayPrototypeForArrayLikeClrObjects()
- {
- var e = new Engine(cfg => cfg
- .AllowClr(typeof(Person).Assembly)
- );
- var person = new Person
- {
- Age = 12,
- Name = "John"
- };
- dynamic obj = new
- {
- values = new ReadOnlyList(person)
- };
- e.SetValue("o", obj);
- var name = e.Evaluate("o.values.filter(x => x.age == 12)[0].name").ToString();
- Assert.Equal("John", name);
- }
- [Fact]
- public void CanSetIsConcatSpreadableForArrays()
- {
- var engine = new Engine();
- engine
- .SetValue("list1", new List<string> { "A", "B", "C" })
- .SetValue("list2", new List<string> { "D", "E", "F" })
- .Execute("var array1 = ['A', 'B', 'C'];")
- .Execute("var array2 = ['D', 'E', 'F'];");
- Assert.True(engine.Evaluate("list1[Symbol.isConcatSpreadable] = true; list1[Symbol.isConcatSpreadable];").AsBoolean());
- Assert.True(engine.Evaluate("list2[Symbol.isConcatSpreadable] = true; list2[Symbol.isConcatSpreadable];").AsBoolean());
- Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(array1);"));
- Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(array2);"));
- Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(list1);"));
- Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(list2);"));
- const string Concatenated = "[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]";
- Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(array2));"));
- Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(list2));"));
- Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(array2));"));
- Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(list2));"));
- Assert.False(engine.Evaluate("list1[Symbol.isConcatSpreadable] = false; list1[Symbol.isConcatSpreadable];").AsBoolean());
- Assert.False(engine.Evaluate("list2[Symbol.isConcatSpreadable] = false; list2[Symbol.isConcatSpreadable];").AsBoolean());
- Assert.Equal("[[\"A\",\"B\",\"C\"]]", engine.Evaluate("JSON.stringify([].concat(list1));"));
- Assert.Equal("[[\"A\",\"B\",\"C\"],[\"D\",\"E\",\"F\"]]", engine.Evaluate("JSON.stringify(list1.concat(list2));"));
- }
- [Fact]
- public void ShouldConvertArrayToArrayInstance()
- {
- var result = _engine
- .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
- .Evaluate("values.filter(function(x){ return x % 2 == 0; })");
- var parts = result.ToObject();
- Assert.True(parts.GetType().IsArray);
- Assert.Equal(3, ((object[]) parts).Length);
- Assert.Equal(2d, ((object[]) parts)[0]);
- Assert.Equal(4d, ((object[]) parts)[1]);
- Assert.Equal(6d, ((object[]) parts)[2]);
- }
- [Fact]
- public void ShouldConvertListsToArrayInstance()
- {
- var result = _engine
- .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
- .Evaluate("new Array(values).filter(function(x){ return x % 2 == 0; })");
- var parts = result.ToObject();
- Assert.True(parts.GetType().IsArray);
- Assert.Equal(3, ((object[]) parts).Length);
- Assert.Equal(2d, ((object[]) parts)[0]);
- Assert.Equal(4d, ((object[]) parts)[1]);
- Assert.Equal(6d, ((object[]) parts)[2]);
- }
- [Fact]
- public void ShouldConvertArrayInstanceToArray()
- {
- var parts = _engine.Evaluate("'[email protected]'.split('@');").ToObject();
- Assert.True(parts.GetType().IsArray);
- Assert.Equal(2, ((object[]) parts).Length);
- Assert.Equal("foo", ((object[]) parts)[0]);
- Assert.Equal("bar.com", ((object[]) parts)[1]);
- }
- [Fact]
- public void ShouldLoopWithNativeEnumerator()
- {
- JsValue adder(JsValue argValue)
- {
- var args = argValue.AsArray();
- double sum = 0;
- foreach (var item in args)
- {
- if (item.IsNumber())
- {
- sum += item.AsNumber();
- }
- }
- return sum;
- }
- var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
- .Evaluate("getSum([1,2,3]);");
- Assert.True(result == 6);
- }
- [Fact]
- public void ShouldConvertBooleanInstanceToBool()
- {
- var value = _engine.Evaluate("new Boolean(true)").ToObject();
- Assert.Equal(typeof(bool), value.GetType());
- Assert.Equal(true, value);
- }
- [Fact]
- public void ShouldAllowBooleanCoercion()
- {
- var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Boolean; });
- engine.SetValue("o", new TestClass());
- Assert.True(engine.Evaluate("o.Bool = 1; return o.Bool;").AsBoolean());
- Assert.True(engine.Evaluate("o.Bool = 'dog'; return o.Bool;").AsBoolean());
- Assert.True(engine.Evaluate("o.Bool = {}; return o.Bool;").AsBoolean());
- Assert.False(engine.Evaluate("o.Bool = 0; return o.Bool;").AsBoolean());
- Assert.False(engine.Evaluate("o.Bool = ''; return o.Bool;").AsBoolean());
- Assert.False(engine.Evaluate("o.Bool = null; return o.Bool;").AsBoolean());
- Assert.False(engine.Evaluate("o.Bool = undefined; return o.Bool;").AsBoolean());
- engine.Evaluate("class MyClass { valueOf() { return 42; } }");
- Assert.Equal(true, engine.Evaluate("let obj = new MyClass(); o.Bool = obj; return o.Bool;").AsBoolean());
- engine.SetValue("func3", new Action<bool, bool, bool>((param1, param2, param3) =>
- {
- Assert.True(param1);
- Assert.True(param2);
- Assert.True(param3);
- }));
- engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
- Assert.Equal(true, engine.Evaluate("o.SetBool(42); return o.Bool;").AsBoolean());
- Assert.Equal(true, engine.Evaluate("o.SetBool(obj); return o.Bool;").AsBoolean());
- Assert.Equal(true, engine.Evaluate("o.SetBool([ 1, 2, 3].length); return o.Bool;").AsBoolean());
- }
- [Fact]
- public void ShouldAllowNumberCoercion()
- {
- var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Number; });
- engine.SetValue("o", new TestClass());
- Assert.Equal(1, engine.Evaluate("o.Int = true; return o.Int;").AsNumber());
- Assert.Equal(0, engine.Evaluate("o.Int = false; return o.Int;").AsNumber());
- engine.Evaluate("class MyClass { valueOf() { return 42; } }");
- Assert.Equal(42, engine.Evaluate("let obj = new MyClass(); o.Int = obj; return o.Int;").AsNumber());
- // but null and undefined should be injected as nulls to nullable objects
- Assert.True(engine.Evaluate("o.NullableInt = null; return o.NullableInt;").IsNull());
- Assert.True(engine.Evaluate("o.NullableInt = undefined; return o.NullableInt;").IsNull());
- engine.SetValue("func3", new Action<int, double, long>((param1, param2, param3) =>
- {
- Assert.Equal(1, param1);
- Assert.Equal(42, param2);
- Assert.Equal(3, param3);
- }));
- engine.Evaluate("func3(true, obj, [ 1, 2, 3].length)");
- Assert.Equal(1, engine.Evaluate("o.SetInt(true); return o.Int;").AsNumber());
- Assert.Equal(42, engine.Evaluate("o.SetInt(obj); return o.Int;").AsNumber());
- Assert.Equal(3, engine.Evaluate("o.SetInt([ 1, 2, 3].length); return o.Int;").AsNumber());
- }
- [Fact]
- public void ShouldAllowStringCoercion()
- {
- var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.String; });
- // basic premise, booleans in JS are lower-case, so should the the toString under interop
- Assert.Equal("true", engine.Evaluate("'' + true").AsString());
- engine.SetValue("o", new TestClass());
- Assert.Equal("false", engine.Evaluate("'' + o.Bool").AsString());
- Assert.Equal("true", engine.Evaluate("o.Bool = true; o.String = o.Bool; return o.String;").AsString());
- Assert.Equal("true", engine.Evaluate("o.String = true; return o.String;").AsString());
- engine.SetValue("func1", new Func<bool>(() => true));
- Assert.Equal("true", engine.Evaluate("'' + func1()").AsString());
- engine.SetValue("func2", new Func<JsValue>(() => JsBoolean.True));
- Assert.Equal("true", engine.Evaluate("'' + func2()").AsString());
- // but null and undefined should be injected as nulls to c# objects
- Assert.True(engine.Evaluate("o.String = null; return o.String;").IsNull());
- Assert.True(engine.Evaluate("o.String = undefined; return o.String;").IsNull());
- Assert.Equal("1,2,3", engine.Evaluate("o.String = [ 1, 2, 3 ]; return o.String;").AsString());
- engine.Evaluate("class MyClass { toString() { return 'hello world'; } }");
- Assert.Equal("hello world", engine.Evaluate("let obj = new MyClass(); o.String = obj; return o.String;").AsString());
- engine.SetValue("func3", new Action<string, string, string>((param1, param2, param3) =>
- {
- Assert.Equal("true", param1);
- Assert.Equal("hello world", param2);
- Assert.Equal("1,2,3", param3);
- }));
- engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
- Assert.Equal("true", engine.Evaluate("o.SetString(true); return o.String;").AsString());
- Assert.Equal("hello world", engine.Evaluate("o.SetString(obj); return o.String;").AsString());
- Assert.Equal("1,2,3", engine.Evaluate("o.SetString([ 1, 2, 3]); return o.String;").AsString());
- }
- [Fact]
- public void ShouldConvertDateInstanceToDateTime()
- {
- var result = _engine.Evaluate("new Date(0)");
- var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
- Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
- Assert.Equal(DateTimeKind.Utc, value.Kind);
- }
- [Fact]
- public void ShouldConvertDateInstanceToLocalDateTime()
- {
- TimeZoneInfo timeZone;
- try
- {
- timeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Helsinki");
- }
- catch (TimeZoneNotFoundException)
- {
- timeZone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
- }
- var engine = new Engine(options =>
- {
- options.TimeZone = timeZone;
- options.Interop.DateTimeKind = DateTimeKind.Local;
- });
- var result = engine.Evaluate("new Date(0)");
- var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
- Assert.Equal(new DateTime(1970, 1, 1, 2, 0, 0, DateTimeKind.Local), value);
- Assert.Equal(DateTimeKind.Local, value.Kind);
- }
- [Fact]
- public void ShouldConvertNumberInstanceToDouble()
- {
- var result = _engine.Evaluate("new Number(10)");
- var value = result.ToObject();
- Assert.Equal(typeof(double), value.GetType());
- Assert.Equal(10d, value);
- }
- [Fact]
- public void ShouldConvertStringInstanceToString()
- {
- var value = _engine.Evaluate("new String('foo')").ToObject();
- Assert.Equal(typeof(string), value.GetType());
- Assert.Equal("foo", value);
- }
- [Fact]
- public void ShouldNotTryToConvertCompatibleTypes()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call3('foo') === 'foo');
- assert(a.Call3(1) === '1');
- ");
- }
- [Fact]
- public void ShouldNotTryToConvertDerivedTypes()
- {
- _engine.SetValue("a", new A());
- _engine.SetValue("p", new Person { Name = "Mickey" });
- RunTest(@"
- assert(a.Call4(p) === 'Mickey');
- ");
- }
- [Fact]
- public void ShouldExecuteFunctionCallBackAsDelegate()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call5(function(a,b){ return a+b }) === '1foo');
- ");
- }
- [Fact]
- public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
- ");
- }
- [Fact]
- public void ShouldExecuteFunctionCallBackAsPredicate()
- {
- _engine.SetValue("a", new A());
- // Func<>
- RunTest(@"
- assert(a.Call8(function(){ return 'foo'; }) === 'foo');
- ");
- }
- [Fact]
- public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
- {
- _engine.SetValue("a", new A());
- // Func<,>
- RunTest(@"
- assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
- ");
- }
- [Fact]
- public void ShouldExecuteActionCallBackAsPredicate()
- {
- _engine.SetValue("a", new A());
- // Action
- RunTest(@"
- var value;
- a.Call9(function(){ value = 'foo'; });
- assert(value === 'foo');
- ");
- }
- [Fact]
- public void ShouldExecuteActionWithParameterCallBackAsPredicate()
- {
- _engine.SetValue("a", new A());
- // Action<>
- RunTest(@"
- var value;
- a.Call10('foo', function(b){ value = b; });
- assert(value === 'foo');
- ");
- }
- [Fact]
- public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
- {
- _engine.SetValue("a", new A());
- // Action<,>
- RunTest(@"
- var value;
- a.Call11('foo', 'bar', function(a,b){ value = a + b; });
- assert(value === 'foobar');
- ");
- }
- [Fact]
- public void ShouldExecuteFunc()
- {
- _engine.SetValue("a", new A());
- // Func<int, int>
- RunTest(@"
- var result = a.Call12(42, function(a){ return a + a; });
- assert(result === 84);
- ");
- }
- [Fact]
- public void ShouldExecuteActionCallbackOnEventChanged()
- {
- var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
- Assert.True(collection.Count == 0);
- _engine.SetValue("collection", collection);
- RunTest(@"
- var callCount = 0;
- var handler = function(sender, eventArgs) { callCount++; } ;
- collection.add_CollectionChanged(handler);
- collection.Add('test');
- collection.remove_CollectionChanged(handler);
- collection.Add('test');
- var json = JSON.stringify(Object.keys(handler));
- ");
- var callCount = (int) _engine.GetValue("callCount").AsNumber();
- Assert.Equal(1, callCount);
- Assert.Equal(2, collection.Count);
- // make sure our delegate holder is hidden
- Assert.Equal("[]", _engine.Evaluate("json"));
- }
- [Fact]
- public void ShouldUseSystemIO()
- {
- RunTest(@"
- var filename = System.IO.Path.GetTempFileName();
- var sw = System.IO.File.CreateText(filename);
- sw.Write('Hello World');
- sw.Dispose();
- var content = System.IO.File.ReadAllText(filename);
- System.Console.WriteLine(content);
- assert(content === 'Hello World');
- ");
- }
- [Fact]
- public void ShouldImportNamespace()
- {
- RunTest(@"
- var Shapes = importNamespace('Shapes');
- var circle = new Shapes.Circle();
- assert(circle.Radius === 0);
- assert(circle.Perimeter() === 0);
- ");
- }
- [Fact]
- public void ShouldImportEmptyNamespace()
- {
- RunTest("""
- var nullSpace = importNamespace(null);
- var c1 = new nullSpace.ShapeWithoutNameSpace();
- assert(c1.Perimeter() === 42);
- var undefinedSpace = importNamespace(undefined);
- var c2 = new undefinedSpace.ShapeWithoutNameSpace();
- assert(c2.Perimeter() === 42);
- var defaultSpace = importNamespace();
- var c3 = new defaultSpace.ShapeWithoutNameSpace();
- assert(c3.Perimeter() === 42);
- """);
- }
- [Fact]
- public void ShouldConstructReferenceTypeWithParameters()
- {
- RunTest(@"
- var Shapes = importNamespace('Shapes');
- var circle = new Shapes.Circle(1);
- assert(circle.Radius === 1);
- assert(circle.Perimeter() === Math.PI);
- ");
- }
- [Fact]
- public void ShouldConstructValueTypeWithoutParameters()
- {
- RunTest(@"
- var guid = new System.Guid();
- assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
- ");
- }
- [Fact]
- public void ShouldInvokeAFunctionByName()
- {
- RunTest(@"
- function add(x, y) { return x + y; }
- ");
- Assert.Equal(3, _engine.Invoke("add", 1, 2));
- }
- [Fact]
- public void ShouldNotInvokeNonFunctionValue()
- {
- RunTest(@"
- var x= 10;
- ");
- Assert.Throws<JavaScriptException>(() => _engine.Invoke("x", 1, 2));
- }
- [Fact]
- public void CanGetField()
- {
- var o = new ClassWithField
- {
- Field = "Mickey Mouse"
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.Field === 'Mickey Mouse');
- ");
- }
- [Fact]
- public void CanSetField()
- {
- var o = new ClassWithField();
- _engine.SetValue("o", o);
- RunTest(@"
- o.Field = 'Mickey Mouse';
- assert(o.Field === 'Mickey Mouse');
- ");
- Assert.Equal("Mickey Mouse", o.Field);
- }
- [Fact]
- public void CanGetStaticField()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var statics = domain.ClassWithStaticFields;
- assert(statics.Get == 'Get');
- ");
- }
- [Fact]
- public void CanSetStaticField()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var statics = domain.ClassWithStaticFields;
- statics.Set = 'hello';
- assert(statics.Set == 'hello');
- ");
- Assert.Equal(ClassWithStaticFields.Set, "hello");
- }
- [Fact]
- public void CanGetStaticAccessor()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var statics = domain.ClassWithStaticFields;
- assert(statics.Getter == 'Getter');
- ");
- }
- [Fact]
- public void CanSetStaticAccessor()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var statics = domain.ClassWithStaticFields;
- statics.Setter = 'hello';
- assert(statics.Setter == 'hello');
- ");
- Assert.Equal(ClassWithStaticFields.Setter, "hello");
- }
- [Fact]
- public void CantSetStaticReadonly()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var statics = domain.ClassWithStaticFields;
- statics.Readonly = 'hello';
- assert(statics.Readonly == 'Readonly');
- ");
- Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
- }
- [Fact]
- public void CanSetCustomConverters()
- {
- var engine1 = new Engine();
- engine1.SetValue("p", new { Test = true });
- engine1.Execute("var result = p.Test;");
- Assert.True((bool) engine1.GetValue("result").ToObject());
- var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
- engine2.SetValue("p", new { Test = true });
- engine2.Execute("var result = p.Test;");
- Assert.False((bool) engine2.GetValue("result").ToObject());
- }
- [Fact]
- public void CanConvertEnumsToString()
- {
- var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
- .SetValue("assert", new Action<bool>(Assert.True));
- engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
- engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
- engine1.Execute("var result = p.Comparison;");
- Assert.Equal("CurrentCulture", (string) engine1.GetValue("result").ToObject());
- }
- [Fact]
- public void CanUserIncrementOperator()
- {
- var p = new Person
- {
- Age = 1
- };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(++p.Age === 2);
- ");
- Assert.Equal(2, p.Age);
- }
- [Fact]
- public void CanOverwriteValues()
- {
- _engine.SetValue("x", 3);
- _engine.SetValue("x", 4);
- RunTest(@"
- assert(x === 4);
- ");
- }
- [Fact]
- public void ShouldCreateGenericType()
- {
- RunTest(@"
- var ListOfString = System.Collections.Generic.List(System.String);
- var list = new ListOfString();
- list.Add('foo');
- list.Add(1);
- assert(2 === list.Count);
- ");
- }
- [Fact]
- public void EnumComparesByName()
- {
- var o = new
- {
- r = Colors.Red,
- b = Colors.Blue,
- g = Colors.Green,
- b2 = Colors.Red
- };
- _engine.SetValue("o", o);
- _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var colors = domain.Colors;
- assert(o.r === colors.Red);
- assert(o.g === colors.Green);
- assert(o.b === colors.Blue);
- assertFalse(o.b2 === colors.Blue);
- ");
- }
- [Fact]
- public void ShouldSetEnumProperty()
- {
- var s = new Circle
- {
- Color = Colors.Red
- };
- _engine.SetValue("s", s);
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var colors = domain.Colors;
- s.Color = colors.Blue;
- assert(s.Color === colors.Blue);
- ");
- _engine.SetValue("s", s);
- RunTest(@"
- s.Color = colors.Blue | colors.Green;
- assert(s.Color === colors.Blue | colors.Green);
- ");
- Assert.Equal(Colors.Blue | Colors.Green, s.Color);
- }
- private enum TestEnumInt32 : int
- {
- None,
- One = 1,
- Min = int.MaxValue,
- Max = int.MaxValue
- }
- private enum TestEnumUInt32 : uint
- {
- None,
- One = 1,
- Min = uint.MaxValue,
- Max = uint.MaxValue
- }
- private enum TestEnumInt64 : long
- {
- None,
- One = 1,
- Min = long.MaxValue,
- Max = long.MaxValue
- }
- private enum TestEnumUInt64 : ulong
- {
- None,
- One = 1,
- Min = ulong.MaxValue,
- Max = ulong.MaxValue
- }
- private void TestEnum<T>(T enumValue)
- {
- var i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
- var s = Convert.ToString(i, CultureInfo.InvariantCulture);
- var o = new Tuple<T>(enumValue);
- _engine.SetValue("o", o);
- RunTest("assert(o.Item1 === " + s + ");");
- }
- [Fact]
- public void ShouldWorkWithEnumInt32()
- {
- TestEnum(TestEnumInt32.None);
- TestEnum(TestEnumInt32.One);
- TestEnum(TestEnumInt32.Min);
- TestEnum(TestEnumInt32.Max);
- }
- [Fact]
- public void ShouldWorkWithEnumUInt32()
- {
- TestEnum(TestEnumUInt32.None);
- TestEnum(TestEnumUInt32.One);
- TestEnum(TestEnumUInt32.Min);
- TestEnum(TestEnumUInt32.Max);
- }
- [Fact]
- public void ShouldWorkWithEnumInt64()
- {
- TestEnum(TestEnumInt64.None);
- TestEnum(TestEnumInt64.One);
- TestEnum(TestEnumInt64.Min);
- TestEnum(TestEnumInt64.Max);
- }
- [Fact]
- public void ShouldWorkWithEnumUInt64()
- {
- TestEnum(TestEnumUInt64.None);
- TestEnum(TestEnumUInt64.One);
- TestEnum(TestEnumUInt64.Min);
- TestEnum(TestEnumUInt64.Max);
- }
- [Fact]
- public void EnumIsConvertedToNumber()
- {
- var o = new
- {
- r = Colors.Red,
- b = Colors.Blue,
- g = Colors.Green
- };
- _engine.SetValue("o", o);
- RunTest(@"
- assert(o.r === 0);
- assert(o.g === 1);
- assert(o.b === 10);
- ");
- }
- [Fact]
- public void ShouldConvertToEnum()
- {
- var s = new Circle
- {
- Color = Colors.Red
- };
- _engine.SetValue("s", s);
- RunTest(@"
- assert(s.Color === 0);
- s.Color = 10;
- assert(s.Color === 10);
- ");
- _engine.SetValue("s", s);
- RunTest(@"
- s.Color = 11;
- assert(s.Color === 11);
- ");
- Assert.Equal(Colors.Blue | Colors.Green, s.Color);
- }
- [Fact]
- public void ShouldUseExplicitPropertyGetter()
- {
- _engine.SetValue("c", new Company("ACME"));
- Assert.Equal("ACME", _engine.Evaluate("c.Name"));
- }
- [Fact]
- public void ShouldUseExplicitIndexerPropertyGetter()
- {
- var company = new Company("ACME");
- ((ICompany) company)["Foo"] = "Bar";
- _engine.SetValue("c", company);
- Assert.Equal("Bar", _engine.Evaluate("c.Foo"));
- }
- [Fact]
- public void ShouldUseExplicitPropertySetter()
- {
- _engine.SetValue("c", new Company("ACME"));
- Assert.Equal("Foo", _engine.Evaluate("c.Name = 'Foo'; c.Name;"));
- }
- [Fact]
- public void ShouldUseExplicitIndexerPropertySetter()
- {
- var company = new Company("ACME");
- ((ICompany) company)["Foo"] = "Bar";
- _engine.SetValue("c", company);
- RunTest(@"
- c.Foo = 'Baz';
- assert(c.Foo === 'Baz');
- ");
- }
- [Fact]
- public void ShouldUseExplicitMethod()
- {
- _engine.SetValue("c", new Company("ACME"));
- RunTest(@"
- assert(0 === c.CompareTo(c));
- ");
- }
- [Fact]
- public void ShouldCallInstanceMethodWithParams()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call13('1','2','3') === '1,2,3');
- assert(a.Call13('1') === '1');
- assert(a.Call13(1) === '1');
- assert(a.Call13() === '');
- assert(a.Call14('a','1','2','3') === 'a:1,2,3');
- assert(a.Call14('a','1') === 'a:1');
- assert(a.Call14('a') === 'a:');
- function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
- assert(call13wrapper('1','2','3') === '1,2,3');
- assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
- ");
- }
- [Fact]
- public void ShouldCallInstanceMethodWithJsValueParams()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- assert(a.Call16('1','2','3') === '1,2,3');
- assert(a.Call16('1') === '1');
- assert(a.Call16(1) === '1');
- assert(a.Call16() === '');
- assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
- ");
- }
- [Fact]
- public void NullValueAsArgumentShouldWork()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- var x = a.Call2(null);
- assert(x === null);
- ");
- }
- [Fact]
- public void ShouldSetPropertyToNull()
- {
- var p = new Person { Name = "Mickey" };
- _engine.SetValue("p", p);
- RunTest(@"
- assert(p.Name != null);
- p.Name = null;
- assert(p.Name == null);
- ");
- Assert.True(p.Name == null);
- }
- [Fact]
- public void ShouldCallMethodWithNull()
- {
- _engine.SetValue("a", new A());
- RunTest(@"
- a.Call15(null);
- var result = a.Call2(null);
- assert(result == null);
- ");
- }
- [Fact]
- public void ShouldReturnUndefinedProperty()
- {
- _engine.SetValue("uo", new { foo = "bar" });
- _engine.SetValue("ud", new Dictionary<string, object> { { "foo", "bar" } });
- _engine.SetValue("ul", new List<string> { "foo", "bar" });
- RunTest(@"
- assert(!uo.undefinedProperty);
- assert(!ul[5]);
- assert(!ud.undefinedProperty);
- ");
- }
- private class FailingObject2
- {
- public int this[int index] => throw new ArgumentException("index is bad", nameof(index));
- }
- [Fact]
- public void ShouldPropagateIndexerExceptions()
- {
- var engine = new Engine();
- engine.Execute(@"function f2(obj) { return obj[1]; }");
- var failingObject = new FailingObject2();
- Assert.Throws<ArgumentException>(() => engine.Invoke("f2", failingObject));
- }
- [Fact]
- public void ShouldAutomaticallyConvertArraysToFindBestInteropResolution()
- {
- _engine.SetValue("a", new ArrayConverterTestClass());
- _engine.SetValue("item1", new ArrayConverterItem(1));
- _engine.SetValue("item2", new ArrayConverterItem(2));
- RunTest(@"
- assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
- assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
- assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
- assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
- assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
- ");
- }
- [Fact]
- public void ShouldImportNamespaceNestedType()
- {
- RunTest(@"
- var shapes = importNamespace('Shapes.Circle');
- var kinds = shapes.Kind;
- assert(kinds.Unit === 0);
- assert(kinds.Ellipse === 1);
- assert(kinds.Round === 5);
- ");
- }
- [Fact]
- public void ShouldImportNamespaceNestedNestedType()
- {
- RunTest(@"
- var meta = importNamespace('Shapes.Circle.Meta');
- var usages = meta.Usage;
- assert(usages.Public === 0);
- assert(usages.Private === 1);
- assert(usages.Internal === 11);
- ");
- }
- [Fact]
- public void ShouldGetNestedTypeFromParentType()
- {
- RunTest(@"
- var Shapes = importNamespace('Shapes');
- var usages = Shapes.Circle.Meta.Usage;
- assert(usages.Public === 0);
- assert(usages.Private === 1);
- assert(usages.Internal === 11);
- ");
- }
- [Fact]
- public void ShouldGetNestedNestedProp()
- {
- RunTest(@"
- var meta = importNamespace('Shapes.Circle');
- var m = new meta.Meta();
- assert(m.Description === 'descp');
- ");
- }
- [Fact]
- public void ShouldSetNestedNestedProp()
- {
- RunTest(@"
- var meta = importNamespace('Shapes.Circle');
- var m = new meta.Meta();
- m.Description = 'hello';
- assert(m.Description === 'hello');
- ");
- }
- [Fact]
- public void CanGetStaticNestedField()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
- var statics = domain.ClassWithStaticFields;
- assert(statics.Get == 'Get');
- ");
- }
- [Fact]
- public void CanSetStaticNestedField()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
- var statics = domain.ClassWithStaticFields;
- statics.Set = 'hello';
- assert(statics.Set == 'hello');
- ");
- Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
- }
- [Fact]
- public void CanGetStaticNestedAccessor()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
- var statics = domain.ClassWithStaticFields;
- assert(statics.Getter == 'Getter');
- ");
- }
- [Fact]
- public void CanSetStaticNestedAccessor()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
- var statics = domain.ClassWithStaticFields;
- statics.Setter = 'hello';
- assert(statics.Setter == 'hello');
- ");
- Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
- }
- [Fact]
- public void CantSetStaticNestedReadonly()
- {
- RunTest(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
- var statics = domain.ClassWithStaticFields;
- statics.Readonly = 'hello';
- assert(statics.Readonly == 'Readonly');
- ");
- Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
- }
- [Fact]
- public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
- {
- _engine.SetValue("a", new A());
- // Func<int, int>
- RunTest(@"
- assert(a.Call17(function(value){ return value; }) === 17);
- ");
- }
- [Fact]
- public void ShouldExecuteActionWithValueTypeParameterCorrectly()
- {
- _engine.SetValue("a", new A());
- // Action<int>
- RunTest(@"
- a.Call18(function(value){ assert(value === 18); });
- ");
- }
- [Fact]
- public void ShouldConvertToJsValue()
- {
- RunTest(@"
- var now = System.DateTime.Now;
- assert(new String(now) == now.toString());
- var zero = System.Int32.MaxValue;
- assert(new String(zero) == zero.toString());
- ");
- }
- [Fact]
- public void ShouldNotCatchClrExceptions()
- {
- var engine = new Engine()
- .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
- .SetValue("Thrower", typeof(Thrower))
- .Execute(@"
- function throwException1(){
- try {
- throwMyException();
- return;
- }
- catch(e) {
- return;
- }
- }
- function throwException2(){
- try {
- new Thrower().ThrowNotSupportedException();
- return;
- }
- catch(e) {
- return;
- }
- }
- ");
- Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
- Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
- }
- [Fact]
- public void ShouldCatchAllClrExceptions()
- {
- var exceptionMessage = "myExceptionMessage";
- var engine = new Engine(o => o.CatchClrExceptions())
- .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
- .SetValue("Thrower", typeof(Thrower))
- .Execute(@"
- function throwException1(){
- try {
- throwMyException();
- return '';
- }
- catch(e) {
- return e.message;
- }
- }
- function throwException2(){
- try {
- new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
- return;
- }
- catch(e) {
- return e.message;
- }
- }
- ");
- Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
- Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
- }
- [Fact]
- public void ShouldNotCatchClrFromApply()
- {
- var engine = new Engine(options =>
- {
- options.CatchClrExceptions(e =>
- {
- Assert.Fail("was called");
- return true;
- });
- });
- engine.Execute(@"
- function throwError() {
- throw new Error();
- }
- // doesn't cause ExceptionDelegateHandler call
- try { throwError(); } catch {}
- // does cause ExceptionDelegateHandler call
- try { throwError.apply(); } catch {}
- ");
- }
- private class MemberExceptionTest
- {
- public MemberExceptionTest(bool throwOnCreate)
- {
- if (throwOnCreate)
- {
- throw new InvalidOperationException("thrown as requested");
- }
- }
- public JsValue ThrowingProperty1
- {
- get => throw new InvalidOperationException();
- set => throw new InvalidOperationException();
- }
- public object ThrowingProperty2
- {
- get => throw new InvalidOperationException();
- set => throw new InvalidOperationException();
- }
- public void ThrowingFunction()
- {
- throw new InvalidOperationException();
- }
- }
- [Fact]
- public void ShouldCatchClrMemberExceptions()
- {
- var engine = new Engine(cfg =>
- {
- cfg.AllowClr();
- cfg.CatchClrExceptions();
- });
- engine.SetValue("assert", new Action<bool>(Assert.True));
- engine.SetValue("log", new Action<object>(Console.WriteLine));
- engine.SetValue("create", typeof(MemberExceptionTest));
- engine.SetValue("instance", new MemberExceptionTest(false));
- // Test calling a constructor that throws an exception
- engine.Execute(@"
- try
- {
- create(true);
- assert(false);
- }
- catch (e)
- {
- assert(true);
- }
- ");
- // Test calling a member function that throws an exception
- engine.Execute(@"
- try
- {
- instance.ThrowingFunction();
- assert(false);
- }
- catch (e)
- {
- assert(true);
- }
- ");
- // Test using a property getter that throws an exception
- engine.Execute(@"
- try
- {
- log(o.ThrowingProperty);
- assert(false);
- }
- catch (e)
- {
- assert(true);
- }
- ");
- // Test using a property setter that throws an exception
- engine.Execute(@"
- try
- {
- instance.ThrowingProperty1 = 123;
- assert(false);
- }
- catch (e)
- {
- assert(true);
- }
- try
- {
- instance.ThrowingProperty2 = 456;
- assert(false);
- }
- catch (e)
- {
- assert(true);
- }
- ");
- }
- [Fact]
- public void ShouldCatchSomeExceptions()
- {
- var exceptionMessage = "myExceptionMessage";
- var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
- .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
- .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
- .SetValue("Thrower", typeof(Thrower))
- .Execute(@"
- function throwException1(){
- try {
- throwMyException1();
- return '';
- }
- catch(e) {
- return e.message;
- }
- }
- function throwException2(){
- try {
- throwMyException2();
- return '';
- }
- catch(e) {
- return e.message;
- }
- }
- function throwException3(){
- try {
- new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
- return '';
- }
- catch(e) {
- return e.message;
- }
- }
- function throwException4(){
- try {
- new Thrower().ThrowArgumentNullException();
- return '';
- }
- catch(e) {
- return e.message;
- }
- }
- ");
- Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
- Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
- Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
- Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
- }
- [Fact]
- public void ArrayFromShouldConvertListToArrayLike()
- {
- var list = new List<Person>
- {
- new Person { Name = "Mike" },
- new Person { Name = "Mika" }
- };
- _engine.SetValue("a", list);
- RunTest(@"
- var arr = new Array(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- RunTest(@"
- var arr = Array.from(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- }
- [Fact]
- public void ArrayFromShouldConvertArrayToArrayLike()
- {
- var list = new[]
- {
- new Person { Name = "Mike" },
- new Person { Name = "Mika" }
- };
- _engine.SetValue("a", list);
- RunTest(@"
- var arr = new Array(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- RunTest(@"
- var arr = Array.from(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- }
- [Fact]
- public void ArrayFromShouldConvertIEnumerable()
- {
- var enumerable = new[]
- {
- new Person { Name = "Mike" },
- new Person { Name = "Mika" }
- }.Select(x => x);
- _engine.SetValue("a", enumerable);
- RunTest(@"
- var arr = new Array(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- RunTest(@"
- var arr = Array.from(a);
- assert(arr.length === 2);
- assert(arr[0].Name === 'Mike');
- assert(arr[1].Name === 'Mika');
- ");
- }
- [Fact]
- public void ShouldBeAbleToPlusAssignStringProperty()
- {
- var p = new Person();
- var engine = new Engine();
- engine.SetValue("P", p);
- engine.Evaluate("P.Name = 'b';");
- engine.Evaluate("P.Name += 'c';");
- Assert.Equal("bc", p.Name);
- }
- [Fact]
- public void ShouldNotResolveToPrimitiveSymbol()
- {
- var engine = new Engine(options =>
- options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
- var c = engine.Evaluate(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- return new domain.FloatIndexer();
- ");
- Assert.NotNull(c.ToString());
- Assert.Equal((uint) 0, c.AsObject().GetLength());
- }
- private class DictionaryWrapper
- {
- public IDictionary<string, object> Values { get; set; }
- }
- private class DictionaryTest
- {
- public void Test1(IDictionary<string, object> values)
- {
- Assert.Equal(1, Convert.ToInt32(values["a"]));
- }
- public void Test2(DictionaryWrapper dictionaryObject)
- {
- Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
- }
- }
- [Fact]
- public void ShouldBeAbleToPassDictionaryToMethod()
- {
- var engine = new Engine();
- engine.SetValue("dictionaryTest", new DictionaryTest());
- engine.Evaluate("dictionaryTest.test1({ a: 1 });");
- }
- [Fact]
- public void ShouldBeAbleToPassDictionaryInObjectToMethod()
- {
- var engine = new Engine();
- engine.SetValue("dictionaryTest", new DictionaryTest());
- engine.Evaluate("dictionaryTest.test2({ values: { a: 1 } });");
- }
- [Fact]
- public void ShouldSupportSpreadForDictionary()
- {
- var engine = new Engine();
- var state = new Dictionary<string, object>
- {
- { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
- };
- engine.SetValue("state", state);
- var result = (IDictionary<string, object>) engine
- .Evaluate("({ supplier: 'S1', ...state.invoice })")
- .ToObject();
- Assert.Equal("S1", result["supplier"]);
- Assert.Equal("42", result["number"]);
- }
- [Fact]
- public void ShouldSupportSpreadForDictionary2()
- {
- var engine = new Engine();
- var state = new Dictionary<string, object>
- {
- { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
- };
- engine.SetValue("state", state);
- var result = (IDictionary<string, object>) engine
- .Execute("function getValue() { return {supplier: 'S1', ...state.invoice}; }")
- .Invoke("getValue")
- .ToObject();
- Assert.Equal("S1", result["supplier"]);
- Assert.Equal("42", result["number"]);
- }
- [Fact]
- public void ShouldSupportSpreadForObject()
- {
- var engine = new Engine();
- var person = new Person
- {
- Name = "Mike",
- Age = 20
- };
- engine.SetValue("p", person);
- var result = (IDictionary<string, object>) engine
- .Evaluate("({ supplier: 'S1', ...p })")
- .ToObject();
- Assert.Equal("S1", result["supplier"]);
- Assert.Equal("Mike", result["Name"]);
- Assert.Equal(20d, result["Age"]);
- }
- [Fact]
- public void ShouldBeAbleToJsonStringifyClrObjects()
- {
- var engine = new Engine();
- engine.Evaluate("var jsObj = { 'key1' :'value1', 'key2' : 'value2' }");
- engine.SetValue("netObj", new Dictionary<string, object>
- {
- { "key1", "value1" },
- { "key2", "value2" }
- });
- var jsValue = engine.Evaluate("jsObj['key1']").AsString();
- var clrValue = engine.Evaluate("netObj['key1']").AsString();
- Assert.Equal(jsValue, clrValue);
- jsValue = engine.Evaluate("JSON.stringify(jsObj)").AsString();
- clrValue = engine.Evaluate("JSON.stringify(netObj)").AsString();
- Assert.Equal(jsValue, clrValue);
- // Write properties on screen using showProps function defined on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
- engine.Execute(@"function showProps(obj, objName) {
- var result = """";
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- result += objName + ""."" + i + "" = "" + obj[i] + ""\n"";
- }
- }
- return result;
- }");
- jsValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
- clrValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
- Assert.Equal(jsValue, clrValue);
- }
- [Fact]
- public void SettingValueViaIntegerIndexer()
- {
- var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
- engine.SetValue("log", new Action<object>(Console.WriteLine));
- engine.Execute(@"
- var domain = importNamespace('Jint.Tests.Runtime.Domain');
- var fia = new domain.IntegerIndexer();
- log(fia[0]);
- ");
- Assert.Equal(123, engine.Evaluate("fia[0]").AsNumber());
- engine.Evaluate("fia[0] = 678;");
- Assert.Equal(678, engine.Evaluate("fia[0]").AsNumber());
- }
- [Fact]
- public void IndexingBsonProperties()
- {
- const string jsonAnimals = @" { ""Animals"": [ { ""Id"": 1, ""Type"": ""Cat"" } ] }";
- var bsonAnimals = BsonDocument.Parse(jsonAnimals);
- _engine.SetValue("animals", bsonAnimals["Animals"]);
- // weak equality does conversions from native types
- Assert.True(_engine.Evaluate("animals[0].Type == 'Cat'").AsBoolean());
- Assert.True(_engine.Evaluate("animals[0].Id == 1").AsBoolean());
- }
- [Fact]
- public void IntegerAndFloatInFunctionOverloads()
- {
- var engine = new Engine(options => options.AllowClr(GetType().Assembly));
- engine.SetValue("a", new OverLoading());
- Assert.Equal("int-val", engine.Evaluate("a.testFunc(123);").AsString());
- Assert.Equal("float-val", engine.Evaluate("a.testFunc(12.3);").AsString());
- }
- [Fact]
- public void TypeConversionWithTemporaryInvalidValuesShouldNotCache()
- {
- var engine = new Engine(options => options.AllowClr());
- engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
- var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("new IntValueInput().testFunc(NaN);").AsString());
- Assert.Equal("No public methods with the specified arguments were found.", ex.Message);
- Assert.Equal(123, engine.Evaluate("new IntValueInput().testFunc(123);").AsNumber());
- }
- [Fact]
- public void CanConvertFloatingPointToIntegerWithoutError()
- {
- var engine = new Engine(options => options.AllowClr());
- engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
- Assert.Equal(12, engine.Evaluate("new IntValueInput().testFunc(12.3);").AsNumber());
- }
- public class IntValueInput
- {
- public int TestFunc(int value) => value;
- }
- public class TestItem
- {
- public double Cost { get; set; }
- public double Age { get; set; }
- public string Name { get; set; }
- }
- public class TestItemList : List<TestItem>
- {
- public double Sum(Func<TestItem, double> calc)
- {
- double rc = 0;
- foreach (var item in this)
- {
- rc += calc(item);
- }
- return rc;
- }
- public TestItemList Where(Func<TestItem, bool> cond)
- {
- var rc = new TestItemList();
- foreach (var item in this)
- {
- if (cond(item))
- {
- rc.Add(item);
- }
- }
- return rc;
- }
- }
- [Fact]
- public void DelegateCanReturnValue()
- {
- var engine = new Engine(options => options.AllowClr(GetType().Assembly));
- var lst = new TestItemList();
- lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
- lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
- lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
- lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
- lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
- engine.SetValue("lst", lst);
- Assert.Equal(5, engine.Evaluate("lst.Sum(x => x.Cost);").AsNumber());
- Assert.Equal(50, engine.Evaluate("lst.Sum(x => x.Age);").AsNumber());
- Assert.Equal(3, engine.Evaluate("lst.Where(x => x.Name == 'b').Count;").AsNumber());
- Assert.Equal(30, engine.Evaluate("lst.Where(x => x.Name == 'b').Sum(x => x.Age);").AsNumber());
- }
- [Fact]
- public void ObjectWrapperOverridingEquality()
- {
- // equality same via name
- _engine.SetValue("a", new Person { Name = "Name" });
- _engine.SetValue("b", new Person { Name = "Name" });
- _engine.Evaluate("const arr = [ null, a, undefined ];");
- Assert.Equal(1, _engine.Evaluate("arr.filter(x => x == b).length").AsNumber());
- Assert.Equal(1, _engine.Evaluate("arr.filter(x => x === b).length").AsNumber());
- Assert.True(_engine.Evaluate("arr.find(x => x == b) === a").AsBoolean());
- Assert.True(_engine.Evaluate("arr.find(x => x === b) == a").AsBoolean());
- Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x == b)").AsNumber());
- Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x === b)").AsNumber());
- Assert.Equal(1, _engine.Evaluate("arr.indexOf(b)").AsNumber());
- Assert.True(_engine.Evaluate("arr.includes(b)").AsBoolean());
- }
- [Fact]
- public void ObjectWrapperWrappingDictionaryShouldNotBeArrayLike()
- {
- var wrapper = ObjectWrapper.Create(_engine, new Dictionary<string, object>());
- Assert.False(wrapper.IsArrayLike);
- }
- [Fact]
- public void ShouldHandleCyclicReferences()
- {
- var engine = new Engine();
- static void Test(string message, object value)
- {
- Console.WriteLine(message);
- }
- engine.Realm.GlobalObject.FastSetDataProperty("global", engine.Realm.GlobalObject);
- engine.Realm.GlobalObject.FastSetDataProperty("test", new DelegateWrapper(engine, (Action<string, object>) Test));
- {
- var ex = Assert.Throws<JavaScriptException>(() => engine.Realm.GlobalObject.ToObject());
- Assert.Equal("Cyclic reference detected.", ex.Message);
- }
- {
- var ex = Assert.Throws<JavaScriptException>(() =>
- engine.Execute(@"
- var demo={};
- demo.value=1;
- test('Test 1', demo.value===1);
- test('Test 2', demo.value);
- demo.demo=demo;
- test('Test 3', demo);
- test('Test 4', global);"
- )
- );
- Assert.Equal("Cyclic reference detected.", ex.Message);
- }
- }
- [Fact]
- public void CanConfigurePropertyNameMatcher()
- {
- // defaults
- var e = new Engine();
- e.SetValue("a", new A());
- Assert.True(e.Evaluate("a.call1").IsObject());
- Assert.True(e.Evaluate("a.Call1").IsObject());
- Assert.True(e.Evaluate("a.CALL1").IsUndefined());
- e = new Engine(options =>
- {
- options.SetTypeResolver(new TypeResolver
- {
- MemberNameComparer = StringComparer.Ordinal
- });
- });
- e.SetValue("a", new A());
- Assert.True(e.Evaluate("a.call1").IsUndefined());
- Assert.True(e.Evaluate("a.Call1").IsObject());
- Assert.True(e.Evaluate("a.CALL1").IsUndefined());
- e = new Engine(options =>
- {
- options.SetTypeResolver(new TypeResolver
- {
- MemberNameComparer = StringComparer.OrdinalIgnoreCase
- });
- });
- e.SetValue("a", new A());
- Assert.True(e.Evaluate("a.call1").IsObject());
- Assert.True(e.Evaluate("a.Call1").IsObject());
- Assert.True(e.Evaluate("a.CALL1").IsObject());
- }
- [Fact]
- public void ShouldNotEnumerateClassMethods()
- {
- var engine = new Engine();
- var dictionary = new Dictionary<string, object>
- {
- { "foo", 5 },
- { "bar", "A string" }
- };
- engine.SetValue("dictionary", dictionary);
- var result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
- Assert.Equal("foo,bar", result);
- engine.Execute("dictionary.ContainsKey('foo')");
- result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
- Assert.Equal("foo,bar", result);
- }
- [Fact]
- public void ShouldNotEnumerateExtensionMethods()
- {
- var engine = new Engine(cfg => cfg.AddExtensionMethods(typeof(Enumerable)));
- var result = engine.Evaluate("Object.keys({ ...[1,2,3] }).join(',')").AsString();
- Assert.Equal("0,1,2", result);
- var script = @"
- var arr = [1,2,3];
- var keys = [];
- for(var index in arr) keys.push(index);
- keys.join(',');
- ";
- result = engine.Evaluate(script).ToString();
- Assert.Equal("0,1,2", result);
- }
- [Fact]
- public void CanCheckIfCallable()
- {
- var engine = new Engine();
- engine.Evaluate("var f = () => true;");
- var result = engine.GetValue("f");
- Assert.True(result.IsCallable);
- Assert.True(result.Call(Array.Empty<JsValue>()).AsBoolean());
- Assert.True(result.Call().AsBoolean());
- }
- [Fact]
- public void CanGiveCustomNameToInteropMembers()
- {
- static IEnumerable<string> MemberNameCreator(MemberInfo prop)
- {
- var attributes = prop.GetCustomAttributes(typeof(CustomNameAttribute), true);
- if (attributes.Length > 0)
- {
- foreach (CustomNameAttribute attribute in attributes)
- {
- yield return attribute.Name;
- }
- }
- else
- {
- yield return prop.Name;
- }
- }
- var customTypeResolver = new TypeResolver
- {
- MemberNameCreator = MemberNameCreator
- };
- var engine = new Engine(options =>
- {
- options.SetTypeResolver(customTypeResolver);
- options.AddExtensionMethods(typeof(CustomNamedExtensions));
- });
- engine.SetValue("o", new CustomNamed());
- Assert.Equal("StringField", engine.Evaluate("o.jsStringField").AsString());
- Assert.Equal("StringField", engine.Evaluate("o.jsStringField2").AsString());
- Assert.Equal("StaticStringField", engine.Evaluate("o.jsStaticStringField").AsString());
- Assert.Equal("StringProperty", engine.Evaluate("o.jsStringProperty").AsString());
- Assert.Equal("Method", engine.Evaluate("o.jsMethod()").AsString());
- Assert.Equal("StaticMethod", engine.Evaluate("o.jsStaticMethod()").AsString());
- Assert.Equal("InterfaceStringProperty", engine.Evaluate("o.jsInterfaceStringProperty").AsString());
- Assert.Equal("InterfaceMethod", engine.Evaluate("o.jsInterfaceMethod()").AsString());
- Assert.Equal("ExtensionMethod", engine.Evaluate("o.jsExtensionMethod()").AsString());
- engine.SetValue("XmlHttpRequest", typeof(CustomNamedEnum));
- engine.Evaluate("o.jsEnumProperty = XmlHttpRequest.HEADERS_RECEIVED;");
- Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
- }
- [Fact]
- public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
- {
- var engine = new Engine(cfg => cfg.CatchClrExceptions());
- engine.SetValue("a", new Person());
- var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = 'It will not work, but it is normal'"));
- Assert.Contains("input string ", ex.Message, StringComparison.OrdinalIgnoreCase);
- Assert.Contains(" was not in a correct format", ex.Message, StringComparison.OrdinalIgnoreCase);
- }
- [Fact]
- public void ShouldLetNotSupportedExceptionBubble()
- {
- _engine.SetValue("profile", new Profile());
- var ex = Assert.Throws<NotSupportedException>(() => _engine.Evaluate("profile.AnyProperty"));
- Assert.Equal("NOT SUPPORTED", ex.Message);
- }
- [Fact]
- public void ShouldBeAbleToUseConvertibleStructAsMethodParameter()
- {
- _engine.SetValue("test", new DiscordTestClass());
- _engine.SetValue("id", new DiscordId("12345"));
- Assert.Equal("12345", _engine.Evaluate("String(id)").AsString());
- Assert.Equal("12345", _engine.Evaluate("test.echo('12345')").AsString());
- Assert.Equal("12345", _engine.Evaluate("test.create(12345)").AsString());
- }
- [Fact]
- public void ShouldGetIteratorForListAndDictionary()
- {
- const string Script = @"
- var it = collection[Symbol.iterator]();
- var result = it.next();
- var str = """";
- while (!result.done) {
- str += result.value;
- result = it.next();
- }
- return str;";
- _engine.SetValue("collection", new List<string> { "a", "b", "c" });
- Assert.Equal("abc", _engine.Evaluate(Script));
- _engine.SetValue("collection", new Dictionary<string, object> { { "a", 1 }, { "b", 2 }, { "c", 3 } });
- Assert.Equal("a,1b,2c,3", _engine.Evaluate(Script));
- }
- [Fact]
- public void ShouldNotIntroduceNewPropertiesWhenTraversing()
- {
- _engine.SetValue("x", new Dictionary<string, int> { { "First", 1 }, { "Second", 2 } });
- Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- Assert.Equal("x['First']: 1", _engine.Evaluate("\"x['First']: \" + x['First']"));
- Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- Assert.Equal("x['Third']: undefined", _engine.Evaluate("\"x['Third']: \" + x['Third']"));
- Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- Assert.Equal(JsValue.Undefined, _engine.Evaluate("x.length"));
- Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- Assert.Equal(2, _engine.Evaluate("x.Count").AsNumber());
- Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- _engine.Evaluate("x.Clear();");
- Assert.Equal("[]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- _engine.Evaluate("x['Fourth'] = 4;");
- Assert.Equal("[\"Fourth\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
- Assert.False(_engine.Evaluate("Object.prototype.hasOwnProperty.call(x, 'Third')").AsBoolean());
- }
- [Fact]
- public void CanConfigureCustomObjectTypeForJsToClrConversion()
- {
- var engine = new Engine(options =>
- {
- options.Interop.CreateClrObject = oi => new Dictionary<string, object>();
- });
- object capture = null;
- var callback = (object value) => capture = value;
- engine.SetValue("callback", callback);
- engine.Evaluate("callback(({'a': 'b'}));");
- Assert.IsType<Dictionary<string, object>>(capture);
- var dictionary = (Dictionary<string, object>) capture;
- Assert.Equal("b", dictionary["a"]);
- }
- [Fact]
- public void ArrayPrototypeIndexOfWithInteropList()
- {
- var engine = new Jint.Engine();
- engine.SetValue("list", new List<string> { "A", "B", "C" });
- Assert.Equal(1, engine.Evaluate("list.indexOf('B')"));
- Assert.Equal(1, engine.Evaluate("list.lastIndexOf('B')"));
- Assert.Equal(1, engine.Evaluate("Array.prototype.indexOf.call(list, 'B')"));
- Assert.Equal(1, engine.Evaluate("Array.prototype.lastIndexOf.call(list, 'B')"));
- }
- [Fact]
- public void ArrayPrototypeFindWithInteropList()
- {
- var engine = new Jint.Engine();
- var list = new List<string> { "A", "B", "C" };
-
- engine.SetValue("list", list);
- Assert.Equal(1, engine.Evaluate("list.findIndex((x) => x === 'B')"));
- Assert.Equal('B', engine.Evaluate("list.find((x) => x === 'B')"));
- }
- [Fact]
- public void ArrayPrototypePushWithInteropList()
- {
- var engine = new Jint.Engine();
- var list = new List<string> { "A", "B", "C" };
- engine.SetValue("list", list);
- engine.Evaluate("list.push('D')");
- Assert.Equal(4, list.Count);
- Assert.Equal("D", list[3]);
- Assert.Equal(3, engine.Evaluate("list.lastIndexOf('D')"));
- }
- [Fact]
- public void ArrayPrototypePopWithInteropList()
- {
- var engine = new Jint.Engine();
- var list = new List<string> { "A", "B", "C" };
- engine.SetValue("list", list);
- Assert.Equal(2, engine.Evaluate("list.lastIndexOf('C')"));
- Assert.Equal(3, list.Count);
- Assert.Equal("C", engine.Evaluate("list.pop()"));
- Assert.Equal(2, list.Count);
- Assert.Equal(-1, engine.Evaluate("list.lastIndexOf('C')"));
- }
- [Fact]
- public void ShouldBeJavaScriptException()
- {
- var engine = new Engine(cfg => cfg.AllowClr().AllowOperatorOverloading().CatchClrExceptions());
- engine.SetValue("Dimensional", typeof(Dimensional));
- engine.Execute(@"
- function Eval(param0, param1)
- {
- var result = param0 + param1;
- return result;
- }");
- // checking working custom type
- Assert.Equal(new Dimensional("kg", 90), (new Dimensional("kg", 30) + new Dimensional("kg", 60)));
- Assert.Equal(new Dimensional("kg", 90), engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("kg", 60) }).ToObject());
- Assert.Throws<InvalidOperationException>(() => new Dimensional("kg", 30) + new Dimensional("piece", 70));
- // checking throwing exception in override operator
- string errorMsg = string.Empty;
- errorMsg = Assert.Throws<JavaScriptException>(() => engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("piece", 70) })).Message;
- Assert.Equal("Dimensionals with different measure types are non-summable", errorMsg);
- }
- private class Profile
- {
- public int AnyProperty => throw new NotSupportedException("NOT SUPPORTED");
- }
- [Fact]
- public void GenericParameterResolutionShouldWorkWithNulls()
- {
- var result = new Engine()
- .SetValue("JintCommon", new JintCommon())
- .Evaluate("JintCommon.sum(1, null)")
- .AsNumber();
- Assert.Equal(2, result);
- }
- public class JintCommon
- {
- public int Sum(int a, int? b) => a + b.GetValueOrDefault(1);
- }
- private delegate void ParamsTestDelegate(params Action[] callbacks);
- [Fact]
- public void CanUseParamsActions()
- {
- var engine = new Engine();
- engine.SetValue("print", new Action<string>(_ => { }));
- engine.SetValue("callAll", new DelegateWrapper(engine, new ParamsTestDelegate(ParamsTest)));
- engine.Execute(@"
- callAll(
- function() { print('a'); },
- function() { print('b'); },
- function() { print('c'); }
- );
- ");
- }
- private static void ParamsTest(params Action[] callbacks)
- {
- foreach (var callback in callbacks)
- {
- callback.Invoke();
- }
- }
- [Fact]
- public void ObjectWrapperIdentityIsMaintained()
- {
- // run in separate method so stack won't keep reference
- var reference = RunWeakReferenceTest();
- GC.Collect();
- // make sure no dangling reference is left
- Assert.False(reference.IsAlive);
- }
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static WeakReference RunWeakReferenceTest()
- {
- var o = new object();
- var engine = new Engine()
- .SetValue("o", o);
- var wrapper1 = (ObjectWrapper) engine.GetValue("o");
- var reference = new WeakReference(wrapper1);
- Assert.Same(wrapper1, engine.GetValue("o"));
- Assert.Same(o, wrapper1.Target);
- // reset
- engine.Realm.GlobalObject.RemoveOwnProperty("o");
- return reference;
- }
- [Fact]
- public void CanUseClrFunction()
- {
- var engine = new Engine();
- engine.SetValue("fn", new ClrFunction(engine, "fn", (_, args) => (JsValue) (args[0].AsInteger() + 1)));
- var result = engine.Evaluate("fn(1)");
- Assert.Equal(2, result);
- }
- [Fact]
- public void ShouldAllowClrExceptionsThrough()
- {
- var engine = new Engine(opts => opts.CatchClrExceptions(exc => false));
- engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
- const string Source = @"
- function wrap() {
- fn();
- }
- wrap();
- ";
- Assert.Throws<InvalidOperationException>(() => engine.Execute(Source));
- }
- [Fact]
- public void ShouldConvertClrExceptionsToErrors()
- {
- var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
- engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
- const string Source = @"
- function wrap() {
- fn();
- }
- wrap();
- ";
- var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
- Assert.Equal(exc.Message, "This is a C# error");
- }
- [Fact]
- public void ShouldAllowCatchingConvertedClrExceptions()
- {
- var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
- engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
- const string Source = @"
- try {
- fn();
- } catch (e) {
- throw new Error('Caught: ' + e.message);
- }
- ";
- var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
- Assert.Equal(exc.Message, "Caught: This is a C# error");
- }
- class Baz
- {
- public int DisposeCalls { get; private set; }
- public IEnumerable<int> Enumerator
- {
- get
- {
- try
- {
- for (int i = 0; i < 10; i++) yield return i;
- }
- finally // finally clause is translated into IDisposable.Dispose in underlying IEnumerator
- {
- ++DisposeCalls;
- }
- }
- }
- }
- [Fact]
- public void ShouldCallEnumeratorDisposeOnNormalTermination()
- {
- var engine = new Engine();
- var baz = new Baz();
- engine.SetValue("baz", baz);
- const string Source = @"
- for (let i of baz.Enumerator) {
- }";
- engine.Execute(Source);
- Assert.Equal(1, baz.DisposeCalls);
- }
- [Fact]
- public void ShouldCallEnumeratorDisposeOnBreak()
- {
- var engine = new Engine();
- var baz = new Baz();
- engine.SetValue("baz", baz);
- const string Source = @"
- for (let i of baz.Enumerator) {
- if (i == 2) break;
- }";
- engine.Execute(Source);
- Assert.Equal(1, baz.DisposeCalls);
- }
- [Fact]
- public void ShouldCallEnumeratorDisposeOnException()
- {
- var engine = new Engine();
- var baz = new Baz();
- engine.SetValue("baz", baz);
- const string Source = @"
- try {
- for (let i of baz.Enumerator) {
- if (i == 2) throw 'exception';
- }
- } catch (e) {
- }";
- engine.Execute(Source);
- Assert.Equal(1, baz.DisposeCalls);
- }
- public class PropertyTestClass
- {
- public object Value;
- }
- [Fact]
- public void PropertiesOfJsObjectPassedToClrShouldBeReadable()
- {
- _engine.SetValue("MyClass", typeof(PropertyTestClass));
- RunTest(@"
- var obj = new MyClass();
- obj.Value = { foo: 'bar' };
- equal('bar', obj.Value.foo);
- ");
- }
- [Fact]
- public void ShouldBeAbleToDeleteDictionaryEntries()
- {
- var engine = new Engine(options => options.Strict());
- var dictionary = new Dictionary<string, int>
- {
- { "a", 1 },
- { "b", 2 }
- };
- engine.SetValue("data", dictionary);
- Assert.True(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
- Assert.True(engine.Evaluate("data['a'] === 1").AsBoolean());
- engine.Evaluate("data['a'] = 42");
- Assert.True(engine.Evaluate("data['a'] === 42").AsBoolean());
- Assert.Equal(42, dictionary["a"]);
- engine.Execute("delete data['a'];");
- Assert.False(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
- Assert.False(engine.Evaluate("data['a'] === 42").AsBoolean());
- Assert.False(dictionary.ContainsKey("a"));
- var engineNoWrite = new Engine(options => options.Strict().AllowClrWrite(false));
- dictionary = new Dictionary<string, int>
- {
- { "a", 1 },
- { "b", 2 }
- };
- engineNoWrite.SetValue("data", dictionary);
- var ex1 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Evaluate("data['a'] = 42"));
- Assert.Equal("Cannot assign to read only property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex1.Message);
- // no changes
- Assert.True(engineNoWrite.Evaluate("data['a'] === 1").AsBoolean());
- var ex2 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Execute("delete data['a'];"));
- Assert.Equal("Cannot delete property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex2.Message);
- }
- public record RecordTestClass(object Value = null);
- public class RecordTestClassContext
- {
- public object Method(RecordTestClass recordTest)
- {
- return recordTest.Value;
- }
- }
- private class ClassWithIndexerAndProperty
- {
- public string MyProp { get; } = "from property";
- public string this[string name] => name != nameof(MyProp) ? "from indexer" : null;
- }
- [Fact]
- public void CanToStringObjectWithoutToPrimitiveSymbol()
- {
- var engine = new Engine();
- engine.SetValue("obj", new ClassWithIndexerAndProperty());
- Assert.Equal("Jint.Tests.Runtime.InteropTests+ClassWithIndexerAndProperty", engine.Evaluate("obj + ''").AsString());
- engine.SetValue("obj", new Company("name"));
- Assert.Equal("Jint.Tests.Runtime.Domain.Company", engine.Evaluate("obj + ''").AsString());
- }
- [Fact]
- public void CanConstructOptionalRecordClass()
- {
- _engine.SetValue("Context", new RecordTestClassContext());
- Assert.Equal(null, _engine.Evaluate("Context.method({});").ToObject());
- Assert.Equal(5, _engine.Evaluate("Context.method({ value: 5 });").AsInteger());
- }
- [Fact]
- public void CanPassDateTimeMinAndMaxViaInterop()
- {
- var engine = new Engine(cfg => cfg.AllowClrWrite());
- var dt = DateTime.UtcNow;
- engine.SetValue("capture", new Action<object>(o => dt = (DateTime) o));
- engine.SetValue("minDate", DateTime.MinValue);
- engine.Execute("capture(minDate);");
- Assert.Equal(DateTime.MinValue, dt);
- engine.SetValue("maxDate", DateTime.MaxValue);
- engine.Execute("capture(maxDate);");
- Assert.Equal(DateTime.MaxValue, dt);
- }
- private class Container
- {
- private readonly Child _child = new();
- public Child Child => _child;
- public BaseClass Get() => _child;
- }
- private class BaseClass
- {
- }
- private class Child : BaseClass
- {
- }
- [Fact]
- public void AccessingBaseTypeShouldBeEqualToAccessingDerivedType()
- {
- var engine = new Engine().SetValue("container", new Container());
- var res = engine.Evaluate("container.Child === container.Get()"); // These two should be the same object. But this PR makes `container.Get()` return a different object
- Assert.True(res.AsBoolean());
- }
- public interface IIndexer<out T>
- {
- T this[int index] { get; }
- }
- public interface ICountable<out T>
- {
- int Count { get; }
- }
- public interface IStringCollection : IIndexer<string>, ICountable<string>
- {
- string this[string name] { get; }
- }
- public class Strings : IStringCollection
- {
- private readonly string[] _strings;
- public Strings(string[] strings)
- {
- _strings = strings;
- }
- public string this[string name] => null;
- public string this[int index] => _strings[index];
- public int Count => _strings.Length;
- }
- public class Utils
- {
- public IStringCollection GetStrings() => new Strings(new[] { "a", "b", "c" });
- }
- [Fact]
- public void AccessingInterfaceShouldContainExtendedInterfaces()
- {
- var engine = new Engine();
- engine.SetValue("Utils", new Utils());
- var result = engine.Evaluate("const strings = Utils.GetStrings(); strings.Count;").AsNumber();
- Assert.Equal(3, result);
- }
- [Fact]
- public void IntegerIndexerIfPreferredOverStringIndexerWhenFound()
- {
- var engine = new Engine();
- engine.SetValue("Utils", new Utils());
- var result = engine.Evaluate("const strings = Utils.GetStrings(); strings[2];");
- Assert.Equal("c", result);
- }
- [Fact]
- public void CanDestructureInteropTargetMethod()
- {
- var engine = new Engine();
- engine.SetValue("test", new Utils());
- var result = engine.Evaluate("const { getStrings } = test; getStrings().Count;");
- Assert.Equal(3, result);
- }
- private class MetadataWrapper : IDictionary<string, object>
- {
- public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => throw new NotImplementedException();
- IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public void Add(KeyValuePair<string, object> item) => throw new NotImplementedException();
- public void Clear() => throw new NotImplementedException();
- public bool Contains(KeyValuePair<string, object> item) => throw new NotImplementedException();
- public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) => throw new NotImplementedException();
- public bool Remove(KeyValuePair<string, object> item) => throw new NotImplementedException();
- public int Count { get; set; }
- public bool IsReadOnly { get; set; }
- public bool ContainsKey(string key) => throw new NotImplementedException();
- public void Add(string key, object value) => throw new NotImplementedException();
- public bool Remove(string key) => throw new NotImplementedException();
- public bool TryGetValue(string key, out object value)
- {
- value = "from-wrapper";
- return true;
- }
- public object this[string key]
- {
- get => "from-wrapper";
- set
- {
- }
- }
- public ICollection<string> Keys { get; set; }
- public ICollection<object> Values { get; set; }
- }
- private class ShadowedGetter : IReadOnlyDictionary<string, object>
- {
- private Dictionary<string, object> _dictionary = new();
- public void SetInitial(object value, string key)
- {
- _dictionary[key] = value;
- }
- public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => throw new NotImplementedException();
- IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public int Count { get; }
- public bool ContainsKey(string key) => _dictionary.ContainsKey(key);
- public bool TryGetValue(string key, out object value) => _dictionary.TryGetValue(key, out value);
- public object this[string key]
- {
- get
- {
- _dictionary.TryGetValue(key, out var value);
- return value;
- }
- }
- public IEnumerable<string> Keys { get; set; }
- public IEnumerable<object> Values { get; set; }
- }
- private class ShadowingSetter : ShadowedGetter
- {
- public Dictionary<string, int> Metadata
- {
- set
- {
- SetInitial(new MetadataWrapper(), "metadata");
- }
- }
- }
- [Fact]
- public void CanSelectShadowedPropertiesBasedOnReadableAndWritable()
- {
- var engine = new Engine();
- engine.SetValue("test", new ShadowingSetter
- {
- Metadata = null
- });
- engine.Evaluate("test.metadata['abc'] = 123");
- var result = engine.Evaluate("test.metadata['abc']");
- Assert.Equal("from-wrapper", result);
- }
- [Fact]
- public void ShouldRespectConcreteGenericReturnTypes()
- {
- var engine = new Engine(opt =>
- {
- opt.AddExtensionMethods(typeof(Enumerable)); // Allow LINQ extension methods.
- });
- var result = new List<string>();
- void Debug(object o)
- {
- result.Add($"{o?.GetType().Name ?? "null"}: {o ?? "null"}");
- }
- engine.SetValue("debug", Debug);
- engine.SetValue("dict", new Dictionary<string, string> { ["test"] = "val" });
- engine.Execute("var t = dict.last(kvp => { debug(kvp); debug(kvp.key); return kvp.key != null; } );");
- engine.Execute("debug(t); debug(t.key);");
- Assert.Equal(4, result.Count);
- Assert.Equal("KeyValuePair`2: [test, val]", result[0]);
- Assert.Equal("String: test", result[1]);
- Assert.Equal("KeyValuePair`2: [test, val]", result[2]);
- Assert.Equal("String: test", result[3]);
- }
- private class ClrMembersVisibilityTestClass
- {
- public string Field = "field";
- public int Property { get; set; } = 10;
- public int Method()
- {
- return 4;
- }
- public string Extras { get; set; }
- }
- [Fact]
- public void PropertiesShouldNotSeeReportMethodsWhenMemberTypesActive()
- {
- var engine = new Engine(opt =>
- {
- opt.Interop.ObjectWrapperReportedMemberTypes = MemberTypes.Field | MemberTypes.Property;
- });
- engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass());
- var val = engine.GetValue("clrInstance");
- var obj = val.AsObject();
- var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
- props.Should().BeEquivalentTo("Property", "Extras", "Field");
- }
- [Fact]
- public void PropertyKeysShouldReportMethods()
- {
- var engine = new Engine();
- engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass());
- var val = engine.GetValue("clrInstance");
- var obj = val.AsObject();
- var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
- props.Should().BeEquivalentTo("Property", "Extras", "Field", "Method");
- }
- [Fact]
- public void PropertyKeysShouldObeyMemberFilter()
- {
- var engine = new Engine(options =>
- {
- options.SetTypeResolver(new TypeResolver
- {
- MemberFilter = member => member.Name == "Extras"
- });
- });
- engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass());
- var val = engine.GetValue("clrInstance");
- var obj = val.AsObject();
- var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
- props.Should().BeEquivalentTo("Extras");
- }
- private class ClrMembersVisibilityTestClass2
- {
- public int Get_A { get; set; } = 5;
- }
- [Fact]
- public void ShouldSeeClrMethods2()
- {
- var engine = new Engine();
- engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass2());
- var val = engine.GetValue("clrInstance");
- var obj = val.AsObject();
- var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
- props.Should().BeEquivalentTo("Get_A");
- }
- [Fact]
- public void ShouldNotThrowOnInspectingClrFunction()
- {
- var engine = new Engine();
- engine.SetValue("clrDelegate", () => 4);
- var val = engine.GetValue("clrDelegate");
- var fn = val as Function;
- var decl = fn!.FunctionDeclaration;
- decl.Should().BeNull();
- }
- private class ShouldNotThrowOnInspectingClrFunctionTestClass
- {
- public int MyInt()
- {
- return 4;
- }
- }
- [Fact]
- public void ShouldNotThrowOnInspectingClrClassFunction()
- {
- var engine = new Engine();
- engine.SetValue("clrCls", new ShouldNotThrowOnInspectingClrFunctionTestClass());
- var val = engine.GetValue("clrCls");
- var clrFn = val.Get("MyInt");
- var fn = clrFn as Function;
- var decl = fn!.FunctionDeclaration;
- decl.Should().BeNull();
- }
- [Fact]
- public void StringifyShouldIncludeInheritedFieldsAndProperties()
- {
- var engine = new Engine();
- engine.SetValue("c", new Circle(12.34));
- engine.Evaluate("JSON.stringify(c)").ToString().Should().Be("{\"Radius\":12.34,\"Color\":0,\"Id\":123}");
- }
- }
|