using System;
using System.IO;
using Xunit;
namespace WinSW.Tests.Util
{
///
/// Helper for WinSW CLI testing
///
public static class CLITestHelper
{
public const string Id = "WinSW.Tests";
public const string Name = "WinSW Test Service";
private static readonly string SeedXml =
$@"
{Id}
{Name}
The service.
node.exe
My Arguments
C:\winsw\workdir
C:\winsw\logs
";
public static readonly ServiceDescriptor DefaultServiceDescriptor = ServiceDescriptor.FromXml(SeedXml);
///
/// Runs a simle test, which returns the output CLI
///
/// CLI arguments to be passed
/// Optional Service descriptor (will be used for initializationpurposes)
/// STDOUT if there's no exceptions
/// Command failure
public static string CLITest(string[] arguments, ServiceDescriptor descriptor = null)
{
TextWriter tmpOut = Console.Out;
TextWriter tmpErr = Console.Error;
using StringWriter swOut = new StringWriter();
using StringWriter swErr = new StringWriter();
Console.SetOut(swOut);
Console.SetError(swErr);
try
{
Program.Run(arguments, descriptor ?? DefaultServiceDescriptor);
}
finally
{
Console.SetOut(tmpOut);
Console.SetError(tmpErr);
}
Assert.Equal(0, swErr.GetStringBuilder().Length);
Console.Write(swOut.ToString());
return swOut.ToString();
}
///
/// Runs a simle test, which returns the output CLI
///
/// CLI arguments to be passed
/// Optional Service descriptor (will be used for initializationpurposes)
/// Test results
public static CLITestResult CLIErrorTest(string[] arguments, ServiceDescriptor descriptor = null)
{
Exception testEx = null;
TextWriter tmpOut = Console.Out;
TextWriter tmpErr = Console.Error;
using StringWriter swOut = new StringWriter();
using StringWriter swErr = new StringWriter();
Console.SetOut(swOut);
Console.SetError(swErr);
try
{
Program.Run(arguments, descriptor ?? DefaultServiceDescriptor);
}
catch (Exception ex)
{
testEx = ex;
}
finally
{
Console.SetOut(tmpOut);
Console.SetError(tmpErr);
}
Console.WriteLine("\n>>> Output: ");
Console.Write(swOut.ToString());
Console.WriteLine("\n>>> Error: ");
Console.Write(swErr.ToString());
if (testEx != null)
{
Console.WriteLine("\n>>> Exception: ");
Console.WriteLine(testEx);
}
return new CLITestResult(swOut.ToString(), swErr.ToString(), testEx);
}
}
///
/// Aggregated test report
///
public class CLITestResult
{
public string Out { get; }
public string Error { get; }
public Exception Exception { get; }
public bool HasException => this.Exception != null;
public CLITestResult(string output, string error, Exception exception = null)
{
this.Out = output;
this.Error = error;
this.Exception = exception;
}
}
}