public async Task WhenRegisteringANewUser_ItShouldAbortUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new RegisterUserDbStatement(this.userManager.Object, testDatabase, this.requestSnapshot);

                var hashedPassword = RegistrationData.Password + "1";
                this.passwordHasher.Setup(v => v.HashPassword(RegistrationData.Password.Value)).Returns(hashedPassword);

                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(
                        UserId,
                        RegistrationData.Username,
                        RegistrationData.Email,
                        RegistrationData.ExampleWork,
                        RegistrationData.Password,
                        TimeStamp));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
Example #2
0
        public async Task WhenTaxamoAmountDoesNotEqualExpectedAmount_AndUserTypeIsTestUser_ItShouldCancelTransactionAndAbort()
        {
            this.getUserPaymentOrigin.Setup(v => v.ExecuteAsync(UserId)).ReturnsAsync(Origin);

            this.createTaxamoTransaction.Setup(v => v.ExecuteAsync(
                                                   Amount,
                                                   Origin.CountryCode,
                                                   Origin.CreditCardPrefix,
                                                   Origin.IpAddress,
                                                   Origin.OriginalTaxamoTransactionKey,
                                                   UserType.TestUser))
            .ReturnsAsync(TaxamoTransaction);

            this.deleteTaxamoTransaction.Setup(v => v.ExecuteAsync(TaxamoTransaction.Key, UserType.TestUser))
            .Returns(Task.FromResult(0))
            .Verifiable();

            await ExpectedException.AssertExceptionAsync <BadRequestException>(
                () => this.target.HandleAsync(
                    UserId,
                    PositiveInt.Parse(10),
                    PositiveInt.Parse(11),
                    UserType.TestUser));

            this.deleteTaxamoTransaction.Verify();
        }
Example #3
0
        public async Task WhenThrowsExceptionOutsideCreateCharge_ItShouldPropagateException()
        {
            this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.TestUser)).Throws(new DivideByZeroException());

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.ExecuteAsync(StripeCustomerId, Amount, UserId, TransactionReference, TaxamoTransactionKey, UserType.TestUser));
        }
        public async Task WhenUpdateAccountSettingsCalled_ItShouldAbortUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateAccountSettingsDbStatement(testDatabase, this.userManager.Object, this.requestSnapshot);
                await this.CreateUserAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                var hashedNewPassword = this.newPassword.Value + "1";
                this.passwordHasher.Setup(v => v.HashPassword(this.newPassword.Value)).Returns(hashedNewPassword);

                var expectedUser                = await this.GetUserAsync(testDatabase);
                expectedUser.UserName           = this.newUsername.Value;
                expectedUser.Email              = this.newEmail.Value;
                expectedUser.EmailConfirmed     = false;
                expectedUser.PasswordHash       = hashedNewPassword;
                expectedUser.ProfileImageFileId = this.newFileId.Value;
                expectedUser.SecurityStamp      = this.securityStamp;

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(
                        this.userId,
                        this.newUsername,
                        this.newEmail,
                        this.newPassword,
                        this.newFileId,
                        this.securityStamp));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
Example #5
0
        public async Task WhenThrowsExceptionDuringCreateCharge_ItShouldWrapAndPropagateException()
        {
            this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.TestUser)).Returns(TestKey);

            var expectedOptions = new StripeChargeCreateOptions
            {
                Amount     = Amount.Value,
                Currency   = PerformStripeCharge.Currency,
                CustomerId = StripeCustomerId,
                Metadata   = new Dictionary <string, string>
                {
                    { PerformStripeCharge.TransactionReferenceMetadataKey, TransactionReference.ToString() },
                    { PerformStripeCharge.TaxamoTransactionKeyMetadataKey, TaxamoTransactionKey },
                    { PerformStripeCharge.UserIdMetadataKey, UserId.ToString() },
                }
            };

            this.stripeService.Setup(v => v.CreateChargeAsync(
                                         It.Is <StripeChargeCreateOptions>(
                                             x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedOptions, Formatting.None)),
                                         TestKey))
            .Throws(new DivideByZeroException());

            await ExpectedException.AssertExceptionAsync <StripeChargeFailedException>(
                () => this.target.ExecuteAsync(StripeCustomerId, Amount, UserId, TransactionReference, TaxamoTransactionKey, UserType.TestUser));
        }
        public async Task WhenTransactionNotFound_ItShouldThrowException()
        {
            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task <GetCreditTransactionInformation.GetCreditTransactionResult> > >()))
            .ReturnsAsync(null);

            await ExpectedException.AssertExceptionAsync <BadRequestException>(
                () => this.target.ExecuteAsync(EnactingUserId, TransactionReference, Now, RefundCreditAmount, Reason, Comment));
        }
