예제 #1
0
        public void GenerateFailureCountryDoesntExistsInTheRepo()
        {
            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();
            // Filling mock rull with repository
            var mock           = new Mock <ILeagueRepository>(MockBehavior.Strict);
            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);
            var mockCountry    = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult((Country)null));

            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;
            String errorMessage          = response.Content.ReadAsStringAsync().Result;

            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
            Assert.AreEqual(errorMessage, "{\"Message\":\"The country doesn't exist\"}");
        }
예제 #2
0
        // Mocking the valide generation for a determined number of players (return the created leagues)
        private List <League> _initGenerateLeagueValidPlayers(int nbPlayers)
        {
            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();

            fillPlayerLeagues(generateLeagueDTO, nbPlayers);
            List <Team> teams = new List <Team>();

            for (int i = 0; i < nbPlayers; i++)
            {
                teams.Add(new Team());
            }


            Season season = new Season();
            Player player = new Player();

            // Filling mock rull with repository
            var mock = new Mock <ILeagueRepository>(MockBehavior.Strict);

            mock.As <ICRUDRepository <League, int, LeagueFilter> >().Setup(l => l.GetAllWithFilter(It.IsAny <LeagueFilter>()))
            .Returns(Task.FromResult((IEnumerable <League>)null));

            // Mocking the creation of the league createLeagueAttachedToPlayers
            List <League> createdLeagues = new List <League>();
            var           mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            // Setting up that the country name already exist
            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(false));

            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Setting up that the teams
            mockTeamRepo.As <ICRUDRepository <Team, int, TeamFilter> >().Setup(s => s.GetAllWithFilter(It.IsAny <TeamFilter>()))
            .Returns(Task.FromResult((IEnumerable <Team>)teams));


            // mocking the answer
            mock.As <ILeagueRepository>().Setup(l => l.GetViewModel(It.IsAny <int>()))
            .Returns(Task.FromResult(new LeagueViewModel()));

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Get(nbPlayers, new GenerateLeagueDTO()).Result;

            var objectContent = response.Content as ObjectContent;

            return((List <League>)objectContent.Value);
        }
예제 #3
0
        public void GenerateFailureIfModelStateNotValid()
        {
            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();

            fillPlayerLeagues(generateLeagueDTO, 4);

            List <Team> teams = new List <Team>();

            for (int i = 0; i < 8; i++)
            {
                teams.Add(new Team());
            }

            // Filling mock rull with repository
            var mock = new Mock <ILeagueRepository>(MockBehavior.Strict);

            mock.As <ICRUDRepository <League, int, LeagueFilter> >().Setup(l => l.GetAllWithFilter(It.IsAny <LeagueFilter>()))
            .Returns(Task.FromResult((IEnumerable <League>)null));

            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            // Setting up that the country name already exist
            mockSeasonRepo.As <ICRUDRepository <Season, int, SeasonFilter> >().Setup(s => s.Get(It.IsAny <int>()))
            .Returns(Task.FromResult(new Season()));


            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Setting up that the teams
            mockTeamRepo.As <ICRUDRepository <Team, int, TeamFilter> >().Setup(s => s.GetAllWithFilter(It.IsAny <TeamFilter>()))
            .Returns(Task.FromResult((IEnumerable <Team>)teams));
            // Setting up that the country name already exist
            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(false));

            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            // Facking a model error
            controller.ModelState.AddModelError("key", "errorMessage");

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;
            String errorMessage          = response.Content.ReadAsStringAsync().Result;

            // the result should say "HttpStatusCode.BadRequest"
            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
            Assert.AreEqual(errorMessage, "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"key\":[\"errorMessage\"]}}");
        }
