Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update tests so that they don't rely on specific credentials #23

Merged
merged 33 commits into from
Feb 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
dceefb2
Check that user_id is a positive number
espoem Feb 15, 2019
3f5fcf4
Change team_ids default type
espoem Feb 15, 2019
da54fd9
Add check on team id
espoem Feb 15, 2019
6d73b4c
Add assertion on non negative player id for player summary
espoem Feb 15, 2019
908e291
Change signature of get_player_summaries
espoem Feb 15, 2019
2149764
Check if a player is found in fpl.get_player
espoem Feb 15, 2019
caa13c3
Change player_ids default to None in get_players
espoem Feb 15, 2019
8df8146
Add checks on unknown fixture ids in get_fixture
espoem Feb 15, 2019
30861e7
Return empty list on empty fixture ids in get_fixtures_by_id
espoem Feb 15, 2019
55f0179
Check email password is set
espoem Feb 15, 2019
a78281d
Update test_fpl
espoem Feb 15, 2019
7b2fff8
Exctract AsyncMock to helper module
espoem Feb 15, 2019
2b7ea75
Update test_classic_league
espoem Feb 15, 2019
316c5ee
Add safe attribute calls to Fixture
espoem Feb 16, 2019
d29623d
Update Fixture tests
espoem Feb 16, 2019
ebc2c5c
Add check on gameweek with id not found
espoem Feb 16, 2019
e289c0f
Add safe attr calls to player
espoem Feb 16, 2019
813f918
Add helper func to check logged in user
espoem Feb 16, 2019
b83e37d
Check login in get_fixtures
espoem Feb 16, 2019
c5b2f09
Update h2h_league tests
espoem Feb 16, 2019
4fc8319
Move fixture test data to test_fixture
espoem Feb 16, 2019
f958c98
Update valid_gameweek
espoem Feb 17, 2019
3dbe312
Fix user.get_season_history
espoem Feb 17, 2019
cfec4b0
Return flattened list of picks in user.get_picks
espoem Feb 17, 2019
85f138c
Update test_user
espoem Feb 17, 2019
7c42987
Return flattened list in get_automatic_substitutions
espoem Feb 17, 2019
e335bf9
Fix check on authenticated user session in User class
espoem Feb 17, 2019
850e553
Add more tests to test_user
espoem Feb 17, 2019
1e70f9d
Fix get_transfers caching logic
espoem Feb 17, 2019
2c97eda
Add tests to test_user
espoem Feb 17, 2019
6a71b98
Update valid_gameweek docstring
espoem Feb 17, 2019
189f65a
Update assertion on fpl.get_team team_id
espoem Feb 17, 2019
7466a9f
Move fixtures def to conftest.py
espoem Feb 18, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 43 additions & 17 deletions fpl/fpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,15 @@ async def get_user(self, user_id, return_json=False):
:type return_json: bool
:rtype: :class:`User` or `dict`
"""
assert int(user_id) > 0, "User ID must be a positive number."
url = API_URLS["user"].format(user_id)
user = await fetch(self.session, url)

if return_json:
return user
return User(user, session=self.session)

async def get_teams(self, team_ids=[], return_json=False):
async def get_teams(self, team_ids=None, return_json=False):
"""Returns either a list of *all* teams, or a list of teams with IDs in
the optional ``team_ids`` list.

Expand All @@ -85,6 +86,7 @@ async def get_teams(self, team_ids=[], return_json=False):
teams = await fetch(self.session, url)

if team_ids:
team_ids = set(team_ids)
teams = [team for team in teams if team["id"] in team_ids]

if return_json:
Expand Down Expand Up @@ -131,6 +133,7 @@ async def get_team(self, team_id, return_json=False):
19 - West Ham
20 - Wolves
"""
assert 0 < int(team_id) < 21, "Team ID must be a number between 1 and 20."
url = API_URLS["teams"]
teams = await fetch(self.session, url)
team = next(team for team in teams if team["id"] == int(team_id))
Expand All @@ -153,6 +156,7 @@ async def get_player_summary(self, player_id, return_json=False):
:type return_json: bool
:rtype: :class:`PlayerSummary` or ``dict``
"""
assert int(player_id) > 0, "Player's ID must be a positive number"
url = API_URLS["player"].format(player_id)
player_summary = await fetch(self.session, url)

