Exemple #1
0
        public async Task Handle_UserCreditCardObjectUpdated_UpdatesAreReflectedInDb()
        {
            // Arrange
            var user = await CreateUserUsingAutoFixture(1);

            // update properties
            var userCreditCard = user.UserCreditCards.First();

            userCreditCard.CardDisplayNumber = _fixture.Create <string>();
            userCreditCard.CardNumber        = _fixture.Create <string>();

            // AutoMapper setup
            _mapperMock.Setup(m => m.Map(It.IsAny <UpdateUserCommand>(), It.IsAny <User>())).Returns(user);

            // creating System Under Test
            var sut = new UpdateUserCommandHandler(_context, _mapperMock.Object);

            // Act
            await sut.Handle(new UpdateUserCommand(), CancellationToken.None);

            // Assert
            var dbUserCreditCards = _context.UserCreditCards.First();

            dbUserCreditCards.CardDisplayNumber.ShouldBe(userCreditCard.CardDisplayNumber);
            dbUserCreditCards.CardNumber.ShouldBe(userCreditCard.CardNumber);
        }
        public async Task GivenValidUserRequest_WhenRequestContainsANewPassword_ReturnsUserViewModelWithSuccessfulResponse()
        {
            // Arrange, grab a reference to the previous user
            var updateUserCommand = new UpdateUserCommand
            {
                User = new UserUpdateDto
                {
                    Bio      = "You feelin' lucky, punk?",
                    Password = "******"
                }
            };
            var originalUser = await UserManager.FindByEmailAsync(TestConstants.TestUserEmail);

            // Act
            var command = new UpdateUserCommandHandler(CurrentUserContext, Mapper, UserManager, Context, TokenService);
            var result  = await command.Handle(updateUserCommand, CancellationToken.None);

            // Assert, validate the password hash has been updated
            result.ShouldNotBeNull();
            result.ShouldBeOfType <UserViewModel>();
            result.User.ShouldNotBeNull();
            result.User.Bio.ShouldBe(updateUserCommand.User.Bio);

            // Validate the updated user
            var updatedUser = await UserManager.FindByEmailAsync(TestConstants.TestUserEmail);

            updatedUser.Bio.ShouldBe(updateUserCommand.User.Bio);
            updatedUser.PasswordHash.ShouldNotBeNullOrWhiteSpace();
            var validatedPassword = await UserManager.CheckPasswordAsync(originalUser, updateUserCommand.User.Password);

            var invalidOldPassword = await UserManager.CheckPasswordAsync(originalUser, "#passwordTwo1!");

            validatedPassword.ShouldBe(true);
            invalidOldPassword.ShouldBe(false);
        }
        public async Task GivenValidUserRequest_WhenTheUserExistsAndDoesNotUpdateUsernameOrEmail_ReturnsUpdateUserViewModelResponseWithSameToken()
        {
            // Arrange, grab a reference to the previous user
            var updateUserCommand = new UpdateUserCommand
            {
                User = new UserUpdateDto
                {
                    Bio   = "My updated bio",
                    Image = "Something super duper sexy"
                }
            };
            var originalUser = await UserManager.FindByEmailAsync(TestConstants.TestUserEmail);

            // Act
            var command = new UpdateUserCommandHandler(CurrentUserContext, Mapper, UserManager, Context, TokenService);
            var result  = await command.Handle(updateUserCommand, CancellationToken.None);

            // Assert
            result.ShouldNotBeNull();
            result.User.ShouldNotBeNull();
            result.User.Email.ShouldBe(TestConstants.TestUserEmail);
            result.User.Username.ShouldBe(TestConstants.TestUserName);
            result.User.Bio.ShouldBe(updateUserCommand.User.Bio);
            result.User.Image.ShouldBe(updateUserCommand.User.Image);

            // Validate a new token was created
            result.User.Token.ShouldBe(new CurrentUserContextTest(UserManager).GetCurrentUserToken());
            result.User.Token.ShouldNotBe(new TokenServiceTest().CreateToken(originalUser));
        }
        public async Task UpdateUserHandler_Should_Update_User()
        {
            // Arrange...
            var unitOfWork = GetUnitOfWork(out var inMemoryContext);
            var user       = _fixture.Create <User>();

            InMemoryContextHelper.AddUserToContext(inMemoryContext, user);
            var sut = new UpdateUserCommandHandler(unitOfWork);
            var updateUserCommand = new UpdateUserCommand
            {
                Id        = user.Id,
                Title     = _fixture.Create <Title>(),
                FirstName = _fixture.Create <string>(),
                LastName  = _fixture.Create <string>(),
                Sex       = _fixture.Create <Sex>()
            };
            var ct = new CancellationToken();

            // Act...
            var updatedUser = await sut.Handle(updateUserCommand, ct);

            // Assert...
            inMemoryContext.Users.Count().Should().Be(1);
            user.Title.Should().Be(updateUserCommand.Title);
            user.FirstName.Should().Be(updateUserCommand.FirstName);
            user.LastName.Should().Be(updateUserCommand.LastName);
            user.Sex.Should().Be(updateUserCommand.Sex);
        }
        public void Setup()
        {
            repositoryMock = Substitute.For <IUserRepository>();
            var unitOfWorkMock = Substitute.For <IUnitOfWork>();

            unitOfWorkMock.CommitAsync().Returns(true);

            handler = new UpdateUserCommandHandler(repositoryMock, unitOfWorkMock, new NotificationContext(), Substitute.For <IMediatorHandler>());
        }
        public void ThrownInvalidUserServiceException_IfUserDataIsNull_WhenUpdateAnUser()
        {
            _repository.Setup(x => x.Create(null)).Verifiable();

            var _handler = new UpdateUserCommandHandler(_repository.Object, _eventBus.Object);

            Assert.ThrowsAsync <InvalidUserServiceException>(
                () => _handler.Handle(null)
                );
        }
        public async Task UpdateAValidUser()
        {
            var userCommandMother = UserMother.GetValidUpdateUserCommand();

            _repository.Setup(x => x.Update(It.IsAny <User>())).Verifiable();

            var _handler = new UpdateUserCommandHandler(_repository.Object, _eventBus.Object);
            await _handler.Handle(userCommandMother);

            _repository.Verify();
        }
