/src/NUnit/core/EventListenerTextWriter.cs
C# | 114 lines | 93 code | 13 blank | 8 comment | 2 complexity | d950716a04cc6d1d53e460847f253c0d MD5 | raw file
1// **************************************************************** 2// Copyright 2007, Charlie Poole 3// This is free software licensed under the NUnit license. You may 4// obtain a copy of the license at http://nunit.org. 5// **************************************************************** 6namespace NUnit.Core 7{ 8 using System; 9 using System.IO; 10 using System.Text; 11 12 public class EventListenerTextWriter : TextWriter 13 { 14 private EventListener eventListener; 15 private TestOutputType type; 16 17 public EventListenerTextWriter( EventListener eventListener, TestOutputType type ) 18 { 19 this.eventListener = eventListener; 20 this.type = type; 21 } 22 override public void Write(char aChar) 23 { 24 this.eventListener.TestOutput( new TestOutput( aChar.ToString(), this.type ) ); 25 } 26 27 override public void Write(string aString) 28 { 29 this.eventListener.TestOutput( new TestOutput( aString, this.type ) ); 30 } 31 32 override public void WriteLine(string aString) 33 { 34 this.eventListener.TestOutput( new TestOutput( aString + this.NewLine, this.type ) ); 35 } 36 37 override public System.Text.Encoding Encoding 38 { 39 get { return Encoding.Default; } 40 } 41 } 42 43 /// <summary> 44 /// This wrapper adds buffering to improve cross-domain performance. 45 /// </summary> 46 public class BufferedEventListenerTextWriter : TextWriter 47 { 48 private EventListener eventListener; 49 private TestOutputType type; 50 private const int MAX_BUFFER = 1024; 51 private StringBuilder sb = new StringBuilder( MAX_BUFFER ); 52 53 public BufferedEventListenerTextWriter( EventListener eventListener, TestOutputType type ) 54 { 55 this.eventListener = eventListener; 56 this.type = type; 57 } 58 59 public override Encoding Encoding 60 { 61 get 62 { 63 return Encoding.Default; 64 } 65 } 66 67 override public void Write(char ch) 68 { 69 lock( sb ) 70 { 71 sb.Append( ch ); 72 this.CheckBuffer(); 73 } 74 } 75 76 override public void Write(string str) 77 { 78 lock( sb ) 79 { 80 sb.Append( str ); 81 this.CheckBuffer(); 82 } 83 } 84 85 override public void WriteLine(string str) 86 { 87 lock( sb ) 88 { 89 sb.Append( str ); 90 sb.Append( base.NewLine ); 91 this.CheckBuffer(); 92 } 93 } 94 95 override public void Flush() 96 { 97 if ( sb.Length > 0 ) 98 { 99 lock( sb ) 100 { 101 TestOutput output = new TestOutput(sb.ToString(), this.type); 102 this.eventListener.TestOutput( output ); 103 sb.Length = 0; 104 } 105 } 106 } 107 108 private void CheckBuffer() 109 { 110 if ( sb.Length >= MAX_BUFFER ) 111 this.Flush(); 112 } 113 } 114}