public void IsInvalidWhen_MatchesUnintendedEntity()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword)
                {
                    ExpiresOnUtc = DateTime.UtcNow.AddMinutes(-1),
                };
                var command = new ResetPasswordCommand
                {
                    Token = confirmation.Token,
                };
                var scenarioOptions = new ScenarioOptions
                {
                    EmailConfirmation = confirmation,
                    Command = command,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");
                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(string.Format(
                    ValidateEmailConfirmation.FailedBecauseIntentWasIncorrect,
                        confirmation.Intent, confirmation.Token));
                // ReSharper restore PossibleNullReferenceException
            }
            public void IsInvalidWhen_MatchesNoEntity()
            {
                var command = new ResetPasswordCommand
                {
                    Token = Guid.NewGuid()
                };
                var scenarioOptions = new ScenarioOptions
                {
                    Command = command,
                    EmailConfirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword),
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");
                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(string.Format(
                    ValidateEmailConfirmation.FailedBecauseTokenMatchedNoEntity,
                        command.Token));
                // ReSharper restore PossibleNullReferenceException
            }
            public void ExecutesNoQuery_WhenEmailArgIsNull()
            {
                var scenarioOptions = new ScenarioOptions();
                var controller = CreateController(scenarioOptions);

                controller.ByEmail(null);

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                    It.Is(PersonQueryBasedOn(null))),
                        Times.Never());
            }
            public void ExecutesQuery_ToGetPersonByEmail()
            {
                const string email = "test";
                var scenarioOptions = new ScenarioOptions();
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                    It.Is(PersonQueryBasedOn(email))))
                    .Returns(null as Person);

                controller.ByEmail(email);

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                    It.Is(PersonQueryBasedOn(email))),
                        Times.Once());
            }
            public void GeneratesSecretCode_WithTwelveCharacters()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.ResetPassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.OutConfirmation.SecretCode.Length.ShouldEqual(12);
            }
            public void IsInvalidWhen_IsNull()
            {
                var command = new SendConfirmEmailMessageCommand();
                var scenarioOptions = new ScenarioOptions();
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == PropertyName);
                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(
                    ValidateEmailAddress.FailedBecauseValueWasEmpty);
                // ReSharper restore PossibleNullReferenceException
            }
            public void ExecutesQuery_ForPerson()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.ResetPassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.Entities.Verify(m => m.Get<Person>(),
                    Times.Once());
            }
            public void IsInvalidWhen_IsEmpty()
            {
                var command = new RedeemEmailConfirmationCommand { Token = Guid.Empty };
                var scenarioOptions = new ScenarioOptions();
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");
                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(string.Format(
                    ValidateEmailConfirmation.FailedBecauseTokenWasEmpty,
                        Guid.Empty));
                // ReSharper restore PossibleNullReferenceException
            }
            public void ThrowsNullReferenceException_WhenUserIsNull()
            {
                var scenarioOptions = new ScenarioOptions();
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(It.IsAny<GetMyEmailAddressByNumberQuery>()))
                    .Returns(null as EmailAddress);
                NullReferenceException exception = null;

                try
                {
                    controller.Get();
                }
                catch (NullReferenceException ex)
                {
                    exception = ex;
                }

                exception.ShouldNotBeNull();
            }
Exemple #10
0
            public void CreatesConfrimation_With_EmailAddres_Intent_AndSecretCode()
            {
                const string emailAddress = "someone";
                var          command      = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent       = EmailConfirmationIntent.CreatePassword,
                    SendFromUrl  = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler         = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.Entities.Verify(m => m.
                                                Create(It.Is(ConfirmationEntityBasedOn(scenarioOptions))),
                                                Times.Once());
                scenarioOptions.OutConfirmation.EmailAddress.ShouldEqual(scenarioOptions.Person.GetEmail(emailAddress));
                scenarioOptions.OutConfirmation.Intent.ShouldEqual(command.Intent);
            }
            public void CreatesConfrimation_With_EmailAddres_Intent_AndSecretCode()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.CreatePassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.Entities.Verify(m => m.
                    Create(It.Is(ConfirmationEntityBasedOn(scenarioOptions))),
                    Times.Once());
                scenarioOptions.OutConfirmation.EmailAddress.ShouldEqual(scenarioOptions.Person.GetEmail(emailAddress));
                scenarioOptions.OutConfirmation.Intent.ShouldEqual(command.Intent);
            }
