File: AssertionFailureMessage.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (533 lines) | stat: -rw-r--r-- 18,054 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************

using System;
using System.Text;
using System.IO;
using System.Collections;

namespace NUnit.Framework
{
	/// <summary>
	/// AssertionFailureMessage encapsulates a failure message
	/// issued as a result of an Assert failure.
	/// </summary>
	[Obsolete( "Use MessageWriter for new work" )]
	public class AssertionFailureMessage : StringWriter
	{
		#region Static Constants

		/// <summary>
		/// Number of characters before a highlighted position before
		/// clipping will occur.  Clipped text is replaced with an
		/// elipsis "..."
		/// </summary>
		static public readonly int PreClipLength = 35;

		/// <summary>
		/// Number of characters after a highlighted position before
		/// clipping will occur.  Clipped text is replaced with an
		/// elipsis "..."
		/// </summary>
		static public readonly int PostClipLength = 35;

		/// <summary>
		/// Prefix used to start an expected value line.
		/// Must be same length as actualPrefix.
		/// </summary>
		static protected readonly string expectedPrefix = "expected:";
		
		/// <summary>
		/// Prefix used to start an actual value line.
		/// Must be same length as expectedPrefix.
		/// </summary>
		static protected readonly string actualPrefix   = " but was:";

		static private readonly string expectedAndActualFmt = "\t{0} {1}";
		static private readonly string diffStringLengthsFmt 
			= "\tString lengths differ.  Expected length={0}, but was length={1}.";
		static private readonly string sameStringLengthsFmt
			= "\tString lengths are both {0}.";
		static private readonly string diffArrayLengthsFmt
			= "Array lengths differ.  Expected length={0}, but was length={1}.";
		static private readonly string sameArrayLengthsFmt
			= "Array lengths are both {0}.";
		static private readonly string stringsDifferAtIndexFmt
			= "\tStrings differ at index {0}.";
		static private readonly string arraysDifferAtIndexFmt
			= "Arrays differ at index {0}.";

		#endregion

		#region Constructors

		/// <summary>
		/// Construct an AssertionFailureMessage with a message
		/// and optional arguments.
		/// </summary>
		/// <param name="message"></param>
		/// <param name="args"></param>
		public AssertionFailureMessage( string message, params object[] args )
		{
			if ( message != null && message != string.Empty )
				if ( args != null )
					WriteLine( message, args );
				else
					WriteLine( message );
		}

		/// <summary>
		/// Construct an empty AssertionFailureMessage
		/// </summary>
		public AssertionFailureMessage() : this( null, null ) { }

		#endregion

		/// <summary>
		/// Add an expected value line to the message containing
		/// the text provided as an argument.
		/// </summary>
		/// <param name="text">Text describing what was expected.</param>
		public void WriteExpectedLine( string text )
		{
			WriteLine( string.Format( expectedAndActualFmt, expectedPrefix, text ) );
		}

		/// <summary>
		/// Add an actual value line to the message containing
		/// the text provided as an argument.
		/// </summary>
		/// <param name="text">Text describing the actual value.</param>
		public void WriteActualLine( string text )
		{
			WriteLine( string.Format( expectedAndActualFmt, actualPrefix, text ) );
		}

		/// <summary>
		/// Add an expected value line to the message containing
		/// a string representation of the object provided.
		/// </summary>
		/// <param name="expected">An object representing the expected value</param>
		public void DisplayExpectedValue( object expected )
		{
			WriteExpectedLine( FormatObjectForDisplay( expected ) );
		}

		/// <summary>
		/// Add an expected value line to the message containing a double
		/// and the tolerance used in making the comparison.
		/// </summary>
		/// <param name="expected">The expected value</param>
		/// <param name="tolerance">The tolerance specified in the Assert</param>
		public void DisplayExpectedValue( double expected, double tolerance )
		{
			WriteExpectedLine( FormatObjectForDisplay( expected ) + " +/- " + tolerance.ToString() );
		}

		/// <summary>
		/// Add an actual value line to the message containing
		/// a string representation of the object provided.
		/// </summary>
		/// <param name="actual">An object representing what was actually found</param>
		public void DisplayActualValue( object actual )
		{
			WriteActualLine( FormatObjectForDisplay( actual ) );
		}

