Пример #1
0
        public void Register_WhenInscriptionFulfilled_ShouldThrowInvalidOperationException()
        {
            // Arrange
            var challengeFaker = TestData.FakerFactory.CreateChallengeFaker(43897896, Game.LeagueOfLegends, ChallengeState.Inscription);

            var challenge = challengeFaker.FakeChallenge();

            var participantCount = challenge.Entries - challenge.Participants.Count;

            for (var index = 0; index < participantCount; index++)
            {
                challenge.Register(
                    new Participant(
                        new ParticipantId(),
                        new UserId(),
                        PlayerId.Parse(Guid.NewGuid().ToString()),
                        new UtcNowDateTimeProvider()));
            }

            // Act
            var action = new Action(
                () => challenge.Register(
                    new Participant(
                        new ParticipantId(),
                        new UserId(),
                        PlayerId.Parse(Guid.NewGuid().ToString()),
                        new UtcNowDateTimeProvider())));

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
        private async Task <LeagueOfLegendsGameAuthentication> GenerateAuthFactor(Summoner summoner)
        {
            const int ProfileIconIdMinIndex = 0;
            const int ProfileIconIdMaxIndex = 28;

            var random = new Random();

            var currentSummonerProfileIconId = summoner.ProfileIconId;

            var expectedSummonerProfileIconId = summoner.ProfileIconId;

            while (expectedSummonerProfileIconId == summoner.ProfileIconId)
            {
                expectedSummonerProfileIconId = random.Next(ProfileIconIdMinIndex, ProfileIconIdMaxIndex);
            }

            var t = await this.DownloadSummonerProfileIconIdAsync(currentSummonerProfileIconId);

            var y = await this.DownloadSummonerProfileIconIdAsync(expectedSummonerProfileIconId);

            return(new LeagueOfLegendsGameAuthentication(
                       PlayerId.Parse(summoner.AccountId),
                       new LeagueOfLegendsGameAuthenticationFactor(
                           currentSummonerProfileIconId,
                           t,
                           expectedSummonerProfileIconId,
                           y)));
        }
        public override async Task <DomainValidationResult <object> > GenerateAuthenticationAsync(UserId userId, LeagueOfLegendsRequest request)
        {
            try
            {
                var result = new DomainValidationResult <object>();

                var summoner = await _leagueOfLegendsService.Summoner.GetSummonerByNameAsync(Region.Na, request.SummonerName);

                if (await _gameCredentialRepository.CredentialExistsAsync(PlayerId.Parse(summoner.AccountId), Game))
                {
                    result.AddFailedPreconditionError("Summoner's name is already linked by another eDoxa account");
                }

                if (result.IsValid)
                {
                    if (await _gameAuthenticationRepository.AuthenticationExistsAsync(userId, Game))
                    {
                        await _gameAuthenticationRepository.RemoveAuthenticationAsync(userId, Game);
                    }

                    var gameAuthentication = await this.GenerateAuthFactor(summoner);

                    await _gameAuthenticationRepository.AddAuthenticationAsync(userId, Game, gameAuthentication);

                    return(gameAuthentication.Factor);
                }

                return(result);
            }
            catch (RiotSharpException)
            {
                return(DomainValidationResult <object> .Failure("Summoner name is invalid"));
            }
        }
Пример #4
0
 public MockHttpContextAccessor()
 {
     this.SetupGet(accessor => accessor.HttpContext.User.Claims)
     .Returns(
         new HashSet <Claim>
     {
         new Claim(JwtClaimTypes.Subject, "5C43502B-FCE8-4235-8557-C22D2A638AD7"),
         new Claim(JwtClaimTypes.Email, "*****@*****.**"),
         new Claim($"games/{Game.LeagueOfLegends.CamelCaseName}", PlayerId.Parse("qwe213rq2131eqw")),
         new Claim(CustomClaimTypes.StripeCustomer, "customerId")
     })
     .Verifiable();
 }
        public static Participant ToEntity(this ParticipantModel model)
        {
            var participant = new Participant(
                ParticipantId.FromGuid(model.Id),
                UserId.FromGuid(model.UserId),
                PlayerId.Parse(model.PlayerId),
                new DateTimeProvider(model.RegisteredAt));

            if (model.SynchronizedAt.HasValue && model.Matches != null)
            {
                participant.Snapshot(model.Matches.Select(match => match.ToEntity()), new DateTimeProvider(model.SynchronizedAt.Value));
            }

            participant.ClearDomainEvents();

            return(participant);
        }
Пример #6
0
        public void Register_WhenParticipantIsRegistered_ShouldThrowInvalidOperationException()
        {
            // Arrange
            var challengeFaker = TestData.FakerFactory.CreateChallengeFaker(48536956, Game.LeagueOfLegends, ChallengeState.Inscription);

            var challenge = challengeFaker.FakeChallenge();

            // Act
            var action = new Action(
                () => challenge.Register(
                    new Participant(
                        new ParticipantId(),
                        challenge.Participants.First().UserId,
                        PlayerId.Parse(Guid.NewGuid().ToString()),
                        new UtcNowDateTimeProvider())));

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
Пример #7
0
        public void Register_WhenStateInscription_ShouldHaveOneMore()
        {
            // Arrange
            var challengeFaker = TestData.FakerFactory.CreateChallengeFaker(85256956, Game.LeagueOfLegends, ChallengeState.Inscription);

            var challenge = challengeFaker.FakeChallenge();

            var participantCount = challenge.Participants.Count;

            // Act
            challenge.Register(
                new Participant(
                    new ParticipantId(),
                    new UserId(),
                    PlayerId.Parse(Guid.NewGuid().ToString()),
                    new UtcNowDateTimeProvider()));

            // Assert
            challenge.Participants.Should().HaveCount(participantCount + 1);
        }
        public async Task GenerateAuthenticationAsync_ShouldBeOfTypeOkObjectResult()
        {
            // Arrange
            var gameAuthentication = new LeagueOfLegendsGameAuthentication(
                PlayerId.Parse("playerId"),
                new LeagueOfLegendsGameAuthenticationFactor(
                    1,
                    string.Empty,
                    2,
                    string.Empty));

            TestMock.GameAuthenticationService
            .Setup(authFactorService => authFactorService.GenerateAuthenticationAsync(It.IsAny <UserId>(), It.IsAny <Game>(), It.IsAny <object>()))
            .ReturnsAsync(DomainValidationResult <GameAuthentication> .Succeeded(gameAuthentication))
            .Verifiable();

            var authFactorController = new GameAuthenticationsController(
                TestMock.GameAuthenticationService.Object,
                TestMock.GameCredentialService.Object,
                TestMapper)
            {
                ControllerContext =
                {
                    HttpContext = MockHttpContextAccessor.GetInstance()
                }
            };

            // Act
            var result = await authFactorController.GenerateAuthenticationAsync(Game.LeagueOfLegends, "playerId");

            // Assert
            result.Should().BeOfType <OkObjectResult>();

            TestMock.GameAuthenticationService.Verify(
                authFactorService => authFactorService.GenerateAuthenticationAsync(It.IsAny <UserId>(), It.IsAny <Game>(), It.IsAny <object>()),
                Times.Once);
        }
Пример #9
0
        public async Task Scenario_ChallengeStateIsValid_ShouldBeTrue(int seed)
        {
            // Arrange
            var faker          = new Faker();
            var challengeFaker = TestData.FakerFactory.CreateChallengeFaker(seed, Game.LeagueOfLegends, ChallengeState.Inscription);
            var fakeChallenge  = challengeFaker.FakeChallenge();

            TestHost.CreateClient();
            var testServer = TestHost.Server;

            testServer.CleanupDbContext();

            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                challengeRepository.Create(fakeChallenge);
                await challengeRepository.CommitAsync(false);
            });

            // Assert
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                challenge?.Should().Be(fakeChallenge);
                challenge?.Timeline.State.Should().Be(ChallengeState.Inscription);
            });

            var participant1 = new Participant(
                new ParticipantId(),
                new UserId(),
                PlayerId.Parse(Guid.NewGuid().ToString()),
                new UtcNowDateTimeProvider());

            // Act
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                challenge?.Register(participant1);
                await challengeRepository.CommitAsync(false);
            });

            // Assert
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                challenge?.Participants.Should().Contain(participant1);
                challenge?.Timeline.State.Should().Be(ChallengeState.Inscription);
            });

            // Act
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                var entries = challenge?.Entries - challenge?.Participants.Count;

                for (var index = 0; index < entries; index++)
                {
                    challenge?.Register(
                        new Participant(
                            new ParticipantId(),
                            new UserId(),
                            PlayerId.Parse(Guid.NewGuid().ToString()),
                            new UtcNowDateTimeProvider()));
                }

                challenge?.Start(new UtcNowDateTimeProvider());
                await challengeRepository.CommitAsync(false);
            });

            // Assert
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                challenge?.Participants.Should().HaveCount(challenge.Entries);
                challenge?.Timeline.State.Should().Be(ChallengeState.InProgress);
            });

            var match1 = new Match(
                new GameUuid(Guid.NewGuid()),
                new UtcNowDateTimeProvider(),
                TimeSpan.FromSeconds(3600),
                fakeChallenge.Scoring.Map(faker.Game().Stats()),
                new UtcNowDateTimeProvider());

            // Act
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                var participant = challenge?.Participants.Single(p => p == participant1);

                participant?.Snapshot(
                    new List <IMatch>
                {
                    match1
                },
                    new UtcNowDateTimeProvider());

                await challengeRepository.CommitAsync(false);
            });

            // Assert
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                var participant = challenge?.Participants.Single(p => p == participant1);
                participant?.Matches.Should().Contain(match1);
                participant?.SynchronizedAt.Should().NotBeNull();
                challenge?.Timeline.State.Should().Be(ChallengeState.InProgress);
            });

            var match2 = new Match(
                new GameUuid(Guid.NewGuid()),
                new UtcNowDateTimeProvider(),
                TimeSpan.FromSeconds(3600),
                new List <Stat>
            {
                new Stat(new StatName(fakeChallenge.Game.Name), new StatValue(23847883M), new StatWeighting(1))
            },
                new UtcNowDateTimeProvider());

            // Act
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                var participant = challenge?.Participants.Single(p => p == participant1);

                participant?.Snapshot(
                    new List <IMatch>
                {
                    match2
                },
                    new UtcNowDateTimeProvider());

                await challengeRepository.CommitAsync(false);
            });

            // Assert
            await testServer.UsingScopeAsync(
                async scope =>
            {
                var challengeRepository = scope.GetRequiredService <IChallengeRepository>();
                var challenge           = await challengeRepository.FindChallengeOrNullAsync(fakeChallenge.Id);
                challenge.Should().NotBeNull();
                var participant = challenge?.Participants.Single(p => p == participant1);
                participant?.Matches.Should().BeEquivalentTo(match1, match2);
                participant?.SynchronizedAt.Should().NotBeNull();
                challenge?.Timeline.State.Should().Be(ChallengeState.InProgress);
            });
        }
