From 3c5e62ffff9d3e9f17383b42251de476a01bdf8a Mon Sep 17 00:00:00 2001 From: Bogdan Popescu Date: Thu, 8 Mar 2018 01:21:03 +0100 Subject: [PATCH] Update coding style in Python files (#724) Make the minimal changes needed to fix most of the errors and warnings reported by pycodestyle (successor of pep8). The following three are ignored in this commit: - E402 module level import not at top of file - E501 line too long - E722 do not use bare except' Most of the changes are actually only spacing fixes. There is an actual code refactor done in order to fix: - W601 .has_key() is deprecated, use 'in' - E711 comparison to None should be 'if cond is None:' - E712 comparison to False should be 'if cond is False:' or 'if not cond:' - E713 test for membership should be 'not in' - E714 test for object identity should be 'is not' - E731 do not assign a lambda expression, use a def - E741 ambiguous variable name 'l' --- wouso/core/__init__.py | 7 +- wouso/core/config/admin.py | 1 + wouso/core/config/models.py | 8 +- wouso/core/god/god.py | 2 +- wouso/core/magic/admin.py | 2 + wouso/core/magic/default_setup.py | 4 +- wouso/core/magic/models.py | 2 + wouso/core/magic/templatetags/artifacts.py | 2 +- wouso/core/magic/tests.py | 8 +- wouso/core/qpool/admin.py | 1 + wouso/core/scoring/sm.py | 5 +- wouso/core/scoring/tests.py | 6 +- wouso/core/security/models.py | 10 +- wouso/core/security/sec.py | 3 +- wouso/core/security/tests.py | 6 +- wouso/core/user/models.py | 17 +- wouso/core/user/tests.py | 8 +- wouso/games/challenge/admin.py | 2 + wouso/games/challenge/api.py | 2 +- wouso/games/challenge/cpanel_urls.py | 5 +- wouso/games/challenge/cpanel_views.py | 4 +- wouso/games/challenge/forms.py | 9 +- wouso/games/challenge/models.py | 13 +- wouso/games/challenge/tests.py | 64 +-- wouso/games/challenge/urls.py | 3 +- wouso/games/challenge/views.py | 87 ++- wouso/games/grandchallenge/admin.py | 2 +- wouso/games/grandchallenge/cpanel_urls.py | 5 +- wouso/games/grandchallenge/cpanel_views.py | 58 +- wouso/games/grandchallenge/models.py | 38 +- wouso/games/grandchallenge/tests.py | 5 +- wouso/games/grandchallenge/urls.py | 3 +- wouso/games/grandchallenge/views.py | 16 +- wouso/games/qotd/api.py | 2 +- wouso/games/qotd/feeds.py | 3 +- wouso/games/qotd/models.py | 3 +- wouso/games/qotd/tests.py | 22 +- wouso/games/qotd/urls.py | 3 +- wouso/games/quest/admin.py | 3 + wouso/games/quest/api.py | 3 +- wouso/games/quest/cpanel.py | 11 +- wouso/games/quest/cpanel_urls.py | 3 +- wouso/games/quest/forms.py | 8 +- wouso/games/quest/models.py | 62 ++- wouso/games/quest/tests.py | 67 +-- wouso/games/quest/tests/task-00/check | 2 +- wouso/games/quest/urls.py | 4 +- wouso/games/quest/views.py | 25 +- wouso/games/quiz/cpanel_urls.py | 3 +- wouso/games/quiz/forms.py | 5 +- wouso/games/quiz/models.py | 59 ++- wouso/games/quiz/urls.py | 3 +- wouso/games/specialchallenge/cpanel_urls.py | 3 +- wouso/games/specialchallenge/cpanel_views.py | 2 +- wouso/games/specialchallenge/forms.py | 10 +- wouso/games/specialchallenge/models.py | 7 +- wouso/games/specialchallenge/tests.py | 5 +- wouso/games/specialchallenge/urls.py | 3 +- wouso/games/specialchallenge/views.py | 1 + wouso/games/specialquest/cpanel.py | 29 +- wouso/games/specialquest/cpanel_urls.py | 7 +- wouso/games/specialquest/forms.py | 3 +- wouso/games/specialquest/tests.py | 13 +- wouso/games/specialquest/urls.py | 3 +- wouso/games/urls.py | 3 +- wouso/games/views.py | 8 +- wouso/games/workshop/admin.py | 4 +- wouso/games/workshop/cpanel.py | 114 ++-- wouso/games/workshop/cpanel_urls.py | 3 +- wouso/games/workshop/models.py | 43 +- wouso/games/workshop/templatetags/workshop.py | 4 +- wouso/games/workshop/tests.py | 11 +- wouso/games/workshop/urls.py | 3 +- wouso/games/workshop/views.py | 50 +- wouso/interface/__init__.py | 14 +- wouso/interface/activity/__init__.py | 2 +- wouso/interface/activity/achievements.py | 20 +- wouso/interface/activity/admin.py | 2 + wouso/interface/activity/models.py | 2 + wouso/interface/activity/tests.py | 496 +++++++++--------- wouso/interface/api/__init__.py | 2 +- wouso/interface/api/admin.py | 2 +- wouso/interface/api/authentication.py | 6 +- wouso/interface/api/c2dm/admin.py | 4 +- wouso/interface/api/c2dm/models.py | 12 +- wouso/interface/api/handlers.py | 29 +- wouso/interface/api/tests.py | 3 +- wouso/interface/api/urls.py | 21 +- wouso/interface/api/views.py | 14 +- wouso/interface/apps/__init__.py | 2 +- wouso/interface/apps/files/admin.py | 1 - wouso/interface/apps/files/cpanel_urls.py | 3 +- wouso/interface/apps/files/urls.py | 3 +- wouso/interface/apps/lesson/cpanel_urls.py | 3 +- wouso/interface/apps/lesson/tests.py | 7 +- wouso/interface/apps/lesson/urls.py | 6 +- wouso/interface/apps/magic/urls.py | 5 +- wouso/interface/apps/magic/views.py | 43 +- wouso/interface/apps/messaging/admin.py | 2 + wouso/interface/apps/messaging/forms.py | 1 + wouso/interface/apps/messaging/models.py | 12 +- wouso/interface/apps/messaging/tests.py | 3 +- wouso/interface/apps/messaging/urls.py | 3 +- wouso/interface/apps/messaging/views.py | 17 +- wouso/interface/apps/pages/__init__.py | 1 - wouso/interface/apps/pages/models.py | 8 +- wouso/interface/apps/pages/urls.py | 3 +- wouso/interface/apps/pages/views.py | 7 +- wouso/interface/apps/qproposal/__init__.py | 2 +- wouso/interface/apps/qproposal/forms.py | 11 +- wouso/interface/apps/qproposal/models.py | 3 +- wouso/interface/apps/qproposal/urls.py | 5 +- wouso/interface/apps/statistics/models.py | 3 +- wouso/interface/apps/statistics/tests.py | 3 +- wouso/interface/apps/statistics/urls.py | 5 +- wouso/interface/apps/statistics/views.py | 7 +- wouso/interface/context_processors.py | 6 +- wouso/interface/cpanel/forms.py | 2 +- wouso/interface/cpanel/tests.py | 3 +- wouso/interface/cpanel/urls.py | 23 +- wouso/interface/cpanel/views.py | 30 +- wouso/interface/forms.py | 4 +- wouso/interface/forum/cpanel_urls.py | 3 +- wouso/interface/forum/tests.py | 5 +- wouso/interface/forum/urls.py | 3 +- wouso/interface/loaders.py | 3 +- wouso/interface/profile/urls.py | 6 +- wouso/interface/profile/views.py | 39 +- wouso/interface/templatetags/ui.py | 2 + wouso/interface/tests.py | 5 +- wouso/interface/top/admin.py | 3 + wouso/interface/top/models.py | 7 +- wouso/interface/top/tests.py | 3 +- wouso/interface/top/urls.py | 3 +- wouso/interface/urls.py | 19 +- wouso/interface/views.py | 50 +- wouso/manage.py | 2 +- wouso/middleware/__init__.py | 2 +- wouso/middleware/debug.py | 1 + wouso/middleware/impersonation.py | 3 +- wouso/middleware/ldap_connection.py | 12 +- wouso/middleware/seen.py | 14 +- wouso/utils/__init__.py | 3 +- wouso/utils/add_questions.py | 39 +- wouso/utils/add_races.py | 5 +- wouso/utils/add_users.py | 5 +- wouso/utils/add_users_force.py | 23 +- wouso/utils/add_users_force_to_race.py | 27 +- wouso/utils/add_users_to_race.py | 5 +- wouso/utils/extract_data_from_oldmysql.py | 9 +- wouso/utils/get_stats.py | 8 +- wouso/utils/import_questions.py | 3 +- wouso/utils/remove_users.py | 7 +- wouso/utils/scoring_update.py | 3 + wouso/utils/stats.py | 12 +- wouso/utils/tests.py | 3 +- wouso/utils/update_race_by_user_email.py | 12 +- wouso/utils/user_util.py | 75 ++- wouso/wsgi.py | 7 +- 159 files changed, 1303 insertions(+), 1022 deletions(-) diff --git a/wouso/core/__init__.py b/wouso/core/__init__.py index f2fba286..9bd090f4 100644 --- a/wouso/core/__init__.py +++ b/wouso/core/__init__.py @@ -1,4 +1,6 @@ -import warnings, logging, sys +import logging +import sys +import warnings from functools import wraps from django.contrib import messages from django.contrib.auth import logout @@ -33,5 +35,6 @@ def block_if_not_staff(sender, user, request, **kwargs): messages.error(request, _('Only staff members can log in')) logout(request) -if not 'test' in sys.argv: + +if 'test' not in sys.argv: user_logged_in.connect(block_if_not_staff) diff --git a/wouso/core/config/admin.py b/wouso/core/config/admin.py index 6223cb6a..05157b0d 100644 --- a/wouso/core/config/admin.py +++ b/wouso/core/config/admin.py @@ -5,4 +5,5 @@ class SettingAdmin(admin.ModelAdmin): list_display = ('name', 'value') + admin.site.register(Setting, SettingAdmin) diff --git a/wouso/core/config/models.py b/wouso/core/config/models.py index fe100267..642db3de 100644 --- a/wouso/core/config/models.py +++ b/wouso/core/config/models.py @@ -154,13 +154,13 @@ def set_value(self, v): self.save() def get_value(self): - l = [] + return_list = [] for n in self.value.split(): try: - l.append(int(n)) + return_list.append(int(n)) except ValueError: - l.append(0) - return l + return_list.append(0) + return return_list def form(self): return '' diff --git a/wouso/core/god/god.py b/wouso/core/god/god.py index 9e306daa..5a8ca986 100644 --- a/wouso/core/god/god.py +++ b/wouso/core/god/god.py @@ -121,7 +121,7 @@ def get_all_modifiers(self): 'curse', # prevent cast of positive spells, or cure and dispell 'immunity', # prevent cast of any spells, or cure and dispell 'top-disguise', # allow showing another number of points in top - ] + ] for g in get_games(): ms.extend(g.get_modifiers()) diff --git a/wouso/core/magic/admin.py b/wouso/core/magic/admin.py index d22a68f7..8e0e1163 100644 --- a/wouso/core/magic/admin.py +++ b/wouso/core/magic/admin.py @@ -4,6 +4,8 @@ class SpellAdmin(admin.ModelAdmin): list_display = ('name', 'title', 'type', 'percents', 'price', 'level_required', 'available', 'mass') + + admin.site.register(Artifact) admin.site.register(ArtifactGroup) admin.site.register(Spell, SpellAdmin) diff --git a/wouso/core/magic/default_setup.py b/wouso/core/magic/default_setup.py index b2aa8e05..e3cde16a 100644 --- a/wouso/core/magic/default_setup.py +++ b/wouso/core/magic/default_setup.py @@ -35,8 +35,8 @@ print "done" # Assure each user has a level - #level = Artifact.get_level_1() - #for u in Player.objects.all(): + # level = Artifact.get_level_1() + # for u in Player.objects.all(): # if u.level is None: # u.level = level # u.save() diff --git a/wouso/core/magic/models.py b/wouso/core/magic/models.py index a5ec63d6..1012887e 100644 --- a/wouso/core/magic/models.py +++ b/wouso/core/magic/models.py @@ -54,6 +54,7 @@ class Artifact(CachedItem, Modifier): but also personalization such as: image (icon) and title """ CACHE_PART = 'full_name' + class Meta: unique_together = ('name', 'group', 'percents') @@ -266,4 +267,5 @@ def management_task(cls, datetime=lambda: datetime.now(), stdout=sys.stdout): signals.postExpire.send(sender=None, psdue=s) s.delete() + register_header_link('bazaar', Bazaar.get_header_link) diff --git a/wouso/core/magic/templatetags/artifacts.py b/wouso/core/magic/templatetags/artifacts.py index 4dcd48b8..e4d87c72 100644 --- a/wouso/core/magic/templatetags/artifacts.py +++ b/wouso/core/magic/templatetags/artifacts.py @@ -53,7 +53,7 @@ def spell_due(psd): html = artifact(psd) return '%s*' % \ - (psd.spell.title, psd.due, html) + (psd.spell.title, psd.due, html) @register.simple_tag diff --git a/wouso/core/magic/tests.py b/wouso/core/magic/tests.py index 813b520d..81f84cb4 100644 --- a/wouso/core/magic/tests.py +++ b/wouso/core/magic/tests.py @@ -55,24 +55,24 @@ def test_cast_spell(self): v = [] for i in range(0, 7): player = self._get_player(i + 2) - player.points = 10-i + player.points = 10 - i player.save() v.append(player) v[3].magic.add_spell(spell2) neigh = v[3].get_neighbours_from_top(2) neigh = v[3].magic.filter_players_by_spell(neigh, spell2) - v[3].magic.mass_cast(spell2, neigh, datetime.now()+timedelta(days=1)) + v[3].magic.mass_cast(spell2, neigh, datetime.now() + timedelta(days=1)) for i in [1, 2, 4, 5]: self.assertTrue(v[i].magic.is_spelled) self.assertTrue(v[3].magic.is_spelled) - v[6].magic.cast_spell(spell1, v[0], datetime.now()+timedelta(days=1)) + v[6].magic.cast_spell(spell1, v[0], datetime.now() + timedelta(days=1)) self.assertFalse(v[6].magic.is_spelled) v[0].magic.add_spell(spell1) - v[6].magic.cast_spell(spell1, v[0], datetime.now()+timedelta(days=1)) + v[6].magic.cast_spell(spell1, v[0], datetime.now() + timedelta(days=1)) self.assertTrue(v[6].magic.is_spelled) diff --git a/wouso/core/qpool/admin.py b/wouso/core/qpool/admin.py index 1e2a4c53..9fed0c96 100644 --- a/wouso/core/qpool/admin.py +++ b/wouso/core/qpool/admin.py @@ -51,6 +51,7 @@ class QuestionAdmin(admin.ModelAdmin): class Questions2(admin.ModelAdmin): list_display = ('text') + admin.site.register(models.Question, QuestionAdmin) admin.site.register(models.Tag) admin.site.register(models.Category) diff --git a/wouso/core/scoring/sm.py b/wouso/core/scoring/sm.py index 33536304..cd7ccc18 100644 --- a/wouso/core/scoring/sm.py +++ b/wouso/core/scoring/sm.py @@ -38,7 +38,7 @@ class InvalidScoreCall(Exception): def fib(n): - return int(round((PHI**n - (1-PHI)**n) / 5**0.5)) + return int(round((PHI**n - (1 - PHI)**n) / 5**0.5)) # Setup @@ -110,7 +110,7 @@ def calculate_expression(expression, formula=None, **params): result = 0 ret[coin] = result except Exception as e: - #logging.exception(e) + # logging.exception(e) raise FormulaParsingError(formula) return ret @@ -304,4 +304,5 @@ def first_login_check(sender, **kwargs): except InvalidFormula: logging.error('Formula start points is missing') + signals.addActivity.connect(first_login_check) diff --git a/wouso/core/scoring/tests.py b/wouso/core/scoring/tests.py index b9f08a25..1187dd11 100644 --- a/wouso/core/scoring/tests.py +++ b/wouso/core/scoring/tests.py @@ -17,7 +17,7 @@ def setUp(self): self.coin = Coin.add('_test') def tearDown(self): - #self.user.delete() + # self.user.delete() self.game.delete() self.coin.delete() @@ -142,7 +142,7 @@ def test_update_points_level_upgrade_back(self): player.points = level_up_points - 1 player.save() update_points(player, None) - #Upgrade player's level back + # Upgrade player's level back player.points = level_up_points + 1 player.save() update_points(player, None) @@ -209,7 +209,7 @@ def test_first_login_points(self): self.assertEqual(player.points, 0) # this won't work, since the activity is sent in our custom view - #self.client.login(username=player.user.username, password='test') + # self.client.login(username=player.user.username, password='test') # using this instead signals.addActivity.send(sender=None, user_from=player, action="login", game=None, public=False) diff --git a/wouso/core/security/models.py b/wouso/core/security/models.py index e16c7163..ec6d7127 100644 --- a/wouso/core/security/models.py +++ b/wouso/core/security/models.py @@ -12,12 +12,12 @@ class Report(models.Model): ) user_from = models.ForeignKey(Player, related_name="user_reporting") - user_to = models.ForeignKey(Player, related_name="user_reported") - dibs = models.ForeignKey(Player, related_name="dibs", null=True, blank=True) + user_to = models.ForeignKey(Player, related_name="user_reported") + dibs = models.ForeignKey(Player, related_name="dibs", null=True, blank=True) timestamp = models.DateTimeField() - status = models.CharField(max_length=1, choices=STATUS, default='R') - text = models.CharField(max_length=250) - extra = models.CharField(max_length=250, blank=True) + status = models.CharField(max_length=1, choices=STATUS, default='R') + text = models.CharField(max_length=250) + extra = models.CharField(max_length=250, blank=True) def set_dibs(self, user_dibs): self.dibs = user_dibs.get_extension(Player) diff --git a/wouso/core/security/sec.py b/wouso/core/security/sec.py index 9a736c39..43886480 100644 --- a/wouso/core/security/sec.py +++ b/wouso/core/security/sec.py @@ -74,7 +74,7 @@ class Security(App): @classmethod def penalise(cls, player, formula, external_id=None): coins = Coin.get('penalty') - if not coins is None: + if coins is not None: score(user=player, game=None, formula=formula, external_id=external_id) @classmethod @@ -93,4 +93,5 @@ def activity_handler(cls, sender, **kwargs): def do_security_check(sender, **kwargs): Security.activity_handler(sender, **kwargs) + signals.addActivity.connect(do_security_check) diff --git a/wouso/core/security/tests.py b/wouso/core/security/tests.py index 9512709c..520aac21 100644 --- a/wouso/core/security/tests.py +++ b/wouso/core/security/tests.py @@ -16,7 +16,7 @@ def setUp(self): scoring.setup_scoring() def test_rule_challenge_was_set_up(self): - #run a challenge + # run a challenge Challenge.WARRANTY = False chall = Challenge.create(user_from=self.chall_user, user_to=self.chall_user2, ignore_questions=True) @@ -29,7 +29,7 @@ def test_rule_challenge_was_set_up(self): chall.user_to.save() chall.played() - #test penalty points - #20 is the default formula value for a chall-was-set-up + # test penalty points + # 20 is the default formula value for a chall-was-set-up self.assertEqual(20, scoring.History.user_coins(self.user2.player_related.get())['penalty']) diff --git a/wouso/core/user/models.py b/wouso/core/user/models.py index 0398c7e6..77426d7e 100644 --- a/wouso/core/user/models.py +++ b/wouso/core/user/models.py @@ -153,14 +153,14 @@ def get_neighbours_from_top(self, count, user_race=None, spell_type=None): else: allUsers = [user for user in allUsers if user.race.name != user_race.name] - if len(allUsers) <= 2*count+1: + if len(allUsers) <= 2 * count + 1: return allUsers - start = max(pos-count, 0) + start = max(pos - count, 0) if pos + count >= len(allUsers): - start = len(allUsers)-2*count-1 + start = len(allUsers) - 2 * count - 1 - players = allUsers[start:start+2*count+1] + players = allUsers[start:start + 2 * count + 1] return players def get_division(self, count): @@ -248,7 +248,7 @@ def _avatar(self): return avatar # special: - #@cached_method + # @cached_method def get_extension(self, cls): if self.__class__ is cls: return self @@ -318,9 +318,9 @@ def _race_name(self): def save(self, **kwargs): """ Clear cache for extensions """ - #for k, v in self.EXTENSIONS.iteritems(): - # drop_cache(self.get_extension, self, v) - #drop_cache(self.get_extension, self, self.__class__) + # for k, v in self.EXTENSIONS.iteritems(): + # drop_cache(self.get_extension, self, v) + # drop_cache(self.get_extension, self, self.__class__) drop_cache(self._race_name, self) drop_cache(self._group, self) update_display_name(self, save=False) @@ -359,6 +359,7 @@ def user_post_save(sender, instance, **kwargs): profile.save() update_display_name(profile) + models.signals.post_save.connect(user_post_save, User) diff --git a/wouso/core/user/tests.py b/wouso/core/user/tests.py index f39e3361..4405b881 100644 --- a/wouso/core/user/tests.py +++ b/wouso/core/user/tests.py @@ -36,19 +36,19 @@ def test_player_neighbours(self): player.save() v.append(player) - #check neighbours for first player in top + # check neighbours for first player in top players = v[0].get_neighbours_from_top(2) self.assertEqual(len(players), 5) for i in range(0, 5): self.assertEqual(players[i], v[i]) - #check neighbours for middle player in top + # check neighbours for middle player in top players = v[3].get_neighbours_from_top(2) self.assertEqual(len(players), 5) for i in range(0, 5): self.assertEqual(players[i], v[i + 1]) - #check neighbours for last player in top + # check neighbours for last player in top players = v[6].get_neighbours_from_top(2) self.assertEqual(len(players), 5) for i in range(0, 5): @@ -100,5 +100,5 @@ def test_nickname_update(self): player.nickname = 'altc3va' player.save() - #self.assertEqual(unicode(player), player.nickname) + # self.assertEqual(unicode(player), player.nickname) self.assertEqual(player.full_name, player.nickname) diff --git a/wouso/games/challenge/admin.py b/wouso/games/challenge/admin.py index ff987492..96639b1d 100644 --- a/wouso/games/challenge/admin.py +++ b/wouso/games/challenge/admin.py @@ -1,9 +1,11 @@ from django.contrib import admin from wouso.games.challenge.models import Challenge, ChallengeUser, Participant + class ChallengeUserAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'last_launched') + admin.site.register(Challenge) admin.site.register(Participant) admin.site.register(ChallengeUser, ChallengeUserAdmin) diff --git a/wouso/games/challenge/api.py b/wouso/games/challenge/api.py index 4080071f..0cb7e1cc 100644 --- a/wouso/games/challenge/api.py +++ b/wouso/games/challenge/api.py @@ -89,7 +89,7 @@ def read(self, request, challenge_id, action='play'): 'questions': dict( [(q.id, {'text': q, 'answers': dict([(a.id, a) for a in q.answers])}) for q in challenge.questions.all()]), - } + } if action == 'refuse': if challenge.user_to.user == challuser and challenge.is_launched(): diff --git a/wouso/games/challenge/cpanel_urls.py b/wouso/games/challenge/cpanel_urls.py index b80ce00d..47cc951a 100644 --- a/wouso/games/challenge/cpanel_urls.py +++ b/wouso/games/challenge/cpanel_urls.py @@ -1,5 +1,6 @@ -from django.conf.urls import patterns, url +from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.games.challenge.cpanel_views', +urlpatterns = patterns( + 'wouso.games.challenge.cpanel_views', url(r'^$', 'list_challenges', name='list_challenges'), ) diff --git a/wouso/games/challenge/cpanel_views.py b/wouso/games/challenge/cpanel_views.py index 0949d301..557fb876 100644 --- a/wouso/games/challenge/cpanel_views.py +++ b/wouso/games/challenge/cpanel_views.py @@ -2,13 +2,15 @@ from wouso.core.decorators import staff_required from wouso.games.challenge.models import Challenge + class ListChallenges(ListView): model = Challenge paginate_by = 50 context_object_name = 'challenges' template_name = 'challenge/cpanel/list_challenges.html' - + def get_queryset(self): return self.model.objects.all().order_by('-date') + list_challenges = staff_required(ListChallenges.as_view()) diff --git a/wouso/games/challenge/forms.py b/wouso/games/challenge/forms.py index 0fbd9dcf..b0f727f3 100644 --- a/wouso/games/challenge/forms.py +++ b/wouso/games/challenge/forms.py @@ -1,5 +1,6 @@ from django import forms + class ChallengeForm(forms.Form): def __init__(self, challenge, data=None): super(ChallengeForm, self).__init__(data) @@ -7,7 +8,7 @@ def __init__(self, challenge, data=None): for q in challenge.questions.all(): field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label=q) field.choices = [(a.id, a) for a in q.shuffled_answers] - self.fields['answer_{id}'.format(id = q.id)] = field + self.fields['answer_{id}'.format(id=q.id)] = field self.data = data def get_response(self): @@ -21,8 +22,8 @@ def get_response(self): adding an empty list to dic in this case""" for field in self.visible_fields(): id = int(field.html_name[len('answer_'):]) - - if not id in res: + + if id not in res: res[id] = [] return res @@ -41,4 +42,4 @@ def get_results_in_order(self, results): for field in self.visible_fields(): id = int(field.html_name[len('answer_'):]) v.append(results[id]) - return v \ No newline at end of file + return v diff --git a/wouso/games/challenge/models.py b/wouso/games/challenge/models.py index 57ef3e9d..959178d5 100644 --- a/wouso/games/challenge/models.py +++ b/wouso/games/challenge/models.py @@ -132,11 +132,11 @@ def get_refused_challenges(self): return self.get_all_challenges().filter(status=u'R') def get_win_percentage(self): - w = self.get_won_challenges().count() - d = self.get_draw_challenges().count() - l = self.get_lost_challenges().count() + won = self.get_won_challenges().count() + draw = self.get_draw_challenges().count() + lost = self.get_lost_challenges().count() # 1 draw counts as 1/2 win, 1/2 loss - return 0 if w + d == 0 else (w + d / 2.0) / (w + l + d) * 100 + return 0 if won + draw == 0 else (won + draw / 2.0) / (won + lost + draw) * 100 def get_random_opponent(self): players = ChallengeUser.objects.exclude(user=self.user) @@ -204,6 +204,7 @@ def get_stats(self): win_percentage=win_percentage, opponents=result) return stats + Player.register_extension('challenge', ChallengeUser) @@ -420,7 +421,7 @@ def formatTime(seconds): elif seconds == 60: ret = _('1 minute') elif seconds % 60 == 0: - ret = _('{minutes} minutes').format(minutes=(seconds/60)) + ret = _('{minutes} minutes').format(minutes=(seconds / 60)) elif 60 < seconds < 120: ret = _('1 minute and {s} seconds').format(s=seconds % 60) else: @@ -825,4 +826,6 @@ def challenge_post_delete(sender, instance, **kwargs): instance.user_to.delete() except: pass + + models.signals.post_delete.connect(challenge_post_delete, Challenge) diff --git a/wouso/games/challenge/tests.py b/wouso/games/challenge/tests.py index 666bc0f9..cf5395a6 100644 --- a/wouso/games/challenge/tests.py +++ b/wouso/games/challenge/tests.py @@ -1,6 +1,6 @@ import json import unittest -from datetime import datetime,timedelta +from datetime import datetime, timedelta from mock import patch from django.contrib.auth.models import User from django.core.urlresolvers import reverse @@ -17,6 +17,7 @@ Challenge.LIMIT = 5 + class ChallengeTestCase(WousoTest): def setUp(self): super(ChallengeTestCase, self).setUp() @@ -35,8 +36,12 @@ def tearDown(self): def _get_foo_question(self, correct=2): """ Return a Question """ - class Question: pass - class Answer: pass + class Question: + pass + + class Answer: + pass + q = Question() q.text = 'How many' q.answers = [] @@ -73,7 +78,6 @@ def testLaunch(self): self.assertFalse(chall.is_refused()) chall.delete() - def test_run_accept(self): chall = Challenge.create(user_from=self.chall_user, user_to=self.chall_user2, ignore_questions=True) @@ -99,7 +103,7 @@ def test_run_doesn_not_expires(self): with patch('wouso.games.challenge.models.datetime') as mock_datetime: # after three minutes, challenge is still available mock_datetime.now.return_value = just_now + timedelta(minutes=3) - #chall.set_played(self.chall_user, {}) + # chall.set_played(self.chall_user, {}) self.assertTrue(chall.is_expired_for_user(self.chall_user)) # pass some more time, challenge cannot be submited any more mock_datetime.now.return_value = just_now + timedelta(minutes=10) @@ -185,7 +189,7 @@ def test_scoring_loss(self): chall = Challenge.create(user_from=winner, user_to=loser, ignore_questions=True) chall.set_won_by_player(winner) - self.assertEqual(loser.player_ptr.points, initial_points + loss_points) # loss_points is negative + self.assertEqual(loser.player_ptr.points, initial_points + loss_points) # loss_points is negative def test_variable_timer(self): formula = Formula.add('chall-timer') @@ -219,19 +223,19 @@ def test_in_same_division(self): hs.save() # Check first player. - self.assertTrue(players[n-1].in_same_division(players[n-2])) - self.assertTrue(players[n-1].in_same_division(players[max(0, n-1-division_range)])) + self.assertTrue(players[n - 1].in_same_division(players[n - 2])) + self.assertTrue(players[n - 1].in_same_division(players[max(0, n - 1 - division_range)])) # Check last player. self.assertTrue(players[0].in_same_division(players[1])) - self.assertTrue(players[0].in_same_division(players[min(n-1, division_range)])) + self.assertTrue(players[0].in_same_division(players[min(n - 1, division_range)])) # Check middle player. t = n / 2 - self.assertTrue(players[t].in_same_division(players[max(0, t-division_range)])) - self.assertTrue(players[t].in_same_division(players[min(n-1, t+division_range)])) - self.assertTrue(players[t].in_same_division(players[t-1])) - self.assertTrue(players[t].in_same_division(players[t+1])) + self.assertTrue(players[t].in_same_division(players[max(0, t - division_range)])) + self.assertTrue(players[t].in_same_division(players[min(n - 1, t + division_range)])) + self.assertTrue(players[t].in_same_division(players[t - 1])) + self.assertTrue(players[t].in_same_division(players[t + 1])) def test_not_in_same_division(self): n = 100 @@ -242,7 +246,7 @@ def test_not_in_same_division(self): # Add an offset value to every user's points in order to avoid top overlapping with other test users. for i in xrange(n): - scoring.score_simple(players[i], 'points', points_offset + i*10) + scoring.score_simple(players[i], 'points', points_offset + i * 10) # Update players top. for i, u in enumerate(Player.objects.all().order_by('-points')): @@ -253,15 +257,15 @@ def test_not_in_same_division(self): hs.save() # Check first player. - self.assertFalse(players[n-1].in_same_division(players[max(0, n-1-division_range-1)])) + self.assertFalse(players[n - 1].in_same_division(players[max(0, n - 1 - division_range - 1)])) # Check last player. - self.assertFalse(players[0].in_same_division(players[min(n-1, division_range+1)])) + self.assertFalse(players[0].in_same_division(players[min(n - 1, division_range + 1)])) # Check middle player. t = n / 2 - self.assertFalse(players[t].in_same_division(players[max(0, t-division_range-1)])) - self.assertFalse(players[t].in_same_division(players[min(n-1, t+division_range+1)])) + self.assertFalse(players[t].in_same_division(players[max(0, t - division_range - 1)])) + self.assertFalse(players[t].in_same_division(players[min(n - 1, t + division_range + 1)])) class ChallengeApi(WousoTest): @@ -315,7 +319,7 @@ def test_post_challenge(self): for i in range(Challenge.LIMIT + 1): q = Question.objects.create(text='text %s' % i, category=category, active=True) for j in range(5): - Answer.objects.create(correct=j==1, question=q) + Answer.objects.create(correct=j == 1, question=q) chall = Challenge.create(user_from=self.challuser2, user_to=self.challuser) chall.accept() response = self.client.get('/api/challenge/{id}/'.format(id=chall.id)) @@ -425,6 +429,7 @@ def test_cache_points(self): # TODO: add page tests (views) for challenge run + class TestChallengeViews(WousoTest): def setUp(self): super(TestChallengeViews, self).setUp() @@ -451,7 +456,7 @@ def setUp(self): self.answer2 = Answer.objects.create(text='second answer', correct=True, question=self.question2) self.ch = Challenge.create(user_from=self.ch_player1, user_to=self.ch_player2, - ignore_questions=True) + ignore_questions=True) self.ch.questions.add(self.question1) self.ch.questions.add(self.question2) @@ -460,7 +465,7 @@ def setUp(self): def test_challenge_index(self): Challenge.create(user_from=self.ch_player2, user_to=self.ch_player1, - ignore_questions=True) + ignore_questions=True) response = self.c.get(reverse('challenge_index_view')) # Test if both challenges are displayed self.assertContains(response, 'testuser1 vs') @@ -504,8 +509,8 @@ def test_challenge_can_be_submitted_only_once(self): # Run the challenge response = self.c.get(reverse('view_challenge', args=[self.ch.id])) # Submit the challenge - data = {self.question1.id: [u'answer_%d' %(self.answer1.id)], - self.question2.id: [u'answer_%d' %(self.answer2.id)]} + data = {self.question1.id: [u'answer_%d' % (self.answer1.id)], + self.question2.id: [u'answer_%d' % (self.answer2.id)]} response = self.c.post(reverse('view_challenge', args=[self.ch.id]), data) self.assertContains(response, 'You scored') # Try to submit it again @@ -516,8 +521,8 @@ def test_challenge_cannot_be_submitted_when_it_is_not_accepted(self): self.ch.status = 'L' self.ch.save() # Submit the challenge - data = {self.question1.id: [u'answer_%d' %(self.answer1.id)], - self.question2.id: [u'answer_%d' %(self.answer2.id)]} + data = {self.question1.id: [u'answer_%d' % (self.answer1.id)], + self.question2.id: [u'answer_%d' % (self.answer2.id)]} response = self.c.post(reverse('view_challenge', args=[self.ch.id]), data, follow=True) self.assertContains(response, 'The challenge was not accepted') @@ -525,8 +530,8 @@ def test_challenge_cannot_be_submitted_when_it_is_refused(self): self.ch.status = 'R' self.ch.save() # Submit the challenge - data = {self.question1.id: [u'answer_%d' %(self.answer1.id)], - self.question2.id: [u'answer_%d' %(self.answer2.id)]} + data = {self.question1.id: [u'answer_%d' % (self.answer1.id)], + self.question2.id: [u'answer_%d' % (self.answer2.id)]} response = self.c.post(reverse('view_challenge', args=[self.ch.id]), data, follow=True) self.assertContains(response, 'The challenge was refused') @@ -640,11 +645,10 @@ def test_admin_button_challenges(self): # Button is not displayed for normal users response = self.c.get(reverse('player_profile', args=[self.ch_player2.pk])) self.assertNotContains(response, - '%s' % (url, _('Challenges'))) + '%s' % (url, _('Challenges'))) # Button is displayed for super users self.c.login(username=admin.username, password='admin') response = self.c.get(reverse('player_profile', args=[self.ch_player2.pk])) self.assertContains(response, - '%s' % (url, _('Challenges'))) - + '%s' % (url, _('Challenges'))) diff --git a/wouso/games/challenge/urls.py b/wouso/games/challenge/urls.py index 45758dbd..4e922ef9 100644 --- a/wouso/games/challenge/urls.py +++ b/wouso/games/challenge/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.challenge.views', +urlpatterns = patterns( + 'wouso.games.challenge.views', url(r'^$', 'index', name='challenge_index_view'), url(r'^(?P\d+)/$', 'challenge', name='view_challenge'), url(r'^launch/(?P\d+)/$', 'launch', name='challenge_launch'), diff --git a/wouso/games/challenge/views.py b/wouso/games/challenge/views.py index 44e49846..947f79a3 100644 --- a/wouso/games/challenge/views.py +++ b/wouso/games/challenge/views.py @@ -20,6 +20,7 @@ import logging from django.db import transaction + @transaction.commit_manually def flush_transaction(): """ Flush the current transaction so we don't read stale data @@ -32,6 +33,7 @@ def flush_transaction(): """ transaction.commit() + class PlayerViewMixin(): def get_player(self): if 'player_id' in self.kwargs.keys() and self.request.user.get_profile().in_staff_group(): @@ -42,6 +44,7 @@ def get_player(self): return current_player + @login_required def index(request): """ Shows all challenges related to the current user """ @@ -54,9 +57,11 @@ def index(request): if not chall_user.is_eligible(): messages.error(request, _('Your race can\'t play. Go home')) - return render_to_response('challenge/index.html', - {'challenges': challs, 'played': played, 'challuser': chall_user, 'challenge': ChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'challenge/index.html', + {'challenges': challs, 'played': played, 'challuser': chall_user, 'challenge': ChallengeGame}, + context_instance=RequestContext(request)) + class ChallengeView(View): def dispatch(self, request, *args, **kwargs): @@ -78,8 +83,8 @@ def dispatch(self, request, *args, **kwargs): return redirect('challenge_index_view') if self.participant.played: - messages.error(request, _('You have already submitted this challenge'\ - ' and scored %.2f points') % self.participant.score) + messages.error(request, _('You have already submitted this challenge' + ' and scored %.2f points') % self.participant.score) return redirect('challenge_index_view') return super(ChallengeView, self).dispatch(request, *args, **kwargs) @@ -89,10 +94,11 @@ def get(self, request, *args, **kwargs): self.chall.set_start(self.chall_user) form = ChallengeForm(self.chall) seconds_left = self.chall.time_for_user(self.chall_user) - return render_to_response('challenge/challenge.html', - {'challenge': self.chall, 'form': form, 'challenge_user': self.chall_user, - 'seconds_left': seconds_left}, - context_instance=RequestContext(request)) + return render_to_response( + 'challenge/challenge.html', + {'challenge': self.chall, 'form': form, 'challenge_user': self.chall_user, + 'seconds_left': seconds_left}, + context_instance=RequestContext(request)) def post(self, request, **kwargs): form = ChallengeForm(self.chall, request.POST) @@ -104,13 +110,16 @@ def post(self, request, **kwargs): questions_and_answers = zip(form.visible_fields(), results['results']) else: questions_and_answers = None - return render_to_response('challenge/result.html', + return render_to_response( + 'challenge/result.html', {'challenge': self.chall, 'challenge_user': self.chall_user, - 'points': results['points'], 'form' : form, 'questions_and_answers' : questions_and_answers}, + 'points': results['points'], 'form': form, 'questions_and_answers': questions_and_answers}, context_instance=RequestContext(request)) + challenge = login_required(ChallengeView.as_view()) + class FileLock: def __init__(self, filename): handle = open(filename, 'w') @@ -123,9 +132,10 @@ def unlock(self): self.handle = None def __del__(self): - if self.handle != None: + if self.handle is not None: self.unlock() + class NamedFileLock: def __init__(self, filename): self.filename = filename @@ -133,13 +143,15 @@ def __init__(self, filename): def lock(self): return FileLock(self.filename) + challengeLock = NamedFileLock("/tmp/wouso_challenge_launch_lock") -#import logging -#logger = logging. +# import logging +# logger = logging. # http://stackoverflow.com/questions/3346124/how-do-i-force-django-to-ignore-any-caches-and-reload-data + @login_required def launch(request, to_id): lock = challengeLock.lock() @@ -150,7 +162,6 @@ def launch(request, to_id): user_to = user_to.get_extension(ChallengeUser) user_from = request.user.get_profile().get_extension(ChallengeUser) - if ChallengeGame.disabled(): messages.error(request, _('Challenges have been disabled.')) logging.info("Ready to unlock (disabled).") @@ -184,13 +195,13 @@ def launch(request, to_id): if user_from.can_challenge(user_to): try: chall = Challenge.create(user_from=user_from, user_to=user_to) - logging.info("Created challenge: %s" %(chall)) + logging.info("Created challenge: %s" % (chall)) except ChallengeException as e: # Some error occurred during question fetch. Clean up, and display error messages.error(request, e.message) lock.unlock() return redirect('challenge_index_view') - #Checking if user_to is stored in session + # Checking if user_to is stored in session PREFIX = "_user:" action_msg = "multiple-login" if (PREFIX + user_to.user.username) in request.session: @@ -207,6 +218,7 @@ def launch(request, to_id): lock.unlock() return redirect('challenge_index_view') + @login_required def accept(request, id): if ChallengeGame.disabled(): @@ -216,27 +228,29 @@ def accept(request, id): chall = get_object_or_404(Challenge, pk=id) user_to = request.user.get_profile().get_extension(ChallengeUser) - if (chall.user_to.user == user_to and chall.is_launched()) or \ - request.user.is_superuser: - chall.accept() - return redirect('challenge_index_view') + if (chall.user_to.user == user_to and + chall.is_launched()) or request.user.is_superuser: + chall.accept() + return redirect('challenge_index_view') messages.error(request, _('Challenge cannot be accepted.')) return redirect('challenge_index_view') + @login_required def refuse(request, id): chall = get_object_or_404(Challenge, pk=id) user_to = request.user.get_profile().get_extension(ChallengeUser) - if (chall.user_to.user == user_to and chall.is_launched()) or \ - request.user.is_superuser: - chall.refuse() - return redirect('challenge_index_view') + if (chall.user_to.user == user_to and + chall.is_launched()) or request.user.is_superuser: + chall.refuse() + return redirect('challenge_index_view') messages.error(request, _('You cannot refuse this challenge.')) return redirect('challenge_index_view') + @login_required def cancel(request, id): chall = get_object_or_404(Challenge, pk=id) @@ -249,6 +263,7 @@ def cancel(request, id): messages.error(request, _('You cannot cancel this challenge.')) return redirect('challenge_index_view') + @login_required def setplayed(request, id): """ Set challenge as played for the other user. @@ -269,6 +284,7 @@ def setplayed(request, id): chall.played() return redirect('challenge_index_view') + @login_required def use_one_more(request): challuser = request.user.get_profile().get_extension(ChallengeUser) @@ -280,6 +296,7 @@ def use_one_more(request): return redirect('challenge_index_view') + def header_link(context): user = context.get('user', None) if not user or not user.is_authenticated(): @@ -303,6 +320,8 @@ def header_link(context): url = reverse('wouso.games.challenge.views.index') return dict(link=url, count=count, text=_('Challenges')) + + register_header_link('challenges', header_link) @@ -317,8 +336,11 @@ def sidebar_widget(context): # reduce noise, thanks if not challs: return '' - return render_to_string('challenge/sidebar.html', {'challenges': challs, - 'challenge': ChallengeGame, 'chall_user': chall_user, 'id': 'challenge'}) + return render_to_string( + 'challenge/sidebar.html', + {'challenges': challs, 'challenge': ChallengeGame, 'chall_user': chall_user, 'id': 'challenge'}) + + register_sidebar_block('challenge', sidebar_widget) @@ -337,8 +359,10 @@ def get_context_data(self, **kwargs): context.update({'challplayer': self.player}) return context + history = HistoryView.as_view() + @login_required def challenge_player(request): if request.method == 'POST': @@ -351,6 +375,7 @@ def challenge_player(request): return redirect('challenge_index_view') return redirect('challenge_index_view') + @login_required def challenge_random(request): setting = BoolSetting.get('random_challenge').get_value() @@ -367,6 +392,7 @@ def challenge_random(request): return redirect('challenge_launch', player.id) + class DetailedChallengeStatsView(ListView, PlayerViewMixin): template_name = 'challenge/statistics_detail.html' context_object_name = 'chall_total' @@ -378,12 +404,14 @@ def get_queryset(self): def get_context_data(self, **kwargs): context = super(DetailedChallengeStatsView, self).get_context_data(**kwargs) context.update({'current_player': self.get_player(), - 'target_player': self.target_user, - 'opponent': self.target_user}) + 'target_player': self.target_user, + 'opponent': self.target_user}) return context + detailed_challenge_stats = login_required(DetailedChallengeStatsView.as_view()) + class ChallengeStatsView(TemplateView, PlayerViewMixin): """ Statistics for one user """ template_name = 'challenge/statistics.html' @@ -393,4 +421,5 @@ def get_context_data(self, **kwargs): context.update(self.get_player().get_stats()) return context + challenge_stats = login_required(ChallengeStatsView.as_view()) diff --git a/wouso/games/grandchallenge/admin.py b/wouso/games/grandchallenge/admin.py index fab2a7b7..31435ffb 100644 --- a/wouso/games/grandchallenge/admin.py +++ b/wouso/games/grandchallenge/admin.py @@ -3,4 +3,4 @@ admin.site.register(GrandChallenge) admin.site.register(GrandChallengeGame) -admin.site.register(GrandChallengeUser) \ No newline at end of file +admin.site.register(GrandChallengeUser) diff --git a/wouso/games/grandchallenge/cpanel_urls.py b/wouso/games/grandchallenge/cpanel_urls.py index 0ba7ca82..14cbfe73 100644 --- a/wouso/games/grandchallenge/cpanel_urls.py +++ b/wouso/games/grandchallenge/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.grandchallenge.cpanel_views', +urlpatterns = patterns( + 'wouso.games.grandchallenge.cpanel_views', url(r'^$', 'grandchalls', name='grandchalls'), url(r'^last/$', 'lastchalls', name='lastchalls'), url(r'^start/$', 'grandchalls_start', name='grandchalls_start'), @@ -10,4 +11,4 @@ url(r'^round/close/$', 'grandchalls_round_close', name='grandchalls_round_close'), url(r'^round/reset/$', 'grandchalls_hard_reset', name='grandchalls_hard_reset'), url(r'^results/$', 'grandchalls_results', name='grandchalls_results'), -) \ No newline at end of file +) diff --git a/wouso/games/grandchallenge/cpanel_views.py b/wouso/games/grandchallenge/cpanel_views.py index cfd8d23f..d9c14739 100644 --- a/wouso/games/grandchallenge/cpanel_views.py +++ b/wouso/games/grandchallenge/cpanel_views.py @@ -8,7 +8,8 @@ def grandchalls(request): round = GrandChallengeGame.get_current_round() nr = round.round_number if round else -1 - return render_to_response('grandchallenge/cpanel/grandchallenge.html', + return render_to_response( + 'grandchallenge/cpanel/grandchallenge.html', {'nr': nr, 'round': round, 'gc': GrandChallengeGame}, context_instance=RequestContext(request)) @@ -18,8 +19,10 @@ def grandchalls_round_next(request): if request.method == 'POST': GrandChallengeGame.round_next() return redirect('grandchalls') - return render_to_response('grandchallenge/cpanel/grandchallenge_round_next.html', {'gc': GrandChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'grandchallenge/cpanel/grandchallenge_round_next.html', + {'gc': GrandChallengeGame}, + context_instance=RequestContext(request)) @staff_required @@ -28,8 +31,10 @@ def grandchalls_round_close(request): round = GrandChallengeGame.get_current_round() GrandChallengeGame.force_round_close(round) return redirect('grandchalls') - return render_to_response('grandchallenge/cpanel/grandchallenge_round_close.html', {'gc': GrandChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'grandchallenge/cpanel/grandchallenge_round_close.html', + {'gc': GrandChallengeGame}, + context_instance=RequestContext(request)) @staff_required @@ -37,22 +42,27 @@ def grandchalls_hard_reset(request): if request.method == 'POST': GrandChallengeGame.reset() return redirect('grandchalls') - return render_to_response('grandchallenge/cpanel/grandchallenge_hard_reset.html', {'gc': GrandChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'grandchallenge/cpanel/grandchallenge_hard_reset.html', + {'gc': GrandChallengeGame}, + context_instance=RequestContext(request)) @staff_required def grandchalls_round_results(request, round_number): round = Round(round_number) - return render_to_response('grandchallenge/cpanel/grandchallenge_round_results.html', {'round': round, 'gc': GrandChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'grandchallenge/cpanel/grandchallenge_round_results.html', + {'round': round, 'gc': GrandChallengeGame}, + context_instance=RequestContext(request)) @staff_required def grandchalls_results(request): - return render_to_response('grandchallenge/cpanel/grandchallenge_results.html', - {'gchalls': GrandChallenge.get_challenges(), - 'clasament': GrandChallenge.clasament()}, + return render_to_response( + 'grandchallenge/cpanel/grandchallenge_results.html', + {'gchalls': GrandChallenge.get_challenges(), + 'clasament': GrandChallenge.clasament()}, context_instance=RequestContext(request)) @@ -90,13 +100,12 @@ def grandchalls_round(request): over = 1 GrandChallengeGame.round_number += 1 - gchalls = sorted(GrandChallenge.get_challenges(), key=lambda gc:gc.branch) + gchalls = sorted(GrandChallenge.get_challenges(), key=lambda gc: gc.branch) - return render_to_response('grandchallenge/cpanel/grandchallenge.html', - {'gchalls': gchalls, - 'nr': GrandChallengeGame.round_number, - 'done': done, - 'over': over}, + return render_to_response( + 'grandchallenge/cpanel/grandchallenge.html', + {'gchalls': gchalls, 'nr': GrandChallengeGame.round_number, + 'done': done, 'over': over}, context_instance=RequestContext(request)) @@ -106,17 +115,20 @@ def grandchalls_start(request): GrandChallengeGame.start() return redirect('grandchalls') + @staff_required def grandchalls_set_active(request): """ Start the game """ - #GrandChallengeGame.set_active() - return render_to_response('grandchallenge/cpanel/grandchallenge.html', + # GrandChallengeGame.set_active() + return render_to_response( + 'grandchallenge/cpanel/grandchallenge.html', context_instance=RequestContext(request)) @staff_required def lastchalls(request): last30 = GrandChallenge.objects.filter(challenge__status__in=['P', 'D']).order_by('-challenge__date')[:30] - return render_to_response('grandchallenge/cpanel/lastchalls.html', - {'last30': last30}, - context_instance=RequestContext(request)) \ No newline at end of file + return render_to_response( + 'grandchallenge/cpanel/lastchalls.html', + {'last30': last30}, + context_instance=RequestContext(request)) diff --git a/wouso/games/grandchallenge/models.py b/wouso/games/grandchallenge/models.py index 0cd005fb..e3f54fed 100644 --- a/wouso/games/grandchallenge/models.py +++ b/wouso/games/grandchallenge/models.py @@ -16,7 +16,11 @@ def get_challenges(self): """ Return a queryset of grandchallenges for this player """ - return Challenge.objects.filter(id__in=GrandChallenge.objects.filter(Q(challenge__user_from__user__id=self.id)|Q(challenge__user_to__user__id=self.id)).order_by('round').values('challenge')) + return Challenge.objects.filter( + id__in=GrandChallenge.objects.filter( + Q(challenge__user_from__user__id=self.id) | + Q(challenge__user_to__user__id=self.id)) + .order_by('round').values('challenge')) def get_active(self): """ @@ -38,13 +42,14 @@ def set_last_round(self, round_number): self.last_round = round_number self.save() + class GrandChallenge(models.Model): challenge = models.ForeignKey(Challenge, blank=True, null=True) round = models.IntegerField(blank=True, null=True) ALL = [] OUT_PLAY = [] - CHALLENGES= [] + CHALLENGES = [] def __oldinit__(self, user_from, user_to): # TODO: change this constructor to a classmethod @@ -88,13 +93,13 @@ def active(cls): @classmethod def all_done(cls): for i in cls.CHALLENGES: - x = Challenge.objects.get(id = i) + x = Challenge.objects.get(id=i) if x.status != "P": return False return True def play(self, round_number): - winner = Challenge.objects.get(id= self.challenge_id).winner #trebuie generat de joc + winner = Challenge.objects.get(id=self.challenge_id).winner # trebuie generat de joc if winner.user == self.user_from.user: self.won = self.user_from @@ -121,16 +126,15 @@ def played_with(cls, user): def joaca(cls, round_number): for c in GrandChallenge.active(): - #numarul rundei... + # numarul rundei... c.play(round_number) if(c.lost.lost == 2): cls.OUT_PLAY.append(c.lost) - #print c.lost - + # print c.lost @classmethod def clasament(cls): - arb_win = GrandChallengeGame.eligible(0) + arb_win = GrandChallengeGame.eligible(0) arb_lose = GrandChallengeGame.eligible(1) if(len(arb_win) == 1): cls.OUT_PLAY.append(arb_win[0]) @@ -167,8 +171,8 @@ def rounds(self): Return a list of previous rounds, as an iterator """ if self.round_number > 0: - for i in range(self.round_number): - yield Round(i + 1) + for i in range(self.round_number): + yield Round(i + 1) def __repr__(self): return '<' + 'Round ' + unicode(self.round_number) + '>' @@ -242,7 +246,7 @@ def eligible(cls, lost_count): @classmethod def is_final(cls): - arb_win = cls.eligible(0) + arb_win = cls.eligible(0) arb_lose = cls.eligible(1) if (len(arb_win) == 1) and (len(arb_lose) == 1): return True @@ -250,7 +254,7 @@ def is_final(cls): @classmethod def final_round(cls): - arb_win = cls.eligible(0) + arb_win = cls.eligible(0) arb_lose = cls.eligible(1) GrandChallenge(arb_win[0], arb_lose[0]) @@ -260,7 +264,7 @@ def final_second_round(cls): @classmethod def is_winner(cls): - arb_win = cls.eligible(0) + arb_win = cls.eligible(0) arb_lose = cls.eligible(1) if (len(arb_win) == 0) and (len(arb_lose) == 2): return False @@ -268,7 +272,7 @@ def is_winner(cls): @classmethod def is_finished(cls): - arb_win = cls.eligible(0) + arb_win = cls.eligible(0) arb_lose = cls.eligible(1) if len(arb_win) == 0 or (len(arb_win) == 1 and len(arb_lose) != 1): return True @@ -290,7 +294,7 @@ def play_round(cls, lost_count, round_number): u = all[0] played_with = GrandChallenge.played_with(u) - adversari = [eu for eu in all if ((eu.lost == u.lost) and (eu != u) and ((eu not in played_with) or (eu == all[-1])) )] + adversari = [eu for eu in all if ((eu.lost == u.lost) and (eu != u) and ((eu not in played_with) or (eu == all[-1])))] if not len(adversari): break @@ -375,7 +379,7 @@ def round_next(cls): challenges = [] if cls.is_final(): # Only two players left in the game - arb_win = cls.eligible(0) + arb_win = cls.eligible(0) arb_lose = cls.eligible(1) challenges.append(GrandChallenge.create(arb_win[0], arb_lose[0], round.round_number + 1)) else: @@ -391,4 +395,4 @@ def round_next(cls): round.round_number += 1 cls.set_current_round(round.round_number) logging.debug('Played round %s' % round.round_number) - return round \ No newline at end of file + return round diff --git a/wouso/games/grandchallenge/tests.py b/wouso/games/grandchallenge/tests.py index fdf6e972..0afcd2bf 100644 --- a/wouso/games/grandchallenge/tests.py +++ b/wouso/games/grandchallenge/tests.py @@ -22,7 +22,7 @@ def test_start_gc(self): GrandChallengeGame.start() self.assertTrue(GrandChallengeGame.is_started()) - c = Challenge.objects.filter(Q(user_from__user=u1, user_to__user=u2)|Q(user_from__user=u2, user_to__user=u1)) + c = Challenge.objects.filter(Q(user_from__user=u1, user_to__user=u2) | Q(user_from__user=u2, user_to__user=u1)) self.assertEqual(c.count(), 1) def _simulate_n_users(self, n): @@ -69,6 +69,7 @@ def test_16_players(self): self._simulate_n_users(17) self.assertEqual(GrandChallengeGame.get_winner().id, self._get_player(1).id) + class GCUserTest(WousoTest): def setUp(self): Challenge.LIMIT = 0 @@ -92,4 +93,4 @@ def test_get_challenges_active_and_played(self): self.assertEqual(gc1.get_active().count(), 0) self.assertEqual(gc2.get_active().count(), 0) self.assertEqual(gc1.get_played().count(), 1) - self.assertEqual(gc2.get_played().count(), 1) \ No newline at end of file + self.assertEqual(gc2.get_played().count(), 1) diff --git a/wouso/games/grandchallenge/urls.py b/wouso/games/grandchallenge/urls.py index 01445b5e..ab057b29 100644 --- a/wouso/games/grandchallenge/urls.py +++ b/wouso/games/grandchallenge/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * from django.conf import settings -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', 'games.grandchallenge.views.index', name='gc_index_view'), ) diff --git a/wouso/games/grandchallenge/views.py b/wouso/games/grandchallenge/views.py index 51a0718e..7e0805ea 100644 --- a/wouso/games/grandchallenge/views.py +++ b/wouso/games/grandchallenge/views.py @@ -2,10 +2,11 @@ from django.contrib.auth.decorators import login_required from django.shortcuts import render, render_to_response from django.template import RequestContext -from models import GrandChallengeGame, GrandChallengeUser +from models import GrandChallengeGame, GrandChallengeUser from wouso.core.ui import register_sidebar_block from wouso.interface import render_string + @login_required def index(request): """ Shows all rounds played by the current user """ @@ -15,13 +16,15 @@ def index(request): active = gc_user.get_active() played = gc_user.get_played() - if not gc_user in GrandChallengeGame.base_query(): + if gc_user not in GrandChallengeGame.base_query(): messages.error(request, _('We are sorry, you are not part of the tournament')) return render(request, 'grandchallenge/message.html') - return render_to_response('grandchallenge/index.html', - {'active': active, 'played': played, 'gcuser': gc_user, 'gc': GrandChallengeGame}, - context_instance=RequestContext(request)) + return render_to_response( + 'grandchallenge/index.html', + {'active': active, 'played': played, 'gcuser': gc_user, 'gc': GrandChallengeGame}, + context_instance=RequestContext(request)) + def sidebar_widget(context): user = context.get('user', None) @@ -31,4 +34,5 @@ def sidebar_widget(context): gc_user = user.get_profile().get_extension(GrandChallengeUser) return render_string('grandchallenge/sidebar.html', {'gc': gc, 'gcuser': gc_user, 'id': 'grandchallenge'}) -register_sidebar_block('grandchallenge', sidebar_widget) \ No newline at end of file + +register_sidebar_block('grandchallenge', sidebar_widget) diff --git a/wouso/games/qotd/api.py b/wouso/games/qotd/api.py index 77c2b486..d133dee6 100644 --- a/wouso/games/qotd/api.py +++ b/wouso/games/qotd/api.py @@ -39,4 +39,4 @@ def create(self, request): return {'success': False, 'error': 'Invalid answer'} else: qotduser.set_answered(answer.id, answer.correct) - return {'success': True, 'correct': answer.correct, 'has_answered': qotduser.has_answered} \ No newline at end of file + return {'success': True, 'correct': answer.correct, 'has_answered': qotduser.has_answered} diff --git a/wouso/games/qotd/feeds.py b/wouso/games/qotd/feeds.py index 27eaa603..c3a3d681 100644 --- a/wouso/games/qotd/feeds.py +++ b/wouso/games/qotd/feeds.py @@ -8,7 +8,7 @@ class LatestQuestionsFeed(Feed): description = "WoUSO Question of the Day" def items(self): - #return Question.objects.order_by('-date')[:5] + # return Question.objects.order_by('-date')[:5] return Question.objects.all()[:5] def item_title(self, item): @@ -19,4 +19,3 @@ def item_description(self, item): def item_link(self): return "/qotd/" - diff --git a/wouso/games/qotd/models.py b/wouso/games/qotd/models.py index deb58d25..681a80b3 100644 --- a/wouso/games/qotd/models.py +++ b/wouso/games/qotd/models.py @@ -66,7 +66,7 @@ def reset_answered(self): @property def has_answered(self): """ Check if last_answered was today """ - #TODO: test this + # TODO: test this if self.last_answered is None: return False else: @@ -155,4 +155,5 @@ def get_history(cls): qs = Schedule.objects.filter(day__lte=today).order_by('-day')[:7] return qs + register_category(QotdGame.QPOOL_CATEGORY, QotdGame) diff --git a/wouso/games/qotd/tests.py b/wouso/games/qotd/tests.py index 821d35fd..e5e5d660 100644 --- a/wouso/games/qotd/tests.py +++ b/wouso/games/qotd/tests.py @@ -10,6 +10,7 @@ from wouso.core import scoring from wouso.core.qpool.models import Question, Schedule, Tag, Category + class QotdTestCase(WousoTest): def setUp(self): super(QotdTestCase, self).setUp() @@ -21,8 +22,12 @@ def setUp(self): def _get_foo_question(self, correct=2): """ Return a Question object selected for Today """ - class Question: pass - class Answer: pass + class Question: + pass + + class Answer: + pass + q = Question() q.text = 'How many' q.answers = [] @@ -33,7 +38,7 @@ class Answer: pass return q def testUserCreate(self): - user,new = User.objects.get_or_create(username='_test2') + user, new = User.objects.get_or_create(username='_test2') profile = user.get_profile() @@ -73,16 +78,18 @@ def test_multiple_qotd(self): a = QotdGame.get_for_today() self.assertTrue(a in (q1, q2)) + def _make_question_for_today(user, text): category = Category(name='qotd') question = Question(text=text, proposed_by=user, category=category, active=1) question.save() for i in range(4): - Answer.objects.create(question=question, correct=i==1, text='a %d'%i) + Answer.objects.create(question=question, correct=i == 1, text='a %d' % i) sched = Schedule(question=question) sched.save() return question + class PageTests(WousoTest): def setUp(self): super(PageTests, self).setUp() @@ -153,7 +160,7 @@ def test_answer_qotd(self): response = self.client.post('/api/qotd/today/', {'answer': wrong.id}) data = json.loads(response.content) - self.assertFalse(data['success']) # because already answered + self.assertFalse(data['success']) # because already answered self.assertEqual(data['error'], 'User already answered') qotduser.reset_answered() @@ -163,6 +170,7 @@ def test_answer_qotd(self): self.assertTrue(data['success']) self.assertFalse(data['correct']) + class TestQotdViews(WousoTest): def setUp(self): super(TestQotdViews, self).setUp() @@ -175,7 +183,7 @@ def setUp(self): self.c = Client() self.c.login(username='testuser1', password='test') - + def test_qotd_index(self): response = self.c.get(reverse('qotd_index_view')) self.assertContains(response, 'a 1') @@ -188,7 +196,7 @@ def test_qotd_index_submit(self): a_id = Answer.objects.filter(question=self.question)[1].id data = {u'answers': [a_id]} self.c.post(reverse('qotd_index_view'), data) - q_user= QotdUser.objects.get(user__username='testuser1') + q_user = QotdUser.objects.get(user__username='testuser1') initial_last_answered = q_user.last_answered self.assertTrue(initial_last_answered) diff --git a/wouso/games/qotd/urls.py b/wouso/games/qotd/urls.py index 2e4d4d4e..74b51ec6 100644 --- a/wouso/games/qotd/urls.py +++ b/wouso/games/qotd/urls.py @@ -2,7 +2,8 @@ from django.conf import settings from feeds import LatestQuestionsFeed -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', 'games.qotd.views.index', name='qotd_index_view'), url(r'^done/$', 'games.qotd.views.done', name='qotd_done_view'), url(r'^feed/$', LatestQuestionsFeed(), name='qotd_feed_view'), diff --git a/wouso/games/quest/admin.py b/wouso/games/quest/admin.py index 5dcb98da..dded92fb 100644 --- a/wouso/games/quest/admin.py +++ b/wouso/games/quest/admin.py @@ -1,14 +1,17 @@ from django.contrib import admin from models import Quest, QuestUser, QuestResult, FinalQuest + class QUAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'current_quest', 'current_level', 'started_time', 'finished_time') list_filter = ('current_quest', 'current_level', 'finished') + class QRAdmin(admin.ModelAdmin): list_display = ('user', 'quest', 'level') list_filter = ('quest', 'level') + admin.site.register(Quest) admin.site.register(FinalQuest) admin.site.register(QuestResult, QRAdmin) diff --git a/wouso/games/quest/api.py b/wouso/games/quest/api.py index af568d02..ea8dfd67 100644 --- a/wouso/games/quest/api.py +++ b/wouso/games/quest/api.py @@ -4,6 +4,7 @@ from piston.utils import rc from models import Quest, QuestUser + class QuestAdminHandler(BaseHandler): """ Get information about the quest module: a list of quests @@ -41,4 +42,4 @@ def create(self, request, quest_id, username): return rc.NOT_FOUND new_level = quest_user.pass_level(quest) - return {'current_level': new_level, 'user': {'id': quest_user.id, 'username': quest_user.user.username}} \ No newline at end of file + return {'current_level': new_level, 'user': {'id': quest_user.id, 'username': quest_user.user.username}} diff --git a/wouso/games/quest/cpanel.py b/wouso/games/quest/cpanel.py index 55ff5dc1..bd1822e3 100644 --- a/wouso/games/quest/cpanel.py +++ b/wouso/games/quest/cpanel.py @@ -29,8 +29,10 @@ def get_context_data(self, **kwargs): 'module': 'quest'}) return context + quest_home = permission_required('quest.change_quest')(QuestHomeView.as_view()) + @permission_required('quest.change_quest') def quest_edit(request, id=None): if id is not None: @@ -54,6 +56,7 @@ def quest_edit(request, id=None): 'module': 'quest'}, context_instance=RequestContext(request)) + @permission_required('quest.change_quest') def quest_sort(request, id): quest = get_object_or_404(Quest, pk=id) @@ -71,12 +74,13 @@ def quest_sort(request, id): 'module': 'quest'}, context_instance=RequestContext(request)) + @permission_required('quest.change_quest') def final_results(request): final = QuestGame.get_final() if not final: return render_to_response('quest/cpanel_final_results.html', - context_instance=RequestContext(request)) + context_instance=RequestContext(request)) levels = final.fetch_levels() return render_to_response('quest/cpanel_final_results.html', {'quest': final, @@ -84,6 +88,7 @@ def final_results(request): 'levels': levels}, context_instance=RequestContext(request)) + @permission_required('quest.change_quest') def final_score(request): final = QuestGame.get_final() @@ -92,7 +97,8 @@ def final_score(request): return render_to_response('quest/cpanel_final_results.html', {'quest': final, 'done': True}, - context_instance=RequestContext(request)) + context_instance=RequestContext(request)) + @permission_required('quest.change_quest') def create_finale(request): @@ -110,6 +116,7 @@ def quest_bonus(request, id): quest.give_bonus() return redirect('quest_home') + @permission_required('quest.change_quest') def register_results(request, id): quest = get_object_or_404(Quest, pk=id) diff --git a/wouso/games/quest/cpanel_urls.py b/wouso/games/quest/cpanel_urls.py index 54601ca1..b249b320 100644 --- a/wouso/games/quest/cpanel_urls.py +++ b/wouso/games/quest/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.quest.cpanel', +urlpatterns = patterns( + 'wouso.games.quest.cpanel', url(r'^$', 'quest_home', name='quest_home'), url(r'^edit/(?P\d*)/$', 'quest_edit', name='quest_edit'), url(r'^sort/(?P\d*)/$', 'quest_sort', name='quest_sort'), diff --git a/wouso/games/quest/forms.py b/wouso/games/quest/forms.py index 67481885..a52b7418 100644 --- a/wouso/games/quest/forms.py +++ b/wouso/games/quest/forms.py @@ -2,14 +2,16 @@ from models import Quest from bootstrap3_datetime import widgets + class QuestForm(Form): answer = CharField(max_length=4000, widget=TextInput) + class QuestCpanel(ModelForm): class Meta: model = Quest widgets = { - 'start': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}), - 'end': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}) - } + 'start': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}), + 'end': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}) + } exclude = ('order', 'registered',) diff --git a/wouso/games/quest/models.py b/wouso/games/quest/models.py index fc222228..87591c57 100644 --- a/wouso/games/quest/models.py +++ b/wouso/games/quest/models.py @@ -103,8 +103,8 @@ def register_quest_result(self): Create a QuestResult entry for the QuestUser's current quest """ if not self.finished: - qr, created = QuestResult.objects.get_or_create(user=self, - quest=self.current_quest, level=self.current_level) + qr, created = QuestResult.objects.get_or_create( + user=self, quest=self.current_quest, level=self.current_level) def set_current(self, quest): self.started_time = datetime.datetime.now() @@ -294,6 +294,7 @@ def register(self): def __unicode__(self): return "%s - %s %s" % (self.start, self.end, self.title) + class QuestGame(Game): """ Each game must extend Game """ class Meta: @@ -312,12 +313,12 @@ def __init__(self, *args, **kwargs): @classmethod def get_current(cls): try: - quest = FinalQuest.objects.get(start__lte=datetime.datetime.now(), - end__gte=datetime.datetime.now()) + quest = FinalQuest.objects.get(start__lte=datetime.datetime.now(), + end__gte=datetime.datetime.now()) except: try: quest = Quest.objects.get(start__lte=datetime.datetime.now(), - end__gte=datetime.datetime.now()) + end__gte=datetime.datetime.now()) except: quest = None return quest @@ -331,30 +332,32 @@ def get_formulas(kls): """ Returns a list of formulas used by qotd """ fs = [] quest_game = kls.get_instance() - fs.append(dict(name='quest-ok', expression='points={level}', - owner=quest_game.game, - description='Points earned when finishing a level. Arguments: level.') - ) - fs.append(dict(name='quest-finish-ok', expression='points=10', + fs.append(dict( + name='quest-ok', expression='points={level}', owner=quest_game.game, - description='Bonus points earned when finishing the entire quest. No arguments.') - ) - fs.append(dict(name='quest-finish-bonus', expression='points=fib(12 - {position})', + description='Points earned when finishing a level. Arguments: level.' + )) + fs.append(dict( + name='quest-finish-ok', expression='points=10', owner=quest_game.game, + description='Bonus points earned when finishing the entire quest. No arguments.' + )) + fs.append(dict( + name='quest-finish-bonus', expression='points=fib(12 - {position})', owner=quest_game.game, - description='Bonus points earned when finishing a quest. Given to first 10, argument: position.') - ) - fs.append(dict(name='finalquest-ok', expression='points={level}+{level_users}', + description='Bonus points earned when finishing a quest. Given to first 10, argument: position.' + )) + fs.append(dict( + name='finalquest-ok', expression='points={level}+{level_users}', owner=quest_game.game, - description='Bonus points earned when finishing the final quest. Arguments: level, level_users') - ) + description='Bonus points earned when finishing the final quest. Arguments: level, level_users' + )) return fs @classmethod def get_api(kls): from api import QuestAdminHandler, QuestAdminUserHandler return {r'^quest/admin/$': QuestAdminHandler, - r'^quest/admin/quest=(?P\d+)/username=(?P[^/]+)/$': QuestAdminUserHandler - } + r'^quest/admin/quest=(?P\d+)/username=(?P[^/]+)/$': QuestAdminUserHandler} @classmethod def final_exists(cls): @@ -367,8 +370,10 @@ def get_final(cls): except IndexError: return None + register_category(QuestGame.QPOOL_CATEGORY, QuestGame) + class FinalQuest(Quest): def give_level_bonus(self): final = QuestGame.get_final() @@ -381,19 +386,12 @@ def give_level_bonus(self): users = QuestUser.objects.filter(current_quest=final, current_level__gte=level, race__can_play=True) for user in users: - scoring.score( - user, - QuestGame, - self.get_formula('finalquest-ok'), - level=level, - level_users=users.count() - ) + scoring.score(user, QuestGame, self.get_formula('finalquest-ok'), level=level, + level_users=users.count()) signal_msg = ugettext_noop("received bonus for reaching level {level} in the final quest") - signals.addActivity.send(sender=None, user_from=user, - user_to=user, message=signal_msg, - arguments=dict(level=level), - game=QuestGame.get_instance() - ) + signals.addActivity.send(sender=None, user_from=user, user_to=user, + message=signal_msg, arguments=dict(level=level), + game=QuestGame.get_instance()) def fetch_levels(self): levels = [] diff --git a/wouso/games/quest/tests.py b/wouso/games/quest/tests.py index 7d32e993..3108817b 100644 --- a/wouso/games/quest/tests.py +++ b/wouso/games/quest/tests.py @@ -13,6 +13,7 @@ from wouso.core.user.models import Race from wouso.games.quest.cpanel import quest_bonus + class QuestStatistics(WousoTest): def setUp(self): super(QuestStatistics, self).setUp() @@ -27,10 +28,10 @@ def setUp(self): scoring.setup_scoring() category = Category.add('quest') question1 = Question.objects.create(text='question1', answer_type='F', - category=category, active=True) + category=category, active=True) answer1 = Answer.objects.create(text='first answer', correct=True, question=question1) question2 = Question.objects.create(text='question2', answer_type='F', - category=category, active=True) + category=category, active=True) answer2 = Answer.objects.create(text='second answer', correct=True, question=question2) start = datetime.datetime.now() end = datetime.datetime.now() + timedelta(days=1) @@ -47,7 +48,7 @@ def test_check_if_both_players_finished(self): self.quest.check_answer(self.quest_user2, 'second answer') self.assertTrue(self.quest_user1.finished) self.assertTrue(self.quest_user2.finished) - + def test_only_one_player_finished(self): self.quest_user1.current_quest = self.quest self.quest_user2.current_quest = self.quest @@ -55,7 +56,7 @@ def test_only_one_player_finished(self): self.quest.check_answer(self.quest_user1, 'second answer') self.assertTrue(self.quest_user1.finished) self.assertFalse(self.quest_user2.finished) - + def test_players_are_registered_if_they_start_a_quest(self): self.quest_user1.current_quest = self.quest self.quest_user2.current_quest = self.quest @@ -81,6 +82,7 @@ def test_check_for_duplicates(self): self.quest_user1.register_quest_result() self.assertEqual(len(QuestResult.objects.all()), 1) + class QuestTestCase(WousoTest): def setUp(self): super(QuestTestCase, self).setUp() @@ -90,37 +92,37 @@ def setUp(self): profile = self.user.get_profile() self.quest_user = profile.get_extension(QuestUser) scoring.setup_scoring() - + def tearDown(self): - #self.user.delete() + # self.user.delete() pass - + def test_check_answer(self): cat = Category.add('quest') question = Question.objects.create(text='test_q', answer_type='F', category=cat, active=True) answer1 = Answer.objects.create(text='test_a1', correct=True, question=question) answer2 = Answer.objects.create(text='test_a2', correct=True, question=question) - + start = datetime.datetime.now() end = datetime.datetime.now() + timedelta(days=1) quest = Quest.objects.create(start=start, end=end) - + quest.questions.add(question) - + self.assertEqual(quest.count, 1) - + self.quest_user.current_quest = quest - #self.quest_user.current_level = 0 - + # self.quest_user.current_level = 0 + quest.check_answer(self.quest_user, 'Test_a2') - + self.assertTrue(self.quest_user.finished) def test_check_bonus_for_quest(self): category = Category.add('quest') question1 = Question.objects.create(text='question1', answer_type='F', - category=category, active=True) + category=category, active=True) answer1 = Answer.objects.create(text='first answer', correct=True, question=question1) start = datetime.datetime.now() end = datetime.datetime.now() + timedelta(days=1) @@ -138,19 +140,20 @@ def test_check_bonus_for_quest(self): fact = RequestFactory() request = fact.get(reverse('register_results', args=[1])) request.user = admin - - #get initial points + + # get initial points initial_points = pl.points - #add quest bonus + # add quest bonus response = quest_bonus(request, quest.id) - #get final points + # get final points pl = User.objects.get(username=self.user.username) final_points = pl.get_profile().points self.assertTrue(final_points > initial_points) + class TestQuestViews(WousoTest): def setUp(self): super(TestQuestViews, self).setUp() @@ -158,13 +161,13 @@ def setUp(self): self.c = Client() self.c.login(username='admin', password='admin') now = datetime.datetime.now() - Quest.objects.create(start=now-timedelta(days=2), end=now-timedelta(days=1), + Quest.objects.create(start=now - timedelta(days=2), end=now - timedelta(days=1), title='Quest no. 1') self.q = Quest.objects.create(start=now, end=now + timedelta(days=1), - title='Quest no. 2') - Quest.objects.create(start=now+timedelta(days=1), end=now + timedelta(days=2), + title='Quest no. 2') + Quest.objects.create(start=now + timedelta(days=1), end=now + timedelta(days=2), title='Quest no. 3') - FinalQuest.objects.create(start=now, end=now+timedelta(days=1), + FinalQuest.objects.create(start=now, end=now + timedelta(days=1), title='Final Quest') scoring.setup_scoring() @@ -180,14 +183,14 @@ def test_history_view(self): questuser2 = self._get_player(2).get_extension(QuestUser) category = Category.add('quest') question1 = Question.objects.create(text='question1', answer_type='F', - category=category, active=True) + category=category, active=True) answer1 = Answer.objects.create(text='first answer', correct=True, question=question1) self.q.questions.add(question1) questuser1.current_quest = self.q questuser2.current_quest = self.q self.q.check_answer(questuser1, 'first answer') self.q.check_answer(questuser2, 'first answer') - + c = Client() c.login(username='testuser1', password='test') response = c.get(reverse('quest_history')) @@ -199,6 +202,7 @@ def test_history_view(self): # 'testuser2' appears only in overall gods and quest result table self.assertContains(response, '>testuser2<', count=2) + class FinalQuestTestCase(WousoTest): def test_final_bonus(self): u1 = self._get_player(1).get_extension(QuestUser) @@ -214,9 +218,9 @@ def test_final_bonus(self): question = Question.objects.create(text='test', answer_type='F') final.questions.add(question) - u1.current_level = 1; u1.race = r; u1.current_quest = final + u1.current_level, u1.race, u1.current_quest = 1, r, final u1.save() - u2.current_level = 1; u2.race = r; u2.current_quest = final + u2.current_level, u2.race, u2.current_quest = 1, r, final u2.save() final.give_level_bonus() u1 = QuestUser.objects.get(pk=u1.pk) @@ -250,9 +254,9 @@ def test_final_quest_results_view(self): question = Question.objects.create(text='test', answer_type='F') final.questions.add(question) - u1.current_level = 1; u1.race = r; u1.current_quest = final + u1.current_level, u1.race, u1.current_quest = 1, r, final u1.save() - u2.current_level = 1; u2.race = r; u2.current_quest = final + u2.current_level, u2.race, u2.current_quest = 1, r, final u2.save() c = Client() @@ -262,11 +266,12 @@ def test_final_quest_results_view(self): self.assertContains(response, 'testuser1') self.assertContains(response, 'testuser2') + # API tests class QuestAPITestCase(WousoTest): def test_info(self): quser = self._get_player(1).get_extension(QuestUser) - quest = Quest.objects.create(start=datetime.datetime.now(), end=datetime.datetime.now()+timedelta(days=1)) + quest = Quest.objects.create(start=datetime.datetime.now(), end=datetime.datetime.now() + timedelta(days=1)) quser.set_current(quest) self._client_superuser() @@ -277,7 +282,7 @@ def test_info(self): def test_level_increment(self): quser = self._get_player(1).get_extension(QuestUser) - quest = Quest.objects.create(start=datetime.datetime.now(), end=datetime.datetime.now()+timedelta(days=1)) + quest = Quest.objects.create(start=datetime.datetime.now(), end=datetime.datetime.now() + timedelta(days=1)) quser.set_current(quest) formula = Formula.add('quest-ok') diff --git a/wouso/games/quest/tests/task-00/check b/wouso/games/quest/tests/task-00/check index efcc90d2..06c7bf76 100755 --- a/wouso/games/quest/tests/task-00/check +++ b/wouso/games/quest/tests/task-00/check @@ -9,4 +9,4 @@ if len(sys.argv) < 3: if sys.argv[1] == sys.argv[2]: sys.exit(0) -sys.exit(1) \ No newline at end of file +sys.exit(1) diff --git a/wouso/games/quest/urls.py b/wouso/games/quest/urls.py index cd6f3c7b..838640cd 100644 --- a/wouso/games/quest/urls.py +++ b/wouso/games/quest/urls.py @@ -1,7 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.quest.views', +urlpatterns = patterns( + 'wouso.games.quest.views', url(r'^$', 'index', name='quest_index_view'), url(r'^history/$', 'history', name='quest_history'), ) - diff --git a/wouso/games/quest/views.py b/wouso/games/quest/views.py index 32ce46c1..2e3b6dfd 100644 --- a/wouso/games/quest/views.py +++ b/wouso/games/quest/views.py @@ -16,7 +16,7 @@ def index(request): quest = QuestGame.get_current() - if quest == None: + if quest is None: return render_to_response('quest/none.html', context_instance=RequestContext(request)) quest_user = request.user.get_profile().get_extension(QuestUser) @@ -39,9 +39,10 @@ def index(request): form = QuestForm() - return render_to_response('quest/index.html', - {'quest': quest, 'progress': quest_user, 'form': form, 'error': error}, - context_instance=RequestContext(request)) + return render_to_response( + 'quest/index.html', + {'quest': quest, 'progress': quest_user, 'form': form, 'error': error}, + context_instance=RequestContext(request)) def sidebar_widget(context): @@ -49,7 +50,7 @@ def sidebar_widget(context): quest = QuestGame.get_current() if quest is None or user is None or not user.is_authenticated(): - return '' + return '' quest_user = user.get_profile().get_extension(QuestUser) if not quest_user.started: @@ -59,14 +60,16 @@ def sidebar_widget(context): if quest_user.finished and (quest_user.is_current(quest)): time_passed = datetime.now() - quest_user.finished_time - if time_passed > timedelta(seconds=600): # ten minutes + if time_passed > timedelta(seconds=600): # ten minutes return '' - return render_to_string('quest/sidebar.html', - {'quest': quest, 'quser': quest_user, - 'quest_progress': quest_progress, - 'id': 'quest' - }) + return render_to_string( + 'quest/sidebar.html', + {'quest': quest, 'quser': quest_user, + 'quest_progress': quest_progress, + 'id': 'quest'}) + + register_sidebar_block('quest', sidebar_widget) diff --git a/wouso/games/quiz/cpanel_urls.py b/wouso/games/quiz/cpanel_urls.py index 29b2964b..015ba664 100644 --- a/wouso/games/quiz/cpanel_urls.py +++ b/wouso/games/quiz/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.games.quiz.cpanel_views', +urlpatterns = patterns( + 'wouso.games.quiz.cpanel_views', url(r'^$', 'list_quizzes', name='list_quizzes'), url(r'^add_quiz/$', 'add_quiz', name='add_quiz'), url(r'^edit_quiz/(?P\d+)/$', 'edit_quiz', name='edit_quiz'), diff --git a/wouso/games/quiz/forms.py b/wouso/games/quiz/forms.py index 761c403d..ea3b3014 100644 --- a/wouso/games/quiz/forms.py +++ b/wouso/games/quiz/forms.py @@ -36,7 +36,7 @@ def get_response(self): adding an empty list to dic in this case""" for field in self.visible_fields(): id = int(field.html_name[len('answer_'):]) - if not res.has_key(id): + if id not in res: res[id] = [] return res @@ -63,8 +63,7 @@ class Meta: model = Quiz widgets = {'start': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}), - 'end': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"}) - } + 'end': widgets.DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss"})} exclude = ['owner', 'players', 'status', 'tags'] def __init__(self, *args, **kwargs): diff --git a/wouso/games/quiz/models.py b/wouso/games/quiz/models.py index 008eed02..8c67259f 100644 --- a/wouso/games/quiz/models.py +++ b/wouso/games/quiz/models.py @@ -12,15 +12,15 @@ from wouso.core.signals import add_activity from wouso.core.user.models import Player from wouso.core.game.models import Game -from wouso.core.qpool import register_category,\ -get_questions_with_tag_and_category +from wouso.core.qpool import \ + register_category, get_questions_with_tag_and_category from wouso.core.qpool.models import Question, Tag class QuizCategory(models.Model): name = models.CharField(max_length=100, unique=True) - logo = models.ImageField(upload_to=\ - settings.MEDIA_ARTIFACTS_DIR, null=True, blank=True) + logo = models.ImageField(upload_to=settings.MEDIA_ARTIFACTS_DIR, + null=True, blank=True) @property def quizzes(self): @@ -28,8 +28,9 @@ def quizzes(self): @property def logo_url(self): - return os.path.join(settings.MEDIA_ARTIFACTS_URL,\ - os.path.basename(str(self.logo))) if self.logo else "" + return os.path.join( + settings.MEDIA_ARTIFACTS_URL, + os.path.basename(str(self.logo))) if self.logo else "" def __unicode__(self): return self.name @@ -121,8 +122,8 @@ def calculate_reward(self, responses): for question_id, checked_answer_id in responses.iteritems(): question = Question.objects.get(id=question_id) - correct_answer_id = [ans.id \ - for ans in question.answers if ans.correct] + correct_answer_id = [ans.id for ans in question.answers + if ans.correct] if checked_answer_id == correct_answer_id: correct_count += 1 @@ -161,15 +162,15 @@ class QuizUser(Player): def active_quizzes(self): # Active public quizzes through = UserToQuiz.objects.filter(user=self) - active_quizzes = [t for t in through \ - if t.quiz.is_active() and t.quiz.is_public()] + active_quizzes = [t for t in through + if t.quiz.is_active() and t.quiz.is_public()] return active_quizzes @property def inactive_quizzes(self): through = UserToQuiz.objects.filter(user=self) - inactive_quizzes = [t for t in through \ - if t.quiz.is_inactive() and t.quiz.is_public()] + inactive_quizzes = [t for t in through + if t.quiz.is_inactive() and t.quiz.is_public()] return inactive_quizzes @property @@ -213,8 +214,8 @@ def all_attempts(self): def best_attempt(self): if self.all_attempts.count() == 0: return None - return sorted(self.all_attempts, \ - key=lambda x: x.points, reverse=True)[0] + return sorted(self.all_attempts, + key=lambda x: x.points, reverse=True)[0] @property def last_attempt(self): @@ -246,17 +247,19 @@ def _give_bonus(self, points, gold): gold = gold - self.best_attempt.gold scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) - add_activity(self.user, _('received {points} points and ' - '{gold} gold bonus'' for beating his/her ' - 'highscore at quiz {quiz_name}'), - points=points, gold=gold, quiz_name=self.quiz.name) + add_activity( + self.user, + _('received {points} points and {gold} gold bonus ' + 'for beating his/her highscore at quiz {quiz_name}'), + points=points, gold=gold, quiz_name=self.quiz.name) else: scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) - add_activity(self.user, _('received {points} points' - ' and {gold} gold bonus' - ' for submitting quiz {quiz_name}'), - points=points, gold=gold, quiz_name=self.quiz.name) + add_activity( + self.user, + _('received {points} points and {gold} gold bonus ' + ' for submitting quiz {quiz_name}'), + points=points, gold=gold, quiz_name=self.quiz.name) def time_left(self): now = datetime.now() @@ -292,24 +295,24 @@ def is_played(self): def can_play_again(self): if self.all_attempts.count(): - return (datetime.now() - self.last_attempt.date).days\ - >= self.quiz.another_chance + return (datetime.now() - + self.last_attempt.date).days >= self.quiz.another_chance return True @property def days_until_can_replay(self): if self.can_play_again(): return 0 - return self.quiz.another_chance - \ - (datetime.now() - self.last_attempt.date).days + return self.quiz.another_chance - (datetime.now() - + self.last_attempt.date).days class QuizAttempt(models.Model): """ Stores information about each quiz attempt """ - user_to_quiz = models.ForeignKey(UserToQuiz, \ - related_name='attempts', blank=True, null=True) + user_to_quiz = models.ForeignKey(UserToQuiz, related_name='attempts', + blank=True, null=True) date = models.DateTimeField(auto_now_add=True, default=True, null=True) results = models.TextField(blank=True, null=True) points = models.IntegerField(default=-1) diff --git a/wouso/games/quiz/urls.py b/wouso/games/quiz/urls.py index 20045047..617414e7 100644 --- a/wouso/games/quiz/urls.py +++ b/wouso/games/quiz/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.quiz.views', +urlpatterns = patterns( + 'wouso.games.quiz.views', url(r'^$', 'index', name='quiz_index_view'), url(r'^cat/(?P\d+)/$', 'category', name='quiz_category_view'), url(r'^(?P\d+)/$', 'quiz', name='quiz_view'), diff --git a/wouso/games/specialchallenge/cpanel_urls.py b/wouso/games/specialchallenge/cpanel_urls.py index 1cb2e012..30a2b982 100644 --- a/wouso/games/specialchallenge/cpanel_urls.py +++ b/wouso/games/specialchallenge/cpanel_urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * from cpanel_views import * -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', CpanelHome.as_view(), name='sc_home'), url(r'^challenge/(?P\d+)/$', CpanelChallenge.as_view(), name='sc_challenge'), ) diff --git a/wouso/games/specialchallenge/cpanel_views.py b/wouso/games/specialchallenge/cpanel_views.py index 1c51245f..9fe0fbc6 100644 --- a/wouso/games/specialchallenge/cpanel_views.py +++ b/wouso/games/specialchallenge/cpanel_views.py @@ -28,4 +28,4 @@ def form_valid(self, form): return redirect(self.get_success_url()) def get_success_url(self): - return reverse('sc_home') \ No newline at end of file + return reverse('sc_home') diff --git a/wouso/games/specialchallenge/forms.py b/wouso/games/specialchallenge/forms.py index 428a5c03..11d48ab7 100644 --- a/wouso/games/specialchallenge/forms.py +++ b/wouso/games/specialchallenge/forms.py @@ -26,12 +26,12 @@ def __init__(self, data=None, instance=None, **kwargs): data = data if data else {} if instance is None: for i in range(self.DEFAULT_ANSWERS): - self.fields['answer_%d' % i] = forms.CharField(max_length=400, required=False, initial=data.get('answer_%d' %i, '')) - self.fields['correct_%d' % i] = forms.BooleanField(required=False, label="Correct?", initial=data.get('correct_%d' %i, False)) + self.fields['answer_%d' % i] = forms.CharField(max_length=400, required=False, initial=data.get('answer_%d' % i, '')) + self.fields['correct_%d' % i] = forms.BooleanField(required=False, label="Correct?", initial=data.get('correct_%d' % i, False)) else: for i, a in enumerate(instance.answers): - self.fields['answer_%d' % i] = forms.CharField(max_length=400, required=False, initial=data.get('answer_%d' %i, a.text)) - self.fields['correct_%d' % i] = forms.BooleanField(required=False, label="Correct?", initial=data.get('correct_%d' %i, a.correct)) + self.fields['answer_%d' % i] = forms.CharField(max_length=400, required=False, initial=data.get('answer_%d' % i, a.text)) + self.fields['correct_%d' % i] = forms.BooleanField(required=False, label="Correct?", initial=data.get('correct_%d' % i, a.correct)) self.fields['answer_new'] = forms.CharField(max_length=400, required=False, initial=data.get('answer_new', '')) self.fields['correct_new'] = forms.BooleanField(required=False, label="Correct?", initial=data.get('correct_new', False)) @@ -59,4 +59,4 @@ def save(self, commit=True): if a_text: Answer.objects.create(question=question, text=a_text, correct=a_correct) - return question \ No newline at end of file + return question diff --git a/wouso/games/specialchallenge/models.py b/wouso/games/specialchallenge/models.py index 773477fb..7e675fa3 100644 --- a/wouso/games/specialchallenge/models.py +++ b/wouso/games/specialchallenge/models.py @@ -16,6 +16,7 @@ STATUS_PLAYABLE, STATUS_DONE) = range(6) + class SpecialChallenge(models.Model): STATUSES = ( (STATUS_NEW, _('New, editing')), @@ -70,7 +71,6 @@ def update_challenge(self): self.status = STATUS_PLAYABLE self.save() - def __unicode__(self): return u"#%d against %s" % (self.id, self.player_to) @@ -85,7 +85,7 @@ def get_result(self): result = (self.challenge.user_to, self.challenge.user_from) elif self.challenge.user_from.score > self.challenge.user_to.score: result = (self.challenge.user_from, self.challenge.user_to) - else: #draw game + else: # draw game result = 'draw' return result @@ -120,5 +120,6 @@ def get_sidebar_widget(kls, context): def get_manager(cls, challenge): return SpecialChallengeManager(challenge) + register_category(SpecialChallengeGame.QPOOL_CATEGORY, SpecialChallengeGame) -register_sidebar_block('specialchallenge', SpecialChallengeGame.get_sidebar_widget) \ No newline at end of file +register_sidebar_block('specialchallenge', SpecialChallengeGame.get_sidebar_widget) diff --git a/wouso/games/specialchallenge/tests.py b/wouso/games/specialchallenge/tests.py index 2b12d0d9..0ea4897b 100644 --- a/wouso/games/specialchallenge/tests.py +++ b/wouso/games/specialchallenge/tests.py @@ -1,6 +1,7 @@ from wouso.core.tests import WousoTest from models import SpecialChallenge + class SpecialChallengeTest(WousoTest): def test_challenge_run(self): p1, p2 = self._get_player(1), self._get_player(2) @@ -14,5 +15,5 @@ def test_challenge_run(self): # fake play c.real_challenge.set_won_by_player(p1) # check status - c = SpecialChallenge.objects.get(pk=c.pk) #refresh - self.assertTrue(c.is_played()) \ No newline at end of file + c = SpecialChallenge.objects.get(pk=c.pk) # refresh + self.assertTrue(c.is_played()) diff --git a/wouso/games/specialchallenge/urls.py b/wouso/games/specialchallenge/urls.py index 237de7dc..30090a34 100644 --- a/wouso/games/specialchallenge/urls.py +++ b/wouso/games/specialchallenge/urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * from views import * -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', IndexView.as_view(), name='specialchallenge_index'), url(r'^create/$', CreateChallenge.as_view(), name='specialchallenge_create'), url(r'^challenge/(?P\d+)/$', ChallengeView.as_view(), name='specialchallenge_challenge'), diff --git a/wouso/games/specialchallenge/views.py b/wouso/games/specialchallenge/views.py index 3f5deb01..e6eb2776 100644 --- a/wouso/games/specialchallenge/views.py +++ b/wouso/games/specialchallenge/views.py @@ -55,6 +55,7 @@ def dispatch(self, request, *args, **kwargs): return redirect('specialchallenge_index') return super(ChallengeMixin, self).dispatch(request, *args, **kwargs) + class ChallengeQuestionAdd(ChallengeMixin, FormView): template_name = 'specialchallenge/challenge_add_question.html' form_class = QuestionForm diff --git a/wouso/games/specialquest/cpanel.py b/wouso/games/specialquest/cpanel.py index 98cf45f9..5e28415a 100644 --- a/wouso/games/specialquest/cpanel.py +++ b/wouso/games/specialquest/cpanel.py @@ -13,6 +13,7 @@ from models import SpecialQuestTask, SpecialQuestUser, SpecialQuestGame, SpecialQuestGroup from forms import TaskForm + class HomeView(ListView): model = SpecialQuestTask template_name = 'specialquest/cpanel_home.html' @@ -27,7 +28,7 @@ class GroupsView(ListView): template_name = 'specialquest/cpanel_groups.html' context_object_name = 'groups' - + groups = permission_required('specialquest.change_specialquestuser')(GroupsView.as_view()) @@ -92,16 +93,16 @@ def manage_player(request, player_id): message = 'Successfully given bonus' if request.POST.get('comment', None): signal_msg = ugettext_noop('received {gold} gold bonus for {comment}') - signals.addActivity.send(sender=None, user_from=player, user_to=player, message=signal_msg, - arguments=dict(gold=amount, comment=request.POST['comment']), - game=SpecialQuestGame.get_instance() - ) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, message=signal_msg, + arguments=dict(gold=amount, comment=request.POST['comment']), + game=SpecialQuestGame.get_instance()) else: error = 'Invalid amount' elif request.POST.get('points', False): try: amount = int(request.POST.get('points', 0)) - #assert amount > 0 + # assert amount > 0 except (ValueError, AssertionError): error = 'Invalid amount' else: @@ -116,10 +117,10 @@ def manage_player(request, player_id): if messages: messages.success(request, message) - return render_to_response('specialquest/cpanel_manage.html', - dict(mplayer=player, tasks_not_done=tasks_not_done, - bonuses=bonuses, penalties=penalties), - context_instance=RequestContext(request)) + return render_to_response( + 'specialquest/cpanel_manage.html', + dict(mplayer=player, tasks_not_done=tasks_not_done, bonuses=bonuses, penalties=penalties), + context_instance=RequestContext(request)) @permission_required('specialquest.change_specialquestuser') @@ -137,14 +138,14 @@ def manage_player_set(request, player_id, task_id): for member in members: if task not in member.done_tasks.all(): member.done_tasks.add(task) - scoring.score(member, SpecialQuestGame, 'specialquest-passed',external_id=task.id, value=task.value) + scoring.score(member, SpecialQuestGame, 'specialquest-passed', external_id=task.id, value=task.value) signal_msg = ugettext_noop('completed special quest {task_name} and earned {value} gold') action_msg = 'specialq-ok-gold' - signals.addActivity.send(sender=None, user_from=member, \ - user_to=member, \ + signals.addActivity.send(sender=None, user_from=member, + user_to=member, message=signal_msg, - arguments=dict(task_name=task.name, value=task.value), \ + arguments=dict(task_name=task.name, value=task.value), game=SpecialQuestGame.get_instance(), action=action_msg) diff --git a/wouso/games/specialquest/cpanel_urls.py b/wouso/games/specialquest/cpanel_urls.py index 7071d41d..8af8289c 100644 --- a/wouso/games/specialquest/cpanel_urls.py +++ b/wouso/games/specialquest/cpanel_urls.py @@ -1,14 +1,15 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.specialquest.cpanel', +urlpatterns = patterns( + 'wouso.games.specialquest.cpanel', url(r'^$', 'home', name='specialquest_home'), url(r'^groups/$', 'groups', name='specialquest_cpanel_groups'), url(r'^groups/edit/(?P\d+)/$', 'group_edit', name='specialquest_group_edit'), - + url(r'^groups/(?P\d+)/toggle/$', 'group_active_toggle', name='specialquest_cpanel_group_toggle'), url(r'^groups/(?P\d+)/edit/(?P\d+)/$', 'group_drop_player', name='specialquest_cpanel_drop'), url(r'^groups/(?P\d+)/destroy/$', 'group_delete', name='specialquest_cpanel_group_delete'), - + url(r'^edit/(?P\d*)/$', 'edit', name='specialquest_edit'), url(r'^new/$', 'edit', name='specialquest_new'), url(r'^delete/{0,1}$', 'delete', name='specialquest_delete_none'), diff --git a/wouso/games/specialquest/forms.py b/wouso/games/specialquest/forms.py index 0a98e92c..238d8c71 100644 --- a/wouso/games/specialquest/forms.py +++ b/wouso/games/specialquest/forms.py @@ -2,10 +2,9 @@ from django.forms.fields import DateField from models import SpecialQuestTask + class TaskForm(ModelForm): class Meta: model = SpecialQuestTask widgets = {'start_date': TextInput(attrs={'placeholder': 'yyyy-mm-dd'}), 'end_date': TextInput(attrs={'placeholder': 'yyyy-mm-dd'})} - - diff --git a/wouso/games/specialquest/tests.py b/wouso/games/specialquest/tests.py index ff1ee74d..acd7c04c 100644 --- a/wouso/games/specialquest/tests.py +++ b/wouso/games/specialquest/tests.py @@ -9,16 +9,17 @@ from wouso.core import scoring from models import SpecialQuestUser, SpecialQuestGroup, SpecialQuestGame, SpecialQuestTask + class TestSpecialQuestViews(WousoTest): def setUp(self): self.user = self._get_player(1).get_extension(SpecialQuestUser) self.admin = self._get_superuser() start = datetime.now() end = start + timedelta(days=1) - self.special_quest1= SpecialQuestTask.objects.create(start_date=start, end_date=end, - name='special_quest1', value=400) - self.special_quest2= SpecialQuestTask.objects.create(start_date=start, end_date=end, - name='special_quest2', value=800) + self.special_quest1 = SpecialQuestTask.objects.create( + start_date=start, end_date=end, name='special_quest1', value=400) + self.special_quest2 = SpecialQuestTask.objects.create( + start_date=start, end_date=end, name='special_quest2', value=800) self.c = Client() def test_cpanel_home_view(self): @@ -102,7 +103,7 @@ def test_profile_page_button(self): # Button 'Invite' is displayed response = self.c.get(reverse('player_profile', args=[user2.pk])) self.assertContains(response, 'Invite in my Special Quest group') - + # Button 'Special mate' is displayed user2.group = new_group user2.save() @@ -152,7 +153,7 @@ def test_remove_user(self): group.remove(p.special_user) p = User.objects.get(username='_test_member') p.special_user = p.get_profile().get_extension(SpecialQuestUser) - self.assertTrue(p.special_user.group == None) + self.assertTrue(p.special_user.group is None) group = SpecialQuestGroup.objects.get(name='le group') self.assertFalse(p.get_profile() in group.players.all()) diff --git a/wouso/games/specialquest/urls.py b/wouso/games/specialquest/urls.py index 4817370e..75521b44 100644 --- a/wouso/games/specialquest/urls.py +++ b/wouso/games/specialquest/urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * from django.conf import settings -urlpatterns = patterns('wouso.games.specialquest.views', +urlpatterns = patterns( + 'wouso.games.specialquest.views', url(r'^$', 'index', name='specialquest_index_view'), url(r'^task/(?P\d+)/$', 'task', name='specialquest_task_view'), diff --git a/wouso/games/urls.py b/wouso/games/urls.py index 1b5d660f..dd24a3ef 100644 --- a/wouso/games/urls.py +++ b/wouso/games/urls.py @@ -5,10 +5,9 @@ from django.conf import settings -upat = [url(r'^$', 'views.games', name='games'),] +upat = [url(r'^$', 'views.games', name='games'), ] for g in get_games(): upat.append((r'^{game}/'.format(game=g), include('games.{game}.urls'.format(game=g)))) urlpatterns = patterns('games', *upat) - diff --git a/wouso/games/views.py b/wouso/games/views.py index 842d6310..408615b1 100644 --- a/wouso/games/views.py +++ b/wouso/games/views.py @@ -4,14 +4,14 @@ from wouso.core.game.models import Game from wouso.interface import logger + def games(request): """ List of games """ wgs = [] for model in get_games(): wgs.append({'link': model._meta.app_label, - 'name': model._meta.verbose_name} - ) + 'name': model._meta.verbose_name}) return render_to_response('interface/games.html', - {'games': wgs}, - context_instance=RequestContext(request)) + {'games': wgs}, + context_instance=RequestContext(request)) diff --git a/wouso/games/workshop/admin.py b/wouso/games/workshop/admin.py index 8e72f30c..d3e20a19 100644 --- a/wouso/games/workshop/admin.py +++ b/wouso/games/workshop/admin.py @@ -6,9 +6,11 @@ admin.site.register(Assessment) admin.site.register(Workshop) + class RAdmin(admin.ModelAdmin): list_filter = ('answer__assessment', 'answer__assessment__workshop', 'answer', 'reviewer') list_display = ('id', 'workshop', 'reviewer', 'feedback', 'answer_grade', 'review_grade') + admin.site.register(Review, RAdmin) -admin.site.register(Answer) \ No newline at end of file +admin.site.register(Answer) diff --git a/wouso/games/workshop/cpanel.py b/wouso/games/workshop/cpanel.py index c11d9c64..e8a5a764 100644 --- a/wouso/games/workshop/cpanel.py +++ b/wouso/games/workshop/cpanel.py @@ -40,13 +40,14 @@ def __init__(self, data=None, **kwargs): @staff_required def workshop_home(request, **kwargs): - return render_to_response('workshop/cpanel/index.html', - {'module': 'workshop', - 'days': DAY_CHOICES, - 'semigroups': Semigroup.objects.all().order_by('name'), - 'hours': range(MIN_HOUR, MAX_HOUR + 2, 2), - 'info': WorkshopGame}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/index.html', + {'module': 'workshop', + 'days': DAY_CHOICES, + 'semigroups': Semigroup.objects.all().order_by('name'), + 'hours': range(MIN_HOUR, MAX_HOUR + 2, 2), + 'info': WorkshopGame}, + context_instance=RequestContext(request) ) @@ -65,6 +66,7 @@ def get_context_data(self, **kwargs): context.update({'module': 'workshop'}) return context + add_group = staff_required(AddGroupView.as_view()) @@ -85,8 +87,10 @@ def get_context_data(self, **kwargs): context.update({'module': 'workshop', 'instance': self.get_object()}) return context + edit_group = staff_required(EditGroupView.as_view()) + @staff_required def edit_spot(request, day, hour): day, hour = int(day), int(hour) @@ -104,13 +108,13 @@ def edit_spot(request, day, hour): else: semigroup.add_player(player) - return render_to_response('workshop/cpanel/editspot.html', - {'module': 'workshop', - 'semigroups': sgs, - }, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/editspot.html', + {'module': 'workshop', 'semigroups': sgs}, + context_instance=RequestContext(request) ) + @staff_required def kick_off(request, player): player = get_object_or_404(Player, pk=player) @@ -121,16 +125,18 @@ def kick_off(request, player): return redirect('workshop_home') + @staff_required def schedule(request): schedules = Schedule.objects.all().order_by('start_date', 'name') - return render_to_response('workshop/cpanel/schedule.html', - {'module': 'workshop', - 'schedules': schedules, - 'category': WorkshopGame.get_question_category(), - 'page': 'schedule'}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/schedule.html', + {'module': 'workshop', + 'schedules': schedules, + 'category': WorkshopGame.get_question_category(), + 'page': 'schedule'}, + context_instance=RequestContext(request) ) @@ -159,6 +165,7 @@ def get_context_data(self, **kwargs): 'page': 'schedule'}) return context + schedule_change = staff_required(ScheduleChangeView.as_view()) @@ -173,11 +180,13 @@ def get_queryset(self): def get_context_data(self, **kwargs): context = super(WorkshopList, self).get_context_data(**kwargs) - context.update({'module': 'workshop', 'page': 'workshops', 'info': WorkshopGame, - 'integrity_check': self.request.GET.get('integrity_check', False) + context.update({ + 'module': 'workshop', 'page': 'workshops', 'info': WorkshopGame, + 'integrity_check': self.request.GET.get('integrity_check', False) }) return context + workshops = staff_required(WorkshopList.as_view()) @@ -210,6 +219,7 @@ def workshop_update_grades(request, workshop): return redirect('ws_reviewers_map', workshop=workshop.id) + @staff_required def workshop_reviewers(request, workshop): workshop = get_object_or_404(Workshop, pk=workshop) @@ -219,14 +229,15 @@ def workshop_reviewers(request, workshop): assessments = workshop.assessment_set.all().order_by('player__user__last_name', 'player__user__first_name') - return render_to_response('workshop/cpanel/workshop_map.html', - {'module': 'workshop', - 'workshop': workshop, - 'assessments': assessments, - 'page': 'workshops', - 'integrity_check': request.GET.get('integrity_check', False), - }, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/workshop_map.html', + {'module': 'workshop', + 'workshop': workshop, + 'assessments': assessments, + 'page': 'workshops', + 'integrity_check': request.GET.get('integrity_check', False), + }, + context_instance=RequestContext(request) ) @@ -287,13 +298,14 @@ def workshop_grade_assessment(request, assessment): else: return redirect('ws_reviewers_map', workshop=assessment.workshop.id) - return render_to_response('workshop/cpanel/workshop_grade_assessment.html', - {'module': 'workshop', - 'assessment': assessment, - 'next_ass': next_ass, - 'page': 'workshops', - }, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/workshop_grade_assessment.html', + {'module': 'workshop', + 'assessment': assessment, + 'next_ass': next_ass, + 'page': 'workshops', + }, + context_instance=RequestContext(request) ) @@ -337,6 +349,7 @@ def post(self, request, *args, **kwargs): workshop_add = staff_required(AddWorkshopView.as_view()) + @staff_required def workshop_edit(request, workshop): workshop = get_object_or_404(Workshop, pk=workshop) @@ -354,29 +367,32 @@ class Meta: else: form = WForm(instance=workshop) - return render_to_response('workshop/cpanel/workshop_edit.html', - {'module': 'workshop', 'form': form, 'info': WorkshopGame, - 'page': 'workshops'}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/workshop_edit.html', + {'module': 'workshop', 'form': form, 'info': WorkshopGame, + 'page': 'workshops'}, + context_instance=RequestContext(request) ) + @staff_required def workshop_delete(request, workshop): workshop = get_object_or_404(Workshop, pk=workshop) workshop.delete() return redirect('ws_workshops') + @staff_required def workshop_start(request, workshop): workshop = get_object_or_404(Workshop, pk=workshop) - workshop.start() # set start_at and active_until + workshop.start() # set start_at and active_until return redirect('ws_status', pk=workshop.pk) @staff_required def workshop_stop(request, workshop): workshop = get_object_or_404(Workshop, pk=workshop) - workshop.stop() # set active_until + workshop.stop() # set active_until return redirect('ws_status', pk=workshop.pk) @@ -386,9 +402,10 @@ def workshop_assessments(request, workshop, assessment=None): if assessment: assessment = get_object_or_404(Assessment, pk=assessment) - return render_to_response('workshop/cpanel/workshop_assessments.html', - {'module': 'workshop', 'page': 'workshops', 'workshop': workshop, 'assessment': assessment}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/workshop_assessments.html', + {'module': 'workshop', 'page': 'workshops', 'workshop': workshop, 'assessment': assessment}, + context_instance=RequestContext(request) ) @@ -405,9 +422,10 @@ def workshop_assessment_edit(request, assessment, **kwargs): if text: a.text = text a.save() - return render_to_response('workshop/cpanel/workshop_assessment_change.html', - {'module': 'workshop', 'page': 'workshops', 'workshop': assessment.workshop, 'assessment': assessment}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/cpanel/workshop_assessment_change.html', + {'module': 'workshop', 'page': 'workshops', 'workshop': assessment.workshop, 'assessment': assessment}, + context_instance=RequestContext(request) ) @@ -439,8 +457,8 @@ def get_context_data(self, **kwargs): context.update({'module': 'workshop', 'page': 'semigroups', 'semigroup': self.semigroup}) return context -gradebook = staff_required(GradebookView.as_view()) +gradebook = staff_required(GradebookView.as_view()) @staff_required diff --git a/wouso/games/workshop/cpanel_urls.py b/wouso/games/workshop/cpanel_urls.py index ccfea0cb..1187c15d 100644 --- a/wouso/games/workshop/cpanel_urls.py +++ b/wouso/games/workshop/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.workshop.cpanel', +urlpatterns = patterns( + 'wouso.games.workshop.cpanel', url(r'^$', 'workshop_home', name='workshop_home'), url(r'^edit-spot/(?P\d+)/(?P\d+)/$', 'edit_spot', name='ws_edit_spot'), url(r'^add-semigroup/$', 'add_group', name='ws_add_group'), diff --git a/wouso/games/workshop/models.py b/wouso/games/workshop/models.py index e1a41cdb..69a20b97 100644 --- a/wouso/games/workshop/models.py +++ b/wouso/games/workshop/models.py @@ -18,8 +18,8 @@ (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), -# (6, 'Saturday'), -# (7, 'Sunday'), + # (6, 'Saturday'), + # (7, 'Sunday'), ) ROOM_CHOICES = ( @@ -226,7 +226,7 @@ def reviews_grade(self): sum = Review.objects.filter(answer__assessment=self, reviewer__in=self.reviewers.all()).aggregate(sum=models.Sum('answer_grade'))['sum'] if sum is None: return None - return int(sum/reviews_count) if reviews_count else 0 + return int(sum / reviews_count) if reviews_count else 0 def set_answered(self, answers=None): """ Set given answer dictionary. @@ -266,7 +266,7 @@ def update_grade(self): 8 * 10 + 16 * 5 / 16 = 10 = max(final_grade) """ self.final_grade = ceil((self.grade * 10 + self.reviewer_grade * 5) * 1.0 / (4 * count)) - except (ZeroDivisionError, TypeError): # one of the grades is None + except (ZeroDivisionError, TypeError): # one of the grades is None self.final_grade = None self.save() @@ -314,7 +314,8 @@ def remove_non_expected_reviews(self): if r.reviewer not in list(self.reviewers.all()) and not r.reviewer.in_staff_group(): r.delete() - __unicode__ = lambda self: u"#%d" % self.id + def __unicode__(self): + return u"#%d" % self.id class Answer(models.Model): @@ -345,7 +346,8 @@ def add_review(self, reviewer, feedback, grade=None): def reviewers(self): return Player.objects.filter(id__in=Review.objects.filter(answer=self).values('reviewer')) - __unicode__ = lambda self: self.text + def __unicode__(self): + return self.text class Review(models.Model): @@ -368,7 +370,8 @@ def set_grade(self, assistant, grade): workshop = property(lambda self: self.answer.assessment.workshop) - __unicode__ = lambda self: u"%s by %s" % (self.feedback, self.reviewer) + def __unicode__(self): + return u"%s by %s" % (self.feedback, self.reviewer) class WorkshopGame(Game): @@ -397,8 +400,8 @@ def get_spot(cls, timestamp=None): """ Return the current laboratory as a day, hour pair """ timestamp = timestamp if timestamp else datetime.now() - day = timestamp.weekday() + 1 # 1 = Monday, etc - hour = timestamp.hour - timestamp.hour % 2 # First lab starts at 8:00 AM + day = timestamp.weekday() + 1 # 1 = Monday, etc + hour = timestamp.hour - timestamp.hour % 2 # First lab starts at 8:00 AM return day, hour @classmethod @@ -479,10 +482,10 @@ def create_workshop(cls, semigroup, date, title, question_count=4): Returns: False if no error, string if error. """ - #questions = cls.get_question_pool(date) + # questions = cls.get_question_pool(date) # - #if not questions or questions.count() < question_count: - # return _("No questions for this date") + # if not questions or questions.count() < question_count: + # return _("No questions for this date") if cls.get_workshop(semigroup, date): raise ValueError(_("Workshop already exists for group at date")) @@ -504,23 +507,23 @@ def start_reviewing(cls, workshop): return pp_rotated = [participating_players[-1]] + participating_players[:-1] - for i,a in enumerate(le_assessments): + for i, a in enumerate(le_assessments): a.reviewers.clear() a.reviewers.add(pp_rotated[i]) # If there are more than two players, do this again if len(participating_players) > 2: pp_rotated = participating_players[-2:] + participating_players[:-2] - for i,a in enumerate(le_assessments): + for i, a in enumerate(le_assessments): a.reviewers.add(pp_rotated[i]) - workshop.status = 1 # reviewing + workshop.status = 1 # reviewing workshop.save() # send message to every player for player in participating_players: Message.send(None, player, _("Workshop to review!"), - _("Hello, the reviewing stage for the latest workshop has begun.")) + _("Hello, the reviewing stage for the latest workshop has begun.")) @classmethod def get_player_info(cls, player, workshop): @@ -560,9 +563,11 @@ def get_sidebar_widget(cls, context): assessment = None sm = ws_player.semigroup in semigroups - return render_to_string('workshop/sidebar.html', - {'semigroups': semigroups, 'workshop': workshop, 'semigroup_member': sm, 'assessment': assessment, - 'id': 'workshop'}) + return render_to_string( + 'workshop/sidebar.html', + {'semigroups': semigroups, 'workshop': workshop, 'semigroup_member': sm, 'assessment': assessment, + 'id': 'workshop'}) + register_sidebar_block('workshop', WorkshopGame.get_sidebar_widget) register_category(WorkshopGame.QPOOL_CATEGORY, WorkshopGame) diff --git a/wouso/games/workshop/templatetags/workshop.py b/wouso/games/workshop/templatetags/workshop.py index 304f999a..9c371f96 100644 --- a/wouso/games/workshop/templatetags/workshop.py +++ b/wouso/games/workshop/templatetags/workshop.py @@ -5,6 +5,7 @@ register = template.Library() + @register.simple_tag def semigroup(sg): if not sg: @@ -17,7 +18,7 @@ def semigroup(sg): @register.simple_tag def get_schedule(day, hour): - return '
'.join([semigroup(s) for s in WorkshopGame.get_by_day_and_hour(day, hour)]) + return '
'.join([semigroup(s) for s in WorkshopGame.get_by_day_and_hour(day, hour)]) @register.simple_tag @@ -51,6 +52,7 @@ def get_answer_feedback(answer, player): return '' return qs.get().feedback + @register.simple_tag def get_final_grade(workshop, player): assessment = workshop.get_assessment(player) diff --git a/wouso/games/workshop/tests.py b/wouso/games/workshop/tests.py index 478d7f8b..17f6947c 100644 --- a/wouso/games/workshop/tests.py +++ b/wouso/games/workshop/tests.py @@ -6,6 +6,7 @@ from models import * from wouso.core.tests import WousoTest + class TestWorkshop(TestCase): def test_current_spot_semigroup(self): @@ -53,6 +54,7 @@ def test_start_reviewing(self): self.assertEqual(i1['reviews'].count(), 0) self.assertEqual(i2['reviews'].count(), 0) + class TestAssessment(WousoTest): def test_grading(self): p1 = self._get_player(1) @@ -80,7 +82,7 @@ def test_grading(self): # Check questions self.assertEqual(a1.questions.all().count(), 4) - #self.assertEqual(a1.questions.all()[-1], q) + # self.assertEqual(a1.questions.all()[-1], q) a1.set_answered() a2.set_answered() @@ -103,9 +105,9 @@ def test_grading(self): r12 = Review.objects.create(answer=ans2, reviewer=p1, answer_grade=7) self.assertEqual(a2.reviews_grade, 7) - + ar = Review.objects.create(answer=ans2, reviewer=p2, answer_grade=8) - self.assertEqual(a2.reviews_grade, 7) # ignores reviews from non-reviewers + self.assertEqual(a2.reviews_grade, 7) # ignores reviews from non-reviewers ar.delete() # Check the reset_reviews view @@ -131,6 +133,7 @@ def test_grading(self): self.assertEqual(a1.final_grade, 69) self.assertEqual(a1.reviews_grade, 3) + class TestWorkshopViews(WousoTest): def setUp(self): super(TestWorkshopViews, self).setUp() @@ -157,7 +160,7 @@ def test_add_group_view_post(self): # Check if it creates a semigroup self.assertTrue(Semigroup.objects.all()) - + # Check if duplicates are created response = self.c.post(reverse('ws_add_group'), data) self.assertEqual(len(Semigroup.objects.all()), 1) diff --git a/wouso/games/workshop/urls.py b/wouso/games/workshop/urls.py index 414d078c..c92cd313 100644 --- a/wouso/games/workshop/urls.py +++ b/wouso/games/workshop/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.games.workshop.views', +urlpatterns = patterns( + 'wouso.games.workshop.views', url(r'^$', 'index', name='workshop_index_view'), url(r'^play/$', 'play', name='workshop_play'), url(r'^review/(?P\d+)/$', 'review', name='workshop_review'), diff --git a/wouso/games/workshop/views.py b/wouso/games/workshop/views.py index 254b9ff2..e18abee9 100644 --- a/wouso/games/workshop/views.py +++ b/wouso/games/workshop/views.py @@ -19,9 +19,10 @@ def index(request, extra_context=None): 'assessment': assessment, 'semigroup': Semigroup.get_by_player(player), 'history': player.assessments.all().order_by('-workshop__active_until')}) - return render_to_response('workshop/index.html', - extra_context, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/index.html', + extra_context, + context_instance=RequestContext(request) ) @@ -57,13 +58,15 @@ def play(request): seconds_left = assessment.time_left() - return render_to_response('workshop/play.html', - {'assessment': assessment, - 'workshop': workshop, - 'seconds_left': seconds_left}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/play.html', + {'assessment': assessment, + 'workshop': workshop, + 'seconds_left': seconds_left}, + context_instance=RequestContext(request) ) + @login_required def review(request, workshop): player = request.user.get_profile() @@ -88,13 +91,15 @@ def review(request, workshop): review.answer_grade = answer_grade review.save() - return render_to_response('workshop/review.html', - {'assessment': assessment, - 'workshop': workshop, - 'assessments': assessments}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/review.html', + {'assessment': assessment, + 'workshop': workshop, + 'assessments': assessments}, + context_instance=RequestContext(request) ) + @login_required def review_change(request, review): review = get_object_or_404(Review, pk=review) @@ -119,12 +124,14 @@ class Meta: else: form = RCForm(instance=review) - return render_to_response('workshop/review_change.html', - {'review': review, - 'form': form}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/review_change.html', + {'review': review, + 'form': form}, + context_instance=RequestContext(request) ) + @login_required def results(request, workshop): player = request.user.get_profile() @@ -135,8 +142,9 @@ def results(request, workshop): if not assessment: return do_error(request, _('Cannot view results for an workshop you did not participate to.')) - return render_to_response('workshop/results.html', - {'assessment': assessment, - 'workshop': workshop}, - context_instance=RequestContext(request) + return render_to_response( + 'workshop/results.html', + {'assessment': assessment, + 'workshop': workshop}, + context_instance=RequestContext(request) ) diff --git a/wouso/interface/__init__.py b/wouso/interface/__init__.py index 5d95553d..849f3a8a 100644 --- a/wouso/interface/__init__.py +++ b/wouso/interface/__init__.py @@ -4,11 +4,12 @@ # Get a specific logger for this module logger = logging.getLogger('interface') + def render_string(template, data=None): """ Provide game context render_to_string, used by widget generators """ - return render_to_string(template, - dictionary=data) + return render_to_string(template, dictionary=data) + def get_static_pages(): """ Return a list of static pages ordered by position, for rendering in footer """ @@ -16,14 +17,16 @@ def get_static_pages(): return StaticPage.get_links() + def mobile_browser(request): - if request.META.has_key("HTTP_USER_AGENT"): + if "HTTP_USER_AGENT" in request.META: s = request.META["HTTP_USER_AGENT"].lower() for i in ('nokia', 'mobile'): if i in s: return True return False + def detect_mobile(request): if request.GET.get('mobile'): request.session['mobile'] = request.GET.get('mobile') @@ -33,6 +36,8 @@ def detect_mobile(request): _theme = None + + def get_theme(): """ Return the current theme @@ -45,6 +50,7 @@ def get_theme(): return _theme + def set_theme(value): """ Set the current theme, temporary. Give it a None parameter to use the one in db settings. @@ -65,4 +71,4 @@ def set_custom_theme(player, theme): if theme in get_themes(): Setting.get('theme_user_%d' % player.id).set_value(theme) return True - return False \ No newline at end of file + return False diff --git a/wouso/interface/activity/__init__.py b/wouso/interface/activity/__init__.py index 5f26a1f7..0f459c4f 100644 --- a/wouso/interface/activity/__init__.py +++ b/wouso/interface/activity/__init__.py @@ -1 +1 @@ -from achievements import Achievements \ No newline at end of file +from achievements import Achievements diff --git a/wouso/interface/activity/achievements.py b/wouso/interface/activity/achievements.py index e0eca591..5d0d0614 100644 --- a/wouso/interface/activity/achievements.py +++ b/wouso/interface/activity/achievements.py @@ -81,8 +81,8 @@ def unique_users_pm(player, minutes): """ Return the count of distinct source messages """ - activities = Message.objects.filter(receiver=player, - timestamp__gt=datetime.now() - timedelta(minutes=minutes) + activities = Message.objects.filter( + receiver=player, timestamp__gt=datetime.now() - timedelta(minutes=minutes) ).values('sender').distinct().count() return activities @@ -181,7 +181,7 @@ def challenges_played_today(player): activities = Activity.get_player_activity(player).filter(action__contains='chall', timestamp__gte=today) result = 0 for a in activities: - if not 'refused' in a.action: + if 'refused' not in a.action: result += 1 return result @@ -251,7 +251,7 @@ def used_all_spells(player, mass): used_spells = [m.spell for m in magic_activity if m.spell.mass == mass] for s in all_spells: - if not s in used_spells: + if s not in used_spells: return False return True @@ -264,8 +264,7 @@ def earn_achievement(cls, player, modifier): message = ugettext_noop('earned {artifact}') action_msg = 'earned-ach' addActivity.send(sender=None, user_from=player, game=None, message=message, - arguments=dict(artifact=result.artifact), action=action_msg - ) + arguments=dict(artifact=result.artifact), action=action_msg) Message.send(sender=None, receiver=player, subject="Achievement", text="You have just earned " + modifier) else: logging.debug('%s would have earned %s, but there was no artifact' % (player, modifier)) @@ -297,9 +296,9 @@ def activity_handler(cls, sender, **kwargs): # Check if the number of refused challenges in the past week is 0 # also check for minimum number of challenges played = 5 if not player.magic.has_modifier('ach-this-is-sparta'): - if refused_challenges(player) == 0 and \ - challenge_count(player, days=7) >= 5 and \ - first_seen(player) >= 7: + if (refused_challenges(player) == 0 and + challenge_count(player, days=7) >= 5 and + first_seen(player) >= 7): cls.earn_achievement(player, 'ach-this-is-sparta') # Check if player played 10 challenges in a day" @@ -406,7 +405,6 @@ def activity_handler(cls, sender, **kwargs): if login_at_start(player, start_day=head_start_date.day, start_month=head_start_date.month): cls.earn_achievement(player, 'ach-head-start') - @classmethod def get_modifiers(self): return ['ach-login-10', @@ -430,7 +428,7 @@ def get_modifiers(self): 'ach-use-all-mass', 'ach-spent-gold', 'ach-head-start', - ] + ] def check_for_achievements(sender, **kwargs): diff --git a/wouso/interface/activity/admin.py b/wouso/interface/activity/admin.py index 626530ea..f8047e21 100644 --- a/wouso/interface/activity/admin.py +++ b/wouso/interface/activity/admin.py @@ -1,8 +1,10 @@ from django.contrib import admin from models import Activity + class ActivityAdmin(admin.ModelAdmin): list_display = ('timestamp', 'user_from', 'user_to', 'game_name', 'message') list_filter = ('game', ) + admin.site.register(Activity, ActivityAdmin) diff --git a/wouso/interface/activity/models.py b/wouso/interface/activity/models.py index 67d38386..ec09801d 100644 --- a/wouso/interface/activity/models.py +++ b/wouso/interface/activity/models.py @@ -9,6 +9,7 @@ from wouso.interface import logger from wouso.core.signals import addActivity, addedActivity + class Activity(models.Model): timestamp = models.DateTimeField(default=datetime.now, blank=True) user_from = models.ForeignKey(Player, related_name='activity_from', blank=True, null=True) @@ -125,6 +126,7 @@ def player_to(self): def __unicode__(self): return u"#%d" % (self.id) + def save_activity_handler(sender, **kwargs): """ Callback function for addActivity signal """ a = Activity() diff --git a/wouso/interface/activity/tests.py b/wouso/interface/activity/tests.py index d8d8b05e..47077131 100644 --- a/wouso/interface/activity/tests.py +++ b/wouso/interface/activity/tests.py @@ -7,12 +7,13 @@ from wouso.games.qotd.models import QotdGame from wouso.games.challenge.models import ChallengeGame, ChallengeUser, Challenge from wouso.interface.apps.messaging.models import Message, MessagingUser -from achievements import consecutive_days_seen, consecutive_qotd_correct, consecutive_chall_won, challenge_count, \ - refused_challenges, get_challenge_time, unique_users_pm, wrong_first_qotd, get_chall_score, \ - challenges_played_today, check_for_god_mode, spell_count, spent_gold, gold_amount, \ - Achievements +from achievements import consecutive_days_seen, consecutive_qotd_correct, consecutive_chall_won, \ + challenge_count, refused_challenges, get_challenge_time, unique_users_pm, wrong_first_qotd, \ + get_chall_score, challenges_played_today, check_for_god_mode, spell_count, spent_gold, \ + gold_amount, Achievements from models import Activity + class AchievementTest(WousoTest): def test_login_with_multiple_seens(self): """ @@ -20,7 +21,7 @@ def test_login_with_multiple_seens(self): """ player = self._get_player() for i in range(100): - timestamp = datetime.now() - timedelta(hours=i*16) + timestamp = datetime.now() - timedelta(hours=i * 16) Activity.objects.create(timestamp=timestamp, user_from=player, action='seen', public=False) self.assertGreaterEqual(consecutive_days_seen(player, datetime.now()), 14) @@ -35,7 +36,6 @@ def test_login_10(self): self.assertEqual(consecutive_days_seen(player, datetime.now()), 14) - def test_login_10_less(self): """ Multiple seens every day for less than 14 days in a row. @@ -43,11 +43,10 @@ def test_login_10_less(self): player = self._get_player() for i in range(20): - timestamp = datetime.now() - timedelta(hours=i*7) + timestamp = datetime.now() - timedelta(hours=i * 7) Activity.objects.create(timestamp=timestamp, user_from=player, action='seen', public=False) self.assertLess(consecutive_days_seen(player, datetime.now()), 14) - def test_login_10_wrong(self): player = self._get_player() for i in range(14): @@ -73,65 +72,63 @@ def test_login_10_activity(self): def test_early_bird_not(self): player = self._get_player() Artifact.objects.create(group=None, name='ach-early-bird') - for i in range(1,2): - Activity.objects.create(timestamp=datetime(2012,9,17,6,0,0), - user_from=player, user_to=player, action='seen', public=False) - - for i in range(1,4): - Activity.objects.create(timestamp=datetime(2012,9,17,5,0,0), - user_from=player, user_to=player, action='seen', public=False) - - signals.addActivity.send(sender=None, timestamp=datetime(2012,9,17,5,0,0), - user_from=player, - user_to=player, - action='seen', - game=None) + for i in range(1, 2): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 6, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + for i in range(1, 4): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 5, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + signals.addActivity.send( + sender=None, timestamp=datetime(2012, 9, 17, 5, 0, 0), + user_from=player, user_to=player, action='seen', game=None) self.assertFalse(player.magic.has_modifier('ach-early-bird')) def test_early_bird_set(self): player = self._get_player() Artifact.objects.create(group=None, name='ach-early-bird') - for i in range(1,4): - Activity.objects.create(timestamp=datetime(2012,9,17,6,0,0), - user_from=player, user_to=player, action='seen', public=False) - - signals.addActivity.send(sender=None, timestamp=datetime(2012,9,17,6,0,0), - user_from=player, - user_to=player, - action='seen', - game=None) + for i in range(1, 4): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 6, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + signals.addActivity.send( + sender=None, timestamp=datetime(2012, 9, 17, 6, 0, 0), + user_from=player, user_to=player, action='seen', game=None) self.assertTrue(player.magic.has_modifier('ach-early-bird')) def test_night_owl_not(self): player = self._get_player() Artifact.objects.create(group=None, name='ach-night-owl') - for i in range(1,3): - Activity.objects.create(timestamp=datetime(2012,9,17,6,0,0), - user_from=player, user_to=player, action='seen', public=False) - - for i in range(1,4): - Activity.objects.create(timestamp=datetime(2012,9,17,5,0,0), - user_from=player, user_to=player, action='seen', public=False) - - signals.addActivity.send(sender=None, timestamp=datetime(2012,9,17,4,0,0), - user_from=player, - user_to=player, - action='seen', - game=None) + for i in range(1, 3): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 6, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + for i in range(1, 4): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 5, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + signals.addActivity.send( + sender=None, timestamp=datetime(2012, 9, 17, 4, 0, 0), + user_from=player, user_to=player, action='seen', game=None) self.assertFalse(player.magic.has_modifier('ach-night-owl')) def test_night_owl_set(self): player = self._get_player() Artifact.objects.create(group=None, name='ach-night-owl') - for i in range(1,4): - Activity.objects.create(timestamp=datetime(2012,9,17,4,0,0), - user_from=player, user_to=player, action='seen', public=False) - - signals.addActivity.send(sender=None, timestamp=datetime(2012,9,17,4,0,0), - user_from=player, - user_to=player, - action='seen', - game=None) + for i in range(1, 4): + Activity.objects.create( + timestamp=datetime(2012, 9, 17, 4, 0, 0), + user_from=player, user_to=player, action='seen', public=False) + + signals.addActivity.send( + sender=None, timestamp=datetime(2012, 9, 17, 4, 0, 0), + user_from=player, user_to=player, action='seen', game=None) self.assertTrue(player.magic.has_modifier('ach-night-owl')) @@ -139,30 +136,37 @@ class QotdAchievementTest(WousoTest): def test_10_qotd_3ok(self): player = self._get_player() for i in range(3): - timestamp=datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct',message_string=str(i),public=True) - self.assertEqual(consecutive_qotd_correct(player),3) + timestamp = datetime.now() + timedelta(days=-i) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='qotd-correct', message_string=str(i), public=True) + self.assertEqual(consecutive_qotd_correct(player), 3) def test_10_qotd_1wrong(self): player = self._get_player() for i in range(10): - timestamp=datetime.now() - timedelta(days=-i) + timestamp = datetime.now() - timedelta(days=-i) if i == 5: - a = Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-wrong',message_string=str(i),public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='qotd-wrong', message_string=str(i), public=True) else: - a = Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct',message_string=str(i),public=True) - self.assertEqual(consecutive_qotd_correct(player),4) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='qotd-correct', message_string=str(i), public=True) + self.assertEqual(consecutive_qotd_correct(player), 4) def test_10_qotd_get_ach(self): Artifact.objects.create(group=None, name='ach-qotd-10') player = self._get_player() for i in range(10): - timestamp=datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct',message_string=str(i),public=True) - signals.addActivity.send(sender=None, user_from=player, - user_to=player, - action='qotd-correct', - game=QotdGame.get_instance()) + timestamp = datetime.now() + timedelta(days=-i) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='qotd-correct', message_string=str(i), public=True) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, + action='qotd-correct', game=QotdGame.get_instance()) self.assertTrue(player.magic.has_modifier('ach-qotd-10')) @@ -171,9 +175,9 @@ def test_chall_10_won(self): player = self._get_player() for i in range(1, 11): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-won', public=True) self.assertEqual(consecutive_chall_won(player), 10) @@ -182,13 +186,13 @@ def test_chall_10_won_wrong_draw(self): for i in range(1, 10): timestamp = datetime.now() + timedelta(days=-i) if i == 5: - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-draw', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-draw', public=True) else: - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-won', public=True) self.assertEqual(consecutive_chall_won(player), 4) @@ -198,13 +202,13 @@ def test_chall_10_won_wrong_lost(self): for i in range(1, 10): timestamp = datetime.now() + timedelta(days=-i) if i == 5: - a = Activity.objects.create(timestamp=timestamp, - user_from=player2, user_to=player1, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player2, user_to=player1, + action='chall-won', public=True) else: - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-won', public=True) self.assertEqual(consecutive_chall_won(player1), 4) @@ -213,24 +217,23 @@ def test_chall_10_won_activity(self): player = self._get_player() for i in range(1, 10): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-won', public=True) self.assertFalse(player.magic.has_modifier('ach-chall-won-10')) - signals.addActivity.send(sender=None, user_from=player, - user_to=player, - action='chall-won', - game=ChallengeGame.get_instance()) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, + action='chall-won', game=ChallengeGame.get_instance()) self.assertTrue(player.magic.has_modifier('ach-chall-won-10')) def test_chall_30(self): player = self._get_player() for i in range(1, 31): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-won', public=True) self.assertEqual(challenge_count(player), 30) @@ -240,17 +243,17 @@ def test_chall_100_draw_lost(self): for i in range(1, 101): timestamp = datetime.now() + timedelta(days=-i) if (i % 5) == 0: - a = Activity.objects.create(timestamp=timestamp, - user_from=player2, user_to=player1, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player2, user_to=player1, + action='chall-won', public=True) elif (i % 7) == 0: - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-draw', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-draw', public=True) else: - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-won', public=True) self.assertEqual(challenge_count(player1), 100) @@ -260,18 +263,17 @@ def test_chall_100_activity(self): for i in range(1, 100): timestamp = datetime.now() + timedelta(days=-i) if i % 5 == 0: - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-draw', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-draw', public=True) else: - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-won', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-won', public=True) - signals.addActivity.send(sender=None, user_from=player, - user_to=player, - action='chall-won', - game=ChallengeGame.get_instance()) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, + action='chall-won', game=ChallengeGame.get_instance()) self.assertTrue(player.magic.has_modifier('ach-chall-100')) def test_defeated_better_player_activity(self): @@ -281,26 +283,24 @@ def test_defeated_better_player_activity(self): player2.level_no = 4 player2.save() - for i in range(1,5): - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-won', - game=ChallengeGame.get_instance()) + for i in range(1, 5): + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-won', game=ChallengeGame.get_instance()) self.assertFalse(player1.magic.has_modifier('ach-chall-def-big')) - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-won', - game=ChallengeGame.get_instance()) + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-won', game=ChallengeGame.get_instance()) self.assertTrue(player1.magic.has_modifier('ach-chall-def-big')) def test_this_is_sparta_correct(self): player = self._get_player() for i in range(1, 7): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, action='chall-refused', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action='chall-refused', public=True) self.assertEqual(refused_challenges(player), 6) @@ -308,89 +308,85 @@ def test_this_is_sparta_activity_not_given(self): Artifact.objects.create(group=None, name='ach-this-is-sparta') player1 = self._get_player() player2 = self._get_player(2) - first_seen = datetime.now() + timedelta(days=-10)#10 days since first login - Activity.objects.create(timestamp=first_seen, - user_from=player1, user_to=player1, action='seen', - public=False) + first_seen = datetime.now() + timedelta(days=-10) # 10 days since first login + Activity.objects.create( + timestamp=first_seen, user_from=player1, user_to=player1, + action='seen', public=False) for i in range(1, 7): timestamp = datetime.now() + timedelta(days=-i) if (i % 4) == 0: - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-refused', - public=True) + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-refused', public=True) else: - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-lost', - public=True) - #send signal to enable achievement validation - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-refused', - game=ChallengeGame.get_instance()) - #False due to refused challenge + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-lost', public=True) + # send signal to enable achievement validation + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-refused', game=ChallengeGame.get_instance()) + # False due to refused challenge self.assertFalse(player1.magic.has_modifier('ach-this-is-sparta')) def test_this_is_sparta_activity_not_enough_challenges(self): Artifact.objects.create(group=None, name='ach-this-is-sparta') player1 = self._get_player() player2 = self._get_player(2) - first_seen = datetime.now() + timedelta(days=-10)#10 days since first login - Activity.objects.create(timestamp=first_seen, - user_from=player1, user_to=player1, action='seen', - public=False) + first_seen = datetime.now() + timedelta(days=-10) # 10 days since first login + Activity.objects.create( + timestamp=first_seen, user_from=player1, user_to=player1, + action='seen', public=False) for i in range(1, 3): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-lost', - public=True) - #send signal to enable achievement validation - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-won', - game=ChallengeGame.get_instance()) - #False due to not enough challenges played + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-lost', public=True) + # send signal to enable achievement validation + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-won', game=ChallengeGame.get_instance()) + # False due to not enough challenges played self.assertFalse(player1.magic.has_modifier('ach-this-is-sparta')) def test_this_is_sparta_activity_not_enough_time(self): Artifact.objects.create(group=None, name='ach-this-is-sparta') player1 = self._get_player() player2 = self._get_player(2) - first_seen = datetime.now() + timedelta(days=-6)#only 6 days have passed - Activity.objects.create(timestamp=first_seen, - user_from=player1, user_to=player1, action='seen', - public=False) + first_seen = datetime.now() + timedelta(days=-6) # only 6 days have passed + Activity.objects.create( + timestamp=first_seen, user_from=player1, user_to=player1, + action='seen', public=False) for i in range(1, 5): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-lost', - public=True) - #send signal to enable achievement validation - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-won', - game=ChallengeGame.get_instance()) - #achievement condition earned + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-lost', public=True) + # send signal to enable achievement validation + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-won', game=ChallengeGame.get_instance()) + # achievement condition earned self.assertFalse(player1.magic.has_modifier('ach-this-is-sparta')) def test_this_is_sparta_activity_passed(self): Artifact.objects.create(group=None, name='ach-this-is-sparta') player1 = self._get_player() player2 = self._get_player(2) - first_seen = datetime.now() + timedelta(days=-7)#barely enough time - Activity.objects.create(timestamp=first_seen, - user_from=player1, user_to=player1, action='seen', - public=False) + first_seen = datetime.now() + timedelta(days=-7) # barely enough time + Activity.objects.create( + timestamp=first_seen, user_from=player1, user_to=player1, + action='seen', public=False) for i in range(1, 5): timestamp = datetime.now() + timedelta(days=-i) - a = Activity.objects.create(timestamp=timestamp, - user_from=player1, user_to=player2, action='chall-lost', - public=True) - #send signal to enable achievement validation - signals.addActivity.send(sender=None, user_from=player1, - user_to=player2, - action='chall-won', - game=ChallengeGame.get_instance()) - #achievement condition earned + a = Activity.objects.create( + timestamp=timestamp, user_from=player1, user_to=player2, + action='chall-lost', public=True) + # send signal to enable achievement validation + signals.addActivity.send( + sender=None, user_from=player1, user_to=player2, + action='chall-won', game=ChallengeGame.get_instance()) + # achievement condition earned self.assertTrue(player1.magic.has_modifier('ach-this-is-sparta')) def test_challenges_played_today(self): @@ -398,13 +394,13 @@ def test_challenges_played_today(self): for i in range(1, 10): timestamp = datetime.now() if (i % 4) == 0: - Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, - action="chall-lost", public=True) + Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action="chall-lost", public=True) else: - Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, - action="chall-won", public=True) + Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action="chall-won", public=True) self.assertEqual(challenges_played_today(player), 9) def test_challenges_played_today_activity(self): @@ -413,20 +409,20 @@ def test_challenges_played_today_activity(self): for i in range(1, 10): timestamp = datetime.now() if (i % 4) == 0: - Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, - action="chall-lost", public=True) + Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action="chall-lost", public=True) else: - Activity.objects.create(timestamp=timestamp, - user_from=player, user_to=player, - action="chall-won", public=True) + Activity.objects.create( + timestamp=timestamp, user_from=player, user_to=player, + action="chall-won", public=True) - signals.addActivity.send(sender=None, user_from=player, - user_to=player, - action='chall-won', - game=ChallengeGame.get_instance()) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, + action='chall-won', game=ChallengeGame.get_instance()) self.assertTrue(player.magic.has_modifier('ach-chall-10-a-day')) + class PopularityTest(WousoTest): def setUp(self): Message.disable_check() @@ -438,17 +434,17 @@ def test_popularity_5_pm_1(self): player = self._get_player() player = player.get_extension(MessagingUser) for i in range(10): - timestamp=datetime.now() + timedelta(minutes = -1) - a = Message.objects.create(timestamp=timestamp, sender=player,receiver=player,subject = "a",text = "b") - self.assertEqual(unique_users_pm(player,3),1) + timestamp = datetime.now() + timedelta(minutes=-1) + a = Message.objects.create(timestamp=timestamp, sender=player, receiver=player, subject="a", text="b") + self.assertEqual(unique_users_pm(player, 3), 1) def test_popularity_5_pm_2(self): player = self._get_player() - player=player.get_extension(MessagingUser) - timestamp=datetime.now() + timedelta(minutes = -1) - a = Message.objects.create(timestamp=timestamp, sender=player,receiver=player,subject = "a",text = "b") - a = Message.objects.create(timestamp=timestamp, sender=self._get_player(2).get_extension(MessagingUser),receiver=player,subject = "a",text = "b") - self.assertEqual(unique_users_pm(player,3),2) + player = player.get_extension(MessagingUser) + timestamp = datetime.now() + timedelta(minutes=-1) + a = Message.objects.create(timestamp=timestamp, sender=player, receiver=player, subject="a", text="b") + a = Message.objects.create(timestamp=timestamp, sender=self._get_player(2).get_extension(MessagingUser), receiver=player, subject="a", text="b") + self.assertEqual(unique_users_pm(player, 3), 2) def test_popularity_5_pm_3(self): Artifact.objects.create(group=None, name='ach-popularity') @@ -457,13 +453,13 @@ def test_popularity_5_pm_3(self): player = self._get_player(i).get_extension(MessagingUser) if i <= 3: timestamp = datetime.now() + timedelta(minutes=-10) - a = Message.objects.create(timestamp=timestamp, sender=player,receiver=user_to,subject = "a",text = "b") + a = Message.objects.create(timestamp=timestamp, sender=player, receiver=user_to, subject="a", text="b") else: timestamp = datetime.now() + timedelta(minutes=-35) - a = Message.objects.create(timestamp=timestamp, sender=player,receiver=user_to,subject = "a",text = "b") - Message.send(sender=player,receiver=user_to,subject="a",text="b") + a = Message.objects.create(timestamp=timestamp, sender=player, receiver=user_to, subject="a", text="b") + Message.send(sender=player, receiver=user_to, subject="a", text="b") - self.assertEqual(unique_users_pm(user_to,30),5) + self.assertEqual(unique_users_pm(user_to, 30), 5) self.assertTrue(user_to.magic.has_modifier('ach-popularity')) @@ -479,29 +475,28 @@ class FlawlessVictoryTest(WousoTest): def setUp(self): super(FlawlessVictoryTest, self).setUp() self.user_from = self._get_player(1) - self.user_to = self._get_player(2) + self.user_to = self._get_player(2) self.chall_user1 = self.user_from.get_extension(ChallengeUser) self.chall_user2 = self.user_to.get_extension(ChallengeUser) scoring.setup_scoring() self.chall = Challenge.create(user_from=self.chall_user1, user_to=self.chall_user2, ignore_questions=True) - def test_scorring(self): self.chall.user_from.score = 100 self.chall.user_from.save() self.chall.user_to.score = 200 self.chall.user_to.save() - self.assertEqual(get_chall_score(dict(id=self.chall.id)),200) + self.assertEqual(get_chall_score(dict(id=self.chall.id)), 200) self.chall.user_from.score = 300 self.chall.user_from.save() - self.assertEqual(get_chall_score(dict(id=self.chall.id)),300) + self.assertEqual(get_chall_score(dict(id=self.chall.id)), 300) self.chall.user_to.score = 500 self.chall.user_to.save() - self.assertEqual(get_chall_score(dict(id=self.chall.id)),500) + self.assertEqual(get_chall_score(dict(id=self.chall.id)), 500) def test_ach_fake(self): Artifact.objects.create(group=None, name='ach-flawless-victory') - player=self._get_player() + player = self._get_player() self.chall.user_from.score = 100 self.chall.user_from.save() self.chall.user_to.score = 200 @@ -524,6 +519,7 @@ def test_ach_real(self): self.chall.played() self.assertTrue(self.user_from.magic.has_modifier('ach-flawless-victory')) + class WinFastTest(WousoTest): def setUp(self): super(WinFastTest, self).setUp() @@ -568,7 +564,7 @@ def test_ach(self): user_to=player, arguments=dict(id=self.chall.id), action="chall-won", - game = ChallengeGame.get_instance()) + game=ChallengeGame.get_instance()) self.assertTrue(player.magic.has_modifier('ach-win-fast')) @@ -577,46 +573,45 @@ class SpellAchievement(WousoTest): def test_spell_count(self): player = self._get_player() spell = Spell.objects.create(name="test", title="", description="", - image=None, percents=100, type='s') + image=None, percents=100, type='s') player.magic.add_spell(spell) player.magic.cast_spell(spell, player, datetime.now() + timedelta(days=3)) self.assertTrue(player.magic.is_spelled) self.assertTrue(spell_count(player), 1) - def test_spell_count_activity(self): Artifact.objects.create(group=None, name='ach-spell-5') player = self._get_player() for i in range(1, 6): name = "test" + str(i) spell = Spell.objects.create(name=name, title="", description="", - image=None, percents=100) + image=None, percents=100) player.magic.add_spell(spell) player.magic.cast_spell(spell, player, datetime.now() + timedelta(days=i)) signals.addActivity.send(sender=None, user_from=player, - user_to=player, action="cast", game=None) + user_to=player, action="cast", game=None) self.assertTrue(player.magic.has_modifier('ach-spell-5')) def test_gold_spent(self): player = self._get_player() spell = Spell.objects.create(name="test", title="", description="", - image=None, percents=100, type='s', - price=25) + image=None, percents=100, type='s', + price=25) SpellHistory.objects.create(type='b', user_from=player, user_to=player, - date=datetime.now(), spell=spell) + date=datetime.now(), spell=spell) self.assertTrue(spent_gold(player), 25) def test_gold_spent_activity(self): Artifact.objects.create(group=None, name='ach-spent-gold') player = self._get_player() spell = Spell.objects.create(name="test", title="", description="", - image=None, percents=100, type='s', - price=600) + image=None, percents=100, type='s', + price=600) SpellHistory.objects.create(type='b', user_from=player, user_to=player, - date=datetime.now(), spell=spell) + date=datetime.now(), spell=spell) signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='spell-buy', - game=None) + user_to=player, action='spell-buy', + game=None) self.assertTrue(player.magic.has_modifier('ach-spent-gold')) @@ -624,13 +619,13 @@ def test_used_all_spells_activity(self): Artifact.objects.create(group=None, name='ach-use-all-spells') player = self._get_player() spell = Spell.objects.create(name="test", title="", description="", - image=None, percents=100, type='s', - price=600) + image=None, percents=100, type='s', + price=600) SpellHistory.objects.create(type='u', user_from=player, user_to=player, - date=datetime.now(), spell=spell) + date=datetime.now(), spell=spell) signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='cast', - game=None) + user_to=player, action='cast', + game=None) self.assertTrue(player.magic.has_modifier('ach-use-all-spells')) @@ -638,13 +633,13 @@ def test_used_all_mass_spells_activity(self): Artifact.objects.create(group=None, name='ach-use-all-mass') player = self._get_player() spell = Spell.objects.create(name="test", title="", description="", - image=None, percents=100, type='s', - price=600, mass=True) + image=None, percents=100, type='s', + price=600, mass=True) SpellHistory.objects.create(type='u', user_from=player, user_to=player, - date=datetime.now(), spell=spell) + date=datetime.now(), spell=spell) signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='cast', - game=None) + user_to=player, action='cast', + game=None) self.assertTrue(player.magic.has_modifier('ach-use-all-mass')) @@ -660,16 +655,16 @@ def test_level_ach(self): player.save() signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='gold-won', - game=None) + user_to=player, action='gold-won', + game=None) self.assertTrue(player.magic.has_modifier('ach-level-5')) player.level_no = 10 player.save() signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='gold-won', - game=None) + user_to=player, action='gold-won', + game=None) self.assertTrue(player.magic.has_modifier('ach-level-10')) @@ -691,31 +686,31 @@ def test_gold_amount_ach(self): scoring.score_simple(player, coin, amount=500) signals.addActivity.send(sender=None, user_from=player, - user_to=player, action='gold-won', - game=None) + user_to=player, action='gold-won', + game=None) self.assertTrue(player.magic.has_modifier('ach-gold-300')) class GodModeTest(WousoTest): def test_check_for_god_mode1(self): - player=self._get_player() - timestamp=datetime.now() + player = self._get_player() + timestamp = datetime.now() for i in range(5): timestamp -= timedelta(days=1) Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct') - self.assertTrue(check_for_god_mode(player,5,0)) + self.assertTrue(check_for_god_mode(player, 5, 0)) def test_check_for_god_mode2(self): - player=self._get_player() - timestamp=datetime.now() + player = self._get_player() + timestamp = datetime.now() for i in range(5): timestamp -= timedelta(days=1) if i == 3: Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-wrong') continue Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct') - self.assertFalse(check_for_god_mode(player,5,0)) + self.assertFalse(check_for_god_mode(player, 5, 0)) def test_check_for_god_mode3(self): player = self._get_player() @@ -725,16 +720,15 @@ def test_check_for_god_mode3(self): timestamp -= timedelta(days=1) Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player2, action='chall-won') Activity.objects.create(timestamp=timestamp, user_from=player, user_to=player, action='qotd-correct') - self.assertTrue(check_for_god_mode(player,5,5)) + self.assertTrue(check_for_god_mode(player, 5, 5)) Artifact.objects.create(group=None, name='ach-god-mode-on') signals.addActivity.send(sender=None, user_from=player, - user_to=player, - action='seen', - game=None) + user_to=player, + action='seen', + game=None) self.assertTrue(player.magic.has_modifier('ach-god-mode-on')) - def test_check_for_god_mode4(self): player = self._get_player() player2 = self._get_player(1) @@ -745,4 +739,4 @@ def test_check_for_god_mode4(self): if i == 3: Activity.objects.create(timestamp=timestamp, user_from=player2, user_to=player, action='chall-won') continue - self.assertFalse(check_for_god_mode(player,5,0)) + self.assertFalse(check_for_god_mode(player, 5, 0)) diff --git a/wouso/interface/api/__init__.py b/wouso/interface/api/__init__.py index d1b0cba9..0ece10c7 100644 --- a/wouso/interface/api/__init__.py +++ b/wouso/interface/api/__init__.py @@ -1,4 +1,4 @@ from django.http import HttpResponseRedirect HttpResponseRedirect.allowed_schemes = ['https', 'http', 'ftp', 'web+wouso'] -API_VERSION = "1" \ No newline at end of file +API_VERSION = "1" diff --git a/wouso/interface/api/admin.py b/wouso/interface/api/admin.py index 07c5408b..5e9eb11f 100644 --- a/wouso/interface/api/admin.py +++ b/wouso/interface/api/admin.py @@ -9,4 +9,4 @@ admin.site.register(Nonce) admin.site.register(Token) except AlreadyRegistered: - pass \ No newline at end of file + pass diff --git a/wouso/interface/api/authentication.py b/wouso/interface/api/authentication.py index eea9b477..46a59169 100644 --- a/wouso/interface/api/authentication.py +++ b/wouso/interface/api/authentication.py @@ -2,6 +2,7 @@ __author__ = 'alex' + # This code is copied from http://yml-blog.blogspot.com/2009/10/django-piston-authentication-against.html class SessionAuthentication(object): """ @@ -19,11 +20,12 @@ def is_authenticated(self, request): self.request = request return request.user.is_authenticated() - #TODO: A real challenge here would be nice + # TODO: A real challenge here would be nice def challenge(self): import piston return piston.authentication.OAuthAuthentication().challenge() + class SimpleAuthentication(SessionAuthentication): def is_authenticated(self, request): @@ -38,4 +40,4 @@ def is_authenticated(self, request): return False request.user = user - return True \ No newline at end of file + return True diff --git a/wouso/interface/api/c2dm/admin.py b/wouso/interface/api/c2dm/admin.py index 75273fbd..08d1a148 100644 --- a/wouso/interface/api/c2dm/admin.py +++ b/wouso/interface/api/c2dm/admin.py @@ -1,7 +1,9 @@ from django.contrib import admin from models import Device + class DeviceAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'player', 'registered') -admin.site.register(Device, DeviceAdmin) \ No newline at end of file + +admin.site.register(Device, DeviceAdmin) diff --git a/wouso/interface/api/c2dm/models.py b/wouso/interface/api/c2dm/models.py index 1add1446..8072cab8 100644 --- a/wouso/interface/api/c2dm/models.py +++ b/wouso/interface/api/c2dm/models.py @@ -1,11 +1,13 @@ import logging -import urllib, urllib2 +import urllib +import urllib2 from django.db import models from django.conf import settings from wouso.core.user.models import Player C2DM_URL = 'https://android.apis.google.com/c2dm/send' + class Device(models.Model): player = models.ForeignKey(Player) registered = models.DateTimeField(auto_now_add=True, editable=False) @@ -17,7 +19,7 @@ def send_message(self, collapse_key='', **kwargs): 'collapse_key': collapse_key, } - for key,value in kwargs.iteritems(): + for key, value in kwargs.iteritems(): values['data.%s' % key] = value headers = { @@ -34,7 +36,7 @@ def send_message(self, collapse_key='', **kwargs): parts = result.split('=') if 'Error' in parts: - #if result[1] == 'InvalidRegistration' or result[1] == 'NotRegistered': + # if result[1] == 'InvalidRegistration' or result[1] == 'NotRegistered': raise Exception(result[1]) except urllib2.URLError: return False @@ -44,14 +46,16 @@ def send_message(self, collapse_key='', **kwargs): def __unicode__(self): return 'Device #%d' % self.id + def register_device(player, registration_id): """ Register a new device to the given player """ device = Device.objects.create(player=player, registration_id=registration_id) device.send_message(payload='Registered') + def notify_user(player, message, collapse_key='wouso'): """ Send push notifications to all devices registered to tis user """ for d in player.device_set.all(): - d.send_message(collapse_key=collapse_key, payload=message) \ No newline at end of file + d.send_message(collapse_key=collapse_key, payload=message) diff --git a/wouso/interface/api/handlers.py b/wouso/interface/api/handlers.py index 8fab4680..f7a26024 100644 --- a/wouso/interface/api/handlers.py +++ b/wouso/interface/api/handlers.py @@ -27,6 +27,7 @@ from . import API_VERSION + def get_fullpath(request): base = 'http://%s' % request.get_host() fullpath = request.get_full_path() @@ -36,6 +37,7 @@ def get_fullpath(request): query = '' return base + fullpath, query + class ApiRoot(BaseHandler): allowed_methods = ('GET',) @@ -47,6 +49,7 @@ def read(self, request): } return api + class Search(BaseHandler): allowed_methods = ('GET',) @@ -61,7 +64,7 @@ class OnlineUsers(BaseHandler): allowed_methods = ('GET',) def read(self, request, type=None): - oldest = datetime.now() - timedelta(minutes = 10) + oldest = datetime.now() - timedelta(minutes=10) online_last10 = Player.objects.filter(last_seen__gte=oldest).order_by('-last_seen') if type == 'list': @@ -90,6 +93,7 @@ def read(self, request, type): else: return rc.BAD_REQUEST + class NotificationsRegister(BaseHandler): allowed_methods = ('POST',) @@ -104,6 +108,7 @@ def create(self, request): register_device(player, attrs['registration_id']) return {'success': True} + class NotificationsDevices(BaseHandler): allowed_methods = ('GET',) @@ -111,6 +116,7 @@ def read(self, request): player = request.user.get_profile() return [dict(registration_id=d.registration_id) for d in player.device_set.all()] + class InfoHandler(BaseHandler): allowed_methods = ('GET',) @@ -131,7 +137,7 @@ def read(self, request, player_id=None): 'title': player.level.title, 'image': player.level.image, 'id': player.level.id, - } if player.level else {} + } if player.level else {} group = player.group gold = player.coins['gold'] if 'gold' in player.coins.keys() else 0 @@ -227,8 +233,7 @@ def read(self, request): 'player_id': s.player.id, 'player': unicode(s.player), 'image_url': s.spell.image_url} for s in player.magic.spells_cast] return {'spells_available': spells_available, 'spells_onme': spells_onme, - 'spells_cast': spells_cast - } + 'spells_cast': spells_cast} class BazaarBuy(BaseHandler): @@ -257,6 +262,7 @@ def create(self, request): SpellHistory.bought(player, spell) return {'success': True} + class BazaarExchange(BaseHandler): allowed_methods = ('POST',) @@ -289,6 +295,7 @@ def create(self, request, coin, tocoin): return {'success': True, 'coins': player.coins} + class Messages(BaseHandler): LIMIT = 100 @@ -302,14 +309,13 @@ def to_dict(self, m): 'to': unicode(m.receiver), 'to_id': m.receiver_id, 'text': m.text, 'subject': m.subject, 'reply_to': m.reply_to.id if m.reply_to else None, - 'read': m.read - } + 'read': m.read} def read(self, request, type='all'): player = request.user.get_profile() msguser = player.get_extension(MessagingUser) if type == 'all': - qs = Message.objects.filter(Q(sender=msguser)|Q(receiver=msguser)).exclude(archived=True)[:self.LIMIT] + qs = Message.objects.filter(Q(sender=msguser) | Q(receiver=msguser)).exclude(archived=True)[:self.LIMIT] elif type == 'sent': qs = Message.objects.filter(sender=msguser)[:self.LIMIT] elif type == 'recv': @@ -318,6 +324,7 @@ def read(self, request, type='all'): return [] return [self.to_dict(m) for m in qs] + class MessagesSender(BaseHandler): allowed_methods = ('POST',) @@ -419,7 +426,7 @@ def create(self, request, player_id): return {'success': False, 'error': 'Invalid days parameter'} due = datetime.now() + timedelta(days=days) - error = destination.magic.cast_spell(spell, source=player, due=due) + error = destination.magic.cast_spell(spell, source=player, due=due) if error is not None: return {'succes': False, 'error': 'Cast failed, %s' % error} @@ -479,6 +486,7 @@ def read(self, request, group_id=None, race_id=None): return [dict(first_name=p.user.first_name, last_name=p.user.last_name, id=p.id, points=p.points, level=p.level_no, avatar=player_avatar(p), display_name=unicode(p)) for p in qs] + class GroupHandler(BaseHandler): allowed_methods = ('GET',) @@ -491,7 +499,7 @@ def read(self, request, group_id, type=None): gh = GroupHistory(group) fp, q = get_fullpath(request) - if type is None: # General information + if type is None: # General information return { 'id': group.id, 'name': group.name, @@ -499,8 +507,7 @@ def read(self, request, group_id, type=None): 'members': group.players.count(), 'rank': gh.position, 'activity': '%sactivity/%s' % (fp, q), - 'evolution': '%sevolution/%s' % (fp, q), - } + 'evolution': '%sevolution/%s' % (fp, q)} elif type == 'activity': qs = Activity.get_group_activiy(group) return [dict(user_from=unicode(a.user_from), user_to=unicode(a.user_to), message=a.message, date=a.timestamp) for a in qs] diff --git a/wouso/interface/api/tests.py b/wouso/interface/api/tests.py index 120f68d3..d75bf1df 100644 --- a/wouso/interface/api/tests.py +++ b/wouso/interface/api/tests.py @@ -76,7 +76,6 @@ def test_notification_register_fail(self): data = json.loads(response.content) self.assertEqual(data['error'], 'No registration_id provided') - def test_notification_register_ok(self): response = self.client.post('/api/notifications/register/', {'registration_id': '1245'}) @@ -97,4 +96,4 @@ def test_cast(self): response = self.client.post('/api/player/{id}/cast/'.format(id=u2.id), {'spell': s.id}) data = json.loads(response.content) - self.assertEqual(data['success'], True) \ No newline at end of file + self.assertEqual(data['success'], True) diff --git a/wouso/interface/api/urls.py b/wouso/interface/api/urls.py index a06dfa43..6836c780 100644 --- a/wouso/interface/api/urls.py +++ b/wouso/interface/api/urls.py @@ -8,7 +8,8 @@ from authentication import SessionAuthentication, SimpleAuthentication # needed by oauth -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^oauth/request_token/$', csrf_exempt(oauth_request_token), name='oauth_request_token'), url(r'^oauth/authorize/$', csrf_exempt(oauth_user_auth), name='oauth_authorize'), url(r'^oauth/access_token/$', csrf_exempt(oauth_access_token), name='oauth_access_token'), @@ -20,18 +21,20 @@ # API: sessionauth = SessionAuthentication() -#simple = SimpleAuthentication() +# simple = SimpleAuthentication() authoauth = OAuthAuthentication(realm='Wouso') -ad = {'authentication': [#simple, - authoauth, - sessionauth] +ad = {'authentication': [ + # simple, + authoauth, + sessionauth] } notifications_resource = Resource(handler=NotificationsHandler, **ad) -urlpatterns += patterns('', - #url(r'^$', Resource(handler=ApiRoot, **ad)), - url(r'^$', Resource(handler=ApiRoot)), # no authentication for basic info +urlpatterns += patterns( + '', + # url(r'^$', Resource(handler=ApiRoot, **ad)), + url(r'^$', Resource(handler=ApiRoot)), # no authentication for basic info url(r'^notifications/register/$', Resource(handler=NotificationsRegister, **ad)), url(r'^notifications/devices/$', Resource(handler=NotificationsDevices, **ad)), url(r'^notifications/(?P[^/]+)/$', notifications_resource), @@ -82,4 +85,4 @@ if api: for k, v in api.iteritems(): resource = Resource(handler=v, **ad) - urlpatterns += patterns('', url(k, resource)) \ No newline at end of file + urlpatterns += patterns('', url(k, resource)) diff --git a/wouso/interface/api/views.py b/wouso/interface/api/views.py index 36db196e..76fe002a 100644 --- a/wouso/interface/api/views.py +++ b/wouso/interface/api/views.py @@ -16,14 +16,15 @@ def request_token_ready(request, token=None): """ error = request.GET.get('error', '') ctx = RequestContext(request, { - 'error' : error, - 'token' : token, + 'error': error, + 'token': token, }) return render_to_response( 'piston/request_token_ready.html', - context_instance = ctx + context_instance=ctx ) + @api_enabled_required def oauth_auth_view(request, token, callback, params): """ This shows the: "Do you want to authorize X on Y?" message @@ -36,10 +37,11 @@ def oauth_auth_view(request, token, callback, params): form = forms.OAuthAuthenticationForm(initial={ 'oauth_token': token.key, 'oauth_callback': token.get_callback_url() or callback, - }) + }) consumer_key = request.GET.get('oauth_consumer_key', '') consumer = Consumer.objects.get(key=consumer_key) - return render_to_response('piston/authorize_token.html', - { 'form': form, 'consumer': consumer }, RequestContext(request)) + return render_to_response( + 'piston/authorize_token.html', + {'form': form, 'consumer': consumer}, RequestContext(request)) diff --git a/wouso/interface/apps/__init__.py b/wouso/interface/apps/__init__.py index 3084a6e1..c448d818 100644 --- a/wouso/interface/apps/__init__.py +++ b/wouso/interface/apps/__init__.py @@ -7,4 +7,4 @@ def get_apps(): from wouso.interface.activity.achievements import Achievements from wouso.interface.top.models import Top - return MessageApp, Bazaar, Achievements, Top \ No newline at end of file + return MessageApp, Bazaar, Achievements, Top diff --git a/wouso/interface/apps/files/admin.py b/wouso/interface/apps/files/admin.py index ad5c917d..e4e9f9ea 100644 --- a/wouso/interface/apps/files/admin.py +++ b/wouso/interface/apps/files/admin.py @@ -4,4 +4,3 @@ admin.site.register(File) admin.site.register(FileCategory) - diff --git a/wouso/interface/apps/files/cpanel_urls.py b/wouso/interface/apps/files/cpanel_urls.py index 790b1782..4a6edf4c 100644 --- a/wouso/interface/apps/files/cpanel_urls.py +++ b/wouso/interface/apps/files/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.apps.files.cpanel_views', +urlpatterns = patterns( + 'wouso.interface.apps.files.cpanel_views', url(r'^$', 'files', name='files'), url(r'^add_file/$', 'add_file', name='add_file'), url(r'^edit_file/(?P\d+)/$', 'edit_file', name='edit_file'), diff --git a/wouso/interface/apps/files/urls.py b/wouso/interface/apps/files/urls.py index e6f72930..7b3f437d 100644 --- a/wouso/interface/apps/files/urls.py +++ b/wouso/interface/apps/files/urls.py @@ -1,6 +1,7 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.apps.files.views', +urlpatterns = patterns( + 'wouso.interface.apps.files.views', url(r'^$', 'index', name='files_index_view'), ) diff --git a/wouso/interface/apps/lesson/cpanel_urls.py b/wouso/interface/apps/lesson/cpanel_urls.py index c35489f9..0d231e61 100644 --- a/wouso/interface/apps/lesson/cpanel_urls.py +++ b/wouso/interface/apps/lesson/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.apps.lesson.cpanel_views', +urlpatterns = patterns( + 'wouso.interface.apps.lesson.cpanel_views', url(r'^$', 'lessons', name='lessons'), url(r'^add_lesson/$', 'add_lesson', name='add_lesson'), url(r'^edit_lesson/(?P\d+)/$', 'edit_lesson', name='edit_lesson'), diff --git a/wouso/interface/apps/lesson/tests.py b/wouso/interface/apps/lesson/tests.py index cd53b9c8..a60ea3ce 100644 --- a/wouso/interface/apps/lesson/tests.py +++ b/wouso/interface/apps/lesson/tests.py @@ -4,7 +4,8 @@ from wouso.interface.apps.lesson.models import LessonCategory, LessonTag, Lesson -class LessonCategoryTestCase(TestCase): + +class LessonCategoryTestCase(TestCase): @raises(IntegrityError) def test_lesson_cateory_name_is_unique(self): @@ -14,11 +15,11 @@ def test_lesson_cateory_name_is_unique(self): lesson_category2.save() -class LessonTestCase(TestCase): +class LessonTestCase(TestCase): @raises(IntegrityError) def test_lesson_tag_is_unique(self): - lesson_tag = LessonTag.objects.create() + lesson_tag = LessonTag.objects.create() lesson = Lesson.objects.create(tag=lesson_tag) lesson2 = Lesson.objects.create(tag=lesson_tag) lesson1.save() diff --git a/wouso/interface/apps/lesson/urls.py b/wouso/interface/apps/lesson/urls.py index ce07b168..1e7ac142 100644 --- a/wouso/interface/apps/lesson/urls.py +++ b/wouso/interface/apps/lesson/urls.py @@ -1,13 +1,15 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.apps.lesson.views', +urlpatterns = patterns( + 'wouso.interface.apps.lesson.views', url(r'^$', 'index', name='lesson_index_view'), url(r'^cat/(?P\d+)/$', 'category', name='lesson_category_view'), url(r'^tag/(?P\d+)/$', 'tag', name='lesson_tag_view'), url(r'^(?P\d+)/$', 'lesson', name='lesson_view'), ) -urlpatterns += patterns('wouso.games.quiz.views', +urlpatterns += patterns( + 'wouso.games.quiz.views', url(r'^(?P\d+)/$', 'quiz', name='quiz_view'), ) diff --git a/wouso/interface/apps/magic/urls.py b/wouso/interface/apps/magic/urls.py index 502ad9bf..95ff872e 100644 --- a/wouso/interface/apps/magic/urls.py +++ b/wouso/interface/apps/magic/urls.py @@ -1,9 +1,10 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.interface.apps.magic.views', +urlpatterns = patterns( + 'wouso.interface.apps.magic.views', url(r'^$', 'bazaar', name='bazaar_home'), url(r'^bazaar/buy/(?P\d+)/$', 'bazaar_buy', name='bazaar_buy'), url(r'^bazaar/exchange/$', 'bazaar_exchange', name='bazaar_exchange'), url(r'^hof/$', 'artifact_hof', name='artifact_hof'), url(r'^hof/(?P\d+)/$', 'artifact_hof', name='artifact_hof'), -) \ No newline at end of file +) diff --git a/wouso/interface/apps/magic/views.py b/wouso/interface/apps/magic/views.py index 233927e7..e36eb8a1 100644 --- a/wouso/interface/apps/magic/views.py +++ b/wouso/interface/apps/magic/views.py @@ -17,14 +17,16 @@ from wouso.core import scoring, signals from wouso.interface.activity.models import Activity + class BazaarView(ListView): template_name = 'magic/bazaar.html' context_object_name = 'activity' paginate_by = 40 def get_queryset(self): - activity_list = Activity.objects.filter(Q(action='spell-buy') | Q(action='earned-ach') | - Q(action__contains='gold') | Q(action='cast')).order_by('-timestamp') + activity_list = Activity.objects.filter( + Q(action='spell-buy') | Q(action='earned-ach') | + Q(action__contains='gold') | Q(action='cast')).order_by('-timestamp') return activity_list def get_context_data(self, **kwargs): @@ -36,7 +38,7 @@ def get_context_data(self, **kwargs): exchange_disabled = BoolSetting.get('setting-bazaar-exchange').get_value() is False try: rate = scoring.calculate('gold-points-rate', gold=1)['points'] - rate2 = round(1/scoring.calculate('points-gold-rate', points=1)['gold']) + rate2 = round(1 / scoring.calculate('points-gold-rate', points=1)['gold']) except InvalidFormula: rate, rate2 = 1, 1 rate_text = _('Rate: 1 gold = {rate} points, {rate2} points = 1 gold').format(rate=rate, @@ -56,8 +58,10 @@ def get_context_data(self, **kwargs): 'exchange_disabled': exchange_disabled}) return context + bazaar = BazaarView.as_view() + @login_required def bazaar_exchange(request): gold_rate = scoring.calculate('gold-points-rate', gold=1)['points'] @@ -103,22 +107,24 @@ def bazaar_exchange(request): if message: messages.success(request, message) - return render_to_response('magic/bazaar_buy.html', - {'tab': 'exchange'}, - context_instance=RequestContext(request)) + return render_to_response( + 'magic/bazaar_buy.html', + {'tab': 'exchange'}, + context_instance=RequestContext(request)) + @login_required def bazaar_buy(request, spell): spell = get_object_or_404(Spell, pk=spell) player = request.user.get_profile() - error, message = '','' + error, message = '', '' if Bazaar.disabled(): error = _("Magic is disabled") elif spell.price > player.coins.get('gold', 0): error = _("Insufficient gold amount") - elif spell.available == False: + elif spell.available is False: error = _("Spell is not available") elif spell.level_required > player.level_no: error = _("Level {level} is required to buy this spell").format(level=spell.level_required) @@ -128,12 +134,9 @@ def bazaar_buy(request, spell): price=spell.price) signal_msg = ugettext_noop('bought a spell') action_msg = 'spell-buy' - signals.addActivity.send(sender=None, user_from=player, - user_to=player, - message=signal_msg, - game=None, - action=action_msg, - public=False) + signals.addActivity.send( + sender=None, user_from=player, user_to=player, message=signal_msg, + game=None, action=action_msg, public=False) SpellHistory.bought(player, spell) message = _("Successfully acquired") @@ -144,6 +147,7 @@ def bazaar_buy(request, spell): return redirect('bazaar_home') + @login_required def magic_cast(request, destination=None, spell=None): player = request.user.get_profile() @@ -198,11 +202,14 @@ def affected_players(request): destination = get_object_or_404(Player, pk=user_id) players = destination.get_neighbours_from_top(2, user.race, spell.type) players = user.magic.filter_players_by_spell(players, spell) - else : + else: user = get_object_or_404(Player, pk=user_id) players = [user] - return render_to_response('profile/mass_cast_players_list.html', { 'players':players }, context_instance=RequestContext(request)) + return render_to_response( + 'profile/mass_cast_players_list.html', + {'players': players}, + context_instance=RequestContext(request)) @login_required @@ -215,5 +222,7 @@ def artifact_hof(request, artifact=None): artifacts = Artifact.objects.all().annotate(used=Count('playerartifactamount')).filter(group__name='Default').order_by('-used') players = Player.objects.all().annotate(owned=Count('playerartifactamount')).exclude(owned=0).order_by('-owned')[:10] - return render_to_response('magic/artifact_hof.html', {'artifacts': artifacts, 'players': players, 'artifact': artifact}, + return render_to_response( + 'magic/artifact_hof.html', + {'artifacts': artifacts, 'players': players, 'artifact': artifact}, context_instance=RequestContext(request)) diff --git a/wouso/interface/apps/messaging/admin.py b/wouso/interface/apps/messaging/admin.py index dc91cb3f..e2107036 100644 --- a/wouso/interface/apps/messaging/admin.py +++ b/wouso/interface/apps/messaging/admin.py @@ -1,9 +1,11 @@ from django.contrib import admin from models import MessagingUser, Message + class MessageAdmin(admin.ModelAdmin): list_filter = ('read', 'sender', 'receiver') list_display = ('__unicode__', 'subject', 'text', 'timestamp') + admin.site.register(MessagingUser) admin.site.register(Message, MessageAdmin) diff --git a/wouso/interface/apps/messaging/forms.py b/wouso/interface/apps/messaging/forms.py index 4754cacc..ab5270e3 100644 --- a/wouso/interface/apps/messaging/forms.py +++ b/wouso/interface/apps/messaging/forms.py @@ -2,6 +2,7 @@ from wouso.core.user.models import Player from wouso.interface.apps.messaging.models import Message + class ComposeForm(forms.Form): to = forms.ModelChoiceField(queryset=Player.objects.all()) subject = forms.CharField(max_length=200, required=False) diff --git a/wouso/interface/apps/messaging/models.py b/wouso/interface/apps/messaging/models.py index 7c5adaeb..687253cf 100644 --- a/wouso/interface/apps/messaging/models.py +++ b/wouso/interface/apps/messaging/models.py @@ -5,7 +5,8 @@ from wouso.core.common import App from wouso.core.user.models import Player -CONSECUTIVE_LIMIT = 12 # in seconds +CONSECUTIVE_LIMIT = 12 # in seconds + class MessagingUser(Player): """ extension of the user profile, customized for messages """ @@ -52,9 +53,9 @@ def set_unread(self): def __unicode__(self): sender = _('System') if not self.sender else self.sender.__unicode__() - return _(u"from {sender} to {receiver} @ {date}").format(sender=sender, - receiver=self.receiver.__unicode__(), - date=self.timestamp.strftime("%A, %d %B %Y %I:%M %p")) + return _(u"from {sender} to {receiver} @ {date}").format( + sender=sender, receiver=self.receiver.__unicode__(), + date=self.timestamp.strftime("%A, %d %B %Y %I:%M %p")) @classmethod def disable_check(cls): @@ -70,7 +71,7 @@ def can_send(cls, sender, receiver): Check against scripts and spam """ if not sender or not cls._CHECK: - return True # System message + return True # System message sender = sender.get_extension(MessagingUser) seconds_since_last = (datetime.now() - sender.last_message_ts).seconds if sender.last_message_ts else 0 @@ -80,7 +81,6 @@ def can_send(cls, sender, receiver): return True - @classmethod def send(cls, sender, receiver, subject, text, reply_to=None): if not cls.can_send(sender, receiver): diff --git a/wouso/interface/apps/messaging/tests.py b/wouso/interface/apps/messaging/tests.py index 2247054b..c82945c6 100644 --- a/wouso/interface/apps/messaging/tests.py +++ b/wouso/interface/apps/messaging/tests.py @@ -7,6 +7,7 @@ from django.test import TestCase + class SimpleTest(TestCase): def test_basic_addition(self): """ @@ -14,10 +15,10 @@ def test_basic_addition(self): """ self.failUnlessEqual(1 + 1, 2) + __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """} - diff --git a/wouso/interface/apps/messaging/urls.py b/wouso/interface/apps/messaging/urls.py index 73e0ddd3..80acce32 100644 --- a/wouso/interface/apps/messaging/urls.py +++ b/wouso/interface/apps/messaging/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -urlpatterns = patterns('wouso.interface.apps.messaging.views', +urlpatterns = patterns( + 'wouso.interface.apps.messaging.views', url(r'^$', 'home', name='messaging'), url(r'^create$', 'create', name='create'), url(r'^create/to=(?P\d+)$', 'create', name='create_to'), diff --git a/wouso/interface/apps/messaging/views.py b/wouso/interface/apps/messaging/views.py index d36e834f..33b229c5 100644 --- a/wouso/interface/apps/messaging/views.py +++ b/wouso/interface/apps/messaging/views.py @@ -12,6 +12,7 @@ from wouso.interface.apps.messaging.forms import ComposeForm from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger + @login_required def home(request, quiet=None, box=None): @@ -28,7 +29,7 @@ def home(request, quiet=None, box=None): messages = Message.objects.none() # working here - messages = messages.order_by('-timestamp') + messages = messages.order_by('-timestamp') paginator = Paginator(messages, 20) page = request.GET.get('page') @@ -69,23 +70,23 @@ def create(request, to=None, reply_to=None): form = ComposeForm(request.POST) if form.is_valid(): m = Message.send(request.user.get_profile(), - form.cleaned_data['to'], - form.cleaned_data['subject'], - form.cleaned_data['text'], - reply_to=reply_to.id if reply_to else None, - ) + form.cleaned_data['to'], + form.cleaned_data['subject'], + form.cleaned_data['text'], + reply_to=reply_to.id if reply_to else None) if m is None: return HttpResponseRedirect(reverse('messaging')) else: error = m - #else: - # print form, form.is_valid(), request.POST + # else: + # print form, form.is_valid(), request.POST return render_to_response('messaging/create.html', {'error': error, 'to': to, 'reply_to': reply_to, 'subject': subject}, context_instance=RequestContext(request)) + @login_required def message(request, mid): message = get_object_or_404(Message, pk=mid) diff --git a/wouso/interface/apps/pages/__init__.py b/wouso/interface/apps/pages/__init__.py index a2873c99..7fdaf6b0 100644 --- a/wouso/interface/apps/pages/__init__.py +++ b/wouso/interface/apps/pages/__init__.py @@ -1,2 +1 @@ __author__ = 'alex' - \ No newline at end of file diff --git a/wouso/interface/apps/pages/models.py b/wouso/interface/apps/pages/models.py index bf5f0a44..f5a9d637 100644 --- a/wouso/interface/apps/pages/models.py +++ b/wouso/interface/apps/pages/models.py @@ -1,14 +1,14 @@ import datetime from django.db import models from django.core.urlresolvers import reverse, NoReverseMatch -from wouso.core.user.models import Player ## this needs to be fixed to wouso.core.user.models +from wouso.core.user.models import Player # this needs to be fixed to wouso.core.user.models class StaticPage(models.Model): - position = models.IntegerField(primary_key=True) + position = models.IntegerField(primary_key=True) slug = models.CharField(max_length=50, blank=False) name = models.CharField(max_length=100, blank=False) - title = models.CharField(max_length=200, blank=False) + title = models.CharField(max_length=200, blank=False) html_contents = models.TextField() hidden = models.BooleanField(default=False, blank=True) @@ -18,7 +18,7 @@ def __unicode__(self): def html_link(self): try: return '%s' % (reverse('static_page', args=(self.slug,)), - self.slug, self.name) + self.slug, self.name) except NoReverseMatch: return '' diff --git a/wouso/interface/apps/pages/urls.py b/wouso/interface/apps/pages/urls.py index 022f3372..d75a09a0 100644 --- a/wouso/interface/apps/pages/urls.py +++ b/wouso/interface/apps/pages/urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * from django.conf import settings -urlpatterns = patterns('wouso.interface.apps.pages.views', +urlpatterns = patterns( + 'wouso.interface.apps.pages.views', url(r'^$', 'news_index', name='news_index_view'), url(r'^(?P\d+)/$', 'news_item', name='news_item_view'), ) diff --git a/wouso/interface/apps/pages/views.py b/wouso/interface/apps/pages/views.py index 8a8e4247..622d40ba 100644 --- a/wouso/interface/apps/pages/views.py +++ b/wouso/interface/apps/pages/views.py @@ -3,6 +3,7 @@ from django.template import RequestContext, loader from wouso.interface.apps.pages.models import StaticPage, NewsItem + def staticpage(request, slug): """ Perform regular search by either first or last name """ staticpage = get_object_or_404(StaticPage, slug=slug) @@ -16,6 +17,7 @@ def staticpage(request, slug): {'staticpage': staticpage}, context_instance=RequestContext(request)) + def news_index(request, page=u'1'): all_news = NewsItem.objects.all().order_by('-date_pub') @@ -26,12 +28,13 @@ def news_index(request, page=u'1'): news_page = paginator.page(paginator.num_pages) return render_to_response('pages/news_index.html', - {'news_page': news_page}, + {'news_page': news_page}, context_instance=RequestContext(request)) + def news_item(request, item_id): n = get_object_or_404(NewsItem, pk=item_id) return render_to_response('pages/news_item.html', - {'n': n}, + {'n': n}, context_instance=RequestContext(request)) diff --git a/wouso/interface/apps/qproposal/__init__.py b/wouso/interface/apps/qproposal/__init__.py index f52bd08d..d8bdfa9d 100644 --- a/wouso/interface/apps/qproposal/__init__.py +++ b/wouso/interface/apps/qproposal/__init__.py @@ -1,3 +1,3 @@ QOTD_GOLD = 10 CHALLENGE_GOLD = 20 -QUEST_GOLD = 30 \ No newline at end of file +QUEST_GOLD = 30 diff --git a/wouso/interface/apps/qproposal/forms.py b/wouso/interface/apps/qproposal/forms.py index 36b3f6cf..2cbdd85e 100644 --- a/wouso/interface/apps/qproposal/forms.py +++ b/wouso/interface/apps/qproposal/forms.py @@ -5,7 +5,7 @@ class QuestionForm(forms.Form): text = forms.CharField(max_length=500, widget=forms.Textarea) - answer_type = forms.ChoiceField(choices=(('R', 'Single'), ('C','Multiple'))) + answer_type = forms.ChoiceField(choices=(('R', 'Single'), ('C', 'Multiple'))) category = forms.ChoiceField(choices=[(cat.name, cat.name) for cat in Category.objects.all().exclude(name='proposed')], widget=forms.Select(attrs={ 'id': 'select-category'})) @@ -13,14 +13,13 @@ def __init__(self, nr_ans=6, data=None): super(QuestionForm, self).__init__(data) self.nr_ans = nr_ans for i in range(nr_ans): - self.fields['answer_%d' % i] = forms.CharField(max_length=100, - widget=forms.Textarea, required=False) + self.fields['answer_%d' % i] = forms.CharField( + max_length=100, widget=forms.Textarea, required=False) self.fields['correct_%d' % i] = forms.BooleanField(required=False, label="Correct?") alltags = Tag.objects.all().exclude(name__in=['qotd', 'challenge', 'quest']) self.fields['tags'] = forms.MultipleChoiceField( - choices=[(tag.name, tag.name) for tag in alltags], - widget=forms.SelectMultiple(attrs={ - 'id': 'select-tags'}), required=False) + choices=[(tag.name, tag.name) for tag in alltags], + widget=forms.SelectMultiple(attrs={'id': 'select-tags'}), required=False) def clean(self): cleaned_data = self.cleaned_data diff --git a/wouso/interface/apps/qproposal/models.py b/wouso/interface/apps/qproposal/models.py index 6ac21816..7d9455e0 100644 --- a/wouso/interface/apps/qproposal/models.py +++ b/wouso/interface/apps/qproposal/models.py @@ -1,4 +1,5 @@ from wouso.core.common import App + class Qproposal(App): - pass \ No newline at end of file + pass diff --git a/wouso/interface/apps/qproposal/urls.py b/wouso/interface/apps/qproposal/urls.py index ab728ac2..cad7becb 100644 --- a/wouso/interface/apps/qproposal/urls.py +++ b/wouso/interface/apps/qproposal/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import * -#from django.conf import settings +# from django.conf import settings -urlpatterns = patterns('wouso.interface.apps.qproposal.views', +urlpatterns = patterns( + 'wouso.interface.apps.qproposal.views', url(r'^$', 'propose', name='propose') ) diff --git a/wouso/interface/apps/statistics/models.py b/wouso/interface/apps/statistics/models.py index 1fa4b02d..ecb7b005 100644 --- a/wouso/interface/apps/statistics/models.py +++ b/wouso/interface/apps/statistics/models.py @@ -1,4 +1,5 @@ from wouso.core.common import App + class Statistics(App): - pass \ No newline at end of file + pass diff --git a/wouso/interface/apps/statistics/tests.py b/wouso/interface/apps/statistics/tests.py index 2247054b..c82945c6 100644 --- a/wouso/interface/apps/statistics/tests.py +++ b/wouso/interface/apps/statistics/tests.py @@ -7,6 +7,7 @@ from django.test import TestCase + class SimpleTest(TestCase): def test_basic_addition(self): """ @@ -14,10 +15,10 @@ def test_basic_addition(self): """ self.failUnlessEqual(1 + 1, 2) + __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """} - diff --git a/wouso/interface/apps/statistics/urls.py b/wouso/interface/apps/statistics/urls.py index c6a0af98..7fce158c 100644 --- a/wouso/interface/apps/statistics/urls.py +++ b/wouso/interface/apps/statistics/urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * -#from django.conf import settings +# from django.conf import settings -urlpatterns = patterns('wouso.interface.apps.statistics.views', +urlpatterns = patterns( + 'wouso.interface.apps.statistics.views', url(r'^$', 'stats', name='stats'), url(r'^extra/$', 'extra_stats', name='extra_stats'), ) diff --git a/wouso/interface/apps/statistics/views.py b/wouso/interface/apps/statistics/views.py index 346c4a72..b9e78769 100644 --- a/wouso/interface/apps/statistics/views.py +++ b/wouso/interface/apps/statistics/views.py @@ -16,6 +16,7 @@ from wouso.interface.activity.models import Activity from models import Statistics + def stats(request): data = {} @@ -99,8 +100,10 @@ def stats(request): def footer_link(request): if Statistics.disabled(): return '' - link = '' + _('Live stats') + '' + link = '' + _('Live stats') + '' return link + + register_footer_link('statistics', footer_link) @@ -179,4 +182,4 @@ def extra_stats(request): data['quest_reached_10'] = ql10 # Pack and print - return HttpResponse(json.dumps(data)) \ No newline at end of file + return HttpResponse(json.dumps(data)) diff --git a/wouso/interface/context_processors.py b/wouso/interface/context_processors.py index d34533da..39272f74 100644 --- a/wouso/interface/context_processors.py +++ b/wouso/interface/context_processors.py @@ -11,6 +11,7 @@ from wouso.settings import FORCE_SCRIPT_NAME from . import set_theme + def context(request): """ Make all configuration settings available as config_name and also define some game context @@ -18,13 +19,14 @@ def context(request): settings_dict = {} settings_dict['basepath'] = FORCE_SCRIPT_NAME for s in Setting.objects.all(): - settings_dict['config_' + s.name.replace('-','_').lower()] = s.get_value() + settings_dict['config_' + s.name.replace('-', '_').lower()] = s.get_value() for k, v in settings_dict.iteritems(): if k.startswith('config_disable'): try: settings_dict[k] = bool(v) - except ValueError: pass + except ValueError: + pass # user defined theme if request.user.is_authenticated(): diff --git a/wouso/interface/cpanel/forms.py b/wouso/interface/cpanel/forms.py index 163793dd..4e8fb8d0 100644 --- a/wouso/interface/cpanel/forms.py +++ b/wouso/interface/cpanel/forms.py @@ -402,4 +402,4 @@ def __init__(self, data=None, players=None): super(KarmaBonusForm, self).__init__(data) for p in players: self.fields['%s' % p.user.username] = forms.IntegerField(label=unicode(p), initial=0, min_value=0, - required=True, help_text=" ") \ No newline at end of file + required=True, help_text=" ") diff --git a/wouso/interface/cpanel/tests.py b/wouso/interface/cpanel/tests.py index d4bc856b..272da9ca 100644 --- a/wouso/interface/cpanel/tests.py +++ b/wouso/interface/cpanel/tests.py @@ -312,13 +312,12 @@ def test_change_password_view_post(self): p1 = self._get_player(1) self.assertTrue(p1.user.check_password('secret')) - # Check the view with an invalid form + # Check the view with an invalid form data = {'password': 'test'} response = self.client.post(reverse('change_password', args=[p1.pk]), data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'This field is required') - def test_races_groups_view(self): """ Test adds races and groups and verifies the following situations: diff --git a/wouso/interface/cpanel/urls.py b/wouso/interface/cpanel/urls.py index ef3b17c2..510b0ff3 100644 --- a/wouso/interface/cpanel/urls.py +++ b/wouso/interface/cpanel/urls.py @@ -31,7 +31,7 @@ url(r'^questions/cat/(?P\w+)/tag=(?P\d+)/$', 'wouso.interface.cpanel.views.qpool_home', name='qpool_home'), url(r'^questions/qpool_remove_all/(?P\w+)/$', 'wouso.interface.cpanel.views.qpool_remove_all', name='remove_all'), url(r'^questions/manage_tags/$', 'wouso.interface.cpanel.views.qpool_managetags', name='qpool_manage_tags'), - url(r'^questions/newtag/$','wouso.interface.cpanel.views.qpool_add_tag', name='qpool_add_tag'), + url(r'^questions/newtag/$', 'wouso.interface.cpanel.views.qpool_add_tag', name='qpool_add_tag'), url(r'^questions/edit_tag/(?P\d+)/$', 'wouso.interface.cpanel.views.qpool_edit_tag', name='qpool_edit_tag'), url(r'^questions/del_tag/(?P\d+)/$', 'wouso.interface.cpanel.views.qpool_delete_tag', name='qpool_del_tag'), url(r'^questions/set_tag/$', 'wouso.interface.cpanel.views.qpool_settag', name='qpool_set_tag'), @@ -48,16 +48,16 @@ url(r'^karma/group/(?P\d+)/$', 'wouso.interface.cpanel.views.karma_group_view', name='karma_group'), - url(r'^spells/$','wouso.interface.cpanel.views.spells', name='spells'), + url(r'^spells/$', 'wouso.interface.cpanel.views.spells', name='spells'), url(r'^spells/switch_active/(?P\d+)/$', 'wouso.interface.cpanel.views.spell_switch', name='spell_switch_active'), - url(r'^spells/edit_spell/(?P\d+)$','wouso.interface.cpanel.views.edit_spell',name='edit_spell'), - url(r'^spells/add_spell/$', 'wouso.interface.cpanel.views.add_spell',name='add_spell'), + url(r'^spells/edit_spell/(?P\d+)$', 'wouso.interface.cpanel.views.edit_spell', name='edit_spell'), + url(r'^spells/add_spell/$', 'wouso.interface.cpanel.views.add_spell', name='add_spell'), url(r'^spells/del/(?P\d+)/$', 'wouso.interface.cpanel.views.spell_delete', name='spell_dell'), - url(r'^formulas/$','wouso.interface.cpanel.views.formulas',name='formulas'), - url(r'^formulas/edit_formula/(?P\d+)/$','wouso.interface.cpanel.views.edit_formula',name='edit_formula'), - url(r'^formulas/del/(?P\d+)/$','wouso.interface.cpanel.views.formula_delete',name='formula_del'), - url(r'^formulas/add_formula/$','wouso.interface.cpanel.views.add_formula',name='add_formula'), + url(r'^formulas/$', 'wouso.interface.cpanel.views.formulas', name='formulas'), + url(r'^formulas/edit_formula/(?P\d+)/$', 'wouso.interface.cpanel.views.edit_formula', name='edit_formula'), + url(r'^formulas/del/(?P\d+)/$', 'wouso.interface.cpanel.views.formula_delete', name='formula_del'), + url(r'^formulas/add_formula/$', 'wouso.interface.cpanel.views.add_formula', name='add_formula'), url(r'^group/set/(?P\d*)/$', 'wouso.interface.cpanel.views.groupset', name='group_set'), url(r'^staff/toggle/(?P\d+)/$', 'wouso.interface.cpanel.views.stafftoggle', name='staff_toggle'), @@ -77,12 +77,11 @@ url(r'^races/groups/add/$', 'wouso.interface.cpanel.views.group_add', name='group_add'), url(r'^races/edit/(?P\d+)/$', 'wouso.interface.cpanel.views.races_edit', name='races_edit'), - url(r'^races/groups/edit/(?P\d+)/$', 'wouso.interface.cpanel.views.group_edit', name='group_edit'), + url(r'^races/groups/edit/(?P\d+)/$', 'wouso.interface.cpanel.views.group_edit', name='group_edit'), url(r'^roles/$', 'wouso.interface.cpanel.views.roles', name='roles'), url(r'^roles/(?P\d+)/$', 'wouso.interface.cpanel.views.roles_update', name='roles_update'), url(r'^roles/(?P\d+)/kick/player=(?P\d+)/$', 'wouso.interface.cpanel.views.roles_update_kick', name='roles_update_kick'), - url(r'^roles/roles_create$', 'wouso.interface.cpanel.views.roles_create', -name='roles_create'), + url(r'^roles/roles_create$', 'wouso.interface.cpanel.views.roles_create', name='roles_create'), (r'^lessons/', include('wouso.interface.apps.lesson.cpanel_urls')), (r'^files/', include('wouso.interface.apps.files.cpanel_urls')), @@ -110,5 +109,5 @@ ] for g, trash in get_cpanel_games().items(): - upat.append((r'{game}/'.format(game=g), include('wouso.{game}.cpanel_urls'.format(game=g.replace('/','.'))))) + upat.append((r'{game}/'.format(game=g), include('wouso.{game}.cpanel_urls'.format(game=g.replace('/', '.'))))) urlpatterns = patterns('', *upat) diff --git a/wouso/interface/cpanel/views.py b/wouso/interface/cpanel/views.py index d4b8ed3b..2e2f5f84 100644 --- a/wouso/interface/cpanel/views.py +++ b/wouso/interface/cpanel/views.py @@ -325,6 +325,7 @@ def get_context_data(self, **kwargs): return context + customization_levels = permission_required('config.change_setting')( CustomizationLevelsView.as_view()) @@ -554,8 +555,7 @@ def qpool_set_active_categories(request): form = TagsForm(tags=tags) return render_to_response('cpanel/qpool_setactivetags.html', {'form': form, 'tags': tags}, - context_instance=RequestContext(request) - ) + context_instance=RequestContext(request)) class QpoolImporterView(TemplateView): @@ -581,7 +581,7 @@ def qpool_import_from_upload(request): tags = request.POST.getlist('tags') all_active = False - if request.POST.has_key('all_active'): + if 'all_active' in request.POST: all_active = True endorsed_by = request.user else: @@ -986,13 +986,13 @@ def infraction_recheck(request): for p in all_participants: id = None if p.user_from.count(): - if p.user_from.all()[0].status == 'P' and p.user_from.all()[ - 0].winner.id != p.user.id: + if (p.user_from.all()[0].status == 'P' and + p.user_from.all()[0].winner.id != p.user.id): user = p.user.player_ptr id = p.user_from.all()[0].id if p.user_to.count(): - if p.user_to.all()[0].status == 'P' and p.user_to.all()[ - 0].winner.id != p.user.id: + if (p.user_to.all()[0].status == 'P' and + p.user_to.all()[0].winner.id != p.user.id): user = p.user.player_ptr id = p.user_to.all()[0].id if id: @@ -1047,13 +1047,16 @@ class GroupsAdd(CreateView): def get_success_url(self): return reverse('races_groups') + class GroupsEdit(CreateView): model = PlayerGroup template_name = 'cpanel/races/group_edit.html' form_class = PlayerGroupForm + def get_success_url(self): return reverse('races_groups') + races_groups = permission_required('config.change_setting')( RacesGroupsView.as_view() ) @@ -1071,6 +1074,7 @@ def get_success_url(self): GroupsEdit.as_view() ) + class RolesView(ListView): template_name = 'cpanel/roles.html' model = Group @@ -1102,8 +1106,7 @@ def roles_update(request, id): user.groups.add(group) return render_to_response('cpanel/roles_update.html', {'role': group}, - context_instance=RequestContext(request) - ) + context_instance=RequestContext(request)) @permission_required('superuser') @@ -1315,10 +1318,11 @@ def bonus(request, player_id): external_id=request.user.get_profile().id, **{coin.name: amount}) if form.cleaned_data['reason']: - add_activity(player, _( - 'received {amount} {coin} bonus for {reason}'), - amount=amount, coin=coin, - reason=form.cleaned_data['reason']) + add_activity( + player, + _('received {amount} {coin} bonus for {reason}'), + amount=amount, coin=coin, + reason=form.cleaned_data['reason']) messages.info(request, 'Successfully given bonus') return redirect('manage_player', pk=player.id) else: diff --git a/wouso/interface/forms.py b/wouso/interface/forms.py index 3a11df2c..9160718a 100644 --- a/wouso/interface/forms.py +++ b/wouso/interface/forms.py @@ -1,11 +1,13 @@ from django import forms + class SearchForm(forms.Form): query = forms.CharField(max_length=100) + class InstantSearchForm(forms.Form): q = forms.CharField(max_length=100) + class SearchOneForm(forms.Form): q = forms.CharField(max_length=100) - diff --git a/wouso/interface/forum/cpanel_urls.py b/wouso/interface/forum/cpanel_urls.py index 746f7337..12527ff1 100644 --- a/wouso/interface/forum/cpanel_urls.py +++ b/wouso/interface/forum/cpanel_urls.py @@ -1,6 +1,7 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.forum.cpanel_views', +urlpatterns = patterns( + 'wouso.interface.forum.cpanel_views', url(r'^$', 'forum', name='forum'), url(r'^add_forum/$', 'add_forum', name='add_forum'), url(r'^edit_forum/(?P\d+)/$', 'edit_forum', name='edit_forum'), diff --git a/wouso/interface/forum/tests.py b/wouso/interface/forum/tests.py index c59b4731..b6a8143c 100644 --- a/wouso/interface/forum/tests.py +++ b/wouso/interface/forum/tests.py @@ -14,11 +14,10 @@ def setUp(self): def test_forum_view(self): response = self.client.get(reverse('forums_overview')) - self.assertContains(response,"Forums") + self.assertContains(response, "Forums") def test_category_view(self): - category = Category.objects.create (name="aCategory") + category = Category.objects.create(name="aCategory") response = self.client.get(reverse('forums_overview')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'aCategory') - diff --git a/wouso/interface/forum/urls.py b/wouso/interface/forum/urls.py index 4041b720..f6378475 100644 --- a/wouso/interface/forum/urls.py +++ b/wouso/interface/forum/urls.py @@ -1,7 +1,8 @@ from django.conf.urls import patterns, url -urlpatterns = patterns('wouso.interface.forum.views', +urlpatterns = patterns( + 'wouso.interface.forum.views', url(r'^$', 'category', name='forums_overview'), url(r'^(?P\d+)/$', 'forum', name='forum'), url(r'^(?P\d+)/create/$', 'topic_create', name='topic_create'), diff --git a/wouso/interface/loaders.py b/wouso/interface/loaders.py index 0d036e34..1cc6f9bf 100644 --- a/wouso/interface/loaders.py +++ b/wouso/interface/loaders.py @@ -3,6 +3,7 @@ from django.template.loader import BaseLoader, TemplateDoesNotExist from . import get_theme + class Loader(BaseLoader): """ Theme template loader: the selected theme can override templates @@ -27,4 +28,4 @@ def load_template_source(self, template_name, template_dirs=None): file.close() except IOError: pass - raise TemplateDoesNotExist(template_name) \ No newline at end of file + raise TemplateDoesNotExist(template_name) diff --git a/wouso/interface/profile/urls.py b/wouso/interface/profile/urls.py index f16d6f3e..36d8af6f 100644 --- a/wouso/interface/profile/urls.py +++ b/wouso/interface/profile/urls.py @@ -1,11 +1,13 @@ from django.conf.urls.defaults import patterns, url from django.core.urlresolvers import reverse_lazy -urlpatterns = patterns('wouso.interface.profile.views', +urlpatterns = patterns( + 'wouso.interface.profile.views', url(r'^race/(?P\d+)/.*$', 'player_race', name='race_view'), ) -urlpatterns += patterns('django.contrib.auth.views', +urlpatterns += patterns( + 'django.contrib.auth.views', url(r'^password_change/$', 'password_change', {'template_name': 'registration/password_change_form.html', diff --git a/wouso/interface/profile/views.py b/wouso/interface/profile/views.py index 3cc82b62..501670f6 100644 --- a/wouso/interface/profile/views.py +++ b/wouso/interface/profile/views.py @@ -45,7 +45,6 @@ def clean_nickname(self): self.cleaned_data['nickname'] = strip_tags(self.cleaned_data['nickname'].strip().replace(' ', '_')) return self.cleaned_data['nickname'] - if request.method == 'POST': form = SForm(request.POST, instance=user) if form.is_valid(): @@ -66,8 +65,8 @@ def save_profile(request): data = request.REQUEST try: - Player.objects.exclude(nickname = user.nickname).get(nickname = data['nickname']) - #print "exista!" + Player.objects.exclude(nickname=user.nickname).get(nickname=data['nickname']) + # print "exista!" return HttpResponseBadRequest() except: user.nickname = data['nickname'] @@ -97,15 +96,15 @@ def user_profile(request, id, page=u'1'): if hasattr(g, 'user_model'): model = getattr(g, 'user_model') setattr(profile, model.__name__.lower(), profile.get_extension(model)) - #Fix to show succes message from report user form + # Fix to show succes message from report user form if 'report_msg' in request.session: message = request.session['report_msg'] del request.session['report_msg'] else: - message='' + message = '' - challenge_launched_recently = Challenge.exist_last_day(date.today(), - request.user.get_profile(), profile) + challenge_launched_recently = Challenge.exist_last_day( + date.today(), request.user.get_profile(), profile) specialquest_button = SpecialQuestGame.get_specialquest_user_button(request, profile) config_disable_magic = BoolSetting.get('setting-magic').get_value() is False @@ -153,6 +152,7 @@ def player_group(request, id, page=u'1'): }, context_instance=RequestContext(request)) + @login_required def player_race(request, race_id): race = get_object_or_404(Race, pk=race_id) @@ -175,20 +175,19 @@ def player_race(request, race_id): # Get levels levels = [] for i, limit in enumerate(God.get_level_limits()): - l = God.get_race_level(level_no=i + 1, race=race) - l.limit = limit - levels.append(l) + level = God.get_race_level(level_no=i + 1, race=race) + level.limit = limit + levels.append(level) return render_to_response('profile/race.html', - {'race': race, - 'children': groups, - 'top_users': top_users, - 'top_rank': top_rank, - 'top': ObjectHistory(), - 'activity': activity, - 'levels': levels}, - context_instance=RequestContext(request) - ) + {'race': race, + 'children': groups, + 'top_users': top_users, + 'top_rank': top_rank, + 'top': ObjectHistory(), + 'activity': activity, + 'levels': levels}, + context_instance=RequestContext(request)) @login_required @@ -210,7 +209,7 @@ def magic_summary(request): return render_to_response('profile/spells.html', {'cast': cast_spells, - 'theowner': player}, + 'theowner': player}, context_instance=RequestContext(request)) diff --git a/wouso/interface/templatetags/ui.py b/wouso/interface/templatetags/ui.py index 3d285c99..31fa767a 100644 --- a/wouso/interface/templatetags/ui.py +++ b/wouso/interface/templatetags/ui.py @@ -3,6 +3,7 @@ from wouso.core.config.models import Setting register = template.Library() + @register.simple_tag(takes_context=True) def render_zone(context, zone, glue): """ @@ -45,6 +46,7 @@ def render_header(context): content += ' ' return content + @register.simple_tag(takes_context=True) def render_footer(context): return render_zone(context=context, zone='footer', glue=' | ') diff --git a/wouso/interface/tests.py b/wouso/interface/tests.py index a79165a6..46ae9434 100644 --- a/wouso/interface/tests.py +++ b/wouso/interface/tests.py @@ -3,6 +3,7 @@ from wouso.core.tests import WousoTest from bs4 import BeautifulSoup + class TestInterface(WousoTest): def test_homepage_anonymous(self): result = self.client.get('/') @@ -43,6 +44,6 @@ def test_user_has_no_control_panel_button(self): player = self._get_player() self.client.login(username=player.user.username, password='test') response = self.client.get('/hub') - soup = BeautifulSoup(response.content, "html.parser") + soup = BeautifulSoup(response.content, "html.parser") button = soup.find_all(id="head-cpanel") - self.assertEqual(len(button), 0) \ No newline at end of file + self.assertEqual(len(button), 0) diff --git a/wouso/interface/top/admin.py b/wouso/interface/top/admin.py index 4f7ac613..34892da7 100644 --- a/wouso/interface/top/admin.py +++ b/wouso/interface/top/admin.py @@ -4,6 +4,9 @@ admin.site.register(TopUser) admin.site.register(History) + class NHAdmin(admin.ModelAdmin): list_display = ('date', 'object', 'object_type', 'relative_to', 'relative_to_type', 'position') + + admin.site.register(NewHistory, NHAdmin) diff --git a/wouso/interface/top/models.py b/wouso/interface/top/models.py index 996df11e..dde663b9 100644 --- a/wouso/interface/top/models.py +++ b/wouso/interface/top/models.py @@ -235,7 +235,10 @@ def get_group_position(kls, group, relative_to=None): return 0 def __unicode__(self): - return u"%s %s at %s, position: %d, points: %f" % ('[%s]' % self.relative_to if self.relative_to else '', self.user if self.user else self.group, self.date, self.position, self.points) + return u"%s %s at %s, position: %d, points: %f" % ( + '[%s]' % self.relative_to if self.relative_to else '', + self.user if self.user else self.group, + self.date, self.position, self.points) class Top(App): @@ -256,7 +259,7 @@ def get_sidebar_widget(kls, context): 'top': Top, 'coin_top_setting': kls.coin_top_settings(), 'config_disable_challenge_top': BoolSetting.get('setting-challenge-top').get_value() is False - }) + }) @classmethod def management_task(cls, now=None, stdout=sys.stdout): diff --git a/wouso/interface/top/tests.py b/wouso/interface/top/tests.py index 5d23fa72..dceab314 100644 --- a/wouso/interface/top/tests.py +++ b/wouso/interface/top/tests.py @@ -1,9 +1,10 @@ from wouso.core.tests import WousoTest from wouso.interface.top.models import TopUser + class TopTest(WousoTest): def test_challenges(self): player = self._get_player() top_player = player.get_extension(TopUser) - self.assertEqual(top_player.won_challenges, 0) \ No newline at end of file + self.assertEqual(top_player.won_challenges, 0) diff --git a/wouso/interface/top/urls.py b/wouso/interface/top/urls.py index 33ffe2f3..4be7a9dc 100644 --- a/wouso/interface/top/urls.py +++ b/wouso/interface/top/urls.py @@ -1,6 +1,7 @@ from django.conf.urls.defaults import patterns, url -urlpatterns = patterns('wouso.interface.top.views', +urlpatterns = patterns( + 'wouso.interface.top.views', # url(r'^$', 'gettop', name='view_top'), # url(r'^toptype/(?P\d)/sortcrit/(?P\d)/page/(?P\d+)/$', 'gettop', name='view_top'), # url(r'^pyramid/$', 'pyramid', name='pyramid'), diff --git a/wouso/interface/urls.py b/wouso/interface/urls.py index 55ff8b8d..239a9a9e 100644 --- a/wouso/interface/urls.py +++ b/wouso/interface/urls.py @@ -3,7 +3,8 @@ from django.contrib import admin admin.autodiscover() -urlpatterns = patterns('', +urlpatterns = patterns( + '', (r'^ckeditor/', include('ckeditor.urls')), url(r'^$', 'wouso.interface.views.homepage', name='homepage'), @@ -20,12 +21,12 @@ url(r'^leaderboard/$', 'wouso.interface.views.leaderboard_view', name='leaderboard'), url(r'^division/$', 'wouso.interface.views.division_view', name='division'), - url(r'^user/login/$','wouso.interface.views.login_view', name='login_view'), - url(r'^user/logout/$','wouso.interface.views.logout_view', name='logout_view'), + url(r'^user/login/$', 'wouso.interface.views.login_view', name='login_view'), + url(r'^user/logout/$', 'wouso.interface.views.logout_view', name='logout_view'), url(r'^player/(?P\d+)/$', 'wouso.interface.profile.views.user_profile', name='player_profile'), url(r'^player/set/$', 'wouso.interface.profile.views.set_profile', name='set_profile'), - url(r'^player/set/s/$','wouso.interface.profile.views.save_profile', name='player_profile'), + url(r'^player/set/s/$', 'wouso.interface.profile.views.save_profile', name='player_profile'), url(r'^player/(?P\d*)/(?P\d*)/$', 'wouso.interface.profile.views.user_profile', name="player_profile"), url(r'^player/(?P\d*)/points-summary/$', 'wouso.interface.profile.views.player_points_history', name='player_points_history'), url(r'^player/cast/to-(?P\d+)/$', 'wouso.interface.apps.magic.views.magic_cast', name='magic_cast'), @@ -46,14 +47,14 @@ (r'^searchone/$', 'wouso.interface.views.searchone'), url(r'^s/(.+)/$', 'wouso.interface.apps.pages.views.staticpage', name='static_page'), - #Lesson + # Lesson (r'^lessons/', include('wouso.interface.apps.lesson.urls')), - #Lesson + # Lesson (r'^files/', include('wouso.interface.apps.files.urls')), - #Report - url(r'^report/(?P\d*)/$','wouso.core.security.views.report', name='report_player'), + # Report + url(r'^report/(?P\d*)/$', 'wouso.core.security.views.report', name='report_player'), # Messaging (r'^m/', include('wouso.interface.apps.messaging.urls')), @@ -84,7 +85,7 @@ # Admin related (r'^cpanel/', include('interface.cpanel.urls')), (r'^admin/', include(admin.site.urls)), - #(r'^admin/djangologdb/', include('djangologdb.urls')), + # (r'^admin/djangologdb/', include('djangologdb.urls')), # Static: not in a real deployment (r'^static/(?P.*)$', 'django.views.static.serve', diff --git a/wouso/interface/views.py b/wouso/interface/views.py index 0ea4557d..2b6f3a90 100644 --- a/wouso/interface/views.py +++ b/wouso/interface/views.py @@ -36,6 +36,7 @@ def get_wall(page=u'1'): activity = paginator.page(paginator.num_pages) return activity + def anonymous_homepage(request): return render_to_response('splash.html', context_instance=RequestContext(request)) @@ -46,27 +47,27 @@ def login_view(request): if request.method != 'POST': form = AuthenticationForm(request) return render_to_response('registration/login.html', {'form': form, 'next': next}, - context_instance=RequestContext(request)) + context_instance=RequestContext(request)) else: form = AuthenticationForm(data=request.POST) if not form.is_valid(): return render_to_response('registration/login.html', {'form': form, 'next': next}, - context_instance=RequestContext(request)) + context_instance=RequestContext(request)) user = authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: if user.is_active: - #Save username in session + # Save username in session PREFIX = "_user:" - MAX_TIME = 48*60*60 #48h in seconds - #Remove entries older than 48h + MAX_TIME = 48 * 60 * 60 # 48h in seconds + # Remove entries older than 48h for i in request.session.keys(): - if PREFIX in i and (request.session.get(i) + datetime.timedelta(minutes = 2*24*60)) < datetime.datetime.now(): + if PREFIX in i and (request.session.get(i) + datetime.timedelta(minutes=2 * 24 * 60)) < datetime.datetime.now(): request.session.__delitem__(i) - request.session.__setitem__(PREFIX+user.username, datetime.datetime.now()) + request.session.__setitem__(PREFIX + user.username, datetime.datetime.now()) request.session.set_expiry(MAX_TIME) login(request, user) - signals.addActivity.send(sender=None, user_from=user.get_profile(), action="login", game = None, public=False) + signals.addActivity.send(sender=None, user_from=user.get_profile(), action="login", game=None, public=False) if request.POST.get('next'): return HttpResponseRedirect(request.POST.get('next')) return redirect(settings.LOGIN_REDIRECT_URL) @@ -100,7 +101,8 @@ def hub(request): from wouso.interface.apps.pages.models import StaticPage try: story = StaticPage.objects.get(slug='poveste') - except: pass + except: + pass else: return HttpResponseRedirect(reverse('static_page', args=(story.slug,))) return homepage(request) @@ -113,7 +115,7 @@ def homepage(request, page=u'1'): profile = request.user.get_profile() # gather users online in the last ten minutes - oldest = datetime.datetime.now() - datetime.timedelta(minutes = 10) + oldest = datetime.datetime.now() - datetime.timedelta(minutes=10) online_last10 = Player.objects.filter(last_seen__gte=oldest).order_by('-last_seen') activity = get_wall(page) @@ -135,13 +137,13 @@ def homepage(request, page=u'1'): return render_to_response(template, {'last10': online_last10, 'activity': activity, - 'is_homepage': True, - 'top': topuser, - 'topgroups': topgroups, - 'games': get_games(), - 'news': news, - 'more': more, - }, + 'is_homepage': True, + 'top': topuser, + 'topgroups': topgroups, + 'games': get_games(), + 'news': news, + 'more': more, + }, context_instance=RequestContext(request)) @@ -155,8 +157,7 @@ def search(request): if len(query.split()) == 1: if request.user.get_profile().in_staff_group(): searchresults = Player.objects.filter(Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | - Q(user__username__icontains=query) | Q(nickname__icontains=query) - ) + Q(user__username__icontains=query) | Q(nickname__icontains=query)) else: searchresults = Player.objects.filter(Q(nickname__icontains=query)) # special queries @@ -168,14 +169,13 @@ def search(request): if request.user.get_profile().in_staff_group(): for word in query: r = Player.objects.filter(Q(user__first_name__icontains=word) | Q(user__last_name__icontains=word) | - Q(nickname__icontains=query) - ) + Q(nickname__icontains=query)) searchresults = searchresults.union(r) else: searchresults = Player.objects.filter(Q(nickname__icontains=query)) # search groups - group_results = PlayerGroup.objects.filter(Q(name__icontains=query)|Q(title__icontains=query)) + group_results = PlayerGroup.objects.filter(Q(name__icontains=query) | Q(title__icontains=query)) return render_to_response('interface/search_results.html', {'searchresults': searchresults, @@ -237,7 +237,7 @@ def searchone(request): def ajax(request, name): if name == 'header': return render_to_response('interface/header.html', - context_instance=RequestContext(request)) + context_instance=RequestContext(request)) raise Http404 @@ -297,7 +297,7 @@ def seen_24h(request): """ Display all players seen in the last 24h """ - oldest = datetime.datetime.now() - datetime.timedelta(minutes = 3600) + oldest = datetime.datetime.now() - datetime.timedelta(minutes=3600) online_last24h = Player.objects.filter(last_seen__gte=oldest).order_by('-last_seen') return render_to_response('activity/seen24h.html', {'seen_players': online_last24h}, context_instance=RequestContext(request)) @@ -311,7 +311,7 @@ def leaderboard_view(request): races = list(Race.objects.exclude(can_play=False)) races.sort(key=lambda a: a.points, reverse=True) return render_to_response(('leaderboard.html'), - {'races':races, 'toptengroups':toptengroups, 'top':Top}, + {'races': races, 'toptengroups': toptengroups, 'top': Top}, context_instance=RequestContext(request)) diff --git a/wouso/manage.py b/wouso/manage.py index 6ce754ca..c34278ab 100755 --- a/wouso/manage.py +++ b/wouso/manage.py @@ -2,7 +2,7 @@ from django.core.management import execute_manager try: - import settings # Assumed to be in the same directory. + import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) diff --git a/wouso/middleware/__init__.py b/wouso/middleware/__init__.py index 61fcdce9..7246266d 100644 --- a/wouso/middleware/__init__.py +++ b/wouso/middleware/__init__.py @@ -1,3 +1,3 @@ from seen import Seen from debug import DebugExceptionMiddleware -from impersonation import ImpersonateMiddleware \ No newline at end of file +from impersonation import ImpersonateMiddleware diff --git a/wouso/middleware/debug.py b/wouso/middleware/debug.py index 3b44180d..ffb288e2 100644 --- a/wouso/middleware/debug.py +++ b/wouso/middleware/debug.py @@ -1,6 +1,7 @@ import logging from django.conf import settings + class DebugExceptionMiddleware(object): """ Throw 500 exceptions to the console. """ diff --git a/wouso/middleware/impersonation.py b/wouso/middleware/impersonation.py index 3e09a6b6..c9182f63 100644 --- a/wouso/middleware/impersonation.py +++ b/wouso/middleware/impersonation.py @@ -3,6 +3,7 @@ KEYWORD = "_as" + class ImpersonateMiddleware(object): def get_impersonation(self, request): if KEYWORD in request.GET: @@ -50,4 +51,4 @@ def process_response(self, request, response): location += "?" location += "%s=%s" % (KEYWORD, request.GET[KEYWORD]) response["Location"] = location - return response \ No newline at end of file + return response diff --git a/wouso/middleware/ldap_connection.py b/wouso/middleware/ldap_connection.py index 1e580797..32ea7ce5 100644 --- a/wouso/middleware/ldap_connection.py +++ b/wouso/middleware/ldap_connection.py @@ -3,7 +3,7 @@ import logging LDAP_URL = 'ldaps://swarm.cs.pub.ro:636' -LDAP_BINDNAME = '' # 'cn=admin,dc=swarm,dc=cs,dc=pub,dc=ro' +LDAP_BINDNAME = '' # 'cn=admin,dc=swarm,dc=cs,dc=pub,dc=ro' LDAP_BINDPASS = '' LDAP_BASECN = 'dc=swarm,dc=cs,dc=pub,dc=ro' LDAP_FILTER = '(uid=%s)' @@ -11,6 +11,7 @@ # Overwrite settings from wouso.settings import * + class LDAPBackend: def authenticate(self, username=None, password=None): if password == "" or password is None or username is None: @@ -21,11 +22,11 @@ def authenticate(self, username=None, password=None): conn = ldap.initialize(LDAP_URL) if LDAP_BINDNAME != '': conn.simple_bind_s(LDAP_BINDNAME, LDAP_BINDPASS) - result = conn.search_ext_s(LDAP_BASECN, ldap.SCOPE_SUBTREE, \ - LDAP_FILTER % username, None) + result = conn.search_ext_s(LDAP_BASECN, ldap.SCOPE_SUBTREE, + LDAP_FILTER % username, None) conn.unbind_s() except ldap.SERVER_DOWN: - #raise Exception('Authentication server is down') + # raise Exception('Authentication server is down') return None if len(result) == 0: @@ -53,7 +54,8 @@ def authenticate(self, username=None, password=None): except User.DoesNotExist: first_name = data['givenName'][0].decode('utf8') last_name = data['sn'][0].decode('utf8') - user = User(username=username, first_name=first_name, last_name=last_name, email=data['mail'][0]) + user = User(username=username, first_name=first_name, + last_name=last_name, email=data['mail'][0]) user.is_staff = False user.is_superuser = False user.is_active = True diff --git a/wouso/middleware/seen.py b/wouso/middleware/seen.py index d8cd0b17..34f893bd 100644 --- a/wouso/middleware/seen.py +++ b/wouso/middleware/seen.py @@ -1,9 +1,10 @@ from datetime import datetime from wouso.core import signals + class Seen: def process_request(self, request): -# import pprint; pprint.pprint(request.META['HTTP_AUTHORIZATION']);pprint.pprint(request.POST); + # import pprint; pprint.pprint(request.META['HTTP_AUTHORIZATION']);pprint.pprint(request.POST); if not request.user.is_anonymous(): try: profile = request.user.get_profile() @@ -14,12 +15,11 @@ def process_request(self, request): if not profile.last_seen or profile.last_seen.hour != datetime.now().hour: # Signal a new hour seen signals.addActivity.send(sender=None, - game=None, - user_from=profile, - user_to=profile, - action='seen', - public=False, - ) + game=None, + user_from=profile, + user_to=profile, + action='seen', + public=False) profile.last_seen = datetime.now() profile.save() return None diff --git a/wouso/utils/__init__.py b/wouso/utils/__init__.py index d2ce58c3..461471c7 100644 --- a/wouso/utils/__init__.py +++ b/wouso/utils/__init__.py @@ -1,5 +1,6 @@ import os + def get_themes(): themes_dir = os.path.abspath(os.path.dirname(__file__) + '/../resources/static/themes/') themes = [] @@ -9,4 +10,4 @@ def get_themes(): themes.append(g) return themes -# TODO: move scripts in this module to management commands. \ No newline at end of file +# TODO: move scripts in this module to management commands. diff --git a/wouso/utils/add_questions.py b/wouso/utils/add_questions.py index e0aba561..2b0c362f 100644 --- a/wouso/utils/add_questions.py +++ b/wouso/utils/add_questions.py @@ -73,6 +73,7 @@ def add_question(question): START_INCORRECT_ANSWER_MARK = "-" START_TAGS_MARK = "tags:" + def import_questions_from_file(f, proposed_by=None, endorsed_by=None, category=None, tag=None, active=False): # read file and parse contents a_saved = True @@ -110,7 +111,7 @@ def import_questions_from_file(f, proposed_by=None, endorsed_by=None, category=N q['tag'] = tag q['file_tags'] = file_tags ret = add_question(q) - print "Added question id %d." %(ret.id) + print "Added question id %d." % (ret.id) num_imported_questions += 1 q_saved = True a_saved = True @@ -152,12 +153,12 @@ def import_questions_from_file(f, proposed_by=None, endorsed_by=None, category=N else: a['correct'] = True a['text'] = line[len(START_CORRECT_ANSWER_MARK):].strip() - num_correct_answers +=1 + num_correct_answers += 1 else: # If nothing else, it's a continuation line. if state == 'question': - if q.has_key('text'): + if 'text' in q: q['text'] += '\n' + line else: q['text'] = line @@ -182,7 +183,7 @@ def import_questions_from_file(f, proposed_by=None, endorsed_by=None, category=N q['tag'] = tag q['file_tags'] = file_tags ret = add_question(q) - print "Added question id %d." %(ret.id) + print "Added question id %d." % (ret.id) num_imported_questions += 1 q_saved = True a_saved = True @@ -206,56 +207,56 @@ def main(): proposed_by = User.objects.get(username=proposed_by_name) except Exception as e: print e - print >>sys.stderr, "Proposed by user %s does not exist." %(proposed_by_name) + print >>sys.stderr, "Proposed by user %s does not exist." % (proposed_by_name) sys.exit(1) if not proposed_by: - print >>sys.stderr, "Proposed by user %s does not exist." %(proposed_by_name) + print >>sys.stderr, "Proposed by user %s does not exist." % (proposed_by_name) sys.exit(1) try: endorsed_by = User.objects.get(username=endorsed_by_name) except Exception as e: print e - print >>sys.stderr, "Endorsed by user %s does not exist." %(endorsed_by_name) + print >>sys.stderr, "Endorsed by user %s does not exist." % (endorsed_by_name) sys.exit(1) if not endorsed_by: - print >>sys.stderr, "Endorsed by user %s does not exist." %(endorsed_by_name) + print >>sys.stderr, "Endorsed by user %s does not exist." % (endorsed_by_name) sys.exit(1) try: category = Category.objects.get(name=category_name) except Exception as e: print e - print >>sys.stderr, "Category %s does not exist." %(category_name) + print >>sys.stderr, "Category %s does not exist." % (category_name) sys.exit(1) if not category: - print >>sys.stderr, "Category %s does not exist." %(category_name) + print >>sys.stderr, "Category %s does not exist." % (category_name) sys.exit(1) try: tag = Tag.objects.get(name=tag_name) except Exception as e: print e - print >>sys.stderr, "Tag %s does not exist." %(tag_name) + print >>sys.stderr, "Tag %s does not exist." % (tag_name) sys.exit(1) if not tag: - print >>sys.stderr, "Tag %s does not exist." %(tag_name) + print >>sys.stderr, "Tag %s does not exist." % (tag_name) sys.exit(1) try: f = codecs.open(filename, 'r', 'utf-8') except: - print >>sys.stderr, "Cannot open file %s for reading questions." %(filename) + print >>sys.stderr, "Cannot open file %s for reading questions." % (filename) sys.exit(1) - print "Import questions from file %s." %(filename) - print " Category: %s" %(category) - print " Tag: %s" %(tag) - print " Proposed by: %s" %(proposed_by) - print " Endorsed by: %s" %(endorsed_by) + print "Import questions from file %s." % (filename) + print " Category: %s" % (category) + print " Tag: %s" % (tag) + print " Proposed by: %s" % (proposed_by) + print " Endorsed by: %s" % (endorsed_by) n = import_questions_from_file(f, proposed_by, endorsed_by, category, tag, active=True) - print "\nImported %d questions." %(n) + print "\nImported %d questions." % (n) if __name__ == '__main__': diff --git a/wouso/utils/add_races.py b/wouso/utils/add_races.py index 8cc90200..a43f12a7 100644 --- a/wouso/utils/add_races.py +++ b/wouso/utils/add_races.py @@ -7,6 +7,7 @@ import csv import wouso.utils.user_util + def main(): if len(sys.argv) != 2: print 'Usage: python add_races.py ' @@ -19,9 +20,9 @@ def main(): race_name, race_title = row ret = wouso.utils.user_util.add_race(race_name, race_title) if ret: - print "Successfully added race %s." %(race_name) + print "Successfully added race %s." % (race_name) else: - print "Failed adding race %s." %(race_name) + print "Failed adding race %s." % (race_name) if __name__ == "__main__": diff --git a/wouso/utils/add_users.py b/wouso/utils/add_users.py index 377b830b..28a1e695 100644 --- a/wouso/utils/add_users.py +++ b/wouso/utils/add_users.py @@ -7,6 +7,7 @@ import csv import wouso.utils.user_util + def main(): if len(sys.argv) != 2: print 'Usage: python add_users.py ' @@ -19,9 +20,9 @@ def main(): username, first_name, last_name, email, password = row ret = wouso.utils.user_util.add_user(username, first_name, last_name, email, password, is_active=1, is_staff=0, is_superuser=0) if ret: - print "Successfully added user %s." %(username) + print "Successfully added user %s." % (username) else: - print "Failed adding user %s." %(username) + print "Failed adding user %s." % (username) if __name__ == "__main__": diff --git a/wouso/utils/add_users_force.py b/wouso/utils/add_users_force.py index 9fedc87d..712ac7be 100644 --- a/wouso/utils/add_users_force.py +++ b/wouso/utils/add_users_force.py @@ -11,10 +11,11 @@ OP_EXCEPTION = -1 OP_EXISTS = -2 + def try_using_index_no_recurse(username, first_name, last_name, email, password): ret = OP_EXISTS - for i in range(1,100): - _username = username+"%d" %(i) + for i in range(1, 100): + _username = username + "%d" % (i) ret = add_user_helper(_username, first_name, last_name, email, password) if ret == OP_SUCCESS: return (_username, ret) @@ -23,21 +24,25 @@ def try_using_index_no_recurse(username, first_name, last_name, email, password) return (_username, ret) return (_username, ret) + def truncate_username(username): parts = username.split('.') if len(parts) != 2: print >>sys.stderr, "Username %s should consist of two parts." return - return parts[0][0:1]+parts[1] + return parts[0][0:1] + parts[1] + def try_using_truncate_no_recurse(username, first_name, last_name, email, password): username = truncate_username(username) return (username, add_user_helper(username, first_name, last_name, email, password)) + def try_using_cookie_no_recurse(username, first_name, last_name, email, password, cookie): - username = username+cookie + username = username + cookie return (username, add_user_helper(username, first_name, last_name, email, password)) + def try_using_truncate(username, first_name, last_name, email, password, cookie): (username, ret) = try_using_truncate_no_recurse(username, first_name, last_name, email, password) @@ -136,13 +141,13 @@ def add_user_helper(username, first_name, last_name, email, password): try: ret = wouso.utils.user_util.add_user(username, first_name, last_name, email, password, is_active=1, is_staff=0, is_superuser=0) except Exception, e: - print "h: Exception when adding %s." %(username) + print "h: Exception when adding %s." % (username) return OP_EXCEPTION if ret: - print "h: Successfully added user %s." %(username) + print "h: Successfully added user %s." % (username) return OP_SUCCESS else: - print "h: Failed adding user %s. User already exists." %(username) + print "h: Failed adding user %s. User already exists." % (username) return OP_EXISTS @@ -178,9 +183,9 @@ def main(): username, first_name, last_name, email, password, cookie = row (_username, ret) = add_user_no_matter_what(username, first_name, last_name, email, password, cookie) if ret: - print "Successfully added user %s." %(_username) + print "Successfully added user %s." % (_username) if not ret: - print "Failed adding user %s. Nothing worked." %(username) + print "Failed adding user %s. Nothing worked." % (username) if __name__ == "__main__": diff --git a/wouso/utils/add_users_force_to_race.py b/wouso/utils/add_users_force_to_race.py index 83dfa9db..d5d7783c 100644 --- a/wouso/utils/add_users_force_to_race.py +++ b/wouso/utils/add_users_force_to_race.py @@ -11,10 +11,11 @@ OP_EXCEPTION = -1 OP_EXISTS = -2 + def try_using_index_no_recurse(username, first_name, last_name, email, password): ret = OP_EXISTS - for i in range(1,100): - _username = username+"%d" %(i) + for i in range(1, 100): + _username = username + "%d" % (i) ret = add_user_helper(_username, first_name, last_name, email, password) if ret == OP_SUCCESS: return (_username, ret) @@ -23,21 +24,25 @@ def try_using_index_no_recurse(username, first_name, last_name, email, password) return (_username, ret) return (_username, ret) + def truncate_username(username): parts = username.split('.') if len(parts) != 2: print >>sys.stderr, "Username %s should consist of two parts." return - return parts[0][0:1]+parts[1] + return parts[0][0:1] + parts[1] + def try_using_truncate_no_recurse(username, first_name, last_name, email, password): username = truncate_username(username) return (username, add_user_helper(username, first_name, last_name, email, password)) + def try_using_cookie_no_recurse(username, first_name, last_name, email, password, cookie): - username = username+cookie + username = username + cookie return (username, add_user_helper(username, first_name, last_name, email, password)) + def try_using_truncate(username, first_name, last_name, email, password, cookie): (username, ret) = try_using_truncate_no_recurse(username, first_name, last_name, email, password) @@ -136,13 +141,13 @@ def add_user_helper(username, first_name, last_name, email, password): try: ret = wouso.utils.user_util.add_user(username, first_name, last_name, email, password, is_active=1, is_staff=0, is_superuser=0) except Exception, e: - print "h: Exception when adding %s." %(username) + print "h: Exception when adding %s." % (username) return OP_EXCEPTION if ret: - print "h: Successfully added user %s." %(username) + print "h: Successfully added user %s." % (username) return OP_SUCCESS else: - print "h: Failed adding user %s. User already exists." %(username) + print "h: Failed adding user %s. User already exists." % (username) return OP_EXISTS @@ -178,14 +183,14 @@ def main(): username, first_name, last_name, email, password, cookie, race = row (_username, ret) = add_user_no_matter_what(username, first_name, last_name, email, password, cookie) if ret: - print "Successfully added user %s." %(_username) + print "Successfully added user %s." % (_username) ret2 = wouso.utils.user_util.add_user_to_race(_username, race) if ret2: - print "Successfully added user %s to race %s." %(_username, race) + print "Successfully added user %s to race %s." % (_username, race) else: - print "Failed adding user %s to race %s." %(_username, race) + print "Failed adding user %s to race %s." % (_username, race) if not ret: - print "Failed adding user %s. Nothing worked." %(_username) + print "Failed adding user %s. Nothing worked." % (_username) if __name__ == "__main__": diff --git a/wouso/utils/add_users_to_race.py b/wouso/utils/add_users_to_race.py index 52329866..6f9e0875 100644 --- a/wouso/utils/add_users_to_race.py +++ b/wouso/utils/add_users_to_race.py @@ -7,6 +7,7 @@ import csv import wouso.utils.user_util + def main(): if len(sys.argv) != 2: print 'Usage: python add_users_to_race.py ' @@ -19,9 +20,9 @@ def main(): username, race_name = row ret = wouso.utils.user_util.add_user_to_race(username, race_name) if ret: - print "Successfully added %s to race %s." %(username, race_name) + print "Successfully added %s to race %s." % (username, race_name) else: - print "Failed adding %s to race %s." %(username, race_name) + print "Failed adding %s to race %s." % (username, race_name) if __name__ == "__main__": diff --git a/wouso/utils/extract_data_from_oldmysql.py b/wouso/utils/extract_data_from_oldmysql.py index 689a08d7..881c778b 100644 --- a/wouso/utils/extract_data_from_oldmysql.py +++ b/wouso/utils/extract_data_from_oldmysql.py @@ -1,5 +1,6 @@ import MySQLdb as mdb + class Table: def __init__(self, db, name): self.db = db @@ -12,8 +13,9 @@ def __getitem__(self, item): def __len__(self): self.dbc.execute("select count(*) from %s" % (self.name)) - l = int(self.dbc.fetchone()[0]) - return l + length = int(self.dbc.fetchone()[0]) + return length + db = mdb.connect(db="baza", user='root', passwd='mihnea', charset='latin1') @@ -24,7 +26,7 @@ def __len__(self): b = unicode(a, 'utf-8') questions[int(records[i][0])] = b -#print questions +# print questions answers = {} records = Table(db, "anschall") @@ -50,4 +52,3 @@ def __len__(self): type = '-' f.write(type + ' ' + ans[0] + '\n') f.write('\n') - diff --git a/wouso/utils/get_stats.py b/wouso/utils/get_stats.py index 48509dd0..0b18433c 100644 --- a/wouso/utils/get_stats.py +++ b/wouso/utils/get_stats.py @@ -15,13 +15,14 @@ from wouso.core.user.models import Race from wouso.core.user.models import Player + def main(): ulist = User.objects.all() accounts_per_race_dict = {} for u in ulist: p = Player.objects.get(user__username=u.username) if not p: - print "Player account for username %s not found." %(u.username) + print "Player account for username %s not found." % (u.username) continue if not p.race: # Player with no race (such as admin). continue @@ -33,8 +34,9 @@ def main(): for race, num in accounts_per_race_dict.iteritems(): r = Race.objects.get(name=race) - print "%s, %s, %d" %(r.name, r.title, num) - print "Total: %d" %(ulist.count()) + print "%s, %s, %d" % (r.name, r.title, num) + print "Total: %d" % (ulist.count()) + if __name__ == "__main__": sys.exit(main()) diff --git a/wouso/utils/import_questions.py b/wouso/utils/import_questions.py index fa54a94a..2f62b0f2 100644 --- a/wouso/utils/import_questions.py +++ b/wouso/utils/import_questions.py @@ -63,7 +63,6 @@ def import_from_file(opened_file, proposed_by=None, endorsed_by=None, category=N nr_imported = 0 - state = 'question' for line in opened_file: @@ -133,7 +132,7 @@ def import_from_file(opened_file, proposed_by=None, endorsed_by=None, category=N else: # continuation line if state == 'question': - if q.has_key('text'): + if 'text' in q: q['text'] += '\n' + line else: q['text'] = line diff --git a/wouso/utils/remove_users.py b/wouso/utils/remove_users.py index cef74c2a..403c5835 100644 --- a/wouso/utils/remove_users.py +++ b/wouso/utils/remove_users.py @@ -7,6 +7,7 @@ import csv import wouso.utils.user_util + def main(): if len(sys.argv) != 2: print 'Usage: python remove_users.py ' @@ -18,12 +19,12 @@ def main(): try: ret = wouso.utils.user_util.remove_user(username) except Exception, e: - print "Failed removing user %s." %(username) + print "Failed removing user %s." % (username) else: if ret: - print "Successfully removed user %s." %(username) + print "Successfully removed user %s." % (username) else: - print "Failed removing user %s." %(username) + print "Failed removing user %s." % (username) if __name__ == "__main__": diff --git a/wouso/utils/scoring_update.py b/wouso/utils/scoring_update.py index 278d2661..fc972d01 100644 --- a/wouso/utils/scoring_update.py +++ b/wouso/utils/scoring_update.py @@ -3,10 +3,12 @@ import sys from django.core.management import setup_environ + def init(): import settings setup_environ(settings) + def main(): try: init() @@ -22,5 +24,6 @@ def main(): return 0 + if __name__ == '__main__': sys.exit(main()) diff --git a/wouso/utils/stats.py b/wouso/utils/stats.py index ced0a7df..06c4424a 100755 --- a/wouso/utils/stats.py +++ b/wouso/utils/stats.py @@ -38,7 +38,7 @@ def scoring_activity_stats(): 'player', 'days', 'days_positive' - ] + ] data.append(header) for p in Player.objects.all(): day = None @@ -78,7 +78,7 @@ def peruser_stats(): 'qotd_points', 'quest_points', 'special_gold', - ] + ] data.append(header) for p in Player.objects.all(): chall = p.get_extension(ChallengeUser) @@ -93,10 +93,11 @@ def peruser_stats(): History.user_points_from_game(p.user, QotdGame)['points'], History.user_points_from_game(p.user, QuestGame)['points'], History.user_points_from_game(p.user, SpecialQuestGame)['gold'], - ] + ] data.append(row) return data + def main(args): from django.db import models from wouso.core.user.models import Player @@ -109,7 +110,7 @@ def main(args): data = [] print "Analyzing ", start_date, "-", end_date for single_date in daterange(start_date, end_date): - #print strftime("%Y-%m-%d", single_date.timetuple()) + # print strftime("%Y-%m-%d", single_date.timetuple()) print '.' singledata = {'date': single_date, 'data': []} @@ -123,7 +124,7 @@ def main(args): if hss: player[formula.id] = hss has_score = True - #print formula.id, hss + # print formula.id, hss else: player[formula.id] = 0 @@ -144,6 +145,7 @@ def main(args): writer.writerow(row) print " done!" + if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--peruser', action='store_true') diff --git a/wouso/utils/tests.py b/wouso/utils/tests.py index e20be438..6ffaa7a6 100644 --- a/wouso/utils/tests.py +++ b/wouso/utils/tests.py @@ -14,11 +14,10 @@ def test_import_questions(self): self.assertEqual(count, 22) self.assertEqual(Question.objects.all().count(), 22) - def test_add_question(self): question = add({'text': "Question text"}, [{'text': 'answer 1'}]) self.assertTrue(question) self.assertEqual(question.text, "Question text") - self.assertEqual(question.answers.count(), 1) \ No newline at end of file + self.assertEqual(question.answers.count(), 1) diff --git a/wouso/utils/update_race_by_user_email.py b/wouso/utils/update_race_by_user_email.py index 5e8e40ae..97fd6e2c 100644 --- a/wouso/utils/update_race_by_user_email.py +++ b/wouso/utils/update_race_by_user_email.py @@ -13,25 +13,27 @@ from django.contrib.auth.models import User + def main(): if len(sys.argv) != 3: print 'Usage: python add_users.py ' sys.exit(1) - print "number of users: %d" %(User.objects.all().count()) + print "number of users: %d" % (User.objects.all().count()) for line in open(sys.argv[1], 'r'): email = line.strip() - print "email: %s" %(email) + print "email: %s" % (email) try: u = User.objects.get(email=email) except: - print "No user with email address %s." %(email) + print "No user with email address %s." % (email) continue if not u: - print "No user with email address %s." %(email) + print "No user with email address %s." % (email) continue wouso.utils.user_util.add_user_to_race(u.username, sys.argv[2]) - print "Updated race for user %s (%s) to %s." %(u.username, email, sys.argv[2]) + print "Updated race for user %s (%s) to %s." % (u.username, email, sys.argv[2]) + if __name__ == "__main__": sys.exit(main()) diff --git a/wouso/utils/user_util.py b/wouso/utils/user_util.py index 25988565..b5e6d4dd 100644 --- a/wouso/utils/user_util.py +++ b/wouso/utils/user_util.py @@ -21,12 +21,14 @@ UTF8Writer = codecs.getwriter('utf8') sys.stdout = UTF8Writer(sys.stdout) + def _print_user(user): """Print information about an user. """ - print "%s,%s,%s,%s,%s,%s,%s" %(user.username, user.first_name, \ - user.last_name, user.email, user.is_active, user.is_staff, \ - user.is_superuser) + print "%s,%s,%s,%s,%s,%s,%s" % ( + user.username, user.first_name, user.last_name, user.email, + user.is_active, user.is_staff, user.is_superuser) + def _print_player(player): """Print information about a player. Same as user but add race name. @@ -34,14 +36,17 @@ def _print_player(player): user = player.user race_name = player.race.name if player.race else "None" race_title = player.race.title if player.race else "None" - print "%s,%s,%s,%s,%s,%s,%s,%s,%s" %(user.username, user.first_name, \ - user.last_name, user.email, user.is_active, user.is_staff, \ - user.is_superuser, race_name, race_title) + print "%s,%s,%s,%s,%s,%s,%s,%s,%s" % ( + user.username, user.first_name, user.last_name, user.email, + user.is_active, user.is_staff, user.is_superuser, race_name, + race_title) + def _print_race(race): """Print information about a race. """ - print "%s,%s,%s" %(race.name, race.title, race.can_play) + print "%s,%s,%s" % (race.name, race.title, race.can_play) + def list_users(race=None): """List users belonging to a particular race. In case race is missing, @@ -50,7 +55,7 @@ def list_users(race=None): if race: users = [] for p in players: - if p.race == None: + if p.race is None: continue if p.race.name == race: users.append(p.user) @@ -59,6 +64,7 @@ def list_users(race=None): for u in users: _print_user(u) + def list_players(race=None): """List players belonging to a particular race. In case race is missing, list all players. Add printing of race name.""" @@ -66,7 +72,7 @@ def list_players(race=None): if race: players = [] for p in _players: - if p.race == None: + if p.race is None: continue if p.race.name == race: players.append(p) @@ -75,12 +81,14 @@ def list_players(race=None): for p in players: _print_player(p) + def list_races(race=None): """List all races. """ for r in Race.objects.all(): _print_race(r) + def show_user(username): """Show information of user. """ @@ -88,7 +96,8 @@ def show_user(username): if not p: return _print_user(p.user) - print "race: %s, %s" %(p.race.name, p.race.title) + print "race: %s, %s" % (p.race.name, p.race.title) + def show_race(race_name): """Show information about race. @@ -98,7 +107,9 @@ def show_race(race_name): return _print_race(r) -def add_user(username, first_name, last_name, email, password, is_active=False, is_staff=False, is_superuser=False): + +def add_user(username, first_name, last_name, email, password, + is_active=False, is_staff=False, is_superuser=False): """Add user and return user object. In case user with given username already exists, return None. """ @@ -116,9 +127,10 @@ def add_user(username, first_name, last_name, email, password, is_active=False, user.save() return user + def remove_user(username): - """Remove user by username. Return True if successful. Return False if user - does not exist. + """Remove user by username. Return True if successful. Return False if + user does not exist. """ user = User.objects.get(username=username) if not user: @@ -127,37 +139,42 @@ def remove_user(username): user.delete() return True -def update_user(username, first_name=None, last_name=None, email=None, password=None, is_active=None, is_staff=None, is_superuser=None): - """Update user by username. Return True if successful. Return False if user - does not exist. + +def update_user(username, first_name=None, last_name=None, email=None, + password=None, is_active=None, is_staff=None, + is_superuser=None): + """Update user by username. Return True if successful. Return False if + user does not exist. """ user = User.objects.get(username=username) if not user: return False - if first_name != None: + if first_name is not None: user.first_name = first_name - if last_name != None: + if last_name is not None: user.last_name = last_name - if email != None: + if email is not None: user.email = email - if password != None: + if password is not None: user.set_password(password) - if is_active != None: + if is_active is not None: user.is_active = is_active - if is_staff != None: + if is_staff is not None: user.is_staff = is_staff - if is_superuser != None: + if is_superuser is not None: user.is_superuser = is_superuser user.save() return True + def change_password(username, password): """Change user password. Return True on success. Return False if user does not exist. """ return update_user(username, password=password) + def add_race(name, title, can_play=False): """Add race and return race object. In case race already exists, return None. @@ -171,6 +188,7 @@ def add_race(name, title, can_play=False): race.save() return race + def remove_race(name): """Remove race by name. Return True if successful. Return False if race does not exist. @@ -182,21 +200,23 @@ def remove_race(name): race.delete() return True + def update_race(name, title=None, can_play=None): - """Update user by username. Return True if successful. Return False if user - does not exist. + """Update user by username. Return True if successful. Return False if + user does not exist. """ race = Race.objects.get(name=name) if not race: return False - if title != None: + if title is not None: race.title = title - if can_play != None: + if can_play is not None: race.can_play = can_play race.save() return True + def add_user_to_race(username, race_name): """Add user to race. Return True if successful. Return False if user or race does not exist.""" @@ -211,6 +231,7 @@ def add_user_to_race(username, race_name): player.save() return True + def remove_user_from_race(username, race_name): """Remove user from race. Return True if successful. Return False if user or race does not exist. Race is actually non important. It will simply be diff --git a/wouso/wsgi.py b/wouso/wsgi.py index d5bd10bf..0f7d5280 100644 --- a/wouso/wsgi.py +++ b/wouso/wsgi.py @@ -1,10 +1,11 @@ -import os, sys +import os +import sys # Add wouso folder and parent folder to path. sys.path.append(os.path.normpath(os.path.dirname(__file__))) -sys.path.append(os.path.join(os.path.normpath(os.path.dirname(__file__)),"..")) +sys.path.append(os.path.join(os.path.normpath(os.path.dirname(__file__)), "..")) -# Poiting to the project settings. +# Pointing to the project settings. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wouso.settings") from django.core.wsgi import get_wsgi_application