public async Task UpdateUser_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "UpdateUser_WhenParamatersAreValidAndUserExistsToggleAdmin")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();

                await actContext.AddAsync(testRole);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await command.ToggleAdmin(testUser.Id);

                var adminUser = await assertContext.Users.Where(user => user.Id == testUser.Id).FirstAsync();

                Assert.AreEqual(GlobalConstants.AdminRole.ToString(), adminUser.Role.ToString());
            }
        }
        public async Task ReturnCorrectData_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnCorrectData_WhenParamatersAreValidAndUserExistsToggleAdmin")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();

                await actContext.AddAsync(testRole);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                var result = await command.ToggleAdmin(testUser.Id);

                Assert.IsInstanceOfType(result, typeof(UserDTO));
                Assert.IsFalse(result.Deleted);
                Assert.AreEqual(testUser.UserName, result.Username);
                Assert.AreEqual(testUser.Id, result.UserId);
                Assert.IsTrue(result.Admin);
            }
        }
        public async Task ReturnCorrectData_WhenNoParametersArePassed()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnCorrectData_WhenNoParametersArePassed")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUserOne);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                var result = await command.GetAllUsers();

                Assert.IsInstanceOfType(result, typeof(IPagedList <UserDTO>));
                Assert.IsTrue(result.Count() == 1);
                Assert.AreEqual(testUserOne.UserName, result.First().Username);
                Assert.IsFalse(result.First().Admin);
                Assert.IsFalse(result.First().Deleted);
            }
        }
        public async Task ThrowException_WhenAParameter_IsNotPassed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_WhenAParameter_IsNotPassed")
                             .Options;

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var amountsDictionary = Enum.GetNames(typeof(TransactionType)).ToDictionary(name => name, value => 0m);

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 0,
                User     = user,
            };

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = null // here there is no passed parameter
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            var getCurrencySymbol = CultureReferences.CurrencySymbols.TryGetValue(userWallet.Currency.ToString(), out string currencySymbol);
            var currencies        = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.GetUserWallet(user));
            }
        }
        public async Task UpdateUser_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "UpdateUser_WhenParamatersAreValidAndUserExistsDeleteUser")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await command.DeleteUser(testUser.Id);

                var deletedUser = await assertContext.Users.Where(user => user.Id == testUser.Id).FirstAsync();

                Assert.IsTrue(deletedUser.IsDeleted);
            }
        }
Пример #6
0
        public async Task ReturnCorrectUpdatedWallet()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnCorrectUpdatedWallet")
                             .Options;

            decimal stake = 1000;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 0,
                User     = user,
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                var updateWallet  = await walletService.UpdateUserWallet(user, stake);

                Assert.AreEqual(stake, updateWallet.Balance);
            }
        }
        public async Task ReturnCorrectData_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnCorrectData_WhenParamatersAreValidAndUserExists")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            var foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 0m)
            };

            foreignExchangeServiceMock.Setup(exchange => exchange.GetConvertionRates())
            .Returns(Task.FromResult(foreignExchangeDTO));

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testWallet);

                await actContext.SaveChangesAsync();

                testUser.Wallet = testWallet;
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                var result = await command.GetUserInfo(testUser.Id);

                Assert.IsInstanceOfType(result, typeof(UserInfoDTO));
                Assert.AreEqual(testUser.UserName, result.Username);
                Assert.AreEqual(testWallet.Balance, result.Balance);
                Assert.AreEqual(walletCurrency.ToString(), result.Currency);
                Assert.AreEqual(testUser.Id, result.UserId);
                Assert.IsFalse(result.Admin);
            }
        }