예제 #4
0
        public void GenerateFailureLeagueLessThanFourPlayers()
        {
            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();

            generateLeagueDTO.PlayerLeagues = new List <PlayerAssignLeagueModel>();
            generateLeagueDTO.Rules         = new RuleSet();
            // We create a list of players
            List <Player> players = new List <Player>();

            for (int i = 0; i < 3; i++)
            {
                players.Add(new Player());
            }
            PlayerAssignLeagueModel playerLeague = new PlayerAssignLeagueModel {
                league = new League(), Players = players
            };

            generateLeagueDTO.PlayerLeagues.Add(playerLeague);

            // Filling mock rull with repository
            var mock = new Mock <ILeagueRepository>(MockBehavior.Strict);

            mock.As <ICRUDRepository <League, int, LeagueFilter> >().Setup(l => l.GetAllWithFilter(It.IsAny <LeagueFilter>()))
            .Returns(Task.FromResult((IEnumerable <League>)null));

            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            // Setting up that the country name already exist
            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(false));

            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Setting up that the teams
            mockTeamRepo.As <ICRUDRepository <Team, int, TeamFilter> >().Setup(s => s.GetAllWithFilter(It.IsAny <TeamFilter>()))
            .Returns(Task.FromResult((IEnumerable <Team>) new List <Team>()));

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;

            String errorMessage = response.Content.ReadAsStringAsync().Result;

            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
            Assert.AreEqual(errorMessage, "{\"Message\":\"You must choose at least 4 players.\"}");
        }
        [Authorize(Roles = AuthenticationRoles.AdministratorRole)] // Require authenticated requests.
        public async Task <HttpResponseMessage> Post(GenerateLeagueDTO item)
        {
            // try to get the season, if it returns null, send an error
            if (item == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Item is empty"));
            }
            else if (!await this.isCountryExist(item.CountryId))
            {
                return(this.createErrorResponseCountryDoesntExists());
            }
            else if (await this.seasonRepository.isSeasonNameExist(item.CountryId, item.SeasonName, null))
            {
                return(this.createErrorResponseSeasonNameExists());
            }
            else
            {
                // get the season
                Season season = new Season {
                    CountryId = item.CountryId, Name = item.SeasonName, RuleSetId = item.Rules.Id
                };

                // retrieving the teams associated to the country
                List <Team> teams = new List <Team>(await this.getTeamsAssociatedToTheCountry(item.CountryId));

                // Counting the total of players inserted and verifying that all the leagues are correctly filled
                int totalOfPlayers = 0;
                foreach (var playerLeagues in item.PlayerLeagues)
                {
                    if (playerLeagues.league == null || playerLeagues.league.Name == "")
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "All the leagues must have a name."));
                    }
                    totalOfPlayers += playerLeagues.Players.Count();
                }

                string errorString = checkNumberOfPlayersRules(totalOfPlayers, teams.Count());
                // Their will be at least <minNumberOfPlayers> players
                if (errorString != null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorString));
                }
                else if (ModelState.IsValid)
                {
                    // Generate the league
                    return(await this.GenerateLeagues(season, teams, new List <PlayerAssignLeagueModel>(item.PlayerLeagues)));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
        }
예제 #6
0
        private void  fillPlayerLeagues(GenerateLeagueDTO generateLeagueDTO, int nbPlayers)
        {
            generateLeagueDTO.PlayerLeagues = new List <PlayerAssignLeagueModel>();
            // We create a list of players
            List <Player> players = new List <Player>();

            for (int i = 0; i < nbPlayers; i++)
            {
                players.Add(new Player());
            }
            generateLeagueDTO.PlayerLeagues.Add(new PlayerAssignLeagueModel {
                league = new League {
                    Name = "League 1"
                }, Players = players
            });
            generateLeagueDTO.Rules = new RuleSet();
        }
예제 #7
0
        public void GenerateFailureSeasonNameExistsInTheRepo()
        {
            IEnumerable <League> leagues           = CreateLeagueList();
            GenerateLeagueDTO    generateLeagueDTO = new GenerateLeagueDTO();

            // Filling mock rull with repository
            var mock = new Mock <ILeagueRepository>(MockBehavior.Strict);

            mock.As <ICRUDRepository <League, int, LeagueFilter> >().Setup(l => l.GetAllWithFilter(It.IsAny <LeagueFilter>()))
            .Returns(Task.FromResult(leagues));

            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            // Setting up that the country name already exist
            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(true));

            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;
            String errorMessage          = response.Content.ReadAsStringAsync().Result;

            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
            Assert.AreEqual(errorMessage, "{\"Message\":\"The season name already exists for this country\"}");
        }
        public async Task <HttpResponseMessage> Get(int numberOfPlayers, [FromUri] GenerateLeagueDTO item = null)
        {
            // retrieving the teams associated to the country
            List <Team> teams = new List <Team>(await this.getTeamsAssociatedToTheCountry(item.CountryId));

            if (item == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Item is empty"));
            }
            else if (!await this.isCountryExist(item.CountryId))
            {
                return(this.createErrorResponseCountryDoesntExists());
            }
            else if (await this.seasonRepository.isSeasonNameExist(item.CountryId, item.SeasonName, null))
            {
                return(this.createErrorResponseSeasonNameExists());
            }
            else
            {
                // Checking that everything is ok for the league generation
                string errorString = checkNumberOfPlayersRules(numberOfPlayers, teams.Count());

                // returning an error if errorString is not empty
                if (errorString != null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorString));
                }
                else
                {
                    List <League> leagues      = new List <League>();
                    int           leagueNumber = 1;

                    // For each <maxNumberOfPlayersByLeague>, we create an other league
                    while (numberOfPlayers > 0)
                    {
                        string leagueName = "League " + leagueNumber;

                        // If numberOfPlayers / maxNumberOfPlayersByLeague > 2, we remove the max number of players
                        if ((numberOfPlayers / MaxNumberOfPlayersByLeague) >= 2)
                        {
                            numberOfPlayers -= MaxNumberOfPlayersByLeague;
                        }
                        else if (numberOfPlayers >= MaxNumberOfPlayersByLeague)
                        {
                            numberOfPlayers -= MinNumberOfPlayers;
                        }
                        else
                        {
                            numberOfPlayers = 0;
                        }

                        leagues.Add(new League {
                            Id = leagueNumber, Name = leagueName
                        });

                        leagueNumber++;
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, leagues));
                }
            }
        }
