示例#1
0
        public void IsExistsReturnsTrueWhenRouteExists()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository = new EfDeletableEntityRepository <Route>(new ApplicationDbContext(options.Options));

            repository.AddAsync(new Route {
                StartPoint = "София", EndPoint = "Пловдив", Distance = 225
            });
            repository.AddAsync(new Route {
                StartPoint = "София", EndPoint = "Хасково", Distance = 267
            });
            repository.SaveChangesAsync();
            var routesService = new RoutesService(repository);

            var route  = repository.AllAsNoTracking().FirstOrDefault(r => r.StartPoint == "София" && r.EndPoint == "Пловдив");
            var exists = routesService.IsExists(route.StartPoint, route.EndPoint);

            Assert.True(exists);
        }
示例#2
0
        public async Task GetCountAsyncShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository = new EfDeletableEntityRepository <Category>(new ApplicationDbContext(options.Options));

            for (int i = 0; i < 3; i++)
            {
                await repository.AddAsync(new Category { Name = $"CategoryName{i}" });
            }

            await repository.SaveChangesAsync();

            var categoryService = new CategoriesService(repository);

            AutoMapperConfig.RegisterMappings(typeof(MyTestCategory).Assembly);

            var categoriesCount = await categoryService.GetCountAsync();

            Assert.Equal(3, categoriesCount);
        }
        public async Task GetByIdAsync_WithExistentId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ReviewService GetByIdAsync() method does not work properly.";

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

            await this.SeedRecipeAndUser(context);

            var reviewRepository = new EfDeletableEntityRepository <Review>(context);
            var reviewService    = this.GetReviewService(reviewRepository);
            var review           = new Review
            {
                Comment    = "Comment",
                Rating     = 5,
                RecipeId   = context.Recipes.First().Id,
                ReviewerId = context.Recipes.First().Id,
            };
            await reviewRepository.AddAsync(review);

            await reviewRepository.SaveChangesAsync();

            var existentId = reviewRepository.All().First().Id;

            // Act
            var actualResult = await reviewService.GetByIdAsync(existentId);

            var expectedResult = (await reviewRepository
                                  .All()
                                  .SingleOrDefaultAsync(x => x.Id == existentId))
                                 .To <ReviewServiceModel>();

            // Assert
            Assert.True(actualResult.Id == expectedResult.Id, errorMessagePrefix + " " + "Id is not returned properly.");
            Assert.True(actualResult.Comment == expectedResult.Comment, errorMessagePrefix + " " + "Comment is not returned properly.");
            Assert.True(actualResult.Rating == expectedResult.Rating, errorMessagePrefix + " " + "Rating is not returned properly.");
            Assert.True(actualResult.RecipeId == expectedResult.RecipeId, errorMessagePrefix + " " + "RecipeId is not returned properly.");
            Assert.True(actualResult.ReviewerId == expectedResult.ReviewerId, errorMessagePrefix + " " + "ReviewerId is not returned properly.");
        }
示例#4
0
        public void TestGetAllGames()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository         = new EfDeletableEntityRepository <Game>(new ApplicationDbContext(options.Options));
            var commentsRepository = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));

            var service = new GamesService(repository, commentsRepository);

            var game = new Game
            {
                Title       = "test",
                CategoryId  = 1,
                Description = "sds",
                ReleaseDate = DateTime.UtcNow,
                CompanyName = "tests",
                PictureUrl  = "est",
            };

            var game2 = new Game
            {
                Title       = "tes2t",
                CategoryId  = 1,
                Description = "sds",
                ReleaseDate = DateTime.UtcNow,
                CompanyName = "tests",
                PictureUrl  = "est",
            };

            repository.AddAsync(game).GetAwaiter().GetResult();
            repository.AddAsync(game2).GetAwaiter().GetResult();
            repository.SaveChangesAsync();

            var games = service.GetAllGames();

            var counter = games.Games.Count();

            Assert.Equal(2, counter);
        }