Пример #8
0
        public async Task ThrowException_When_NullOrInvalidParamsPassed()
        {
            // Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_NullOrInvalidParamsPassed")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User();

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = null
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id));
            }
        }
        public async Task RemoveFromUserRolesTable_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "RemoveFromUserRolesTable_WhenParamatersAreValidAndUserExists")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();

                await actContext.AddAsync(testRole);

                await actContext.SaveChangesAsync();

                var userRole = new IdentityUserRole <string>();
                userRole.UserId = testUser.Id;
                userRole.RoleId = testRole.Id;
                await actContext.AddAsync(userRole);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await command.ToggleAdmin(testUser.Id);

                var updatedUser = await assertContext.Users.Where(user => user.Id == testUser.Id).FirstOrDefaultAsync();

                var assignedRole = await assertContext.Roles.Where(role => role.Id == testRole.Id).FirstOrDefaultAsync();

                var userRole = await assertContext.UserRoles.Where(ur => ur.UserId == updatedUser.Id && ur.RoleId == assignedRole.Id).FirstOrDefaultAsync();

                Assert.IsNull(userRole);
            }
        }
Пример #10
0
        public async Task ReturnTrue_IfCardDoesntExist()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTrue_IfCardDoesntExist")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                ExpiryDate = DateTime.Parse("02.03.2020"),
                User       = user,
                UserId     = user.Id,
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            // Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var cardService = new CardService(assertContext, dateTimeProvider);
                //We pass in a different cardNumber which is not added  thus it does not exist in the context!
                var doesCardExist = cardService.DoesCardExist("23232112412");

                Assert.IsTrue(doesCardExist);
            }
        }
        public async Task ThrowEntityNotFoundException_WhenUserCurrencyIsNotInCurrencyRates()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ThrowEntityNotFoundException_WhenUserCurrencyIsNotInCurrencyRates")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            var foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = new Dictionary <string, decimal>()
            };

            foreignExchangeServiceMock.Setup(exchange => exchange.GetConvertionRates())
            .Returns(Task.FromResult(foreignExchangeDTO));

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testWallet);

                await actContext.SaveChangesAsync();

                testUser.Wallet = testWallet;
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await command.GetUserInfo(testUser.Id));
            }
        }
Пример #12
0
        public async Task ReturnDeletedCard_AsNewCard_AfterReadding()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnDeletedCard_AsNewCard_AfterReadding")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                ExpiryDate = DateTime.Parse("02.03.2020"),
                IsDeleted  = true,
                User       = user
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            // Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var        cardService      = new CardService(assertContext, dateTimeProvider);
                CreditCard creditCardResult = await cardService.AddCard(cardNumber, cvv, DateTime.Parse("02.03.2020"), user);

                Assert.IsInstanceOfType(creditCardResult, typeof(CreditCard));
            }
        }
Пример #13
0
        public async Task ThrowException_When_CardAlreadyExists()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_CardAlreadyExists")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                ExpiryDate = DateTime.Parse("02.03.2020"),
                User       = user,
                UserId     = user.Id
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var cardService = new CardService(actContext, dateTimeProvider);
                await Assert.ThrowsExceptionAsync <EntityAlreadyExistsException>(async() => await cardService.AddCard("23232141412", "3232", DateTime.Parse("02.03.2020"), user));
            }
        }
Пример #14
0
        public async Task ThrowException_When_NullValuesArePassed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_NullValuesArePassed")
                             .Options;

            decimal stake = 1000;

            user = new User();

            userWallet = new Wallet();

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            dateTimeProvider = new DateTimeProvider();

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);

                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.UpdateUserWallet(user, stake));
            }
        }
Пример #15
0
        public async Task UpdateUser_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "UpdateUser_WhenParamatersAreValidAndUserExistsLockoutUser")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            dateTimeProviderMock
            .Setup(date => date.UtcNow)
            .Returns(DateTime.Parse(fakeDate));

            dateTimeProviderMock
            .Setup(date => date.Now)
            .Returns(DateTime.Parse(fakeDate));

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await command.LockoutUser(testUser.Id, lockoutDays);

                var lockedUser = await assertContext.Users.Where(user => user.Id == testUser.Id).FirstAsync();

                Assert.IsNotNull(lockedUser.LockoutEnd);
                Assert.AreEqual(DateTime.Parse(fakeDate).AddDays(1).Date, lockedUser.LockoutEnd.Value.Date);
            }
        }
