コード例 #1
0
        public void GetAll_Integration_ReturnsSortedList()
        {
            string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest");

            using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath))
            {
                dbContext.Initialise();
                dbContext.BeginTransaction();

                IUserRepository userRepo = new UserRepository(dbContext);

                ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, new UserValidator(userRepo), new PasswordProvider());

                // create the users
                UserModel userB = DataHelper.CreateUserModel();
                userB.UserName = "******";
                createUserCommand.Execute(userB.UserName, userB.Password, userB.Role);

                UserModel userC = DataHelper.CreateUserModel();
                userC.UserName = "******";
                createUserCommand.Execute(userC.UserName, userC.Password, userC.Role);

                UserModel userA = DataHelper.CreateUserModel();
                userA.UserName = "******";
                createUserCommand.Execute(userA.UserName, userA.Password, userA.Role);

                List <UserModel> result = userRepo.GetAll().ToList();
                Assert.AreEqual(3, result.Count);
                Assert.AreEqual(userA.UserName, result[0].UserName);
                Assert.AreEqual(userB.UserName, result[1].UserName);
                Assert.AreEqual(userC.UserName, result[2].UserName);
            }
        }
コード例 #2
0
        public void Execute_CreatesUserWithFactory()
        {
            var email    = "email";
            var password = "******";

            _subject.Execute(email, password);

            _factory.Verify(c => c.Create(It.Is <string>(x => x == email), It.Is <string>(x => x == password)), Times.Once());
        }
コード例 #3
0
        public void Execute_IntegrationTest_SQLite()
        {
            string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest");

            using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath))
            {
                dbContext.Initialise();
                dbContext.BeginTransaction();

                // create the user
                UserModel user = DataHelper.CreateUserModel();

                IUserRepository   userRepo         = new UserRepository(dbContext);
                IUserValidator    userValidator    = new UserValidator(userRepo);
                IPasswordProvider passwordProvider = new PasswordProvider();

                ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, userValidator, passwordProvider);
                createUserCommand.Execute(user.UserName, user.Password, user.Role);

                UserModel savedUser = userRepo.GetByUserName(user.UserName);

                Assert.IsNotNull(savedUser);
                Assert.AreEqual(user.Role, savedUser.Role);
                Assert.IsTrue(passwordProvider.CheckPassword(user.Password, savedUser.Password));
            }
        }
コード例 #4
0
        public void Execute_IntegrationTest_SQLite()
        {
            string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest");

            using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath))
            {
                dbContext.Initialise();
                dbContext.BeginTransaction();

                IUserRepository    userRepo          = new UserRepository(dbContext);
                ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, new UserValidator(userRepo), new PasswordProvider());
                IDeleteUserCommand deleteUserCommand = new DeleteUserCommand(dbContext);


                // create the user
                UserModel user = createUserCommand.Execute("test", Guid.NewGuid().ToString(), Roles.User);

                int rowCount = dbContext.ExecuteScalar <int>("SELECT COUNT(*) FROM Users");
                Assert.AreEqual(1, rowCount);

                //  run the delete command and check the end tables - should be 0 records
                deleteUserCommand.Execute(user.Id);

                rowCount = dbContext.ExecuteScalar <int>("SELECT COUNT(*) FROM Users");
                Assert.AreEqual(0, rowCount);
            }
        }
