Ejemplo n.º 1
0
        public Task PostAsync_NoAvailableAddress_ShouldServiceUnavailable()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(100),
                };

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync((ReceivingAddressReservation)null);

                // Act.
                var result = await Subject.PostAsync(request, cancellationToken);

                // Assert.
                var status = Assert.IsType <StatusCodeResult>(result);

                Assert.Equal((int)HttpStatusCode.ServiceUnavailable, status.StatusCode);

                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());
            }));
        }
Ejemplo n.º 2
0
        public Task ExecuteAsync_CreateWatchesAsyncReturnNonEmptyList_ShouldInvokeAddWatchesAsync()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var watch = new Watch <object>(null, TestBlock.Regtest0.GetHash());

                this.subject.StubbedCreateWatchesAsync.Setup(f => f(TestBlock.Regtest0, 0, cancellationToken))
                .Returns(Task.FromResult <IEnumerable <Watch <object> > >(new[] { watch }));

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest0, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.subject.StubbedCreateWatchesAsync.Verify(
                    f => f(TestBlock.Regtest0, 0, cancellationToken),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(It.Is <IEnumerable <Watch <object> > >(l => l.Single() == watch), cancellationToken),
                    Times.Once()
                    );
            }));
        }
Ejemplo n.º 3
0
        public Task StartAsync_WhenPostExecuteAsyncThrow_ShouldInvokeExceptionHandler()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedPostExecuteAsync
                .Setup(f => f(It.IsAny <CancellationToken>()))
                .ThrowsAsync(new Exception());

                // Act.
                await this.subject.StartAsync(cancellationToken);
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedPostExecuteAsync.Verify(
                    f => f(CancellationToken.None),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(this.subject.GetType(), It.Is <Exception>(ex => ex != null), CancellationToken.None),
                    Times.Once()
                    );
            }));
        }
Ejemplo n.º 4
0
        public async Task StopAsync_BackgroundTaskThrowException_ShouldSuccess()
        {
            await AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedExecuteAsync.Setup(f => f(It.IsAny <CancellationToken>()))
                .Returns(Task.FromException(new Exception()));

                await this.subject.StartAsync(cancellationToken);

                // Act.
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.Is <CancellationToken>(t => t != cancellationToken)),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(this.subject.GetType(), It.Is <Exception>(ex => ex != null), CancellationToken.None),
                    Times.Once()
                    );
            });
        }
        public Task ExecuteAsync_CreateContextsAsyncReturnNonEmptyList_ShouldCreateWatchesEqualToNumberOfContexts()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var ctx1 = new object();
                var ctx2 = new object();

                this.handler.Setup(h => h.CreateContextsAsync(this.block.Transactions[0], It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult <IEnumerable <object> >(new[] { ctx1, ctx2 }));

                // Act.
                await this.subject.ExecuteAsync(this.block, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.handler.Verify(
                    h => h.CreateContextsAsync(this.block.Transactions[0], cancellationToken),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(
                        It.Is <IEnumerable <TransactionWatch <object> > >(l => l.Count() == 2 && l.First().Context == ctx1 && l.Last().Context == ctx2),
                        cancellationToken
                        ),
                    Times.Once()
                    );
            }));
        }
Ejemplo n.º 6
0
        public async Task StopAsync_BackgroundTaskCanceled_ShouldSuccess()
        {
            await AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedExecuteAsync.Setup(f => f(It.IsAny <CancellationToken>()))
                .Returns <CancellationToken>(async t =>
                {
                    await Task.Delay(Timeout.InfiniteTimeSpan, t);
                    t.ThrowIfCancellationRequested();
                });

                await this.subject.StartAsync(cancellationToken);

                // Act.
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.Is <CancellationToken>(t => t != cancellationToken)),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(It.IsAny <Type>(), It.IsAny <Exception>(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            });
        }
Ejemplo n.º 7
0
        public Task PostAsync_WithValidArgs_ShouldGenerateNewAddress()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var address = new ReceivingAddress(
                    Guid.NewGuid(),
                    TestAddress.Regtest1,
                    false,
                    new Collection <ReceivingAddressReservation>());

                var request = new CreateReceivingAddressesRequest();

                this.pool
                .Setup(p => p.GenerateAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(address);

                // Act.
                var result = await this.subject.PostAsync(request, cancellationToken);

                // Assert.
                var ok = Assert.IsType <OkObjectResult>(result);
                var response = Assert.IsType <CreateReceivingAddressesResponse>(ok.Value);

                Assert.Equal(address.Address, response.Address);

                this.pool.Verify(p => p.GenerateAddressAsync(cancellationToken), Times.Once());
            }));
        }
