Skip to content

Commit

Permalink
Merge pull request amosbastian#52 from amosbastian/johnmadden86-master
Browse files Browse the repository at this point in the history
Fix H2HLeague.get_fixtures()
  • Loading branch information
amosbastian authored Sep 22, 2019
2 parents 9cf75bb + 6a26752 commit cfe612e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 56 deletions.
3 changes: 1 addition & 2 deletions fpl/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
"gameweeks": "{}events/".format(API_BASE_URL),
"gameweek_fixtures": "{}fixtures/?event={{}}".format(API_BASE_URL),
"gameweek_live": "{}event/{{}}/live".format(API_BASE_URL),
"h2h": "{}leagues-entries-and-h2h-matches/league/{{}}?page={{}}".format(
API_BASE_URL),
"league_classic": "{}leagues-classic/{{}}/standings/".format(API_BASE_URL),
"league_h2h": "{}leagues-h2h/{{}}/standings/".format(API_BASE_URL),
"league_h2h_fixtures": "{}leagues-h2h-matches/league/{{}}/?{{}}page={{}}".format(API_BASE_URL),
"players": "{}elements/".format(API_BASE_URL),
"player": "{}element-summary/{{}}/".format(API_BASE_URL),
"settings": "{}game-settings/".format(API_BASE_URL),
Expand Down
31 changes: 17 additions & 14 deletions fpl/models/h2h_league.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,36 +30,39 @@ def __init__(self, league_information, session):
for k, v in league_information.items():
setattr(self, k, v)

async def get_fixtures(self, gameweek=None):
async def get_fixtures(self, gameweek=None, page=1):
"""Returns a list of fixtures / results of the H2H league.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/leagues-h2h-matches/league/946125/?page=1
:param gameweek: (optional) The gameweek of the fixtures / results.
:type gameweek: string or int
:param page: (optional) The fixtures / results page.
:type page: string or int
:rtype: list
"""
if not self._session:
return
return []

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

if gameweek:
gameweeks = range(gameweek, gameweek + 1)
else:
current_gameweek = await get_current_gameweek(self._session)
gameweeks = range(1, current_gameweek + 1)
url_query = f"event={gameweek}&" if gameweek else ""
has_next = True
results = []

tasks = [asyncio.ensure_future(
fetch(self._session,
API_URLS["h2h"].format(self.league["id"], page)))
for page in gameweeks]
while has_next:
fixtures = await fetch(
self._session, API_URLS["league_h2h_fixtures"].format(
self.league["id"], url_query, page))
results.extend(fixtures["results"])

fixtures = await asyncio.gather(*tasks)
has_next = fixtures["has_next"]
page += 1

return fixtures
return results

def __str__(self):
return f"{self.league['name']} - {self.league['id']}"
68 changes: 28 additions & 40 deletions tests/test_h2h_league.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,31 @@
from tests.helper import AsyncMock

h2h_league_data = {
"new_entries": {"has_next": False, "number": 1, "results": []},
"league": {
"id": 829116,
"leagueban_set": [],
"name": "League 829116",
"has_started": True,
"can_delete": False,
"short_name": None,
"created": "2018-08-09T18:10:37Z",
"closed": True,
"forum_disabled": False,
"make_code_public": False,
"rank": None,
"size": None,
"league_type": "c",
"_scoring": "h",
"ko_rounds": 2,
"admin_entry": None,
"start_event": 1,
},
"standings": {"has_next": False, "number": 1, "results": []},
"matches_next": {},
"matches_this": {},
"league": {
"id": 946125,
"name": "THE PUNDITS H2H",
"created": "2019-08-07T20:52:58.751814Z",
"closed": True,
"max_entries": None,
"league_type": "x",
"scoring": "h",
"admin_entry": 1726046,
"start_event": 1,
"code_privacy": "p",
"ko_rounds": None
},
"new_entries": {
"has_next": False,
"page": 1,
"results": [

]
},
"standings": {
"has_next": False,
"page": 1,
"results": []
}
}


Expand All @@ -42,24 +44,20 @@ async def test_init(self, loop):

@staticmethod
def test_h2h_league(loop, h2h_league):
assert h2h_league.__str__() == "League 829116 - 829116"
assert h2h_league.__str__() == "THE PUNDITS H2H - 946125"

async def test_get_fixtures_with_known_gameweek_unauthorized(
self, loop, h2h_league):
with pytest.raises(Exception):
await h2h_league.get_fixtures(1)
await h2h_league.get_fixtures(gameweek=1)

async def test_get_fixtures_with_known_gameweek_authorized(
self, loop, mocker, h2h_league):
mocked_logged_in = mocker.patch(
"fpl.models.h2h_league.logged_in", return_value=True)
mocked_fetch = mocker.patch(
"fpl.models.h2h_league.fetch", return_value={}, new_callable=AsyncMock)
fixtures = await h2h_league.get_fixtures(1)
fixtures = await h2h_league.get_fixtures(gameweek=1)
assert isinstance(fixtures, list)
assert len(fixtures) == 1
mocked_logged_in.assert_called_once()
mocked_fetch.assert_called_once()

async def test_get_fixtures_with_unknown_gameweek_unauthorized(
self, loop, h2h_league):
Expand All @@ -70,16 +68,6 @@ async def test_get_fixtures_with_unknown_gameweek_authorized(
self, loop, mocker, h2h_league):
mocked_logged_in = mocker.patch(
"fpl.models.h2h_league.logged_in", return_value=True)
mocked_fetch = mocker.patch(
"fpl.models.h2h_league.fetch", return_value={}, new_callable=AsyncMock)
gameweek_number = 3
mocked_current_gameweek = mocker.patch(
"fpl.models.h2h_league.get_current_gameweek",
return_value=gameweek_number,
new_callable=AsyncMock)
fixtures = await h2h_league.get_fixtures()
assert isinstance(fixtures, list)
assert len(fixtures) == gameweek_number
assert mocked_fetch.call_count == gameweek_number
mocked_logged_in.assert_called_once()
mocked_current_gameweek.assert_called_once()

0 comments on commit cfe612e

Please sign in to comment.