示例#5
0
        public async Task GetByIdAsyncShouldWorkCorrectlyWhitTypeMobile()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var numberRepo = new EfDeletableEntityRepository <ServiceNumber>(dbContext);

            var service = new ServiceNumbersService(numberRepo);

            await numberRepo.AddAsync(new ServiceNumber
            {
                Number = "866666666",
                IsFree = true,
            });

            await numberRepo.AddAsync(new ServiceNumber
            {
                Number = "866666661",
                IsFree = false,
            });

            await numberRepo.AddAsync(new ServiceNumber
            {
                Number = "N.123456",
                IsFree = true,
            });

            await numberRepo.AddAsync(new ServiceNumber
            {
                Number = "TV.123456",
                IsFree = true,
            });

            await numberRepo.SaveChangesAsync();

            var number = await service.GetByIdAsync(1);

            Assert.Equal("866666666", number);
        }
示例#6
0
        public async Task GetAllCategoriesAsyncShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryArticle         = new EfDeletableEntityRepository <Article>(dbContext);
            var repositoryNewsFeedPost    = new EfDeletableEntityRepository <NewsFeedPost>(dbContext);
            var repositoryNewsFeedComment = new EfDeletableEntityRepository <NewsFeedComment>(dbContext);
            var repositoryCategory        = new EfDeletableEntityRepository <Category>(dbContext);
            var repositoryComment         = new EfDeletableEntityRepository <Comment>(dbContext);

            var categoryOne = new Category
            {
                Title       = "test",
                Name        = "test",
                Description = "TEST",
            };

            var categoryTwo = new Category
            {
                Title       = "test",
                Name        = "test",
                Description = "TEST",
            };

            await repositoryCategory.AddAsync(categoryOne);

            await repositoryCategory.AddAsync(categoryTwo);

            await repositoryCategory.SaveChangesAsync();

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

            var service = new AdministratorService(repositoryNewsFeedPost, repositoryArticle, repositoryNewsFeedComment, repositoryCategory, repositoryComment);

            var category = await service.GetAllCategoriesAsync <CategoryTestViewModel>();

            Assert.Equal(2, category.Count());
        }
示例#7
0
        public async Task GetTopFourMostWatchedCarsOfUserAsyncTest()
        {
            var options        = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString());
            var carRepository  = new EfDeletableEntityRepository <Car>(new ApplicationDbContext(options.Options));
            var viewRepository = new EfDeletableEntityRepository <AdView>(new ApplicationDbContext(options.Options));
            var adService      = new Mock <IAdService>();
            var viewService    = new ViewService(viewRepository);

            var homeService = new HomeService(carRepository, adService.Object, viewService);

            await SeedData(carRepository);

            // id=car2-first, id=car4-second(created later than id=car3), id=car3 - third, id=car5-fourth id=car1-not approved
            await viewRepository.AddAsync(new AdView { CarId = "car1", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car2", User = "******" });

            await viewRepository.AddAsync(new AdView { CarId = "car2", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car2", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car3", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car3", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car4", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car4", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.AddAsync(new AdView { CarId = "car5", User = GlobalConstants.NotRegisterUserId });

            await viewRepository.SaveChangesAsync();

            var result = await homeService.GetTopFourMostWatchedCarsOfUserAsync("1");

            Assert.Equal("car2", result.ToArray()[0].Id);
            Assert.Equal("car4", result.ToArray()[1].Id);
            Assert.Equal("car3", result.ToArray()[2].Id);
            Assert.Equal("car5", result.ToArray()[3].Id);
        }
        public void TestAddJobCorrectId()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository =
                new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));
            var studentEfRepository =
                new EfRepository <StudentJob>(new ApplicationDbContext(options.Options));
            var userSkillRepository =
                new EfRepository <UsersSkill>(new ApplicationDbContext(options.Options));
            var jobRepository =
                new EfDeletableEntityRepository <Job>(new ApplicationDbContext(options.Options));
            var jobService      = new JobsService(jobRepository, studentEfRepository);
            var skillRepository =
                new EfDeletableEntityRepository <Skill>(new ApplicationDbContext(options.Options));
            var skillService = new SkillsService(skillRepository, userSkillRepository);
            var usersService = new ApplicationUsersService(repository, jobService, studentEfRepository, jobRepository,
                                                           skillService, userSkillRepository, skillRepository);
            var user = new ApplicationUser
            {
                Description = "test",
                Type        = UserType.Student,
            };
            var user1 = new ApplicationUser
            {
                Description = "test1",
                Type        = UserType.Student,
            };
            var job = new Job
            {
                Title = "test",
            };

            jobRepository.AddAsync(job).GetAwaiter().GetResult();
            jobRepository.SaveChangesAsync().GetAwaiter().GetResult();
            repository.AddAsync(user1).GetAwaiter().GetResult();
            repository.SaveChangesAsync().GetAwaiter().GetResult();
            AutoMapperConfig.RegisterMappings(typeof(CompaniesServiceTests.MyTest).Assembly);
            Assert.NotNull(studentEfRepository.All());
        }
        public async Task CorrectInputToGettingByNameShouldReturnTrue()
        {
            var builder = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var dbContext = new ApplicationDbContext(builder.Options);

            var categoriesRepository    = new EfDeletableEntityRepository <Category>(dbContext);
            var subCategoriesRepository = new EfDeletableEntityRepository <SubCategory>(dbContext);

            var profile       = new FamilyKitchenProfile();
            var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));
            var mapper        = new Mapper(configuration);

            var categoriesService = new CategoriesService(categoriesRepository, subCategoriesRepository, mapper);

            await categoriesRepository.AddAsync(new Category
            {
                Name          = "Drinks",
                SubCategories = new List <SubCategory>
                {
                    new SubCategory {
                        Name = "Alcohol", Category = new Category {
                            Name = "Drinks",
                        },
                    },
                    new SubCategory {
                        Name = "Water", Category = new Category {
                            Name = "Drinks",
                        },
                    },
                },
            });

            await categoriesRepository.SaveChangesAsync();

            var category = categoriesService.GetByName("Drinks");

            Assert.Equal("Drinks", category.Name);
        }