Exemple #12
0
            public void IsInvalidWhen_IsEmptyString()
            {
                var command = new ResetPasswordCommand {
                    Ticket = string.Empty
                };
                var scenarioOptions = new ScenarioOptions();
                var validator       = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Ticket");

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(
                    ValidateEmailConfirmation.FailedBecauseTicketWasEmpty);
                // ReSharper restore PossibleNullReferenceException
            }
Exemple #13
0
            public void ReturnsJson_WithEmptyData_WhenPeopleAreNotFound()
            {
                const string term            = "test";
                var          scenarioOptions = new ScenarioOptions();
                var          controller      = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                                                             It.Is(PeopleWithLastNameQueryBasedOn(term))))
                .Returns(new Person[] { });

                var result = controller.WithLastName(term);

                result.ShouldNotBeNull();
                result.ShouldBeType <JsonResult>();
                result.Data.ShouldNotBeNull();
                result.Data.ShouldBeType <PersonInfoModel[]>();
                var models = (PersonInfoModel[])result.Data;

                models.Length.ShouldEqual(0);
            }
Exemple #14
0
            public void IsInvalidWhen_IsNotEmailAddress()
            {
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = "user@domain.",
                };
                var scenarioOptions = new ScenarioOptions();
                var validator       = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == PropertyName);

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(
                    ValidateEmailAddress.FailedBecauseValueWasNotValidEmailAddress);
                // ReSharper restore PossibleNullReferenceException
            }
Exemple #15
0
            public void IsValidWhen_PasswordIsIncorrectLength()
            {
                var command = new ResetPasswordCommand
                {
                    Password             = "******",
                    PasswordConfirmation = "1234",
                };
                var scenarioOptions = new ScenarioOptions
                {
                    MinimumPasswordLength = 6,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "PasswordConfirmation");

                error.ShouldBeNull();
            }
Exemple #16
0
            public void ReturnsJson_WithIEnumerable_IncludingNullValueLabel_AsTopResult()
            {
                var scenarioOptions = new ScenarioOptions();
                var controller      = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(It.Is(FindDistinctSuffixesQuery)))
                .Returns(null as string[]);

                var result = controller.AutoCompleteSuffixes(null);

                result.ShouldNotBeNull();
                result.ShouldBeType <JsonResult>();
                result.Data.ShouldImplement <IEnumerable <object> >();
                var     enumerable = (IEnumerable <object>)result.Data;
                dynamic item       = enumerable.First();
                string  value      = item.value;
                string  label      = item.label;

                value.ShouldEqual(string.Empty);
                label.ShouldEqual(PersonNameController.SalutationAndSuffixNullValueLabel);
            }
Exemple #17
0
            public void IsInvalidWhen_MatchesNoEstablishment()
            {
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = "*****@*****.**",
                };
                var person = new Person
                {
                    DisplayName = "Adam West",
                    Emails      = new Collection <EmailAddress>
                    {
                        new EmailAddress {
                            Value = command.EmailAddress,
                        },
                    },
                };
                var scenarioOptions = new ScenarioOptions
                {
                    Command       = command,
                    Person        = person,
                    Establishment = new Establishment
                    {
                        EmailDomains = new Collection <EstablishmentEmailDomain>(),
                    },
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == PropertyName);

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(string.Format(
                                                   ValidateEstablishment.FailedBecauseEmailMatchedNoEntity,
                                                   command.EmailAddress));
                // ReSharper restore PossibleNullReferenceException
            }
Exemple #18
0
            public void IsInvalidWhen_DoesNotEqualPassword_AndPasswordIsValid()
            {
                var command = new ResetPasswordCommand
                {
                    Password             = "******",
                    PasswordConfirmation = "12345",
                };
                var scenarioOptions = new ScenarioOptions();
                var validator       = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "PasswordConfirmation");

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(
                    ValidatePassword.FailedBecausePasswordConfirmationDidNotEqualPassword);
                // ReSharper restore PossibleNullReferenceException
            }
Exemple #19
0
        private static SendConfirmEmailMessageValidator CreateValidator(ScenarioOptions scenarioOptions = null)
        {
            scenarioOptions = scenarioOptions ?? new ScenarioOptions();
            var entities = new Mock <IQueryEntities>(MockBehavior.Strict).Initialize();

            if (scenarioOptions.Command != null)
            {
                entities.Setup(m => m.Query <Person>()).Returns(new[] { scenarioOptions.Person }.AsQueryable);
                entities.Setup(m => m.Query <Establishment>()).Returns(new[] { scenarioOptions.Establishment }.AsQueryable);
            }
            var passwords = new Mock <IStorePasswords>(MockBehavior.Strict);

            if (scenarioOptions.Person != null &&
                scenarioOptions.Person.User != null &&
                !string.IsNullOrWhiteSpace(scenarioOptions.Person.User.Name))
            {
                passwords.Setup(m => m
                                .Exists(scenarioOptions.Person.User.Name))
                .Returns(scenarioOptions.LocalMemberExists);
            }
            return(new SendConfirmEmailMessageValidator(entities.Object, passwords.Object));
        }
