1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using Jint.Native;
- using Jint.Native.Object;
- using Jint.Native.Symbol;
- 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;
- using Xunit;
- 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(System.IO.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 DelegateWithDefaultValueParametersCanBeInvoked()
- {
- var instance = new A();
- _engine.SetValue("Instance", instance);
- _engine.SetValue("Class", TypeReference.CreateTypeReference(_engine, typeof(A)));
- RunTest(@"
- assert(Instance.Call19() === 0);
- assert(Instance.Call19(1) === 1);
- assert(Instance.Call20(1) === 4);
- assert(Instance.Call20(1, 2) === 5);
- assert(Instance.Call20(1 , 2, 3) === 6);
- assert(Class.Call19Static() === 0);
- assert(Class.Call19Static(1) === 1);
- assert(Class.Call20Static(1) === 4);
- assert(Class.Call20Static(1, 2) === 5);
- assert(Class.Call20Static(1 , 2, 3) === 6);
- ");
- }
- [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 ObjectInstance(_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);
- ");
- }
- [Fact]
- public void JavaScriptClassCanExtendClrType()
- {
- _engine.SetValue("TestClass", TypeReference.CreateTypeReference<TestClass>(_engine));
- _engine.Execute("class ExtendedType extends TestClass { constructor() { super(); this.a = 1; } get aProp() { return 'A'; } }");
- _engine.Execute("class MyExtendedType extends ExtendedType { constructor() { super(); this.b = 2; } get bProp() { return 'B'; } }");
- _engine.Evaluate("let obj = new MyExtendedType();");
- _engine.Evaluate("obj.setString('Hello World!');");
- Assert.Equal("Hello World!", _engine.Evaluate("obj.string"));
- Assert.Equal(1, _engine.Evaluate("obj.a"));
- Assert.Equal(2, _engine.Evaluate("obj.b"));
- Assert.Equal("A", _engine.Evaluate("obj.aProp"));
- Assert.Equal("B", _engine.Evaluate("obj.bProp"));
- // TODO we should have a special prototype based on wrapped type so we could differentiate between own and type properties
- // Assert.Equal("[\"a\"]", _engine.Evaluate("JSON.stringify(Object.getOwnPropertyNames(new ExtendedType()))"));
- // Assert.Equal("[\"a\",\"b\"]", _engine.Evaluate("JSON.stringify(Object.getOwnPropertyNames(new MyExtendedType()))"));
- }
- [Fact]
- public void ShouldAllowMethodsOnClrExtendedTypes()
- {
- _engine.SetValue("ClrBaseType", TypeReference.CreateTypeReference<TestClass>(_engine));
- _engine.Evaluate(@"
- class JsBaseType {}
- class ExtendsFromJs extends JsBaseType {
- constructor() {
- super();
- this.a = 1;
- }
- getA() {
- return this.a;
- }
- }
- class ExtendsFromClr extends ClrBaseType {
- constructor() {
- super();
- this.a = 1;
- }
- getA() {
- return this.a;
- }
- }
- ");
- var extendsFromJs = _engine.Construct("ExtendsFromJs");
- Assert.Equal(1, _engine.Evaluate("new ExtendsFromJs().getA();"));
- Assert.NotEqual(JsValue.Undefined, extendsFromJs.Get("getA"));
- var extendsFromClr = _engine.Construct("ExtendsFromClr");
- Assert.Equal(1, _engine.Evaluate("new ExtendsFromClr().getA();"));
- Assert.NotEqual(JsValue.Undefined, extendsFromClr.Get("getA"));
- }
- 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)
- .SetWrapObjectHandler((engine, target) =>
- {
- var instance = new ObjectWrapper(engine, target);
- if (instance.IsArrayLike)
- {
- instance.SetPrototypeOf(engine.Realm.Intrinsics.Array.PrototypeObject);
- }
- return instance;
- })
- );
- 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(opt =>
- {
- opt.SetWrapObjectHandler((eng, obj) =>
- {
- var wrapper = new ObjectWrapper(eng, obj);
- if (wrapper.IsArrayLike)
- {
- wrapper.SetPrototypeOf(eng.Realm.Intrinsics.Array.PrototypeObject);
- wrapper.Set(GlobalSymbolRegistry.IsConcatSpreadable, true);
- }
- return wrapper;
- });
- });
- 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();
- Assert.Equal(typeof(DateTime), value.GetType());
- Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
- }
- [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 ShouldBeInstanceOfTypeReferenceType()
- {
- _engine.SetValue("A", typeof(A));
- RunTest(@"
- var a = new A();
- assert(a instanceof A);
- ");
- }
- [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 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"));
- RunTest(@"
- assert(c.Name === 'ACME');
- ");
- }
- [Fact]
- public void ShouldUseExplicitIndexerPropertyGetter()
- {
- var company = new Company("ACME");
- ((ICompany) company)["Foo"] = "Bar";
- _engine.SetValue("c", company);
- RunTest(@"
- assert(c.Foo === 'Bar');
- ");
- }
- [Fact]
- public void ShouldUseExplicitPropertySetter()
- {
- _engine.SetValue("c", new Company("ACME"));
- RunTest(@"
- c.Name = 'Foo';
- assert(c.Name === 'Foo');
- ");
- }
- [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 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);
- }
- 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.As<ObjectInstance>().Length);
- }
- 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 IntegerEnumResolutionShouldWork()
- {
- var engine = new Engine(options => options.AllowClr(GetType().Assembly));
- engine.SetValue("a", new OverLoading());
- engine.SetValue("E", TypeReference.CreateTypeReference(engine, typeof(IntegerEnum)));
- Assert.Equal("integer-enum", engine.Evaluate("a.testFunc(E.a);").AsString());
- }
- [Fact]
- public void UnsignedIntegerEnumResolutionShouldWork()
- {
- var engine = new Engine(options => options.AllowClr(GetType().Assembly));
- engine.SetValue("E", TypeReference.CreateTypeReference(engine, typeof(UintEnum)));
- Assert.Equal(1, engine.Evaluate("E.b;").AsNumber());
- }
- [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());
- }
- 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 ExceptionFromConstructorShouldPropagate()
- {
- _engine.SetValue("Class", TypeReference.CreateTypeReference(_engine, typeof(MemberExceptionTest)));
- var ex = Assert.Throws<InvalidOperationException>(() => _engine.Evaluate("new Class(true);"));
- Assert.Equal("thrown as requested", ex.Message);
- }
- [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 = new ObjectWrapper(_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.FastAddProperty("global", engine.Realm.GlobalObject, true, true, true);
- engine.Realm.GlobalObject.FastAddProperty("test", new DelegateWrapper(engine, (Action<string, object>) Test), true, true, true);
- {
- 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 won't work, but it's normal\""));
- Assert.Equal("Input string was not in a correct format.", ex.Message);
- }
- [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>((int) oi.Length);
- });
- 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 ShouldScoreDoubleToDoubleParameterMatchHigherThanDoubleToFloat()
- {
- var engine = new Engine();
- var mathTypeReference = TypeReference.CreateTypeReference(engine, typeof(Math));
- engine.SetValue("Math2", mathTypeReference);
- var result = engine.Evaluate("Math2.Max(5.37, 5.56)").AsNumber();
- Assert.Equal(5.56d, result);
- }
- [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 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);
- }
- }
- }
|