EngineTests.cs 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Reflection;
  5. using Esprima;
  6. using Esprima.Ast;
  7. using Jint.Native;
  8. using Jint.Native.Array;
  9. using Jint.Native.Object;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Debugger;
  12. using Xunit;
  13. using Xunit.Abstractions;
  14. namespace Jint.Tests.Runtime
  15. {
  16. public class EngineTests : IDisposable
  17. {
  18. private readonly Engine _engine;
  19. private int countBreak = 0;
  20. private StepMode stepMode;
  21. private static readonly TimeZoneInfo _pacificTimeZone;
  22. private static readonly TimeZoneInfo _tongaTimeZone;
  23. private static readonly TimeZoneInfo _easternTimeZone;
  24. static EngineTests()
  25. {
  26. try
  27. {
  28. _pacificTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  29. }
  30. catch (TimeZoneNotFoundException)
  31. {
  32. // https://stackoverflow.com/questions/47848111/how-should-i-fetch-timezoneinfo-in-a-platform-agnostic-way
  33. // should be natively supported soon https://github.com/dotnet/runtime/issues/18644
  34. _pacificTimeZone = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
  35. }
  36. try
  37. {
  38. _tongaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  39. }
  40. catch (TimeZoneNotFoundException)
  41. {
  42. // https://stackoverflow.com/questions/47848111/how-should-i-fetch-timezoneinfo-in-a-platform-agnostic-way
  43. // should be natively supported soon https://github.com/dotnet/runtime/issues/18644
  44. _tongaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific/Tongatapu");
  45. }
  46. try
  47. {
  48. _easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
  49. }
  50. catch (TimeZoneNotFoundException)
  51. {
  52. // https://stackoverflow.com/questions/47848111/how-should-i-fetch-timezoneinfo-in-a-platform-agnostic-way
  53. // should be natively supported soon https://github.com/dotnet/runtime/issues/18644
  54. _easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
  55. }
  56. }
  57. public EngineTests(ITestOutputHelper output)
  58. {
  59. _engine = new Engine()
  60. .SetValue("log", new Action<object>(o => output.WriteLine(o.ToString())))
  61. .SetValue("assert", new Action<bool>(Assert.True))
  62. .SetValue("equal", new Action<object, object>(Assert.Equal))
  63. ;
  64. }
  65. void IDisposable.Dispose()
  66. {
  67. }
  68. private void RunTest(string source)
  69. {
  70. _engine.Execute(source);
  71. }
  72. private string GetEmbeddedFile(string filename)
  73. {
  74. const string prefix = "Jint.Tests.Runtime.Scripts.";
  75. var assembly = typeof(EngineTests).GetTypeInfo().Assembly;
  76. var scriptPath = prefix + filename;
  77. using (var stream = assembly.GetManifestResourceStream(scriptPath))
  78. {
  79. using (var sr = new StreamReader(stream))
  80. {
  81. return sr.ReadToEnd();
  82. }
  83. }
  84. }
  85. [Theory]
  86. [InlineData(42d, "42")]
  87. [InlineData("Hello", "'Hello'")]
  88. public void ShouldInterpretLiterals(object expected, string source)
  89. {
  90. var engine = new Engine();
  91. var result = engine.Evaluate(source).ToObject();
  92. Assert.Equal(expected, result);
  93. }
  94. [Fact]
  95. public void ShouldInterpretVariableDeclaration()
  96. {
  97. var engine = new Engine();
  98. var result = engine
  99. .Evaluate("var foo = 'bar'; foo;")
  100. .ToObject();
  101. Assert.Equal("bar", result);
  102. }
  103. [Theory]
  104. [InlineData(4d, "1 + 3")]
  105. [InlineData(-2d, "1 - 3")]
  106. [InlineData(3d, "1 * 3")]
  107. [InlineData(2d, "6 / 3")]
  108. [InlineData(9d, "15 & 9")]
  109. [InlineData(15d, "15 | 9")]
  110. [InlineData(6d, "15 ^ 9")]
  111. [InlineData(36d, "9 << 2")]
  112. [InlineData(2d, "9 >> 2")]
  113. [InlineData(4d, "19 >>> 2")]
  114. public void ShouldInterpretBinaryExpression(object expected, string source)
  115. {
  116. var engine = new Engine();
  117. var result = engine.Evaluate(source).ToObject();
  118. Assert.Equal(expected, result);
  119. }
  120. [Theory]
  121. [InlineData(-59d, "~58")]
  122. [InlineData(58d, "~~58")]
  123. public void ShouldInterpretUnaryExpression(object expected, string source)
  124. {
  125. var engine = new Engine();
  126. var result = engine.Evaluate(source).ToObject();
  127. Assert.Equal(expected, result);
  128. }
  129. [Fact]
  130. public void ShouldHaveProperReferenceErrorMessage()
  131. {
  132. RunTest(@"
  133. 'use strict';
  134. var arr = [1, 2];
  135. try {
  136. for (i in arr) { }
  137. assert(false);
  138. }
  139. catch (ex) {
  140. assert(ex.message === 'i is not defined');
  141. }
  142. ");
  143. }
  144. [Fact]
  145. public void ShouldHaveProperNotAFunctionErrorMessage()
  146. {
  147. RunTest(@"
  148. try {
  149. var example = {};
  150. example();
  151. assert(false);
  152. }
  153. catch (ex) {
  154. assert(ex.message === 'example is not a function');
  155. }
  156. ");
  157. }
  158. [Fact]
  159. public void ShouldEvaluateHasOwnProperty()
  160. {
  161. RunTest(@"
  162. var x = {};
  163. x.Bar = 42;
  164. assert(x.hasOwnProperty('Bar'));
  165. ");
  166. }
  167. [Fact]
  168. public void FunctionConstructorsShouldCreateNewObjects()
  169. {
  170. RunTest(@"
  171. var Vehicle = function () {};
  172. var vehicle = new Vehicle();
  173. assert(vehicle != undefined);
  174. ");
  175. }
  176. [Fact]
  177. public void NewObjectsInheritFunctionConstructorProperties()
  178. {
  179. RunTest(@"
  180. var Vehicle = function () {};
  181. var vehicle = new Vehicle();
  182. Vehicle.prototype.wheelCount = 4;
  183. assert(vehicle.wheelCount == 4);
  184. assert((new Vehicle()).wheelCount == 4);
  185. ");
  186. }
  187. [Fact]
  188. public void PrototypeFunctionIsInherited()
  189. {
  190. RunTest(@"
  191. function Body(mass){
  192. this.mass = mass;
  193. }
  194. Body.prototype.offsetMass = function(dm) {
  195. this.mass += dm;
  196. return this;
  197. }
  198. var b = new Body(36);
  199. b.offsetMass(6);
  200. assert(b.mass == 42);
  201. ");
  202. }
  203. [Fact]
  204. public void FunctionConstructorCall()
  205. {
  206. RunTest(@"
  207. function Body(mass){
  208. this.mass = mass;
  209. }
  210. var john = new Body(36);
  211. assert(john.mass == 36);
  212. ");
  213. }
  214. [Fact]
  215. public void ArrowFunctionCall()
  216. {
  217. RunTest(@"
  218. var add = (a, b) => {
  219. return a + b;
  220. }
  221. var x = add(1, 2);
  222. assert(x == 3);
  223. ");
  224. }
  225. [Fact]
  226. public void ArrowFunctionExpressionCall()
  227. {
  228. RunTest(@"
  229. var add = (a, b) => a + b;
  230. var x = add(1, 2);
  231. assert(x === 3);
  232. ");
  233. }
  234. [Fact]
  235. public void ArrowFunctionScope()
  236. {
  237. RunTest(@"
  238. var bob = {
  239. _name: ""Bob"",
  240. _friends: [""Alice""],
  241. printFriends() {
  242. this._friends.forEach(f => assert(this._name === ""Bob"" && f === ""Alice""))
  243. }
  244. };
  245. bob.printFriends();
  246. ");
  247. }
  248. [Fact]
  249. public void NewObjectsShouldUsePrivateProperties()
  250. {
  251. RunTest(@"
  252. var Vehicle = function (color) {
  253. this.color = color;
  254. };
  255. var vehicle = new Vehicle('tan');
  256. assert(vehicle.color == 'tan');
  257. ");
  258. }
  259. [Fact]
  260. public void FunctionConstructorsShouldDefinePrototypeChain()
  261. {
  262. RunTest(@"
  263. function Vehicle() {};
  264. var vehicle = new Vehicle();
  265. assert(vehicle.hasOwnProperty('constructor') == false);
  266. ");
  267. }
  268. [Fact]
  269. public void NewObjectsConstructorIsObject()
  270. {
  271. RunTest(@"
  272. var o = new Object();
  273. assert(o.constructor == Object);
  274. ");
  275. }
  276. [Fact]
  277. public void NewObjectsIntanceOfConstructorObject()
  278. {
  279. RunTest(@"
  280. var o = new Object();
  281. assert(o instanceof Object);
  282. ");
  283. }
  284. [Fact]
  285. public void NewObjectsConstructorShouldBeConstructorObject()
  286. {
  287. RunTest(@"
  288. var Vehicle = function () {};
  289. var vehicle = new Vehicle();
  290. assert(vehicle.constructor == Vehicle);
  291. ");
  292. }
  293. [Fact]
  294. public void NewObjectsIntanceOfConstructorFunction()
  295. {
  296. RunTest(@"
  297. var Vehicle = function () {};
  298. var vehicle = new Vehicle();
  299. assert(vehicle instanceof Vehicle);
  300. ");
  301. }
  302. [Fact]
  303. public void ShouldEvaluateForLoops()
  304. {
  305. RunTest(@"
  306. var foo = 0;
  307. for (var i = 0; i < 5; i++) {
  308. foo += i;
  309. }
  310. assert(foo == 10);
  311. ");
  312. }
  313. [Fact]
  314. public void ShouldEvaluateRecursiveFunctions()
  315. {
  316. RunTest(@"
  317. function fib(n) {
  318. if (n < 2) {
  319. return n;
  320. }
  321. return fib(n - 1) + fib(n - 2);
  322. }
  323. var result = fib(6);
  324. assert(result == 8);
  325. ");
  326. }
  327. [Fact]
  328. public void ShouldAccessObjectProperties()
  329. {
  330. RunTest(@"
  331. var o = {};
  332. o.Foo = 'bar';
  333. o.Baz = 42;
  334. o.Blah = o.Foo + o.Baz;
  335. assert(o.Blah == 'bar42');
  336. ");
  337. }
  338. [Fact]
  339. public void ShouldConstructArray()
  340. {
  341. RunTest(@"
  342. var o = [];
  343. assert(o.length == 0);
  344. ");
  345. }
  346. [Fact]
  347. public void ArrayPushShouldIncrementLength()
  348. {
  349. RunTest(@"
  350. var o = [];
  351. o.push(1);
  352. assert(o.length == 1);
  353. ");
  354. }
  355. [Fact]
  356. public void ArrayFunctionInitializesLength()
  357. {
  358. RunTest(@"
  359. assert(Array(3).length == 3);
  360. assert(Array('3').length == 1);
  361. ");
  362. }
  363. [Fact]
  364. public void ArrayIndexerIsAssigned()
  365. {
  366. RunTest(@"
  367. var n = 8;
  368. var o = Array(n);
  369. for (var i = 0; i < n; i++) o[i] = i;
  370. equal(0, o[0]);
  371. equal(7, o[7]);
  372. ");
  373. }
  374. [Fact]
  375. public void DenseArrayTurnsToSparseArrayWhenSizeGrowsTooMuch()
  376. {
  377. RunTest(@"
  378. var n = 1024*10+2;
  379. var o = Array(n);
  380. for (var i = 0; i < n; i++) o[i] = i;
  381. equal(0, o[0]);
  382. equal(n -1, o[n - 1]);
  383. ");
  384. }
  385. [Fact]
  386. public void DenseArrayTurnsToSparseArrayWhenSparseIndexed()
  387. {
  388. RunTest(@"
  389. var o = Array();
  390. o[100] = 1;
  391. assert(o[100] == 1);
  392. ");
  393. }
  394. [Fact]
  395. public void ArrayPopShouldDecrementLength()
  396. {
  397. RunTest(@"
  398. var o = [42, 'foo'];
  399. var pop = o.pop();
  400. assert(o.length == 1);
  401. assert(pop == 'foo');
  402. ");
  403. }
  404. [Fact]
  405. public void ArrayConstructor()
  406. {
  407. RunTest(@"
  408. var o = [];
  409. assert(o.constructor == Array);
  410. ");
  411. }
  412. [Fact]
  413. public void DateConstructor()
  414. {
  415. RunTest(@"
  416. var o = new Date();
  417. assert(o.constructor == Date);
  418. assert(o.hasOwnProperty('constructor') == false);
  419. ");
  420. }
  421. [Fact]
  422. public void DateConstructorWithInvalidParameters()
  423. {
  424. RunTest(@"
  425. var dt = new Date (1, Infinity);
  426. assert(isNaN(dt.getTime()));
  427. ");
  428. }
  429. [Fact]
  430. public void ShouldConvertDateToNumber()
  431. {
  432. RunTest(@"
  433. assert(Number(new Date(0)) === 0);
  434. ");
  435. }
  436. [Fact]
  437. public void MathObjectIsDefined()
  438. {
  439. RunTest(@"
  440. var o = Math.abs(-1)
  441. assert(o == 1);
  442. ");
  443. }
  444. [Fact]
  445. public void VoidShouldReturnUndefined()
  446. {
  447. RunTest(@"
  448. assert(void 0 === undefined);
  449. var x = '1';
  450. assert(void x === undefined);
  451. x = 'x';
  452. assert (isNaN(void x) === true);
  453. x = new String('-1');
  454. assert (void x === undefined);
  455. ");
  456. }
  457. [Fact]
  458. public void TypeofObjectShouldReturnString()
  459. {
  460. RunTest(@"
  461. assert(typeof x === 'undefined');
  462. assert(typeof 0 === 'number');
  463. var x = 0;
  464. assert (typeof x === 'number');
  465. var x = new Object();
  466. assert (typeof x === 'object');
  467. ");
  468. }
  469. [Fact]
  470. public void MathAbsReturnsAbsolute()
  471. {
  472. RunTest(@"
  473. assert(1 == Math.abs(-1));
  474. ");
  475. }
  476. [Fact]
  477. public void NaNIsNan()
  478. {
  479. RunTest(@"
  480. var x = NaN;
  481. assert(isNaN(NaN));
  482. assert(isNaN(Math.abs(x)));
  483. ");
  484. }
  485. [Fact]
  486. public void ToNumberHandlesStringObject()
  487. {
  488. RunTest(@"
  489. x = new String('1');
  490. x *= undefined;
  491. assert(isNaN(x));
  492. ");
  493. }
  494. [Fact]
  495. public void FunctionScopesAreChained()
  496. {
  497. RunTest(@"
  498. var x = 0;
  499. function f1(){
  500. function f2(){
  501. return x;
  502. };
  503. return f2();
  504. var x = 1;
  505. }
  506. assert(f1() === undefined);
  507. ");
  508. }
  509. [Fact]
  510. public void EvalFunctionParseAndExecuteCode()
  511. {
  512. RunTest(@"
  513. var x = 0;
  514. eval('assert(x == 0)');
  515. ");
  516. }
  517. [Fact]
  518. public void ForInStatement()
  519. {
  520. RunTest(@"
  521. var x, y, str = '';
  522. for(var z in this) {
  523. str += z;
  524. }
  525. equal('xystrz', str);
  526. ");
  527. }
  528. [Fact]
  529. public void ForInStatementEnumeratesKeys()
  530. {
  531. RunTest(@"
  532. for(var i in 'abc');
  533. log(i);
  534. assert(i === '2');
  535. ");
  536. }
  537. [Fact]
  538. public void WithStatement()
  539. {
  540. RunTest(@"
  541. with (Math) {
  542. assert(cos(0) == 1);
  543. }
  544. ");
  545. }
  546. [Fact]
  547. public void ObjectExpression()
  548. {
  549. RunTest(@"
  550. var o = { x: 1 };
  551. assert(o.x == 1);
  552. ");
  553. }
  554. [Fact]
  555. public void StringFunctionCreatesString()
  556. {
  557. RunTest(@"
  558. assert(String(NaN) === 'NaN');
  559. ");
  560. }
  561. [Fact]
  562. public void ScopeChainInWithStatement()
  563. {
  564. RunTest(@"
  565. var x = 0;
  566. var myObj = {x : 'obj'};
  567. function f1(){
  568. var x = 1;
  569. function f2(){
  570. with(myObj){
  571. return x;
  572. }
  573. };
  574. return f2();
  575. }
  576. assert(f1() === 'obj');
  577. ");
  578. }
  579. [Fact]
  580. public void TryCatchBlockStatement()
  581. {
  582. RunTest(@"
  583. var x, y, z;
  584. try {
  585. x = 1;
  586. throw new TypeError();
  587. x = 2;
  588. }
  589. catch(e) {
  590. assert(x == 1);
  591. assert(e instanceof TypeError);
  592. y = 1;
  593. }
  594. finally {
  595. assert(x == 1);
  596. z = 1;
  597. }
  598. assert(x == 1);
  599. assert(y == 1);
  600. assert(z == 1);
  601. ");
  602. }
  603. [Fact]
  604. public void FunctionsCanBeAssigned()
  605. {
  606. RunTest(@"
  607. var sin = Math.sin;
  608. assert(sin(0) == 0);
  609. ");
  610. }
  611. [Fact]
  612. public void FunctionArgumentsIsDefined()
  613. {
  614. RunTest(@"
  615. function f() {
  616. assert(arguments.length > 0);
  617. }
  618. f(42);
  619. ");
  620. }
  621. [Fact]
  622. public void PrimitiveValueFunctions()
  623. {
  624. RunTest(@"
  625. var s = (1).toString();
  626. assert(s == '1');
  627. ");
  628. }
  629. [Theory]
  630. [InlineData(true, "'ab' == 'a' + 'b'")]
  631. public void OperatorsPrecedence(object expected, string source)
  632. {
  633. var engine = new Engine();
  634. var result = engine.Evaluate(source).ToObject();
  635. Assert.Equal(expected, result);
  636. }
  637. [Fact]
  638. public void FunctionPrototypeShouldHaveApplyMethod()
  639. {
  640. RunTest(@"
  641. var numbers = [5, 6, 2, 3, 7];
  642. var max = Math.max.apply(null, numbers);
  643. assert(max == 7);
  644. ");
  645. }
  646. [Theory]
  647. [InlineData(double.NaN, "parseInt(NaN)")]
  648. [InlineData(double.NaN, "parseInt(null)")]
  649. [InlineData(double.NaN, "parseInt(undefined)")]
  650. [InlineData(double.NaN, "parseInt(new Boolean(true))")]
  651. [InlineData(double.NaN, "parseInt(Infinity)")]
  652. [InlineData(-1d, "parseInt(-1)")]
  653. [InlineData(-1d, "parseInt('-1')")]
  654. public void ShouldEvaluateParseInt(object expected, string source)
  655. {
  656. var engine = new Engine();
  657. var result = engine.Evaluate(source).ToObject();
  658. Assert.Equal(expected, result);
  659. }
  660. [Fact]
  661. public void ShouldNotExecuteDebuggerStatement()
  662. {
  663. new Engine().Evaluate("debugger");
  664. }
  665. [Fact]
  666. public void ShouldConvertDoubleToStringWithoutLosingPrecision()
  667. {
  668. RunTest(@"
  669. assert(String(14.915832707045631) === '14.915832707045631');
  670. assert(String(-14.915832707045631) === '-14.915832707045631');
  671. assert(String(0.5) === '0.5');
  672. assert(String(0.00000001) === '1e-8');
  673. assert(String(0.000001) === '0.000001');
  674. assert(String(-1.0) === '-1');
  675. assert(String(30.0) === '30');
  676. assert(String(0.2388906159889881) === '0.2388906159889881');
  677. ");
  678. }
  679. [Fact]
  680. public void ShouldWriteNumbersUsingBases()
  681. {
  682. RunTest(@"
  683. assert(15.0.toString() === '15');
  684. assert(15.0.toString(2) === '1111');
  685. assert(15.0.toString(8) === '17');
  686. assert(15.0.toString(16) === 'f');
  687. assert(15.0.toString(17) === 'f');
  688. assert(15.0.toString(36) === 'f');
  689. assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
  690. ");
  691. }
  692. [Fact]
  693. public void ShouldNotAlterSlashesInRegex()
  694. {
  695. RunTest(@"
  696. equal('/\\//', new RegExp('/').toString());
  697. ");
  698. }
  699. [Fact]
  700. public void ShouldHandleEscapedSlashesInRegex()
  701. {
  702. RunTest(@"
  703. var regex = /[a-z]\/[a-z]/;
  704. assert(regex.test('a/b') === true);
  705. assert(regex.test('a\\/b') === false);
  706. ");
  707. }
  708. [Fact]
  709. public void ShouldComputeFractionInBase()
  710. {
  711. Assert.Equal("011", _engine.Realm.Intrinsics.Number.PrototypeObject.ToFractionBase(0.375, 2));
  712. Assert.Equal("14141414141414141414141414141414141414141414141414", _engine.Realm.Intrinsics.Number.PrototypeObject.ToFractionBase(0.375, 5));
  713. }
  714. [Fact]
  715. public void ShouldInvokeAFunctionValue()
  716. {
  717. RunTest(@"
  718. function add(x, y) { return x + y; }
  719. ");
  720. var add = _engine.GetValue("add");
  721. Assert.Equal(3, add.Invoke(1, 2));
  722. }
  723. [Fact]
  724. public void ShouldAllowInvokeAFunctionValueWithNullValueAsArgument()
  725. {
  726. RunTest(@"
  727. function get(x) { return x; }
  728. ");
  729. var add = _engine.GetValue("get");
  730. string str = null;
  731. Assert.Equal(Native.JsValue.Null, add.Invoke(str));
  732. }
  733. [Fact]
  734. public void ShouldNotInvokeNonFunctionValue()
  735. {
  736. RunTest(@"
  737. var x= 10;
  738. ");
  739. var x = _engine.GetValue("x");
  740. Assert.Throws<TypeErrorException>(() => x.Invoke(1, 2));
  741. }
  742. [Fact]
  743. public void ShouldInvokeAFunctionValueThatBelongsToAnObject()
  744. {
  745. RunTest(@"
  746. var obj = { foo: 5, getFoo: function (bar) { return 'foo is ' + this.foo + ', bar is ' + bar; } };
  747. ");
  748. var obj = _engine.GetValue("obj").AsObject();
  749. var getFoo = obj.Get("getFoo", obj);
  750. Assert.Equal("foo is 5, bar is 7", _engine.Invoke(getFoo, obj, new object[] { 7 }).AsString());
  751. }
  752. [Fact]
  753. public void ShouldNotInvokeNonFunctionValueThatBelongsToAnObject()
  754. {
  755. RunTest(@"
  756. var obj = { foo: 2 };
  757. ");
  758. var obj = _engine.GetValue("obj").AsObject();
  759. var foo = obj.Get("foo", obj);
  760. Assert.Throws<JavaScriptException>(() => _engine.Invoke(foo, obj, new object[] { }));
  761. }
  762. [Fact]
  763. public void ShouldNotAllowModifyingSharedUndefinedDescriptor()
  764. {
  765. var e = new Engine();
  766. e.Evaluate("var x = { literal: true };");
  767. var pd = e.GetValue("x").AsObject().GetProperty("doesNotExist");
  768. Assert.Throws<InvalidOperationException>(() => pd.Value = "oh no, assigning this breaks things");
  769. }
  770. [Theory]
  771. [InlineData("0", 0, 16)]
  772. [InlineData("1", 1, 16)]
  773. [InlineData("100", 100, 10)]
  774. [InlineData("1100100", 100, 2)]
  775. [InlineData("2s", 100, 36)]
  776. [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
  777. public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
  778. {
  779. var result = _engine.Realm.Intrinsics.Number.PrototypeObject.ToBase(number, radix);
  780. Assert.Equal(expected, result);
  781. }
  782. [Fact]
  783. public void JsonParserShouldParseNegativeNumber()
  784. {
  785. RunTest(@"
  786. var a = JSON.parse('{ ""x"":-1 }');
  787. assert(a.x === -1);
  788. var b = JSON.parse('{ ""x"": -1 }');
  789. assert(b.x === -1);
  790. ");
  791. }
  792. [Fact]
  793. public void JsonParserShouldUseToString()
  794. {
  795. RunTest(@"
  796. var a = JSON.parse(null); // Equivalent to JSON.parse('null')
  797. assert(a === null);
  798. ");
  799. RunTest(@"
  800. var a = JSON.parse(true); // Equivalent to JSON.parse('true')
  801. assert(a === true);
  802. ");
  803. RunTest(@"
  804. var a = JSON.parse(false); // Equivalent to JSON.parse('false')
  805. assert(a === false);
  806. ");
  807. RunTest(@"
  808. try {
  809. JSON.parse(undefined); // Equivalent to JSON.parse('undefined')
  810. assert(false);
  811. }
  812. catch(ex) {
  813. assert(ex instanceof SyntaxError);
  814. }
  815. ");
  816. RunTest(@"
  817. try {
  818. JSON.parse({}); // Equivalent to JSON.parse('[object Object]')
  819. assert(false);
  820. }
  821. catch(ex) {
  822. assert(ex instanceof SyntaxError);
  823. }
  824. ");
  825. RunTest(@"
  826. try {
  827. JSON.parse(function() { }); // Equivalent to JSON.parse('function () {}')
  828. assert(false);
  829. }
  830. catch(ex) {
  831. assert(ex instanceof SyntaxError);
  832. }
  833. ");
  834. }
  835. [Fact]
  836. public void JsonParserShouldDetectInvalidNegativeNumberSyntax()
  837. {
  838. RunTest(@"
  839. try {
  840. JSON.parse('{ ""x"": -.1 }'); // Not allowed
  841. assert(false);
  842. }
  843. catch(ex) {
  844. assert(ex instanceof SyntaxError);
  845. }
  846. ");
  847. RunTest(@"
  848. try {
  849. JSON.parse('{ ""x"": - 1 }'); // Not allowed
  850. assert(false);
  851. }
  852. catch(ex) {
  853. assert(ex instanceof SyntaxError);
  854. }
  855. ");
  856. }
  857. [Fact]
  858. public void JsonParserShouldUseReviverFunction()
  859. {
  860. RunTest(@"
  861. var jsonObj = JSON.parse('{""p"": 5}', function (key, value){
  862. return typeof value === 'number' ? value * 2 : value;
  863. });
  864. assert(jsonObj.p === 10);
  865. ");
  866. RunTest(@"
  867. var expectedKeys = [""1"", ""2"", ""4"", ""6"", ""5"", ""3"", """"];
  868. var actualKeys = [];
  869. JSON.parse('{""1"": 1, ""2"": 2, ""3"": {""4"": 4, ""5"": {""6"": 6}}}', function (key, value){
  870. actualKeys.push(key);
  871. return value;// return the unchanged property value.
  872. });
  873. expectedKeys.forEach(function (val, i){
  874. assert(actualKeys[i] === val);
  875. });
  876. ");
  877. }
  878. [Fact]
  879. public void JsonParserShouldHandleEmptyString()
  880. {
  881. var ex = Assert.Throws<ParserException>(() => _engine.Evaluate("JSON.parse('');"));
  882. Assert.Equal("Line 1: Unexpected end of input", ex.Message);
  883. }
  884. [Fact]
  885. [ReplaceCulture("fr-FR")]
  886. public void ShouldBeCultureInvariant()
  887. {
  888. // decimals in french are separated by commas
  889. var engine = new Engine();
  890. var result = engine.Evaluate("1.2 + 2.1").AsNumber();
  891. Assert.Equal(3.3d, result);
  892. result = engine.Evaluate("JSON.parse('{\"x\" : 3.3}').x").AsNumber();
  893. Assert.Equal(3.3d, result);
  894. }
  895. [Fact]
  896. public void ShouldGetTheLastSyntaxNode()
  897. {
  898. var engine = new Engine();
  899. engine.Evaluate("1.2");
  900. var result = engine.GetLastSyntaxNode();
  901. Assert.Equal(Nodes.Literal, result.Type);
  902. }
  903. [Fact]
  904. public void ShouldGetParseErrorLocation()
  905. {
  906. var engine = new Engine();
  907. try
  908. {
  909. engine.Evaluate("1.2+ new", new ParserOptions(source: "jQuery.js"));
  910. }
  911. catch (ParserException e)
  912. {
  913. Assert.Equal(1, e.LineNumber);
  914. Assert.Equal(9, e.Column);
  915. Assert.Equal("jQuery.js", e.SourceText);
  916. }
  917. }
  918. #region DateParsingAndStrings
  919. [Fact]
  920. public void ParseShouldReturnNumber()
  921. {
  922. var engine = new Engine();
  923. var result = engine.Evaluate("Date.parse('1970-01-01');").AsNumber();
  924. Assert.Equal(0, result);
  925. }
  926. [Fact]
  927. public void TimeWithinDayShouldHandleNegativeValues()
  928. {
  929. RunTest(@"
  930. // using a date < 1970 so that the primitive value is negative
  931. var d = new Date(1958, 0, 1);
  932. d.setMonth(-1);
  933. assert(d.getDate() == 1);
  934. ");
  935. }
  936. [Fact]
  937. public void LocalDateTimeShouldNotLoseTimezone()
  938. {
  939. var date = new DateTime(2016, 1, 1, 13, 0, 0, DateTimeKind.Local);
  940. var engine = new Engine().SetValue("localDate", date);
  941. var actual = engine.Evaluate(@"localDate").AsDate().ToDateTime();
  942. Assert.Equal(date.ToUniversalTime(), actual.ToUniversalTime());
  943. Assert.Equal(date.ToLocalTime(), actual.ToLocalTime());
  944. }
  945. [Fact]
  946. public void UtcShouldUseUtc()
  947. {
  948. var customTimeZone = _tongaTimeZone;
  949. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  950. var result = engine.Evaluate("Date.UTC(1970,0,1)").AsNumber();
  951. Assert.Equal(0, result);
  952. }
  953. [Fact]
  954. public void ShouldUseLocalTimeZoneOverride()
  955. {
  956. const string customName = "Custom Time";
  957. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  958. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  959. var epochGetLocalMinutes = engine.Evaluate("var d = new Date(0); d.getMinutes();").AsNumber();
  960. Assert.Equal(11, epochGetLocalMinutes);
  961. var localEpochGetUtcMinutes = engine.Evaluate("var d = new Date(1970,0,1); d.getUTCMinutes();").AsNumber();
  962. Assert.Equal(49, localEpochGetUtcMinutes);
  963. var parseLocalEpoch = engine.Evaluate("Date.parse('January 1, 1970');").AsNumber();
  964. Assert.Equal(-11 * 60 * 1000, parseLocalEpoch);
  965. var epochToLocalString = engine.Evaluate("var d = new Date(0); d.toString();").AsString();
  966. Assert.Equal("Thu Jan 01 1970 00:11:00 GMT+0011", epochToLocalString);
  967. var epochToUTCString = engine.Evaluate("var d = new Date(0); d.toUTCString();").AsString();
  968. Assert.Equal("Thu, 01 Jan 1970 00:00:00 GMT", epochToUTCString);
  969. }
  970. [Theory]
  971. [InlineData("1970")]
  972. [InlineData("1970-01")]
  973. [InlineData("1970-01-01")]
  974. [InlineData("1970-01-01T00:00")]
  975. [InlineData("1970-01-01T00:00:00")]
  976. [InlineData("1970-01-01T00:00:00.000")]
  977. [InlineData("1970Z")]
  978. [InlineData("1970-1Z")]
  979. [InlineData("1970-1-1Z")]
  980. [InlineData("1970-1-1T0:0Z")]
  981. [InlineData("1970-1-1T0:0:0Z")]
  982. [InlineData("1970-1-1T0:0:0.0Z")]
  983. [InlineData("1970/1Z")]
  984. [InlineData("1970/1/1Z")]
  985. [InlineData("1970/1/1 0:0Z")]
  986. [InlineData("1970/1/1 0:0:0Z")]
  987. [InlineData("1970/1/1 0:0:0.0Z")]
  988. [InlineData("January 1, 1970 GMT")]
  989. [InlineData("1970-01-01T00:00:00.000-00:00")]
  990. public void ShouldParseAsUtc(string date)
  991. {
  992. var customTimeZone = _tongaTimeZone;
  993. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  994. engine.SetValue("d", date);
  995. var result = engine.Evaluate("Date.parse(d);").AsNumber();
  996. Assert.Equal(0, result);
  997. }
  998. [Theory]
  999. [InlineData("1970/01")]
  1000. [InlineData("1970/01/01")]
  1001. [InlineData("1970/01/01T00:00")]
  1002. [InlineData("1970/01/01 00:00")]
  1003. [InlineData("1970-1")]
  1004. [InlineData("1970-1-1")]
  1005. [InlineData("1970-1-1T0:0")]
  1006. [InlineData("1970-1-1 0:0")]
  1007. [InlineData("1970/1")]
  1008. [InlineData("1970/1/1")]
  1009. [InlineData("1970/1/1T0:0")]
  1010. [InlineData("1970/1/1 0:0")]
  1011. [InlineData("01-1970")]
  1012. [InlineData("01-01-1970")]
  1013. [InlineData("January 1, 1970")]
  1014. [InlineData("1970-01-01T00:00:00.000+00:11")]
  1015. public void ShouldParseAsLocalTime(string date)
  1016. {
  1017. const int timespanMinutes = 11;
  1018. const int msPriorMidnight = -timespanMinutes * 60 * 1000;
  1019. const string customName = "Custom Time";
  1020. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, timespanMinutes, 0), customName, customName, customName, null, false);
  1021. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone)).SetValue("d", date);
  1022. var result = engine.Evaluate("Date.parse(d);").AsNumber();
  1023. Assert.Equal(msPriorMidnight, result);
  1024. }
  1025. public static System.Collections.Generic.IEnumerable<object[]> TestDates
  1026. {
  1027. get
  1028. {
  1029. yield return new object[] { new DateTime(2000, 1, 1) };
  1030. yield return new object[] { new DateTime(2000, 1, 1, 0, 15, 15, 15) };
  1031. yield return new object[] { new DateTime(2000, 6, 1, 0, 15, 15, 15) };
  1032. yield return new object[] { new DateTime(1900, 1, 1) };
  1033. yield return new object[] { new DateTime(1900, 1, 1, 0, 15, 15, 15) };
  1034. yield return new object[] { new DateTime(1900, 6, 1, 0, 15, 15, 15) };
  1035. }
  1036. }
  1037. [Theory, MemberData("TestDates")]
  1038. public void TestDateToISOStringFormat(DateTime testDate)
  1039. {
  1040. var customTimeZone = _pacificTimeZone;
  1041. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1042. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1043. engine.Execute(
  1044. string.Format("var d = new Date({0},{1},{2},{3},{4},{5},{6});", testDateTimeOffset.Year, testDateTimeOffset.Month - 1, testDateTimeOffset.Day, testDateTimeOffset.Hour, testDateTimeOffset.Minute, testDateTimeOffset.Second, testDateTimeOffset.Millisecond));
  1045. Assert.Equal(testDateTimeOffset.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture), engine.Evaluate("d.toISOString();").ToString());
  1046. }
  1047. [Theory, MemberData("TestDates")]
  1048. public void TestDateToStringFormat(DateTime testDate)
  1049. {
  1050. var customTimeZone = _pacificTimeZone;
  1051. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1052. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1053. engine.Execute(
  1054. string.Format("var d = new Date({0},{1},{2},{3},{4},{5},{6});", testDateTimeOffset.Year, testDateTimeOffset.Month - 1, testDateTimeOffset.Day, testDateTimeOffset.Hour, testDateTimeOffset.Minute, testDateTimeOffset.Second, testDateTimeOffset.Millisecond));
  1055. var expected = testDateTimeOffset.ToString("ddd MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture);
  1056. expected += testDateTimeOffset.ToString(" 'GMT'zzz", CultureInfo.InvariantCulture).Replace(":", "");
  1057. var actual = engine.Evaluate("d.toString();").ToString();
  1058. Assert.Equal(expected, actual);
  1059. }
  1060. #endregion
  1061. //DateParsingAndStrings
  1062. [Fact]
  1063. public void EmptyStringShouldMatchRegex()
  1064. {
  1065. RunTest(@"
  1066. var regex = /^(?:$)/g;
  1067. assert(''.match(regex) instanceof Array);
  1068. ");
  1069. }
  1070. [Fact]
  1071. public void ShouldExecuteHandlebars()
  1072. {
  1073. var content = GetEmbeddedFile("handlebars.js");
  1074. RunTest(content);
  1075. RunTest(@"
  1076. var source = 'Hello {{name}}';
  1077. var template = Handlebars.compile(source);
  1078. var context = {name: 'Paul'};
  1079. var html = template(context);
  1080. assert('Hello Paul' == html);
  1081. ");
  1082. }
  1083. [Fact]
  1084. public void ShouldExecuteDromaeoBase64()
  1085. {
  1086. RunTest(@"
  1087. var startTest = function () { };
  1088. var test = function (name, fn) { fn(); };
  1089. var endTest = function () { };
  1090. var prep = function (fn) { fn(); };
  1091. ");
  1092. var content = GetEmbeddedFile("dromaeo-string-base64.js");
  1093. RunTest(content);
  1094. }
  1095. [Fact]
  1096. public void ShouldExecuteKnockoutWithoutErrorWhetherTolerantOrIntolerant()
  1097. {
  1098. var content = GetEmbeddedFile("knockout-3.4.0.js");
  1099. _engine.Execute(content, new ParserOptions { Tolerant = true });
  1100. _engine.Execute(content, new ParserOptions { Tolerant = false });
  1101. }
  1102. [Fact]
  1103. public void ShouldAllowProtoProperty()
  1104. {
  1105. var code = "if({ __proto__: [] } instanceof Array) {}";
  1106. _engine.Execute(code);
  1107. _engine.Execute($"eval('{code}')");
  1108. _engine.Execute($"new Function('{code}')");
  1109. }
  1110. [Fact]
  1111. public void ShouldNotAllowDuplicateProtoProperty()
  1112. {
  1113. var code = "if({ __proto__: [], __proto__:[] } instanceof Array) {}";
  1114. Exception ex = Assert.Throws<ParserException>(() => _engine.Execute(code, new ParserOptions { Tolerant = false }));
  1115. Assert.Contains("Duplicate __proto__ fields are not allowed in object literals", ex.Message);
  1116. ex = Assert.Throws<JavaScriptException>(() => _engine.Execute($"eval('{code}')"));
  1117. Assert.Contains("Duplicate __proto__ fields are not allowed in object literals", ex.Message);
  1118. Assert.Throws<JavaScriptException>(() => _engine.Execute($"new Function('{code}')"));
  1119. Assert.Contains("Duplicate __proto__ fields are not allowed in object literals", ex.Message);
  1120. }
  1121. [Fact]
  1122. public void ShouldExecuteLodash()
  1123. {
  1124. var content = GetEmbeddedFile("lodash.min.js");
  1125. RunTest(content);
  1126. }
  1127. [Fact]
  1128. public void DateParseReturnsNaN()
  1129. {
  1130. RunTest(@"
  1131. var d = Date.parse('not a date');
  1132. assert(isNaN(d));
  1133. ");
  1134. }
  1135. [Fact]
  1136. public void ShouldIgnoreHtmlComments()
  1137. {
  1138. RunTest(@"
  1139. var d = Date.parse('not a date'); <!-- a comment -->
  1140. assert(isNaN(d));
  1141. ");
  1142. }
  1143. [Fact]
  1144. public void DateShouldAllowEntireDotNetDateRange()
  1145. {
  1146. var engine = new Engine();
  1147. var minValue = engine.Evaluate("new Date('0001-01-01T00:00:00.000')").ToObject();
  1148. Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc), minValue);
  1149. var maxValue = engine.Evaluate("new Date('9999-12-31T23:59:59.999')").ToObject();
  1150. #if NETCOREAPP
  1151. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 998, DateTimeKind.Utc), maxValue);
  1152. #else
  1153. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc), maxValue);
  1154. #endif
  1155. }
  1156. [Fact]
  1157. public void ShouldConstructNewArrayWithInteger()
  1158. {
  1159. RunTest(@"
  1160. var a = new Array(3);
  1161. assert(a.length === 3);
  1162. assert(a[0] == undefined);
  1163. assert(a[1] == undefined);
  1164. assert(a[2] == undefined);
  1165. ");
  1166. }
  1167. [Fact]
  1168. public void ShouldConstructNewArrayWithString()
  1169. {
  1170. RunTest(@"
  1171. var a = new Array('foo');
  1172. assert(a.length === 1);
  1173. assert(a[0] === 'foo');
  1174. ");
  1175. }
  1176. [Fact]
  1177. public void ShouldThrowRangeExceptionWhenConstructedWithNonInteger()
  1178. {
  1179. RunTest(@"
  1180. var result = false;
  1181. try {
  1182. var a = new Array(3.4);
  1183. }
  1184. catch(e) {
  1185. result = e instanceof RangeError;
  1186. }
  1187. assert(result);
  1188. ");
  1189. }
  1190. [Fact]
  1191. public void ShouldInitializeArrayWithSingleIngegerValue()
  1192. {
  1193. RunTest(@"
  1194. var a = [3];
  1195. assert(a.length === 1);
  1196. assert(a[0] === 3);
  1197. ");
  1198. }
  1199. [Fact]
  1200. public void ShouldInitializeJsonObjectArrayWithSingleIntegerValue()
  1201. {
  1202. RunTest(@"
  1203. var x = JSON.parse('{ ""a"": [3] }');
  1204. assert(x.a.length === 1);
  1205. assert(x.a[0] === 3);
  1206. ");
  1207. }
  1208. [Fact]
  1209. public void ShouldInitializeJsonArrayWithSingleIntegerValue()
  1210. {
  1211. RunTest(@"
  1212. var a = JSON.parse('[3]');
  1213. assert(a.length === 1);
  1214. assert(a[0] === 3);
  1215. ");
  1216. }
  1217. [Fact]
  1218. public void ShouldReturnTrueForEmptyIsNaNStatement()
  1219. {
  1220. RunTest(@"
  1221. assert(true === isNaN());
  1222. ");
  1223. }
  1224. [Theory]
  1225. [InlineData(4d, 0, "4")]
  1226. [InlineData(4d, 1, "4.0")]
  1227. [InlineData(4d, 2, "4.00")]
  1228. [InlineData(28.995, 2, "29.00")]
  1229. [InlineData(-28.995, 2, "-29.00")]
  1230. [InlineData(-28.495, 2, "-28.50")]
  1231. [InlineData(-28.445, 2, "-28.45")]
  1232. [InlineData(28.445, 2, "28.45")]
  1233. [InlineData(10.995, 0, "11")]
  1234. public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
  1235. {
  1236. var engine = new Engine();
  1237. var value = engine.Evaluate(
  1238. String.Format("new Number({0}).toFixed({1})",
  1239. number.ToString(CultureInfo.InvariantCulture),
  1240. fractionDigits.ToString(CultureInfo.InvariantCulture)))
  1241. .ToObject();
  1242. Assert.Equal(value, result);
  1243. }
  1244. [Fact]
  1245. public void ShouldSortArrayWhenCompareFunctionReturnsFloatingPointNumber()
  1246. {
  1247. RunTest(@"
  1248. var nums = [1, 1.1, 1.2, 2, 2, 2.1, 2.2];
  1249. nums.sort(function(a,b){return b-a;});
  1250. assert(nums[0] === 2.2);
  1251. assert(nums[1] === 2.1);
  1252. assert(nums[2] === 2);
  1253. assert(nums[3] === 2);
  1254. assert(nums[4] === 1.2);
  1255. assert(nums[5] === 1.1);
  1256. assert(nums[6] === 1);
  1257. ");
  1258. }
  1259. [Fact]
  1260. public void ShouldBreakWhenBreakpointIsReached()
  1261. {
  1262. countBreak = 0;
  1263. stepMode = StepMode.None;
  1264. var engine = new Engine(options => options.DebugMode());
  1265. engine.DebugHandler.Break += EngineStep;
  1266. engine.DebugHandler.BreakPoints.Add(new BreakPoint(1, 1));
  1267. engine.Evaluate(@"var local = true;
  1268. if (local === true)
  1269. {}");
  1270. engine.DebugHandler.Break -= EngineStep;
  1271. Assert.Equal(1, countBreak);
  1272. }
  1273. [Fact]
  1274. public void ShouldExecuteStepByStep()
  1275. {
  1276. countBreak = 0;
  1277. stepMode = StepMode.Into;
  1278. var engine = new Engine(options => options.DebugMode());
  1279. engine.DebugHandler.Step += EngineStep;
  1280. engine.Evaluate(@"var local = true;
  1281. var creatingSomeOtherLine = 0;
  1282. var lastOneIPromise = true");
  1283. engine.DebugHandler.Step -= EngineStep;
  1284. Assert.Equal(3, countBreak);
  1285. }
  1286. [Fact]
  1287. public void ShouldNotBreakTwiceIfSteppingOverBreakpoint()
  1288. {
  1289. countBreak = 0;
  1290. stepMode = StepMode.Into;
  1291. var engine = new Engine(options => options.DebugMode());
  1292. engine.DebugHandler.BreakPoints.Add(new BreakPoint(1, 1));
  1293. engine.DebugHandler.Step += EngineStep;
  1294. engine.DebugHandler.Break += EngineStep;
  1295. engine.Evaluate(@"var local = true;");
  1296. engine.DebugHandler.Step -= EngineStep;
  1297. engine.DebugHandler.Break -= EngineStep;
  1298. Assert.Equal(1, countBreak);
  1299. }
  1300. private StepMode EngineStep(object sender, DebugInformation debugInfo)
  1301. {
  1302. Assert.NotNull(sender);
  1303. Assert.IsType(typeof(Engine), sender);
  1304. Assert.NotNull(debugInfo);
  1305. countBreak++;
  1306. return stepMode;
  1307. }
  1308. [Fact]
  1309. public void ShouldShowProperDebugInformation()
  1310. {
  1311. countBreak = 0;
  1312. stepMode = StepMode.None;
  1313. var engine = new Engine(options => options.DebugMode());
  1314. engine.DebugHandler.BreakPoints.Add(new BreakPoint(5, 0));
  1315. engine.DebugHandler.Break += EngineStepVerifyDebugInfo;
  1316. engine.Evaluate(@"var global = true;
  1317. function func1()
  1318. {
  1319. var local = false;
  1320. ;
  1321. }
  1322. func1();");
  1323. engine.DebugHandler.Break -= EngineStepVerifyDebugInfo;
  1324. Assert.Equal(1, countBreak);
  1325. }
  1326. private StepMode EngineStepVerifyDebugInfo(object sender, DebugInformation debugInfo)
  1327. {
  1328. Assert.NotNull(sender);
  1329. Assert.IsType(typeof(Engine), sender);
  1330. Assert.NotNull(debugInfo);
  1331. Assert.NotNull(debugInfo.CallStack);
  1332. Assert.NotNull(debugInfo.CurrentStatement);
  1333. Assert.NotNull(debugInfo.CurrentScopeChain);
  1334. Assert.NotNull(debugInfo.CurrentScopeChain.Global);
  1335. Assert.NotNull(debugInfo.CurrentScopeChain.Local);
  1336. Assert.Equal(2, debugInfo.CallStack.Count);
  1337. Assert.Equal("func1", debugInfo.CurrentCallFrame.FunctionName);
  1338. var globalScope = debugInfo.CurrentScopeChain.Global;
  1339. var localScope = debugInfo.CurrentScopeChain.Local;
  1340. Assert.Contains("global", globalScope.BindingNames);
  1341. Assert.Equal(true, globalScope.GetBindingValue("global").AsBoolean());
  1342. Assert.Contains("local", localScope.BindingNames);
  1343. Assert.Equal(false, localScope.GetBindingValue("local").AsBoolean());
  1344. Assert.DoesNotContain("global", localScope.BindingNames);
  1345. countBreak++;
  1346. return stepMode;
  1347. }
  1348. [Fact]
  1349. public void ShouldBreakWhenConditionIsMatched()
  1350. {
  1351. countBreak = 0;
  1352. stepMode = StepMode.None;
  1353. var engine = new Engine(options => options.DebugMode());
  1354. engine.DebugHandler.Break += EngineStep;
  1355. engine.DebugHandler.BreakPoints.Add(new BreakPoint(5, 16, "condition === true"));
  1356. engine.DebugHandler.BreakPoints.Add(new BreakPoint(6, 16, "condition === false"));
  1357. engine.Evaluate(@"var local = true;
  1358. var condition = true;
  1359. if (local === true)
  1360. {
  1361. ;
  1362. ;
  1363. }");
  1364. engine.DebugHandler.Break -= EngineStep;
  1365. Assert.Equal(1, countBreak);
  1366. }
  1367. [Fact]
  1368. public void ShouldNotStepInSameLevelStatementsWhenStepOut()
  1369. {
  1370. countBreak = 0;
  1371. stepMode = StepMode.Out;
  1372. var engine = new Engine(options => options.DebugMode());
  1373. engine.DebugHandler.Step += EngineStep;
  1374. engine.Evaluate(@"function func() // first step - then stepping out
  1375. {
  1376. ; // shall not step
  1377. ; // not even here
  1378. }
  1379. func(); // shall not step
  1380. ; // shall not step ");
  1381. engine.DebugHandler.Step -= EngineStep;
  1382. Assert.Equal(1, countBreak);
  1383. }
  1384. [Fact]
  1385. public void ShouldNotStepInIfRequiredToStepOut()
  1386. {
  1387. countBreak = 0;
  1388. var engine = new Engine(options => options.DebugMode());
  1389. engine.DebugHandler.Step += EngineStepOutWhenInsideFunction;
  1390. engine.Evaluate(@"function func() // first step
  1391. {
  1392. ; // third step - now stepping out
  1393. ; // it should not step here
  1394. }
  1395. func(); // second step
  1396. ; // fourth step ");
  1397. engine.DebugHandler.Step -= EngineStepOutWhenInsideFunction;
  1398. Assert.Equal(4, countBreak);
  1399. }
  1400. private StepMode EngineStepOutWhenInsideFunction(object sender, DebugInformation debugInfo)
  1401. {
  1402. Assert.NotNull(sender);
  1403. Assert.IsType(typeof(Engine), sender);
  1404. Assert.NotNull(debugInfo);
  1405. countBreak++;
  1406. if (debugInfo.CallStack.Count > 1) // CallStack always has at least one element
  1407. return StepMode.Out;
  1408. return StepMode.Into;
  1409. }
  1410. [Fact]
  1411. public void ShouldBreakWhenStatementIsMultiLine()
  1412. {
  1413. countBreak = 0;
  1414. stepMode = StepMode.None;
  1415. var engine = new Engine(options => options.DebugMode());
  1416. engine.DebugHandler.BreakPoints.Add(new BreakPoint(4, 33));
  1417. engine.DebugHandler.Break += EngineStep;
  1418. engine.Evaluate(@"var global = true;
  1419. function func1()
  1420. {
  1421. var local =
  1422. false;
  1423. }
  1424. func1();");
  1425. engine.DebugHandler.Break -= EngineStep;
  1426. Assert.Equal(1, countBreak);
  1427. }
  1428. [Fact]
  1429. public void ShouldNotStepInsideIfRequiredToStepOver()
  1430. {
  1431. countBreak = 0;
  1432. var engine = new Engine(options => options.DebugMode());
  1433. stepMode = StepMode.Over;
  1434. engine.DebugHandler.Step += EngineStep;
  1435. engine.Evaluate(@"function func() // first step
  1436. {
  1437. ; // third step - it shall not step here
  1438. ; // it shall not step here
  1439. }
  1440. func(); // second step
  1441. ; // third step ");
  1442. engine.DebugHandler.Step -= EngineStep;
  1443. Assert.Equal(3, countBreak);
  1444. }
  1445. [Fact]
  1446. public void ShouldStepAllStatementsWithoutInvocationsIfStepOver()
  1447. {
  1448. countBreak = 0;
  1449. var engine = new Engine(options => options.DebugMode());
  1450. stepMode = StepMode.Over;
  1451. engine.DebugHandler.Step += EngineStep;
  1452. engine.Evaluate(@"var step1 = 1; // first step
  1453. var step2 = 2; // second step
  1454. if (step1 !== step2) // third step
  1455. { // fourth step
  1456. ; // fifth step
  1457. }");
  1458. engine.DebugHandler.Step -= EngineStep;
  1459. Assert.Equal(5, countBreak);
  1460. }
  1461. [Fact]
  1462. public void ShouldEvaluateVariableAssignmentFromLeftToRight()
  1463. {
  1464. RunTest(@"
  1465. var keys = ['a']
  1466. , source = { a: 3}
  1467. , target = {}
  1468. , key
  1469. , i = 0;
  1470. target[key = keys[i++]] = source[key];
  1471. equal(1, i);
  1472. equal('a', key);
  1473. equal(3, target[key]);
  1474. ");
  1475. }
  1476. [Fact]
  1477. public void ObjectShouldBeExtensible()
  1478. {
  1479. RunTest(@"
  1480. try {
  1481. Object.defineProperty(Object.defineProperty, 'foo', { value: 1 });
  1482. }
  1483. catch(e) {
  1484. assert(false);
  1485. }
  1486. ");
  1487. }
  1488. [Fact]
  1489. public void ArrayIndexShouldBeConvertedToUint32()
  1490. {
  1491. // This is missing from ECMA tests suite
  1492. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  1493. RunTest(@"
  1494. var a = [ 'foo' ];
  1495. assert(a[0] === 'foo');
  1496. assert(a['0'] === 'foo');
  1497. assert(a['00'] === undefined);
  1498. ");
  1499. }
  1500. [Fact]
  1501. public void HexZeroAsArrayIndexShouldWork()
  1502. {
  1503. var engine = new Engine();
  1504. engine.Evaluate("var t = '1234'; var value = null;");
  1505. Assert.Equal("1", engine.Execute("value = t[0x0];").GetValue("value").AsString());
  1506. Assert.Equal("1", engine.Execute("value = t[0];").GetValue("value").AsString());
  1507. Assert.Equal("1", engine.Execute("value = t['0'];").GetValue("value").AsString());
  1508. }
  1509. [Fact]
  1510. public void DatePrototypeFunctionWorkOnDateOnly()
  1511. {
  1512. RunTest(@"
  1513. try {
  1514. var myObj = Object.create(Date.prototype);
  1515. myObj.toDateString();
  1516. } catch (e) {
  1517. assert(e instanceof TypeError);
  1518. }
  1519. ");
  1520. }
  1521. [Fact]
  1522. public void DateToStringMethodsShouldUseCurrentTimeZoneAndCulture()
  1523. {
  1524. // Forcing to PDT and FR for tests
  1525. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1526. var PDT = _pacificTimeZone;
  1527. var FR = new CultureInfo("fr-FR");
  1528. var engine = new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1529. .SetValue("log", new Action<object>(Console.WriteLine))
  1530. .SetValue("assert", new Action<bool>(Assert.True))
  1531. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1532. ;
  1533. engine.Evaluate(@"
  1534. var d = new Date(1433160000000);
  1535. equal('Mon Jun 01 2015 05:00:00 GMT-0700', d.toString());
  1536. equal('Mon Jun 01 2015', d.toDateString());
  1537. equal('05:00:00 GMT-0700', d.toTimeString());
  1538. equal('lundi 1 juin 2015 05:00:00', d.toLocaleString());
  1539. equal('lundi 1 juin 2015', d.toLocaleDateString());
  1540. equal('05:00:00', d.toLocaleTimeString());
  1541. ");
  1542. }
  1543. [Fact]
  1544. public void DateShouldHonorTimezoneDaylightSavingRules()
  1545. {
  1546. var EST = _easternTimeZone;
  1547. var engine = new Engine(options => options.LocalTimeZone(EST))
  1548. .SetValue("log", new Action<object>(Console.WriteLine))
  1549. .SetValue("assert", new Action<bool>(Assert.True))
  1550. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1551. ;
  1552. engine.Evaluate(@"
  1553. var d = new Date(2016, 8, 1);
  1554. equal('Thu Sep 01 2016 00:00:00 GMT-0400', d.toString());
  1555. equal('Thu Sep 01 2016', d.toDateString());
  1556. ");
  1557. }
  1558. [Fact]
  1559. public void DateShouldParseToString()
  1560. {
  1561. // Forcing to PDT and FR for tests
  1562. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1563. var PDT = _pacificTimeZone;
  1564. var FR = new CultureInfo("fr-FR");
  1565. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1566. .SetValue("log", new Action<object>(Console.WriteLine))
  1567. .SetValue("assert", new Action<bool>(Assert.True))
  1568. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1569. .Evaluate(@"
  1570. var d = new Date(1433160000000);
  1571. equal(Date.parse(d.toString()), d.valueOf());
  1572. equal(Date.parse(d.toLocaleString()), d.valueOf());
  1573. ");
  1574. }
  1575. [Fact]
  1576. public void LocaleNumberShouldUseLocalCulture()
  1577. {
  1578. // Forcing to PDT and FR for tests
  1579. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1580. var PDT = _pacificTimeZone;
  1581. var FR = new CultureInfo("fr-FR");
  1582. var engine = new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1583. .SetValue("log", new Action<object>(Console.WriteLine))
  1584. .SetValue("assert", new Action<bool>(Assert.True))
  1585. .SetValue("equal", new Action<object, object>(Assert.Equal));
  1586. engine.Evaluate("var d = new Number(-1.23);");
  1587. engine.Evaluate("equal('-1.23', d.toString());");
  1588. // NET 5 globalization APIs use ICU libraries on newer Windows 10 giving different result
  1589. // build server is older Windows...
  1590. engine.Evaluate("assert('-1,230' === d.toLocaleString() || '-1,23' === d.toLocaleString());");
  1591. }
  1592. [Fact]
  1593. public void DateCtorShouldAcceptDate()
  1594. {
  1595. RunTest(@"
  1596. var a = new Date();
  1597. var b = new Date(a);
  1598. assert(String(a) === String(b));
  1599. ");
  1600. }
  1601. [Fact]
  1602. public void RegExpResultIsMutable()
  1603. {
  1604. RunTest(@"
  1605. var match = /quick\s(brown).+?(jumps)/ig.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
  1606. var result = match.shift();
  1607. assert(result === 'Quick Brown Fox Jumps');
  1608. ");
  1609. }
  1610. [Fact]
  1611. public void RegExpSupportsMultiline()
  1612. {
  1613. RunTest(@"
  1614. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1615. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1616. match = rheaders.exec(headersString);
  1617. assert('X-AspNetMvc-Version' === match[1]);
  1618. assert('4.0' === match[2]);
  1619. ");
  1620. RunTest(@"
  1621. var rheaders = /^(.*?):[ \t]*(.*?)$/mg;
  1622. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1623. match = rheaders.exec(headersString);
  1624. assert('X-AspNetMvc-Version' === match[1]);
  1625. assert('4.0' === match[2]);
  1626. ");
  1627. RunTest(@"
  1628. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1629. var headersString = 'X-AspNetMvc-Version: 4.0\nX-Powered-By: ASP.NET\n\n';
  1630. match = rheaders.exec(headersString);
  1631. assert('X-AspNetMvc-Version' === match[1]);
  1632. assert('4.0' === match[2]);
  1633. ");
  1634. }
  1635. [Fact]
  1636. public void RegExpPrototypeToString()
  1637. {
  1638. RunTest("assert(RegExp.prototype.toString() === '/(?:)/');");
  1639. }
  1640. [Fact]
  1641. public void ShouldSetYearBefore1970()
  1642. {
  1643. RunTest(@"
  1644. var d = new Date('1969-01-01T08:17:00');
  1645. d.setYear(2015);
  1646. equal('2015-01-01T08:17:00.000Z', d.toISOString());
  1647. ");
  1648. }
  1649. [Fact]
  1650. public void ShouldUseReplaceMarkers()
  1651. {
  1652. RunTest(@"
  1653. var re = /a/g;
  1654. var str = 'abab';
  1655. var newstr = str.replace(re, '$\'x');
  1656. equal('babxbbxb', newstr);
  1657. ");
  1658. }
  1659. [Fact]
  1660. public void ExceptionShouldHaveLocationOfInnerFunction()
  1661. {
  1662. try
  1663. {
  1664. new Engine()
  1665. .Evaluate(@"
  1666. function test(s) {
  1667. o.boom();
  1668. }
  1669. test('arg');
  1670. ");
  1671. }
  1672. catch (JavaScriptException ex)
  1673. {
  1674. Assert.Equal(3, ex.LineNumber);
  1675. }
  1676. }
  1677. [Fact]
  1678. public void GlobalRegexLiteralShouldNotKeepState()
  1679. {
  1680. RunTest(@"
  1681. var url = 'https://www.example.com';
  1682. assert(isAbsolutePath(url));
  1683. assert(isAbsolutePath(url));
  1684. assert(isAbsolutePath(url));
  1685. function isAbsolutePath(path) {
  1686. return /\.+/g.test(path);
  1687. }
  1688. ");
  1689. }
  1690. [Fact]
  1691. public void ShouldCompareInnerValueOfClrInstances()
  1692. {
  1693. var engine = new Engine();
  1694. // Create two separate Guid with identical inner values.
  1695. var guid1 = Guid.NewGuid();
  1696. var guid2 = new Guid(guid1.ToString());
  1697. engine.SetValue("guid1", guid1);
  1698. engine.SetValue("guid2", guid2);
  1699. var result = engine.Evaluate("guid1 == guid2").AsBoolean();
  1700. Assert.True(result);
  1701. }
  1702. [Fact]
  1703. public void CanStringifyToConsole()
  1704. {
  1705. var engine = new Engine(options => options.AllowClr(typeof(Console).Assembly));
  1706. engine.Evaluate("System.Console.WriteLine(JSON.stringify({x:12, y:14}));");
  1707. }
  1708. [Fact]
  1709. public void ShouldNotCompareClrInstancesWithObjects()
  1710. {
  1711. var engine = new Engine();
  1712. var guid1 = Guid.NewGuid();
  1713. engine.SetValue("guid1", guid1);
  1714. var result = engine.Evaluate("guid1 == {}").AsBoolean();
  1715. Assert.False(result);
  1716. }
  1717. [Fact]
  1718. public void ShouldStringifyNumWithoutV8DToA()
  1719. {
  1720. // 53.6841659 cannot be converted by V8's DToA => "old" DToA code will be used.
  1721. var engine = new Engine();
  1722. var val = engine.Evaluate("JSON.stringify(53.6841659)");
  1723. Assert.Equal("53.6841659", val.AsString());
  1724. }
  1725. [Fact]
  1726. public void ShouldStringifyObjectWithPropertiesToSameRef()
  1727. {
  1728. var engine = new Engine();
  1729. var res = engine.Evaluate(@"
  1730. var obj = {
  1731. a : [],
  1732. a1 : ['str'],
  1733. a2 : {},
  1734. a3 : { 'prop' : 'val' }
  1735. };
  1736. obj.b = obj.a;
  1737. obj.b1 = obj.a1;
  1738. JSON.stringify(obj);
  1739. ");
  1740. Assert.True(res == "{\"a\":[],\"a1\":[\"str\"],\"a2\":{},\"a3\":{\"prop\":\"val\"},\"b\":[],\"b1\":[\"str\"]}");
  1741. }
  1742. [Fact]
  1743. public void ShouldThrowOnSerializingCyclicRefObject()
  1744. {
  1745. var engine = new Engine();
  1746. var res = engine.Evaluate(@"
  1747. (function(){
  1748. try{
  1749. a = [];
  1750. a[0] = a;
  1751. my_text = JSON.stringify(a);
  1752. }
  1753. catch(ex){
  1754. return ex.message;
  1755. }
  1756. })();
  1757. ");
  1758. Assert.True(res == "Cyclic reference detected.");
  1759. }
  1760. [Theory]
  1761. [InlineData("", "escape('')")]
  1762. [InlineData("%u0100%u0101%u0102", "escape('\u0100\u0101\u0102')")]
  1763. [InlineData("%uFFFD%uFFFE%uFFFF", "escape('\ufffd\ufffe\uffff')")]
  1764. [InlineData("%uD834%uDF06", "escape('\ud834\udf06')")]
  1765. [InlineData("%00%01%02%03", "escape('\x00\x01\x02\x03')")]
  1766. [InlineData("%2C", "escape(',')")]
  1767. [InlineData("%3A%3B%3C%3D%3E%3F", "escape(':;<=>?')")]
  1768. [InlineData("%60", "escape('`')")]
  1769. [InlineData("%7B%7C%7D%7E%7F%80", "escape('{|}~\x7f\x80')")]
  1770. [InlineData("%FD%FE%FF", "escape('\xfd\xfe\xff')")]
  1771. [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./", "escape('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./')")]
  1772. public void ShouldEvaluateEscape(object expected, string source)
  1773. {
  1774. var engine = new Engine();
  1775. var result = engine.Evaluate(source).ToObject();
  1776. Assert.Equal(expected, result);
  1777. }
  1778. [Theory]
  1779. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/empty-string.js
  1780. [InlineData("", "unescape('')")]
  1781. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-bad-u.js
  1782. [InlineData("%U0000", "unescape('%U0000')")]
  1783. [InlineData("%t0000", "unescape('%t0000')")]
  1784. [InlineData("%v0000", "unescape('%v0000')")]
  1785. [InlineData("%" + "\x00" + "00", "unescape('%%0000')")]
  1786. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-end-str.js
  1787. [InlineData("%u", "unescape('%u')")]
  1788. [InlineData("%u0", "unescape('%u0')")]
  1789. [InlineData("%u1", "unescape('%u1')")]
  1790. [InlineData("%u2", "unescape('%u2')")]
  1791. [InlineData("%u3", "unescape('%u3')")]
  1792. [InlineData("%u4", "unescape('%u4')")]
  1793. [InlineData("%u5", "unescape('%u5')")]
  1794. [InlineData("%u6", "unescape('%u6')")]
  1795. [InlineData("%u7", "unescape('%u7')")]
  1796. [InlineData("%u8", "unescape('%u8')")]
  1797. [InlineData("%u9", "unescape('%u9')")]
  1798. [InlineData("%ua", "unescape('%ua')")]
  1799. [InlineData("%uA", "unescape('%uA')")]
  1800. [InlineData("%ub", "unescape('%ub')")]
  1801. [InlineData("%uB", "unescape('%uB')")]
  1802. [InlineData("%uc", "unescape('%uc')")]
  1803. [InlineData("%uC", "unescape('%uC')")]
  1804. [InlineData("%ud", "unescape('%ud')")]
  1805. [InlineData("%uD", "unescape('%uD')")]
  1806. [InlineData("%ue", "unescape('%ue')")]
  1807. [InlineData("%uE", "unescape('%uE')")]
  1808. [InlineData("%uf", "unescape('%uf')")]
  1809. [InlineData("%uF", "unescape('%uF')")]
  1810. [InlineData("%u01", "unescape('%u01')")]
  1811. [InlineData("%u02", "unescape('%u02')")]
  1812. [InlineData("%u03", "unescape('%u03')")]
  1813. [InlineData("%u04", "unescape('%u04')")]
  1814. [InlineData("%u05", "unescape('%u05')")]
  1815. [InlineData("%u06", "unescape('%u06')")]
  1816. [InlineData("%u07", "unescape('%u07')")]
  1817. [InlineData("%u08", "unescape('%u08')")]
  1818. [InlineData("%u09", "unescape('%u09')")]
  1819. [InlineData("%u0a", "unescape('%u0a')")]
  1820. [InlineData("%u0A", "unescape('%u0A')")]
  1821. [InlineData("%u0b", "unescape('%u0b')")]
  1822. [InlineData("%u0B", "unescape('%u0B')")]
  1823. [InlineData("%u0c", "unescape('%u0c')")]
  1824. [InlineData("%u0C", "unescape('%u0C')")]
  1825. [InlineData("%u0d", "unescape('%u0d')")]
  1826. [InlineData("%u0D", "unescape('%u0D')")]
  1827. [InlineData("%u0e", "unescape('%u0e')")]
  1828. [InlineData("%u0E", "unescape('%u0E')")]
  1829. [InlineData("%u0f", "unescape('%u0f')")]
  1830. [InlineData("%u0F", "unescape('%u0F')")]
  1831. [InlineData("%u000", "unescape('%u000')")]
  1832. [InlineData("%u001", "unescape('%u001')")]
  1833. [InlineData("%u002", "unescape('%u002')")]
  1834. [InlineData("%u003", "unescape('%u003')")]
  1835. [InlineData("%u004", "unescape('%u004')")]
  1836. [InlineData("%u005", "unescape('%u005')")]
  1837. [InlineData("%u006", "unescape('%u006')")]
  1838. [InlineData("%u007", "unescape('%u007')")]
  1839. [InlineData("%u008", "unescape('%u008')")]
  1840. [InlineData("%u009", "unescape('%u009')")]
  1841. [InlineData("%u00a", "unescape('%u00a')")]
  1842. [InlineData("%u00A", "unescape('%u00A')")]
  1843. [InlineData("%u00b", "unescape('%u00b')")]
  1844. [InlineData("%u00B", "unescape('%u00B')")]
  1845. [InlineData("%u00c", "unescape('%u00c')")]
  1846. [InlineData("%u00C", "unescape('%u00C')")]
  1847. [InlineData("%u00d", "unescape('%u00d')")]
  1848. [InlineData("%u00D", "unescape('%u00D')")]
  1849. [InlineData("%u00e", "unescape('%u00e')")]
  1850. [InlineData("%u00E", "unescape('%u00E')")]
  1851. [InlineData("%u00f", "unescape('%u00f')")]
  1852. [InlineData("%u00F", "unescape('%u00F')")]
  1853. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-non-hex.js
  1854. [InlineData("%u000%0", "unescape('%u000%0')")]
  1855. [InlineData("%u000g0", "unescape('%u000g0')")]
  1856. [InlineData("%u000G0", "unescape('%u000G0')")]
  1857. [InlineData("%u00g00", "unescape('%u00g00')")]
  1858. [InlineData("%u00G00", "unescape('%u00G00')")]
  1859. [InlineData("%u0g000", "unescape('%u0g000')")]
  1860. [InlineData("%u0G000", "unescape('%u0G000')")]
  1861. [InlineData("%ug0000", "unescape('%ug0000')")]
  1862. [InlineData("%uG0000", "unescape('%uG0000')")]
  1863. [InlineData("%u000u0", "unescape('%u000u0')")]
  1864. [InlineData("%u000U0", "unescape('%u000U0')")]
  1865. [InlineData("%u00u00", "unescape('%u00u00')")]
  1866. [InlineData("%u00U00", "unescape('%u00U00')")]
  1867. [InlineData("%u0u000", "unescape('%u0u000')")]
  1868. [InlineData("%u0U000", "unescape('%u0U000')")]
  1869. [InlineData("%uu0000", "unescape('%uu0000')")]
  1870. [InlineData("%uU0000", "unescape('%uU0000')")]
  1871. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four.js
  1872. [InlineData("%0" + "\x00" + "0", "unescape('%0%u00000')")]
  1873. [InlineData("%0" + "\x01" + "0", "unescape('%0%u00010')")]
  1874. [InlineData("%0)0", "unescape('%0%u00290')")]
  1875. [InlineData("%0*0", "unescape('%0%u002a0')")]
  1876. [InlineData("%0*0", "unescape('%0%u002A0')")]
  1877. [InlineData("%0+0", "unescape('%0%u002b0')")]
  1878. [InlineData("%0+0", "unescape('%0%u002B0')")]
  1879. [InlineData("%0,0", "unescape('%0%u002c0')")]
  1880. [InlineData("%0,0", "unescape('%0%u002C0')")]
  1881. [InlineData("%0-0", "unescape('%0%u002d0')")]
  1882. [InlineData("%0-0", "unescape('%0%u002D0')")]
  1883. [InlineData("%090", "unescape('%0%u00390')")]
  1884. [InlineData("%0:0", "unescape('%0%u003a0')")]
  1885. [InlineData("%0:0", "unescape('%0%u003A0')")]
  1886. [InlineData("%0?0", "unescape('%0%u003f0')")]
  1887. [InlineData("%0?0", "unescape('%0%u003F0')")]
  1888. [InlineData("%0@0", "unescape('%0%u00400')")]
  1889. [InlineData("%0Z0", "unescape('%0%u005a0')")]
  1890. [InlineData("%0Z0", "unescape('%0%u005A0')")]
  1891. [InlineData("%0[0", "unescape('%0%u005b0')")]
  1892. [InlineData("%0[0", "unescape('%0%u005B0')")]
  1893. [InlineData("%0^0", "unescape('%0%u005e0')")]
  1894. [InlineData("%0^0", "unescape('%0%u005E0')")]
  1895. [InlineData("%0_0", "unescape('%0%u005f0')")]
  1896. [InlineData("%0_0", "unescape('%0%u005F0')")]
  1897. [InlineData("%0`0", "unescape('%0%u00600')")]
  1898. [InlineData("%0a0", "unescape('%0%u00610')")]
  1899. [InlineData("%0z0", "unescape('%0%u007a0')")]
  1900. [InlineData("%0z0", "unescape('%0%u007A0')")]
  1901. [InlineData("%0{0", "unescape('%0%u007b0')")]
  1902. [InlineData("%0{0", "unescape('%0%u007B0')")]
  1903. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufffe0')")]
  1904. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uFffe0')")]
  1905. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufFfe0')")]
  1906. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uffFe0')")]
  1907. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufffE0')")]
  1908. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uFFFE0')")]
  1909. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uffff0')")]
  1910. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uFfff0')")]
  1911. [InlineData("%0" + "\uffff" + "0", "unescape('%0%ufFff0')")]
  1912. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uffFf0')")]
  1913. [InlineData("%0" + "\uffff" + "0", "unescape('%0%ufffF0')")]
  1914. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uFFFF0')")]
  1915. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two-ignore-end-str.js
  1916. [InlineData("%", "unescape('%')")]
  1917. [InlineData("%0", "unescape('%0')")]
  1918. [InlineData("%1", "unescape('%1')")]
  1919. [InlineData("%2", "unescape('%2')")]
  1920. [InlineData("%3", "unescape('%3')")]
  1921. [InlineData("%4", "unescape('%4')")]
  1922. [InlineData("%5", "unescape('%5')")]
  1923. [InlineData("%6", "unescape('%6')")]
  1924. [InlineData("%7", "unescape('%7')")]
  1925. [InlineData("%8", "unescape('%8')")]
  1926. [InlineData("%9", "unescape('%9')")]
  1927. [InlineData("%a", "unescape('%a')")]
  1928. [InlineData("%A", "unescape('%A')")]
  1929. [InlineData("%b", "unescape('%b')")]
  1930. [InlineData("%B", "unescape('%B')")]
  1931. [InlineData("%c", "unescape('%c')")]
  1932. [InlineData("%C", "unescape('%C')")]
  1933. [InlineData("%d", "unescape('%d')")]
  1934. [InlineData("%D", "unescape('%D')")]
  1935. [InlineData("%e", "unescape('%e')")]
  1936. [InlineData("%E", "unescape('%E')")]
  1937. [InlineData("%f", "unescape('%f')")]
  1938. [InlineData("%F", "unescape('%F')")]
  1939. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two-ignore-non-hex.js
  1940. [InlineData("%0%0", "unescape('%0%0')")]
  1941. [InlineData("%0g0", "unescape('%0g0')")]
  1942. [InlineData("%0G0", "unescape('%0G0')")]
  1943. [InlineData("%g00", "unescape('%g00')")]
  1944. [InlineData("%G00", "unescape('%G00')")]
  1945. [InlineData("%0u0", "unescape('%0u0')")]
  1946. [InlineData("%0U0", "unescape('%0U0')")]
  1947. [InlineData("%u00", "unescape('%u00')")]
  1948. [InlineData("%U00", "unescape('%U00')")]
  1949. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two.js
  1950. [InlineData("%0" + "\x00" + "00", "unescape('%0%0000')")]
  1951. [InlineData("%0" + "\x01" + "00", "unescape('%0%0100')")]
  1952. [InlineData("%0)00", "unescape('%0%2900')")]
  1953. [InlineData("%0*00", "unescape('%0%2a00')")]
  1954. [InlineData("%0*00", "unescape('%0%2A00')")]
  1955. [InlineData("%0+00", "unescape('%0%2b00')")]
  1956. [InlineData("%0+00", "unescape('%0%2B00')")]
  1957. [InlineData("%0,00", "unescape('%0%2c00')")]
  1958. [InlineData("%0,00", "unescape('%0%2C00')")]
  1959. [InlineData("%0-00", "unescape('%0%2d00')")]
  1960. [InlineData("%0-00", "unescape('%0%2D00')")]
  1961. [InlineData("%0900", "unescape('%0%3900')")]
  1962. [InlineData("%0:00", "unescape('%0%3a00')")]
  1963. [InlineData("%0:00", "unescape('%0%3A00')")]
  1964. [InlineData("%0?00", "unescape('%0%3f00')")]
  1965. [InlineData("%0?00", "unescape('%0%3F00')")]
  1966. [InlineData("%0@00", "unescape('%0%4000')")]
  1967. [InlineData("%0Z00", "unescape('%0%5a00')")]
  1968. [InlineData("%0Z00", "unescape('%0%5A00')")]
  1969. [InlineData("%0[00", "unescape('%0%5b00')")]
  1970. [InlineData("%0[00", "unescape('%0%5B00')")]
  1971. [InlineData("%0^00", "unescape('%0%5e00')")]
  1972. [InlineData("%0^00", "unescape('%0%5E00')")]
  1973. [InlineData("%0_00", "unescape('%0%5f00')")]
  1974. [InlineData("%0_00", "unescape('%0%5F00')")]
  1975. [InlineData("%0`00", "unescape('%0%6000')")]
  1976. [InlineData("%0a00", "unescape('%0%6100')")]
  1977. [InlineData("%0z00", "unescape('%0%7a00')")]
  1978. [InlineData("%0z00", "unescape('%0%7A00')")]
  1979. [InlineData("%0{00", "unescape('%0%7b00')")]
  1980. [InlineData("%0{00", "unescape('%0%7B00')")]
  1981. public void ShouldEvaluateUnescape(object expected, string source)
  1982. {
  1983. var engine = new Engine();
  1984. var result = engine.Evaluate(source).ToObject();
  1985. Assert.Equal(expected, result);
  1986. }
  1987. [Theory]
  1988. [InlineData("new Date(1969,0,1,19,45,30,500).getHours()", 19)]
  1989. [InlineData("new Date(1970,0,1,19,45,30,500).getHours()", 19)]
  1990. [InlineData("new Date(1971,0,1,19,45,30,500).getHours()", 19)]
  1991. [InlineData("new Date(1969,0,1,19,45,30,500).getMinutes()", 45)]
  1992. [InlineData("new Date(1970,0,1,19,45,30,500).getMinutes()", 45)]
  1993. [InlineData("new Date(1971,0,1,19,45,30,500).getMinutes()", 45)]
  1994. [InlineData("new Date(1969,0,1,19,45,30,500).getSeconds()", 30)]
  1995. [InlineData("new Date(1970,0,1,19,45,30,500).getSeconds()", 30)]
  1996. [InlineData("new Date(1971,0,1,19,45,30,500).getSeconds()", 30)]
  1997. //[InlineData("new Date(1969,0,1,19,45,30,500).getMilliseconds()", 500)]
  1998. //[InlineData("new Date(1970,0,1,19,45,30,500).getMilliseconds()", 500)]
  1999. //[InlineData("new Date(1971,0,1,19,45,30,500).getMilliseconds()", 500)]
  2000. public void ShouldExtractDateParts(string source, double expected)
  2001. {
  2002. var engine = new Engine();
  2003. var result = engine.Evaluate(source).ToObject();
  2004. Assert.Equal(expected, result);
  2005. }
  2006. [Theory]
  2007. [InlineData("'abc'.padStart(10)", " abc")]
  2008. [InlineData("'abc'.padStart(10, \"foo\")", "foofoofabc")]
  2009. [InlineData("'abc'.padStart(6, \"123456\")", "123abc")]
  2010. [InlineData("'abc'.padStart(8, \"0\")", "00000abc")]
  2011. [InlineData("'abc'.padStart(1)", "abc")]
  2012. public void ShouldPadStart(string source, object expected)
  2013. {
  2014. var engine = new Engine();
  2015. var result = engine.Evaluate(source).ToObject();
  2016. Assert.Equal(expected, result);
  2017. }
  2018. [Theory]
  2019. [InlineData("'abc'.padEnd(10)", "abc ")]
  2020. [InlineData("'abc'.padEnd(10, \"foo\")", "abcfoofoof")]
  2021. [InlineData("'abc'.padEnd(6, \"123456\")", "abc123")]
  2022. [InlineData("'abc'.padEnd(1)", "abc")]
  2023. public void ShouldPadEnd(string source, object expected)
  2024. {
  2025. var engine = new Engine();
  2026. var result = engine.Evaluate(source).ToObject();
  2027. Assert.Equal(expected, result);
  2028. }
  2029. /// <summary>
  2030. /// Tests for startsWith - tests created from MDN and https://github.com/mathiasbynens/String.prototype.startsWith/blob/master/tests/tests.js
  2031. /// </summary>
  2032. [Theory]
  2033. [InlineData("'To be, or not to be, that is the question.'.startsWith('To be')", true)]
  2034. [InlineData("'To be, or not to be, that is the question.'.startsWith('not to be')", false)]
  2035. [InlineData("'To be, or not to be, that is the question.'.startsWith()", false)]
  2036. [InlineData("'To be, or not to be, that is the question.'.startsWith('not to be', 10)", true)]
  2037. [InlineData("'undefined'.startsWith()", true)]
  2038. [InlineData("'undefined'.startsWith(undefined)", true)]
  2039. [InlineData("'undefined'.startsWith(null)", false)]
  2040. [InlineData("'null'.startsWith()", false)]
  2041. [InlineData("'null'.startsWith(undefined)", false)]
  2042. [InlineData("'null'.startsWith(null)", true)]
  2043. [InlineData("'abc'.startsWith()", false)]
  2044. [InlineData("'abc'.startsWith('')", true)]
  2045. [InlineData("'abc'.startsWith('\0')", false)]
  2046. [InlineData("'abc'.startsWith('a')", true)]
  2047. [InlineData("'abc'.startsWith('b')", false)]
  2048. [InlineData("'abc'.startsWith('ab')", true)]
  2049. [InlineData("'abc'.startsWith('bc')", false)]
  2050. [InlineData("'abc'.startsWith('abc')", true)]
  2051. [InlineData("'abc'.startsWith('bcd')", false)]
  2052. [InlineData("'abc'.startsWith('abcd')", false)]
  2053. [InlineData("'abc'.startsWith('bcde')", false)]
  2054. [InlineData("'abc'.startsWith('', 1)", true)]
  2055. [InlineData("'abc'.startsWith('\0', 1)", false)]
  2056. [InlineData("'abc'.startsWith('a', 1)", false)]
  2057. [InlineData("'abc'.startsWith('b', 1)", true)]
  2058. [InlineData("'abc'.startsWith('ab', 1)", false)]
  2059. [InlineData("'abc'.startsWith('bc', 1)", true)]
  2060. [InlineData("'abc'.startsWith('abc', 1)", false)]
  2061. [InlineData("'abc'.startsWith('bcd', 1)", false)]
  2062. [InlineData("'abc'.startsWith('abcd', 1)", false)]
  2063. [InlineData("'abc'.startsWith('bcde', 1)", false)]
  2064. public void ShouldStartWith(string source, object expected)
  2065. {
  2066. var engine = new Engine();
  2067. var result = engine.Evaluate(source).ToObject();
  2068. Assert.Equal(expected, result);
  2069. }
  2070. [Theory]
  2071. [InlineData("throw {}", "undefined")]
  2072. [InlineData("throw {message:null}", "null")]
  2073. [InlineData("throw {message:''}", "")]
  2074. [InlineData("throw {message:2}", "2")]
  2075. public void ShouldAllowNonStringMessage(string source, string expected)
  2076. {
  2077. var engine = new Engine();
  2078. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute(source));
  2079. Assert.Equal(expected, ex.Message);
  2080. }
  2081. [Theory]
  2082. //Months
  2083. [InlineData("new Date(2017, 0, 1, 0, 0, 0)", "new Date(2016, 12, 1, 0, 0, 0)")]
  2084. [InlineData("new Date(2016, 0, 1, 23, 59, 59)", "new Date(2015, 12, 1, 23, 59, 59)")]
  2085. [InlineData("new Date(2013, 0, 1, 0, 0, 0)", "new Date(2012, 12, 1, 0, 0, 0)")]
  2086. [InlineData("new Date(2013, 0, 29, 23, 59, 59)", "new Date(2012, 12, 29, 23, 59, 59)")]
  2087. [InlineData("new Date(2015, 11, 1, 0, 0, 0)", "new Date(2016, -1, 1, 0, 0, 0)")]
  2088. [InlineData("new Date(2014, 11, 1, 23, 59, 59)", "new Date(2015, -1, 1, 23, 59, 59)")]
  2089. [InlineData("new Date(2011, 11, 1, 0, 0, 0)", "new Date(2012, -1, 1, 0, 0, 0)")]
  2090. [InlineData("new Date(2011, 11, 29, 23, 59, 59)", "new Date(2012, -1, 29, 23, 59, 59)")]
  2091. [InlineData("new Date(2015, 1, 1, 0, 0, 0)", "new Date(2016, -11, 1, 0, 0, 0)")]
  2092. [InlineData("new Date(2014, 1, 1, 23, 59, 59)", "new Date(2015, -11, 1, 23, 59, 59)")]
  2093. [InlineData("new Date(2011, 1, 1, 0, 0, 0)", "new Date(2012, -11, 1, 0, 0, 0)")]
  2094. [InlineData("new Date(2011, 2, 1, 23, 59, 59)", "new Date(2012, -11, 29, 23, 59, 59)")]
  2095. [InlineData("new Date(2015, 0, 1, 0, 0, 0)", "new Date(2016, -12, 1, 0, 0, 0)")]
  2096. [InlineData("new Date(2014, 0, 1, 23, 59, 59)", "new Date(2015, -12, 1, 23, 59, 59)")]
  2097. [InlineData("new Date(2011, 0, 1, 0, 0, 0)", "new Date(2012, -12, 1, 0, 0, 0)")]
  2098. [InlineData("new Date(2011, 0, 29, 23, 59, 59)", "new Date(2012, -12, 29, 23, 59, 59)")]
  2099. [InlineData("new Date(2014, 11, 1, 0, 0, 0)", "new Date(2016, -13, 1, 0, 0, 0)")]
  2100. [InlineData("new Date(2013, 11, 1, 23, 59, 59)", "new Date(2015, -13, 1, 23, 59, 59)")]
  2101. [InlineData("new Date(2010, 11, 1, 0, 0, 0)", "new Date(2012, -13, 1, 0, 0, 0)")]
  2102. [InlineData("new Date(2010, 11, 29, 23, 59, 59)", "new Date(2012, -13, 29, 23, 59, 59)")]
  2103. [InlineData("new Date(2013, 11, 1, 0, 0, 0)", "new Date(2016, -25, 1, 0, 0, 0)")]
  2104. [InlineData("new Date(2012, 11, 1, 23, 59, 59)", "new Date(2015, -25, 1, 23, 59, 59)")]
  2105. [InlineData("new Date(2009, 11, 1, 0, 0, 0)", "new Date(2012, -25, 1, 0, 0, 0)")]
  2106. [InlineData("new Date(2009, 11, 29, 23, 59, 59)", "new Date(2012, -25, 29, 23, 59, 59)")]
  2107. //Days
  2108. [InlineData("new Date(2016, 1, 11, 0, 0, 0)", "new Date(2016, 0, 42, 0, 0, 0)")]
  2109. [InlineData("new Date(2016, 0, 11, 23, 59, 59)", "new Date(2015, 11, 42, 23, 59, 59)")]
  2110. [InlineData("new Date(2012, 3, 11, 0, 0, 0)", "new Date(2012, 2, 42, 0, 0, 0)")]
  2111. [InlineData("new Date(2012, 2, 13, 23, 59, 59)", "new Date(2012, 1, 42, 23, 59, 59)")]
  2112. [InlineData("new Date(2015, 11, 31, 0, 0, 0)", "new Date(2016, 0, 0, 0, 0, 0)")]
  2113. [InlineData("new Date(2015, 10, 30, 23, 59, 59)", "new Date(2015, 11, 0, 23, 59, 59)")]
  2114. [InlineData("new Date(2012, 1, 29, 0, 0, 0)", "new Date(2012, 2, 0, 0, 0, 0)")]
  2115. [InlineData("new Date(2012, 0, 31, 23, 59, 59)", "new Date(2012, 1, 0, 23, 59, 59)")]
  2116. [InlineData("new Date(2015, 10, 24, 0, 0, 0)", "new Date(2016, 0, -37, 0, 0, 0)")]
  2117. [InlineData("new Date(2015, 9, 24, 23, 59, 59)", "new Date(2015, 11, -37, 23, 59, 59)")]
  2118. [InlineData("new Date(2012, 0, 23, 0, 0, 0)", "new Date(2012, 2, -37, 0, 0, 0)")]
  2119. [InlineData("new Date(2011, 11, 25, 23, 59, 59)", "new Date(2012, 1, -37, 23, 59, 59)")]
  2120. //Hours
  2121. [InlineData("new Date(2016, 0, 2, 1, 0, 0)", "new Date(2016, 0, 1, 25, 0, 0)")]
  2122. [InlineData("new Date(2015, 11, 2, 1, 59, 59)", "new Date(2015, 11, 1, 25, 59, 59)")]
  2123. [InlineData("new Date(2012, 2, 2, 1, 0, 0)", "new Date(2012, 2, 1, 25, 0, 0)")]
  2124. [InlineData("new Date(2012, 2, 1, 1, 59, 59)", "new Date(2012, 1, 29, 25, 59, 59)")]
  2125. [InlineData("new Date(2016, 0, 19, 3, 0, 0)", "new Date(2016, 0, 1, 435, 0, 0)")]
  2126. [InlineData("new Date(2015, 11, 19, 3, 59, 59)", "new Date(2015, 11, 1, 435, 59, 59)")]
  2127. [InlineData("new Date(2012, 2, 19, 3, 0, 0)", "new Date(2012, 2, 1, 435, 0, 0)")]
  2128. [InlineData("new Date(2012, 2, 18, 3, 59, 59)", "new Date(2012, 1, 29, 435, 59, 59)")]
  2129. [InlineData("new Date(2015, 11, 31, 23, 0, 0)", "new Date(2016, 0, 1, -1, 0, 0)")]
  2130. [InlineData("new Date(2015, 10, 30, 23, 59, 59)", "new Date(2015, 11, 1, -1, 59, 59)")]
  2131. [InlineData("new Date(2012, 1, 29, 23, 0, 0)", "new Date(2012, 2, 1, -1, 0, 0)")]
  2132. [InlineData("new Date(2012, 1, 28, 23, 59, 59)", "new Date(2012, 1, 29, -1, 59, 59)")]
  2133. [InlineData("new Date(2015, 11, 3, 18, 0, 0)", "new Date(2016, 0, 1, -678, 0, 0)")]
  2134. [InlineData("new Date(2015, 10, 2, 18, 59, 59)", "new Date(2015, 11, 1, -678, 59, 59)")]
  2135. [InlineData("new Date(2012, 1, 1, 18, 0, 0)", "new Date(2012, 2, 1, -678, 0, 0)")]
  2136. [InlineData("new Date(2012, 0, 31, 18, 59, 59)", "new Date(2012, 1, 29, -678, 59, 59)")]
  2137. // Minutes
  2138. [InlineData("new Date(2016, 0, 1, 1, 0, 0)", "new Date(2016, 0, 1, 0, 60, 0)")]
  2139. [InlineData("new Date(2015, 11, 2, 0, 0, 59)", "new Date(2015, 11, 1, 23, 60, 59)")]
  2140. [InlineData("new Date(2012, 2, 1, 1, 0, 0)", "new Date(2012, 2, 1, 0, 60, 0)")]
  2141. [InlineData("new Date(2012, 2, 1, 0, 0, 59)", "new Date(2012, 1, 29, 23, 60, 59)")]
  2142. [InlineData("new Date(2015, 11, 31, 23, 59, 0)", "new Date(2016, 0, 1, 0, -1, 0)")]
  2143. [InlineData("new Date(2015, 11, 1, 22, 59, 59)", "new Date(2015, 11, 1, 23, -1, 59)")]
  2144. [InlineData("new Date(2012, 1, 29, 23, 59, 0)", "new Date(2012, 2, 1, 0, -1, 0)")]
  2145. [InlineData("new Date(2012, 1, 29, 22, 59, 59)", "new Date(2012, 1, 29, 23, -1, 59)")]
  2146. [InlineData("new Date(2016, 0, 2, 15, 5, 0)", "new Date(2016, 0, 1, 0, 2345, 0)")]
  2147. [InlineData("new Date(2015, 11, 3, 14, 5, 59)", "new Date(2015, 11, 1, 23, 2345, 59)")]
  2148. [InlineData("new Date(2012, 2, 2, 15, 5, 0)", "new Date(2012, 2, 1, 0, 2345, 0)")]
  2149. [InlineData("new Date(2012, 2, 2, 14, 5, 59)", "new Date(2012, 1, 29, 23, 2345, 59)")]
  2150. [InlineData("new Date(2015, 11, 25, 18, 24, 0)", "new Date(2016, 0, 1, 0, -8976, 0)")]
  2151. [InlineData("new Date(2015, 10, 25, 17, 24, 59)", "new Date(2015, 11, 1, 23, -8976, 59)")]
  2152. [InlineData("new Date(2012, 1, 23, 18, 24, 0)", "new Date(2012, 2, 1, 0, -8976, 0)")]
  2153. [InlineData("new Date(2012, 1, 23, 17, 24, 59)", "new Date(2012, 1, 29, 23, -8976, 59)")]
  2154. // Seconds
  2155. [InlineData("new Date(2016, 0, 1, 0, 1, 0)", "new Date(2016, 0, 1, 0, 0, 60)")]
  2156. [InlineData("new Date(2015, 11, 2, 0, 0, 0)", "new Date(2015, 11, 1, 23, 59, 60)")]
  2157. [InlineData("new Date(2012, 2, 1, 0, 1, 0)", "new Date(2012, 2, 1, 0, 0, 60)")]
  2158. [InlineData("new Date(2012, 2, 1, 0, 0, 0)", "new Date(2012, 1, 29, 23, 59, 60)")]
  2159. [InlineData("new Date(2015, 11, 31, 23, 59, 59)", "new Date(2016, 0, 1, 0, 0, -1)")]
  2160. [InlineData("new Date(2015, 11, 1, 23, 58, 59)", "new Date(2015, 11, 1, 23, 59, -1)")]
  2161. [InlineData("new Date(2012, 1, 29, 23, 59, 59)", "new Date(2012, 2, 1, 0, 0, -1)")]
  2162. [InlineData("new Date(2012, 1, 29, 23, 58, 59)", "new Date(2012, 1, 29, 23, 59, -1)")]
  2163. [InlineData("new Date(2016, 0, 3, 17, 9, 58)", "new Date(2016, 0, 1, 0, 0, 234598)")]
  2164. [InlineData("new Date(2015, 11, 4, 17, 8, 58)", "new Date(2015, 11, 1, 23, 59, 234598)")]
  2165. [InlineData("new Date(2012, 2, 3, 17, 9, 58)", "new Date(2012, 2, 1, 0, 0, 234598)")]
  2166. [InlineData("new Date(2012, 2, 3, 17, 8, 58)", "new Date(2012, 1, 29, 23, 59, 234598)")]
  2167. [InlineData("new Date(2015, 11, 21, 14, 39, 15)", "new Date(2016, 0, 1, 0, 0, -897645)")]
  2168. [InlineData("new Date(2015, 10, 21, 14, 38, 15)", "new Date(2015, 11, 1, 23, 59, -897645)")]
  2169. [InlineData("new Date(2012, 1, 19, 14, 39, 15)", "new Date(2012, 2, 1, 0, 0, -897645)")]
  2170. [InlineData("new Date(2012, 1, 19, 14, 38, 15)", "new Date(2012, 1, 29, 23, 59, -897645)")]
  2171. public void ShouldSupportDateConsturctorWithArgumentOutOfRange(string expected, string actual)
  2172. {
  2173. var engine = new Engine(o => o.LocalTimeZone(TimeZoneInfo.Utc));
  2174. var expectedValue = engine.Evaluate(expected).ToObject();
  2175. var actualValue = engine.Evaluate(actual).ToObject();
  2176. Assert.Equal(expectedValue, actualValue);
  2177. }
  2178. [Fact]
  2179. public void ShouldReturnCorrectConcatenatedStrings()
  2180. {
  2181. RunTest(@"
  2182. function concat(x, a, b) {
  2183. x += a;
  2184. x += b;
  2185. return x;
  2186. }");
  2187. var concat = _engine.GetValue("concat");
  2188. var result = concat.Invoke("concat", "well", "done").ToObject() as string;
  2189. Assert.Equal("concatwelldone", result);
  2190. }
  2191. [Fact]
  2192. public void ComplexMappingAndReducing()
  2193. {
  2194. const string program = @"
  2195. Object.map = function (o, f, ctx) {
  2196. ctx = ctx || this;
  2197. var result = [];
  2198. Object.keys(o).forEach(function(k) {
  2199. result.push(f.call(ctx, o[k], k));
  2200. });
  2201. return result;
  2202. };
  2203. var x1 = {""Value"":1.0,""Elements"":[{""Name"":""a"",""Value"":""b"",""Decimal"":3.2},{""Name"":""a"",""Value"":""b"",""Decimal"": 3.5}],""Values"":{""test"": 2,""test1"":3,""test2"": 4}}
  2204. var x2 = {""Value"":2.0,""Elements"":[{""Name"":""aa"",""Value"":""ba"",""Decimal"":3.5}],""Values"":{""test"":1,""test1"":2,""test2"":3}};
  2205. function output(x) {
  2206. var elements = x.Elements.map(function(a){return a.Decimal;});
  2207. var values = x.Values;
  2208. var generated = x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {});
  2209. return {
  2210. TestDictionary1 : values,
  2211. TestDictionary2 : x.Values,
  2212. TestDictionaryDirectAccess1 : Object.keys(x.Values).length,
  2213. TestDictionaryDirectAccess2 : Object.keys(x.Values),
  2214. TestDictionaryDirectAccess4 : Object.keys(x.Values).map(function(a){return x.Values[a];}),
  2215. TestDictionarySum1 : Object.keys(values).map(function(a){return{Key: a,Value:values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2216. TestDictionarySum2 : Object.keys(x.Values).map(function(a){return{Key: a,Value:x.Values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2217. TestDictionarySum3 : Object.keys(x.Values).map(function(a){return x.Values[a];}).reduce(function(a, b) { return a + b; }, 0),
  2218. TestDictionaryAverage1 : Object.keys(values).map(function(a){return{Key: a,Value:values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(values).length||1),
  2219. TestDictionaryAverage2 : Object.keys(x.Values).map(function(a){return{Key: a,Value:x.Values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Values).length||1),
  2220. TestDictionaryAverage3 : Object.keys(x.Values).map(function(a){return x.Values[a];}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Values).map(function(a){return x.Values[a];}).length||1),
  2221. TestDictionaryFunc1 : Object.keys(x.Values).length,
  2222. TestDictionaryFunc2 : Object.map(x.Values, function(v, k){ return v;}),
  2223. TestGeneratedDictionary1 : generated,
  2224. TestGeneratedDictionary2 : x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {}),
  2225. TestGeneratedDictionary3 : Object.keys(generated).length,
  2226. TestGeneratedDictionarySum1 : Object.keys(generated).map(function(a){return{Key: a,Value:generated[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2227. TestGeneratedDictionarySum2 : Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).map(function(a){return{Key: a,Value:x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2228. TestGeneratedDictionaryAverage1 : Object.keys(generated).map(function(a){return{Key: a,Value:generated[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(generated).length||1),
  2229. TestGeneratedDictionaryAverage2 : Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).map(function(a){return{Key: a,Value:x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).length||1),
  2230. TestGeneratedDictionaryDirectAccess1 : Object.keys(generated),
  2231. TestGeneratedDictionaryDirectAccess2 : Object.keys(generated).map(function(a){return generated[a];}),
  2232. TestGeneratedDictionaryDirectAccess3 : Object.keys(generated).length,
  2233. TestList1 : elements.reduce(function(a, b) { return a + b; }, 0),
  2234. TestList2 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0),
  2235. TestList3 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0),
  2236. TestList4 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0)/(x.Elements.length||1),
  2237. TestList5 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0)/(x.Elements.map((function(a){return a.Decimal;})).length||1)
  2238. };
  2239. };
  2240. ";
  2241. _engine.Execute(program);
  2242. var result1 = (ObjectInstance) _engine.Evaluate("output(x1)");
  2243. var result2 = (ObjectInstance) _engine.Evaluate("output(x2)");
  2244. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum1")));
  2245. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum2")));
  2246. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum3")));
  2247. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage1")));
  2248. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage2")));
  2249. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage3")));
  2250. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryFunc1")));
  2251. Assert.Equal(1, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionary3")));
  2252. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionarySum1")));
  2253. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionarySum2")));
  2254. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryAverage1")));
  2255. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryAverage2")));
  2256. Assert.Equal(1, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryDirectAccess3")));
  2257. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList1")));
  2258. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList2")));
  2259. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList3")));
  2260. Assert.Equal(3.35, TypeConverter.ToNumber(result1.Get("TestList4")));
  2261. Assert.Equal(3.35, TypeConverter.ToNumber(result1.Get("TestList5")));
  2262. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum1")));
  2263. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum2")));
  2264. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum3")));
  2265. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage1")));
  2266. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage2")));
  2267. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage3")));
  2268. }
  2269. [Fact]
  2270. public void ShouldBeAbleToSpreadArrayLiteralsAndFunctionParameters()
  2271. {
  2272. RunTest(@"
  2273. function concat(x, a, b) {
  2274. x += a;
  2275. x += b;
  2276. return x;
  2277. }
  2278. var s = [...'abc'];
  2279. var c = concat(1, ...'ab');
  2280. var arr1 = [1, 2];
  2281. var arr2 = [3, 4 ];
  2282. var r = [...arr2, ...arr1];
  2283. ");
  2284. var arrayInstance = (ArrayInstance) _engine.GetValue("r");
  2285. Assert.Equal(arrayInstance[0], 3);
  2286. Assert.Equal(arrayInstance[1], 4);
  2287. Assert.Equal(arrayInstance[2], 1);
  2288. Assert.Equal(arrayInstance[3], 2);
  2289. arrayInstance = (ArrayInstance) _engine.GetValue("s");
  2290. Assert.Equal(arrayInstance[0], 'a');
  2291. Assert.Equal(arrayInstance[1], 'b');
  2292. Assert.Equal(arrayInstance[2], 'c');
  2293. var c = _engine.GetValue("c").ToString();
  2294. Assert.Equal("1ab", c);
  2295. }
  2296. [Fact]
  2297. public void ShouldSupportDefaultsInFunctionParameters()
  2298. {
  2299. RunTest(@"
  2300. function f(x, y=12) {
  2301. // y is 12 if not passed (or passed as undefined)
  2302. return x + y;
  2303. }
  2304. ");
  2305. var function = _engine.GetValue("f");
  2306. var result = function.Invoke(3).ToString();
  2307. Assert.Equal("15", result);
  2308. result = function.Invoke(3, JsValue.Undefined).ToString();
  2309. Assert.Equal("15", result);
  2310. }
  2311. [Fact]
  2312. public void ShouldReportErrorForInvalidJson()
  2313. {
  2314. var engine = new Engine();
  2315. var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("JSON.parse('[01]')"));
  2316. Assert.Equal("Unexpected token '1'", ex.Message);
  2317. var voidCompletion = engine.Evaluate("try { JSON.parse('01') } catch (e) {}");
  2318. Assert.Equal(JsValue.Undefined, voidCompletion);
  2319. }
  2320. [Fact]
  2321. public void ShouldParseAnonymousToTypeObject()
  2322. {
  2323. var obj = new Wrapper();
  2324. var engine = new Engine()
  2325. .SetValue("x", obj);
  2326. var js = @"
  2327. x.test = {
  2328. name: 'Testificate',
  2329. init (a, b) {
  2330. return a + b
  2331. }
  2332. }";
  2333. engine.Execute(js);
  2334. Assert.Equal("Testificate", obj.Test.Name);
  2335. Assert.Equal(5, obj.Test.Init(2, 3));
  2336. }
  2337. [Fact]
  2338. public void ShouldOverrideDefaultTypeConverter()
  2339. {
  2340. var engine = new Engine(options => options
  2341. .SetTypeConverter(e => new TestTypeConverter())
  2342. );
  2343. Assert.IsType<TestTypeConverter>(engine.ClrTypeConverter);
  2344. engine.SetValue("x", new Testificate());
  2345. Assert.Throws<JavaScriptException>(() => engine.Evaluate("c.Name"));
  2346. }
  2347. [Fact]
  2348. public void ShouldAllowDollarPrefixForProperties()
  2349. {
  2350. _engine.SetValue("str", "Hello");
  2351. _engine.Evaluate("equal(undefined, str.$ref);");
  2352. _engine.Evaluate("equal(undefined, str.ref);");
  2353. _engine.Evaluate("equal(undefined, str.$foo);");
  2354. _engine.Evaluate("equal(undefined, str.foo);");
  2355. _engine.Evaluate("equal(undefined, str['$foo']);");
  2356. _engine.Evaluate("equal(undefined, str['foo']);");
  2357. _engine.Evaluate("equal(false, str.hasOwnProperty('$foo'));");
  2358. _engine.Evaluate("equal(false, str.hasOwnProperty('foo'));");
  2359. }
  2360. [Fact]
  2361. public void ShouldProvideEngineForOptionsAsOverload()
  2362. {
  2363. new Engine((e, options) =>
  2364. {
  2365. Assert.IsType<Engine>(e);
  2366. options
  2367. .AddObjectConverter(new TestObjectConverter())
  2368. .AddObjectConverter<TestObjectConverter>();
  2369. })
  2370. .SetValue("a", 1);
  2371. }
  2372. [Fact]
  2373. public void ShouldReuseOptions()
  2374. {
  2375. var options = new Options().Configure(e => e.SetValue("x", 1));
  2376. var engine1 = new Engine(options);
  2377. var engine2 = new Engine(options);
  2378. Assert.Equal(1, Convert.ToInt32(engine1.GetValue("x").ToObject()));
  2379. Assert.Equal(1, Convert.ToInt32(engine2.GetValue("x").ToObject()));
  2380. }
  2381. [Fact]
  2382. public void RecursiveCallStack()
  2383. {
  2384. var engine = new Engine();
  2385. Func<string, object> evaluateCode = code => engine.Evaluate(code);
  2386. var evaluateCodeValue = JsValue.FromObject(engine, evaluateCode);
  2387. engine.SetValue("evaluateCode", evaluateCodeValue);
  2388. var result = (int) engine.Evaluate(@"evaluateCode('678 + 711')").AsNumber();
  2389. Assert.Equal(1389, result);
  2390. }
  2391. private class Wrapper
  2392. {
  2393. public Testificate Test { get; set; }
  2394. }
  2395. private class Testificate
  2396. {
  2397. public string Name { get; set; }
  2398. public Func<int, int, int> Init { get; set; }
  2399. }
  2400. private class TestObjectConverter : Jint.Runtime.Interop.IObjectConverter
  2401. {
  2402. public bool TryConvert(Engine engine, object value, out JsValue result)
  2403. {
  2404. throw new NotImplementedException();
  2405. }
  2406. }
  2407. private class TestTypeConverter : Jint.Runtime.Interop.ITypeConverter
  2408. {
  2409. public object Convert(object value, Type type, IFormatProvider formatProvider)
  2410. {
  2411. throw new NotImplementedException();
  2412. }
  2413. public bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
  2414. {
  2415. throw new NotImplementedException();
  2416. }
  2417. }
  2418. }
  2419. }