Beispiel #1
0
        public async Task RemoveCommentShouldReduceCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "MyTestDb5")
                          .Options;
            var dbContext = new ApplicationDbContext(options);
            var comment1  = new Comment {
                Id = 1
            };
            var comment2 = new Comment {
                Id = 2
            };

            dbContext.Comments.Add(comment1);
            dbContext.Comments.Add(comment2);
            await dbContext.SaveChangesAsync();

            var repository = new EfDeletableEntityRepository <Comment>(dbContext);
            var service    = new CommentService(repository);
            int existingId = 2;
            await service.RemoveComment(existingId);

            Assert.Equal(1, repository.All().Count());
        }
        public async Task Handle_GivenInvalidRequest_ShouldThrowPlayerCannotBeAMemeberOfMultipleTeamsWithTheSameFormatException()
        {
            // Arrange
            var command = new InvitePlayerCommand {
                TeamId = 1, UserName = "******"
            };

            this.dbContext.PlayerTeams.Add(new PlayerTeam {
                PlayerId = "Foo5", TeamId = 2
            });
            this.dbContext.SaveChanges();

            var playersRepository = new EfDeletableEntityRepository <Player>(this.dbContext);

            var sut = new InvitePlayerCommandHandler(
                this.deletableEntityRepository,
                playersRepository,
                It.IsAny <IDeletableEntityRepository <TeamInvite> >(),
                It.IsAny <IMediator>(),
                It.IsAny <IUserAccessor>());

            // Act & Assert
            await Should.ThrowAsync <PlayerCannotBeAMemeberOfMultipleTeamsWithTheSameFormatException>(sut.Handle(command, It.IsAny <CancellationToken>()));
        }
        public async void DeleteProductAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Product_Database")
                          .Options;
            var dbContext = new ApplicationDbContext(options);
            await dbContext.AddAsync(new Product { Name = "TestProduct", Details = "TestDetails" });

            await dbContext.SaveChangesAsync();

            var product     = new EfDeletableEntityRepository <Product>(dbContext);
            var productLang = new EfDeletableEntityRepository <ProductLang>(dbContext);
            var userStore   = new UserStore <ApplicationUser>(dbContext);
            var sanitizer   = new HtmlSanitizer();

            var service = new ProductService(product, productLang, userStore, sanitizer);

            var productToDelete = service.GetAll().FirstOrDefault(x => x.Details == "TestDetails");
            await service.Delete(productToDelete);

            var count = service.GetAll().Count();

            Assert.Equal(0, count);
        }
        public async void GetNotificationTemplateShouldRetunrProperType()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var notificationRepository = new EfDeletableEntityRepository <Notification>(new ApplicationDbContext(options.Options));
            var userRepository         = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly);

            var notificationsService = new NotificationsService(notificationRepository, userRepository);

            var notification = new Notification
            {
                DogsitterId = Guid.NewGuid().ToString(),
                OwnerId     = Guid.NewGuid().ToString(),
                Content     = "True",
            };

            await notificationsService.SendNotification(notification);

            var notificationBase = notificationsService.GetNotificationById <NotificationViewModel>(notification.Id);

            Assert.IsType <NotificationViewModel>(notificationBase);
        }
Beispiel #5
0
        public async Task Handle_GivenInvalidRequest_ShouldThrowNotFoundExceptionForTeam()
        {
            // Arrange
            var command = new EnrollATeamCommand {
                TableId = 2, TeamId = 55
            };

            var userAccessorMock = new Mock <IUserAccessor>();

            userAccessorMock.Setup(x => x.UserId).Returns("Foo3");

            var playersRepository          = new EfDeletableEntityRepository <Player>(this.dbContext);
            var teamsRepository            = new EfDeletableEntityRepository <Team>(this.dbContext);
            var tournamentTablesRepository = new EfDeletableEntityRepository <TournamentTable>(this.dbContext);

            var sut = new EnrollATeamCommandHandler(
                teamsRepository,
                playersRepository,
                tournamentTablesRepository,
                userAccessorMock.Object);

            // Act & Assert
            await Should.ThrowAsync <NotFoundException>(sut.Handle(command, It.IsAny <CancellationToken>()));
        }
        public async Task DeleteRequestAsync_WithValidReqesterUsername_ShouldRemoveFromDatabase()
        {
            // Arrange
            var context                = InMemoryDbContext.Initiliaze();
            var userRepository         = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userFollowerRepository = new EfRepository <UserFollower>(context);
            var profileService         = new ProfilesService(userRepository, userFollowerRepository);

            await this.SeedUsers(context);

            await userFollowerRepository.AddAsync(new UserFollower
                                                  { UserId = "userOneId", FollowerId = "userTwoId", IsApproved = false });

            await userFollowerRepository.SaveChangesAsync();

            // Act
            int expectedCount = userFollowerRepository.All().Count() - 1;
            await profileService.DeleteRequestAsync("userTwoUsername");

            int actualCount = userFollowerRepository.All().Count();

            // Assert
            Assert.Equal(expectedCount, actualCount);
        }
