Beispiel #1
0
        public async Task <Game> HandleAsync(int userId)
        {
            Game historyGame = FindHistoryGame(userId);

            // Create if not exist
            if (!(historyGame is null))
            {
                return(historyGame);
            }

            historyGame = new Game {
                CreatorId = userId
            };
            context.Games.Add(historyGame);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var tag = new GameTag
            {
                Tags   = GameTags.CustomLevelsHistory,
                UserId = userId,
                GameId = historyGame.GameId
            };

            context.GameTags.Add(tag);
            await context.SaveChangesAsync().ConfigureAwait(false);

            return(historyGame);
        }
Beispiel #2
0
        public async void GetUserWords()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            context.Add(CreateUserWordPair(userId, "0", "0-0"));
            context.Add(CreateUserWordPair(userId, "1", "1-1"));
            context.Add(CreateUserWordPair(userId, "3", "3-3"));
            context.Add(CreateUserWordPair(otherId, "2", "2-2"));
            await context.SaveChangesAsync();

            // act
            var service     = new GetUserWords(context);
            var requestData = new GetWordsRequest();
            var request     = new AuthReq <GetWordsRequest, WordsReply>(requestData)
            {
                UserId = userId
            };
            var reply = await service.HandleRequest(request, default);

            // assert
            Assert.Equal(context.UserWordPairs.Where(d => d.UserId == userId).Count(), reply.ToAdd.Count());
            Assert.Empty(reply.ToDelete);
        }
Beispiel #3
0
        public async void RequestContainsExistedWords()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            context.Add(CreateUserWordPair(userId, "0", "0-0", 1));
            context.Add(CreateUserWordPair(userId, "1", "1-1", 2));
            context.Add(CreateUserWordPair(otherId, "2", "2-2", 3));
            context.Add(CreateUserWordPair(userId, "3", "3-3", 4));
            await context.SaveChangesAsync();

            // act
            var service     = new GetUserWords(context);
            var requestData = new GetWordsRequest();

            requestData.UserWordpairIds.Add(new int[] { 1, 2, 99, 100 });
            var request = new AuthReq <GetWordsRequest, WordsReply>(requestData)
            {
                UserId = userId
            };
            var reply = await service.HandleRequest(request, default);

            // assert
            Assert.Equal(4, reply.ToAdd[0].UserWordPair);
            Assert.Equal(new int[] { 99, 100 }, reply.ToDelete.ToArray());
        }
        public static async Task <int> AddOrGetUserHistoryGame(this InWordsDataContext context, int userId)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var historyGame = (from game in context.Games.Where(d => d.CreatorId == userId)
                               join tag in context.GameTags.Where(d => d.Tags == GameTags.CustomLevelsHistory)
                               on game.GameId equals tag.GameId
                               select game).OrderBy(g => g.GameId).ToArray();

            int historyGameId = 0;

            if (historyGame.Any())
            {
                historyGameId = historyGame[0].GameId;

                if (historyGame.Length > 1)
                {
                    var historyCollisions = historyGame.Skip(1);

                    int[] ids    = historyCollisions.Select(d => d.GameId).ToArray();
                    var   levels = context.GameLevels.Where(g => ids.Contains(g.GameId));

                    levels.ForEach(level =>
                    {
                        level.GameId = historyGameId;
                    });
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    context.Remove(historyCollisions);
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            else
            {
                Game game = new Game
                {
                    CreatorId = userId
                };
                context.Add(game);
                await context.SaveChangesAsync().ConfigureAwait(false);

                GameTag historyGameTag = new GameTag()
                {
                    GameId = game.GameId,
                    Tags   = GameTags.CustomLevelsHistory,
                    UserId = userId
                };

                context.Add(historyGameTag);
                await context.SaveChangesAsync().ConfigureAwait(false);

                historyGameId = game.GameId;
            }
            return(historyGameId);
        }
Beispiel #5
0
        public async void DeleteUserWordPairs_ShouldBeOk()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            context.Add(new UserWordPair()
            {
                UserWordPairId = 1,
                ForeignWord    = "Test1",
                NativeWord     = "Тест1",
                UserId         = userId
            });;
            context.Add(new UserWordPair()
            {
                UserWordPairId = 2,
                ForeignWord    = "Test2",
                NativeWord     = "Тест2",
                UserId         = userId
            });
            context.Add(new UserWordPair()
            {
                UserWordPairId = 3,
                ForeignWord    = "Test3",
                NativeWord     = "Тест3",
                UserId         = userId
            });

            await context.SaveChangesAsync();

            DeleteWordsRequest deletewordsRequets = new DeleteWordsRequest();

            deletewordsRequets.Delete.AddRange(new int[] { 1, 3 });

            // act
            var requestObject = new AuthReq <DeleteWordsRequest, Empty>(deletewordsRequets)
            {
                UserId = userId
            };

            var   deleteWords = new DeleteWords(context);
            Empty response    = await deleteWords.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(1, context.UserWordPairs.Count());
            Assert.Equal("Тест2", context.UserWordPairs.First().NativeWord);
        }