Ejemplo n.º 8
0
        public Task StartAsync_NotStarted_ShouldStart()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Act.
                await this.subject.StartAsync(cancellationToken);
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedPreExecuteAsync.Verify(
                    f => f(It.IsNotIn(cancellationToken, CancellationToken.None)),
                    Times.Once()
                    );

                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.IsNotIn(cancellationToken, CancellationToken.None)),
                    Times.Once()
                    );

                this.subject.StubbedPostExecuteAsync.Verify(
                    f => f(CancellationToken.None),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(It.IsAny <Type>(), It.IsAny <Exception>(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 9
0
        public Task ExecuteAsync_GetBalanceChangesAsyncReturnEmptyList_ShouldNotCreateAnyWatches()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var changes = new Dictionary <BitcoinAddress, BalanceChange <object, int> >();

                this.handler.Setup(h => h.GetBalanceChangesAsync(It.IsNotNull <Transaction>(), It.IsAny <CancellationToken>()))
                .ReturnsAsync(changes);

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest0, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.handler.Verify(
                    h => h.GetBalanceChangesAsync(
                        It.IsIn <Transaction>(TestBlock.Regtest0.Transactions),
                        cancellationToken
                        ),
                    Times.Exactly(TestBlock.Regtest0.Transactions.Count)
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(
                        It.IsAny <IEnumerable <BalanceWatch <object, int> > >(),
                        It.IsAny <CancellationToken>()
                        ),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 10
0
        public Task GenerateAddressAsync_WhenInvoke_ShouldReturnGeneratedAddress()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var address = new ReceivingAddress(
                    Guid.NewGuid(),
                    TestAddress.Regtest1,
                    false,
                    new Collection <ReceivingAddressReservation>());

                this.generator
                .Setup(g => g.GenerateAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(address.Address);

                this.repository
                .Setup(r => r.AddAsync(address.Address, It.IsAny <CancellationToken>()))
                .ReturnsAsync(address);

                // Act.
                var result = await this.subject.GenerateAddressAsync(cancellationToken);

                // Assert.
                Assert.Same(address, result);

                this.generator.Verify(g => g.GenerateAsync(cancellationToken), Times.Once());
                this.repository.Verify(r => r.AddAsync(address.Address, CancellationToken.None), Times.Once());
            }));
        }
Ejemplo n.º 11
0
        public Task PostAsync_WithCallback_ShouldWatchWithCallback()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(1000),
                };

                var callback = new Callback(
                    Guid.NewGuid(),
                    IPAddress.Parse("192.168.1.2"),
                    DateTime.Now,
                    false,
                    new Uri("http://localhost/a"));

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(this.reservation);

                MockCallback(callback);

                // Act.
                var result = await Subject.PostAsync(request, cancellationToken);

                // Assert.
                var callbackId = Assert.Contains(CallbackId, ResponseHeaders);
                var accepted = Assert.IsType <AcceptedResult>(result);
                var response = Assert.IsType <ReceivingResponse>(accepted.Value);

                Assert.Equal(callback.Id.ToString(), callbackId);
                Assert.Null(accepted.Location);
                Assert.Equal(this.address.Address, response.Address);
                Assert.Equal(DateTime.UtcNow + TimeSpan.FromHours(1), response.Deadline, TimeSpan.FromSeconds(1));

                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());

                this.Callbacks.Verify(
                    r => r.AddAsync(callback.RegisteredIp, callback.Url, CancellationToken.None),
                    Times.Once());

                this.watcher.Verify(
                    w => w.StartWatchAsync(
                        this.reservation,
                        new PropertyAmount(1000),
                        6,
                        TimeSpan.FromHours(1),
                        new TokenReceivingCallback(callback, ReceivingController.TimeoutStatus),
                        CancellationToken.None),
                    Times.Once());

                this.pool.Verify(
                    p => p.ReleaseAddressAsync(this.reservation.Id, It.IsAny <CancellationToken>()),
                    Times.Never());
            }));
        }