Beispiel #7
0
        public async Task GetDetailsForNewByIdAsync_WithData_ShouldReturnNew()
        {
            var         context    = SteuDbContextInMemoryFactory.InitializeContext();
            NewsService service    = this.IntializeNewsService(context);
            var         repository = new EfDeletableEntityRepository <News>(context);

            var tempNews = new News()
            {
                Id         = "newsId",
                Content    = "content",
                Title      = "title",
                IsDeleted  = false,
                SteuUserId = "userId",
            };

            await repository.AddAsync(tempNews);

            await repository.SaveChangesAsync();

            var actualResult =
                await service.GetDetailsForNewByIdAsync <NewsDetailsViewModel>("newsId");

            Assert.Equal("content", actualResult.Content);
        }
Beispiel #8
0
        public async Task EditLoadAsync_WithIncorectOrderId_ShouldReturnArgumentNullException()
        {
            var          context    = SteuDbContextInMemoryFactory.InitializeContext();
            LoadsService service    = IntializeLoadService(context);
            var          repository = new EfDeletableEntityRepository <Order>(context);

            await repository.AddAsync(new Order()
            {
                Id   = "asdasd",
                Load = new Load(),
            });

            await context.SaveChangesAsync();

            EditLoadViewModel model = new EditLoadViewModel()
            {
                Id               = "asd",
                CountryFrom      = "Bulgaria",
                TownFrom         = "Sofia",
                CountryTo        = "Croatia",
                TownTo           = "Zagreb",
                TruckTypeName    = "Normal",
                Priority         = "Normal",
                Circle           = false,
                ExpireTime       = DateTime.UtcNow,
                LoadDeliveryTime = DateTime.UtcNow,
                LoadTime         = DateTime.UtcNow,
                LoadVolume       = 100,
                LoadWeight       = 20000,
                Price            = 12312231,
                Referer          = "dasada",
                InputModel       = new LoadEditViewModel(),
            };

            await Assert.ThrowsAsync <ArgumentNullException>(() => service.EditLoadAsync(model));
        }
Beispiel #9
0
        public async Task GetAllAvaibleLoadsBySearchAsync_WhithNonExistingLoad_ShoulRetunEmptyList()
        {
            var          context    = SteuDbContextInMemoryFactory.InitializeContext();
            LoadsService service    = IntializeLoadService(context);
            var          repository = new EfDeletableEntityRepository <Order>(context);

            await repository.AddAsync(new Order()
            {
                AddressFrom = new Address()
                {
                    Country = new Country()
                    {
                        Name = "Bulgaria"
                    },
                    Town = new Town()
                    {
                        Name = "Sofia"
                    },
                },
                ExpireTime = DateTime.UtcNow.AddDays(7),
                IsDeleted  = false,
                Load       = new Load(),
            });

            await context.SaveChangesAsync();

            SearchLoadInputModel model = new SearchLoadInputModel()
            {
                CountryTo = "Bulgaria",
            };

            var actualResult =
                await service.GetAllAvaibleLoadsBySearchAsync <AllAvaibleLoadsBySearchViewModel>(model);

            Assert.Empty(actualResult);
        }
        public async Task DeleteAsyncWorksCorrectly()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repository = new EfDeletableEntityRepository <Category>(dbContext);

            var service  = new CategoriesService(repository);
            var category = new Category()
            {
                Id = 1,
            };

            var childCategoryOne = new Category()
            {
                Id = 2,
                ParentCategoryId = 1,
            };
            var childCategoryTwo = new Category()
            {
                Id = 3,
                ParentCategoryId = 1,
            };

            dbContext.Add(category);
            dbContext.Add(childCategoryOne);
            dbContext.Add(childCategoryTwo);
            await dbContext.SaveChangesAsync();

            await service.DeleteAsync(1);

            var categoriesInDbCount = dbContext.Categories.ToList().Count();

            Assert.Equal(0, categoriesInDbCount);
        }
