123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
- using System;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Threading;
- using Jint.Native.Number;
- using Jint.Parser;
- using Jint.Parser.Ast;
- using Jint.Runtime;
- using Xunit;
- using Xunit.Extensions;
- namespace Jint.Tests.Runtime
- {
- public class EngineTests : IDisposable
- {
- private readonly Engine _engine;
- public EngineTests()
- {
- _engine = new Engine()
- .SetValue("log", new Action<object>(Console.WriteLine))
- .SetValue("assert", new Action<bool>(Assert.True))
- ;
- }
- void IDisposable.Dispose()
- {
- }
- private void RunTest(string source)
- {
- _engine.Execute(source);
- }
- [Theory]
- [InlineData("Scratch.js")]
- public void ShouldInterpretScriptFile(string file)
- {
- const string prefix = "Jint.Tests.Runtime.Scripts.";
- var assembly = Assembly.GetExecutingAssembly();
- var scriptPath = prefix + file;
- using (var stream = assembly.GetManifestResourceStream(scriptPath))
- if (stream != null)
- using (var sr = new StreamReader(stream))
- {
- var source = sr.ReadToEnd();
- RunTest(source);
- }
- }
- [Theory]
- [InlineData(42d, "42")]
- [InlineData("Hello", "'Hello'")]
- public void ShouldInterpretLiterals(object expected, string source)
- {
- var engine = new Engine();
- var result = engine.Execute(source).GetCompletionValue().ToObject();
- Assert.Equal(expected, result);
- }
- [Fact]
- public void ShouldInterpretVariableDeclaration()
- {
- var engine = new Engine();
- var result = engine
- .Execute("var foo = 'bar'; foo;")
- .GetCompletionValue()
- .ToObject();
- Assert.Equal("bar", result);
- }
- [Theory]
- [InlineData(4d, "1 + 3")]
- [InlineData(-2d, "1 - 3")]
- [InlineData(3d, "1 * 3")]
- [InlineData(2d, "6 / 3")]
- [InlineData(9d, "15 & 9")]
- [InlineData(15d, "15 | 9")]
- [InlineData(6d, "15 ^ 9")]
- [InlineData(36d, "9 << 2")]
- [InlineData(2d, "9 >> 2")]
- [InlineData(4d, "19 >>> 2")]
- public void ShouldInterpretBinaryExpression(object expected, string source)
- {
- var engine = new Engine();
- var result = engine.Execute(source).GetCompletionValue().ToObject();
- Assert.Equal(expected, result);
- }
- [Fact]
- public void ShouldEvaluateHasOwnProperty()
- {
- RunTest(@"
- var x = {};
- x.Bar = 42;
- assert(x.hasOwnProperty('Bar'));
- ");
- }
- [Fact]
- public void FunctionConstructorsShouldCreateNewObjects()
- {
- RunTest(@"
- var Vehicle = function () {};
- var vehicle = new Vehicle();
- assert(vehicle != undefined);
- ");
- }
- [Fact]
- public void NewObjectsInheritFunctionConstructorProperties()
- {
- RunTest(@"
- var Vehicle = function () {};
- var vehicle = new Vehicle();
- Vehicle.prototype.wheelCount = 4;
- assert(vehicle.wheelCount == 4);
- assert((new Vehicle()).wheelCount == 4);
- ");
- }
- [Fact]
- public void PrototypeFunctionIsInherited()
- {
- RunTest(@"
- function Body(mass){
- this.mass = mass;
- }
- Body.prototype.offsetMass = function(dm) {
- this.mass += dm;
- return this;
- }
- var b = new Body(36);
- b.offsetMass(6);
- assert(b.mass == 42);
- ");
- }
- [Fact]
- public void FunctionConstructorCall()
- {
- RunTest(@"
- function Body(mass){
- this.mass = mass;
- }
-
- var john = new Body(36);
- assert(john.mass == 36);
- ");
- }
- [Fact]
- public void NewObjectsShouldUsePrivateProperties()
- {
- RunTest(@"
- var Vehicle = function (color) {
- this.color = color;
- };
- var vehicle = new Vehicle('tan');
- assert(vehicle.color == 'tan');
- ");
- }
- [Fact]
- public void FunctionConstructorsShouldDefinePrototypeChain()
- {
- RunTest(@"
- function Vehicle() {};
- var vehicle = new Vehicle();
- assert(vehicle.hasOwnProperty('constructor') == false);
- ");
- }
- [Fact]
- public void NewObjectsConstructorIsObject()
- {
- RunTest(@"
- var o = new Object();
- assert(o.constructor == Object);
- ");
- }
- [Fact]
- public void NewObjectsIntanceOfConstructorObject()
- {
- RunTest(@"
- var o = new Object();
- assert(o instanceof Object);
- ");
- }
- [Fact]
- public void NewObjectsConstructorShouldBeConstructorObject()
- {
- RunTest(@"
- var Vehicle = function () {};
- var vehicle = new Vehicle();
- assert(vehicle.constructor == Vehicle);
- ");
- }
- [Fact]
- public void NewObjectsIntanceOfConstructorFunction()
- {
- RunTest(@"
- var Vehicle = function () {};
- var vehicle = new Vehicle();
- assert(vehicle instanceof Vehicle);
- ");
- }
- [Fact]
- public void ShouldEvaluateForLoops()
- {
- RunTest(@"
- var foo = 0;
- for (var i = 0; i < 5; i++) {
- foo += i;
- }
- assert(foo == 10);
- ");
- }
- [Fact]
- public void ShouldEvaluateRecursiveFunctions()
- {
- RunTest(@"
- function fib(n) {
- if (n < 2) {
- return n;
- }
- return fib(n - 1) + fib(n - 2);
- }
- var result = fib(6);
- assert(result == 8);
- ");
- }
- [Fact]
- public void ShouldAccessObjectProperties()
- {
- RunTest(@"
- var o = {};
- o.Foo = 'bar';
- o.Baz = 42;
- o.Blah = o.Foo + o.Baz;
- assert(o.Blah == 'bar42');
- ");
- }
- [Fact]
- public void ShouldConstructArray()
- {
- RunTest(@"
- var o = [];
- assert(o.length == 0);
- ");
- }
- [Fact]
- public void ArrayPushShouldIncrementLength()
- {
- RunTest(@"
- var o = [];
- o.push(1);
- assert(o.length == 1);
- ");
- }
- [Fact]
- public void ArrayFunctionInitializesLength()
- {
- RunTest(@"
- assert(Array(3).length == 3);
- assert(Array('3').length == 1);
- ");
- }
- [Fact]
- public void ArrayIndexerIsAssigned()
- {
- RunTest(@"
- var n = 8;
- var o = Array(n);
- for (var i = 0; i < n; i++) o[i] = i;
- assert(o[0] == 0);
- assert(o[7] == 7);
- ");
- }
- [Fact]
- public void ArrayPopShouldDecrementLength()
- {
- RunTest(@"
- var o = [42, 'foo'];
- var pop = o.pop();
- assert(o.length == 1);
- assert(pop == 'foo');
- ");
- }
- [Fact]
- public void ArrayConstructor()
- {
- RunTest(@"
- var o = [];
- assert(o.constructor == Array);
- ");
- }
- [Fact]
- public void DateConstructor()
- {
- RunTest(@"
- var o = new Date();
- assert(o.constructor == Date);
- assert(o.hasOwnProperty('constructor') == false);
- ");
- }
- [Fact]
- public void ShouldConvertDateToNumber()
- {
- RunTest(@"
- assert(Number(new Date(0)) === 0);
- ");
- }
- [Fact]
- public void DatePrimitiveValueShouldBeNaN()
- {
- RunTest(@"
- assert(isNaN(Date.prototype.valueOf()));
- ");
- }
- [Fact]
- public void MathObjectIsDefined()
- {
- RunTest(@"
- var o = Math.abs(-1)
- assert(o == 1);
- ");
- }
- [Fact]
- public void VoidShouldReturnUndefined()
- {
- RunTest(@"
- assert(void 0 === undefined);
- var x = '1';
- assert(void x === undefined);
- x = 'x';
- assert (isNaN(void x) === true);
- x = new String('-1');
- assert (void x === undefined);
- ");
- }
- [Fact]
- public void TypeofObjectShouldReturnString()
- {
- RunTest(@"
- assert(typeof x === 'undefined');
- assert(typeof 0 === 'number');
- var x = 0;
- assert (typeof x === 'number');
- var x = new Object();
- assert (typeof x === 'object');
- ");
- }
- [Fact]
- public void MathAbsReturnsAbsolute()
- {
- RunTest(@"
- assert(1 == Math.abs(-1));
- ");
- }
- [Fact]
- public void NaNIsNan()
- {
- RunTest(@"
- var x = NaN;
- assert(isNaN(NaN));
- assert(isNaN(Math.abs(x)));
- ");
- }
- [Fact]
- public void ToNumberHandlesStringObject()
- {
- RunTest(@"
- x = new String('1');
- x *= undefined;
- assert(isNaN(x));
- ");
- }
- [Fact]
- public void FunctionScopesAreChained()
- {
- RunTest(@"
- var x = 0;
- function f1(){
- function f2(){
- return x;
- };
- return f2();
-
- var x = 1;
- }
- assert(f1() === undefined);
- ");
- }
- [Fact]
- public void EvalFunctionParseAndExecuteCode()
- {
- RunTest(@"
- var x = 0;
- eval('assert(x == 0)');
- ");
- }
- [Fact]
- public void ForInStatement()
- {
- RunTest(@"
- var x, y, str = '';
- for(var z in this) {
- str += z;
- }
-
- assert(str == 'xystrz');
- ");
- }
- [Fact]
- public void WithStatement()
- {
- RunTest(@"
- with (Math) {
- assert(cos(0) == 1);
- }
- ");
- }
- [Fact]
- public void ObjectExpression()
- {
- RunTest(@"
- var o = { x: 1 };
- assert(o.x == 1);
- ");
- }
- [Fact]
- public void StringFunctionCreatesString()
- {
- RunTest(@"
- assert(String(NaN) === 'NaN');
- ");
- }
- [Fact]
- public void ScopeChainInWithStatement()
- {
- RunTest(@"
- var x = 0;
- var myObj = {x : 'obj'};
- function f1(){
- var x = 1;
- function f2(){
- with(myObj){
- return x;
- }
- };
- return f2();
- }
- assert(f1() === 'obj');
- ");
- }
- [Fact]
- public void TryCatchBlockStatement()
- {
- RunTest(@"
- var x, y, z;
- try {
- x = 1;
- throw new TypeError();
- x = 2;
- }
- catch(e) {
- assert(x == 1);
- assert(e instanceof TypeError);
- y = 1;
- }
- finally {
- assert(x == 1);
- z = 1;
- }
-
- assert(x == 1);
- assert(y == 1);
- assert(z == 1);
- ");
- }
- [Fact]
- public void FunctionsCanBeAssigned()
- {
- RunTest(@"
- var sin = Math.sin;
- assert(sin(0) == 0);
- ");
- }
- [Fact]
- public void FunctionArgumentsIsDefined()
- {
- RunTest(@"
- function f() {
- assert(arguments.length > 0);
- }
- f(42);
- ");
- }
- [Fact]
- public void PrimitiveValueFunctions()
- {
- RunTest(@"
- var s = (1).toString();
- assert(s == '1');
- ");
- }
- [Theory]
- [InlineData(true, "'ab' == 'a' + 'b'")]
- public void OperatorsPrecedence(object expected, string source)
- {
- var engine = new Engine();
- var result = engine.Execute(source).GetCompletionValue().ToObject();
- Assert.Equal(expected, result);
- }
- [Fact]
- public void FunctionPrototypeShouldHaveApplyMethod()
- {
- RunTest(@"
- var numbers = [5, 6, 2, 3, 7];
- var max = Math.max.apply(null, numbers);
- assert(max == 7);
- ");
- }
- [Theory]
- [InlineData(double.NaN, "parseInt(NaN)")]
- [InlineData(double.NaN, "parseInt(null)")]
- [InlineData(double.NaN, "parseInt(undefined)")]
- [InlineData(double.NaN, "parseInt(new Boolean(true))")]
- [InlineData(double.NaN, "parseInt(Infinity)")]
- [InlineData(-1d, "parseInt(-1)")]
- [InlineData(-1d, "parseInt('-1')")]
- public void ShouldEvaluateParseInt(object expected, string source)
- {
- var engine = new Engine();
- var result = engine.Execute(source).GetCompletionValue().ToObject();
- Assert.Equal(expected, result);
- }
- [Fact]
- public void ShouldNotExecuteDebuggerStatement()
- {
- new Engine().Execute("debugger");
- }
-
- [Fact]
- public void ShouldThrowStatementCountOverflow()
- {
- Assert.Throws<StatementsCountOverflowException>(
- () => new Engine(cfg => cfg.MaxStatements(100)).Execute("while(true);")
- );
- }
- [Fact]
- public void ShouldDiscardRecursion()
- {
- var script = @"var factorial = function(n) {
- if (n>1) {
- return n * factorial(n - 1);
- }
- };
- var result = factorial(500);
- ";
- Assert.Throws<RecursionDiscardedException>(
- () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
- );
- }
- [Fact]
- public void ShouldDiscardHiddenRecursion()
- {
- var script = @"var renamedFunc;
- var exec = function(callback) {
- renamedFunc = callback;
- callback();
- };
- var result = exec(function() {
- renamedFunc();
- });
- ";
- Assert.Throws<RecursionDiscardedException>(
- () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
- );
- }
- [Fact]
- public void ShouldRecognizeAndDiscardChainedRecursion()
- {
- var script = @" var funcRoot, funcA, funcB, funcC, funcD;
- var funcRoot = function() {
- funcA();
- };
-
- var funcA = function() {
- funcB();
- };
- var funcB = function() {
- funcC();
- };
- var funcC = function() {
- funcD();
- };
- var funcD = function() {
- funcRoot();
- };
- funcRoot();
- ";
- Assert.Throws<RecursionDiscardedException>(
- () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
- );
- }
- [Fact]
- public void ShouldProvideCallChainWhenDiscardRecursion()
- {
- var script = @" var funcRoot, funcA, funcB, funcC, funcD;
- var funcRoot = function() {
- funcA();
- };
-
- var funcA = function() {
- funcB();
- };
- var funcB = function() {
- funcC();
- };
- var funcC = function() {
- funcD();
- };
- var funcD = function() {
- funcRoot();
- };
- funcRoot();
- ";
- RecursionDiscardedException exception = null;
- try
- {
- new Engine(cfg => cfg.DiscardRecursion()).Execute(script);
- }
- catch (RecursionDiscardedException ex)
- {
- exception = ex;
- }
- Assert.NotNull(exception);
- Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
- Assert.Equal("funcRoot", exception.CallExpressionReference);
- }
- [Fact]
- public void ShouldConvertDoubleToStringWithoutLosingPrecision()
- {
- RunTest(@"
- assert(String(14.915832707045631) === '14.915832707045631');
- assert(String(-14.915832707045631) === '-14.915832707045631');
- assert(String(0.5) === '0.5');
- assert(String(0.00000001) === '1e-8');
- assert(String(0.000001) === '0.000001');
- assert(String(-1.0) === '-1');
- assert(String(30.0) === '30');
- assert(String(0.2388906159889881) === '0.2388906159889881');
- ");
- }
- [Fact]
- public void ShouldWriteNumbersUsingBases()
- {
- RunTest(@"
- assert(15.0.toString() === '15');
- assert(15.0.toString(2) === '1111');
- assert(15.0.toString(8) === '17');
- assert(15.0.toString(16) === 'f');
- assert(15.0.toString(17) === 'f');
- assert(15.0.toString(36) === 'f');
- assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
- ");
- }
- [Fact]
- public void ShouldNotAlterSlashesInRegex()
- {
- RunTest(@"
- assert(new RegExp('/').toString() === '///');
- ");
- }
- [Fact]
- public void ShouldHandleEscapedSlashesInRegex()
- {
- RunTest(@"
- var regex = /[a-z]\/[a-z]/;
- assert(regex.test('a/b') === true);
- assert(regex.test('a\\/b') === false);
- ");
- }
- [Fact]
- public void ShouldComputeFractionInBase()
- {
- Assert.Equal("011", NumberPrototype.ToFractionBase(0.375, 2));
- Assert.Equal("14141414141414141414141414141414141414141414141414", NumberPrototype.ToFractionBase(0.375, 5));
- }
- [Fact]
- public void ShouldInvokeAFunctionValue()
- {
- RunTest(@"
- function add(x, y) { return x + y; }
- ");
- var add = _engine.GetValue("add");
- Assert.Equal(3, add.Invoke(1, 2));
- }
- [Fact]
- public void ShouldNotInvokeNonFunctionValue()
- {
- RunTest(@"
- var x= 10;
- ");
- var x = _engine.GetValue("x");
- Assert.Throws<ArgumentException>(() => x.Invoke(1, 2));
- }
- [Theory]
- [InlineData("0", 0, 16)]
- [InlineData("1", 1, 16)]
- [InlineData("100", 100, 10)]
- [InlineData("1100100", 100, 2)]
- [InlineData("2s", 100, 36)]
- [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
- public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
- {
- var result = NumberPrototype.ToBase(number, radix);
- Assert.Equal(expected, result);
- }
- [Fact]
- public void ShouldBeCultureInvariant()
- {
- // decimals in french are separated by commas
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
- var engine = new Engine();
-
- var result = engine.Execute("1.2 + 2.1").GetCompletionValue().AsNumber();
- Assert.Equal(3.3d, result);
- result = engine.Execute("JSON.parse('{\"x\" : 3.3}').x").GetCompletionValue().AsNumber();
- Assert.Equal(3.3d, result);
- }
- [Fact]
- public void ShouldGetTheLastSyntaxNode()
- {
- var engine = new Engine();
- engine.Execute("1.2");
- var result = engine.GetLastSyntaxNode();
- Assert.Equal(SyntaxNodes.Literal, result.Type);
- }
- [Fact]
- public void ShouldGetParseErrorLocation()
- {
- var engine = new Engine();
- try
- {
- engine.Execute("1.2+ new", new ParserOptions { Source = "jQuery.js" });
- }
- catch (ParserException e)
- {
- Assert.Equal(1, e.LineNumber);
- Assert.Equal(9, e.Column);
- Assert.Equal("jQuery.js", e.Source);
- }
- }
- }
- }
|