Beispiel #6
0
        public async void GetLevelWords()
        {
            // arrange
            int userId = 1;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            Game game = new Game()
            {
            };

            context.Add(game);
            await context.SaveChangesAsync();

            GameLevel gameLevel = new GameLevel()
            {
                GameId = game.GameId
            };

            context.Add(gameLevel);
            await context.SaveChangesAsync();

            List <GameLevelWord> gameLevelWords = new List <GameLevelWord>
            {
                new GameLevelWord()
                {
                    GameLevelId = gameLevel.GameLevelId, ForeignWord = "test1", NativeWord = "тест1"
                },
                new GameLevelWord()
                {
                    GameLevelId = gameLevel.GameLevelId, ForeignWord = "test2", NativeWord = "тест2"
                },
            };

            context.GameLevelWords.AddRange(gameLevelWords);
            await context.SaveChangesAsync();

            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            // act
            var data = new GetLevelWordsRequest()
            {
                LevelId = gameLevel.GameLevelId
            };
            var request = new AuthReq <GetLevelWordsRequest, GetLevelWordsReply>(data)
            {
                UserId = userId
            };
            GetLevelWordsReply result = await new GetLevelWords(context).HandleRequest(request);

            // assert
            Assert.Equal(2, result.Words.Count);
        }
        public static async Task <int[]> CreateLevels(this InWordsDataContext context, int gameId, int userId, IList <int[]> pairsInLevels)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (pairsInLevels == null)
            {
                pairsInLevels = Array.Empty <int[]>();
            }

            // create levles
            var levels = pairsInLevels.Select(d =>
            {
                var game = new GameLevel()
                {
                    GameId = gameId
                };
                game.Historylevel = new Historylevel()
                {
                    DateTime   = DateTime.UtcNow,
                    WordsCount = d.Distinct().Count(),
                    GameLevel  = game
                };
                context.Add(game);
                return(game);
            }).ToArray();

            await context.SaveChangesAsync().ConfigureAwait(false);

            // fill levels with words
            for (int i = 0; i < pairsInLevels.Count; i++)
            {
                var   currentLevel    = levels[i];
                int[] currentWordsIds = pairsInLevels[i].ToArray();

                var currentWords = context.CurrentUserWordPairs(userId)
                                   .Where(u => currentWordsIds.Contains(u.UserWordPairId))
                                   .ToArray();

                var gameLevelWords = currentWords.Select(w => new GameLevelWord()
                {
                    ForeignWord = w.ForeignWord,
                    NativeWord  = w.NativeWord,
                    GameLevelId = currentLevel.GameLevelId,
                }).ToArray();

                context.GameLevelWords.AddRange(gameLevelWords);
            }
            await context.SaveChangesAsync().ConfigureAwait(false);

            return(levels.Select(level => level.GameLevelId).ToArray());
        }
