Skip to content

Modernisation with MsieJavaScriptEngine support #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JSTest.Integration.Xunit</RootNamespace>
<AssemblyName>JSTest.Integration.xUnit</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
Expand Down
66 changes: 7 additions & 59 deletions src/JSTest.Test/CScriptCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,87 +24,35 @@ public class WhenUsingCScriptCommand
[Theory, InlineData(0), InlineData(100), InlineData(Int16.MaxValue)]
public void TimeoutAcceptedIfSecondsBetweenZeroAnd32768(Int32 timeout)
{
Assert.DoesNotThrow(() => new CScriptCommand(TimeSpan.FromSeconds(timeout)));
Assert.DoesNotThrow(() => new CScriptEngine(TimeSpan.FromSeconds(timeout)));
}

[Theory, InlineData(-1), InlineData(Int16.MaxValue + 1)]
public void TimeoutRejectedIfSecondsNotBetweenZeroAnd32767(Int32 timeout)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new CScriptCommand(TimeSpan.FromSeconds(timeout)));
Assert.Throws<ArgumentOutOfRangeException>(() => new CScriptEngine(TimeSpan.FromSeconds(timeout)));
}

[Fact]
public void RunReturnsStdOutText()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>WScript.Echo('Sample Text');</script></job>");

Assert.Equal("Sample Text", new CScriptCommand().Run(tempFile.FileName));
}
Assert.Equal("Sample Text", new CScriptEngine().Execute(@"<script language='JavaScript'>WScript.Echo('Sample Text');</script>"));
}

[Fact]
public void RunThrowsInvalidProgramExceptionOnBadInputFile()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>function ) { return 'Missing Opening ('; }</script></job>");

var ex = Assert.Throws<ScriptException>(() => new CScriptCommand().Run(tempFile.FileName));
var ex = Assert.Throws<ScriptException>(() => new CScriptEngine().Execute(@"<script language='JavaScript'>function ) { return 'Missing Opening ('; }</script>"));

Assert.Contains("Microsoft JScript compilation error: Expected '('", ex.Message);
}
Assert.Contains("Microsoft JScript compilation error: Expected '('", ex.Message);
}

[Fact]
public void RunTimesOutOnLongRunningScript()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>while(true) { }</script></job>");

var ex = Assert.Throws<ScriptException>(() => new CScriptCommand(TimeSpan.FromMilliseconds(100)).Run(tempFile.FileName));

Assert.Contains("Script execution time was exceeded on script", ex.Message);
}
}

[Fact]
public void DebugReturnsStdOutText()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>WScript.Echo('Sample Text');</script></job>");

Assert.Equal("Sample Text", new CScriptCommand().Debug(tempFile.FileName));
}
}

[Fact]
public void DebugThrowsInvalidProgramExceptionOnBadInputFile()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>function ) { return 'Missing Opening ('; }</script></job>");

var ex = Assert.Throws<ScriptException>(() => new CScriptCommand().Debug(tempFile.FileName));

Assert.Contains("Microsoft JScript compilation error: Expected '('", ex.Message);
}
}

