public async Task GivenInvalidId_ThrowsNotFoundException()
        {
            var invalidId = 25;
            var command   = new UpdateUserCommand {
                Id = invalidId, FirstName = "Louis", LastName = "Blaz", Email = "*****@*****.**", UserName = "******", PasswordHash = "12345678"
            };

            await Assert.ThrowsAsync <NotFoundException>(() => updateUserCommandHandler.Handle(command, CancellationToken.None));
        }
        public async Task UpdateUserCommandHandler_UserIsNotExist_ShouldReturn_UserIsNotFind()
        {
            User user    = null;
            var  command = new UpdateUserCommandBuilder().Builder();

            repositoryMock.GetByExternalIdAsync(Arg.Any <string>()).Returns(user);

            var result = await handler.Handle(command, new CancellationToken());

            Assert.IsTrue(result.HasAProblem);
        }
예제 #3
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 ThrownInvalidUserServiceException_IfUserDataIsNull_WhenUpdateAnUser()
        {
            _repository.Setup(x => x.Create(null)).Verifiable();

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

            Assert.ThrowsAsync <InvalidUserServiceException>(
                () => _handler.Handle(null)
                );
        }
예제 #8
0
        public async Task Handle_GivenValidRequest_ShouldUpdateUser()
        {
            // Arrange
            var command = new UpdateUserCommand
            {
                UserId       = KnownUserID,
                FirstName    = "Bob",
                LastName     = "Test",
                EmailAddress = "*****@*****.**",
                DOB          = DateTime.Today.AddYears(-30)
            };

            // Act
            await _sut.Handle(command, CancellationToken.None);

            // Assert
            var user = await DbContext.Users.FindAsync(KnownUserID);

            Assert.Equal(command.EmailAddress, user.EmailAddress);
        }
        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();
        }
예제 #10
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);
        }
        public IActionResult User([FromForm] UpdateUserCommandBinder updateUserCommandBinder)
        {
            try
            {
                _updateUserCommandHandler.Handle(updateUserCommandBinder.GetCommand());
            }
            catch (UserNotCreatedException e)
            {
                return(Conflict(new JsonResult(e.Message)));
            }

            return(Ok());
        }
예제 #12
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_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);
            });
        }
예제 #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);
        }
        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);
            });
        }
예제 #17
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);
            });
        }
예제 #18
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);
        }
예제 #19
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);
        }
예제 #20
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);
        }
예제 #21
0
 async Task WhenHandlerHandlesTheCommand()
 {
     await _sut.Handle(_command);
 }