Example #7
0
        public async Task WhenFreePostsNotAvailable_ItShouldCompleteSuccessfully()
        {
            this.requestFreePost.Setup(v => v.ExecuteAsync(RequestorId, PostId, Timestamp, PostConstants.MaximumFreePostsPerInterval)).ReturnsAsync(false)
            .Verifiable();

            await ExpectedException.AssertExceptionAsync <RecoverableException>(
                () => this.target.ExecuteAsync(RequestorId, PostId, Now));

            this.requestFreePost.Verify();
        }
        public async Task WhenCalledAndFileDoesNotBelogToUser_ItShouldNotUpdateStorageOrQueue()
        {
            this.channelSecurity.Setup(v => v.AssertWriteAllowedAsync(UserId, ChannelId))
            .Returns(Task.FromResult(0));

            this.getFileWaitingForUpload.Setup(v => v.ExecuteAsync(FileId))
            .ReturnsAsync(new FileWaitingForUpload(FileId, new UserId(Guid.NewGuid()), "myfile", FileExtension, Purpose));

            await ExpectedException.AssertExceptionAsync <UnauthorizedException>(() =>
            {
                return(this.handler.HandleAsync(new CompleteFileUploadCommand(Requester, ChannelId, FileId)));
            });
        }
        public async Task WhenAuthorizingPostWriting_ItShouldForbidIfUserDoesNotOwnPost()
        {
            this.isPostOwner.Setup(_ => _.ExecuteAsync(UserId, PostId)).ReturnsAsync(false);

            var result = await this.target.IsWriteAllowedAsync(UserId, PostId);

            Assert.IsFalse(result);

            await ExpectedException.AssertExceptionAsync <UnauthorizedException>(() =>
            {
                return(this.target.AssertWriteAllowedAsync(UserId, PostId));
            });
        }
Example #10
0
        public async Task WhenInitiateThrowsAnException_ItShouldStopProcessingAndPropagate()
        {
            var tasks = new List <Func <Task> >();

            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task <InitializeCreditRequestResult> > >()))
            .Callback <Func <Task> >(tasks.Add)
            .ThrowsAsync(new DivideByZeroException());

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.ExecuteAsync(UserId, Now, TransactionReference, Amount, ExpectedTotalAmount, UserType.StandardUser));

            Assert.AreEqual(1, tasks.Count);
        }
        public async Task WhenNotEnoughRemainingCredit_ItShouldThrowException()
        {
            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task <GetCreditTransactionInformation.GetCreditTransactionResult> > >()))
            .ReturnsAsync(new GetCreditTransactionInformation.GetCreditTransactionResult(
                              UserId.Random(),
                              "stripeChargeId",
                              "taxamoTransactionKey",
                              100,
                              RefundCreditAmount.Value - 1));

            await ExpectedException.AssertExceptionAsync <BadRequestException>(
                () => this.target.ExecuteAsync(EnactingUserId, TransactionReference, Now, RefundCreditAmount, Reason, Comment));
        }
