public async void GetAllByUserId_ShouldReturnAllUsersAddressesByUserId()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetAllByUserId_ShouldReturnAllUsersAddressesByUserId")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            await SeedData(context);

            IUserService    userService    = new UserService(context);
            IAddressService addressService = new AddressService(context, userService);

            TechAndToolsUser testUser = new TechAndToolsUser
            {
                Id       = "testId",
                UserName = "******",
                Email    = "testEmail"
            };

            await context.AddAsync(testUser);

            await context.SaveChangesAsync();

            int expectedResult = context.Addresses.Where(x => x.TechAndToolsUserId == "testId").ToList().Count;
            int actualResult   = addressService.GetAllByUserId("testId").ToList().Count;

            Assert.Equal(expectedResult, actualResult);
        }
Ejemplo n.º 2
0
        public async Task EditCategoryAsync_ShouldEditCategoryById()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "EditCategoryAsync_ShouldEditCategoryById")
                          .Options;

            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            ICategoryService categoryService = new CategoryService(context);

            var categoryId        = 1;
            var newName           = "newName";
            var newMainCategoryId = 2;

            var expectedData = context.Categories.Find(categoryId).To <CategoryServiceModel>();

            expectedData.MainCategoryId = newMainCategoryId;
            expectedData.Name           = newName;

            await categoryService.EditCategoryAsync(expectedData);

            var actualData = context.Categories.Find(categoryId);

            Assert.Equal(expectedData.Name, actualData.Name);
            Assert.Equal(expectedData.MainCategoryId, actualData.MainCategoryId);
        }
        public async void CreateAsync_ShouldCreateSuppliersAndAddToDatabase()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateAsync_ShouldCreateSuppliersAndAddToDatabase")
                          .Options;

            TechAndToolsDbContext dbContext = new TechAndToolsDbContext(options);

            ISupplierService supplierService = new SupplierService(dbContext);

            await supplierService.CreateAsync(new SupplierServiceModel
            {
                Name = "name1",
                DeliveryTimeInDays = 2,
                PriceToAddress     = 2,
                PriceToOffice      = 3
            });

            await supplierService.CreateAsync(new SupplierServiceModel
            {
                Name = "name2",
                DeliveryTimeInDays = 3,
                PriceToAddress     = 3,
                PriceToOffice      = 4
            });

            int expectedResult = 2;

            int actualResult = await dbContext.Suppliers.CountAsync();

            Assert.Equal(expectedResult, actualResult);
        }
        public async void CreateAsync_WithIncorrectUserShouldThrowException()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateAsync_WithIncorrectUserShouldThrowException")
                          .Options;

            TechAndToolsDbContext context        = new TechAndToolsDbContext(options);
            IUserService          userService    = new UserService(context);
            IAddressService       addressService = new AddressService(context, userService);

            TechAndToolsUser testUser = new TechAndToolsUser
            {
                UserName = "******",
                Email    = "testEmail"
            };

            await context.AddAsync(testUser);

            await context.SaveChangesAsync();


            AddressServiceModel serviceModel = new AddressServiceModel
            {
                Id                 = 1,
                City               = "CityTest1",
                CityAddress        = "CityAddressTest1",
                PostCode           = 9000,
                TechAndToolsUserId = Guid.NewGuid().ToString()
            };

            await Assert.ThrowsAsync <ArgumentNullException>(() => addressService.CreateAsync(serviceModel, "wrongUsername"));
        }
Ejemplo n.º 5
0
 private async Task SeedData(TechAndToolsDbContext context)
 {
     context.AddRange(this.GetProductsData());
     context.AddRange(this.GetArticlesData());
     context.AddRange(this.GetImagesData());
     await context.SaveChangesAsync();
 }
        public async Task EditBrandAsync_ShouldEditBrandById()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "EditBrandAsync_ShouldEditBrandById")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            await SeedData(context);

            IBrandService brandService = new BrandService(context);

            Brand expectedData = context.Brands.First();

            expectedData.Name         = "New Name";
            expectedData.LogoUrl      = "New Logo";
            expectedData.OfficialSite = "New Site";

            BrandServiceModel serviceModel = expectedData.To <BrandServiceModel>();

            BrandServiceModel actualData = await brandService.EditAsync(serviceModel);

            Assert.Equal(expectedData.Id, actualData.Id);
            Assert.Equal(expectedData.Name, actualData.Name);
            Assert.Equal(expectedData.LogoUrl, actualData.LogoUrl);
            Assert.Equal(expectedData.OfficialSite, actualData.OfficialSite);
            Assert.NotNull(actualData);
            Assert.NotNull(actualData.Products);
        }
 private async Task SeedData(TechAndToolsDbContext context)
 {
     context.AddRange(this.GetProductsData());
     context.Users.Add(this.GetTestUser());
     context.FavoriteProducts.AddRange(this.GetFavoriteProductsData());
     await context.SaveChangesAsync();
 }
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger(typeof(TechAndToolsDbContext));

            var seeders = new List <ISeeder>
            {
                new RolesSeeder(),
                new PaymentStatusesSeeder(),
                new PaymentTypesSeeder(),
                new OrderStatusesSeeder(),
                new SeedRootAdminUser()
            };

            foreach (var seeder in seeders)
            {
                await seeder.SeedAsync(dbContext, serviceProvider);

                await dbContext.SaveChangesAsync();

                logger.LogInformation($"Seeder {seeder.GetType().Name} done.");
            }
        }
