Esempio n. 1
0
def pull_teams(url, player_lookup, sponsor_lookup, league_lookup):
    """
    pull_teams
        Returns a lookup of teams that were pulled
        from the website into local DB
        Parameters:
            url: the url of the main site
        Returns:
            a dictionary lookup
                for the website team id to local team object
                e.g. team_lookup = {1: Team(), etc..}
    """
    _teams = requests.get(url + "/api/teams").json()
    if isinstance(_teams, dict):
        _teams = pull_all_pages(url, _teams)
    team_lookups = {}
    for team in tqdm(_teams, desc="Pulling teams from {}".format(url)):
        temp = Team(color=team['color'],
                    sponsor_id=sponsor_lookup[team['sponsor_id']].id,
                    league_id=league_lookup[team['league_id']].id,
                    year=team['year'])
        # need to add the players from the roster to the team
        players = requests.get(url + "/api/teamroster/" +
                               team['team_id']).json()
        for player in players:
            temp.insert_player(player_lookup[player['player_id']].id,
                               is_player_captain(player, team))
        team_lookups[team['team_id']] = temp
        DB.session.add(temp)
    DB.session.commit()
    return team_lookups
Esempio n. 2
0
    def add_team_functional(self):
        """ Add a team to the database using functions instead of methods"""
        # parse out the parts - background, header, players
        parts = parse_lines(self.lines)
        self.warnings = parts['warnings']

        # extract the background such a league, sponsor and color
        background = extract_background(parts['background'])

        # extract the players using the header as lookup
        lookup = extract_column_indices_lookup(parts['header'])
        players = extract_players(parts["players"], lookup)
        self.warnings = self.warnings + players['warnings']

        # add the players
        player_models = []
        for player_json in players['player_info']:
            try:
                if (player_json['player_id'] is None):
                    # need to create the player
                    player = Player(player_json['name'],
                                    player_json['email'],
                                    gender=player_json["gender"])
                    self.session.add(player)
                    self.session.commit()
                else:
                    email = player_json['email']
                    player = Player.query.filter(
                        func.lower(Player.email) == func.lower(email)).first()
                player_models.append(player.json())
            except Exception as error:
                player_info = "-".join(
                    [player_json["name"], player_json["email"]])
                self.warnings.append(
                    INVALID_PLAYER.format(player_info, str(error)))

        # get the team, create if does not exist
        if background['team']['team_id'] is None:
            team = Team(color=background['team']['color'],
                        sponsor_id=background['sponsor']['sponsor_id'],
                        league_id=background['league']['league_id'],
                        year=date.today().year)
            self.session.add(team)
        else:

            # get the team and remove all players
            team = Team.query.get(background['team']['team_id'])
            team.players = []
        set_captain = False
        for player in player_models:
            if (player["player_name"].lower() == background["captain"]
                ["player_name"].lower()):
                set_captain = True
                team.insert_player(player["player_id"], captain=True)
            else:
                team.insert_player(player["player_id"], captain=False)
        if not set_captain:
            self.warnings.append(CAPTAIN_NOT_ASSIGNED)
        self.session.commit()
 def post(self):
     """
         POST request for Teams List
         Route: Routes['team']
         Parameters :
             league_id: the league's id (int)
             sponsor_id: the sponsor's id (int)
             color: the color of the team (string)
             year: the year the team is playing in (int)
             espys: the team espys points (int)
         Returns:
             if successful
                 status: 200
                 mimetype: application/json
                 data: the create team id (int)
             possible errors
                 status: 400, IFSC, LDNESC, PDNESC or SDNESC
                 mimetype: application/json
                 data: the create team id (int)
     """
     # create a new user
     args = post_parser.parse_args()
     color = None
     sponsor_id = None
     league_id = None
     year = date.today().year
     if args['color']:
         color = args['color']
     if args['sponsor_id']:
         sponsor_id = args['sponsor_id']
     if args['league_id']:
         league_id = args['league_id']
     if args['year']:
         year = args['year']
     t = Team(color=color,
              sponsor_id=sponsor_id,
              league_id=league_id,
              year=year)
     DB.session.add(t)
     DB.session.commit()
     result = t.id
     handle_table_change(Tables.TEAM, item=t.json())
     return Response(dumps(result), status=201, mimetype="application/json")