示例#10
0
        public async Task DeleteArticleShouldReturnCorrectCountAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryArticle         = new EfDeletableEntityRepository <Article>(dbContext);
            var repositoryNewsFeedPost    = new EfDeletableEntityRepository <NewsFeedPost>(dbContext);
            var repositoryNewsFeedComment = new EfDeletableEntityRepository <NewsFeedComment>(dbContext);
            var repositoryCategory        = new EfDeletableEntityRepository <Category>(dbContext);
            var repositoryComment         = new EfDeletableEntityRepository <Comment>(dbContext);

            var service = new AdministratorService(repositoryNewsFeedPost, repositoryArticle, repositoryNewsFeedComment, repositoryCategory, repositoryComment);

            var articleOne = new Article
            {
                Id      = 1,
                Title   = "test",
                Content = "test",
                UserId  = "1",
            };

            var articleTwo = new Article
            {
                Id      = 2,
                Title   = "testTwo",
                Content = "testTwo",
                UserId  = "1",
            };

            await repositoryArticle.AddAsync(articleOne);

            await repositoryArticle.AddAsync(articleTwo);

            await repositoryArticle.SaveChangesAsync();

            await service.DeleteArticleAsync(articleOne);

            Assert.Equal(1, repositoryArticle.All().Count());
        }
        public async Task GetAdditionalInfoByUserIdAsync_WithExistentUserId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "UserService GetAdditionalInfoByUserIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context        = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userRepository = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userService    = this.GetUserService(userRepository, context);

            await this.SeedDataAsync(context);

            var user = userRepository.All().First();

            user.FullName     = "FullName";
            user.Biography    = "Biography";
            user.ProfilePhoto = "ProfilePhoto";
            user.Lifestyle    = context.Lifestyles.First();
            user.Allergies.Add(new UserAllergen()
            {
                Allergen = context.Allergens.First(),
            });
            userRepository.Update(user);
            await userRepository.SaveChangesAsync();

            // Act
            var actualResult = await userService.GetAdditionalInfoByUserIdAsync(user.Id);

            var expectedResult = userRepository
                                 .All()
                                 .First()
                                 .To <UserAdditionalInfoServiceModel>();

            // Assert
            Assert.True(expectedResult.FullName == actualResult.FullName, errorMessagePrefix + " " + "FullName is not returned properly.");
            Assert.True(expectedResult.Biography == actualResult.Biography, errorMessagePrefix + " " + "Biography is not returned properly.");
            Assert.True(expectedResult.ProfilePhoto == actualResult.ProfilePhoto, errorMessagePrefix + " " + "ProfilePhoto is not returned properly.");
            Assert.True(expectedResult.Lifestyle.Id == actualResult.Lifestyle.Id, errorMessagePrefix + " " + "Lifestyle is not returned properly.");
            Assert.True(expectedResult.Allergies.First().Allergen.Id == actualResult.Allergies.First().Allergen.Id, errorMessagePrefix + " " + "Allergen is not returned properly.");
        }
        public async Task UpdateCardTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var cardsRepository = new EfDeletableEntityRepository <Card>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetCardsData())
            {
                await cardsRepository.AddAsync(item);

                await cardsRepository.SaveChangesAsync();
            }

            var decksRepository = new EfDeletableEntityRepository <Deck>(new ApplicationDbContext(options.Options));

            foreach (var deck in this.GetDecksData())
            {
                await decksRepository.AddAsync(deck);

                await decksRepository.SaveChangesAsync();
            }

            var store           = new Mock <IUserStore <ApplicationUser> >();
            var mockUserManager = new Mock <UserManager <ApplicationUser> >(store.Object, null, null, null, null, null, null, null, null);

            var service = new DecksService(decksRepository, cardsRepository, mockUserManager.Object);

            await service.UpdateCard("NEWFRONT", "NEWBACK", "2", "User1");

            await service.UpdateCard("NEWFRONT2", "NEWBACK2", "3", "User1");

            var card1 = cardsRepository.All().FirstOrDefault(x => x.Id == "2");
            var card2 = cardsRepository.All().FirstOrDefault(x => x.Id == "3");

            Assert.Equal("NEWFRONT", card1.FrontSide);
            Assert.Equal("NEWBACK", card1.BackSide);

            Assert.Equal("front3", card2.FrontSide);
            Assert.Equal("back3", card2.BackSide);
        }
