-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShouldBeMessage.cs
263 lines (221 loc) · 9.59 KB
/
ShouldBeMessage.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using NUnit.Framework;
using ShouldBe.DifferenceHighlighting;
namespace ShouldBe
{
/// <summary/>
public class AssertionStackFrameInfo
{
/// <summary/>
public bool CanReadSourceCode { get; set; }
/// <summary/>
public string ShouldMethod { get; set; }
/// <summary/>
public string FileName { get; set; }
/// <summary/>
public int LineNumber { get; set; }
/// <summary/>
public int ColumnNumber { get; set; }
}
/// <summary>
/// Helper class for creating assertion failure messages.
/// </summary>
internal class ShouldBeMessage
{
internal static T2 Assert<T1, T2>(
bool assertion,
T2 originalActual,
T2 originalExpected)
{
if (!assertion)
{
Fail(originalActual, originalExpected);
}
return originalActual;
}
public static void FailActualIfNull(bool actualIsNull)
{
if (actualIsNull)
{
throw new AssertionException(GetMessageActualIsNull());
}
}
public static void FailActual<T>(T actual)
{
throw new AssertionException(GetMessageActual(actual));
}
public static void FailActual<T>(IEnumerable<T> actual)
{
throw new AssertionException(GetMessageActual(actual));
}
public static void FailExpecting<T>(T expected)
{
throw new AssertionException(GetMessageExpecting(expected));
}
public static void FailExpectingElement<T>(T expectedElement)
{
throw new AssertionException(GetMessageExpectingElement(expectedElement));
}
public static void FailExpectingFormatted(string expected)
{
throw new AssertionException(GetMessageExpectingFormatted(expected));
}
public static void Fail<T>(T actual, T expected, string context = null)
{
throw new AssertionException(GetMessage(actual, expected, context));
}
public static void Fail<T>(IEnumerable<T> actual, T expected, T tolerance)
{
throw new AssertionException(GetMessageWithTolerance(actual, expected, tolerance));
}
public static void Fail<T>(IEnumerable<T> actual, T expected, string context = null)
{
throw new AssertionException(GetMessage(actual, expected, context));
}
public static string GetMessage<T1, T2>(T1 actual, T2 expected, string context = null)
{
string message = string.Format("{0}\n {1}\n but was\n {2}",
context ?? GetContext(), expected.Inspect(), actual.Inspect());
if (actual.CanGenerateDifferencesBetween(expected))
{
message += string.Format("\n difference\n {0}",
actual.HighlightDifferencesBetween(expected));
}
return message;
}
public static string GetMessageWithTolerance<T>(IEnumerable<T> actual, T expected, T tolerance)
{
return string.Format("{0}\n {1} (+/- {2})\n but was\n {3}",
GetContext(), expected, tolerance, actual.Inspect());
}
public static string GetMessageActual<T>(T actual)
{
string context = GetContext();
return string.Format("{0} but was\n {1}", context, actual.Inspect());
}
public static string GetMessageActualIsNull()
{
string context = GetContext(true);
return string.Format("{0} should not be null", context);
}
public static string GetMessageExpecting<T>(T expected)
{
string context = GetContext();
return string.Format("{0}\n {1}", context, expected.Inspect());
}
public static string GetMessageExpectingFormatted(string expected)
{
string context = GetContext();
return string.Format("{0}\n {1}", context, expected);
}
public static string GetMessageExpectingElement<T>(T expectedElement)
{
string context = GetContext();
return string.Format("{0} an element satisfying the condition\n {1}",
context, expectedElement.Inspect());
}
public static string GetContext()
{
return GetContext(false);
}
private static string GetContext(bool codeOnly)
{
AssertionStackFrameInfo assertionStackFrame = GetStackFrameForOriginatingTestMethod();
var codePart = "The provided expression";
// Extract "actual" expression from source code using stackframeInfo
if (assertionStackFrame.CanReadSourceCode)
{
var possibleCodeLines = File.ReadAllLines(assertionStackFrame.FileName)
.Skip(assertionStackFrame.LineNumber).ToArray();
var codeLines = possibleCodeLines.DelimitWith("\n");
var shouldMethodIndex = codeLines.IndexOf(assertionStackFrame.ShouldMethod);
codePart = shouldMethodIndex > -1 ?
codeLines.Substring(0, shouldMethodIndex - 1).Trim() :
possibleCodeLines[0];
if (codePart.StartsWith("() => ")) codePart = codePart.Substring(6);
}
if (codeOnly)
{
return codePart;
}
else
{
string assertDesc = assertionStackFrame.ShouldMethod.Replace("Async", "").CamelCasedToSpaced();
return string.Format("{0}\n {1}", codePart, assertDesc);
}
}
//private static TestEnvironment GetStackFrameForOriginatingTestMethod1()
//{
// var stackTrace = new StackTrace(true);
// StackFrame[] frames = stackTrace.GetFrames();
// if (frames == null) throw new Exception("Unable to find test method");
// // Filter out asyc, system or other library stack frames.
// frames = frames.Where(frm => frm.GetFileName() != null).ToArray();
// if (frames.Length == 0) throw new Exception("Unable to find test method. No stack frames available. Run unit tests with a debug build.");
// var i = 0;
// var shouldbeFrame = frames[i];
// if (shouldbeFrame == null) throw new Exception("Unable to find test method");
// while (!shouldbeFrame.GetMethod().DeclaringType.GetCustomAttributes(typeof(ShouldBeMethodsAttribute), true).Any())
// {
// shouldbeFrame = frames[++i];
// }
// var originatingFrame = frames[i + 1];
// string sourceFile = originatingFrame.GetFileName();
// return new TestEnvironment
// {
// CanReadSourceCode = sourceFile != null && File.Exists(sourceFile),
// ShouldMethod = shouldbeFrame.GetMethod().Name,
// FileName = sourceFile,
// LineNumber = originatingFrame.GetFileLineNumber() - 1
// };
//}
private static AssertionStackFrameInfo GetStackFrameForOriginatingTestMethod()
{
var stackTrace = new StackTrace(true);
StackFrame[] frames = stackTrace.GetFrames();
if (frames == null) throw new Exception("Unable to find test method. No stack frames available. Run unit tests with a debug build.");
// Filter out asyc, system or other library stack frames.
//frames = frames.Where(frm => frm.GetFileName() != null).ToArray();
if (frames.Length == 0) throw new Exception("Unable to find test method. No stack frames available. Run unit tests with a debug build.");
StackFrame frame;
MethodBase method;
string assertionMethodName = null;
Type declType;
int i;
for (i = 0;
i < frames.Length
&& (frame = frames[i]) != null
&& (method = frame.GetMethod()) != null
&& (declType = method.DeclaringType) != null;
i++)
{
// Find at least one StackFrame having [ShouldBeMethodsAttribute] on the method class.
if (declType.GetCustomAttributes(typeof (ShouldBeMethodsAttribute), true).Any())
{
assertionMethodName = frame.GetMethod().Name;
}
// THEN next StackFrame after the method class.
else if (assertionMethodName != null)
{
// Use NUnit test fixture method as the source code for the assertion failure message
string sourceFile = frame.GetFileName();
return new AssertionStackFrameInfo
{
CanReadSourceCode = sourceFile != null && File.Exists(sourceFile),
ShouldMethod = assertionMethodName,
FileName = sourceFile,
LineNumber = frame.GetFileLineNumber() - 1,
ColumnNumber = frame.GetFileColumnNumber()
};
}
}
throw new Exception("Unable to find test method source code. No stack available or using async calls.");
}
}
}