Beispiel #11
0
        public async Task EditAsync_WithCorrectData_ShouldSuccessfullyEdit()
        {
            var errorMessagePrefix = "SpecialOffersService EditAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var seeder  = new SpecialOffersServiceTestsSeeder();
            await seeder.SeedSpecialOfferAsync(context);

            var specialOfferRepository = new EfDeletableEntityRepository <SpecialOffer>(context);
            var specialOffersService   = this.GetSpecialOffersService(specialOfferRepository, context);

            var specialOffer = context.SpecialOffers.First();

            var model = new EditSpecialOfferViewModel
            {
                Id           = specialOffer.Id,
                Title        = "Title1-Edited",
                Content      = "Content1-Edited",
                ShortContent = "ShortContenr1-Edited",
                HotelDataId  = context.Hotels.FirstOrDefault().Id,
            };

            // Act
            await specialOffersService.EditAsync(model);

            var actualResult   = specialOfferRepository.All().First();
            var expectedResult = model;

            // Assert
            Assert.True(expectedResult.Title == actualResult.Title, errorMessagePrefix + " " + "Title is not returned properly.");
            Assert.True(expectedResult.Content == actualResult.Content, errorMessagePrefix + " " + "Content is not returned properly.");
            Assert.True(expectedResult.ShortContent == actualResult.ShortContent, errorMessagePrefix + " " + "Short content is not returned properly.");
            Assert.True(expectedResult.HotelDataId == actualResult.HotelDataId, errorMessagePrefix + " " + "Hotel is not returned properly.");
        }
        public async Task UpdateProfileCorrectlyUpdatesProfilePictureUrlWhenItIsNotNull()
        {
            AutoMapperInitializer.InitializeMapper();
            var context = InMemoryDbContextInitializer.InitializeContext();
            await context.Candidates.AddRangeAsync(this.SeedTestData());

            await context.SaveChangesAsync();

            var candidatesRepository = new EfDeletableEntityRepository <Candidate>(context);
            var languagesRepository  = new EfDeletableEntityRepository <CandidateLanguage>(context);
            var skillsRepository     = new EfDeletableEntityRepository <CandidateSkill>(context);
            var cloudinary           = new Cloudinary(new Account(CloudinaryConfig.CloudName, CloudinaryConfig.ApiKey, CloudinaryConfig.ApiSecret));
            var candidatesService    = this.GetMockedService(candidatesRepository, languagesRepository, skillsRepository, cloudinary);

            var profilePicture = this.PrepareImage();

            var candidateId = await candidatesService.UpdateProfileAsync("Second", new UpdateCandidateProfileViewModel { ProfilePicture = profilePicture });

            Assert.NotNull(candidateId);

            var profilePictureUrl = context.Candidates.Find(candidateId).ProfilePictureUrl;

            Assert.NotEqual("someUrl", profilePictureUrl);
        }
        public async Task EditAsync_WithIncorrectProperty_ShouldThrowArgumentNullException()
        {
            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var reservationRepository = new EfDeletableEntityRepository <Reservation>(context);
            var reservationsService   = this.GetReservationService(reservationRepository, context);
            var seeder = new ReservationsServiceTestsSeeder();
            await seeder.SeedReservationAsync(context);

            var reservation = context.Reservations.First();

            var model = new EditReservationViewModel
            {
                Id                  = reservation.Id,
                UserId              = null,
                StartDate           = new DateTime(2020, 4, 4),
                EndDate             = new DateTime(2020, 4, 8),
                Adults              = 2,
                Kids                = 1,
                ReservationStatusId = null,
                PaymentTypeId       = null,
                TotalAmount         = 1000,
                TotalDays           = 4,
                AdvancedPayment     = 300,
                RoomId              = null,
            };

            // Act

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await reservationsService.EditAsync(model);
            });
        }
        public async Task EditAsync_WithCorrectData_ShouldReturnCorrectResult()
        {
            var errorMessage = "ReservationsService EditAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var reservationRepository = new EfDeletableEntityRepository <Reservation>(context);
            var reservationsService   = this.GetReservationService(reservationRepository, context);
            var seeder = new ReservationsServiceTestsSeeder();
            await seeder.SeedReservationAsync(context);

            var reservation = context.Reservations.First();

            var model = new EditReservationViewModel
            {
                Id                  = reservation.Id,
                UserId              = context.Users.First().Id,
                StartDate           = new DateTime(2020, 4, 4),
                EndDate             = new DateTime(2020, 4, 8),
                Adults              = 2,
                Kids                = 1,
                ReservationStatusId = context.ReservationStatuses.First().Id,
                PaymentTypeId       = context.PaymentTypes.First().Id,
                TotalAmount         = 1000,
                TotalDays           = 4,
                AdvancedPayment     = 300,
                RoomId              = context.Rooms.First().Id,
            };

            // Act
            var result = await reservationsService.EditAsync(model);

            // Assert
            Assert.True(result, errorMessage + " " + "Returns false.");
        }