Ejemplo n.º 12
0
        public Task ExecuteAsync_BlockRemovingAndExecuteWatchesAsyncReturnEmptyList_ShouldRemoveWatchesForThatBlock()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var watch1 = new Watch <object>(null, TestBlock.Regtest0.GetHash());
                var watch2 = new Watch <object>(null, TestBlock.Regtest1.GetHash());
                var watches = new[] { watch1, watch2 };

                this.subject.StubbedGetWatchesAsync.Setup(f => f(TestBlock.Regtest1, 1, It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult <IEnumerable <Watch <object> > >(watches));

                this.subject.StubbedExecuteWatchesAsync.Setup(f => f(watches, TestBlock.Regtest1, 1, BlockEventType.Removing, It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult <ISet <Watch <object> > >(new HashSet <Watch <object> >()));

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest1, 1, BlockEventType.Removing, cancellationToken);

                // Assert.
                this.subject.StubbedGetWatchesAsync.Verify(
                    f => f(
                        TestBlock.Regtest1,
                        1,
                        cancellationToken
                        ),
                    Times.Once()
                    );

                this.subject.StubbedExecuteWatchesAsync.Verify(
                    f => f(
                        watches,
                        TestBlock.Regtest1,
                        1,
                        BlockEventType.Removing,
                        cancellationToken
                        ),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.RemoveCompletedWatchesAsync(
                        It.IsAny <IEnumerable <Watch <object> > >(),
                        It.IsAny <CancellationToken>()
                        ),
                    Times.Never()
                    );

                this.handler.Verify(
                    h => h.RemoveUncompletedWatchesAsync(
                        TestBlock.Regtest1.GetHash(),
                        CancellationToken.None
                        ),
                    Times.Once()
                    );
            }));
        }
Ejemplo n.º 13
0
        public Task WaitAsync_WithCancellationToken_ShouldCancelWhenCancellationTokenCanceled()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async(cancellationToken, cancel) =>
            {
                // Act.
                var task = this.source.Token.WaitAsync(cancellationToken);
                cancel();

                // Assert.
                await Assert.ThrowsAsync <TaskCanceledException>(() => task);
            }, source => source.Cancel()));
        }
Ejemplo n.º 14
0
        public Task WaitAsync_WithCancellationToken_ShouldCompletedWhenCanceled()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Act.
                var task = this.source.Token.WaitAsync(cancellationToken);
                this.source.Cancel();

                // Assert.
                await task;
            }));
        }
Ejemplo n.º 15
0
        public async Task StartAsync_AlreadyStarted_ShouldThrow()
        {
            await AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Act.
                await this.subject.StartAsync(cancellationToken);

                // Assert.
                this.subject.Invoking(s => s.StartAsync(CancellationToken.None))
                .Should().ThrowExactly <InvalidOperationException>();
            });
        }
Ejemplo n.º 16
0
        public Task TryLockAddressAsync_AndHaveAnAvailable_ShouldSuccess()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var address = new ReceivingAddress(
                    Guid.NewGuid(),
                    TestAddress.Regtest1,
                    false,
                    new Collection <ReceivingAddressReservation>());

                var addresses = new[] { address };

                this.repository
                .Setup(r => r.ListAsync(AddressFilter.Available, It.IsAny <CancellationToken>()))
                .ReturnsAsync(addresses);

                this.choser
                .Setup(c => c.Choose(addresses))
                .Returns(address);

                this.repository
                .Setup(r => r.TryLockAsync(address.Id, It.IsAny <CancellationToken>()))
                .ReturnsAsync(() =>
                {
                    var reservation = new ReceivingAddressReservation(Guid.NewGuid(), address, DateTime.Now, null);

                    address.Reservations.Add(reservation);

                    return reservation;
                });

                // Act.
                var recv = await this.subject.TryLockAddressAsync(cancellationToken);

                // Assert.
                Assert.NotNull(recv);
                Assert.Equal(address, recv.Address);
                Assert.NotEqual(Guid.Empty, recv.Id);
                Assert.Null(recv.ReleasedDate);
                Assert.Equal(DateTime.Now, recv.ReservedDate, TimeSpan.FromSeconds(1));

                this.repository.Verify(
                    r => r.ListAsync(It.Is <AddressFilter>(f => f.HasFlag(AddressFilter.Available)), cancellationToken),
                    Times.Once());

                this.choser.Verify(c => c.Choose(addresses), Times.Once());
                this.repository.Verify(r => r.TryLockAsync(address.Id, cancellationToken), Times.Once());
            }));
        }
