Skip to content

Commit

Permalink
Update for subdomains (get_tournament and get_tournaments)
Browse files Browse the repository at this point in the history
Some doc improvements as well
  • Loading branch information
fp12 committed May 20, 2017
1 parent b4491f9 commit 1628a65
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 15 deletions.
60 changes: 49 additions & 11 deletions challonge/user.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from . import AUTO_GET_PARTICIPANTS, AUTO_GET_MATCHES
from .helpers import get_connection
from .helpers import get_connection, assert_or_raise
from .tournament import Tournament, TournamentType


Expand All @@ -13,6 +13,7 @@ class User:
def __init__(self, username: str, api_key: str, **kwargs):
self.tournaments = None
self.connection = get_connection(username, api_key, **kwargs)
self._subdomains_searched = []

def _refresh_tournament_from_json(self, tournament_data):
if self.tournaments is None:
Expand All @@ -28,13 +29,21 @@ def _refresh_tournament_from_json(self, tournament_data):
def _create_tournament(self, json_def) -> Tournament:
return Tournament(self.connection, json_def)

def _find_tournament(self, e_id):
def _find_tournament_by_id(self, e_id):
if self.tournaments is not None:
for e in self.tournaments:
if e.id == int(e_id):
return e
return None

def _find_tournament_by_url(self, url, subdomain):
if self.tournaments is not None:
for e in self.tournaments:
if e.url == url:
if subdomain is None or e.subdomain == subdomain:
return e
return None

async def validate(self):
""" checks whether the current user is connected
Expand All @@ -46,36 +55,52 @@ async def validate(self):
"""
await self.connection('GET', 'tournaments')

async def get_tournament(self, t_id: int, force_update=False) -> Tournament:
""" gets a tournament with its id
async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament:
""" gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament is added to the local list of tournaments, but some functions (updates/destroy...) cannot be used for tournaments not owned by this user.
|methcoro|
Args:
t_id: tournament id
url: last part of the tournament url (http://challonge.com/XXX)
subdomain: first part of the tournament url, if any (http://XXX.challonge.com/...)
force_update: *optional* set to True to force the data update from Challonge
Returns:
Tournament
Raises:
APIException
ValueError: if neither of the arguments are provided
"""
found_t = self._find_tournament(t_id)
assert_or_raise((t_id is None) ^ (url is None),
ValueError,
'One of t_id or url must not be None')

found_t = self._find_tournament_by_id(t_id) if t_id is not None else self._find_tournament_by_url(url, subdomain)
if force_update or found_t is None:
res = await self.connection('GET', 'tournaments/{}'.format(t_id))
param = t_id
if param is None:
if subdomain is not None:
param = '{}-{}'.format(subdomain, url)
else:
param = url
res = await self.connection('GET', 'tournaments/{}'.format(param))
self._refresh_tournament_from_json(res)
found_t = self._find_tournament(t_id)
found_t = self._find_tournament_by_id(res['tournament']['id'])

return found_t

async def get_tournaments(self, force_update=False) -> list:
async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list:
""" gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to True to force the data update from Challonge
Returns:
Expand All @@ -85,11 +110,24 @@ async def get_tournaments(self, force_update=False) -> list:
APIException
"""
if force_update or self.tournaments is None:
if self.tournaments is None:
force_update = True
self._subdomains_searched.append('' if subdomain is None else subdomain)
elif subdomain is None and '' not in self._subdomains_searched:
force_update = True
self._subdomains_searched.append('')
elif subdomain is not None and subdomain not in self._subdomains_searched:
force_update = True
self._subdomains_searched.append(subdomain)

if force_update:
params = {
'include_participants': 1 if AUTO_GET_PARTICIPANTS else 0,
'include_matches': 1 if AUTO_GET_MATCHES else 0
}
if subdomain is not None:
params['subdomain'] = subdomain

res = await self.connection('GET', 'tournaments', **params)
if len(res) == 0:
self.tournaments = []
Expand All @@ -99,7 +137,7 @@ async def get_tournaments(self, force_update=False) -> list:

return self.tournaments

async def create_tournament(self, name: str, url: str, tournament_type=TournamentType.single_elimination, **params) -> Tournament:
async def create_tournament(self, name: str, url: str, tournament_type: TournamentType = TournamentType.single_elimination, **params) -> Tournament:
""" creates a simple tournament with basic options
|methcoro|
Expand All @@ -124,7 +162,7 @@ async def create_tournament(self, name: str, url: str, tournament_type=Tournamen
})
res = await self.connection('POST', 'tournaments', 'tournament', **params)
self._refresh_tournament_from_json(res)
return self._find_tournament(res['tournament']['id'])
return self._find_tournament_by_id(res['tournament']['id'])

async def destroy_tournament(self, t: Tournament):
""" completely removes a tournament from Challonge
Expand Down
11 changes: 7 additions & 4 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def get_credentials():


username, api_key = get_credentials()
organization = 'achallonge-testing1'


def get_random_name():
Expand All @@ -53,7 +54,7 @@ def test_cleanup(self):
user = yield from challonge.get_user(username, api_key)
tournaments = yield from user.get_tournaments()
for t in tournaments[:]:
if t.name.startswith('pychallonge'):
if t.name.startswith('achallonge'):
yield from user.destroy_tournament(t)


Expand Down Expand Up @@ -100,6 +101,9 @@ def test_b_get_tournaments(self):
ts = yield from new_user.get_tournaments()
self.assertIsInstance(ts, list)

ts = yield from new_user.get_tournaments(subdomain=organization)
self.assertIsInstance(ts, list)

random_name = get_random_name()
t1 = yield from new_user.create_tournament(random_name, random_name)

Expand All @@ -109,9 +113,8 @@ def test_b_get_tournaments(self):
t3 = yield from new_user.get_tournament(t1.id, force_update=True)
self.assertEqual(t1, t3)

fake_id = 0
t4 = yield from new_user.get_tournament(fake_id)
self.assertEqual(t4, None)
with self.assertRaises(challonge.APIException):
yield from new_user.get_tournament(-1)

yield from new_user.destroy_tournament(t1)

Expand Down

0 comments on commit 1628a65

Please sign in to comment.