Ejemplo n.º 9
0
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            var userManager = serviceProvider.GetRequiredService <UserManager <TechAndToolsUser> >();

            var hasAdmin = userManager.GetUsersInRoleAsync(GlobalConstants.AdminRole).Result.Any();

            if (!hasAdmin)
            {
                TechAndToolsUser admin = new TechAndToolsUser
                {
                    UserName             = GlobalConstants.AdminUsername,
                    FirstName            = GlobalConstants.AdminFirstName,
                    LastName             = GlobalConstants.AdminLastName,
                    Email                = GlobalConstants.AdminEmail,
                    CreatedOn            = DateTime.UtcNow,
                    PhoneNumber          = GlobalConstants.AdminPhoneNumber,
                    PhoneNumberConfirmed = true,
                    EmailConfirmed       = true,
                    ShoppingCart         = new ShoppingCart()
                };

                var password = GlobalConstants.AdminPassword;

                await userManager.CreateAsync(admin, password);

                await userManager.AddToRoleAsync(admin, GlobalConstants.AdminRole);
            }
        }
Ejemplo n.º 10
0
        public async Task CreateAsync_ShouldCreateAContact()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateAsync_ShouldCreateAContact")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            IContactService contactService = new ContactService(context);

            await contactService.CreateAsync(new ContactServiceModel
            {
                FullName = "Full Name Test 1",
                Email    = "*****@*****.**",
                Message  = "test1 message"
            });

            await contactService.CreateAsync(new ContactServiceModel
            {
                FullName = "Full Name Test 2",
                Email    = "*****@*****.**",
                Message  = "test2 message"
            });

            const int expectedResult = 2;

            int actualResult = context.Contacts.Count();

            Assert.Equal(expectedResult, actualResult);
        }
Ejemplo n.º 11
0
        public async void CreateArticleAsync_ShouldCreateAndAddArticlesToDatabase()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateArticleAsync_ShouldCreateAndAddArticlesToDatabase")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            IArticleService articleService = new ArticleService(context);

            string authorId = "998DC52A-7FA4-461F-9F79-3F9720D64C01";

            int articleId = 111;

            var actualResult = await articleService.CreateArticleAsync(new ArticleServiceModel
            {
                Id      = articleId,
                Title   = "title1",
                Content = "content1111111111111111111",
                Image   = new ImageServiceModel
                {
                    ArticleId = articleId,
                    ImageUrl  = "url"
                }
            }, authorId);

            int expectedCount = 1;
            var actualCount   = context.Articles.ToList().Count;

            Assert.Equal(actualCount, expectedCount);
        }
Ejemplo n.º 12
0
        public async void EditArticleAsync_ShouldEditArticleById()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateArticleAsync_ShouldCreateAndAddArticlesToDatabase")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            IArticleService articleService = new ArticleService(context);

            await this.SeedData(context);

            var actualResult = await articleService.EditArticleAsync(new ArticleServiceModel
            {
                Id       = 1,
                Title    = "new title",
                Content  = "new content",
                AuthorId = "998DC52A-7FA4-461F-9F79-3F9720D64C01",
                Image    = new ImageServiceModel
                {
                    ArticleId = 1,
                    ImageUrl  = "Url"
                }
            });


            Assert.Equal("new title", actualResult.Title);
            Assert.Equal("new content", actualResult.Content);
        }
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            await SeedRoleAsync(roleManager, GlobalConstants.AdminRole);
            await SeedRoleAsync(roleManager, GlobalConstants.UserRole);
        }