		/// <summary>
		/// Display two lines that communicate the expected value, and the actual value
		/// </summary>
		/// <param name="expected">The expected value</param>
		/// <param name="actual">The actual value found</param>
		public void DisplayExpectedAndActual( Object expected, Object actual )
		{
			DisplayExpectedValue( expected );
			DisplayActualValue( actual );
		}

		/// <summary>
		/// Display two lines that communicate the expected value, the actual value and
		/// the tolerance used in comparing two doubles.
		/// </summary>
		/// <param name="expected">The expected value</param>
		/// <param name="actual">The actual value found</param>
		/// <param name="tolerance">The tolerance specified in the Assert</param>
		public void DisplayExpectedAndActual( double expected, double actual, double tolerance )
		{
			DisplayExpectedValue( expected, tolerance );
			DisplayActualValue( actual );
		}

		/// <summary>
		/// Draws a marker under the expected/actual strings that highlights
		/// where in the string a mismatch occurred.
		/// </summary>
		/// <param name="iPosition">The position of the mismatch</param>
		public void DisplayPositionMarker( int iPosition )
		{
			WriteLine( "\t{0}^", new String( '-', expectedPrefix.Length + iPosition + 3 ) );
		}

		/// <summary>
		/// Reports whether the string lengths are the same or different, and
		/// what the string lengths are.
		/// </summary>
		/// <param name="sExpected">The expected string</param>
		/// <param name="sActual">The actual string value</param>
		protected void BuildStringLengthReport( string sExpected, string sActual )
		{
			if( sExpected.Length != sActual.Length )
				WriteLine( diffStringLengthsFmt, sExpected.Length, sActual.Length );
			else
				WriteLine( sameStringLengthsFmt, sExpected.Length );
		}

		/// <summary>
		/// Called to create additional message lines when two objects have been 
		/// found to be unequal.  If the inputs are strings, a special message is
		/// rendered that can help track down where the strings are different,
		/// based on differences in length, or differences in content.
		/// 
		/// If the inputs are not strings, the ToString method of the objects
		/// is used to show what is different about them.
		/// </summary>
		/// <param name="expected">The expected value</param>
		/// <param name="actual">The actual value</param>
		/// <param name="caseInsensitive">True if a case-insensitive comparison is being performed</param>
		public void DisplayDifferences( object expected, object actual, bool caseInsensitive )
		{
			if( InputsAreStrings( expected, actual ) )
			{
				DisplayStringDifferences( 
					(string)expected, 
					(string)actual,
					caseInsensitive );
			}
			else
			{
				DisplayExpectedAndActual( expected, actual );
			}
		}

		/// <summary>
		/// Called to create additional message lines when two doubles have been 
		/// found to be unequal, within the specified tolerance.
		/// </summary>
		public void DisplayDifferencesWithTolerance( double expected, double actual, double tolerance )
		{
			DisplayExpectedAndActual( expected, actual, tolerance );
		}

		/// <summary>
		/// Constructs a message that can be displayed when the content of two
		/// strings are different, but the string lengths are the same.  The
		/// message will clip the strings to a reasonable length, centered
		/// around the first position where they are mismatched, and draw 
		/// a line marking the position of the difference to make comparison
		/// quicker.
		/// </summary>
		/// <param name="sExpected">The expected string value</param>
		/// <param name="sActual">The actual string value</param>
		/// <param name="caseInsensitive">True if a case-insensitive comparison is being performed</param>
		protected void DisplayStringDifferences( string sExpected, string sActual, bool caseInsensitive )
		{
			//
			// If they mismatch at a specified position, report the
			// difference.
			//
			int iPosition = caseInsensitive
				? FindMismatchPosition( sExpected.ToLower(), sActual.ToLower(), 0 )
				: FindMismatchPosition( sExpected, sActual, 0 );
			//
			// If the lengths differ, but they match up to the length,
			// show the difference just past the length of the shorter
			// string
			//
			if( iPosition == -1 ) 
				iPosition = Math.Min( sExpected.Length, sActual.Length );
			
			BuildStringLengthReport( sExpected, sActual );

			WriteLine( stringsDifferAtIndexFmt, iPosition );

			//
			// Clips the strings, then turns any hidden whitespace into visible
			// characters
			//
			string sClippedExpected = ConvertWhitespace(ClipAroundPosition( sExpected, iPosition ));
			string sClippedActual   = ConvertWhitespace(ClipAroundPosition( sActual,   iPosition ));

			DisplayExpectedAndActual( 
				sClippedExpected, 
				sClippedActual );

			// Add a line showing where they differ.  If the string lengths are
			// different, they start differing just past the length of the 
			// shorter string
			DisplayPositionMarker( caseInsensitive
				? FindMismatchPosition( sClippedExpected.ToLower(), sClippedActual.ToLower(), 0 )
				: FindMismatchPosition( sClippedExpected, sClippedActual, 0 ) );
		}

