-
Notifications
You must be signed in to change notification settings - Fork 763
/
FakeTimeProviderTests.cs
392 lines (316 loc) · 13 KB
/
FakeTimeProviderTests.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Time.Testing;
using Xunit;
namespace Microsoft.Extensions.Time.Testing.Test;
public class FakeTimeProviderTests
{
[Fact]
public void DefaultCtor()
{
var timeProvider = new FakeTimeProvider();
var now = timeProvider.GetUtcNow();
var timestamp = timeProvider.GetTimestamp();
var frequency = timeProvider.TimestampFrequency;
Assert.Equal(2000, now.Year);
Assert.Equal(1, now.Month);
Assert.Equal(1, now.Day);
Assert.Equal(0, now.Hour);
Assert.Equal(0, now.Minute);
Assert.Equal(0, now.Second);
Assert.Equal(0, now.Millisecond);
Assert.Equal(TimeSpan.Zero, now.Offset);
Assert.Equal(10_000_000, frequency);
Assert.Equal(TimeSpan.Zero, timeProvider.AutoAdvanceAmount);
var timestamp2 = timeProvider.GetTimestamp();
var frequency2 = timeProvider.TimestampFrequency;
var now2 = timeProvider.GetUtcNow();
Assert.Equal(now, now2);
Assert.Equal(frequency, frequency2);
Assert.Equal(timestamp, timestamp2);
}
[Fact]
public void RichCtor()
{
var timeProvider = new FakeTimeProvider(new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero));
timeProvider.Advance(TimeSpan.FromMilliseconds(8));
var pnow = timeProvider.GetTimestamp();
var frequency = timeProvider.TimestampFrequency;
var now = timeProvider.GetUtcNow();
Assert.Equal(2001, now.Year);
Assert.Equal(2, now.Month);
Assert.Equal(3, now.Day);
Assert.Equal(4, now.Hour);
Assert.Equal(5, now.Minute);
Assert.Equal(6, now.Second);
Assert.Equal(TimeSpan.Zero, now.Offset);
Assert.Equal(8, now.Millisecond);
Assert.Equal(10_000_000, frequency);
Assert.Equal(TimeSpan.Zero, timeProvider.AutoAdvanceAmount);
timeProvider.Advance(TimeSpan.FromMilliseconds(8));
var pnow2 = timeProvider.GetTimestamp();
var frequency2 = timeProvider.TimestampFrequency;
now = timeProvider.GetUtcNow();
Assert.Equal(2001, now.Year);
Assert.Equal(2, now.Month);
Assert.Equal(3, now.Day);
Assert.Equal(4, now.Hour);
Assert.Equal(5, now.Minute);
Assert.Equal(6, now.Second);
Assert.Equal(16, now.Millisecond);
Assert.Equal(frequency, frequency2);
Assert.True(pnow2 > pnow);
}
[Fact]
public void LocalTimeZoneIsUtc()
{
var timeProvider = new FakeTimeProvider();
var localTimeZone = timeProvider.LocalTimeZone;
Assert.Equal(TimeZoneInfo.Utc, localTimeZone);
}
[Fact]
public void SetLocalTimeZoneWorks()
{
var timeProvider = new FakeTimeProvider();
var localTimeZone = timeProvider.LocalTimeZone;
Assert.Equal(TimeZoneInfo.Utc, localTimeZone);
var tz = TimeZoneInfo.CreateCustomTimeZone("DUMMY", TimeSpan.FromHours(2), null, null);
timeProvider.SetLocalTimeZone(tz);
Assert.Equal(timeProvider.LocalTimeZone, tz);
}
[Fact]
public void GetTimestampSyncWithUtcNow()
{
var timeProvider = new FakeTimeProvider(new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero));
var initialTimeUtcNow = timeProvider.GetUtcNow();
var initialTimestamp = timeProvider.GetTimestamp();
timeProvider.SetUtcNow(timeProvider.GetUtcNow().AddMilliseconds(1234));
var finalTimeUtcNow = timeProvider.GetUtcNow();
var finalTimeTimestamp = timeProvider.GetTimestamp();
var utcDelta = finalTimeUtcNow - initialTimeUtcNow;
var perfDelta = finalTimeTimestamp - initialTimestamp;
var elapsedTime = timeProvider.GetElapsedTime(initialTimestamp, finalTimeTimestamp);
Assert.Equal(1, utcDelta.Seconds);
Assert.Equal(234, utcDelta.Milliseconds);
Assert.Equal(1234D, utcDelta.TotalMilliseconds);
Assert.Equal(1.234D, (double)perfDelta / timeProvider.TimestampFrequency, 3);
Assert.Equal(1234, elapsedTime.TotalMilliseconds);
}
[Fact]
public void AdvanceGoesForward()
{
var timeProvider = new FakeTimeProvider(new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero));
var initialTimeUtcNow = timeProvider.GetUtcNow();
var initialTimestamp = timeProvider.GetTimestamp();
timeProvider.Advance(TimeSpan.FromMilliseconds(1234));
var finalTimeUtcNow = timeProvider.GetUtcNow();
var finalTimeTimestamp = timeProvider.GetTimestamp();
var utcDelta = finalTimeUtcNow - initialTimeUtcNow;
var perfDelta = finalTimeTimestamp - initialTimestamp;
var elapsedTime = timeProvider.GetElapsedTime(initialTimestamp, finalTimeTimestamp);
Assert.Equal(1, utcDelta.Seconds);
Assert.Equal(234, utcDelta.Milliseconds);
Assert.Equal(1234D, utcDelta.TotalMilliseconds);
Assert.Equal(1.234D, (double)perfDelta / timeProvider.TimestampFrequency, 3);
Assert.Equal(1234, elapsedTime.TotalMilliseconds);
}
[Fact]
public void TimeCannotGoBackwards()
{
var timeProvider = new FakeTimeProvider();
Assert.Throws<ArgumentOutOfRangeException>(() => timeProvider.Advance(TimeSpan.FromTicks(-1)));
Assert.Throws<ArgumentOutOfRangeException>(() => timeProvider.SetUtcNow(timeProvider.GetUtcNow() - TimeSpan.FromTicks(1)));
}
[Fact]
public void ToStr()
{
var dto = new DateTimeOffset(new DateTime(2022, 1, 2, 3, 4, 5, 6), TimeSpan.Zero);
var timeProvider = new FakeTimeProvider(dto);
Assert.Equal("2022-01-02T03:04:05.006", timeProvider.ToString());
}
private readonly TimeSpan _infiniteTimeout = TimeSpan.FromMilliseconds(-1);
[Fact]
public void Delay_InvalidArgs()
{
var timeProvider = new FakeTimeProvider();
_ = Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => timeProvider.Delay(TimeSpan.FromTicks(-1), CancellationToken.None));
_ = Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => timeProvider.Delay(_infiniteTimeout, CancellationToken.None));
}
[Fact]
public async Task Delay_Zero()
{
var timeProvider = new FakeTimeProvider();
var t = timeProvider.Delay(TimeSpan.Zero, CancellationToken.None);
await t;
Assert.True(t.IsCompleted && !t.IsFaulted);
}
[Fact]
public async Task Delay_Timeout()
{
var timeProvider = new FakeTimeProvider();
var delay = timeProvider.Delay(TimeSpan.FromMilliseconds(1), CancellationToken.None);
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
await delay;
Assert.True(delay.IsCompleted);
Assert.False(delay.IsFaulted);
Assert.False(delay.IsCanceled);
}
[Fact]
public async Task Delay_Cancelled()
{
var timeProvider = new FakeTimeProvider();
using var cs = new CancellationTokenSource();
var delay = timeProvider.Delay(_infiniteTimeout, cs.Token);
Assert.False(delay.IsCompleted);
cs.Cancel();
#pragma warning disable VSTHRD003 // Avoid awaiting foreign Tasks
await Assert.ThrowsAsync<TaskCanceledException>(async () => await delay);
#pragma warning restore VSTHRD003 // Avoid awaiting foreign Tasks
}
[Fact]
public async Task CreateSource()
{
var timeProvider = new FakeTimeProvider();
using var cts = timeProvider.CreateCancellationTokenSource(TimeSpan.FromMilliseconds(1));
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
await Assert.ThrowsAsync<TaskCanceledException>(() => timeProvider.Delay(TimeSpan.FromTicks(1), cts.Token));
}
[Fact]
public async Task WaitAsync()
{
var timeProvider = new FakeTimeProvider();
var source = new TaskCompletionSource<bool>();
#if NET8_0_OR_GREATER
await Assert.ThrowsAsync<TimeoutException>(() => source.Task.WaitAsync(TimeSpan.FromTicks(-1), timeProvider, CancellationToken.None));
#else
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => source.Task.WaitAsync(TimeSpan.FromTicks(-1), timeProvider, CancellationToken.None));
#endif
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => source.Task.WaitAsync(TimeSpan.FromMilliseconds(-2), timeProvider, CancellationToken.None));
var t = source.Task.WaitAsync(TimeSpan.FromSeconds(100000), timeProvider, CancellationToken.None);
while (!t.IsCompleted)
{
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
await Task.Delay(1);
_ = source.TrySetResult(true);
}
Assert.True(t.IsCompleted);
Assert.False(t.IsFaulted);
Assert.False(t.IsCanceled);
}
[Fact]
public async Task WaitAsync_InfiniteTimeout()
{
var timeProvider = new FakeTimeProvider();
var source = new TaskCompletionSource<bool>();
var t = source.Task.WaitAsync(_infiniteTimeout, timeProvider, CancellationToken.None);
while (!t.IsCompleted)
{
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
await Task.Delay(1);
_ = source.TrySetResult(true);
}
Assert.True(t.IsCompleted);
Assert.False(t.IsFaulted);
Assert.False(t.IsCanceled);
}
[Fact]
public async Task WaitAsync_Timeout()
{
var timeProvider = new FakeTimeProvider();
var source = new TaskCompletionSource<bool>();
var t = source.Task.WaitAsync(TimeSpan.FromMilliseconds(1), timeProvider, CancellationToken.None);
while (!t.IsCompleted)
{
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
await Task.Delay(1);
}
Assert.True(t.IsCompleted);
Assert.True(t.IsFaulted);
Assert.False(t.IsCanceled);
}
[Fact]
public async Task WaitAsync_Cancel()
{
var timeProvider = new FakeTimeProvider();
var source = new TaskCompletionSource<bool>();
using var cts = new CancellationTokenSource();
var t = source.Task.WaitAsync(_infiniteTimeout, timeProvider, cts.Token);
cts.Cancel();
#pragma warning disable VSTHRD003 // Avoid awaiting foreign Tasks
await Assert.ThrowsAsync<TaskCanceledException>(() => t).ConfigureAwait(false);
#pragma warning restore VSTHRD003 // Avoid awaiting foreign Tasks
}
[Fact]
public void AutoAdvance()
{
var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow)
{
AutoAdvanceAmount = TimeSpan.FromSeconds(1)
};
var first = timeProvider.GetUtcNow();
var second = timeProvider.GetUtcNow();
var third = timeProvider.GetUtcNow();
Assert.Equal(timeProvider.Start, first);
Assert.Equal(timeProvider.Start + TimeSpan.FromSeconds(1), second);
Assert.Equal(timeProvider.Start + TimeSpan.FromSeconds(2), third);
}
[Fact]
public void ToString_AutoAdvance_off()
{
var timeProvider = new FakeTimeProvider();
_ = timeProvider.ToString();
Assert.Equal(timeProvider.Start, timeProvider.GetUtcNow());
}
[Fact]
public void ToString_AutoAdvance_on()
{
var timeProvider = new FakeTimeProvider
{
AutoAdvanceAmount = TimeSpan.FromSeconds(1)
};
_ = timeProvider.ToString();
timeProvider.AutoAdvanceAmount = TimeSpan.Zero;
Assert.Equal(timeProvider.Start, timeProvider.GetUtcNow());
}
[Fact]
public void AdvanceTimeInCallback()
{
var oneSecond = TimeSpan.FromSeconds(1);
var timeProvider = new FakeTimeProvider();
var timer = timeProvider.CreateTimer(_ =>
{
// Advance the time with exactly the same amount as the period of the timer. This could lead to an
// infinite loop where this callback repeatedly gets invoked. A correct implementation however
// will adjust the timer's wake time so this won't be a problem.
timeProvider.Advance(oneSecond);
}, null, TimeSpan.Zero, oneSecond);
Assert.True(true, "Yay, we didn't enter an infinite loop!");
}
[Fact]
public void ShouldResetGateUnderLock_PreventingContextSwitching_AffectionOnTimerCallback()
{
// Arrange
var provider = new FakeTimeProvider { AutoAdvanceAmount = TimeSpan.FromSeconds(2) };
var calls = new List<object?>();
using var timer = provider.CreateTimer(calls.Add, "timer-1", TimeSpan.FromSeconds(3), TimeSpan.Zero);
var th = new Thread(() => provider.GetUtcNow());
provider.GateOpening += (_, _) =>
{
if (!th.IsAlive)
{
th.Start();
}
// use a timeout to prevent deadlock
th.Join(TimeSpan.FromMilliseconds(200));
};
// Act
provider.GetUtcNow();
th.Join();
// Assert
Assert.Single(calls);
}
}