Ejemplo n.º 17
0
        public Task ReleaseAddressAsync_ReleaseFunctionInStorageShouldBeCalled()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var id = Guid.NewGuid();

                // Act.
                await this.subject.ReleaseAddressAsync(id, cancellationToken);

                // Assert.
                this.repository.Verify(r => r.ReleaseAsync(id, cancellationToken), Times.Once());
            }));
        }
Ejemplo n.º 18
0
        public Task ExecuteAsync_GetWatchesAsyncReturnEmptyList_ShouldDoNothing(BlockEventType eventType)
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedGetWatchesAsync.Setup(f => f(TestBlock.Regtest0, 0, cancellationToken))
                .Returns(Task.FromResult(Enumerable.Empty <Watch <object> >()));

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest0, 0, eventType, cancellationToken);

                // Assert.
                this.subject.StubbedGetWatchesAsync.Verify(
                    f => f(
                        TestBlock.Regtest0,
                        0,
                        cancellationToken
                        ),
                    Times.Once()
                    );

                this.subject.StubbedExecuteWatchesAsync.Verify(
                    f => f(
                        It.IsAny <IEnumerable <Watch <object> > >(),
                        It.IsAny <Block>(),
                        It.IsAny <int>(),
                        It.IsAny <BlockEventType>(),
                        It.IsAny <CancellationToken>()
                        ),
                    Times.Never()
                    );

                this.handler.Verify(
                    h => h.RemoveCompletedWatchesAsync(
                        It.IsAny <IEnumerable <Watch <object> > >(),
                        It.IsAny <CancellationToken>()
                        ),
                    Times.Never()
                    );

                this.handler.Verify(
                    h => h.RemoveUncompletedWatchesAsync(
                        It.IsAny <uint256>(),
                        It.IsAny <CancellationToken>()
                        ),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 19
0
        public Task PostAsync_ErrorWhileStoringCallback_ShouldReleaseAddressReservation()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var requester = IPAddress.Parse("192.168.1.2");
                var callback = new Uri("http://localhost/a");
                var ex = new Exception();

                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(10000),
                };

                RequestHeaders.Add(CallbackUrl, callback.ToString());
                Connection.SetupGet(c => c.RemoteIpAddress).Returns(requester);

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(this.reservation);

                this.Callbacks
                .Setup(r => r.AddAsync(It.IsAny <IPAddress>(), It.IsAny <Uri>(), It.IsAny <CancellationToken>()))
                .ThrowsAsync(ex);

                // Act.
                var result = await Assert.ThrowsAnyAsync <Exception>(
                    () => Subject.PostAsync(request, cancellationToken));

                // Assert.
                Assert.Same(ex, result);

                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());
                this.Callbacks.Verify(r => r.AddAsync(requester, callback, CancellationToken.None), Times.Once());

                this.watcher.Verify(
                    w => w.StartWatchAsync(
                        It.IsAny <ReceivingAddressReservation>(),
                        It.IsAny <PropertyAmount>(),
                        It.IsAny <int>(),
                        It.IsAny <TimeSpan>(),
                        It.IsAny <TokenReceivingCallback>(),
                        It.IsAny <CancellationToken>()),
                    Times.Never());

                this.pool.Verify(p => p.ReleaseAddressAsync(this.reservation.Id, CancellationToken.None), Times.Once());
            }));
        }
Ejemplo n.º 20
0
        public Task PostAsync_NoCallback_ShouldNotWatchWithCallback()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(100),
                };

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(this.reservation);

                // Act.
                var result = await Subject.PostAsync(request, cancellationToken);

                // Assert.
                var accepted = Assert.IsType <AcceptedResult>(result);
                var response = Assert.IsType <ReceivingResponse>(accepted.Value);

                Assert.Null(accepted.Location);
                Assert.Equal(this.address.Address, response.Address);
                Assert.Equal(DateTimeKind.Utc, response.Deadline.Kind);
                Assert.Equal(DateTime.UtcNow + TimeSpan.FromHours(1), response.Deadline, TimeSpan.FromSeconds(1));

                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());

                this.Callbacks.Verify(
                    r => r.AddAsync(It.IsAny <IPAddress>(), It.IsAny <Uri>(), It.IsAny <CancellationToken>()),
                    Times.Never());

                this.watcher.Verify(
                    w => w.StartWatchAsync(
                        this.reservation,
                        new PropertyAmount(100),
                        6,
                        TimeSpan.FromHours(1),
                        null,
                        CancellationToken.None),
                    Times.Once());

                this.pool.Verify(
                    p => p.ReleaseAddressAsync(this.reservation.Id, It.IsAny <CancellationToken>()),
                    Times.Never());
            }));
        }