Example #12
0
        public async Task ItShouldAbortUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                await this.ExecuteSuccessfully(testDatabase);

                this.requestSnapshotService.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.HandleAsync(Command));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
        public async Task WhenErrorOccurs_ItShouldLogAndThrow()
        {
            var exception = new DivideByZeroException("message");

            this.createSnapshotMultiplexer.Setup(v => v.ExecuteAsync(UserId, SnapshotType.CreatorFreeAccessUsers)).Throws(exception);

            this.logger.Setup(v => v.Error(exception));

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.CreateSnapshotAsync(
                    new CreateSnapshotMessage(UserId, SnapshotType.CreatorFreeAccessUsers),
                    this.logger.Object,
                    CancellationToken));
        }
        public async Task WhenNoReleaseTimesExist_ItShouldThrowException()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new GetWeeklyReleaseScheduleDbStatement(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                await ExpectedException.AssertExceptionAsync <Exception>(() =>
                {
                    return(this.target.ExecuteAsync(QueueId));
                });

                return(ExpectedSideEffects.None);
            });
        }
        public async Task WhenInsertFailsBecauseOtherError_ItShouldRaiseError()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new RequestFreePostDbStatement(testDatabase);
                await this.CreateDataAsync(testDatabase);

                await testDatabase.TakeSnapshotAsync();

                await ExpectedException.AssertExceptionAsync <Exception>(
                    () => this.target.ExecuteAsync(RequestorId, PostId.Random(), Now, MaximumPosts));

                return(ExpectedSideEffects.None);
            });
        }
        public async Task WhenExceptionOccurs_ItShouldPropagate()
        {
            var tasks = new List <Func <Task> >();

            this.applyUserCredit.Setup(v => v.ExecuteAsync(Command.UserId, Now, TransactionReference, Command.Amount, Command.ExpectedTotalAmount, UserType.StandardUser))
            .Throws(new DivideByZeroException());

            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task> >()))
            .Callback <Func <Task> >(tasks.Add)
            .Returns(Task.FromResult(0));

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.HandleAsync(Command));

            Assert.AreEqual(0, tasks.Count);
        }
        public async Task WhenNotEnoughLiveDatesAreProvided_ItShouldThrowException()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.InitializeTarget(testDatabase);
                await this.CreatePostsAsync(testDatabase, QueueId, FutureDatesA, scheduledByQueue: true);
                await testDatabase.TakeSnapshotAsync();

                await ExpectedException.AssertExceptionAsync <ArgumentException>(() =>
                {
                    return(this.target.ExecuteAsync(QueueId, FutureDatesB.Skip(1).ToArray(), Now));
                });

                return(ExpectedSideEffects.None);
            });
        }
Example #18
0
        public async Task ItShouldAbortUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.InitializeTarget(testDatabase);
                await this.CreateEntitiesAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(CreatorId, ChannelId));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
        public async Task WhenCreateCreditRefundFails_ItShouldWrapException()
        {
            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task <GetCreditTransactionInformation.GetCreditTransactionResult> > >()))
            .ReturnsAsync(TransactionResult);

            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task <CreateTaxamoRefund.TaxamoRefundResult> > >()))
            .ReturnsAsync(TaxamoResult);

            this.retryOnTransientFailure.Setup(v => v.HandleAsync(It.IsAny <Func <Task> >()))
            .Throws(new DivideByZeroException());

            await ExpectedException.AssertExceptionAsync <FailedToRefundCreditException>(
                () => this.target.ExecuteAsync(EnactingUserId, TransactionReference, Now, RefundCreditAmount, Reason, Comment));

            this.retryOnTransientFailure.Verify(v => v.HandleAsync(It.IsAny <Func <Task> >()), Times.Once());
        }
        public async Task ItShouldAbortUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                var trackingDatabase = new TrackingConnectionFactory(testDatabase);
                this.InitializeTarget(trackingDatabase);
                await this.CreateChannelAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(UserId, ChannelId, Name, Price, IsVisibleToNonSubscribers, Now));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
        public async Task WhenNonLeaseConflictError_ItShouldPropagateException()
        {
            var blob = new Mock <ICloudBlockBlob>(MockBehavior.Strict);

            this.blobLeaseHelper.Setup(v => v.GetLeaseBlob(Fifthweek.Payments.Shared.Constants.ProcessPaymentsLeaseObjectName))
            .Returns(blob.Object);

            var exception = new DivideByZeroException();

            blob.Setup(v => v.AcquireLeaseAsync(BlockPaymentProcessingCommandHandler.LeaseLength, CommandWithProposedLeaseId.ProposedLeaseId, CancellationToken.None))
            .Throws(exception);

            this.blobLeaseHelper.Setup(v => v.IsLeaseConflictException(exception)).Returns(false);

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.HandleAsync(CommandWithProposedLeaseId));
        }