示例#13
0
        public async Task Handle_GivenValidRequest_ShouldEnrollTeam()
        {
            // Arrange
            var command = new EnrollATeamCommand {
                TableId = 2, TeamId = 2
            };

            var userAccessorMock = new Mock <IUserAccessor>();

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


            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
            var teamToBeEnrolled = teamsRepository.All().FirstOrDefault(t => t.Id == 2);

            for (int i = 0; i < 6; i++)
            {
                teamToBeEnrolled.PlayerTeams.Add(new PlayerTeam()
                {
                    PlayerId = $"FooPlayer{i + 11}", TeamId = 2
                });
            }

            await teamsRepository.SaveChangesAsync();

            var rowsAffected = await sut.Handle(command, It.IsAny <CancellationToken>());

            // Assert
            rowsAffected.ShouldBe(2);
        }
示例#14
0
        public async Task GetCompanyProfileInformationByUserIdTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository = new EfDeletableEntityRepository <CompanyInfo>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetCompanyInfoData())
            {
                await repository.AddAsync(item);

                await repository.SaveChangesAsync();
            }

            var service = new CompanyProfileService(repository);

            AutoMapperConfig.RegisterMappings(typeof(CompanyProfileViewModel).Assembly);

            var profile = service.GetCompanyProfileInformationByUserId <CompanyProfileViewModel>("1");

            Assert.Equal("bcsuigvfdgvdfcdz", profile.Address);
        }