Beispiel #8
0
        public async void Find_Existed_Account()
        {
            // arrange
            int userId = 1;

            int other = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            // act
            var requestData = new FindIdRequest()
            {
                UserId = userId
            };
            var request = new AuthReq <FindIdRequest, PublicProfileReply>(requestData)
            {
                UserId = other,
            };
            var handler = new FindProfileId(context);
            var result  = await handler.Handle(request);

            // assert
            Assert.Equal(userId, result.UserId);
        }
        public async void WrongLinkTest()
        {
            // arrange
            string rightGuid = Guid.NewGuid().ToString();

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            context.EmailVerifies.Add(new EmailVerifies()
            {
                Guid = rightGuid,
            });
            await context.SaveChangesAsync();

            // act
            var requestObject =
                new RequestObject <ConfirmEmailLinkRequest, ConfirmEmailReply>(
                    new ConfirmEmailLinkRequest()
            {
                ActivationGuid = "wronglink"
            });

            var registration = new ConfirmEmailLink(context);
            await registration.HandleRequest(requestObject);

            Assert.Equal(StatusCode.InvalidArgument, requestObject.StatusCode);
        }
Beispiel #10
0
        public async void CreateScore()
        {
            using InWordsDataContext context = InWordsDataContextFactory.Create();
            {
                CreateGameContext(context);

                ClassicCardLevelMetricQuery request = new ClassicCardLevelMetricQuery()
                {
                    UserId  = 1,
                    Metrics = new List <ClassicCardLevelMetric>()
                    {
                        new ClassicCardLevelMetric()
                        {
                            GameLevelId          = 1,
                            WordPairIdOpenCounts = new Dictionary <int, int>()
                            {
                                { 1, 4 },
                                { 3, 4 },
                                { 4, 1 }
                            }
                        }
                    }.ToImmutableArray()
                };

                await context.SaveChangesAsync().ConfigureAwait(false);

                ClassicCardLevelMetricQueryResult result = await new SaveLevelMetric(context)
                                                           .Handle(request)
                                                           .ConfigureAwait(false);
            }

            var userGameLevel = context.UserGameLevels.First(u => u.UserId.Equals(1));

            Assert.Equal(3, userGameLevel.UserStars);
        }
Beispiel #11
0
        private static async Task CreateTestContext(InWordsDataContext context)
        {
            await context.AddAccount(1);

            context.Languages.AddLanguages();


            HashSet <GameLevelWord> gameLevelWords = new HashSet <GameLevelWord>
            {
                new GameLevelWord()
                {
                    NativeWord = "тест4", ForeignWord = "test4"
                },
                new GameLevelWord()
                {
                    NativeWord = "тест5", ForeignWord = "test5"
                }
            };

            HashSet <GameLevel> gameLevels = new HashSet <GameLevel>
            {
                new GameLevel()
                {
                    GameLevelWords = gameLevelWords,
                }
            };
            Game game = new Game()
            {
                CreatorId  = 0,
                GameLevels = gameLevels
            };

            context.Games.Add(game);
            await context.SaveChangesAsync();
        }
Beispiel #12
0
        public async void Find_Existed_Account()
        {
            // arrange
            int    userId   = 1;
            string nickname = "nick";

            int other = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            context.Users.First().NickName = nickname;
            context.SaveChanges();


            // act
            var requestData = new FindUsernameRequest()
            {
                UserName = nickname
            };
            var request = new AuthReq <FindUsernameRequest, PublicProfilesReply>(requestData)
            {
                UserId = other,
            };
            var handler = new FindProfileNickname(context);
            var result  = await handler.Handle(request);

            // assert
            Assert.Equal(userId, result.Users.First().UserId);
        }
Beispiel #13
0
        public async void GetLevelsInSet()
        {
            // arrange
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            var game1 = new Game();

            context.Add(game1);

            List <GameLevel> gameLevels = new List <GameLevel>
            {
                new GameLevel()
                {
                    GameId = game1.GameId,
                },
                new GameLevel()
                {
                    GameId = game1.GameId,
                }
            };

            context.AddRange(gameLevels);
            await context.SaveChangesAsync();

            // act
            var data = new GetLevelsRequest()
            {
                WordSetId = game1.GameId
            };
            var request = new AuthReq <GetLevelsRequest, GetLevelsReply>(data);
            var handler = new GetWordSetLevels(context);
            var result  = await handler.Handle(request);

            // assert
            Assert.Equal(2, result.Levels.Count);
        }