Пример #16
0
        public async Task ReturnCardToDelete_WhenValidParams_Passed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnCardToDelete_WhenValidParams_Passed")
                             .Options;

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                ExpiryDate = DateTime.Parse("02.03.2018"),
                User       = user,
                UserId     = user.Id,
            };

            dateTimeProvider = new DateTimeProvider();

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var cardService  = new CardService(assertContext, dateTimeProvider);
                var cardToDelete = await cardService.DeleteCard(creditCard.Id);

                Assert.IsInstanceOfType(cardToDelete, typeof(CreditCard));
                Assert.IsTrue(cardToDelete.IsDeleted);
            }
        }
        public static void SeedAdmins(this IApplicationBuilder builder, UserManager <User> userManager, ItsAllAboutTheGameDbContext context)
        {
            Task.Run(async() =>
            {
                //Here we create the Admin account
                if (await userManager.FindByEmailAsync(GlobalConstants.AdminEmail) == null)
                {
                    var wallet = new Wallet()
                    {
                        Balance = 0, Currency = Currency.BGN
                    };
                    context.Wallets.Add(wallet);
                    await context.SaveChangesAsync();

                    User user = new User
                    {
                        UserName    = GlobalConstants.AdminEmail,
                        FirstName   = "Admin",
                        LastName    = "Admin",
                        DateOfBirth = DateTime.Parse("1/1/1991"),
                        Email       = GlobalConstants.AdminEmail,
                        Wallet      = wallet,
                        WalletId    = wallet.Id,
                        Role        = UserRole.Administrator
                    };

                    var result = await userManager.CreateAsync(user, "Admin123_");

                    if (result.Succeeded)
                    {
                        await userManager.AddToRoleAsync(user, GlobalConstants.AdminRole);
                    }
                }

                //Here we create the MasterAdmin account
                if (await userManager.FindByEmailAsync(GlobalConstants.MasterAdminEmail) == null)
                {
                    var wallet = new Wallet()
                    {
                        Balance = 0, Currency = Currency.BGN
                    };
                    context.Wallets.Add(wallet);
                    await context.SaveChangesAsync();

                    User user = new User
                    {
                        UserName    = GlobalConstants.MasterAdminEmail,
                        FirstName   = "MasterAdmin",
                        LastName    = "MasterAdmin",
                        DateOfBirth = DateTime.Parse("1/1/1991"),
                        Email       = GlobalConstants.MasterAdminEmail,
                        Wallet      = wallet,
                        WalletId    = wallet.Id,
                        Role        = UserRole.MasterAdministrator
                    };


                    var result = await userManager.CreateAsync(user, "Admin123_");

                    if (result.Succeeded)
                    {
                        await userManager.AddToRoleAsync(user, GlobalConstants.MasterAdminRole);
                    }
                }
            }).Wait();
        }
