forked from fluentassertions/fluentassertions
/
AssertionScope.cs
267 lines (226 loc) · 8.89 KB
/
AssertionScope.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
264
265
266
267
#region
using System;
using System.Linq;
using System.Threading;
using FluentAssertions.Common;
#endregion
namespace FluentAssertions.Execution
{
/// <summary>
/// Represents an implicit or explicit scope within which multiple assertions can be collected.
/// </summary>
public class AssertionScope : IAssertionScope
{
#region Private Definitions
private readonly IAssertionStrategy assertionStrategy;
private readonly ContextDataItems contextData = new ContextDataItems();
private Func<string> reason;
private bool useLineBreaks;
[ThreadStatic]
private static AssertionScope current;
private AssertionScope parent;
private Func<string> expectation;
private string fallbackIdentifier = "object";
#endregion
private AssertionScope(IAssertionStrategy _assertionStrategy)
{
assertionStrategy = _assertionStrategy;
parent = null;
}
/// <summary>
/// Starts an unnamed scope within which multiple assertions can be executed
/// and which will not throw until the scope is disposed.
/// </summary>
public AssertionScope()
: this(new CollectingAssertionStrategy())
{
parent = current;
current = this;
if (parent != null)
{
contextData.Add(parent.contextData);
Context = parent.Context;
}
}
/// <summary>
/// Starts a named scope within which multiple assertions can be executed and which will not throw until the scope is disposed.
/// </summary>
public AssertionScope(string context)
: this()
{
Context = context;
}
/// <summary>
/// Gets or sets the context of the current assertion scope, e.g. the path of the object graph
/// that is being asserted on.
/// </summary>
public string Context { get; set; }
/// <summary>
/// Gets the current thread-specific assertion scope.
/// </summary>
public static AssertionScope Current
{
get => current ?? new AssertionScope(new DefaultAssertionStrategy());
private set => current = value;
}
public IAssertionScope UsingLineBreaks
{
get
{
useLineBreaks = true;
return this;
}
}
/// <summary>
/// Gets a value indicating whether or not the last assertion executed through this scope succeeded.
/// </summary>
public bool? Succeeded { get; private set; }
public IAssertionScope BecauseOf(string because, params object[] becauseArgs)
{
reason = () =>
{
try
{
string becauseOrEmpty = because ?? "";
return (becauseArgs?.Any() == true) ? string.Format(becauseOrEmpty, becauseArgs) : becauseOrEmpty;
}
catch (FormatException formatException)
{
return $"**WARNING** because message '{because}' could not be formatted with string.Format{Environment.NewLine}{formatException.StackTrace}";
}
};
return this;
}
/// <summary>
/// Sets the expectation part of the failure message when the assertion is not met.
/// </summary>
/// <remarks>
/// In addition to the numbered <see cref="string.Format(string,object[])"/>-style placeholders, messages may contain a few
/// specialized placeholders as well. For instance, {reason} will be replaced with the reason of the assertion as passed
/// to <see cref="BecauseOf"/>. Other named placeholders will be replaced with the <see cref="Current"/> scope data
/// passed through <see cref="AddNonReportable"/> and <see cref="AddReportable"/>. Finally, a description of the
/// current subject can be passed through the {context:description} placeholder. This is used in the message if no
/// explicit context is specified through the <see cref="AssertionScope"/> constructor.
/// Note that only 10 <paramref name="args"/> are supported in combination with a {reason}.
/// If an expectation was set through a prior call to <see cref="WithExpectation"/>, then the failure message is appended to that
/// expectation.
/// </remarks>
/// <param name="expectation">The format string that represents the failure message.</param>
/// <param name="args">Optional arguments to any numbered placeholders.</param>
public IAssertionScope WithExpectation(string message, params object[] args)
{
var localReason = reason;
expectation = () =>
{
var messageBuilder = new MessageBuilder(useLineBreaks);
string reason = localReason != null ? localReason() : "";
string identifier = GetIdentifier();
return messageBuilder.Build(message, args, reason, contextData, identifier, fallbackIdentifier);
};
return this;
}
public Continuation ClearExpectation()
{
expectation = null;
return new Continuation(this, !Succeeded.HasValue || Succeeded.Value);
}
public GivenSelector<T> Given<T>(Func<T> selector)
{
return new GivenSelector<T>(selector, !Succeeded.HasValue || Succeeded.Value, this);
}
public IAssertionScope ForCondition(bool condition)
{
Succeeded = condition;
return this;
}
public Continuation FailWith(string message, params object[] args)
{
try
{
if (!Succeeded.HasValue || !Succeeded.Value)
{
string localReason = reason != null ? reason() : "";
var messageBuilder = new MessageBuilder(useLineBreaks);
string identifier = GetIdentifier();
string result = messageBuilder.Build(message, args, localReason, contextData, identifier, fallbackIdentifier);
if (expectation != null)
{
result = expectation() + result;
}
assertionStrategy.HandleFailure(result.Capitalize());
Succeeded = false;
}
return new Continuation(this, Succeeded.Value);
}
finally
{
Succeeded = null;
}
}
private string GetIdentifier()
{
if (!string.IsNullOrEmpty(Context))
{
return Context;
}
return CallerIdentifier.DetermineCallerIdentity();
}
/// <summary>
/// Adds a pre-formatted failure message to the current scope.
/// </summary>
public void AddPreFormattedFailure(string formattedFailureMessage)
{
assertionStrategy.HandleFailure(formattedFailureMessage);
}
public void AddNonReportable(string key, object value)
{
contextData.Add(key, value, Reportability.Hidden);
}
/// <summary>
/// Adds some information to the assertion scope that will be included in the message
/// that is emitted if an assertion fails.
/// </summary>
public void AddReportable(string key, string value)
{
contextData.Add(key, value, Reportability.Reportable);
}
/// <summary>
/// Discards and returns the failures that happened up to now.
/// </summary>
public string[] Discard()
{
return assertionStrategy.DiscardFailures().ToArray();
}
/// <summary>
/// Gets data associated with the current scope and identified by <paramref name="key"/>.
/// </summary>
public T Get<T>(string key)
{
return contextData.Get<T>(key);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Current = parent;
if (parent != null)
{
foreach (string failureMessage in assertionStrategy.FailureMessages)
{
parent.assertionStrategy.HandleFailure(failureMessage);
}
parent = null;
}
else
{
assertionStrategy.ThrowIfAny(contextData.GetReportable());
}
}
public IAssertionScope WithDefaultIdentifier(string identifier)
{
fallbackIdentifier = identifier;
return this;
}
}
}