Beispiel #14
0
        public async void DeleteExistedAccount()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            // act
            var requestObject =
                new AuthorizedRequestObject <DeleteAccountRequest, Empty>(
                    new DeleteAccountRequest()
            {
                Text = "Delete me just for test"
            })
            {
                UserId = userId
            };

            var registration = new DeleteAccount(context);
            await registration.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Single(context.Accounts);
            Assert.Equal(otherId, context.Accounts.First().AccountId);
        }
Beispiel #15
0
        public async void ConfirmValidCode()
        {
            // arrange
            int    userId    = 1;
            Guid   rightGuid = Guid.NewGuid();
            string newEmail  = "*****@*****.**";

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            context.EmailVerifies.Add(new EmailVerifies()
            {
                UserId = userId,
                Guid   = rightGuid,
                Email  = newEmail
            });
            await context.SaveChangesAsync();

            // act
            var requestObject =
                new RequestObject <ConfirmEmailLinkRequest, ConfirmEmailReply>(
                    new ConfirmEmailLinkRequest()
            {
                ActivationGuid = rightGuid.ToString()
            });

            var registration = new ConfirmEmailLink(context);
            var test         = await registration.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(0, context.EmailVerifies.Count());
            Assert.Equal(newEmail, test.Email);
            Assert.Equal(newEmail, context.Accounts.First().Email);
        }
Beispiel #16
0
        public async void GetOfficialSets_ShouldBeOk()
        {
            // arrange
            string picture     = "testPicture";
            string description = "testdes";
            string title       = "testtitle";

            Language language = new Language()
            {
                LanguageId = 2, Title = "ru"
            };

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            Game game = new Game()
            {
                Picture = picture
            };

            context.Add(language);
            context.Add(game);
            await context.SaveChangesAsync();

            CreationDescription creationDescription = new CreationDescription()
            {
                CreationId  = game.GameId,
                Description = description,
                LanguageId  = 2,
                Title       = title,
            };

            context.Add(creationDescription);
            GameTag gameTag = new GameTag()
            {
                GameId = game.GameId,
                Tags   = GameTags.Official
            };

            context.Add(gameTag);
            context.SaveChanges();

            // act
            Empty empty   = new Empty();
            var   request = new AuthReq <Empty, WordSetReply>(empty)
            {
                UserId = 0
            };
            var reply = await new GetWordSetsHandler(context).Handle(request);

            // assert
            Assert.Single(reply.WordSets);
            Assert.Equal(description, reply.WordSets[0].Description);
            Assert.Equal(title, reply.WordSets[0].Title);
            Assert.Equal(picture, reply.WordSets[0].Picture);
        }
        public async void EstimateTraining_Returns6Stars()
        {
            // arrange
            int userId = 1;

            using InWordsDataContext context = InWordsDataContextFactory.Create();
            Game game = new Game()
            {
            };

            context.Add(game);
            context.SaveChanges();
            GameLevel gameLevel = new GameLevel()
            {
                GameId = game.GameId
            };

            context.Add(gameLevel);
            context.SaveChanges();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            // act
            TrainingDataRequest trainingDataRequest = new TrainingDataRequest();
            Training            training            = new Training {
            };

            training.ClosedCardsMetric = new ClosedCardsMetric();
            training.ClosedCardsMetric.WordIdOpenCount.Add(1, 4);
            training.ClosedCardsMetric.WordIdOpenCount.Add(2, 4);
            training.ClosedCardsMetric.WordIdOpenCount.Add(3, 2);
            training.OpenedCardsMetric = new OpenedCardsMetric();
            training.OpenedCardsMetric.WordIdOpenCount.Add(1, 3);
            training.OpenedCardsMetric.WordIdOpenCount.Add(2, 2);
            training.OpenedCardsMetric.WordIdOpenCount.Add(3, 2);
            trainingDataRequest.Metrics.Add(training);

            var requestData = new AuthReq <TrainingDataRequest, TrainingScoreReply>(trainingDataRequest)
            {
                UserId = userId
            };
            var requestHandler = new EstimateTraining(context);
            var result         = await requestHandler.HandleRequest(requestData);

            // assert
            Assert.Single(result.Scores);
            Assert.Equal(6, result.Scores.Single().ClosedCards.Score);
            Assert.Equal(5, result.Scores.Single().OpenedCards.Score);
            Assert.Equal(6, result.Scores.Single().Score);
        }
        private static async Task CreateTestContext(InWordsDataContext context)
        {
            await context.AddAccount(1);

            context.Languages.AddLanguages();

            HashSet <GameLevelWord> gameLevelWords1 = new HashSet <GameLevelWord>
            {
                new GameLevelWord()
                {
                    NativeWord = "тест4", ForeignWord = "test4"
                },
                new GameLevelWord()
                {
                    NativeWord = "тест5", ForeignWord = "test5"
                }
            };

            CreateGame(gameLevelWords1, context);
            await context.SaveChangesAsync();

            HashSet <GameLevelWord> gameLevelWords2 = new HashSet <GameLevelWord>
            {
                new GameLevelWord()
                {
                    NativeWord = "тест6", ForeignWord = "test6"
                },
                new GameLevelWord()
                {
                    NativeWord = "тест7", ForeignWord = "test7"
                }
            };

            CreateGame(gameLevelWords2, context);

            await context.SaveChangesAsync();
        }