예제 #9
0
        public void GenerateLeagueWithOnlyOneTeamReturnsAFailure()
        {
            League league = new League();

            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();

            fillPlayerLeagues(generateLeagueDTO, 4); //Add 4 people to first league
            // We create a list of players
            List <Player> players = new List <Player>()
            {
                new Player()
            };

            //Add second league with just one player
            generateLeagueDTO.PlayerLeagues.Add(new PlayerAssignLeagueModel {
                league = new League {
                    Name = "League 2"
                }, Players = players
            });
            List <Team> teams = new List <Team>();

            for (int i = 0; i < 5; i++)
            {
                teams.Add(new Team());
            }

            Season season = new Season();
            Player player = new Player();

            var mockLeagueRepo = new Mock <ILeagueRepository>(MockBehavior.Strict);

            List <League> createdLeagues = new List <League>();

            //Mock the season repo to replay that the season name does not already exist
            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(false));

            //Mock the country repo to return a country, a country is needed to create seasons
            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            //Mock the team repo to return the list of teams we created earlier
            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            mockTeamRepo.As <ICRUDRepository <Team, int, TeamFilter> >().Setup(s => s.GetAllWithFilter(It.IsAny <TeamFilter>()))
            .Returns(Task.FromResult((IEnumerable <Team>)teams));

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mockLeagueRepo.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);

            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;

            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
            String errorMessage = response.Content.ReadAsStringAsync().Result;

            Assert.AreEqual(errorMessage, "{\"Message\":\"A league must have at least 2 players\"}");
        }
예제 #10
0
        public void GenerateLeagueValidPlayersWithTeam()
        {
            League league = new League();

            GenerateLeagueDTO generateLeagueDTO = new GenerateLeagueDTO();

            fillPlayerLeagues(generateLeagueDTO, 4);
            List <Team> teams = new List <Team>();

            for (int i = 0; i < 8; i++)
            {
                teams.Add(new Team());
            }
            Season season = new Season();
            Player player = new Player();

            // Filling mock rull with repository
            var mock = new Mock <ILeagueRepository>(MockBehavior.Strict);

            mock.As <ICRUDRepository <League, int, LeagueFilter> >().Setup(l => l.GetAllWithFilter(It.IsAny <LeagueFilter>()))
            .Returns(Task.FromResult((IEnumerable <League>)null));

            // Mocking the creation of the league createLeagueAttachedToPlayers
            mock.As <ILeagueRepository>().Setup(l => l.createSeasonWithLeagues(It.IsAny <Season>(), It.IsAny <List <League> >()))
            .Returns(Task.FromResult(season));

            var mockSeasonRepo = new Mock <ISeasonRepository>(MockBehavior.Strict);

            // Setting up that the country name already exist
            mockSeasonRepo.As <ICRUDRepository <Season, int, SeasonFilter> >().Setup(s => s.Get(It.IsAny <int>()))
            .Returns(Task.FromResult(new Season()));
            // Setting up that the country name already exist
            mockSeasonRepo.As <ISeasonRepository>().Setup(s => s.isSeasonNameExist(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int?>()))
            .Returns(Task.FromResult(false));

            var mockCountry = new Mock <ICountryRepository>(MockBehavior.Strict);

            mockCountry.As <ICountryRepository>().Setup(c => c.Get(It.IsAny <int>())).Returns(Task.FromResult(new Country()));

            var mockTeamRepo = new Mock <ITeamRepository>(MockBehavior.Strict);

            // Setting up that the teams
            mockTeamRepo.As <ICRUDRepository <Team, int, TeamFilter> >().Setup(s => s.GetAllWithFilter(It.IsAny <TeamFilter>()))
            .Returns(Task.FromResult((IEnumerable <Team>)teams));


            // mocking the answer
            mock.As <ILeagueRepository>().Setup(l => l.GetViewModel(It.IsAny <int>()))
            .Returns(Task.FromResult(new LeagueViewModel()));

            // Creating the controller which we want to create
            GenerateLeagueController controller = new GenerateLeagueController(mock.Object, mockSeasonRepo.Object,
                                                                               mockTeamRepo.Object, mockCountry.Object);


            // configuring the context for the controler
            fakeContext(controller);

            HttpResponseMessage response = controller.Post(generateLeagueDTO).Result;

            // the result should say "HttpStatusCode.Created"
            Assert.AreEqual(response.StatusCode, HttpStatusCode.Created);
        }