Exemple #8
0
        public async void UpdateInvalidUserTest()
        {
            var command = new UpdateUserCommand()
            {
                Name     = "Johnnny",
                LastName = "Doeere",
                Password = "******",
                Mail     = "jonny123gmailcom"
            };
            var handler = new UpdateUserCommandHandler(Context);

            Assert.ThrowsAny <Exception>(() => handler.Handle(command, CancellationToken.None).Result);
        }
Exemple #9
0
        public void UpdateUser_CallIUserRepositoryUpdate(
            [Frozen] IUserRepository userRepository,
            UpdateUserCommand message,
            User user,
            UpdateUserCommandHandler updateUserCommandHandler)
        {
            //Information
            A.CallTo(() => userRepository.GetById(message.UserId)).Returns(user);

            //Act
            updateUserCommandHandler.ExecuteAsync(message);

            //Test
            A.CallTo(() => userRepository.Update(user)).MustHaveHappened();
        }
Exemple #10
0
 public UserController(
     CreateUserCommandHandler createCommand,
     GetAllUsersQuery getAllQuery,
     GetUserQuery getOneQuery,
     DownloadPhotoQuery getPhotoQuery,
     SessionQuery sessionQuery,
     UpdateUserCommandHandler updateCommand,
     DeleteUserCommandHandler deleteCommand)
 {
     this.createCommand = createCommand;
     this.getAllQuery   = getAllQuery;
     this.getOneQuery   = getOneQuery;
     this.getPhotoQuery = getPhotoQuery;
     this.sessionQuery  = sessionQuery;
     this.updateCommand = updateCommand;
     this.deleteCommand = deleteCommand;
 }