コード例 #5
0
        public void ReturnCorrectMessage_WhenUserHasBeenSuccessfullyCreated()
        {
            // arrange
            var addUser     = new Mock <IAddUser>();
            var userFactory = new Mock <IUserFactory>();
            var user        = new Mock <IUser>();

            userFactory.Setup(x => x.CreateUser(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(user.Object);

            string projectId         = "0";
            string username          = "******";
            string email             = "someEmail";
            var    commandParameters = new List <string>()
            {
                projectId, username, email
            };

            var    createUserCommand = new CreateUserCommand(addUser.Object, userFactory.Object);
            string expectedMessage   = "Successfully created a new user!";

            // act
            string resultMessage = createUserCommand.Execute(commandParameters);

            // assert
            StringAssert.Contains(expectedMessage, resultMessage);
        }
コード例 #6
0
        public void CallAddUsersAddUserMethodWithCorrectProjectIdAndUser_WhenPassedParametersListIsValid()
        {
            // arrange
            var addUser     = new Mock <IAddUser>();
            var userFactory = new Mock <IUserFactory>();
            var user        = new Mock <IUser>();

            userFactory.Setup(x => x.CreateUser(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(user.Object);

            string projectId         = "0";
            string username          = "******";
            string email             = "someEmail";
            var    commandParameters = new List <string>()
            {
                projectId, username, email
            };

            var createUserCommand = new CreateUserCommand(addUser.Object, userFactory.Object);

            // act
            createUserCommand.Execute(commandParameters);

            // assert
            addUser.Verify(x => x.AddUser(0, It.Is <IUser>(u => u == user.Object)), Times.Once);
        }
コード例 #7
0
        public void Execute_IntegrationTest_SQLite()
        {
            string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest");

            using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath))
            {
                dbContext.Initialise();
                dbContext.BeginTransaction();

                // create the user
                UserModel       user          = DataHelper.CreateUserModel();
                IUserRepository userRepo      = new UserRepository(dbContext);
                IUserValidator  userValidator = new UserValidator(userRepo);

                IPasswordProvider  passwordProvider  = new PasswordProvider();
                ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, userValidator, passwordProvider);
                UserModel          savedUser         = createUserCommand.Execute(user.UserName, user.Password, user.Role);

                // reset the password
                string newPassword = Guid.NewGuid().ToString();
                IUpdateUserPasswordCommand updateCommand = new UpdateUserPasswordCommand(dbContext, userRepo, passwordProvider);
                updateCommand.Execute(savedUser.UserName, newPassword);

                // now fetch it again and check the password is good
                savedUser = userRepo.GetByUserName(user.UserName);
                Assert.IsTrue(passwordProvider.CheckPassword(newPassword, savedUser.Password));
            }
        }
コード例 #8
0
        public void ShouldSaveAnUser()
        {
            IUserRepository repository   = new UserRepository();
            IEmailService   emailService = new EmailService();
            User            user         = new User("Name", DateTime.Now.AddYears(-20), "*****@*****.**", "pass", "999999999");

            ICommand <User> command = new CreateUserCommand(repository, emailService);

            Assert.AreEqual(true, command.Execute(user));
        }
コード例 #9
0
        public async Task <CreateUserResponse> CreateUser(
            [FromBody] CreateUserRequest request,
            CancellationToken cancellationToken)
        {
            var createUserCommand = new CreateUserCommand(
                request.ToCommand(),
                _repository,
                _logger);

            var result = await createUserCommand.Execute(cancellationToken);

            return(result.ToApiResponse());
        }
コード例 #10
0
        public void WhenCreatingUserTaskWillBeSuccessful()
        {
            var command = new CreateUserCommand()
            {
                LoginName = USER_LOGIN_NAME
            };
            var helloWorldApi = new Mock <ISimpleAuthenticationDataStore>();

            helloWorldApi.Setup(x => x.CreateUser(USER_LOGIN_NAME)).Returns(Task.FromResult(Mock.Of <IPostResult>()));

            command.SimpleAuthenticationApi = helloWorldApi.Object;

            var result = command.Execute();

            Assert.IsTrue(result.IsCompleted);
        }
コード例 #11
0
        public void CanCreateUserCommand()
        {
            var command = new CreateUserCommand
            {
                LoginName = USER_LOGIN_NAME
            };

            var helloWorldApi = new Mock <ISimpleAuthenticationDataStore>();

            helloWorldApi.Setup(x => x.CreateUser(USER_LOGIN_NAME)).Returns(Task.FromResult(Mock.Of <IPostResult>()));

            command.SimpleAuthenticationApi = helloWorldApi.Object;

            command.Execute();

            helloWorldApi.VerifyAll();
        }
コード例 #12
0
        public void CreateUserAndCallSaveChanges_WhenExecuted()
        {
            // Arrange
            var mockedContext         = new Mock <IMotorSystemContext>();
            var userInputProviderMock = new Mock <IUserInputProvider>();
            var factoryMock           = new Mock <IModelFactory>();
            var mockedCache           = new Mock <IMemoryCacheProvider>();
            var mockedHelper          = new Mock <IHelperMethods>();



            userInputProviderMock.Setup(i => i.RegisterUserInput())
            .Returns(new List <string>()
            {
                "username", "pass", "email"
            });

            mockedHelper.Setup(h => h.GenerateSHA256Hash(It.IsAny <string>(), It.IsAny <string>()))
            .Returns("some-hash123");

            factoryMock.Setup(f => f.CreateUser(It.IsAny <string>(), It.IsAny <string>(),
                                                It.IsAny <string>(), It.IsAny <string>()))
            .Returns(new User());

            mockedContext.SetupGet(c => c.Users)
            .Returns((new Mock <IDbSet <User> >()).Object);

            var cache = new MemoryCache("test");

            cache["user"] = "******";
            mockedCache.SetupGet(c => c.MemoryCache).Returns(cache);



            var createUserCommand = new CreateUserCommand(mockedContext.Object,
                                                          userInputProviderMock.Object, factoryMock.Object, mockedCache.Object,
                                                          mockedHelper.Object);

            createUserCommand.Execute();

            mockedContext.Verify(c => c.SaveChanges(), Times.Once);
        }
コード例 #13
0
        public void CallUserFactoryWithCorrectUsernameAndEmailParameters_WhenPassedParametersListIsValid()
        {
            // arrange
            var addUser     = new Mock <IAddUser>();
            var userFactory = new Mock <IUserFactory>();

            string projectId         = "0";
            string username          = "******";
            string email             = "someEmail";
            var    commandParameters = new List <string>()
            {
                projectId, username, email
            };

            var createUserCommand = new CreateUserCommand(addUser.Object, userFactory.Object);

            // act
            createUserCommand.Execute(commandParameters);

            // assert
            userFactory.Verify(x => x.CreateUser(username, email), Times.Once);
        }
コード例 #14
0
        public void GetByUserName_Integration_ReturnsData()
        {
            string filePath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName() + ".dbtest");
            string userName = Path.GetRandomFileName();

            using (SQLiteDbContext dbContext = new SQLiteDbContext(filePath))
            {
                dbContext.Initialise();
                dbContext.BeginTransaction();

                IUserRepository userRepo = new UserRepository(dbContext);

                ICreateUserCommand createUserCommand = new CreateUserCommand(dbContext, new UserValidator(userRepo), new PasswordProvider());

                // create the user
                UserModel user = DataHelper.CreateUserModel();
                user.UserName = userName;
                createUserCommand.Execute(user.UserName, user.Password, user.Role);

                UserModel result = userRepo.GetByUserName(userName);
                Assert.IsNotNull(result);
                Assert.AreEqual(userName, result.UserName);
            }
        }