Пример #18
0
        public async Task ReturnTransactionDTO_WhenPassedValidParams()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_WhenPassedValidParams")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService  = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                var transactionDTO = await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id);

                Assert.IsInstanceOfType(transactionDTO, typeof(TransactionDTO));
                Assert.IsTrue(transactionDTO.Username == user.UserName);
            }
        }
        public async Task ReturnPageList_OfTransactionDTO_WithDefaultParams()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnPageList_OfTransactionDTO_WithDefaultParams")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userTwo = new User
            {
                Id           = userIdTwo,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userNameTwo,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = emailTwo,
                FirstName    = firstNameTwo,
                LastName     = lastNameTwo,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var transaction = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3232".PadLeft(16, '*'),
                User        = user,
                Amount      = 1000,
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = Currency.BGN
            };

            var transactionTwo = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3102".PadLeft(16, '*'),
                User        = userTwo,
                Amount      = 1500,
                CreatedOn   = dateTimeProviderMock.Object.Now.AddDays(1), // adding 1 day otherwise it will be created at the exact same time as the first transaction
                Currency    = Currency.USD
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Users.AddAsync(userTwo);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.Transactions.AddAsync(transactionTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var pageList = await sut.GetAllTransactions();

                Assert.IsInstanceOfType(pageList, typeof(IPagedList <TransactionDTO>));
                Assert.IsTrue(pageList.Count == 2);
                Assert.IsTrue(pageList.Select(c => c.Username).First() == userTwo.UserName);
            }
        }
        public async Task ReturnTransactionListDTO_With_ConcreteUserParams()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionListDTO_With_ConcreteUserParam")
                             .Options;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();
            walletServiceMock    = new Mock <IWalletService>();
            userServiceMock      = new Mock <IUserService>();
            cardServiceMock      = new Mock <ICardService>();

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var userTwo = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = "******",
                CreatedOn    = dateTimeProviderMock.Object.Now.AddDays(1),
                Email        = "email",
                FirstName    = "firstName",
                LastName     = "lastName",
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var transaction = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3232".PadLeft(16, '*'),
                User        = user,
                Amount      = 1000,
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = Currency.BGN
            };

            var transactionTwo = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3102".PadLeft(16, '*'),
                User        = userTwo,
                Amount      = 1500,
                CreatedOn   = dateTimeProviderMock.Object.Now.AddDays(1), // adding 1 day otherwise it will be created at the exact same time as the first transaction
                Currency    = Currency.USD
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Users.AddAsync(userTwo);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.Transactions.AddAsync(transactionTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var listDTO = await sut.GetUserTransactions(user.UserName); // we get only the DTO of one of the users

                Assert.IsInstanceOfType(listDTO, typeof(TransactionListDTO));
                Assert.IsTrue(listDTO.TotalItemCount == 1);
            }
        }
        public async Task ReturnEmptyTransactionListDTO_With_UserWalletCurrency_WhenUserHasNoTransactions()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnEmptyTransactionListDTO_With_UserWalletCurrency_WhenUserHasNoTransactions")
                             .Options;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();
            walletServiceMock    = new Mock <IWalletService>();
            userServiceMock      = new Mock <IUserService>();
            cardServiceMock      = new Mock <ICardService>();

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var userTwo = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = "******",
                CreatedOn    = dateTimeProviderMock.Object.Now.AddDays(1),
                Email        = "email",
                FirstName    = "firstName",
                LastName     = "lastName",
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.GBP,
                User     = user
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Users.AddAsync(userTwo);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var listDTO = await sut.GetUserTransactions(user.UserName); // we get only the DTO of one of the users

                Assert.IsInstanceOfType(listDTO, typeof(TransactionListDTO));
                Assert.IsTrue(listDTO.TotalItemCount == 0);
            }
        }
Пример #22
0
        public async Task ReturnTransactionDTO_OfTypeStakeAndWin_WhenPassedValidParams(string userName, string amount, string game, string description, string type)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_OfTypeStakeAndWin_WhenPassedValidParams")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            var user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = "*****@*****.**",
                FirstName    = "Edward",
                LastName     = "Evlogiev",
                DateOfBirth  = DateTime.Parse("12.03.1993"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.EUR,
                User     = user
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                assertContext.Attach(wallet);
                var gameResult = await sut.GameTransaction(user, int.Parse(amount),
                                                           game, description, (TransactionType)Enum.Parse(typeof(TransactionType), type));

                Assert.IsInstanceOfType(gameResult, typeof(TransactionDTO));
                Assert.IsTrue(gameResult.Description == description + game);
                Assert.IsTrue(gameResult.Type == (TransactionType)Enum.Parse(typeof(TransactionType), type));
                Assert.IsTrue(gameResult.Amount == int.Parse(amount) / 2);
                Assert.IsTrue(gameResult.Username == userName);
            }
        }
Пример #23
0
        public async Task MakeTransactions_ThatAreAdded_ToTheBase(string userName, string amount, string game, string description, string type)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "MakeTransactions_ThatAreAdded_ToTheBase")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            var user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = "*****@*****.**",
                FirstName    = "Edward",
                LastName     = "Evlogiev",
                DateOfBirth  = DateTime.Parse("12.03.1993"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.EUR,
                User     = user
            };

            var transaction = new Transaction()
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), type),
                Description = description + game,
                User        = user,
                Amount      = int.Parse(amount) / foreignExchangeDTO.Rates[Currency.EUR.ToString()],
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = wallet.Currency
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                assertContext.Attach(wallet);
                var gameResult = await sut.GameTransaction(user, int.Parse(amount),
                                                           game, description, (TransactionType)Enum.Parse(typeof(TransactionType), type));

                Assert.AreEqual(transaction, await assertContext.Transactions.Where(t => t.User == user).FirstOrDefaultAsync());
            }
        }