		/// <summary>
		/// Display a standard message showing the differences found between 
		/// two arrays that were expected to be equal.
		/// </summary>
		/// <param name="expected">The expected array value</param>
		/// <param name="actual">The actual array value</param>
		/// <param name="index">The index at which a difference was found</param>
		public void DisplayArrayDifferences( Array expected, Array actual, int index )
		{
			if( expected.Length != actual.Length )
				WriteLine( diffArrayLengthsFmt, expected.Length, actual.Length );
			else
				WriteLine( sameArrayLengthsFmt, expected.Length );
			
			WriteLine( arraysDifferAtIndexFmt, index );
				
			if ( index < expected.Length && index < actual.Length )
			{
				DisplayDifferences( GetValueFromCollection(expected, index ), GetValueFromCollection(actual, index), false );
			}
			else if( expected.Length < actual.Length )
				DisplayListElements( "   extra:", actual, index, 3 );
			else
				DisplayListElements( " missing:", expected, index, 3 );
		}

		/// <summary>
		/// Display a standard message showing the differences found between 
		/// two collections that were expected to be equal.
		/// </summary>
		/// <param name="expected">The expected collection value</param>
		/// <param name="actual">The actual collection value</param>
		/// <param name="index">The index at which a difference was found</param>
		// NOTE: This is a temporary method for use until the code from NUnitLite
		// is integrated into NUnit.
		public void DisplayCollectionDifferences( ICollection expected, ICollection actual, int index )
		{
			if( expected.Count != actual.Count )
				WriteLine( diffArrayLengthsFmt, expected.Count, actual.Count );
			else
				WriteLine( sameArrayLengthsFmt, expected.Count );
			
			WriteLine( arraysDifferAtIndexFmt, index );
				
			if ( index < expected.Count && index < actual.Count )
			{
				DisplayDifferences( GetValueFromCollection(expected, index ), GetValueFromCollection(actual, index), false );
			}
//			else if( expected.Count < actual.Count )
//				DisplayListElements( "   extra:", actual, index, 3 );
//			else
//				DisplayListElements( " missing:", expected, index, 3 );
		}

		private static object GetValueFromCollection(ICollection collection, int index)
		{
			Array array = collection as Array;

			if (array != null && array.Rank > 1)
				return array.GetValue(GetArrayIndicesFromCollectionIndex(array, index));

			if (collection is IList)
				return ((IList)collection)[index];

			foreach (object obj in collection)
				if (--index < 0)
					return obj;

			return null;
		}

		/// <summary>
		/// Get an array of indices representing the point in a collection or
		/// array corresponding to a single int index into the collection.
		/// </summary>
		/// <param name="collection">The collection to which the indices apply</param>
		/// <param name="index">Index in the collection</param>
		/// <returns>Array of indices</returns>
		private static int[] GetArrayIndicesFromCollectionIndex(ICollection collection, int index)
		{
			Array array = collection as Array;
			int rank = array == null ? 1 : array.Rank;
			int[] result = new int[rank];

			for (int r = array.Rank; --r > 0; )
			{
				int l = array.GetLength(r);
				result[r] = index % l;
				index /= l;
			}

			result[0] = index;
			return result;
		}

		/// <summary>
		/// Displays elements from a list on a line
		/// </summary>
		/// <param name="label">Text to prefix the line with</param>
		/// <param name="list">The list of items to display</param>
		/// <param name="index">The index in the list of the first element to display</param>
		/// <param name="max">The maximum number of elements to display</param>
		public void DisplayListElements( string label, IList list, int index, int max )
		{
			Write( "{0}<", label );

			if ( list == null )
				Write( "null" );
			else if ( list.Count == 0 )
				Write( "empty" );
			else
			{
				for( int i = 0; i < max && index < list.Count; i++ )
				{
					Write( FormatObjectForDisplay( list[index++] ) );
				
					if ( index < list.Count )
						Write( "," );
				}

				if ( index < list.Count )
					Write( "..." );
			}

			WriteLine( ">" );
		}