Exemple #11
0
        public async void UpdateOnlyNameTest()
        {
            var command = new UpdateUserCommand()
            {
                Id   = 1,
                Name = "name"
            };
            var handler = new UpdateUserCommandHandler(Context);

            await handler.Handle(command, CancellationToken.None);

            User user = Users.Single(u => u.Id == 1);

            Assert.Equal(command.Name, user.Name);
            Assert.NotNull(user.LastName);
            Assert.NotNull(user.Mail);
        }
        public async void UserWithIdExists_Executed_UpdateUser()
        {
            //Arrange
            var user = new User("Usuário 1", "*****@*****.**", Convert.ToDateTime("15/12/1993"), "123456", "client");

            var userRepositoryMock = new Mock <IUserRepository>();
            var id = 99999;

            userRepositoryMock.Setup(u => u.GetByIdAsync(id).Result).Returns(user);

            var updateUserCommand       = new UpdateUserCommand(id, "*****@*****.**");
            var updateUserCommandHander = new UpdateUserCommandHandler(userRepositoryMock.Object);

            //Act
            await updateUserCommandHander.Handle(updateUserCommand, new CancellationToken());

            //Assert
            userRepositoryMock.Verify(u => u.SaveChangesAsync(), Times.Once);
        }
        public async Task GivenValidUserRequest_WhenTheUpdatedEmailAlreadyExists_ThrowsConduitApiExceptionForBadRequest()
        {
            // Arrange, grab a reference to the previous user
            var updateUserCommand = new UpdateUserCommand
            {
                User = new UserUpdateDto
                {
                    Email = "*****@*****.**",
                }
            };

            // Act
            var command = new UpdateUserCommandHandler(CurrentUserContext, Mapper, UserManager, Context, TokenService);

            // Assert
            await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await command.Handle(updateUserCommand, CancellationToken.None);
            });
        }
        public async Task GivenValidUserRequest_WhenTheUpdatedUsernameIsEmpty_ThrowsConduitApiExceptionForBadRequest()
        {
            // Arrange, grab a reference to the previous user
            var updateUserCommand = new UpdateUserCommand
            {
                User = new UserUpdateDto
                {
                    Username = string.Empty,
                }
            };

            // Act
            var command = new UpdateUserCommandHandler(CurrentUserContext, Mapper, UserManager, Context, TokenService);

            // Assert
            await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await command.Handle(updateUserCommand, CancellationToken.None);
            });
        }
Exemple #15
0
        public async void UpdateValidUserTest()
        {
            var command = new UpdateUserCommand()
            {
                Id       = 1,
                Name     = "Johnnny",
                LastName = "Doeere",
                Password = "******",
                Mail     = "*****@*****.**"
            };
            var handler = new UpdateUserCommandHandler(Context);

            await handler.Handle(command, CancellationToken.None);

            User user = Users.Single(u => u.Id == 1);

            Assert.Equal(command.Name, user.Name);
            Assert.Equal(command.Mail, user.Mail);
            Assert.Equal(command.LastName, user.LastName);
        }
Exemple #16
0
        public async Task UpdateUserCommandHandler_GivenValidCommand_ShouldInsertedInDb()
        {
            _startUp.InitializeDefaultUserInDb();
            var userRepository = new UserRepository(_startUp.UnitOfWork);
            var userToUpdate   = await userRepository.FindAsync(new UserSpecification(UserBuilder.UserId));

            var userData = new UserBuilder().UserToUpdate();
            var factory  = _startUp.ServiceProvider.GetRequiredService <ILoggerFactory>();
            var logger   = factory.CreateLogger <UpdateUserCommandHandler>();

            _commandHandler = new UpdateUserCommandHandler(userRepository, logger, _startUp.UnitOfWork);
            await _commandHandler.Handle(
                new UpdateUserCommand()
            {
                Id             = userToUpdate.Id,
                BirthDate      = userData.BirthDate,
                Email          = userData.Email,
                EmailConfirmed = userData.EmailConfirmed,
                FirstName      = userData.FirstName,
                IsActive       = userData.IsActive,
                LastName       = userData.LastName,
                PhoneNumber    = userData.PhoneNumber,
                Roles          = userData.Roles.Select(role => new RoleDto()
                {
                    Name = role.Role.Name
                })
            },
                CancellationToken.None);

            var updatedUser = await userRepository.FindAsync(new UserSpecification(userData.Email));

            updatedUser.ShouldNotBeNull();
            updatedUser.Email.ShouldBe(userData.Email);
            updatedUser.Roles.ShouldNotBeNull();
            updatedUser.Roles.First(userRole => userRole.Role.Name == Roles.Patient).ShouldNotBeNull();
            updatedUser.Roles.First(userRole => userRole.Role.Name == Roles.Admin).ShouldNotBeNull();
            Should.Throw <InvalidOperationException>(() =>
            {
                var notHasDoctorRole = updatedUser.Roles.First(userRole => userRole.Role.Name == Roles.Doctor);
            });
        }
