def test_get_users(): """ Tests the get_users method""" league = League(355526480094113792) users = league.get_users() assert isinstance(users, list) assert isinstance(users[0]["user_id"], str)
def test_get_trades(): """ Tests the get_trades method. Note: It would be better if we had trades to verify!""" league = League(355526480094113792) trades = league.get_trades(4) assert isinstance(trades, list) assert len(trades) == 0
def test_get_league(capsys): """ Tests the get_league method""" league = League(355526480094113792) league_info = league.get_league() assert isinstance(league_info, dict) assert league_info["league_id"] == "355526480094113792"
def test_get_rosters(): """ Tests the get_rosters method""" league = League(355526480094113792) rosters = league.get_rosters() assert isinstance(rosters, list) assert len(rosters) > 5
def get_standings_string(league_id): """ Creates and returns a message of the league's standings. :param league_id: Int league_id :return: string message of the leagues standings. """ league = League(league_id) rosters = league.get_rosters() users = league.get_users() standings = league.get_standings(rosters, users) final_message_string = "________________________________\n" final_message_string += "Standings \n|{0:^7}|{1:^7}|{2:^7}|{3:^7}\n".format( "rank", "team", "wins", "points") final_message_string += "________________________________\n\n" try: playoff_line = os.environ["NUMBER_OF_PLAYOFF_TEAMS"] - 1 except: playoff_line = 5 for i, standing in enumerate(standings): team = standing[0] if team is None: team = "Team NA" if len(team) >= 7: team_name = team[:7] else: team_name = team string_to_add = "{0:^7} {1:^10} {2:>7} {3:>7}\n".format( i + 1, team_name, standing[1], standing[2]) if i == playoff_line: string_to_add += "________________________________\n\n" final_message_string += string_to_add return final_message_string
def test_get_all_drafts(): league = League(355526480094113792) drafts = league.get_all_drafts() first_item = drafts[0] assert isinstance(drafts, list) assert isinstance(first_item, dict)
def test_get_free_agents(): """Tests the get_free_agents method. Note: It would be better if we had free agents to verify!""" league = League(355526480094113792) free_agents = league.get_free_agents(4) assert isinstance(free_agents, list) assert len(free_agents) == 0
def test_get_waivers(): """Tests the get_waivers method. Note: It would be better if we had waivers to verify!""" league = League(355526480094113792) waivers = league.get_waivers(4) assert isinstance(waivers, list) assert len(waivers) == 0
def test_get_playoff_losers_bracket(): """ Tests the get_playoff_losers method""" league = League(355526480094113792) bracket = league.get_playoff_losers_bracket() first_item = bracket[0] assert isinstance(bracket, list) assert isinstance(first_item, dict)
def test_get_traded_picks(): """ Tests the get_traded_picks method""" league = League(355526480094113792) traded_picks = league.get_traded_picks() first_item = traded_picks[0] assert isinstance(traded_picks, list) assert isinstance(first_item, dict)
def get_playoff_bracket_string(league_id): """ Creates and returns a message of the league's playoff bracket. :param league_id: Int league_id :return: string message league's playoff bracket """ league = League(league_id) bracket = league.get_playoff_winners_bracket() return bracket
def main(argv): # Parse all of the user-provided flags args = parse_user_provided_flags() # Convert the computed args into our more-verbose local fields account_username = args.username league_year = args.year position = args.position team = args.team output_format = args.output_format league_regex = re.compile(args.league_regex) # Retrieve the user and all of their leagues admin_user = User(account_username) all_leagues = admin_user.get_all_leagues("nfl", league_year) # Map to store the drafted player results player_id_to_drafted_player = {} for league_object in all_leagues: league = League(league_object.get("league_id")) league_name = league.get_league().get("name") # Only look at leagues that match the provided regex if league_regex.match(league_name): draft_id = league.get_league().get("draft_id") draft = Drafts(draft_id) for pick in draft.get_all_picks(): player_id = pick["player_id"] if player_id in player_id_to_drafted_player.keys(): drafted_player = player_id_to_drafted_player.get(player_id) else: drafted_player = DraftedPlayer( pick["player_id"], pick["metadata"]["first_name"], pick["metadata"]["last_name"], pick["metadata"]["position"], pick["metadata"]["team"]) player_id_to_drafted_player[player_id] = drafted_player drafted_player.add_draft_position(pick["pick_no"]) # Print the results of all the parsing print("") for player_id in sorted(player_id_to_drafted_player, key=player_id_to_drafted_player.get): drafted_player = player_id_to_drafted_player[player_id] if position != INCLUDE_ALL and drafted_player.position != position: continue if team != INCLUDE_ALL and drafted_player.team != team: continue print(create_output_for_player(drafted_player, output_format))
def test_get_transactions(): """ Tests the get_transactions method Note: Not really sure wether this method works or what its supposed to do yet because the season has not fully started. """ league = League(355526480094113792) transactions = league.get_transactions(4) assert isinstance(transactions, list) transactions = league.get_transactions("4") assert isinstance(transactions, list)
def resolve_matchups(parent, info, leagueId, week): league = League(leagueId) leagueMatchups = league.get_matchups(week) match_list = [] for i in leagueMatchups: matches = Matchup.from_json(i) match_list.append(matches) return match_list
def test_get_standings(capsys): """ Tests the get_standings method""" league = League(355526480094113792) rosters = league.get_rosters() users = league.get_users() standings = league.get_standings(rosters, users) first_item = standings[0] assert isinstance(first_item, tuple) assert len(standings) == 12
def resolve_rosters(parent, info, leagueId): league = League(leagueId) leagueRosters = league.get_rosters() roster_list = [] for i in leagueRosters: rosters = Roster.from_json(i) roster_list.append(rosters) return roster_list
def test_get_matchups(capsys): """ Tests the get_matchups method""" league = League(355526480094113792) matchup_info = league.get_matchups(4) first_item = matchup_info[0] assert isinstance(matchup_info, list) assert isinstance(first_item, dict) matchup_info = league.get_matchups(20) assert len(matchup_info) == 0
def map_roster_id_to_owner_id(league_id): """ :return: Dict {roster_id: owner_id, ...} """ league = League(league_id) rosters = league.get_rosters() result_dict = {} for roster in rosters: roster_id = roster["roster_id"] owner_id = roster["owner_id"] result_dict[roster_id] = owner_id return result_dict
def generate_data_sheets(league_id=516427156663472128): league = League(league_id) rosters = league.get_rosters() users = league.get_users() user_map = {user["user_id"]: user["display_name"] for user in users} running_scores_by_owner = {} weekly_scores_by_weekandowner = defaultdict(dict) for week in range(1, 18): scores_by_owner = get_scores_by_owner(league, rosters, week) calculate_team_totals( week, scores_by_owner, weekly_scores_by_weekandowner, running_scores_by_owner, ) for week, scores_by_owner in weekly_scores_by_weekandowner.items(): with open(f"data/week{week}.csv", "w") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow([ "owner", "score", "for", "against", "total score", "total for", "total against", ]) for owner_id, row in scores_by_owner.items(): csvwriter.writerow([user_map[owner_id]] + [i for i in row]) with open("data/total.csv", "w") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow([ "owner", "total score", "total for", "total against", ]) rows = [(owner_id, row) for owner_id, row in running_scores_by_owner.items()] rows.sort(key=lambda row: (row[1][4], row[1][3]), reverse=True) for owner_id, row in rows: csvwriter.writerow([user_map[owner_id]] + [i for i in row[3:]]) print("Done")
def get_negative_starters(league_id): """ Finds all of the players that scores negative points in standard and :param league_id: Int league_id :return: Dict {"owner_name":[("player_name", std_score), ...], "owner_name":...} """ week = get_current_week() league = League(league_id) users = league.get_users() matchups = league.get_matchups(week) stats = Stats() # WEEK STATS NEED TO BE FIXED week_stats = stats.get_week_stats("regular", STARTING_YEAR, week) players = Players() players_dict = players.get_all_players() owner_id_to_team_dict = map_users_to_team_name(users) roster_id_to_owner_id_dict = map_roster_id_to_owner_id(league_id) result_dict = {} for i, matchup in enumerate(matchups): starters = matchup["starters"] negative_players = [] for starter_id in starters: try: std_pts = week_stats[str(starter_id)]["pts_std"] except KeyError: std_pts = 0 if std_pts < 0: player_info = players_dict[starter_id] player_name = "{} {}".format(player_info["first_name"], player_info["last_name"]) negative_players.append((player_name, std_pts)) if len(negative_players) > 0: owner_id = roster_id_to_owner_id_dict[matchup["roster_id"]] if owner_id is None: team_name = "Team name not available" + str(i) else: team_name = owner_id_to_team_dict[owner_id] result_dict[team_name] = negative_players return result_dict
def get_weekly_scores_for_league_and_week( league: League, week: int, user_store: UserStore) -> List[WeeklyScore]: """Retrieves all of the weekly scores for the league in a given week This parses through all of the league matchups, transforming the API matchup and roster objects into a WeeklyScore report that can be parsed later on Parameters ---------- league : League The League object being analyzed week : int The week for which to pull matchups user_store : UserStore Storage object used to retrieve the username for a specific team Returns ------- List[WeeklyScore] A list of the individual weekly scores """ rosters = league.get_rosters() # Short circuit to avoid problems if the league is empty if is_league_inactive(rosters): return [] roster_id_to_username = {} weekly_scores = [] # Create a mapping of the roster id to the username for roster in rosters: roster_id_to_username[roster.get( "roster_id")] = user_store.get_username(roster.get("owner_id")) # Each "matchup" represents a single teams performance weekly_matchups = league.get_matchups(week) for matchup in weekly_matchups: weekly_scores.append( WeeklyScore(roster_id_to_username[matchup.get("roster_id")], league.get_league().get("name"), week, matchup.get("points"))) return weekly_scores
def get_scores_by_owner(league: League, rosters, week): matchups = league.get_matchups(week) roster_id_dict = league.map_rosterid_to_ownerid(rosters) scores = {} total_score = 0 for team in matchups: current_roster_id = team["roster_id"] owner_id = roster_id_dict[current_roster_id] score = team["points"] if score: total_score += score scores[owner_id] = score if total_score == 0: return None else: return scores
def get_bench_beats_starters_string(league_id): """ Gets all bench players that outscored starters at their position. :param league_id: Int league_id :return: String teams which had bench players outscore their starters in a position. """ week = get_current_week() league = League(league_id) matchups = league.get_matchups(week) final_message_string = "________________________________\n" final_message_string += "Worst of the week💩💩\n" final_message_string += "________________________________\n\n" for matchup in matchups: starters = matchup["starters"] all_players = matchup["players"] bench = set(all_players) - set(starters)
def main(argv): args = parse_user_provided_flags() user = args.username year = args.year league_regex = re.compile(args.league_regex) week = args.week include_covid = args.include_covid include_missing = args.include_missing # Retrieve the list of all inactive players nfl_players = Players() inactive_players = find_all_inactive_players_for_week( nfl_players.get_all_players(), week, include_covid) if include_missing: # Empty starting slots fill in as id 0, so add an entry for that # 0th player in order to report the empty spot inactive_players.append( Player("Missing Player", "0", "None", "MISSING", "NONE")) # Retrieve all of the leagues admin_user = User(user) all_leagues = admin_user.get_all_leagues("nfl", year) user_store = UserStore() inactive_rosters = [] # Iterate through each league to find the inactive owners in each for league_object in all_leagues: league = League(league_object.get("league_id")) league_name = league.get_league().get("name") # Only look at leagues that match the provided regex if league_regex.match(league_name): user_store.store_users_for_league(league) inactive_rosters.extend( find_inactive_starters_for_league_and_week( league, week, inactive_players, user_store)) # Print out the final inactive rosters print("") for roster in inactive_rosters: print(roster)
def get_pf_for_entire_league(league: League, user_store: UserStore) -> List[SeasonScore]: """Retrieves all of the season scores for the league This parses through all of the league rosters, trasnforming what's available on the roster object into a SeasonScore object for each team Parameters ---------- league : League The League object being analyzed user_store : UserStore Storage object used to retrieve the username for a specific team Returns ------- List[SeasonScore] A list of the Season-long scores for each team in the league """ rosters = league.get_rosters() # Short circuit to avoid problems if the league is empty if is_league_inactive(rosters): return [] season_scores = [] for roster in rosters: total_points_for = float(roster.get("settings").get("fpts")) try: total_points_for += float( roster.get("settings").get("fpts_decimal")) / 100 except Exception: # Decimal field may not be pressent, skip total_points_for += 0.00 season_scores.append( SeasonScore(user_store.get_username(roster.get("owner_id")), league.get_league().get("name"), total_points_for)) return season_scores
def get_close_games_string(league_id, close_num): """ Creates and returns a message of the league's close games. :param league_id: Int league_id :param close_num: Int what poInt difference is considered a close game. :return: string message of the current week's close games. """ league = League(league_id) week = get_current_week() scoreboards = get_league_scoreboards(league_id, week) close_games = league.get_close_games(scoreboards, close_num) final_message_string = "___________________\n" final_message_string += "Close games😰😰\n" final_message_string += "___________________\n\n" for i, matchup_id in enumerate(close_games): matchup = close_games[matchup_id] string_to_add = "Matchup {}\n{:<8} {:<8.2f}\n{:<8} {:<8.2f}\n\n".format( i + 1, matchup[0][0], matchup[0][1], matchup[1][0], matchup[1][1]) final_message_string += string_to_add return final_message_string
def get_bench_points(league_id): """ :param league_id: Int league_id :return: List [(team_name, score), ...] """ week = get_current_week() league = League(league_id) users = league.get_users() matchups = league.get_matchups(week) stats = Stats() # WEEK STATS NEED TO BE FIXED week_stats = stats.get_week_stats("regular", STARTING_YEAR, week) owner_id_to_team_dict = map_users_to_team_name(users) roster_id_to_owner_id_dict = map_roster_id_to_owner_id(league_id) result_list = [] for matchup in matchups: starters = matchup["starters"] all_players = matchup["players"] bench = set(all_players) - set(starters) std_points = 0 for player in bench: try: std_points += week_stats[str(player)]["pts_std"] except: continue owner_id = roster_id_to_owner_id_dict[matchup["roster_id"]] if owner_id is None: team_name = "Team name not available" else: team_name = owner_id_to_team_dict[owner_id] result_list.append((team_name, std_points)) return result_list
def test_get_close_games(capsys): """ Tests the get_close_games method -Notes: Need to test more. """ league = League(442724598706860032) matchups = league.get_matchups(1) users = league.get_users() rosters = league.get_rosters() scoreboards = league.get_scoreboards(rosters, matchups, users, "pts_half_ppr", 1) close_games = league.get_close_games(scoreboards, 10) assert isinstance(close_games, dict)
def test_get_close_games(capsys): """ Tests the get_close_games method -Notes: Need to test more. """ league = League(355526480094113792) matchups = league.get_matchups(11) users = league.get_users() rosters = league.get_rosters() scoreboards = league.get_scoreboards(rosters, matchups, users) close_games = league.get_close_games(scoreboards, 10) assert isinstance(close_games, dict)
def test_get_scoreboards(capsys): """Tests the get_scoreoards method -Needs more testing after the season starts""" league = League(355526480094113792) matchups = league.get_matchups(11) users = league.get_users() rosters = league.get_rosters() scoreboards = league.get_scoreboards(rosters, matchups, users) assert isinstance(scoreboards, dict)