Beispiel #19
0
 private async void AddFakeUser(InWordsDataContext context)
 {
     context.Accounts.Add(new Account()
     {
         AccountId = 1,
         Email     = email,
         Hash      = new byte[255],
         Role      = role
     });
     context.Users.Add(new User()
     {
         UserId   = 1,
         NickName = nickname
     });
     await context.SaveChangesAsync();
 }
Beispiel #20
0
        public async void HistoryLevelHistoryGameExistWordsExists()
        {
            const int userId = 1;

            // initialise
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            CreateContextWithExistedGame(context, userId);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var testQuery = new CustomLevelMetricQuery()
            {
                UserId  = userId,
                Metrics = new List <ClassicCardLevelMetric>()
                {
                    new ClassicCardLevelMetric()
                    {
                        GameLevelId          = 0,
                        WordPairIdOpenCounts = new Dictionary <int, int>()
                        {
                            { 1, 4 },
                            { 2, 5 },
                            { 3, 1 }
                        }
                    }
                }.ToImmutableArray()
            };


            // act
            var handler = new CreateHistoryLevelsRequest(context);
            CustomLevelMetricQuery actualResult = await handler.Handle(testQuery).ConfigureAwait(false);

            // assert
            var expectedLevels            = 1;
            List <GameLevel> actualLevels = context.GameLevels.Where(g => g.GameId.Equals(1)).ToList();

            Assert.Equal(expectedLevels, actualLevels.Count);
            var expectedLevelWords = 3;
            var actualLevelWords   = context.GameLevelWords
                                     .Where(d => actualLevels.Contains(d.GameLevel));

            Assert.Equal(expectedLevelWords, actualLevelWords.Count());

            Assert.Equal(4, actualResult.Metrics[0].WordPairIdOpenCounts[2]);

            context.Dispose();
        }
Beispiel #21
0
        public async void TrainingIds_Ok()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            var time = DateTime.UtcNow;

            context.UserWordPairs.Add(new UserWordPair()
            {
                UserWordPairId = 1, UserId = userId, NativeWord = "1", ForeignWord = "1", Background = false, TimeGap = time
            });
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserWordPairId = 2, UserId = userId, NativeWord = "2", ForeignWord = "2", Background = false, TimeGap = time.AddDays(1)
            });
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserWordPairId = 3, UserId = userId, NativeWord = "2", ForeignWord = "2", Background = false, TimeGap = time.AddDays(2)
            });
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserWordPairId = 4, UserId = otherId, NativeWord = "3", ForeignWord = "3", Background = false, TimeGap = time
            });
            context.SaveChanges();
            // act
            var requestObject = new AuthReq <Empty, TrainingIdsReply>(new Empty())
            {
                UserId = userId
            };

            var addWords = new GetTrainingIds(context);
            TrainingIdsReply response = await addWords.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(2, response.UserWordPairs.Count);
            Assert.Contains(1, response.UserWordPairs);
            Assert.Contains(2, response.UserWordPairs);
        }