Exemple #17
0
        public async Task InputDataIsOk_Executed_ReturnUser()
        {
            // Arrange
            var userRepository = new Mock <IUserRepository>();

            var updateUserCommand = new UpdateUserCommand
            {
                Id       = 1,
                FullName = "Matheus",
                Email    = "*****@*****.**",
                Active   = true
            };

            var updateUserCommandHandler = new UpdateUserCommandHandler(userRepository.Object);

            // Act
            await updateUserCommandHandler.Handle(updateUserCommand, new CancellationToken());

            // Assert
            userRepository.Verify(u => u.GetByIdAsync(updateUserCommand.Id), Times.Once);
            userRepository.Verify(u => u.SaveChangesAsync(), Times.Once);
        }
Exemple #18
0
        public async void UpdateExistingMailTest()
        {
            Users.Add(new User()
            {
                Id       = 2,
                Name     = "NotJohn",
                LastName = "NotDoe",
                Password = "******",
                Mail     = "*****@*****.**"
            });
            var command = new UpdateUserCommand()
            {
                Id       = 2,
                Name     = "Johnnny",
                LastName = "Doeere",
                Password = "******",
                Mail     = "jonny123gmailcom"
            };
            var handler = new UpdateUserCommandHandler(Context);

            Assert.ThrowsAny <Exception>(() => handler.Handle(command, CancellationToken.None).Result);
        }
Exemple #19
0
        public async Task Handle_UserObjectSimplePropertiesUpdated_UpdatesAreReflectedInDb()
        {
            // Arrange
            var user = await CreateUserUsingAutoFixture(0);

            // update properties
            user.CreationDate = _fixture.Create <DateTime>();
            user.UserName     = _fixture.Create <string>();

            // AutoMapper setup
            _mapperMock.Setup(m => m.Map(It.IsAny <UpdateUserCommand>(), It.IsAny <User>())).Returns(user);

            // creating System Under Test
            var sut = new UpdateUserCommandHandler(_context, _mapperMock.Object);

            // Act
            await sut.Handle(new UpdateUserCommand(), CancellationToken.None);

            // Assert
            var dbUser = _context.Users.First();

            dbUser.CreationDate.ShouldBe(user.CreationDate);
            dbUser.UserName.ShouldBe(user.UserName);
        }
Exemple #20
0
 public UpdateUserTest()
 {
     // Arrange
     Context = ContextFactory.Create();
     Handler = new UpdateUserCommandHandler(Context);
 }
 public UpdateUserCommandTest() : base()
 {
     mediatorMock             = new Mock <IMediator>();
     updateUserCommandHandler = new UpdateUserCommandHandler(usersContext, mediatorMock.Object, mapper);
 }
 public UpdateUserController(UpdateUserCommandHandler updateUserCommandHandler)
 {
     _updateUserCommandHandler = updateUserCommandHandler;
 }
Exemple #23
0
 void GivenSystemUnderTest()
 {
     _sut = new UpdateUserCommandHandler(_userAccountDataRepository);
 }
Exemple #24
0
 public UpdateUserCommandHandlerTests()
 {
     this.sut = new UpdateUserCommandHandler(this.Context);
 }
Exemple #25
0
 public UpdateUserCommandTests()
 {
     _sut = new UpdateUserCommandHandler(DbContext);
 }