-
-
Notifications
You must be signed in to change notification settings - Fork 540
/
ExecutionTimeAssertions.cs
280 lines (251 loc) · 11.9 KB
/
ExecutionTimeAssertions.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
277
278
279
280
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using FluentAssertions.Execution;
using System.Threading.Tasks;
using System.Threading;
namespace FluentAssertions.Specialized
{
/// <summary>
/// Provides methods for asserting that the execution time of an <see cref="Action"/> satisfies certain conditions.
/// </summary>
public class ExecutionTimeAssertions
{
private readonly ExecutionTime execution;
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionTime"/> class.
/// </summary>
/// <param name="executionTime">The execution on which time must be asserted.</param>
public ExecutionTimeAssertions(ExecutionTime executionTime)
{
this.execution = executionTime;
}
/// <summary>
/// Checks the executing action if it satisfies a condition.
/// If the execution runs into an exeption, then this will rethrow it.
/// </summary>
/// <param name="condition">Condition to check on the current elapsed time.</param>
/// <param name="expectedResult">Polling stops when condition returns the expected result.</param>
/// <param name="rate">The rate at which the condition is re-checked.</param>
/// <return>The elapsed time. (use this, don't measure twice)</return>
private (bool isRunning, TimeSpan elapsed) PollUntil(Func<TimeSpan, bool> condition, bool expectedResult, TimeSpan rate)
{
TimeSpan elapsed = execution.ElapsedTime;
bool isRunning = execution.IsRunning;
while (isRunning)
{
if (condition(elapsed) == expectedResult)
{
break;
}
isRunning = !execution.Task.Wait(rate);
elapsed = execution.ElapsedTime;
}
if (execution.Exception != null)
{
// rethrow captured exception
throw execution.Exception;
}
return (isRunning, elapsed);
}
/// <summary>
/// Asserts that the execution time of the operation is less or equal to a specified amount of time.
/// </summary>
/// <param name="maxDuration">
/// The maximum allowed duration.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public void BeLessOrEqualTo(TimeSpan maxDuration, string because = "", params object[] becauseArgs)
{
bool Condition(TimeSpan duration) => duration.CompareTo(maxDuration) <= 0;
var (isRunning, elapsed) = PollUntil(Condition, expectedResult: false, rate: maxDuration);
Execute.Assertion
.ForCondition(Condition(elapsed))
.BecauseOf(because, becauseArgs)
.FailWith("Execution of " +
execution.ActionDescription + " should be less or equal to {0}{reason}, but it required " +
(isRunning ? "more than " : "exactly ") + "{1}.",
maxDuration,
elapsed);
}
/// <summary>
/// Asserts that the execution time of the operation is less than a specified amount of time.
/// </summary>
/// <param name="maxDuration">
/// The maximum allowed duration.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public void BeLessThan(TimeSpan maxDuration, string because = "", params object[] becauseArgs)
{
bool Condition(TimeSpan duration) => duration.CompareTo(maxDuration) < 0;
var (isRunning, elapsed) = PollUntil(Condition, expectedResult: false, rate: maxDuration);
Execute.Assertion
.ForCondition(Condition(execution.ElapsedTime))
.BecauseOf(because, becauseArgs)
.FailWith("Execution of " +
execution.ActionDescription + " should be less than {0}{reason}, but it required " +
(isRunning ? "more than " : "exactly ") + "{1}.",
maxDuration,
elapsed);
}
/// <summary>
/// Asserts that the execution time of the operation is greater or equal to a specified amount of time.
/// </summary>
/// <param name="minDuration">
/// The minimum allowed duration.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public void BeGreaterOrEqualTo(TimeSpan minDuration, string because = "", params object[] becauseArgs)
{
bool Condition(TimeSpan duration) => duration.CompareTo(minDuration) >= 0;
var (isRunning, elapsed) = PollUntil(Condition, expectedResult: true, rate: minDuration);
Execute.Assertion
.ForCondition(Condition(elapsed))
.BecauseOf(because, becauseArgs)
.FailWith("Execution of " +
execution.ActionDescription + " should be greater or equal to {0}{reason}, but it required " +
(isRunning ? "more than " : "exactly ") + "{1}.",
minDuration,
elapsed);
}
/// <summary>
/// Asserts that the execution time of the operation is greater than a specified amount of time.
/// </summary>
/// <param name="minDuration">
/// The minimum allowed duration.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public void BeGreaterThan(TimeSpan minDuration, string because = "", params object[] becauseArgs)
{
bool Condition(TimeSpan duration) => duration.CompareTo(minDuration) > 0;
var (isRunning, elapsed) = PollUntil(Condition, expectedResult: true, rate: minDuration);
Execute.Assertion
.ForCondition(Condition(elapsed))
.BecauseOf(because, becauseArgs)
.FailWith("Execution of " +
execution.ActionDescription + " should be greater than {0}{reason}, but it required " +
(isRunning ? "more than " : "exactly ") + "{1}.",
minDuration,
elapsed);
}
/// <summary>
/// Asserts that the execution time of the operation is within the expected duration.
/// by a specified precision.
/// </summary>
/// <param name="expectedDuration">
/// The expected duration.
/// </param>
/// <param name="precision">
/// The maximum amount of time which the execution time may differ from the expected duration.
/// </param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders.
/// </param>
public void BeCloseTo(TimeSpan expectedDuration, TimeSpan precision, string because = "", params object[] becauseArgs)
{
var minimumValue = expectedDuration - precision;
var maximumValue = expectedDuration + precision;
bool MaxCondition(TimeSpan duration) => duration <= maximumValue;
bool MinCondition(TimeSpan duration) => duration >= minimumValue;
// for polling we only use max condition, we don't want poll to stop if
// elapsed time didn't even get to the acceptable range
var (isRunning, elapsed) = PollUntil(MaxCondition, expectedResult: false, rate: maximumValue);
Execute.Assertion
.ForCondition(MinCondition(elapsed) && MaxCondition(elapsed))
.BecauseOf(because, becauseArgs)
.FailWith("Execution of " + execution.ActionDescription +
" should be within {0} from {1}{reason}, but it required " +
(isRunning ? "more than " : "exactly ") + "{2}.",
precision,
expectedDuration,
elapsed);
}
}
public class ExecutionTime
{
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionTime"/> class.
/// </summary>
/// <param name="action">The action of which the execution time must be asserted.</param>
public ExecutionTime(Action action)
: this(() => Task.Run(action), "the action")
{
}
public ExecutionTime(Func<Task> action)
: this(action, "the action")
{
}
protected ExecutionTime(Func<Task> action, string actionDescription)
{
ActionDescription = actionDescription;
stopwatch = new Stopwatch();
IsRunning = true;
Task = Task.Run(async () =>
{
// move stopwatch as close to action start as possible
// so that we have to get correct time readings
try
{
stopwatch.Start();
await action();
}
catch (Exception exception)
{
Exception = exception;
}
finally
{
// ensures that we stop the stopwatch even on exceptions
stopwatch.Stop();
IsRunning = false;
}
});
}
internal TimeSpan ElapsedTime => stopwatch.Elapsed;
internal bool IsRunning { get; private set; }
internal string ActionDescription { get; }
internal Task Task { get; }
internal Exception Exception { get; private set; }
private readonly Stopwatch stopwatch;
}
public class MemberExecutionTime<T> : ExecutionTime
{
/// <summary>
/// Initializes a new instance of the <see cref="MemberExecutionTime<T>"/> class.
/// </summary>
/// <param name="subject">The object that exposes the method or property.</param>
/// <param name="action">A reference to the method or property to measure the execution time of.</param>
public MemberExecutionTime(T subject, Expression<Action<T>> action)
: base(() => Task.Run(() => action.Compile()(subject)), "(" + action.Body + ")")
{
}
}
}