Exemple #20
0
            public void IsInvalidWhen_MatchesNoUser()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword)
                {
                    RedeemedOnUtc = DateTime.UtcNow,
                    ExpiresOnUtc  = DateTime.UtcNow.AddMinutes(1),
                    EmailAddress  = new EmailAddress
                    {
                        IsConfirmed = true,
                        Person      = new Person
                        {
                            DisplayName = "Adam West"
                        }
                    }
                };
                var command = new ResetPasswordCommand
                {
                    Token = confirmation.Token,
                };
                var scenarioOptions = new ScenarioOptions
                {
                    EmailConfirmation = confirmation,
                    Command           = command,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(string.Format(
                                                   ValidatePerson.FailedBecauseUserWasNull,
                                                   confirmation.EmailAddress.Person.DisplayName));
                // ReSharper restore PossibleNullReferenceException
            }
            public void ExecutesQuery_ToGenerateDisplayName()
            {
                var model = new GenerateDisplayNameForm
                {
                    Salutation = "Mr",
                    FirstName = "Adam",
                    MiddleName = "B",
                    LastName = "West",
                    Suffix = "Sr.",
                };
                var scenarioOptions = new ScenarioOptions();
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                    It.Is(GenerateDisplayNameQueryBasedOn(model))))
                    .Returns("derived display name");

                controller.GenerateDisplayName(model);

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                    It.Is(GenerateDisplayNameQueryBasedOn(model))),
                        Times.Once());
            }
            public void IsValidWhen_IsNotEmpty_AndMatchesEntity_Unexpired_UnRedeemed_Unretired()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword)
                {
                    ExpiresOnUtc = DateTime.UtcNow.AddMinutes(1),
                };
                var command = new RedeemEmailConfirmationCommand
                {
                    Token = confirmation.Token,
                };
                var scenarioOptions = new ScenarioOptions
                {
                    EmailConfirmation = confirmation,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");

                error.ShouldBeNull();
            }
        private static MyHomeController CreateController(ScenarioOptions scenarioOptions = null)
        {
            scenarioOptions = scenarioOptions ?? new ScenarioOptions();

            scenarioOptions.MockQueryProcessor = new Mock <IProcessQueries>(MockBehavior.Strict);

            var services = new MyHomeServices(scenarioOptions.MockQueryProcessor.Object);

            var controller = new MyHomeController(services);

            var builder = ReuseMock.TestControllerBuilder();

            builder.HttpContext.User = null;
            if (!string.IsNullOrWhiteSpace(scenarioOptions.PrincipalIdentityName))
            {
                builder.HttpContext.User = scenarioOptions.PrincipalIdentityName.AsPrincipal();
            }

            builder.InitializeController(controller);

            return(controller);
        }
Exemple #24
0
            public void ReturnsView_WhenEmailAddress_IsFound()
            {
                const int    number          = 2;
                const string userName        = "******";
                var          scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = userName,
                };
                var controller = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(It.Is(EmailQueryBasedOn(number, userName))))
                .Returns(new EmailAddress());

                var result = controller.Get(number);

                result.ShouldNotBeNull();
                result.ShouldBeType <ViewResult>();
                var viewResult = (ViewResult)result;

                viewResult.Model.ShouldNotBeNull();
                viewResult.Model.ShouldBeType <UpdateEmailValueForm>();
            }
Exemple #25
0
            public void ExecutesQuery_ToGenerateDisplayName()
            {
                var model = new GenerateDisplayNameForm
                {
                    Salutation = "Mr",
                    FirstName  = "Adam",
                    MiddleName = "B",
                    LastName   = "West",
                    Suffix     = "Sr.",
                };
                var scenarioOptions = new ScenarioOptions();
                var controller      = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                                                             It.Is(GenerateDisplayNameQueryBasedOn(model))))
                .Returns("derived display name");

                controller.GenerateDisplayName(model);

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                                                              It.Is(GenerateDisplayNameQueryBasedOn(model))),
                                                          Times.Once());
            }
