forked from fluentassertions/fluentassertions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DelegateAssertions.cs
276 lines (239 loc) · 12.1 KB
/
DelegateAssertions.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
268
269
270
271
272
273
274
275
276
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using FluentAssertions.Common;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace FluentAssertions.Specialized
{
[DebuggerNonUserCode]
public abstract class DelegateAssertions<TDelegate, TAssertions> : ReferenceTypeAssertions<TDelegate, DelegateAssertions<TDelegate, TAssertions>>
where TDelegate : Delegate
where TAssertions : DelegateAssertions<TDelegate, TAssertions>
{
private readonly IExtractExceptions extractor;
protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor) : this(@delegate, extractor, new Clock())
{
}
private protected DelegateAssertions(TDelegate @delegate, IExtractExceptions extractor, IClock clock) : base(@delegate)
{
this.extractor = extractor ?? throw new ArgumentNullException(nameof(extractor));
Clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
private protected IClock Clock { get; }
private protected virtual bool CanHandleAsync => false;
/// <summary>
/// Asserts that the current <see cref="Delegate" /> throws an exception of type <typeparamref name="TException"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public ExceptionAssertions<TException> Throw<TException>(string because = "", params object[] becauseArgs)
where TException : Exception
{
Execute.Assertion
.ForCondition(Subject is object)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context} to throw {0}{reason}, but found <null>.", typeof(TException));
FailIfSubjectIsAsyncVoid();
Exception exception = InvokeSubjectWithInterception();
return Throw<TException>(exception, because, becauseArgs);
}
/// <summary>
/// Asserts that the current <see cref="Delegate" /> does not throw an exception of type <typeparamref name="TException"/>.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotThrow<TException>(string because = "", params object[] becauseArgs)
where TException : Exception
{
Execute.Assertion
.ForCondition(Subject is object)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context} not to throw {0}{reason}, but found <null>.", typeof(TException));
FailIfSubjectIsAsyncVoid();
Exception exception = InvokeSubjectWithInterception();
return NotThrow<TException>(exception, because, becauseArgs);
}
/// <summary>
/// Asserts that the current <see cref="Delegate" /> does not throw any exception.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> NotThrow(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject is object)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context} not to throw{reason}, but found <null>.");
FailIfSubjectIsAsyncVoid();
Exception exception = InvokeSubjectWithInterception();
return NotThrow(exception, because, becauseArgs);
}
/// <summary>
/// Asserts that the current <see cref="Delegate"/> throws an exception of the exact type <typeparamref name="TException"/> (and not a derived exception type).
/// </summary>
/// <typeparam name="TException">
/// The type of the exception it should throw.
/// </typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <returns>
/// Returns an object that allows asserting additional members of the thrown exception.
/// </returns>
public ExceptionAssertions<TException> ThrowExactly<TException>(string because = "",
params object[] becauseArgs)
where TException : Exception
{
Execute.Assertion
.ForCondition(Subject is object)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context} to throw exactly {0}{reason}, but found <null>.", typeof(TException));
FailIfSubjectIsAsyncVoid();
Exception exception = InvokeSubjectWithInterception();
Type expectedType = typeof(TException);
Execute.Assertion
.ForCondition(exception != null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {0}{reason}, but no exception was thrown.", expectedType);
exception.Should().BeOfType(expectedType, because, becauseArgs);
return new ExceptionAssertions<TException>(new[] { exception as TException });
}
/// <summary>
/// Asserts that the current <see cref="Delegate"/> stops throwing any exception
/// after a specified amount of time.
/// </summary>
/// <remarks>
/// The delegate is invoked. If it raises an exception,
/// the invocation is repeated until it either stops raising any exceptions
/// or the specified wait time is exceeded.
/// </remarks>
/// <param name="waitTime">
/// The time after which the delegate should have stopped throwing any exception.
/// </param>
/// <param name="pollInterval">
/// The time between subsequent invocations of the delegate.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">Throws if waitTime or pollInterval are negative.</exception>
public AndConstraint<TAssertions> NotThrowAfter(TimeSpan waitTime, TimeSpan pollInterval, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject is object)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context} not to throw after {0}{reason}, but found <null>.", waitTime);
FailIfSubjectIsAsyncVoid();
if (waitTime < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(waitTime), $"The value of {nameof(waitTime)} must be non-negative.");
}
if (pollInterval < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(pollInterval), $"The value of {nameof(pollInterval)} must be non-negative.");
}
TimeSpan? invocationEndTime = null;
Exception exception = null;
ITimer timer = Clock.StartTimer();
while (invocationEndTime is null || invocationEndTime < waitTime)
{
exception = InvokeSubjectWithInterception();
if (exception is null)
{
break;
}
Clock.Delay(pollInterval);
invocationEndTime = timer.Elapsed;
}
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(exception is null)
.FailWith("Did not expect any exceptions after {0}{reason}, but found {1}.", waitTime, exception);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected ExceptionAssertions<TException> Throw<TException>(Exception exception, string because, object[] becauseArgs)
where TException : Exception
{
TException[] expectedExceptions = extractor.OfType<TException>(exception).ToArray();
Execute.Assertion
.BecauseOf(because, becauseArgs)
.WithExpectation("Expected a <{0}> to be thrown{reason}, ", typeof(TException))
.ForCondition(exception != null)
.FailWith("but no exception was thrown.")
.Then
.ForCondition(expectedExceptions.Any())
.FailWith("but found <{0}>: {1}{2}.",
exception?.GetType(),
Environment.NewLine,
exception)
.Then
.ClearExpectation();
return new ExceptionAssertions<TException>(expectedExceptions);
}
protected AndConstraint<TAssertions> NotThrow(Exception exception, string because, object[] becauseArgs)
{
Execute.Assertion
.ForCondition(exception is null)
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect any exception{reason}, but found {0}.", exception);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected AndConstraint<TAssertions> NotThrow<TException>(Exception exception, string because, object[] becauseArgs) where TException : Exception
{
IEnumerable<TException> exceptions = extractor.OfType<TException>(exception);
Execute.Assertion
.ForCondition(!exceptions.Any())
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect {0}{reason}, but found {1}.", typeof(TException), exception);
return new AndConstraint<TAssertions>((TAssertions)this);
}
protected abstract void InvokeSubject();
private Exception InvokeSubjectWithInterception()
{
Exception actualException = null;
try
{
InvokeSubject();
}
catch (Exception exc)
{
actualException = exc;
}
return actualException;
}
private void FailIfSubjectIsAsyncVoid()
{
if (!CanHandleAsync && Subject.GetMethodInfo().IsDecoratedWithOrInherit<AsyncStateMachineAttribute>())
{
throw new InvalidOperationException("Cannot use action assertions on an async void method. Assign the async method to a variable of type Func<Task> instead of Action so that it can be awaited.");
}
}
}
}