Beispiel #15
0
        public async Task GetAllCoverPicturesAsyncShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryNewsFeedPost = new EfDeletableEntityRepository <NewsFeedPost>(dbContext);
            var applicationUser        = new EfDeletableEntityRepository <ApplicationUser>(dbContext);
            var pictureRepository      = new EfRepository <UserProfilePicture>(dbContext);
            var repositoryComment      = new EfDeletableEntityRepository <NewsFeedComment>(dbContext);
            var coverPictureRepository = new EfRepository <UserCoverPicture>(dbContext);
            var friendRepository       = new EfDeletableEntityRepository <Friend>(dbContext);

            var userPicture = new UserCoverPicture
            {
                PictureURL        = "mountain.jpg",
                ApplicationUserId = "1",
            };

            var secondUserPicture = new UserCoverPicture
            {
                PictureURL        = "mountainTwo.jpg",
                ApplicationUserId = "1",
            };

            var service = new NewsFeedService(repositoryNewsFeedPost, applicationUser, pictureRepository, repositoryComment, coverPictureRepository, friendRepository);

            var firstPictureResult  = service.CreateCoverPictureAsync(userPicture.ApplicationUserId, userPicture.PictureURL);
            var secondPictureResult = service.CreateCoverPictureAsync(secondUserPicture.ApplicationUserId, secondUserPicture.PictureURL);

            AutoMapperConfig.RegisterMappings(typeof(GetAllCoverPictureForUserViewModel).GetTypeInfo().Assembly);

            var resultCount = await service.GetAllCoverPicturesAsync <GetAllCoverPictureForUserViewModel>(userPicture.ApplicationUserId);

            Assert.Equal(2, resultCount.Count());
        }