		#region Static Methods

		/// <summary>
		/// Formats an object for display in a message line
		/// </summary>
		/// <param name="obj">The object to be displayed</param>
		/// <returns></returns>
		static public string FormatObjectForDisplay( object  obj )
		{
			if ( obj == null ) 
				return "<(null)>";
			else if ( obj is string )
				return string.Format( "<\"{0}\">", obj );
			else if ( obj is double )
				return string.Format( "<{0}>", ((double)obj).ToString( "G17" ) );
			else if ( obj is float )
				return string.Format( "<{0}>", ((float)obj).ToString( "G9" ) );
			else
				return string.Format( "<{0}>", obj );
		}

		/// <summary>
		/// Tests two objects to determine if they are strings.
		/// </summary>
		/// <param name="expected"></param>
		/// <param name="actual"></param>
		/// <returns></returns>
		static protected bool InputsAreStrings( Object expected, Object actual )
		{
			return expected != null && actual != null && 
				expected is string && actual is string;
		}

		/// <summary>
		/// Renders up to M characters before, and up to N characters after
		/// the specified index position.  If leading or trailing text is
		/// clipped, and elipses "..." is added where the missing text would
		/// be.
		/// 
		/// Clips strings to limit previous or post newline characters,
		/// since these mess up the comparison
		/// </summary>
		/// <param name="sString"></param>
		/// <param name="iPosition"></param>
		/// <returns></returns>
		static protected string ClipAroundPosition( string sString, int iPosition )
		{
			if( sString == null || sString.Length == 0 )
				return "";

			bool preClip = iPosition > PreClipLength;
			bool postClip = iPosition + PostClipLength < sString.Length;

			int start = preClip 
				? iPosition - PreClipLength : 0;
			int length = postClip 
				? iPosition + PostClipLength - start : sString.Length - start;

			if ( start + length > iPosition + PostClipLength )
				length = iPosition + PostClipLength - start;

			StringBuilder sb = new StringBuilder();
			if ( preClip ) sb.Append("...");
			sb.Append( sString.Substring( start, length ) );
			if ( postClip ) sb.Append("...");

			return sb.ToString();
		}

		/// <summary>
		/// Shows the position two strings start to differ.  Comparison 
		/// starts at the start index.
		/// </summary>
		/// <param name="sExpected"></param>
		/// <param name="sActual"></param>
		/// <param name="iStart"></param>
		/// <returns>-1 if no mismatch found, or the index where mismatch found</returns>
		static private int FindMismatchPosition( string sExpected, string sActual, int iStart )
		{
			int iLength = Math.Min( sExpected.Length, sActual.Length );
			for( int i=iStart; i<iLength; i++ )
			{
				//
				// If they mismatch at a specified position, report the
				// difference.
				//
				if( sExpected[i] != sActual[i] )
				{
					return i;
				}
			}
			//
			// Strings have same content up to the length of the shorter string.
			// Mismatch occurs because string lengths are different, so show
			// that they start differing where the shortest string ends
			//
			if( sExpected.Length != sActual.Length )
			{
				return iLength;
			}
            
			//
			// Same strings
			//
			Assert.IsTrue( sExpected.Equals( sActual ) );
			return -1;
		}

		/// <summary>
		/// Turns CR, LF, or TAB into visual indicator to preserve visual marker 
		/// position.   This is done by replacing the '\r' into '\\' and 'r' 
		/// characters, and the '\n' into '\\' and 'n' characters, and '\t' into
		/// '\\' and 't' characters.  
		/// 
		/// Thus the single character becomes two characters for display.
		/// </summary>
		/// <param name="sInput"></param>
		/// <returns></returns>
		static protected string ConvertWhitespace( string sInput )
		{
			if( null != sInput )
			{
				sInput = sInput.Replace( "\\", "\\\\" );
				sInput = sInput.Replace( "\r", "\\r" );
				sInput = sInput.Replace( "\n", "\\n" );
				sInput = sInput.Replace( "\t", "\\t" );
			}
			return sInput;
		}
		#endregion
	}
}