Exemple #26
0
            public void IsInvalidWhen_Length_IsLessThanSixCharacters()
            {
                var command = new ResetPasswordCommand {
                    Password = "******"
                };
                var scenarioOptions = new ScenarioOptions
                {
                    MinimumPasswordLength = 6,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                results.IsValid.ShouldBeFalse();
                results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Password");

                error.ShouldNotBeNull();
                // ReSharper disable PossibleNullReferenceException
                error.ErrorMessage.ShouldEqual(
                    ValidatePassword.FailedBecausePasswordWasTooShort(6));
                // ReSharper restore PossibleNullReferenceException
            }
Exemple #27
0
            public void ReturnsJson_WithPersonInfoModelData_WhenPersonIsFound()
            {
                var guid            = Guid.NewGuid();
                var scenarioOptions = new ScenarioOptions();
                var controller      = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                                                             It.Is(PersonQueryBasedOn(guid))))
                .Returns(new Person
                {
                    EntityId = guid,
                });

                var result = controller.ByGuid(guid);

                result.ShouldNotBeNull();
                result.ShouldBeType <JsonResult>();
                result.Data.ShouldNotBeNull();
                result.Data.ShouldBeType <PersonInfoModel>();
                var model = (PersonInfoModel)result.Data;

                model.EntityId.ShouldEqual(guid);
            }
Exemple #28
0
            public void ReturnsJson_WithGeneratedDisplayName()
            {
                const string generatedDisplayName = "generated display name";
                var          model = new GenerateDisplayNameForm
                {
                    Salutation = "Mr",
                    FirstName  = "Adam",
                    MiddleName = "B",
                    LastName   = "West",
                    Suffix     = "Sr.",
                };
                var scenarioOptions = new ScenarioOptions();
                var controller      = CreateController(scenarioOptions);

                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                                                             It.Is(GenerateDisplayNameQueryBasedOn(model))))
                .Returns(generatedDisplayName);

                var result = controller.GenerateDisplayName(model);

                result.ShouldNotBeNull();
                result.ShouldBeType <JsonResult>();
                result.Data.ShouldEqual(generatedDisplayName);
            }
Exemple #29
0
            public void IsValidWhen_MatchesEntity_Intended_Unexpired_Unretired_Redeemed_WithNonSamlLocalUser()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword)
                {
                    ExpiresOnUtc  = DateTime.UtcNow.AddMinutes(1),
                    RedeemedOnUtc = DateTime.UtcNow,
                    EmailAddress  = new EmailAddress
                    {
                        IsConfirmed = true,
                        Person      = new Person
                        {
                            User = new User
                            {
                                Name = "local"
                            }
                        }
                    }
                };
                var command = new ResetPasswordCommand
                {
                    Token = confirmation.Token,
                };
                var scenarioOptions = new ScenarioOptions
                {
                    Command           = command,
                    EmailConfirmation = confirmation,
                    LocalMemberExists = true,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token");

                error.ShouldBeNull();
            }