Beispiel #22
0
        public async void ResendEmailIfUnverfed()
        {
            string testEmail = "*****@*****.**";

            // arrange
            await using InWordsDataContext context = InWordsDataContextFactory.Create();

            Account account = new Account()
            {
                Email = testEmail, Hash = new byte[255], Role = RoleType.Unverified
            };
            User User = new User()
            {
                Account = account, NickName = "user"
            };

            await context.SaveChangesAsync();

            var mock = new Mock <IEmailTemplateSender>();

            mock.Setup(a => a.SendMailAsync(testEmail, It.IsAny <EmailTemplateBase>()));
            // act
            var registration = new ChangeEmail(context, mock.Object);

            var requestObject = new AuthorizedRequestObject <EmailChangeRequest, EmailChangeReply>(
                new EmailChangeRequest()
            {
                Email = testEmail,
            })
            {
                UserId = account.AccountId
            };

            var test = await registration.HandleRequest(
                new AuthorizedRequestObject <EmailChangeRequest, EmailChangeReply>(
                    new EmailChangeRequest()
            {
                Email = testEmail,
            }))
                       .ConfigureAwait(false);

            // assert
            Assert.Equal(1, context.EmailVerifies.Count());
            mock.Verify(a => a.SendMailAsync(testEmail, It.IsAny <EmailTemplateBase>()), Times.Once());
        }
Beispiel #23
0
        public async Task <GameToUserQueryResult> Handle(GameToUserQuery request,
                                                         CancellationToken cancellationToken = default)
        {
            // find user word pairs
            IQueryable <UserWordPair> userWordPairs = FindUserWordPairs(request);

            // add to user words
            await context.UserWordPairs.AddRangeAsync(userWordPairs, cancellationToken).ConfigureAwait(false);

            // cache changes count
            int count = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            // return count
            return(new GameToUserQueryResult
            {
                WordsAdded = count
            });
        }
Beispiel #24
0
        public async void RegisterExistedEmail()
        {
            string email = "*****@*****.**";

            // arrange
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            Account account = new Account()
            {
                Email = email,
                Hash  = new byte[256],
                Role  = InWords.Data.Enums.RoleType.Unverified
            };
            User user = new User()
            {
                Account = account, NickName = "nick"
            };

            context.Accounts.Add(account);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var mock = new Mock <IEmailVerifierService>();

            mock.Setup(a => a.InstatiateVerifierMessage(It.IsAny <User>(), It.IsAny <string>()));
            var jwtMock = new Mock <IJwtProvider>();

            jwtMock.Setup(a => a.GenerateToken(It.IsAny <ClaimsIdentity>())).Returns("token");
            // act
            var registration = new UserRegistration(context, jwtMock.Object, mock.Object);
            // assert
            var request = new RequestObject <RegistrationRequest, RegistrationReply>(
                new RegistrationRequest()
            {
                Email    = email,
                Password = "******"
            });
            var reply = registration.HandleRequest(request);


            Assert.Equal(StatusCode.AlreadyExists, request.StatusCode);
            Assert.Equal(1, context.Accounts.Count());
            mock.Verify(a => a.InstatiateVerifierMessage(It.IsAny <User>(), It.IsAny <string>()), Times.Never());
        }
        public async Task WhereAnyTestUserWordPairTest()
        {
            // prepare
            var userWordPairsList = new List <int>()
            {
                2, 3, 4
            };
            var expectedWordPairsList = new List <int>()
            {
                3, 4, 4
            };

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserId = 1, UserWordPairId = 1, WordPairId = 2
            });                                                                                               // Bad
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserId = 1, UserWordPairId = 2, WordPairId = 3
            });                                                                                               // Good
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserId = 1, UserWordPairId = 3, WordPairId = 4
            });                                                                                               // Good
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserId = 2, UserWordPairId = 4, WordPairId = 4
            });                                                                                               // Good
            context.UserWordPairs.Add(new UserWordPair()
            {
                UserId = 2, UserWordPairId = 5, WordPairId = 3
            });                                                                                               // Bad
            await context.SaveChangesAsync().ConfigureAwait(false);

            // act

            var actualList = context.UserWordPairs.WhereAny(userWordPairsList).Select(d => d.WordPairId).ToList();

            // assert
            Assert.Equal(expectedWordPairsList, actualList);
        }