Beispiel #16
0
        public async Task GetAllLoadsByUserIdAsync_WithNullUser_ShouldReturnArgumentNullException()
        {
            var          context    = SteuDbContextInMemoryFactory.InitializeContext();
            LoadsService service    = IntializeLoadService(context);
            var          repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Load       = new Load(),
                SteuUser   = new SteuUser()
                {
                    Id = "userId",
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            await Assert.ThrowsAsync <ArgumentNullException>(() => service.GetAllLoadsByUserIdAsync(1, 10, null));
        }
Beispiel #17
0
        public async Task GetUserFollowingsAsync_WithValidData_ShouldReturnUserFollowings()
        {
            // Arrange
            this.InitilaizeMapper();
            var context                = InMemoryDbContext.Initiliaze();
            var userRepository         = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userFollowerRepository = new EfRepository <UserFollower>(context);
            var profileService         = new ProfilesService(userRepository, userFollowerRepository);

            await this.SeedUsers(context);

            await userFollowerRepository.AddAsync(new UserFollower { UserId = "userOneId", FollowerId = "userTwoId", IsApproved = true });

            await userFollowerRepository.SaveChangesAsync();

            // Act
            var followings = await profileService.GetUserFollowingsAsync("userTwoUsername");

            string expectedUsername = userRepository.All().FirstOrDefault(u => u.Id == "userOneId").UserName;
            string actualUsername   = followings.FirstOrDefault().UserUserName;

            // Assert
            Assert.Equal(expectedUsername, actualUsername);
        }
Beispiel #18
0
        public async void ListAllUserFeedbackCorrectly()
        {
            var dbContext = new DbContextOptionsBuilder <ApplicationDbContext>()
                            .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var feedbackRepository = new EfDeletableEntityRepository <Feedback>(new ApplicationDbContext(dbContext.Options));

            feedbackRepository.SaveChangesAsync().GetAwaiter().GetResult();

            var service = new FeedbacksService(feedbackRepository);

            var user = new ApplicationUser
            {
                Id = Guid.NewGuid().ToString(),
            };

            var meeting = new Meeting
            {
                Id    = Guid.NewGuid().ToString(),
                Title = "Test 1",
            };

            var secondMeeting = new Meeting
            {
                Id    = Guid.NewGuid().ToString(),
                Title = "Test 2",
            };

            await service.AddAsync(user.Id, user, 6, "Awesome", meeting.Id, meeting);

            await service.AddAsync("Not user id", new ApplicationUser { }, 1, "Poor", secondMeeting.Id, secondMeeting);

            var list = service.GetUserFeedbacks(user.Id).ToList();

            Assert.Single(list);
        }
Beispiel #19
0
        public async Task DeleteByIdAsync_WithExistentId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "NutritionalValueService DeleteByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var nutritionalValueRepository = new EfDeletableEntityRepository <NutritionalValue>(context);
            var nutritionalValueService    = new NutritionalValueService(nutritionalValueRepository);
            var existentId = nutritionalValueRepository.All().First().Id;

            // Act
            var nutritionalValuesCount = nutritionalValueRepository.All().Count();
            await nutritionalValueService.DeleteByIdAsync(existentId);

            var actualResult   = nutritionalValueRepository.All().Count();
            var expectedResult = nutritionalValuesCount - 1;

            // Assert
            Assert.True(actualResult == expectedResult, errorMessagePrefix + " " + "NutritionalValues count is not reduced.");
        }
Beispiel #20
0
        public async Task FindProduct_WithExistingId_ShouldSuccessfullyFind()
        {
            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var groupRepository   = new EfDeletableEntityRepository <Product_Group>(context);
            var productRepository = new EfDeletableEntityRepository <Product>(context);

            var groupService   = new GroupService(groupRepository);
            var productService = new ProductService(productRepository, groupService);

            var seeder = new DbContextTestsSeeder();
            await seeder.SeedGroupAsync(context);

            await seeder.SeedProdcutAsync(context);

            // Act
            var result = productService.GetById("abc").Name;

            var actual = context.Products.SingleOrDefault(p => p.Id == "abc").Name;

            // Assert
            AssertExtension.EqualsWithMessage(actual, result, string.Format(ErrorMessage, "ProductGetIdByNameAndGroup"));
        }
Beispiel #21
0
        public async Task TestGetExercisesByCategoryAsync_WithValidData_ShouldReturnCorrectExercises()
        {
            MapperInitializer.InitializeMapper();
            var context    = ApplicationDbContextInMemoryFactory.InitializeContext();
            var repository = new EfDeletableEntityRepository <Exercise>(context);

            await repository.AddAsync(new Exercise { Name = "first", MuscleGroup = MuscleGroup.Abs });

            await repository.AddAsync(new Exercise { Name = "second", MuscleGroup = MuscleGroup.Abs });

            await repository.AddAsync(new Exercise { Name = "third", MuscleGroup = MuscleGroup.Shoulders });

            await repository.AddAsync(new Exercise { Name = "fourth", MuscleGroup = MuscleGroup.Upper_Legs });

            await repository.SaveChangesAsync();

            var service = new ExercisesService(repository);

            var exercises = await service.GetExercisesByCategoryAsync(false, null, MuscleGroup.Abs.ToString(), null);

            Assert.Equal(2, exercises.Count);
            Assert.Equal("first", exercises[0].Name);
            Assert.Equal("second", exercises[1].Name);
        }