Ejemplo n.º 14
0
        public async void CreateCategoryAsync_ShouldCreateCategory()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateCategoryAsync_ShouldCreateCategory")
                          .Options;

            var context = new TechAndToolsDbContext(options);

            context.Database.EnsureDeleted();

            var mainCategory = new MainCategory
            {
                Id   = 1,
                Name = "PC"
            };

            await context.MainCategories.AddAsync(mainCategory);

            await context.SaveChangesAsync();

            ICategoryService categoryService = new CategoryService(context);

            await categoryService.CreateCategoryAsync(new CategoryServiceModel { Name = "category1", MainCategoryId = 1 });

            await categoryService.CreateCategoryAsync(new CategoryServiceModel { Name = "category2", MainCategoryId = 1 });

            int expectedResult = 2;
            int actualResult   = context.Categories.Count();

            Assert.Equal(expectedResult, actualResult);
        }
        public async void CreateMainCategoryAsyncShouldCreateMainCategory()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateMainCategoryAsyncShouldCreateMainCategory")
                          .Options;

            var context = new TechAndToolsDbContext(options);

            IMainCategoryService mainCategoryService = new MainCategoryService(context);

            await mainCategoryService.CreateAsync(new MainCategoryServiceModel { Name = "PC" });

            await mainCategoryService.CreateAsync(new MainCategoryServiceModel { Name = "Tools" });

            MainCategory first  = context.MainCategories.First();
            MainCategory second = context.MainCategories.Last();

            Assert.Equal(2, context.MainCategories.Count());
            Assert.Equal("PC", first.Name);
            Assert.Equal("Tools", second.Name);
            Assert.NotNull(first);
            Assert.NotNull(first.Categories);
            Assert.NotNull(second);
            Assert.NotNull(second.Categories);
        }
        public async Task AddProductInShoppingCartAsync_WithAlreadyAddedProductInShoppingCartShouldIncreaseShoppingCartProductQuantity()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddProductInShoppingCartAsync_WithAlreadyAddedProductInShoppingCartShouldIncreaseShoppingCartProductQuantity")
                          .Options;
            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            const string username        = "******";
            const int    productId       = 1;
            const int    defaultQuantity = 1;
            const int    expectedCount   = 1;

            var userService = new Mock <IUserService>();

            userService.Setup(r => r.GetUserByUsername(username))
            .Returns(context.Users.FirstOrDefault(x => x.UserName == username));

            var productService = new Mock <IProductService>();

            productService.Setup(p => p.GetProductById(productId))
            .Returns(context.Products.Find(productId).To <ProductServiceModel>());

            IShoppingCartService shoppingCartsService = new ShoppingCartService(context, productService.Object, userService.Object);

            await shoppingCartsService.AddToShoppingCartAsync(productId, username, defaultQuantity);

            var user = userService.Object.GetUserByUsername(username);

            Assert.True(user.ShoppingCart.ShoppingCartProducts.Any());
            Assert.Equal(expectedCount, user.ShoppingCart.ShoppingCartProducts.Count);
        }
        public async Task GetAllShoppingCartProducts_ShouldReturnAllShoppingCartProductsByUsername()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetAllShoppingCartProducts_ShouldReturnAllShoppingCartProductsByUsername")
                          .Options;
            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            const string username  = "******";
            const int    productId = 2;

            var userService = new Mock <IUserService>();

            userService.Setup(r => r.GetUserByUsername(username))
            .Returns(context.Users.FirstOrDefault(x => x.UserName == username));
            var productService = new Mock <IProductService>();

            productService.Setup(p => p.GetProductById(productId))
            .Returns(context.Products.Find(productId).To <ProductServiceModel>());
            IShoppingCartService shoppingCartsService = new ShoppingCartService(context, productService.Object, userService.Object);

            var user           = userService.Object.GetUserByUsername(username);
            int expectedResult = user.ShoppingCart.ShoppingCartProducts.Count;
            int actualResult   = shoppingCartsService.GetAllShoppingCartProducts(username).Count();

            Assert.Equal(expectedResult, actualResult);
        }
        public async Task AnyProducts_ShouldReturnIsAnyProductsInShoppingCart()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "AnyProducts_ShouldReturnIsAnyProductsInShoppingCart")
                          .Options;
            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            const string username  = "******";
            const int    productId = 1;

            var userService = new Mock <IUserService>();

            userService.Setup(r => r.GetUserByUsername(username))
            .Returns(context.Users.FirstOrDefault(x => x.UserName == username));
            var productService = new Mock <IProductService>();

            productService.Setup(p => p.GetProductById(productId))
            .Returns(context.Products.Find(productId).To <ProductServiceModel>());
            IShoppingCartService shoppingCartsService = new ShoppingCartService(context, productService.Object, userService.Object);

            bool result = shoppingCartsService.AnyProducts(username);

            Assert.True(result);
        }
        public async Task AddProductInShoppingCartAsync_WithIncorrectProductShouldThrowException()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddProductInShoppingCartAsync_WithIncorrectProductShouldThrowException")
                          .Options;
            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            const string username        = "******";
            const int    productId       = int.MaxValue;
            const int    defaultQuantity = 1;

            var userService = new Mock <IUserService>();

            userService.Setup(r => r.GetUserByUsername(username))
            .Returns(context.Users.FirstOrDefault(x => x.UserName == username));

            var productService = new Mock <IProductService>();

            IShoppingCartService shoppingCartsService = new ShoppingCartService(context, productService.Object, userService.Object);

            await Assert.ThrowsAsync <ArgumentNullException>(() =>
                                                             shoppingCartsService.AddToShoppingCartAsync(productId, username, defaultQuantity));
        }
        public async void EditAsync_ShouldEditSupplier()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "EditAsync_ShouldEditSupplier")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            await SeedData(context);

            ISupplierService supplierService = new SupplierService(context);

            SupplierServiceModel serviceModel = new SupplierServiceModel
            {
                Id   = 1,
                Name = "edited",
                DeliveryTimeInDays = 5,
                PriceToOffice      = 10,
                PriceToAddress     = 10
            };

            var actualResult = await supplierService.EditAsync(serviceModel);

            Assert.NotNull(actualResult);
            Assert.Equal(serviceModel.Name, actualResult.Name);
            Assert.Equal(serviceModel.DeliveryTimeInDays, actualResult.DeliveryTimeInDays);
            Assert.Equal(serviceModel.PriceToAddress, actualResult.PriceToAddress);
            Assert.Equal(serviceModel.PriceToOffice, actualResult.PriceToOffice);
        }