Ejemplo n.º 21
0
        public Task RunAsync_WithValidArgs_ShouldInvokeProtectedRunAsync()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var exception = new Exception();

                // Act.
                await this.subject.InvokeRunAsync(typeof(FakeBackgroundService), exception, cancellationToken);

                // Assert.
                this.subject.StubbedRunAsync.Verify(
                    f => f(typeof(FakeBackgroundService), exception, cancellationToken),
                    Times.Once()
                    );
            }));
        }
        public Task ExecuteAsync_WhenGetWatchesAsyncInvoked_ShouldInvokeGetCurrentWatchesAsync()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var block = ZcoinNetworks.Instance.Regtest.GetGenesis();

                // Act.
                await this.subject.ExecuteAsync(block, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.handler.Verify(
                    h => h.GetCurrentWatchesAsync(cancellationToken),
                    Times.Once()
                    );
            }));
        }
Ejemplo n.º 23
0
        public Task PostAsync_ErrorWhileStartWatching_ShouldReleaseAddressReservation()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var ex = new Exception();

                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(5),
                };

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(this.reservation);

                this.watcher
                .Setup(w => w.StartWatchAsync(
                           It.IsAny <ReceivingAddressReservation>(),
                           It.IsAny <PropertyAmount>(),
                           It.IsAny <int>(),
                           It.IsAny <TimeSpan>(),
                           It.IsAny <TokenReceivingCallback>(),
                           It.IsAny <CancellationToken>()))
                .ThrowsAsync(ex);

                // Act.
                var result = await Assert.ThrowsAnyAsync <Exception>(
                    () => Subject.PostAsync(request, cancellationToken));

                // Assert.
                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());

                this.watcher.Verify(
                    w => w.StartWatchAsync(
                        this.reservation,
                        new PropertyAmount(5),
                        6,
                        TimeSpan.FromHours(1),
                        null,
                        CancellationToken.None),
                    Times.Once());

                this.pool.Verify(p => p.ReleaseAddressAsync(this.reservation.Id, CancellationToken.None), Times.Once());
            }));
        }
Ejemplo n.º 24
0
        public async Task StopAsync_WhenCanceled_ShouldThrow()
        {
            await AsynchronousTesting.WithCancellationTokenAsync(async (cancellationToken, cancel) =>
            {
                // Arrange.
                this.subject.StubbedExecuteAsync.Setup(f => f(It.IsAny <CancellationToken>()))
                .Returns(Task.Delay(Timeout.InfiniteTimeSpan));

                await this.subject.StartAsync(CancellationToken.None);

                // Act.
                var stop = this.subject.StopAsync(cancellationToken);

                cancel();

                // Assert.
                await Assert.ThrowsAnyAsync <OperationCanceledException>(() => stop);
            }, cancellationSource => cancellationSource.Cancel());
        }
Ejemplo n.º 25
0
        public async Task StopAsync_BackgroundTaskSucceeded_ShouldSuccess()
        {
            await AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                await this.subject.StartAsync(cancellationToken);

                // Act.
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.Is <CancellationToken>(t => t != cancellationToken)),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(It.IsAny <Type>(), It.IsAny <Exception>(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            });
        }