Expand All @@ -161,20 +165,23 @@ async def get_player_summary(self, player_id, return_json=False):

return PlayerSummary(player_summary)

async def get_player_summaries(self, player_ids=[], return_json=False):
"""Returns either a list of summaries of *all* players, or a list of
summaries of players whose ID are in the ``player_ids`` list.
async def get_player_summaries(self, player_ids, return_json=False):
"""Returns a list of summaries of players whose ID are
in the ``player_ids`` list.

Information is taken from e.g.:
https://fantasy.premierleague.com/drf/element-summary/1

:param list player_ids: (optional) A list of player IDs.
:param list player_ids: A list of player IDs.
:param return_json: (optional) Boolean. If ``True`` returns a list of
``dict``s, if ``False`` returns a list of :class:`PlayerSummary`
objects. Defaults to ``False``.
:type return_json: bool
:rtype: list
"""
if not player_ids:
return []

tasks = [asyncio.ensure_future(
fetch(self.session, API_URLS["player"].format(player_id)))
for player_id in player_ids]
Expand Down Expand Up @@ -204,12 +211,16 @@ async def get_player(self, player_id, players=None, include_summary=False,
if ``False`` returns a :class:`Player` object. Defaults to
``False``.
:rtype: :class:`Player` or ``dict``
:raises ValueError: Player with ``player_id`` not found
"""
if not players:
players = await fetch(self.session, API_URLS["players"])

player = next(player for player in players
if player["id"] == player_id)
try:
player = next(player for player in players
if player["id"] == player_id)
except StopIteration:
raise ValueError(f"Player with ID {player_id} not found")