Exemple #30
0
            public void IsValidWhen_IsNotEmpty_AndIsCorrectMatch()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword)
                {
                    Ticket = "tomato",
                };
                var command = new ResetPasswordCommand
                {
                    Token  = confirmation.Token,
                    Ticket = "tomato"
                };
                var scenarioOptions = new ScenarioOptions
                {
                    EmailConfirmation = confirmation,
                    Command           = command,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Ticket");

                error.ShouldBeNull();
            }
            public void IsValidWhen_IsCorrectMatch()
            {
                var confirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword)
                {
                    SecretCode = "tomato",
                };
                var command = new RedeemEmailConfirmationCommand
                {
                    Token      = confirmation.Token,
                    SecretCode = "tomato",
                    Intent     = EmailConfirmationIntent.CreatePassword,
                };
                var scenarioOptions = new ScenarioOptions
                {
                    EmailConfirmation = confirmation,
                };
                var validator = CreateValidator(scenarioOptions);

                var results = validator.Validate(command);

                var error = results.Errors.SingleOrDefault(e => e.PropertyName == "SecretCode");

                error.ShouldBeNull();
            }
        private static UpdateNameController CreateController(ScenarioOptions scenarioOptions = null)
        {
            scenarioOptions = scenarioOptions ?? new ScenarioOptions();

            scenarioOptions.MockQueryProcessor = new Mock <IProcessQueries>(MockBehavior.Strict);

            scenarioOptions.MockCommandHandler = new Mock <IHandleCommands <UpdateMyNameCommand> >(MockBehavior.Strict);

            var services = new UpdateNameServices(scenarioOptions.MockQueryProcessor.Object, scenarioOptions.MockCommandHandler.Object);

            var controller = new UpdateNameController(services);

            var builder = ReuseMock.TestControllerBuilder();

            if (!string.IsNullOrWhiteSpace(scenarioOptions.PrincipalIdentityName))
            {
                builder.HttpContext.User = scenarioOptions.PrincipalIdentityName.AsPrincipal();
            }

            builder.InitializeController(controller);

            if (scenarioOptions.IsChildAction)
            {
                var controllerContext = new Mock <ControllerContext>(MockBehavior.Strict);
                var parentContext     = new ViewContext {
                    TempData = new TempDataDictionary()
                };
                builder.RouteData.DataTokens.Add("ParentActionViewContext", parentContext);
                controllerContext.Setup(p => p.IsChildAction).Returns(true);
                controllerContext.Setup(p => p.HttpContext).Returns(builder.HttpContext);
                controllerContext.Setup(p => p.RouteData).Returns(builder.RouteData);
                controller.ControllerContext = controllerContext.Object;
            }

            return(controller);
        }
            public void ExecutesQuery_ForAffiliation_ByPrincipalAndEstablishmentId()
            {
                const int establishmentId = 2;
                const string userName = "******";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = userName,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                    It.Is(AffiliationQueryBasedOn(userName, establishmentId))))
                        .Returns(null as Affiliation);

                controller.Get(establishmentId);

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                    It.Is(AffiliationQueryBasedOn(userName, establishmentId))),
                        Times.Once());
            }
        private static UpdateAffiliationController CreateController(ScenarioOptions scenarioOptions = null)
        {
            scenarioOptions = scenarioOptions ?? new ScenarioOptions();

            scenarioOptions.MockQueryProcessor = new Mock<IProcessQueries>(MockBehavior.Strict);

            scenarioOptions.MockCommandHandler = new Mock<IHandleCommands<UpdateMyAffiliationCommand>>(MockBehavior.Strict);

            var services = new UpdateAffiliationServices(scenarioOptions.MockQueryProcessor.Object, scenarioOptions.MockCommandHandler.Object);

            var controller = new UpdateAffiliationController(services);

            var builder = ReuseMock.TestControllerBuilder();

            builder.HttpContext.User = null;
            if (!string.IsNullOrWhiteSpace(scenarioOptions.PrincipalIdentityName))
            {
                var principal = scenarioOptions.PrincipalIdentityName.AsPrincipal();
                builder.HttpContext.User = principal;
            }

            builder.InitializeController(controller);

            return controller;
        }
            public void ReturnsRedirect_ToModelReturnUrl_AfterCommandIsExecuted()
            {
                const string principalIdentityName = "*****@*****.**";
                const int establishmentId = 8;
                const string jobTitles = "job titles";
                const EmployeeOrStudentAffiliate employeeOrStudentAffiliation
                    = EmployeeOrStudentAffiliate.StudentOnly;
                const string returnUrl = "http://www.site.tld";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = principalIdentityName,
                };
                var model = new UpdateAffiliationForm
                {
                    JobTitles = jobTitles,
                    EstablishmentId = establishmentId,
                    EmployeeOrStudentAffiliation = employeeOrStudentAffiliation,
                    IsClaimingStaff = true,
                    ReturnUrl = returnUrl,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockCommandHandler.Setup(m => m.Handle(
                    It.Is(CommandBasedOn(model, principalIdentityName))));

                var result = controller.Put(model);

                result.ShouldNotBeNull();
                result.ShouldBeType<RedirectResult>();
                var redirectResult = (RedirectResult)result;
                redirectResult.Url.ShouldEqual(model.ReturnUrl);
                redirectResult.Permanent.ShouldBeFalse();
            }
Exemple #36
0
 private static Expression <Func <ComposeEmailMessageQuery, bool> > CompositionQueryBasedOn(ScenarioOptions scenarioOptions)
 {
     return(q =>
            q.Template == scenarioOptions.EmailTemplate &&
            q.ToEmailAddress == scenarioOptions.Person.GetEmail(scenarioOptions.Command.EmailAddress)
            );
 }
Exemple #37
0
 public virtual Task <SpeechToTextResponse> SpeechToTextAsync(Stream audioStream, ScenarioOptions scenario,
                                                              SpeechLocaleOptions locale, SpeechOsOptions os, Guid fromDeviceId, int maxnbest = 1, int profanitycheck = 1)
 {
     return(PolicyService.ExecuteRetryAndCapture400Errors(
                "SpeechService.SpeechToTextAsync",
                ApiKeys.SpeechRetryInSeconds,
                () =>
     {
         var result = SpeechRepository.SpeechToTextAsync(audioStream, scenario, locale, os, fromDeviceId, maxnbest, profanitycheck);
         return result;
     },
                null));
 }