Ejemplo n.º 26
0
        public Task ExecuteAsync_GetBalanceChangesAsyncReturnNonEmptyList_ShouldCreateWatchesWithSameAmount()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var block = TestBlock.Regtest0;
                var ctx1 = new object();
                var ctx2 = new object();
                var changes = new Dictionary <BitcoinAddress, BalanceChange <object, int> >()
                {
                    { TestAddress.Regtest1, new BalanceChange <object, int>(ctx1, 10) },
                    { TestAddress.Regtest2, new BalanceChange <object, int>(ctx2, -10) }
                };

                this.handler.Setup(h => h.GetBalanceChangesAsync(block.Transactions[0], It.IsAny <CancellationToken>()))
                .ReturnsAsync(changes);

                // Act.
                await this.subject.ExecuteAsync(block, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.handler.Verify(
                    h => h.GetBalanceChangesAsync(block.Transactions[0], cancellationToken),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(
                        It.Is <IEnumerable <BalanceWatch <object, int> > >(
                            l => l.Count(w => w.Context == ctx1 && w.StartBlock == block.GetHash() && w.Transaction == block.Transactions[0].GetHash() && w.Address == TestAddress.Regtest1 && w.BalanceChange == 10) == 1 &&
                            l.Count(w => w.Context == ctx2 && w.StartBlock == block.GetHash() && w.Transaction == block.Transactions[0].GetHash() && w.Address == TestAddress.Regtest2 && w.BalanceChange == -10) == 1
                            ),
                        cancellationToken
                        ),
                    Times.Once()
                    );
            }));
        }
        public Task ExecuteAsync_CreateContextsAsyncReturnEmptyList_ShouldNotCreateAnyWatches()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.handler.Setup(h => h.CreateContextsAsync(this.block.Transactions[0], It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(Enumerable.Empty <object>()));

                // Act.
                await this.subject.ExecuteAsync(this.block, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.handler.Verify(
                    h => h.CreateContextsAsync(this.block.Transactions[0], cancellationToken),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(It.IsAny <IEnumerable <TransactionWatch <object> > >(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 28
0
        public Task ExecuteAsync_CreateWatchesAsyncReturnEmptyList_ShouldNotInvokeAddWatchesAsync()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedCreateWatchesAsync.Setup(f => f(It.IsAny <Block>(), It.IsAny <int>(), It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(Enumerable.Empty <Watch <object> >()));

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest0, 0, BlockEventType.Added, cancellationToken);

                // Assert.
                this.subject.StubbedCreateWatchesAsync.Verify(
                    f => f(TestBlock.Regtest0, 0, cancellationToken),
                    Times.Once()
                    );

                this.handler.Verify(
                    h => h.AddWatchesAsync(It.IsAny <IEnumerable <Watch <object> > >(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 29
0
        public Task ExecuteAsync_WithBlockRemovingAndGetWatchesAsyncReturnEmptyList_ShouldRemoveUncompletedWatches()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedGetWatchesAsync
                .Setup(f => f(TestBlock.Regtest0, 0, cancellationToken))
                .ReturnsAsync(Enumerable.Empty <Watch <object> >());

                // Act.
                await this.subject.ExecuteAsync(TestBlock.Regtest0, 0, BlockEventType.Removing, cancellationToken);

                // Assert.
                this.subject.StubbedGetWatchesAsync.Verify(
                    f => f(TestBlock.Regtest0, 0, cancellationToken),
                    Times.Once());

                this.subject.StubbedExecuteWatchesAsync.Verify(
                    f => f(
                        It.IsAny <IEnumerable <Watch <object> > >(),
                        It.IsAny <Block>(),
                        It.IsAny <int>(),
                        It.IsAny <BlockEventType>(),
                        It.IsAny <CancellationToken>()),
                    Times.Never());

                this.handler.Verify(
                    h => h.RemoveCompletedWatchesAsync(
                        It.IsAny <IEnumerable <Watch <object> > >(),
                        It.IsAny <CancellationToken>()),
                    Times.Never());

                this.handler.Verify(
                    h => h.RemoveUncompletedWatchesAsync(TestBlock.Regtest0.GetHash(), CancellationToken.None),
                    Times.Once());
            }));
        }
Ejemplo n.º 30
0
        public Task PostAsync_WithInvalidCallbackUrl_ShouldReleaseAddressReservation(string url)
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                var request = new ReceivingRequest()
                {
                    TargetAmount = new PropertyAmount(1),
                };

                RequestHeaders.Add(CallbackUrl, url);

                this.pool
                .Setup(p => p.TryLockAddressAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(this.reservation);

                // Act.
                await Assert.ThrowsAsync <InvalidCallbackUrlException>(
                    () => Subject.PostAsync(request, cancellationToken));

                // Assert.
                this.pool.Verify(p => p.TryLockAddressAsync(cancellationToken), Times.Once());

                this.watcher.Verify(
                    w => w.StartWatchAsync(
                        It.IsAny <ReceivingAddressReservation>(),
                        It.IsAny <PropertyAmount>(),
                        It.IsAny <int>(),
                        It.IsAny <TimeSpan>(),
                        It.IsAny <TokenReceivingCallback>(),
                        It.IsAny <CancellationToken>()),
                    Times.Never());

                this.pool.Verify(p => p.ReleaseAddressAsync(this.reservation.Id, CancellationToken.None), Times.Once());
            }));
        }