if include_summary:
player_summary = await self.get_player_summary(
Expand All @@ -221,7 +232,7 @@ async def get_player(self, player_id, players=None, include_summary=False,

return Player(player)

async def get_players(self, player_ids=[], include_summary=False,
async def get_players(self, player_ids=None, include_summary=False,
return_json=False):
"""Returns either a list of *all* players, or a list of players whose
IDs are in the given ``player_ids`` list.
Expand Down Expand Up @@ -264,19 +275,26 @@ async def get_fixture(self, fixture_id, return_json=False):
``False``.
:type return_json: bool
:rtype: :class:`Fixture` or ``dict``
:raises ValueError: if fixture with ``fixture_id`` not found
"""
fixtures = await fetch(self.session, API_URLS["fixtures"])

fixture = next(fixture for fixture in fixtures
if fixture["id"] == fixture_id)
try:
fixture = next(fixture for fixture in fixtures
if fixture["id"] == fixture_id)
except StopIteration:
raise ValueError(f"Fixture with ID {fixture_id} not found")
fixture_gameweek = fixture["event"]

gameweek_fixtures = await fetch(
self.session,
API_URLS["gameweek_fixtures"].format(fixture_gameweek))

fixture = next(fixture for fixture in gameweek_fixtures
if fixture["id"] == fixture_id)
try:
fixture = next(fixture for fixture in gameweek_fixtures
if fixture["id"] == fixture_id)
except StopIteration:
raise ValueError(f"Fixture with ID {fixture_id} not found in gameweek fixtures")

if return_json:
return fixture
Expand All @@ -298,6 +316,9 @@ async def get_fixtures_by_id(self, fixture_ids, return_json=False):
:type return_json: bool
:rtype: list
"""
if not fixture_ids:
return []

fixtures = await fetch(self.session, API_URLS["fixtures"])
fixture_gameweeks = set(fixture["event"] for fixture in fixtures
if fixture["id"] in fixture_ids)
Expand Down Expand Up @@ -386,8 +407,11 @@ async def get_gameweek(self, gameweek_id, include_live=False,
"""

static_gameweeks = await fetch(self.session, API_URLS["gameweeks"])
static_gameweek = next(gameweek for gameweek in static_gameweeks if
gameweek["id"] == gameweek_id)
try:
static_gameweek = next(gameweek for gameweek in static_gameweeks if
gameweek["id"] == gameweek_id)
except StopIteration:
raise ValueError(f"Gameweek with ID {gameweek_id} not found")
live_gameweek = await fetch(
self.session, API_URLS["gameweek_live"].format(gameweek_id))

Expand Down Expand Up @@ -483,14 +507,16 @@ async def get_h2h_league(self, league_id, return_json=False):
async def login(self, email=None, password=None):
"""Returns a requests session with FPL login authentication.

:param string user: Email address for the user's Fantasy Premier League
:param string email: Email address for the user's Fantasy Premier League
account.
:param string password: Password for the user's Fantasy Premier League
account.
"""
if not email and not password:
email = os.environ["FPL_EMAIL"]
password = os.environ["FPL_PASSWORD"]
email = os.getenv("FPL_EMAIL", None)
password = os.getenv("FPL_PASSWORD", None)
if not email or not password:
raise ValueError("Email and password must be set")

url = "https://fantasy.premierleague.com/"
await self.session.get(url)
Expand Down
47 changes: 24 additions & 23 deletions fpl/models/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,20 @@ def _get_players(self, metric):
"""Helper function that returns a dictionary containing players for the
given metric (away and home).
"""
for statistic in self.stats:
stats = getattr(self, "stats", [])
for statistic in stats:
if metric in statistic.keys():
player_information = statistic[metric]
return statistic[metric]

return player_information
return {}

def get_goalscorers(self):
"""Returns all players who scored in the fixture.

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("goals_scored")

Expand All @@ -56,8 +57,8 @@ def get_assisters(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("assists")

Expand All @@ -66,8 +67,8 @@ def get_own_goalscorers(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("own_goals")

Expand All @@ -76,8 +77,8 @@ def get_yellow_cards(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("yellow_cards")

Expand All @@ -86,8 +87,8 @@ def get_red_cards(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("red_cards")

Expand All @@ -96,8 +97,8 @@ def get_penalty_saves(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("penalties_saved")

Expand All @@ -106,8 +107,8 @@ def get_penalty_misses(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("penalties_missed")

Expand All @@ -116,8 +117,8 @@ def get_saves(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("saves")

Expand All @@ -126,8 +127,8 @@ def get_bonus(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("bonus")

Expand All @@ -136,8 +137,8 @@ def get_bps(self):

:rtype: dict
"""
if not self.finished:
return
if not getattr(self, "finished", False):
return {}

return self._get_players("bps")

Expand Down
7 changes: 5 additions & 2 deletions fpl/models/h2h_league.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio

from ..constants import API_URLS
from ..utils import fetch, get_current_gameweek
from ..utils import fetch, get_current_gameweek, logged_in


class H2HLeague():
Expand All @@ -23,7 +23,7 @@ class H2HLeague():
>>> asyncio.run(main())
League 760869 - 760869
"""
def __init__(self, league_information, session=None):
def __init__(self, league_information, session):
self._session = session

for k, v in league_information.items():
Expand All @@ -42,6 +42,9 @@ async def get_fixtures(self, gameweek=None):
if not self._session:
return

if not logged_in(self._session):
raise Exception("Not authorized to get h2h fixtures. Log in.")

if gameweek:
gameweeks = range(gameweek, gameweek + 1)
else:
Expand Down
7 changes: 4 additions & 3 deletions fpl/models/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,18 @@ def games_played(self):

:rtype: int
"""
return sum([1 for fixture in self.fixtures if fixture["minutes"] > 0])
return sum([1 for fixture in getattr(self, "fixtures", []) if fixture["minutes"] > 0])

@property
def pp90(self):
"""Points per 90 minutes.

:rtype: float
"""
if self.minutes == 0:
minutes = getattr(self, "minutes", 0)
if minutes == 0:
return 0
return self.total_points / float(self.minutes)
return getattr(self, "total_points", 0) / float(minutes)

def __str__(self):
return (f"{self.web_name} - "
Expand Down
Loading