public async Task Index_ReturnsNoCartItems_WhenNoItemsInCart()
        {
            // Arrange
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", "CartId_A");

            var controller = new ShoppingCartController()
            {
                DbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(),
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.NotNull(viewResult.ViewData);
            Assert.Null(viewResult.ViewName);

            var model = Assert.IsType<ShoppingCartViewModel>(viewResult.ViewData.Model);
            Assert.Equal(0, model.CartItems.Count);
            Assert.Equal(0, model.CartTotal);
        }
예제 #2
0
        public async Task AddressAndPayment_RedirectToCompleteWhenSuccessful()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            var orderId = 10;
            var order = new Order()
            {
                OrderId = orderId,
            };

            // Session initialization
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            // FormCollection initialization
            httpContext.Request.Form =
                new FormCollection(
                    new Dictionary<string, string[]>()
                        { { "PromoCode", new string[] { "FREE" } } }
                    );

            // UserName initialization
            var claims = new List<Claim> { new Claim(ClaimTypes.Name, "TestUserName") };
            httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            
            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 1);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new CheckoutController()
            {
                DbContext = dbContext,
            };
            controller.ActionContext.HttpContext = httpContext;
            
            // Act
            var result = await controller.AddressAndPayment(order, CancellationToken.None);

            // Assert
            var redirectResult = Assert.IsType<RedirectToActionResult>(result);
            Assert.Equal("Complete", redirectResult.ActionName);
            Assert.Null(redirectResult.ControllerName);
            Assert.NotNull(redirectResult.RouteValues);

            Assert.Equal(orderId, redirectResult.RouteValues["Id"]);
        }
예제 #3
0
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         sessionKey          = context.Request.Cookies.Get(_options.CookieName);

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                var establisher = new SessionEstablisher(context, sessionKey, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature();

            feature.Factory = new SessionFactory(sessionKey, _options.Store, _options.IdleTimeout, tryEstablishSession, isNewSessionKey);
            feature.Session = feature.Factory.Create();
            context.SetFeature <ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.SetFeature <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        feature.Session.Commit();
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError("Error closing the session.", ex);
                    }
                }
            }
        }
예제 #4
0
        public async Task Invoke(HttpContext context)
        {
            var isNewSessionKey = false;
            Func<bool> tryEstablishSession = ReturnTrue;
            var sessionKey = context.Request.Cookies.Get(_options.CookieName);
            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                var establisher = new SessionEstablisher(context, sessionKey, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey = true;
            }

            var feature = new SessionFeature();
            feature.Factory = new SessionFactory(sessionKey, _options.Store, _options.IdleTimeout, tryEstablishSession, isNewSessionKey);
            feature.Session = feature.Factory.Create();
            context.SetFeature<ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.SetFeature<ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        feature.Session.Commit();
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError("Error closing the session.", ex);
                    }
                }
            }
        }
        public async Task CartSummaryComponent_Returns_CartedItems()
        {
            // Arrange
            var viewContext = new ViewContext()
            {
                HttpContext = new DefaultHttpContext()
            };

            // Session initialization
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };
            viewContext.HttpContext.SetFeature<ISessionFeature>(sessionFeature);
            viewContext.HttpContext.Session.SetString("Session", cartId);

            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            PopulateData(dbContext, cartId, albumTitle: "AlbumA", itemCount: 10);

            // CartSummaryComponent initialization
            var cartSummaryComponent = new CartSummaryComponent(dbContext)
            {
                ViewComponentContext = new ViewComponentContext() { ViewContext = viewContext }
            };

            // Act
            var result = await cartSummaryComponent.InvokeAsync();

            // Assert
            Assert.NotNull(result);
            var viewResult = Assert.IsType<ViewViewComponentResult>(result);
            Assert.Null(viewResult.ViewName);
            Assert.Null(viewResult.ViewData.Model);
            Assert.Equal(10, cartSummaryComponent.ViewBag.CartCount);
            Assert.Equal("AlbumA", cartSummaryComponent.ViewBag.CartSummary);
        }
        public async Task RemoveFromCart_RemovesItemFromCart()
        {
            // Arrange
            var cartId = "CartId_A";
            var cartItemId = 3;
            var numberOfItem = 5;
            var unitPrice = 10;
            var httpContext = new DefaultHttpContext();

            // Session and cart initialization
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(cartId, unitPrice, numberOfItem);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            // ServiceProvder initialization
            var serviceProviderFeature = new ServiceProvidersFeature();
            httpContext.SetFeature<IServiceProvidersFeature>(serviceProviderFeature);

            // AntiForgery initialization
            serviceProviderFeature.RequestServices = _serviceProvider;
            var antiForgery = serviceProviderFeature.RequestServices.GetRequiredService<AntiForgery>();
            var tokens = antiForgery.GetTokens(httpContext, "testToken");

            // Header initialization for AntiForgery
            var headers = new KeyValuePair<string, string[]>(
                "RequestVerificationToken",
                new string[] { tokens.CookieToken + ":" + tokens.FormToken });
            httpContext.Request.Headers.Add(headers);

            // Cotroller initialization
            var controller = new ShoppingCartController()
            {
                DbContext = dbContext,
                AntiForgery = antiForgery,
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.RemoveFromCart(cartItemId, CancellationToken.None);

            // Assert
            var jsonResult = Assert.IsType<JsonResult>(result);
            var viewModel = Assert.IsType<ShoppingCartRemoveViewModel>(jsonResult.Value);
            Assert.Equal(numberOfItem - 1, viewModel.CartCount);
            Assert.Equal((numberOfItem - 1) * 10, viewModel.CartTotal);
            Assert.Equal(" has been removed from your shopping cart.", viewModel.Message);

            var cart = ShoppingCart.GetCart(dbContext, httpContext);
            Assert.False((await cart.GetCartItems()).Any(c => c.CartItemId == cartItemId));
        }
        public async Task AddToCart_AddsItemToCart()
        {
            // Arrange
            var albumId = 3;
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", "CartId_A");

            // Creates the albums of AlbumId = 1 ~ 10.
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var albums = CreateTestAlbums(itemPrice: 10);
            dbContext.AddRange(albums);
            dbContext.SaveChanges();

            var controller = new ShoppingCartController()
            {
                DbContext = dbContext
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.AddToCart(albumId, CancellationToken.None);

            // Assert
            var cart = ShoppingCart.GetCart(dbContext, httpContext);
            Assert.Equal(1, (await cart.GetCartItems()).Count);
            Assert.Equal(albumId, (await cart.GetCartItems()).Single().AlbumId);

            var redirectResult = Assert.IsType<RedirectToActionResult>(result);
            Assert.Null(redirectResult.ControllerName);
            Assert.Equal("Index", redirectResult.ActionName);
        }
        public async Task Index_ReturnsCartItems_WhenItemsInCart()
        {
            // Arrange
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 5);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new ShoppingCartController()
            {
                DbContext = dbContext,
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.NotNull(viewResult.ViewData);
            Assert.Null(viewResult.ViewName);

            var model = Assert.IsType<ShoppingCartViewModel>(viewResult.ViewData.Model);
            Assert.Equal(5, model.CartItems.Count);
            Assert.Equal(5 * 10, model.CartTotal);
        }