Пример #24
0
        public async Task ReturnListOfCards_AfterSelectingUserExistingCards()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnListOfCards_AfterSelectingUserExistingCards")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumberOne,
                CVV        = cvvOne,
                ExpiryDate = DateTime.Parse("02.03.2020"),
                User       = user,
                UserId     = user.Id,
            };

            creditCardTwo = new CreditCard
            {
                CardNumber = cardNumberTwo,
                CVV        = cvvTwo,
                ExpiryDate = DateTime.Parse("02.03.2016"),
                User       = user,
                UserId     = user.Id,
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.CreditCards.AddAsync(creditCardTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var cardService = new CardService(assertContext, dateTimeProvider);
                var userCards   = await cardService.GetSelectListCards(user);

                Assert.IsInstanceOfType(userCards, typeof(IEnumerable <SelectListItem>));
            }
        }
        public async Task ReturnTransactionDTO_When_PassedValidParams()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_When_PassedValidParams")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            dateTimeProvider = new Mock <IDateTimeProvider>();

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();
            decimal amount = 1000;

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProvider.Object.Now
            };

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            foreignExchangeServiceMock
            .Setup(foreign => foreign.GetConvertionRates())
            .ReturnsAsync(foreignExchangeDTO);

            userWalletDTO = new WalletDTO(userWallet, foreignExchangeDTO);

            walletServiceMock = new Mock <IWalletService>();
            walletServiceMock
            .Setup(wsm => wsm.GetUserWallet(It.IsAny <User>()))
            .ReturnsAsync(userWalletDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.SaveChangesAsync();

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object,
                                                 userServiceMock.Object, foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProvider.Object);
                assertContext.Attach(user);//We tell the context to monitor the selected object
                var transactionDTO = await sut.MakeDeposit(user, creditCard.Id, amount);

                Assert.IsInstanceOfType(transactionDTO, typeof(TransactionDTO));
            }
        }
Пример #26
0
        public async Task ReturnCorrectConvertedBalance_When_PassedValidValue()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnCorrectConvertedBalance_When_PassedValidValue")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                var convertedBalance = await sut.ConvertBalance(user);

                var currentWalletBalance = await assertContext.Wallets.Where(w => w.User == user).FirstOrDefaultAsync();

                var expectedAmount = currentWalletBalance.Balance * foreignExchangeDTO.Rates[userWallet.Currency.ToString()];
                Assert.AreEqual(expectedAmount, convertedBalance);
            }
        }
Пример #27
0
        public async Task ThrowException_When_CardIsDeleted()
        {
            // Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_CardIsDeleted")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now,
                IsDeleted  = true
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
                        // All of the rates are with value 2 for testing purposes (value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id));
            }
        }
        public async Task ReturnDictionary_WithConcreteUserParams(string transactionType, string userName, string firstName, string lastName)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnDictionary_WithConcreteUserParams")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var transaction = new Transaction
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), transactionType),
                Description = GlobalConstants.DepositDescription + "3232".PadLeft(16, '*'),
                User        = user,
                Amount      = 1000,
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = Currency.BGN
            };

            var transactionTwo = new Transaction
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), transactionType),
                Description = GlobalConstants.DepositDescription + "3102".PadLeft(16, '*'),
                User        = user,
                Amount      = 1495.5332m,
                CreatedOn   = dateTimeProviderMock.Object.Now.AddDays(1), // adding 1 day otherwise it will be created at the exact same time as the first transaction
                Currency    = Currency.BGN
            };

            int digitsAfterFloatingPoint;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.Transactions.AddAsync(transactionTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var dictionaryResult = await sut.GetAllAmounts();

                digitsAfterFloatingPoint = dictionaryResult[transactionType]
                                           .ToString()
                                           .Substring(dictionaryResult[transactionType]
                                                      .ToString()
                                                      .IndexOf(".") + 1)
                                           .Length;

                Assert.IsInstanceOfType(dictionaryResult, typeof(Dictionary <string, decimal>));
                Assert.IsTrue(digitsAfterFloatingPoint == 2);
            }
        }