Esempio n. 4
0
    def testJoinLeagueRequestInit(self):
        """ Test the constructor validates the given data"""
        player = str(uuid.uuid1())
        email = player + "@mlsb.ca"
        some_gender = "m"
        color = str(uuid.uuid1())
        league = self.add_league(str(uuid.uuid1()))
        sponsor = self.add_sponsor(str(uuid.uuid1()))
        no_team = Team(color="Black",
                       sponsor_id=sponsor['sponsor_id'],
                       league_id=league['league_id'])
        team_json = self.add_team(color, sponsor=sponsor, league=league)
        team = Team.query.get(team_json['team_id'])

        # good request and test json method
        league_request = JoinLeagueRequest(email, player, team, some_gender)
        league_request.json()

        # bad stuff
        try:
            JoinLeagueRequest(1, player, team, some_gender)
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
        try:
            JoinLeagueRequest(email, 1, team, some_gender)
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
        try:
            JoinLeagueRequest(email, player, "wrong team", some_gender)
            self.assertEqual(False, True, "Should raise team does not exist")
        except TeamDoesNotExist:
            pass
        try:
            JoinLeagueRequest(email, player, no_team, some_gender)
            self.assertEqual(False, True, "Should raise team does not exist")
        except TeamDoesNotExist:
            pass
        try:
            JoinLeagueRequest(email, player, team, "XX")
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
Esempio n. 5
0
    def testTeamInit(self):
        league = self.add_league(str(uuid.uuid1()))
        sponsor = self.add_sponsor(str(uuid.uuid1()))

        # good Teams
        Team(color="Black",
             sponsor_id=sponsor['sponsor_id'],
             league_id=league['league_id'])
        Team(color="Green",
             sponsor_id=sponsor['sponsor_id'],
             league_id=league['league_id'],
             year=VALID_YEAR)

        # now for bad teams
        try:
            Team(color="Black",
                 sponsor_id=INVALID_ID,
                 league_id=league['league_id'])
            self.assertEqual(False, True, "Should raise no sponsor")
        except SponsorDoesNotExist:
            pass
        try:
            Team(color="Black",
                 sponsor_id=sponsor['sponsor_id'],
                 league_id=INVALID_ID)
            self.assertEqual(False, True, "Should raise no league")
        except LeagueDoesNotExist:
            pass
        try:
            Team(color=1,
                 sponsor_id=sponsor['sponsor_id'],
                 league_id=league['league_id'])
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
        try:
            Team(color="Black",
                 sponsor_id=sponsor['sponsor_id'],
                 league_id=league['league_id'],
                 year=1)
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
Esempio n. 6
0
 def import_headers(self):
     done = False
     i = 0
     sponsor = None
     color = None
     captain = None
     league = None
     while not done:
         # read the headers
         line = self.lines[i]
         columns = line.split(",")
         if self.clean_cell(columns[0]) == "sponsor":
             sponsor = columns[1].strip()
         elif self.clean_cell(columns[0]) == "color":
             color = columns[1].strip()
         elif self.clean_cell(columns[0]) == "captain":
             captain =  columns[1].strip()
         elif self.clean_cell(columns[0]) == "league":
             league = columns[1].strip()
         else:
             # assuming done reading the headers
             done = True
         i += 1
     player_index = i
     if sponsor is None:
         raise InvalidField(payload={"details": "No sponsor was given"})
     if captain is None:
         raise InvalidField(payload={"details": "No captain was given"})
     if color is None:
         raise InvalidField(payload={"details": "No color was given"})
     if league is None:
         raise InvalidField(payload={"details": "No league was given"})
     # check no examples were left and actually real info
     if (league.lower().startswith("ex.")
         or sponsor.lower().startswith("ex.")
         or color.lower().startswith("ex.")
         or captain.lower().startswith("ex.")):
         raise InvalidField(payload={"details": "The header's still had an example"})
     sponsor_id = (DB.session.query(Sponsor).filter(Sponsor.name==sponsor)
                   .first())
     if sponsor_id  is None:
         sponsor_id = (DB.session.query(Sponsor).filter(Sponsor.nickname==sponsor)
                   .first())
     if sponsor_id is None:
         # what kind of sponsor are you giving
         raise SponsorDoesNotExist(payload={'details': "The sponsor does not exist (check case)"})
     sponsor_id = sponsor_id.id
     league_id = (DB.session.query(League).filter(League.name==league)).first()
     if league_id is None:
         raise LeagueDoesNotExist(payload={"details": "The league does not exist (check case)"})
     league_id = league_id.id
     # check to see if team was already created
     teams = (DB.session.query(Team)
                 .filter(Team.color==color)
                 .filter(Team.sponsor_id==sponsor_id)
                 .filter(Team.year==date.today().year).all())
     team_found = None
     if len(teams) > 0:
         team_found = teams[0]
     # was the team not found then should create it
     if team_found is None:
         self.warnings.append("Team was created")
         team_found = Team(color=color,
                           sponsor_id=sponsor_id,
                           league_id=league_id)
     else:
         team_found.players = [] # remove all the players before
     self.team = team_found # set the team
     self.captain_name = captain # remember captains name
     return player_index