示例#15
0
        public async Task DeleteMovieShouldDeleteTargetMovieByid()
        {
            AutoMapperConfig.RegisterMappings(typeof(MovieTestModel).Assembly);

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

            await repository.AddAsync(new Movie { Id = 1, Name = "Movie1" });

            await repository.AddAsync(new Movie { Id = 2, Name = "Movie2" });

            await repository.AddAsync(new Movie { Id = 3, Name = "Movie3" });

            await repository.SaveChangesAsync();

            var service = new MoviesService(repository, null, null, null);

            await service.DeleteMovieAsync(2);

            Assert.Equal(2, repository.All().Count());
        }
        public async Task GetSegmentsTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var segmentsRepository = new EfDeletableEntityRepository <Segment>(new ApplicationDbContext(options.Options));

            foreach (var segment in this.GetSegmentsData())
            {
                await segmentsRepository.AddAsync(segment);

                await segmentsRepository.SaveChangesAsync();
            }

            var mockLessonsRepository = new Mock <IDeletableEntityRepository <Lesson> >();
            var mockCoursesRepository = new Mock <IDeletableEntityRepository <Course> >();

            AutoMapperConfig.RegisterMappings(typeof(StudySegmentViewModel).Assembly);
            var service  = new SegmentsService(segmentsRepository, mockLessonsRepository.Object, mockCoursesRepository.Object);
            var segments = service.GetSegments <StudySegmentViewModel>("lesson1");

            Assert.Equal(2, segments.Count());
        }
        public async Task DeleteSegmentTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var segmentsRepository = new EfDeletableEntityRepository <Segment>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetSegmentsData())
            {
                await segmentsRepository.AddAsync(item);

                await segmentsRepository.SaveChangesAsync();
            }

            var lessonsRepository = new EfDeletableEntityRepository <Lesson>(new ApplicationDbContext(options.Options));

            foreach (var lesson in this.GetLessonData())
            {
                await lessonsRepository.AddAsync(lesson);

                await lessonsRepository.SaveChangesAsync();
            }

            var coursesRepository = new EfDeletableEntityRepository <Course>(new ApplicationDbContext(options.Options));

            foreach (var course in this.GetCourseData())
            {
                await coursesRepository.AddAsync(course);

                await coursesRepository.SaveChangesAsync();
            }

            var service = new SegmentsService(segmentsRepository, lessonsRepository, coursesRepository);
            await service.DeleteSegment("1", "User1");

            Assert.Equal(2, segmentsRepository.All().Count());
            await service.DeleteSegment("2", "User2");

            Assert.Equal(2, segmentsRepository.All().Count());
        }
        public async Task EditeAsyncWithDublicateNameShouldThrowArgumentException()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext        = new ApplicationDbContext(options);
            var cloudinary       = new Mock <ICloudinaryService>();
            var venuesRepository = new EfDeletableEntityRepository <Venue>(dbContext);
            var venuesService    = new VenuesService(venuesRepository, cloudinary.Object);
            var photo            = new Mock <IFormFile>();

            await venuesRepository.AddAsync(new Venue
            {
                Name     = "Port Varna",
                ImgUrl   = "https://res.cloudinary.com/nikolacgeorgiev/image/upload/v1587377702/venues_photos/Port_Varna_t44ryy.jpg",
                Country  = "Bulgaria",
                City     = "Varna",
                Address  = "Sq. Slaveykov 1",
                Capacity = 30000,
            });

            await venuesRepository.SaveChangesAsync();

            var id = await venuesService.CreateAsync("Rowing Canal", photo.Object, "Bulgaria", "Plovdiv", "Yasna Polyana", 70000);

            var venue = new VenueEditInputModel
            {
                Name     = "Port Varna",
                ImgUrl   = "https://res.cloudinary.com/nikolacgeorgiev/image/upload/v1587377745/venues_photos/Rowing_Canal_g5uvuq.jpg",
                Country  = "Bulgaria",
                City     = "Plovdiv",
                Address  = "Yasna Polyana",
                Capacity = 70000,
            };

            await Assert.ThrowsAsync <ArgumentException>(async() =>
            {
                await venuesService.EditAsync(id, venue);
            });
        }
        public async void RemoveQuestionsAnswersFromUserAsyncShouldRemoveDataAccordingly()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var userRepository     = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));
            var questionRepository = new EfDeletableEntityRepository <QuestionAnswer>(new ApplicationDbContext(options.Options));

            var administartorService = new AdministartorService(userRepository, questionRepository);


            var user = new ApplicationUser();

            var questionAnswer = new List <QuestionAnswer>
            {
                new QuestionAnswer {
                    UserId = user.Id
                },
                new QuestionAnswer {
                    UserId = user.Id
                },
                new QuestionAnswer {
                    UserId = user.Id
                },
                new QuestionAnswer {
                    UserId = user.Id
                },
            };

            foreach (var qa in questionAnswer)
            {
                await questionRepository.AddAsync(qa);
            }

            await questionRepository.SaveChangesAsync();

            await administartorService.RemoveQuestionsAnswersFromUserAsync(user.Id);

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

            var userRepo = new EfDeletableEntityRepository <ApplicationUser>(dbContext);

            var service = new EmployeesService(userRepo);

            await userRepo.AddAsync(new ApplicationUser
            {
                FirstName  = "ivan",
                LastName   = "ivanov",
                MiddleName = "ivanov",
                EGN        = "1234567890",
            });

            await userRepo.SaveChangesAsync();

            Assert.False(await service.ExistAsync(Guid.NewGuid().ToString()));
        }
