def test_free_agents_fails(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) with self.assertRaises(Exception): league.free_agents()
def test_top_scorer(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) team = league.top_scorer() self.assertEqual(team.team_id, 1)
def test_recent_activity(self, m): self.mock_setUp(m) league = League(self.league_id, 2018) # TODO hack until I get all mock data for 2019 league.year = 2019 self.espn_endpoint = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/" + str( 2019) + "/segments/0/leagues/" + str(self.league_id) league.espn_request.LEAGUE_ENDPOINT = self.espn_endpoint with open('tests/football/unit/data/league_recent_activity_2019.json' ) as f: data = json.loads(f.read()) m.get(self.espn_endpoint + '/communication/?view=kona_league_communication', status_code=200, json=data) m.get(self.espn_endpoint + '?view=kona_playercard', status_code=200, json=self.player_card_data) activity = league.recent_activity() self.assertEqual(repr(activity[0].actions[0][0]), 'Team(Perscription Mixon)') self.assertEqual(len(repr(activity)), 2765)
def test_box_score_fails(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) with self.assertRaises(Exception): league.box_scores(1)
def test_most_pa(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) team = league.most_points_against() self.assertEqual(team.team_id, 2)
def test_least_scored(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) team = league.least_scored_week() self.assertEqual(team[0].team_id, 10)
def initialize_bot(): """Initialize a chatbot using the required Environmental Variables Return each bot (slack, discord, groupme) and the Leauge object """ bot_id = os.getenv("BOT_ID", 1) slack_webhook_url = os.getenv("SLACK_WEBHOOK_URL", 1) discord_webhook_url = os.getenv("DISCORD_WEBHOOK_URL", 1) league_id = int(os.getenv("LEAGUE_ID", "1")) year = int(os.getenv("LEAGUE_YEAR", 2021)) swid = os.getenv("SWID", "{1}") if swid.find("{", 0) == -1: swid = "{" + swid if swid.find("}", -1) == -1: swid = swid + "}" espn_s2 = os.getenv("ESPN_S2", "1") bot = GroupMeBot(bot_id) slack_bot = SlackBot(slack_webhook_url) discord_bot = DiscordBot(discord_webhook_url) if swid == '{1}' and espn_s2 == '1': league = League(league_id, year) else: league = League(league_id, year, espn_s2, swid) return { "gm_bot": bot, "slack_bot": slack_bot, "discord_bot": discord_bot, "league": league }
def test_league_standings(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) standings = league.standings() self.assertEqual(standings[0].final_standing, 1)
def get_season(self, key_map=None): """ Request a season from ESPN :param key_map: A dictionary representing the values to be parsed from the API response :return: A DataFrame representing the season """ self.response = League( league_id=self.league_id, year=self.year, espn_s2=self.s2, swid=self.swid, ) response = vars(self.response) response["settings"] = vars(response["settings"]) self.start_week = response.get("firstScoringPeriod", 1) self.regular_season_weeks = response["settings"].get( "reg_season_count" ) self.team_objs = [vars(team) for team in response["teams"]] self.draft_picks = [vars(pick) for pick in response["draft"]] self.player_map = response["player_map"] if key_map: response = format_response(response, key_map) self.season = pd.DataFrame([response]) self.season["season_id"] = self.season_id self.season["league_name"] = self.league_name return self.season
def test_box_scores(self): league = League(48153503, 2019) box_scores = league.box_scores(week=2) self.assertEqual(repr(box_scores[1].away_team), 'Team(TEAM BERRY)') self.assertEqual(repr(box_scores[1].away_lineup[1]), 'Player(Odell Beckham Jr., points:29, projected:16)') self.assertEqual(repr(box_scores[1]), 'Box Score(Team(TEAM BERRY) at Team(TEAM HOLLAND))')
def set_league_endpoint(league: League): if ( league.year >= pd.datetime.today().year ): #(dt.datetime.now() - dt.timedelta(540)).year): # ESPN API v3 league.endpoint = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/" + \ str(league.year) + "/segments/0/leagues/" + str(league.league_id) + "?" else: # ESPN API v2 league.endpoint = "https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/" + \ str(league.league_id) + "?seasonId=" + str(league.year)
def test_get_team(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) team = league.get_team_data(8) self.assertEqual(team.team_id, 8) team = league.get_team_data(18) self.assertEqual(team, None)
def __init__(self, year, league_id, espn_s2, swid): self.league = League(league_id=league_id, year=year, espn_s2=espn_s2, swid=swid) self.teams = self.league.teams self.week = self.league.current_week self.week_list = list(range(1, self.week)) self.box_score_list = [] self.box_score_objs = [] self.box_scores_player_list = []
def test_free_agents(self, m, mock_boxplayer, mock_nfl_schedule, mock_pos_ratings): self.mock_setUp(m) mock_boxplayer.return_value = None league = League(self.league_id, self.season) m.get(self.espn_endpoint + '?view=kona_player_info&scoringPeriodId=16', status_code=200, json={'players': [1, 2]}) league.year = 2019 free_agents = league.free_agents(position='QB', position_id=0) self.assertEqual(len(free_agents), 2)
def __init__(self, year=2021): league_id = "832593" year = year swid = "{ADB2C88A-0CCD-4491-B8B7-4657E6A412FD}" espn_s2 = ( "AECvR2KuFAHIFNvXPmowC7LgFu4G2jj6tzWOaOd8xnX2wu3BaSy3Dogb5KU0KAiHu3xcqKzkMa%2FwbLIIzA4DMqtr%2FZF48Xs" "PMFyOGScz3xl0qO3ekELFD7qgY0qYdGbg%2BwbX0NntqxWwPaLPdrEaIc1vlXxehme7cbLRq6Uf5iP3f%2FpQvG51KexkEMJy6H" "c1C1zZxZ41fQ4EddVA%2BhaqQ9%2BADWELwT9hFbPFjoBxco8T%2FvSxS0TJFEqLiBUBfp%2F2RbE%3D" ) self.league = League(league_id=league_id, year=year, espn_s2=espn_s2, swid=swid)
def test_player_info(self, m): self.mock_setUp(m) m.get(self.espn_endpoint + '?view=kona_playercard', status_code=200, json=self.player_card_data) league = League(self.league_id, self.season) # Invalid name player = league.player_info('Test 1') self.assertEqual(player, None) player = league.player_info('James Conner') self.assertEqual(player.name, 'James Conner') self.assertEqual(player.stats[1]['points'], 10.5)
def test_create_object(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) self.assertEqual(repr(league), 'League(123, 2018)') self.assertEqual(repr(league.settings), 'Settings(FXBG League)') self.assertEqual(league.current_week, 16) self.assertEqual(len(league.teams), 10) league.refresh() self.assertEqual(repr(league), 'League(123, 2018)') self.assertEqual(repr(league.settings), 'Settings(FXBG League)') self.assertEqual(league.current_week, 16) self.assertEqual(len(league.teams), 10)
def scrape_matchups(): """Scrape all matchup data from 2017 to 2020""" matchup_data = {} years = [2017, 2018, 2019, 2020] PRINT_STR = "{}: {}" for year in years: matchup_data[year] = {} league = League(league_id=345674, year=year, swid=SWID, espn_s2=ESPN_S2) for week in range(1, 15): matchup_data[year][week] = [] print(PRINT_STR.format(year, week)) for box_score in league.scoreboard(week): try: if box_score.home_score > box_score.away_score: matchup_data[year][week].append({ "winner": box_score.home_team.owner.rstrip(" "), "loser": box_score.away_team.owner.rstrip(" "), "winner_score": box_score.home_score, "loser_score": box_score.away_score, }) else: matchup_data[year][week].append({ "winner": box_score.away_team.owner.rstrip(" "), "loser": box_score.home_team.owner.rstrip(" "), "winner_score": box_score.away_score, "loser_score": box_score.home_score, }) except Exception as exc: print(year, week) print(exc) with open("history.json", mode="w") as f: json.dump(matchup_data, f, indent=4)
def test_cookie_set(self, mock_fetch_league): league = League(league_id=1234, year=2019, espn_s2='cookie1', swid='cookie2') self.assertEqual(league.espn_s2, 'cookie1') self.assertEqual(league.swid, 'cookie2')
def test_cookie_set(self, mock_fetch_league): league = League(league_id=1234, year=2019, espn_s2='cookie1', swid='cookie2') self.assertEqual(league.espn_request.cookies['espn_s2'], 'cookie1') self.assertEqual(league.espn_request.cookies['SWID'], 'cookie2')
def getPlayers(): db = sqlite3.connect('fantasyDb_' + LEAGUENAME + '.db') cursor = db.cursor() for currentYear in range(2016, 2021): #get league for current year league = League(league_id=currentLeague, year=currentYear, espn_s2=_espn_s2, swid=_swid) #code for current year for Team_Id in range(0, len(league.teams)): #get league with method arguments for player in range(0, len(league.teams[Team_Id].roster)): roster = league.teams[Team_Id].roster[player] cursor.execute( "INSERT INTO Players (Season, Player_Name, Player_Team_Id, Player_Position, Player_Points) VALUES (?,?,?,?,?)", ( currentYear, roster.name, league.teams[Team_Id].owner #Team_Id , roster.position, roster.stats[0]['points'])) db.commit() db.close()
def test_username_pass_set(self, mock_authentication, mock_fetch_league): league = League(league_id=1234, year=2019, username='******', password='******') self.assertEqual(league.username, 'user') self.assertEqual(league.password, 'pass')
def fetch_league(league_id: int, year: int, swid: str, espn_s2: str): print('[BUILDING LEAGUE] Fetching league data...') league = League(league_id=league_id, year=year, swid=swid, espn_s2=espn_s2) # Set cookies league.cookies = {'swid': swid, 'espn_s2': espn_s2} # Set league endpoint set_league_endpoint(league) # Get roster information get_roster_settings(league) # Load current league data print('[BUILDING LEAGUE] Loading current league details...') league.load_roster_week(league.current_week) return league
def test_player(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) team = league.teams[2] self.assertEqual(repr(team.roster[0]), 'Player(Drew Brees)') self.assertEqual(team.get_player_name(2521161), 'Zach Zenner') self.assertEqual(team.get_player_name(0), '')
def get_lineup(league: League, team: Team, week: int, box_scores=None): ''' Return the lineup of the given team during the given week ''' # Get the lineup for the team during the specified week if box_scores is None: box_scores = league.box_scores(week) for box_score in box_scores: if team == box_score.home_team: return box_score.home_lineup elif team == box_score.away_team: return box_score.away_lineup
def test_load_roster_week(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) with open('tests/football/unit/data/league_roster_week1.json') as f: data = json.loads(f.read()) m.get(self.espn_endpoint + '?view=mRoster&scoringPeriodId=1', status_code=200, json=data) league.load_roster_week(1) # check player that I know is on roster name = '' team = league.teams[1] for player in team.roster: if player.name == "Le'Veon Bell": name = player.name self.assertEqual(name, "Le'Veon Bell")
def test_get_scoreboard(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) with open('tests/unit/data/league_matchupScore_2015.json') as f: data = json.loads(f.read()) m.get(self.espn_endpoint + '&view=mMatchupScore', status_code=200, json=data) scoreboard = league.scoreboard(1) self.assertEqual(repr(scoreboard[1]), 'Matchup(Team(Go Deep Jack ), Team(Last Place))') self.assertEqual(scoreboard[0].home_score, 133) scoreboard = league.scoreboard() self.assertEqual(repr(scoreboard[-1]), 'Matchup(Team(Go Deep Jack ), Team(Last Place))') self.assertEqual(scoreboard[-1].away_score, 123)
def test_draft(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) first_pick = league.draft[0] third_pick = league.draft[2] self.assertEqual(repr(first_pick), 'Pick(Eddie Lacy, Team(Show Me Your TD\'s))') self.assertEqual(third_pick.round_num, 1) self.assertEqual(third_pick.round_pick, 3)
def test_authentication_api_fail(self, mock_request, mock_stdout, mock_fetch_league): url_api_key = 'https://registerdisney.go.com/jgc/v5/client/ESPN-FANTASYLM-PROD/api-key?langPref=en-US' mock_request.post(url_api_key, status_code=400) league = League(league_id=1234, year=2019, username='******', password='******') self.assertEqual( mock_stdout.getvalue(), 'Unable to access API-Key\nRetry the authentication or continuing without private league access\n' )
def test_draft(self, m): self.mock_setUp(m) league = League(self.league_id, self.season) first_pick = league.draft[0] third_pick = league.draft[2] self.assertEqual(repr(first_pick), 'Pick(Le\'Veon Bell, Team(Rollin\' With Mahomies))') self.assertEqual(third_pick.round_num, 1) self.assertEqual(third_pick.round_pick, 3) self.assertEqual(third_pick.auction_repr(), 'T M, 13934, Antonio Brown, 0, False')