Beispiel #22
0
        public async Task AddVisitsToUserShouldWorkCorrectly()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
            var db         = new ApplicationDbContext(options);
            var repository = new EfDeletableEntityRepository <Card>(db);
            var user       = new ApplicationUser();
            await repository.AddAsync(new Card()
            {
                User   = user,
                UserId = user.Id,
            });

            await repository.SaveChangesAsync();

            var service = new CardsService(repository, this.qrcodeService.Object, this.notificationsService.Object);

            var result = await service.AddVisitsToUser(user.Id, 12);

            var result2 = await service.AddVisitsToUser(user.Id, 12);

            Assert.Equal(12, result.Visits);
            Assert.Equal(12, result2.Visits);
        }
        public async void SendNotificationShouldHaveTheSameValuesAsTheSentOne()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var notificationRepository = new EfDeletableEntityRepository <Notification>(new ApplicationDbContext(options.Options));
            var userRepository         = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            var notificationsService = new NotificationsService(notificationRepository, userRepository);

            var notification = new Notification
            {
                DogsitterId = Guid.NewGuid().ToString(),
                OwnerId     = Guid.NewGuid().ToString(),
                Content     = "True",
            };

            await notificationRepository.SaveChangesAsync();

            await notificationsService.SendNotification(notification);

            var notifFromDb = await notificationRepository.All().FirstAsync();

            Assert.Equal(notification.Content, notifFromDb.Content);
        }
        public async Task EditAsync_WithNonExistentId_ShouldThrowArgumentNullException()
        {
            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var reservationStatusRepository = new EfDeletableEntityRepository <ReservationStatus>(context);
            var reservationStatusesService  = this.GetReservationStatusesService(reservationStatusRepository, context);

            var nonExistentId = Guid.NewGuid().ToString();

            var model = new EditReservationStatusViewModel
            {
                Id   = nonExistentId,
                Name = "Test-1-Edited",
            };

            // Act

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await reservationStatusesService.EditAsync(model);
            });
        }
Beispiel #25
0
        public async Task Handle_GivenInvalidRequest_ShouldThrowTeamFormatDoesNotMatchTournamentFormatException()
        {
            // Arrange
            var command = new EnrollATeamCommand {
                TableId = 2, TeamId = 123
            };

            var userAccessorMock = new Mock <IUserAccessor>();

            userAccessorMock.Setup(x => x.UserId).Returns("Foo2");

            var playersRepository          = new EfDeletableEntityRepository <Player>(this.dbContext);
            var tournamentTablesRepository = new EfDeletableEntityRepository <TournamentTable>(this.dbContext);

            var dataSet = new List <Team>(1)
            {
                new Team {
                    Id = 123, OwnerId = "Foo2", TournamentFormatId = 6969, Name = "MockTeam"
                }
            }
            .AsQueryable()
            .BuildMock();

            var teamsMockRepository = new Mock <IDeletableEntityRepository <Team> >();

            teamsMockRepository.Setup(x => x.AllAsNoTracking()).Returns(dataSet.Object);

            var sut = new EnrollATeamCommandHandler(
                teamsMockRepository.Object,
                playersRepository,
                tournamentTablesRepository,
                userAccessorMock.Object);

            // Act & Assert
            await Should.ThrowAsync <TeamFormatDoesNotMatchTournamentFormatException>(sut.Handle(command, It.IsAny <CancellationToken>()));
        }
        public async Task DeleteByIdAsync_WithExistentId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "ReservationStatusesService DeleteByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var reservationStatusRepository = new EfDeletableEntityRepository <ReservationStatus>(context);
            var reservationStatusesService  = this.GetReservationStatusesService(reservationStatusRepository, context);
            var seeder = new ReservationStatusesServiceTestsSeeder();
            await seeder.SeedReservationStatusesAsync(context);

            var reservationStatusId = reservationStatusRepository.All().First().Id;

            // Act
            var reservationStatusCount = reservationStatusRepository.All().Count();
            await reservationStatusesService.DeleteByIdAsync(reservationStatusId);

            var actualResult   = reservationStatusRepository.All().Count();
            var expectedResult = reservationStatusCount - 1;

            // Assert
            Assert.True(actualResult == expectedResult, errorMessagePrefix + " " + "Reservation ststuses count is not reduced.");
        }
