Skip to content

Commit

Permalink
VS2017 - NetCore2 (UnitTest redirect console to StringWriter)
Browse files Browse the repository at this point in the history
  • Loading branch information
snakefoot committed Sep 12, 2017
1 parent 4d5cf2d commit 3872685
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 74 deletions.
40 changes: 13 additions & 27 deletions tests/NLog.UnitTests/Common/InternalLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,22 +229,20 @@ public void WriteToConsoleOutTests()
// Expected result is the same for both types of method invocation.
const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n";

InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
InternalLogger.LogToConsole = true;

TextWriter oldConsoleOutWriter = Console.Out;

try
using (var loggerScope = new InternalLoggerScope(true))
{
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
InternalLogger.LogToConsole = true;

{
StringWriter consoleOutWriter1 = new StringWriter()
{
NewLine = "\n"
};

// Redirect the console output to a StringWriter.
Console.SetOut(consoleOutWriter1);
loggerScope.SetConsoleOutput(consoleOutWriter1);

// Named (based on LogLevel) public methods.
InternalLogger.Warn("WWW");
Expand All @@ -264,7 +262,7 @@ public void WriteToConsoleOutTests()
{
NewLine = "\n"
};
Console.SetOut(consoleOutWriter2);
loggerScope.SetConsoleOutput(consoleOutWriter2);

// Invoke Log(LogLevel, string) for every log level.
InternalLogger.Log(LogLevel.Warn, "WWW");
Expand All @@ -285,7 +283,7 @@ public void WriteToConsoleOutTests()
};

// Redirect the console output to a StringWriter.
Console.SetOut(consoleOutWriter1);
loggerScope.SetConsoleOutput(consoleOutWriter1);

// Named (based on LogLevel) public methods.
InternalLogger.Warn(() => "WWW");
Expand All @@ -298,19 +296,12 @@ public void WriteToConsoleOutTests()
TestWriter(expected, consoleOutWriter1);
}
}
finally
{
Console.SetOut(oldConsoleOutWriter);
InternalLogger.Reset();
}
}

[Fact]
public void WriteToConsoleErrorTests()
{
TextWriter oldConsoleErrorWriter = Console.Error;

try
using (var loggerScope = new InternalLoggerScope(true))
{
// Expected result is the same for both types of method invocation.
const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n";
Expand All @@ -326,7 +317,7 @@ public void WriteToConsoleErrorTests()
};

// Redirect the console output to a StringWriter.
Console.SetError(consoleWriter1);
loggerScope.SetConsoleError(consoleWriter1);

// Named (based on LogLevel) public methods.
InternalLogger.Warn("WWW");
Expand All @@ -336,7 +327,7 @@ public void WriteToConsoleErrorTests()
InternalLogger.Debug("DDD");
InternalLogger.Info("III");

TestWriter(expected, consoleWriter1);
TestWriter(expected, loggerScope.ConsoleErrorWriter);
}

{
Expand All @@ -347,7 +338,7 @@ public void WriteToConsoleErrorTests()
{
NewLine = "\n"
};
Console.SetError(consoleWriter2);
loggerScope.SetConsoleError(consoleWriter2);

// Invoke Log(LogLevel, string) for every log level.
InternalLogger.Log(LogLevel.Warn, "WWW");
Expand All @@ -356,14 +347,9 @@ public void WriteToConsoleErrorTests()
InternalLogger.Log(LogLevel.Trace, "TTT");
InternalLogger.Log(LogLevel.Debug, "DDD");
InternalLogger.Log(LogLevel.Info, "III");
TestWriter(expected, consoleWriter2);
TestWriter(expected, loggerScope.ConsoleErrorWriter);
}
}
finally
{
InternalLogger.Reset();
Console.SetError(oldConsoleErrorWriter);
}
}