Ejemplo n.º 21
0
 public ShoppingCartService(TechAndToolsDbContext context,
                            IProductService productService,
                            IUserService userService)
 {
     this.context        = context;
     this.productService = productService;
     this.userService    = userService;
 }
        private static async Task SeedPaymentTypesAsync(string paymentTypeName, TechAndToolsDbContext dbContext)
        {
            var paymentType = new PaymentMethod {
                Name = paymentTypeName
            };

            await dbContext.PaymentMethods.AddAsync(paymentType);
        }
        private static async Task SeedOrderStatusAsync(string orderStatusName, TechAndToolsDbContext dbContext)
        {
            var orderStatus = new OrderStatus {
                Name = orderStatusName
            };

            await dbContext.OrderStatuses.AddAsync(orderStatus);
        }
Ejemplo n.º 24
0
        private static async Task SeedPaymentStatusAsync(string paymentName, TechAndToolsDbContext dbContext)
        {
            var paymentStatus = new PaymentStatus {
                Name = paymentName
            };

            await dbContext.PaymentStatuses.AddAsync(paymentStatus);

            await dbContext.SaveChangesAsync();
        }
Ejemplo n.º 25
0
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            bool hasPaymentStatuses = await dbContext.PaymentStatuses.AnyAsync();

            if (!hasPaymentStatuses)
            {
                await SeedPaymentStatusAsync(GlobalConstants.Unpaid, dbContext);
                await SeedPaymentStatusAsync(GlobalConstants.Paid, dbContext);
            }
        }
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            bool hasPaymentTypes = await dbContext.PaymentMethods.AnyAsync();

            if (!hasPaymentTypes)
            {
                await SeedPaymentTypesAsync(GlobalConstants.CashOnDeliver, dbContext);

                await dbContext.SaveChangesAsync();
            }
        }
 public OrderService(IUserService userService,
                     IShoppingCartService shoppingCartService,
                     ISupplierService supplierService,
                     IProductService productService,
                     TechAndToolsDbContext context)
 {
     this.userService         = userService;
     this.shoppingCartService = shoppingCartService;
     this.supplierService     = supplierService;
     this.productService      = productService;
     this.context             = context;
 }
        public async Task SeedAsync(TechAndToolsDbContext dbContext, IServiceProvider serviceProvider)
        {
            bool hasOrderStatuses = await dbContext.OrderStatuses.AnyAsync();

            if (!hasOrderStatuses)
            {
                await SeedOrderStatusAsync("Необработена", dbContext);
                await SeedOrderStatusAsync("Обработена", dbContext);
                await SeedOrderStatusAsync("Доставена", dbContext);

                await dbContext.SaveChangesAsync();
            }
        }
        public async void GetPaymentMethodByName_ShouldThrowArgumentNullExceptionIfMethodIsNull()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetPaymentMethodByName_ShouldThrowArgumentNullExceptionIfMethodIsNull")
                          .Options;

            var context = new TechAndToolsDbContext(options);

            await SeedData(context);

            IPaymentMethodService paymentMethodService = new PaymentMethodService(context);

            await Assert.ThrowsAsync <ArgumentNullException>(() => paymentMethodService.GetPaymentMethodByName("blabla"));
        }
        public async void GetSupplierById_WithIncorrectIdShouldThrowException()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetSupplierById_WithIncorrectIdShouldThrowException")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            await SeedData(context);

            ISupplierService supplierService = new SupplierService(context);

            int testSupplierId = 111111;

            Assert.Throws <ArgumentNullException>(() => supplierService.GetSupplierById(testSupplierId));
        }