Esempio n. 7
0
 def testTeamUpdate(self):
     self.insertLeague()
     self.insertSponsor()
     # good Teams
     l = Team(color="Black", 
              sponsor_id=1, 
              league_id=1)
     l.update(color="Green", 
              sponsor_id=1, 
              league_id=1,
              year = 2014,
               )
     # now for bad teams
     try:
         l.update(color="Black", 
                  sponsor_id=99999, 
                  league_id=1)
         self.assertEqual(False, True, "Should raise no sponsor")
     except SponsorDoesNotExist:
         pass
     try:
         l.update(color="Black", 
                  sponsor_id=1, 
                  league_id=99999)
         self.assertEqual(False, True, "Should raise no league")
     except LeagueDoesNotExist:
         pass
     try:
         l.update(color=1, 
                  sponsor_id=1, 
                  league_id=1)
         self.assertEqual(False, True, "Should raise invalid field")
     except InvalidField:
         pass
     try:
         l.update(color="Black", 
                  sponsor_id=1, 
                  league_id=1,
                  year=1)
         self.assertEqual(False, True, "Should raise invalid field")
     except InvalidField:
         pass
Esempio n. 8
0
def mock_teams_games(league, sponsor_lookup):
    """
    mock_team_games
        Mocks up some data for the league by add some players to a team,
        then a few games to the league and a few scores for some games
        Parameters:
            league: the league object
            sponsor_lookup: a dictionary lookup for a id to its given sponsor
        Returns:
            None
    """
    # add some players
    domain = "@" + league.name.replace(" ", "")
    team_one_players = [
        Player("Captain1", "captain1" + domain, gender="M"),
        Player("MalePlayer1", "mp1" + domain, gender="M"),
        Player("FemalePlayer1", "fp1" + domain, gender="F")
    ]
    team_two_players = [
        Player("Captain2", "captain2" + domain, gender="F"),
        Player("MalePlayer2", "mp2" + domain, gender="M"),
        Player("FemalePlayer2", "fp2" + domain, gender="F")
    ]
    team_three_players = [
        Player("Captain3", "captain3" + domain, gender="M"),
        Player("MalePlayer3", "mp3" + domain, gender="M"),
        Player("FemalePlayer3", "fp3" + domain, gender="F")
    ]
    team_four_players = [
        Player("Captain4", "captain4" + domain, gender="F"),
        Player("MalePlayer4", "mp4" + domain, gender="M"),
        Player("FemalePlayer4", "fp4" + domain, gender="F")
    ]
    team_players = [
        team_one_players, team_two_players, team_three_players,
        team_four_players
    ]
    for team in tqdm(team_players, desc="Adding mock Players"):
        for player in team:
            DB.session.add(player)
    DB.session.commit()

    # add four teams with some players
    teams = [
        Team(color="Black",
             sponsor_id=random_value_lookup(sponsor_lookup).id,
             league_id=league.id),
        Team(color="Blue",
             sponsor_id=random_value_lookup(sponsor_lookup).id,
             league_id=league.id),
        Team(color="Red",
             sponsor_id=random_value_lookup(sponsor_lookup).id,
             league_id=league.id),
        Team(color="Green",
             sponsor_id=random_value_lookup(sponsor_lookup).id,
             league_id=league.id)
    ]
    for i in tqdm(range(0, len(teams)), desc="Adding mock players to Teams"):
        team = teams[i]
        DB.session.add(team)
        # add the players to the team
        for player in team_players[i]:
            team.insert_player(player.id, "captain" in player.name.lower())
    DB.session.commit()

    # add some random espsy to each team and
    # create a lookup for team id to players
    team_player_lookup = {}
    random_prices = [9.99, 4.75, 100, 15.50, 12.99]
    for i in tqdm(range(0, len(teams)), desc="Adding mock espys to Teams"):
        team_player_lookup[team.id] = team_players[i]
        team = teams[i]
        for __ in range(0, 4):
            points = random_value_list(random_prices)
            espy = Espys(team.id,
                         sponsor_id=random_value_lookup(sponsor_lookup).id,
                         description="Purchase",
                         points=points)
            DB.session.add(espy)
    DB.session.commit()

    # add some games between the teams
    # need a bunch of games
    today = datetime.date.today()
    games = []
    for day in range(-3, 3):
        date_string = (today +
                       datetime.timedelta(days=day)).strftime("%Y-%m-%d")
        status = "Completed" if day < 0 else "To Be Played"
        games.append(
            Game(date_string,
                 "10:00",
                 teams[0].id,
                 teams[1].id,
                 league.id,
                 status=status,
                 field="WP1"))
        games.append(
            Game(date_string,
                 "10:00",
                 teams[2].id,
                 teams[3].id,
                 league.id,
                 status=status,
                 field="WP2"))
        games.append(
            Game(date_string,
                 "11:00",
                 teams[0].id,
                 teams[2].id,
                 league.id,
                 status=status,
                 field="WP1"))
        games.append(
            Game(date_string,
                 "11:00",
                 teams[2].id,
                 teams[1].id,
                 league.id,
                 status=status,
                 field="WP2"))
        games.append(
            Game(date_string,
                 "12:00",
                 teams[0].id,
                 teams[3].id,
                 league.id,
                 status=status,
                 field="WP1"))
        games.append(
            Game(date_string,
                 "12:00",
                 teams[2].id,
                 teams[1].id,
                 league.id,
                 status=status,
                 field="WP2"))
    for game in tqdm(games, "Adding mock games"):
        DB.session.add(game)
    DB.session.commit()

    # now add a random score to the game
    for game in tqdm(games[:18], desc="Mocking scores for games"):
        add_random_score(game.id, game.away_team_id,
                         team_player_lookup[game.away_team_id])
        add_random_score(game.id, game.home_team_id,
                         team_player_lookup[game.home_team_id])
    DB.session.commit()