Exemple #38
0
 protected virtual string GetSpeechToTextUrl(ScenarioOptions scenario, SpeechLocaleOptions locale, SpeechOsOptions os, Guid fromDeviceId, int maxnbest, int profanitycheck)
 {
     return($"{ApiKeys.SpeechEndpoint}recognize?version=3.0&scenarios={scenario}&appid=D4D52672-91D7-4C74-8AD8-42B1D98141A5&requestid={Guid.NewGuid()}&format=json&locale={locale}&device.os={os}&instanceid={fromDeviceId}&maxnbest={maxnbest}&result.profanitymarkup={profanitycheck}");
 }
        private static SendConfirmEmailMessageHandler CreateHandler(ScenarioOptions scenarioOptions)
        {
            var queryProcessor = new Mock<IProcessQueries>(MockBehavior.Strict);
            scenarioOptions.QueryProcessor = queryProcessor;
            queryProcessor.Setup(m => m
                .Execute(It.Is(EmailTemplateQueryBasedOn(scenarioOptions.Command))))
                .Returns(scenarioOptions.EmailTemplate);
            queryProcessor.Setup(m => m
                .Execute(It.Is(FormattersQueryBasedOn(scenarioOptions))))
                .Returns(null as IDictionary<string, string>);
            queryProcessor.Setup(m => m
                .Execute(It.Is(CompositionQueryBasedOn(scenarioOptions))))
                .Returns(scenarioOptions.EmailMessage);

            var entities = new Mock<ICommandEntities>(MockBehavior.Strict).Initialize();
            scenarioOptions.Entities = entities;
            entities.Setup(m => m.Get<Person>()).Returns(new[] { scenarioOptions.Person }.AsQueryable);
            entities.Setup(m => m.Create(It.Is(ConfirmationEntityBasedOn(scenarioOptions))))
                .Callback((Entity entity) => scenarioOptions.OutConfirmation = (EmailConfirmation)entity);
            entities.Setup(m => m.Create(It.Is(MessageEntityBasedOn(scenarioOptions))));

            var nestedHandler = new Mock<IHandleCommands<SendEmailMessageCommand>>(MockBehavior.Strict);
            scenarioOptions.NestedHandler = nestedHandler;
            nestedHandler.Setup(m => m.Handle(It.Is(NestedCommandBasedOn(scenarioOptions))));

            return new SendConfirmEmailMessageHandler(queryProcessor.Object, entities.Object, nestedHandler.Object);
        }
Exemple #40
0
 internal Scenario(ScenarioOptions options) : this(options.Client, options.LogMessage,
                                                   options.BadRequestProvider, options.Services, options.MaxApiResponseTime)
 {
 }
            public void ExecutesQuery_ForUser_ByName()
            {
                const string userName = "******";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = userName,
                };
                Expression<Func<GetUserByNameQuery, bool>> userByNameQuery =
                    query => query.Name == userName;
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(It.Is(userByNameQuery)))
                    .Returns(null as User);

                controller.Get();

                scenarioOptions.MockQueryProcessor.Verify(m => m.Execute(
                    It.Is(userByNameQuery)),
                        Times.Once());
            }
Exemple #42
0
 private static Expression <Func <SendEmailMessageCommand, bool> > NestedCommandBasedOn(ScenarioOptions scenarioOptions)
 {
     return(c =>
            c.PersonId == scenarioOptions.EmailMessage.ToPerson.RevisionId &&
            c.MessageNumber == scenarioOptions.EmailMessage.Number
            );
 }
Exemple #43
0
 internal Scenario(ScenarioOptions options, EventAggregator eventAggregator) : this(options.Client,
                                                                                    options.LogMessage,
                                                                                    options.BadRequestProvider, options.Services, options.MaxApiResponseTime, eventAggregator,
                                                                                    options.JsonDeserializeOptions, options.JsonSerializeOptions)
 {
 }
            public void CreatesEmailMessage()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.CreatePassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.Entities.Verify(m => m.
                    Create(It.Is(MessageEntityBasedOn(scenarioOptions))),
                    Times.Once());
            }
 private static Expression<Func<ComposeEmailMessageQuery, bool>> CompositionQueryBasedOn(ScenarioOptions scenarioOptions)
 {
     return q =>
            q.Template == scenarioOptions.EmailTemplate &&
            q.ToEmailAddress == scenarioOptions.Person.GetEmail(scenarioOptions.Command.EmailAddress)
     ;
 }