示例#21
0
        public async Task GetAllNewsFeedPostAsyncShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryArticle         = new EfDeletableEntityRepository <Article>(dbContext);
            var repositoryNewsFeedPost    = new EfDeletableEntityRepository <NewsFeedPost>(dbContext);
            var repositoryNewsFeedComment = new EfDeletableEntityRepository <NewsFeedComment>(dbContext);
            var repositoryCategory        = new EfDeletableEntityRepository <Category>(dbContext);
            var repositoryComment         = new EfDeletableEntityRepository <Comment>(dbContext);


            var postOne = new NewsFeedPost
            {
                Content = "Test",
                UserId  = "1",
            };

            var postTwo = new NewsFeedPost
            {
                Content = "Test",
                UserId  = "1",
            };

            await repositoryNewsFeedPost.AddAsync(postOne);

            await repositoryNewsFeedPost.AddAsync(postTwo);

            await repositoryNewsFeedPost.SaveChangesAsync();

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

            var service = new AdministratorService(repositoryNewsFeedPost, repositoryArticle, repositoryNewsFeedComment, repositoryCategory, repositoryComment);

            var result = await service.GetAllNewsFeedPostAsync <TimeLineAllPostsViewModelTest>();

            Assert.Equal(2, result.Count());
        }
示例#22
0
        public async Task AddToAdminsShouldCreateNewUserRole()
        {
            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);
            await rolesRepo.AddAsync(new ApplicationRole { Name = GlobalConstants.AdministratorRoleName, Id = "admin", CreatedOn = DateTime.MinValue, ConcurrencyStamp = "asdfghjkl", NormalizedName = "ADMIN" });

            await rolesRepo.SaveChangesAsync();

            var service = new UsersService(userRepo, rolesRepo);

            await service.AddToAdmins("trk");

            Assert.Equal(1, dbContext.Users.Find("trk").Roles.Count);
        }
        public async void SendNotificationShouldSaveTheNotificationProperly()
        {
            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);

            Assert.Single(notificationRepository.All());
        }
        public async void RemoveCommentNotificationShouldReturnProperCount()
        {
            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();
            var notification2 = new Notification();

            await notificationRepository.AddAsync(notification);

            await notificationRepository.AddAsync(notification2);

            await notificationRepository.SaveChangesAsync();

            await notificationsService.RemoveCommentNotification(notification.Id);

            Assert.Single(notificationRepository.AllAsNoTracking());
        }
        public async Task TestGetAllCities()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase("Cities");

            var cityRepository = new EfDeletableEntityRepository <City>(new ApplicationDbContext(options.Options));

            await cityRepository.AddAsync(new City { Name = "София" });

            await cityRepository.AddAsync(new City { Name = "Стара Загора" });

            await cityRepository.AddAsync(new City { Name = "Пловдив" });

            await cityRepository.SaveChangesAsync();

            var cityService = new CitiesService(cityRepository);

            AutoMapperConfig.RegisterMappings(typeof(MyTestCity).Assembly);
            var cities = cityService.GetAll <MyTestCity>();

            Assert.Equal(3, cities.Count());
        }
        public async Task MarkJobPostingAsDeletedTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository = new EfDeletableEntityRepository <JobPosting>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetJobPostingData())
            {
                await repository.AddAsync(item);

                await repository.SaveChangesAsync();
            }

            var service = new JobPostingsService(repository);

            await service.MarkJobPostingAsDeleted("2222");

            var user = repository.AllWithDeleted().Where(x => x.Id == "2222").FirstOrDefault();

            Assert.True(user.IsDeleted);
        }