Пример #10
0
        public async Task Success2()
        {
            // Arrange
            using var gamesHost = new GamesHostFactory();

            var gamesServiceClient = new GameService.GameServiceClient(gamesHost.CreateChannel());

            var findChallengeScoringRequest = new FindChallengeScoringRequest
            {
                Game = EnumGame.LeagueOfLegends
            };

            var findChallengeScoringResponse = await gamesServiceClient.FindChallengeScoringAsync(findChallengeScoringRequest);

            var createdAt = new DateTimeProvider(
                new DateTime(
                    2019,
                    12,
                    30,
                    21,
                    9,
                    22,
                    DateTimeKind.Utc));

            var startedAt = new DateTimeProvider(
                new DateTime(
                    2019,
                    12,
                    30,
                    22,
                    42,
                    50,
                    DateTimeKind.Utc));

            var challenge = new Challenge(
                new ChallengeId(),
                new ChallengeName("TEST CHALLENGE"),
                Game.LeagueOfLegends,
                BestOf.One,
                Entries.Two,
                new ChallengeTimeline(createdAt, ChallengeDuration.OneDay),
                new Scoring(
                    findChallengeScoringResponse.Scoring.Items.OrderBy(scoring => scoring.Order)
                    .ToDictionary(scoring => scoring.StatName, scoring => scoring.StatWeighting)));

            var participant = new Participant(
                new ParticipantId(),
                new UserId(),
                PlayerId.Parse("V1R8S4W19KGdqSTn-rRO-pUGv6lfu2BkdVCaz_8wd-m6zw"),
                new DateTimeProvider(createdAt.DateTime + TimeSpan.FromMinutes(5)));

            challenge.Register(participant);

            challenge.Register(
                new Participant(
                    new ParticipantId(),
                    new UserId(),
                    new PlayerId(),
                    new DateTimeProvider(createdAt.DateTime + TimeSpan.FromMinutes(10))));

            challenge.Start(startedAt);

            var mockServiceBusPublisher = new Mock <IServiceBusPublisher>();

            mockServiceBusPublisher.Setup(serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            using var challengesHost = new ChallengesHostFactory().WithWebHostBuilder(
                      builder =>
            {
                builder.ConfigureTestContainer <ContainerBuilder>(
                    container =>
                {
                    container.RegisterInstance(mockServiceBusPublisher.Object).As <IServiceBusPublisher>().SingleInstance();
                });
            });

            challengesHost.Server.CleanupDbContext();

            await challengesHost.Server.UsingScopeAsync(
                async scope =>
            {
                var repository = scope.GetRequiredService <IChallengeRepository>();

                repository.Create(challenge);

                await repository.CommitAsync(false);
            });

            var recurringJob = new ChallengeRecurringJob(
                new ChallengeService.ChallengeServiceClient(challengesHost.CreateChannel()),
                new GameService.GameServiceClient(gamesHost.CreateChannel()));

            // Act
            await recurringJob.SynchronizeChallengesAsync(EnumGame.LeagueOfLegends);

            // Assert
            await challengesHost.Server.UsingScopeAsync(
                async scope =>
            {
                var repository = scope.GetRequiredService <IChallengeRepository>();

                var persistentChallenge = await repository.FindChallengeAsync(challenge.Id);

                persistentChallenge.FindParticipant(participant.PlayerId).Matches.Should().HaveCount(2);
            });

            mockServiceBusPublisher.Verify(
                serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()),
                Times.Exactly(1));
        }
Пример #11
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Credential>(
                builder =>
            {
                builder.Property(credential => credential.UserId).HasConversion <Guid>(userId => userId, value => UserId.FromGuid(value)).IsRequired();

                builder.Property(credential => credential.Game).HasConversion(game => game.Value, value => Game.FromValue(value)).IsRequired();

                builder.Property(credential => credential.PlayerId).HasConversion <string>(userId => userId, value => PlayerId.Parse(value)).IsRequired();

                builder.Property(credential => credential.Timestamp).HasConversion(dateTime => dateTime.Ticks, value => new DateTime(value)).IsRequired();

                builder.HasKey(
                    credential => new
                {
                    credential.UserId,
                    credential.Game
                });

                builder.HasIndex(
                    credential => new
                {
                    credential.Game,
                    credential.PlayerId
                })
                .IsUnique();

                builder.ToTable("Credential");
            });
        }