[Fact]
Expand Down
51 changes: 27 additions & 24 deletions tests/NLog.UnitTests/Config/InternalLoggingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void InternalLoggingConfigTes3()
[Fact]
public void InternalLoggingConfigTestDefaults()
{
using (new InternalLoggerScope())
using (new InternalLoggerScope(true))
{
InternalLogger.LogLevel = LogLevel.Error;
InternalLogger.LogToConsole = true;
Expand All @@ -90,29 +90,32 @@ public void InternalLoggingConfigTestDefaults()
[Fact]
public void InternalLoggingConfig_off_should_be_off()
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
InternalLogger.LogWriter = stringWriter;
string wrongFileName = "WRONG/***[]???////WRONG";
LogManager.Configuration = CreateConfigurationFromString(string.Format(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog internalLogFile='{0}'
internalLogLevel='Off'
throwExceptions='true' >
<targets>
<target name='logfile' type='File' fileName='WRONG' />
</targets>
<rules>
<logger name='*' writeTo='logfile' />
</rules>
</nlog>
", wrongFileName));

Assert.Equal("",sb.ToString());
Assert.Equal(LogLevel.Off,InternalLogger.LogLevel);
Assert.False(InternalLogger.ExceptionThrowWhenWriting);
using (new InternalLoggerScope())
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
InternalLogger.LogWriter = stringWriter;
string wrongFileName = "WRONG/***[]???////WRONG";
LogManager.Configuration = CreateConfigurationFromString(string.Format(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog internalLogFile='{0}'
internalLogLevel='Off'
throwExceptions='true' >
<targets>
<target name='logfile' type='File' fileName='WRONG' />
</targets>
<rules>
<logger name='*' writeTo='logfile' />
</rules>
</nlog>
", wrongFileName));

Assert.Equal("", sb.ToString());
Assert.Equal(LogLevel.Off, InternalLogger.LogLevel);
Assert.False(InternalLogger.ExceptionThrowWhenWriting);
}
}

private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, bool logToConsoleError, LogLevel globalThreshold, bool throwExceptions, bool? throwConfigExceptions, string file, bool logToTrace)
{
Expand All @@ -124,7 +127,7 @@ private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, boo
var throwConfigExceptionsString = throwConfigExceptions == null ? "" : throwConfigExceptions.ToString().ToLower();
var logToTraceString = logToTrace.ToString().ToLower();

using (new InternalLoggerScope())
using (new InternalLoggerScope(true))
{
CreateConfigurationFromString(string.Format(@"
<nlog internalLogFile='{0}' internalLogLevel='{1}' internalLogToConsole='{2}' internalLogToConsoleError='{3}' globalThreshold='{4}' throwExceptions='{5}' throwConfigExceptions='{6}' internalLogToTrace='{7}'>
Expand Down
44 changes: 24 additions & 20 deletions tests/NLog.UnitTests/Config/XmlConfigTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,33 +45,37 @@ public class XmlConfigTests : NLogTestBase
[Fact]
public void ParseNLogOptionsDefaultTest()
{
var xml = "<nlog></nlog>";
var config = CreateConfigurationFromString(xml);
using (new InternalLoggerScope())
{
var xml = "<nlog></nlog>";
var config = CreateConfigurationFromString(xml);

Assert.Equal(false, config.AutoReload);
Assert.Equal(true, config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.Equal(true, InternalLogger.IncludeTimestamp);
Assert.Equal(false, InternalLogger.LogToConsole);
Assert.Equal(false, InternalLogger.LogToConsoleError);
Assert.Equal(null, InternalLogger.LogWriter);
InternalLogger.Reset();
Assert.Equal(false, config.AutoReload);
Assert.Equal(true, config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.Equal(true, InternalLogger.IncludeTimestamp);
Assert.Equal(false, InternalLogger.LogToConsole);
Assert.Equal(false, InternalLogger.LogToConsoleError);
Assert.Equal(null, InternalLogger.LogWriter);
}
}

[Fact]
public void ParseNLogOptionsTest()
{
var xml = "<nlog autoreload='true' logfile='test.txt' internalLogIncludeTimestamp='false' internalLogToConsole='true' internalLogToConsoleError='true'></nlog>";
var config = CreateConfigurationFromString(xml);
using (new InternalLoggerScope(true))
{
var xml = "<nlog autoreload='true' logfile='test.txt' internalLogIncludeTimestamp='false' internalLogToConsole='true' internalLogToConsoleError='true'></nlog>";
var config = CreateConfigurationFromString(xml);

Assert.Equal(true, config.AutoReload);
Assert.Equal(true, config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.Equal(false, InternalLogger.IncludeTimestamp);
Assert.Equal(true, InternalLogger.LogToConsole);
Assert.Equal(true, InternalLogger.LogToConsoleError);
Assert.Equal(null, InternalLogger.LogWriter);
InternalLogger.Reset();
Assert.Equal(true, config.AutoReload);
Assert.Equal(true, config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.Equal(false, InternalLogger.IncludeTimestamp);
Assert.Equal(true, InternalLogger.LogToConsole);
Assert.Equal(true, InternalLogger.LogToConsoleError);
Assert.Equal(null, InternalLogger.LogWriter);
}
}


Expand Down
45 changes: 42 additions & 3 deletions tests/NLog.UnitTests/NLogTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -439,24 +439,63 @@ protected static bool IsAppVeyor()

public class InternalLoggerScope : IDisposable
{
private readonly TextWriter oldConsoleOutputWriter;
public StringWriter ConsoleOutputWriter { get; private set; }
private readonly TextWriter oldConsoleErrorWriter;
public StringWriter ConsoleErrorWriter { get; private set; }
private readonly LogLevel globalThreshold;
private readonly bool throwExceptions;
private readonly bool? throwConfigExceptions;

public InternalLoggerScope()
public InternalLoggerScope(bool redirectConsole = false)
{
if (redirectConsole)
{
ConsoleOutputWriter = new StringWriter() { NewLine = "\n" };
ConsoleErrorWriter = new StringWriter() { NewLine = "\n" };

this.oldConsoleOutputWriter = Console.Out;
this.oldConsoleErrorWriter = Console.Error;

Console.SetOut(ConsoleOutputWriter);
Console.SetError(ConsoleErrorWriter);
}

this.globalThreshold = LogManager.GlobalThreshold;
this.throwExceptions = LogManager.ThrowExceptions;
this.throwConfigExceptions = LogManager.ThrowConfigExceptions;
}

public void SetConsoleError(StringWriter consoleErrorWriter)
{
if (ConsoleOutputWriter == null || consoleErrorWriter == null)
throw new InvalidOperationException("Initialize with redirectConsole=true");

ConsoleErrorWriter = consoleErrorWriter;
Console.SetError(consoleErrorWriter);
}

public void SetConsoleOutput(StringWriter consoleOutputWriter)
{
if (ConsoleOutputWriter == null || consoleOutputWriter == null)
throw new InvalidOperationException("Initialize with redirectConsole=true");

ConsoleOutputWriter = consoleOutputWriter;
Console.SetOut(consoleOutputWriter);
}

public void Dispose()
{
InternalLogger.Reset();

if (ConsoleOutputWriter != null)
Console.SetOut(oldConsoleOutputWriter);
if (ConsoleErrorWriter != null)
Console.SetError(oldConsoleErrorWriter);

if (File.Exists(InternalLogger.LogFile))
File.Delete(InternalLogger.LogFile);

InternalLogger.Reset();

//restore logmanager
LogManager.GlobalThreshold = this.globalThreshold;
LogManager.ThrowExceptions = this.throwExceptions;
Expand Down

0 comments on commit 3872685

Please sign in to comment.