From 2a3cc5ece3fd3fb18c2352bce54e32547f7eaf17 Mon Sep 17 00:00:00 2001 From: Jeroen Vervaeke Date: Thu, 23 Mar 2023 23:40:16 +0000 Subject: [PATCH] Fixed issue where TextRunner accidentally disposes System.Out --- .../nunitlite.tests/TextRunnerTests.cs | 57 +++++++++++++++++++ .../nunitlite/ColorConsoleWriter.cs | 7 +++ 2 files changed, 64 insertions(+) create mode 100644 src/NUnitFramework/nunitlite.tests/TextRunnerTests.cs diff --git a/src/NUnitFramework/nunitlite.tests/TextRunnerTests.cs b/src/NUnitFramework/nunitlite.tests/TextRunnerTests.cs new file mode 100644 index 0000000000..61ca96f1ef --- /dev/null +++ b/src/NUnitFramework/nunitlite.tests/TextRunnerTests.cs @@ -0,0 +1,57 @@ +// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt + +using System; +using System.IO; +using System.Text; +using NUnit.Framework; + +namespace NUnitLite.Tests +{ + [TestFixture] + public class TextRunnerTests + { + [Test] + public void CommandLineTests() + { + Console.SetOut(new WriteToStreamAndConsole(Console.Out, new MemoryStream())); + + var textRunner = new TextRunner(); + textRunner.Execute(new[] { "--noresult" }); + Console.Out.WriteLine("Broken"); + } + } + + public class WriteToStreamAndConsole : TextWriter + { + private readonly TextWriter _writer; + private readonly StreamWriter _streamWriter; + + public WriteToStreamAndConsole(TextWriter writer, Stream stream) + { + _writer = writer; + _streamWriter = new StreamWriter(stream); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _writer.Dispose(); + _streamWriter.Dispose(); + } + + base.Dispose(disposing); + } + + // Only overriden WriteLine for simplicity sake + public override void WriteLine(string value) + { + _writer.WriteLine(value); + _streamWriter.WriteLine(value); + + base.WriteLine(value); + } + + public override Encoding Encoding => _writer.Encoding; + } +} diff --git a/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs b/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs index e673d9b2b2..adee135ed8 100644 --- a/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs +++ b/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs @@ -104,6 +104,13 @@ public override void WriteLabelLine(string label, object option, ColorStyle valu WriteLine(); } + protected override void Dispose(bool disposing) + { + // The base class disposes the writer it's wrapping + // In our case the writer is System.Out, + // We don't want to dispose of System.Out as it could potentially break other peoples code + } + #endregion } }