Example #22
0
        public async Task WhenProcessingAPoisonMessageAndAnErrorOccursProcessingThumbnails_ItShouldLogTheError()
        {
            this.logger.Setup(v => v.Warn("Failed to resize image from blob {0}/{1}", Message.ContainerName, Message.InputBlobName));
            this.thumbnailProcessor.Setup(v => v.CreatePoisonThumbnailSetAsync(Message, this.storageAccount.Object, this.logger.Object, CancellationToken.None))
            .Throws(new DivideByZeroException());

            this.logger.Setup(v => v.Error(It.IsAny <DivideByZeroException>())).Verifiable();

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(() => this.target.CreatePoisonThumbnailSetAsync(
                                                                                     Message,
                                                                                     this.storageAccount.Object,
                                                                                     this.logger.Object,
                                                                                     9,
                                                                                     CancellationToken.None));

            this.logger.Verify();
        }
Example #23
0
        public async Task WhenProcessingAMessageAndAnErrorOccursProcessingThumbnails_ItShouldLogTheError()
        {
            this.thumbnailProcessor.Setup(v => v.CreateThumbnailSetAsync(Message, this.input.Object, this.storageAccount.Object, this.logger.Object, CancellationToken.None))
            .ThrowsAsync(new DivideByZeroException());

            this.logger.Setup(v => v.Error(It.IsAny <DivideByZeroException>())).Verifiable();

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(() => this.target.CreateThumbnailSetAsync(
                                                                                     Message,
                                                                                     this.input.Object,
                                                                                     this.storageAccount.Object,
                                                                                     this.logger.Object,
                                                                                     9,
                                                                                     CancellationToken.None));

            this.logger.Verify();
        }
Example #24
0
        public async Task ItShouldNotUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UnsubscribeFromChannelDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(UserId, Subscriptions[0].ChannelId));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
Example #25
0
        public async Task ItShouldNotUpdateIfSnapshotFails()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateFreeAccessUsersDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase, true);
                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.ThrowException();

                await ExpectedException.AssertExceptionAsync <SnapshotException>(
                    () => this.target.ExecuteAsync(CreatorId, BlogId, null));

                return(ExpectedSideEffects.TransactionAborted);
            });
        }
Example #26
0
        public async Task WhenAnErrorOccurs_ItShouldLogAndRethrow()
        {
            var cts = new CancellationTokenSource();

            var lease = new Mock <IBlobLease>(MockBehavior.Strict);

            this.blobLeaseFactory.Setup(v => v.Create(Shared.Constants.LeaseObjectName, cts.Token))
            .Returns(lease.Object);

            lease.Setup(v => v.TryAcquireLeaseAsync()).Throws(new DivideByZeroException());

            this.logger.Setup(v => v.Error(It.IsAny <DivideByZeroException>())).Verifiable();

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(
                () => this.target.RunGarbageCollectionAsync(new RunGarbageCollectionMessage(), this.logger.Object, cts.Token));

            this.logger.Verify();
        }