示例#27
0
        public async Task ChangeUserIsAuthorizeSatusByUserIdAsync_WithCorrectData_ShouldChangeUserStatus()
        {
            var context    = SteuDbContextInMemoryFactory.InitializeContext();
            var service    = this.IntializeUsersService(context);
            var repository = new EfDeletableEntityRepository <SteuUser>(context);

            var user = new SteuUser()
            {
                Id          = "userId",
                IsAuthorize = false,
            };

            await repository.AddAsync(user);

            await repository.SaveChangesAsync();

            await service.ChangeUserIsAuthorizeSatusByUserIdAsync("userId", "true");

            var actualResultUser = await repository.All().SingleOrDefaultAsync(x => x.Id == "userId");

            Assert.True(actualResultUser.IsAuthorize);
        }
示例#28
0
        public void TestGetAuthorJobNoExistId()
        {
            ApplicationUser user     = new ApplicationUser();
            Category        category = new Category();
            var             notReal  = "sdaasdasg";
            var             options  = new DbContextOptionsBuilder <ApplicationDbContext>()
                                       .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository  = new EfDeletableEntityRepository <Job>(new ApplicationDbContext(options.Options));
            var studentRepo = new EfRepository <StudentJob>(new ApplicationDbContext(options.Options));

            repository.AddAsync(new Job
            {
                ApplicationUser = user,
                Salary          = 900,
                Description     = "test",
            });
            repository.SaveChangesAsync().GetAwaiter().GetResult();
            var jobService = new JobsService(repository, studentRepo);

            AutoMapperConfig.RegisterMappings(typeof(MyTestJob).Assembly);
            Assert.Empty(jobService.GetById <MyTestJob>(notReal));
        }
示例#29
0
        public async void DogsitterDetailsByIdTemplateShouldReturnProperType()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var userRepository      = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));
            var dogsitterRepository = new EfDeletableEntityRepository <Dogsitter>(new ApplicationDbContext(options.Options));
            var ownerRepository     = new EfDeletableEntityRepository <Owner>(new ApplicationDbContext(options.Options));

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

            var ownersService = new OwnersService(userRepository, ownerRepository, dogsitterRepository);

            var dogsitter = new Dogsitter();

            await dogsitterRepository.AddAsync(dogsitter);

            await dogsitterRepository.SaveChangesAsync();

            var dogsitterDb = ownersService.DogsitterDetailsById <DogsitterInfoViewModel>(dogsitter.Id);

            Assert.IsType <DogsitterInfoViewModel>(dogsitterDb);
        }
示例#30
0
        public void TestGetJobByIncorrectId()
        {
            ApplicationUser user     = new ApplicationUser();
            Category        category = new Category();
            var             options  = new DbContextOptionsBuilder <ApplicationDbContext>()
                                       .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository  = new EfDeletableEntityRepository <Job>(new ApplicationDbContext(options.Options));
            var studentRepo = new EfRepository <StudentJob>(new ApplicationDbContext(options.Options));
            var job         = new Job
            {
                ApplicationUser = user,
                Salary          = 900,
                Description     = "test",
            };

            repository.AddAsync(job);
            repository.SaveChangesAsync().GetAwaiter().GetResult();
            var jobService = new JobsService(repository, studentRepo);

            AutoMapperConfig.RegisterMappings(typeof(MyTestJob).Assembly);
            Assert.Throws <Exception>(() => jobService.GetJobById <MyTestJob>(18683));
        }