Exemple #46
0
        /// <summary>
        /// This transcribes voice queries
        /// </summary>
        /// <param name="audioStream">Audio stream</param>
        /// <param name="scenario">The context for performing a recognition.</param>
        /// <param name="locale">Language code of the audio content in IETF RFC 5646. Case does not matter. </param>
        /// <param name="os">Operating system the client is running on. This is an open field but we encourage clients to use it consistently across devices and applications.</param>
        /// <param name="fromDeviceId">A globally unique device identifier of the device making the request.</param>
        /// <param name="maxnbest">Maximum number of results the voice application API should return. The default is 1. The maximum is 5. Example: maxnbest=3</param>
        /// <param name="profanitycheck">Scan the result text for words included in an offensive word list. If found, the word will be delimited by bad word tag. Example: result.profanity=1 (0 means off, 1 means on, default is 1.)</param>
        public virtual async Task <SpeechToTextResponse> SpeechToTextAsync(Stream audioStream, ScenarioOptions scenario, SpeechLocaleOptions locale, SpeechOsOptions os, Guid fromDeviceId, int maxnbest = 1, int profanitycheck = 1)
        {
            string url   = GetSpeechToTextUrl(scenario, locale, os, fromDeviceId, maxnbest, profanitycheck);
            string token = GetSpeechToken();

            byte[] data = RepositoryClient.GetByteArray(audioStream);

            var response = await RepositoryClient.SendAsync(ApiKeys.Speech, url, data, contentType, "POST", token, true, "speech.platform.bing.com");

            return(JsonConvert.DeserializeObject <SpeechToTextResponse>(response));
        }
            public void ExecutesQuery_ToComposeEmailMessage()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.CreatePassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.QueryProcessor.Verify(m => m.
                    Execute(It.Is(CompositionQueryBasedOn(scenarioOptions))),
                    Times.Once());
            }
 private static Expression<Func<EmailMessage, bool>> MessageEntityBasedOn(ScenarioOptions scenarioOptions)
 {
     return e => e == scenarioOptions.EmailMessage;
 }
            public void InvokesNestedHandler()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.ResetPassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                scenarioOptions.NestedHandler.Verify(m => m.
                    Handle(It.Is(NestedCommandBasedOn(scenarioOptions))),
                    Times.Once());
            }
Exemple #50
0
 private static Expression <Func <EmailMessage, bool> > MessageEntityBasedOn(ScenarioOptions scenarioOptions)
 {
     return(e => e == scenarioOptions.EmailMessage);
 }
 private static Expression<Func<GetConfirmEmailFormattersQuery, bool>> FormattersQueryBasedOn(ScenarioOptions scenarioOptions)
 {
     return e =>
         e.Confirmation.EmailAddress == scenarioOptions.Person.GetEmail(scenarioOptions.Command.EmailAddress) &&
         e.Confirmation.Intent == scenarioOptions.Command.Intent
     ;
 }
            public void Returns404_WhenAffiliation_CannotBeFound()
            {
                const int establishmentId = 2;
                const string userName = "******";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = userName,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                    It.Is(AffiliationQueryBasedOn(userName, establishmentId))))
                        .Returns(null as Affiliation);

                var result = controller.Get(establishmentId);

                result.ShouldNotBeNull();
                result.ShouldBeType<HttpNotFoundResult>();
            }
 private static Expression<Func<EmailConfirmation, bool>> ConfirmationEntityBasedOn(ScenarioOptions scenarioOptions)
 {
     return e =>
         e.EmailAddress == scenarioOptions.Person.GetEmail(scenarioOptions.Command.EmailAddress) &&
         e.Intent == scenarioOptions.Command.Intent
     ;
 }
            public void ReturnsView_WhenAffiliation_IsFound()
            {
                const int establishmentId = 2;
                const string userName = "******";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = userName,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockQueryProcessor.Setup(m => m.Execute(
                    It.Is(AffiliationQueryBasedOn(userName, establishmentId))))
                        .Returns(new Affiliation
                        {
                            Establishment = new Establishment
                            {
                                Type = new EstablishmentType
                                {
                                    Category = new EstablishmentCategory
                                    {
                                        Code = EstablishmentCategoryCode.Inst
                                    }
                                }
                            }
                        });

                var result = controller.Get(establishmentId);

                result.ShouldNotBeNull();
                result.ShouldBeType<ViewResult>();
                var viewResult = (ViewResult)result;
                viewResult.Model.ShouldNotBeNull();
                viewResult.Model.ShouldBeType<UpdateAffiliationForm>();
            }
 private static Expression<Func<SendEmailMessageCommand, bool>> NestedCommandBasedOn(ScenarioOptions scenarioOptions)
 {
     return c =>
         c.PersonId == scenarioOptions.EmailMessage.ToPerson.RevisionId &&
         c.MessageNumber == scenarioOptions.EmailMessage.Number
     ;
 }
            public void ReturnsView_WhenModelState_IsInvalid()
            {
                var scenarioOptions = new ScenarioOptions();
                var model = new UpdateAffiliationForm();
                var controller = CreateController(scenarioOptions);
                controller.ModelState.AddModelError("error", "message");

                var result = controller.Put(model);

                result.ShouldNotBeNull();
                result.ShouldBeType<ViewResult>();
                var viewResult = (ViewResult)result;
                viewResult.Model.ShouldNotBeNull();
                viewResult.Model.ShouldBeType<UpdateAffiliationForm>();
                viewResult.Model.ShouldEqual(model);
            }