Beispiel #26
0
        public async void GuidLinkNotFound()
        {
            // arrange
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            context.EmailVerifies.Add(new EmailVerifies()
            {
                Guid = Guid.NewGuid(),
            });
            await context.SaveChangesAsync();

            // act
            var requestObject =
                new RequestObject <ConfirmEmailLinkRequest, ConfirmEmailReply>(
                    new ConfirmEmailLinkRequest()
            {
                ActivationGuid = $"{Guid.NewGuid()}"
            });

            var registration = new ConfirmEmailLink(context);
            await Assert.ThrowsAsync <ArgumentNullException>(() => registration.HandleRequest(requestObject));
        }
        public async void Find_Existed_Account()
        {
            // arrange
            int userId = 1;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            var request = new AuthReq <Empty, ProfileReply>(new Empty())
            {
                UserId = userId,
            };

            var handler = new GetCurrentProfile(context);
            var result  = await handler.Handle(request);

            // assert
            Assert.Equal(userId, result.UserId);
        }
Beispiel #28
0
        public async void AddUserWordPair()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            AddWordsRequest addWordsRequest = new AddWordsRequest();

            addWordsRequest.Words.Add(new AddWordRequest()
            {
                LocalId = 0, WordForeign = "0", WordNative = "0-0"
            });
            addWordsRequest.Words.Add(new AddWordRequest()
            {
                LocalId = 2, WordForeign = "2", WordNative = "2-2"
            });

            // act
            var requestObject = new AuthorizedRequestObject <AddWordsRequest, AddWordsReply>(addWordsRequest)
            {
                UserId = userId
            };

            var           registration = new AddWords(context);
            AddWordsReply response     = await registration.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(4, context.Words.Count());
            Assert.Equal(2, context.WordPairs.Count());
            Assert.Equal(2, context.UserWordPairs.Count());

            CheckPairs(addWordsRequest, response, context, userId);
        }
Beispiel #29
0
        public async void ConfirmValidCode()
        {
            // arrange
            int    userId    = 1;
            int    rightCode = 111111;
            string newEmail  = "*****@*****.**";

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            context.EmailVerifies.Add(new EmailVerifies()
            {
                UserId = userId,
                Code   = rightCode,
                Email  = newEmail
            });
            await context.SaveChangesAsync();

            Account account = context.Accounts.First();

            // act
            var requestObject =
                new AuthReq <ConfirmEmailRequest, ConfirmEmailReply>(
                    new ConfirmEmailRequest()
            {
                Email = newEmail, Code = rightCode
            })
            {
                UserId = account.AccountId
            };

            var registration = new ConfirmEmail(context);
            var test         = await registration.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(0, context.EmailVerifies.Count());
            Assert.Equal(newEmail, test.Email);
            Assert.Equal(newEmail, context.Accounts.First().Email);
        }
Beispiel #30
0
        public async void HistoryNonExistWordsExist()
        {
            // initialise
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            context.Games.Add(new Game {
                GameId = 1
            });
            context.GameTags.Add(new GameTag()
            {
                UserId = 1, Tags = GameTags.CustomLevelsHistory, GameId = 1
            });
            var testQuery = new CustomLevelMetricQuery()
            {
                UserId  = 1,
                Metrics = new List <ClassicCardLevelMetric>()
                {
                    new ClassicCardLevelMetric()
                    {
                        GameLevelId          = 0,
                        WordPairIdOpenCounts = new Dictionary <int, int>()
                        {
                            { 1, 2 },
                            { 2, 3 },
                            { 3, 4 }
                        }
                    }
                }.ToImmutableArray()
            };
            await context.SaveChangesAsync().ConfigureAwait(false);


            // act
            var handler = new CreateHistoryLevelsRequest(context);

            // assert
            await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => handler.Handle(testQuery)).ConfigureAwait(false);

            context.Dispose();
        }