コード例 #15
0
 public async Task Create([FromBody] CreateUserInputModel model) => await createUserCommand.Execute(model);
コード例 #16
0
        /// <summary>
        /// Creates a new demo account
        /// </summary>
        /// <param name="procParams"></param>
        /// <returns></returns>
        public CreatedDemoAccountViewModel Execute(CreateDemoAccountParams procParams)
        {
            if (!_siteAdminAuthProc.Execute(new SiteAdminAuthorizationParams {
                UserId = procParams.RequestingUserID
            }).UserAuthorized)
            {
                throw new UserNotAuthorizedForProcessException(procParams.RequestingUserID, typeof(CreateDemoAccountParams), typeof(CreatedDemoAccountViewModel));
            }

            int userId = 0;

            using (var transaction = new TransactionScope())
            {
                var user = _createUserCmd.Execute(new CreateUserCommandParams
                {
                    Email             = procParams.Email,
                    PlainTextPassword = procParams.Password,
                    FullName          = procParams.Name
                });

                //_context.Users.Attach(user);
                user = _context.Users.Find(user.Id);

                // Create the organization
                var org = new MyJobLeads.DomainModel.Entities.Organization
                {
                    Name = procParams.OrganizationName,
                    RegistrationToken = Guid.NewGuid()
                };

                user.IsOrganizationAdmin = true;
                user.Organization        = org;
                _context.Organizations.Add(org);

                // Create a new jobsearch with random data
                var jobsearch = new JobSearch();
                var values    = new DemoCreationValues();
                int seed      = new Random(DateTime.Now.Millisecond).Next(1000, 50000);

                foreach (var companyData in values.Companies)
                {
                    var company = new Company
                    {
                        Name       = companyData[0],
                        Phone      = companyData[1],
                        City       = companyData[2],
                        State      = companyData[3],
                        Zip        = companyData[4],
                        LeadStatus = companyData[5],
                        Notes      = companyData[6]
                    };

                    for (int x = 0; x < 3; x++)
                    {
                        var contactData = values.Contacts[new Random(seed++).Next(0, values.Contacts.Count - 1)];
                        var contact     = new Contact
                        {
                            Name        = contactData[0],
                            DirectPhone = contactData[1],
                            MobilePhone = contactData[2],
                            Extension   = contactData[3],
                            Email       = contactData[4],
                            Assistant   = contactData[5],
                            ReferredBy  = contactData[6],
                            Notes       = contactData[7]
                        };

                        company.Contacts.Add(contact);
                    }

                    var task = new Task
                    {
                        Name           = values.TaskNames[new Random(seed++).Next(0, values.TaskNames.Count - 1)],
                        CompletionDate = new Random(seed++).Next(0, 1000) % 2 == 0 ? DateTime.Now : (DateTime?)null,
                        TaskDate       = DateTime.Now.AddDays(new Random(seed++).Next(-7, 30)).AddHours(new Random(seed++).Next(-24, 24))
                    };

                    company.Tasks.Add(task);

                    jobsearch.Companies.Add(company);
                }

                user.JobSearches.Add(jobsearch);
                _context.SaveChanges();

                // This has to be done once we have an id
                user.LastVisitedJobSearchId = jobsearch.Id;
                _context.SaveChanges();

                transaction.Complete();
            }

            return(new CreatedDemoAccountViewModel
            {
                NewUserId = userId,
                Name = procParams.Name,
                Email = procParams.Email,
                Password = procParams.Password
            });
        }