Exemple #57
0
 private static Expression <Func <EmailConfirmation, bool> > ConfirmationEntityBasedOn(ScenarioOptions scenarioOptions)
 {
     return(e =>
            e.EmailAddress == scenarioOptions.Person.GetEmail(scenarioOptions.Command.EmailAddress) &&
            e.Intent == scenarioOptions.Command.Intent
            );
 }
            public void ExecutesCommand_WhenAction_IsValid()
            {
                const string principalIdentityName = "*****@*****.**";
                const int establishmentId = 8;
                const string jobTitles = "job titles";
                const EmployeeOrStudentAffiliate employeeOrStudentAffiliation
                    = EmployeeOrStudentAffiliate.StudentOnly;
                const string returnUrl = "http://www.site.tld";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = principalIdentityName,
                };
                var model = new UpdateAffiliationForm
                {
                    JobTitles = jobTitles,
                    EstablishmentId = establishmentId,
                    EmployeeOrStudentAffiliation = employeeOrStudentAffiliation,
                    IsClaimingInternationalOffice = true,
                    ReturnUrl = returnUrl,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockCommandHandler.Setup(m => m.Handle(
                    It.Is(CommandBasedOn(model, principalIdentityName))));

                controller.Put(model);

                scenarioOptions.MockCommandHandler.Verify(m =>
                    m.Handle(It.Is(CommandBasedOn(model, principalIdentityName))),
                        Times.Once());
            }
            public void SetsCommandProperty_ConfirmationToken()
            {
                const string emailAddress = "someone";
                var command = new SendConfirmEmailMessageCommand
                {
                    EmailAddress = emailAddress,
                    Intent = EmailConfirmationIntent.CreatePassword,
                    SendFromUrl = "test",
                };
                var scenarioOptions = new ScenarioOptions(command);
                var handler = CreateHandler(scenarioOptions);

                handler.Handle(command);

                command.ConfirmationToken.ShouldEqual(scenarioOptions.OutConfirmation.Token);
            }
            public void FlashesNoChangesMessage_WhenCommand_ChangedState()
            {
                const string principalIdentityName = "*****@*****.**";
                const int establishmentId = 8;
                const string jobTitles = "job titles";
                const EmployeeOrStudentAffiliate employeeOrStudentAffiliation
                    = EmployeeOrStudentAffiliate.StudentOnly;
                const string returnUrl = "http://www.site.tld";
                var scenarioOptions = new ScenarioOptions
                {
                    PrincipalIdentityName = principalIdentityName,
                };
                var model = new UpdateAffiliationForm
                {
                    JobTitles = jobTitles,
                    EstablishmentId = establishmentId,
                    EmployeeOrStudentAffiliation = employeeOrStudentAffiliation,
                    IsClaimingFaculty = true,
                    ReturnUrl = returnUrl,
                };
                var controller = CreateController(scenarioOptions);
                scenarioOptions.MockCommandHandler.Setup(m => m.Handle(
                    It.Is(CommandBasedOn(model, principalIdentityName))));

                controller.Put(model);

                controller.TempData.ShouldNotBeNull();
                var message = controller.TempData.FeedbackMessage();
                message.ShouldNotBeNull();
                message.ShouldEqual(UpdateAffiliationController.NoChangesMessage);
            }