[Fact]
public void DebugTimesOutOnLongRunningScript()
{
using (var tempFile = new TempFile("wsf"))
{
File.WriteAllText(tempFile.FileName, @"<job id='Test'><script language='JavaScript'>while(true) { }</script></job>");

var ex = Assert.Throws<ScriptException>(() => new CScriptCommand(TimeSpan.FromMilliseconds(100)).Debug(tempFile.FileName));
var ex = Assert.Throws<ScriptException>(() => new CScriptEngine(TimeSpan.FromMilliseconds(100)).Execute(@"<script language='JavaScript'>while(true) { }</script>"));

Assert.Contains("Script execution time was exceeded on script", ex.Message);
}
Assert.Contains("Script execution time was exceeded on script", ex.Message);
}
}
}
3 changes: 3 additions & 0 deletions src/JSTest.Test/JSTest.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
Expand Down Expand Up @@ -69,7 +70,9 @@
<Compile Include="CScriptCommandTests.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="MsieEngine\TestScriptTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="MsieEngine\MsieJavaScriptCommandTests.cs" />
<Compile Include="ScriptElements\EmbeddedScriptBlockTests.cs" />
<Compile Include="ScriptElements\ScriptBlockTests.cs">
<SubType>Code</SubType>
Expand Down
31 changes: 31 additions & 0 deletions src/JSTest.Test/MsieEngine/MsieJavaScriptCommandTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace JSTest.Tests.MsieEngine
{
public class MsieJavaScriptCommandTests
{
[Fact]
public void ShouldUseEcmaScript5PolyfillByDefault()
{
var script = new TestScript(new MsieJavaScriptEngine());

var result = script.RunTest(@"
return [{ a: 1 }, { a: 2 }, { a: 3 }].filter(function (l) { return l.a >= 2; }).length;
");
Assert.Equal("2", result);
}

[Fact]
public void RunThrowsInvalidProgramExceptionOnBadInputFile()
{
var ex = Assert.Throws<ScriptException>(() => new MsieJavaScriptEngine().Execute(@"function ) { return 'Missing Opening ('; }"));

Assert.Contains("Expected '('", ex.Message);
}
}
}
90 changes: 90 additions & 0 deletions src/JSTest.Test/MsieEngine/TestScriptTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.IO;
using JSTest.ScriptElements;
using Xunit;

/* Copyright (c) 2011 CBaxter
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/

namespace JSTest.Test.MsieEngine
{
public class WhenUsingTestScript
{
[Fact]
public void AlwaysAppendBlockToExistingScript()
{
var block1 = new ScriptBlock("var x = 0;");
var block2 = new ScriptBlock("var y = 1;");
var block3 = new ScriptBlock("var z = 2;");
var script = new TestScript(new MsieJavaScriptEngine());

script.AppendBlock(block1);
script.AppendBlock(block2);
script.AppendBlock(block3);

Assert.Equal(block1.ToInlineScriptFragment() + Environment.NewLine + block2.ToInlineScriptFragment() + Environment.NewLine + block3.ToInlineScriptFragment() + Environment.NewLine, script.ToString());
}

[Fact]
public void AlwaysAppendIncludeToExistingScript()
{
using (var tempFile1 = new TempFile())
using (var tempFile2 = new TempFile())
using (var tempFile3 = new TempFile())
{
File.WriteAllText(tempFile1.FileName, "var x = 1;");
File.WriteAllText(tempFile2.FileName, "var y = 2;");
File.WriteAllText(tempFile3.FileName, "var z = 3;");
var script = new TestScript(new MsieJavaScriptEngine());

script.AppendFile(tempFile1.FileName);
script.AppendFile(tempFile2.FileName);
script.AppendFile(tempFile3.FileName);

Assert.Equal(
@"var x = 1;
var y = 2;
var z = 3;
",
script.ToString());
}
}

[Fact]
public void RunTestReturnsNullWhenNoReturnSpecified()
{
var script = new TestScript(new MsieJavaScriptEngine());

Assert.Equal("null", script.RunTest("var result = 'Success!';"));
}

[Fact]
public void RunTestReturnsValueWhenExplicitReturnSpecified()
{
var script = new TestScript(new MsieJavaScriptEngine());

Assert.Equal("\"Success!\"", script.RunTest("return 'Success!';"));
}

[Fact]
public void RunTestThrowsScriptExceptionBackToCaller()
{
var script = new TestScript(new MsieJavaScriptEngine());

var ex = Assert.Throws<ScriptException>(() => script.RunTest("throw { message: 'My Script Exception' };"));

Assert.Equal(ex.Message, "{\"message\":\"My Script Exception\"}");
}
}
}
10 changes: 10 additions & 0 deletions src/JSTest.Test/ScriptElements/TestCaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ public void CanImplicitlyConvertToString()
Assert.Equal(testCase.ToScriptFragment(), script);
}

[Fact]
public void CanImplicitlyConvertToInlineString()
{
var testCase = new TestCase(@"..\..\Scripts\TestFile1.js", "function1");

String script = testCase;

Assert.Equal(testCase.ToInlineScriptFragment(), script);
}

[Fact]
public void ScriptFragmentIsFunctionInvocationWithReturn()
{
Expand Down
2 changes: 1 addition & 1 deletion src/JSTest.Test/ScriptResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 5 additions & 7 deletions src/JSTest.Test/TestScriptTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,22 +118,20 @@ public void RunTestDoesNotIncludeDefaultDebuggerStatementIfSuppressed()
Assert.False(cscriptCommand.ScriptContainedDebuggerStatement);
}

private class FakeCScriptCommand : ICScriptCommand
private class FakeCScriptCommand : IScriptEngine
{
public Boolean ScriptContainedDebuggerStatement { get; set; }

public String Run(String fileName)
public String Execute(String script)
{
ScriptContainedDebuggerStatement = File.ReadAllText(fileName).Contains("debugger;");
ScriptContainedDebuggerStatement = script.Contains("debugger;");

return null;
}

public String Debug(String fileName)
public string Convert(ScriptElement element)
{
ScriptContainedDebuggerStatement = File.ReadAllText(fileName).Contains("debugger;");

return null;
return element.ToScriptFragment();
}
}
}
Expand Down
54 changes: 32 additions & 22 deletions src/JSTest/CScriptCommand.cs → src/JSTest/CScriptEngine.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using JSTest.ScriptElements;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;

/* Copyright (c) 2011 CBaxter
Expand All @@ -18,36 +20,39 @@

namespace JSTest
{
internal interface ICScriptCommand
{
String Run(String fileName);
String Debug(String fileName);
}

internal class CScriptCommand : ICScriptCommand
public class CScriptEngine : IScriptEngine
{
private readonly Int16 _timeoutInSeconds;

public CScriptCommand()
: this(TimeSpan.FromSeconds(10))
{ }

public CScriptCommand(TimeSpan timeout)
public CScriptEngine(TimeSpan? timeout = null)
{
if (timeout.TotalSeconds < 0 || timeout.TotalSeconds > Int16.MaxValue)
throw new ArgumentOutOfRangeException("timeout", timeout.TotalSeconds, String.Format("Timeout must be between {0} and {1} seconds inclusive.", 0, Int16.MaxValue));
if (timeout == null) timeout = TimeSpan.FromSeconds(10);

_timeoutInSeconds = Convert.ToInt16(Math.Ceiling(timeout.TotalSeconds));
}
if (timeout.Value.TotalSeconds < 0 || timeout.Value.TotalSeconds > Int16.MaxValue)
throw new ArgumentOutOfRangeException("timeout", timeout.Value.TotalSeconds, String.Format("Timeout must be between {0} and {1} seconds inclusive.", 0, Int16.MaxValue));

public String Run(String fileName)
{
return Run(fileName, _timeoutInSeconds, false);
_timeoutInSeconds = System.Convert.ToInt16(Math.Ceiling(timeout.Value.TotalSeconds));
}

public String Debug(String fileName)
public String Execute(String script)
{
return Run(fileName, _timeoutInSeconds, Debugger.IsAttached);
String scriptFile = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()), ".wsf");

try
{
using (var writer = new StreamWriter(scriptFile))
{
writer.WriteLine("<job id='UnitTest'>");
writer.Write(script);
writer.WriteLine("</job>");
}

return Run(scriptFile, _timeoutInSeconds, Debugger.IsAttached);
}
finally
{
File.Delete(scriptFile);
}
}

private static String Run(String fileName, Int16 timeoutInSeconds, Boolean enableDebugging)
Expand Down Expand Up @@ -91,5 +96,10 @@ private static String Run(String fileName, Int16 timeoutInSeconds, Boolean enabl
throw new ScriptException(error);
}
}

public string Convert(ScriptElement element)
{
return element.ToScriptFragment();
}
}
}
11 changes: 11 additions & 0 deletions src/JSTest/IScriptEngine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using JSTest.ScriptElements;
using System;

namespace JSTest
{
public interface IScriptEngine
{
String Execute(String script);
String Convert(ScriptElement element);
}
}
Loading