Example #27
0
        public async Task WhenProcessingAPoisonMessageAndAnErrorOccursLoggingToDatabase_ItShouldLogTheError()
        {
            this.logger.Setup(v => v.Warn("Failed to resize image from blob {0}/{1}", Message.ContainerName, Message.InputBlobName));
            this.thumbnailProcessor.Setup(v => v.CreatePoisonThumbnailSetAsync(Message, this.storageAccount.Object, this.logger.Object, CancellationToken.None))
            .Returns(Task.FromResult(0)).Verifiable();
            this.setFileProcessingComplete.Setup(v => v.ExecuteAsync(Message.FileId, -9, It.IsAny <DateTime>(), It.IsAny <DateTime>(), 1, 1))
            .Throws(new DivideByZeroException());

            this.logger.Setup(v => v.Error(It.IsAny <DivideByZeroException>())).Verifiable();

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(() => this.target.CreatePoisonThumbnailSetAsync(
                                                                                     Message,
                                                                                     this.storageAccount.Object,
                                                                                     this.logger.Object,
                                                                                     9,
                                                                                     CancellationToken.None));

            this.logger.Verify();
        }
Example #28
0
        public async Task WhenProcessingAMessageAndAnErrorOccursLoggingToDatabase_ItShouldLogTheError()
        {
            this.thumbnailProcessor.Setup(v => v.CreateThumbnailSetAsync(Message, this.input.Object, this.storageAccount.Object, this.logger.Object, CancellationToken.None))
            .ReturnsAsync(new CreateThumbnailSetResult(800, 600));

            this.setFileProcessingComplete.Setup(v => v.ExecuteAsync(Message.FileId, 9, It.IsAny <DateTime>(), It.IsAny <DateTime>(), 800, 600))
            .Throws(new DivideByZeroException());

            this.logger.Setup(v => v.Error(It.IsAny <DivideByZeroException>())).Verifiable();

            await ExpectedException.AssertExceptionAsync <DivideByZeroException>(() => this.target.CreateThumbnailSetAsync(
                                                                                     Message,
                                                                                     this.input.Object,
                                                                                     this.storageAccount.Object,
                                                                                     this.logger.Object,
                                                                                     9,
                                                                                     CancellationToken.None));

            this.logger.Verify();
        }
Example #29
0
        public async Task WhenCalculatedLiveDateMatchesAnotherQueuedPostInTheCollection_ItShouldThrowOptimisticConcurrencyException()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.getLiveDateOfNewQueuedPost.Setup(_ => _.ExecuteAsync(QueueId)).ReturnsAsync(UniqueLiveDate);

                this.InitializeTarget(testDatabase);
                await this.CreateEntitiesAsync(testDatabase);
                await this.CreatePostAsync(testDatabase, ExistingFutureLiveDate);
                await this.CreateOtherPostAsync(testDatabase, UniqueLiveDate, scheduledByQueue: true, differentCollection: false);
                await testDatabase.TakeSnapshotAsync();

                await ExpectedException.AssertExceptionAsync <OptimisticConcurrencyException>(() =>
                {
                    return(this.target.ExecuteAsync(PostId, QueueId));
                });

                return(ExpectedSideEffects.None);
            });
        }
Example #30
0
        public async Task WhenQueueing_AndCalculatedLiveDateMatchesAnotherQueuedPostInTheCollection_ItShouldThrowOptimisticConcurrencyException()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                var sharedLiveDate = DateTime.UtcNow.AddDays(42);
                this.getLiveDateOfNewQueuedPost.Setup(_ => _.ExecuteAsync(QueueId)).ReturnsAsync(sharedLiveDate);

                this.InitializeTarget(testDatabase);
                await this.CreateEntitiesAsync(testDatabase);
                await this.CreatePostAsync(testDatabase, sharedLiveDate, scheduledByQueue: true, differentCollection: false);
                await testDatabase.TakeSnapshotAsync();

                var givenPost     = UnscheduledPost();
                givenPost.QueueId = QueueId.Value;
                await ExpectedException.AssertExceptionAsync <OptimisticConcurrencyException>(() =>
                {
                    return(this.target.QueuePostAsync(givenPost, PostFiles));
                });

                return(ExpectedSideEffects.TransactionAborted);
            });
        }