2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2019-01-16 11:14:45 +01:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Globalization;
|
2020-06-28 10:55:27 +02:00
|
|
|
using System.Linq;
|
2019-01-16 11:14:45 +01:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
namespace BTCPayServer.Tests
|
|
|
|
{
|
|
|
|
public class MockDelay : IDelay
|
|
|
|
{
|
|
|
|
class WaitObj
|
|
|
|
{
|
|
|
|
public DateTimeOffset Expiration;
|
|
|
|
public TaskCompletionSource<bool> CTS;
|
|
|
|
}
|
|
|
|
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly List<WaitObj> waits = new List<WaitObj>();
|
2019-01-16 11:14:45 +01:00
|
|
|
DateTimeOffset _Now = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
|
|
|
public async Task Wait(TimeSpan delay, CancellationToken cancellation)
|
|
|
|
{
|
|
|
|
WaitObj w = new WaitObj();
|
|
|
|
w.Expiration = _Now + delay;
|
|
|
|
w.CTS = new TaskCompletionSource<bool>();
|
|
|
|
using (cancellation.Register(() =>
|
|
|
|
{
|
|
|
|
w.CTS.TrySetCanceled();
|
|
|
|
}))
|
|
|
|
{
|
|
|
|
lock (waits)
|
|
|
|
{
|
|
|
|
waits.Add(w);
|
|
|
|
}
|
|
|
|
await w.CTS.Task;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-05 08:16:36 +02:00
|
|
|
public async Task Advance(TimeSpan time)
|
2019-01-16 11:14:45 +01:00
|
|
|
{
|
|
|
|
_Now += time;
|
2019-04-05 08:16:36 +02:00
|
|
|
List<WaitObj> overdue = new List<WaitObj>();
|
2019-01-16 11:14:45 +01:00
|
|
|
lock (waits)
|
|
|
|
{
|
|
|
|
foreach (var wait in waits.ToArray())
|
|
|
|
{
|
|
|
|
if (_Now >= wait.Expiration)
|
|
|
|
{
|
2019-04-05 08:16:36 +02:00
|
|
|
overdue.Add(wait);
|
2019-01-16 11:14:45 +01:00
|
|
|
waits.Remove(wait);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-04-05 08:16:36 +02:00
|
|
|
foreach (var o in overdue)
|
|
|
|
o.CTS.TrySetResult(true);
|
|
|
|
try
|
|
|
|
{
|
|
|
|
await Task.WhenAll(overdue.Select(o => o.CTS.Task).ToArray());
|
|
|
|
}
|
|
|
|
catch { }
|
2019-01-16 11:14:45 +01:00
|
|
|
}
|
|
|
|
public override string ToString()
|
|
|
|
{
|
|
|
|
return _Now.Millisecond.ToString(CultureInfo.InvariantCulture);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|