Beispiel #27
0
        public async Task UnBanShouldUnBanUserAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            AutoMapperConfig.RegisterMappings(Assembly.Load("CookingBook.Web.ViewModels"));
            var dbContext = new ApplicationDbContext(options);
            var userRepo  = new EfDeletableEntityRepository <ApplicationUser>(dbContext);
            await userRepo.AddAsync(new ApplicationUser
            {
                Name               = "Trayan Keranov",
                Id                 = "trk",
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                PasswordHash       = "AQAAAAEAACcQAAAAEKDTOW0hiJThqFCz2cTS+wMBN2HthJkHT1jCsqVhgYwc0XikiVo0ESJYcqs8yrZkgg==",
                SecurityStamp      = "5ZMAFTFQEDOZPXC573KIOV5B56KVMHKS",
                ConcurrencyStamp   = "5ed4afbd-318e-456b-8d1b-19a36f2d82f1",
                CreatedOn          = DateTime.Parse("1993-03-21 08:10:00.2228617"),
                EmailConfirmed     = true,
                Roles              = new List <IdentityUserRole <string> >(),
                LockoutEnabled     = true,
                LockoutEnd         = DateTimeOffset.MaxValue,
            });

            await userRepo.SaveChangesAsync();

            var rolesRepo = new EfDeletableEntityRepository <ApplicationRole>(dbContext);
            var service   = new UsersService(userRepo, rolesRepo);

            await service.Unban("trk");

            Assert.Null(dbContext.Users.Find("trk").LockoutEnd);
            Assert.False(dbContext.Users.Find("trk").LockoutEnabled);
        }
        public async Task GetReservationStatusByNamec_WithExistentName_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ReservationStatusesService GetReservationStatusByName() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = HotelDbContextInMemoryFactory.InitializeContext();
            var reservationStatusRepository = new EfDeletableEntityRepository <ReservationStatus>(context);
            var reservationStatusesService  = this.GetReservationStatusesService(reservationStatusRepository, context);
            var seeder = new ReservationStatusesServiceTestsSeeder();
            await seeder.SeedReservationStatusesAsync(context);

            var reservationStatusName = reservationStatusRepository.All().First().Name;

            // Act
            var actualResult   = reservationStatusesService.GetReserVationStatusByName(reservationStatusName);
            var expectedResult = await reservationStatusRepository
                                 .All()
                                 .SingleOrDefaultAsync(x => x.Name == reservationStatusName);

            // Assert
            Assert.True(expectedResult.Id == actualResult.Id, errorMessagePrefix + " " + "Id is not returned properly.");
            Assert.True(expectedResult.Name == actualResult.Name, errorMessagePrefix + " " + "Name is not returned properly.");
        }
        public async Task ChangeStatusToPendingShouldChangeStatusOnExistingId()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "MyTestDb2")
                          .Options;
            var dbContext = new ApplicationDbContext(options);

            dbContext.Claims.Add(new InsuranceClaim {
                Id = 1, Status = ClaimStatus.Open
            });
            dbContext.Claims.Add(new InsuranceClaim {
                Id = 2, Status = ClaimStatus.Settled
            });
            await dbContext.SaveChangesAsync();

            var repository = new EfDeletableEntityRepository <InsuranceClaim>(dbContext);
            var service    = new ClaimService(repository);
            await service.ChangeStatusToPending(1);

            Assert.True((await repository.GetByIdAsync(1)).Status == ClaimStatus.Pending);
            await service.ChangeStatusToPending(2);

            Assert.True((await repository.GetByIdAsync(2)).Status == ClaimStatus.Pending);
        }
        public async Task DeleteUserShouldRemoveUserFromService()
        {
            AutoMapperConfig.RegisterMappings(typeof(UserTestModel).Assembly);

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            await repository.AddAsync(new ApplicationUser { Id = "test1", UserName = "******" });

            await repository.AddAsync(new ApplicationUser { Id = "test2", UserName = "******" });

            await repository.AddAsync(new ApplicationUser { Id = "test3", UserName = "******" });

            await repository.SaveChangesAsync();

            var mockedUserManager = MockUserManager <ApplicationUser>(repository.All().ToList());
            var service           = new UsersService(repository, null, null, null, mockedUserManager.Object);

            var outputMessage = await service.DeleteUserAsync("TestUser2");

            Assert.Equal($"User 'TestUser2' successfully deleted.", outputMessage);
            Assert.Equal(2, repository.All().Count());
        }