Esempio n. 9
0
 def import_headers(self):
     """Parse the headers of the csv and add team"""
     done = False
     i = 0
     sponsor = None
     color = None
     captain = None
     league = None
     while not done:
         # read the headers
         line = self.lines[i]
         columns = line.split(",")
         if self.clean_cell(columns[0]) == "sponsor":
             sponsor = columns[1].strip()
         elif self.clean_cell(columns[0]) == "color":
             color = columns[1].strip()
         elif self.clean_cell(columns[0]) == "captain":
             captain = columns[1].strip()
         elif self.clean_cell(columns[0]) == "league":
             league = columns[1].strip()
         else:
             # assuming done reading the headers
             done = True
         i += 1
     player_index = i
     if sponsor is None:
         raise InvalidField(payload={"details": "No sponsor was given"})
     if captain is None:
         raise InvalidField(payload={"details": "No captain was given"})
     if color is None:
         raise InvalidField(payload={"details": "No color was given"})
     if league is None:
         raise InvalidField(payload={"details": "No league was given"})
     # check no examples were left and actually real info
     if (league.lower().startswith("ex.")
             or sponsor.lower().startswith("ex.")
             or color.lower().startswith("ex.")
             or captain.lower().startswith("ex.")):
         t = "The header's still had an example"
         raise InvalidField(payload={"details": t})
     sponsor_id = (DB.session.query(Sponsor).filter(
         Sponsor.name == sponsor).first())
     if sponsor_id is None:
         sponsor_id = (DB.session.query(Sponsor).filter(
             Sponsor.nickname == sponsor).first())
     if sponsor_id is None:
         # what kind of sponsor are you giving
         t = "The sponsor does not exist (check case)"
         raise SponsorDoesNotExist(payload={'details': t})
     sponsor_id = sponsor_id.id
     league_id = (DB.session.query(League).filter(
         League.name == league)).first()
     if league_id is None:
         t = "The league does not exist (check case)"
         raise LeagueDoesNotExist(payload={"details": t})
     league_id = league_id.id
     # check to see if team was already created
     teams = (DB.session.query(Team).filter(Team.color == color).filter(
         Team.sponsor_id == sponsor_id).filter(
             Team.year == date.today().year).all())
     team_found = None
     if len(teams) > 0:
         team_found = teams[0]
     # was the team not found then should create it
     if team_found is None:
         self.warnings.append("Team was created")
         team_found = Team(color=color,
                           sponsor_id=sponsor_id,
                           league_id=league_id)
     else:
         team_found.players = []  # remove all the players before
     self.team = team_found  # set the team
     self.captain_name = captain  # remember captains name
     return player_index
Esempio n. 10
0
    def testTeamUpdate(self):
        league_id = self.add_league("TestModelLeague")['league_id']
        sponsor_id = self.add_sponsor("TestModelSponsor")['sponsor_id']

        # good Teams
        team = Team(color="Black", sponsor_id=sponsor_id, league_id=league_id)
        team.update(color="Green",
                    sponsor_id=sponsor_id,
                    league_id=league_id,
                    year=VALID_YEAR)

        # now for bad teams
        try:
            team.update(color="Black",
                        sponsor_id=INVALID_ID,
                        league_id=league_id)
            self.assertEqual(False, True, "Should raise no sponsor")
        except SponsorDoesNotExist:
            pass
        try:
            team.update(color="Black",
                        sponsor_id=sponsor_id,
                        league_id=INVALID_ID)
            self.assertEqual(False, True, "Should raise no league")
        except LeagueDoesNotExist:
            pass
        try:
            team.update(color=1, sponsor_id=sponsor_id, league_id=league_id)
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass
        try:
            team.update(color="Black",
                        sponsor_id=sponsor_id,
                        league_id=league_id,
                        year=1)
            self.assertEqual(False, True, "Should raise invalid field")
        except InvalidField:
            pass