Esempio n. 1
0
def validate(request, pk):
   errors = []
   _messages = {
      "invalid_key": {
         "level": messages.ERROR,
         "text": _("Sorry, wrong key. Try again !")
         },
      "valid_key": {
         "level": messages.SUCCESS,
         "text": _("Congratulation, you found the key !")
         },
      "breakthrough": {
         "level": messages.WARNING,
         "text": _("Great, you just made a breakthrough !")
         },
      "already_done": {
         "level": messages.INFO,
         "text": _("This challenge was already done by your team !")
         },
      "before_start": {
         "level": messages.INFO,
         "text": _("The contest is not yet started !")
         },
      "after_end": {
         "level": messages.INFO,
         "text": _("The contest is finished !")
         },
      }

   # Check if the contest is open
   start_date = \
       datetime.datetime.strptime(settings.CONTEST_START_DATE, "%Y-%m-%d %H:%M")

   end_date = \
       datetime.datetime.strptime(settings.CONTEST_END_DATE, "%Y-%m-%d %H:%M")

   now = datetime.datetime.now()

   if (now <= start_date):
      messages.add_message(request,
                           _messages['before_start']['level'],
                           _messages['before_start']['text'])

      return HttpResponseRedirect('/challenges/')

   if (now >= end_date):
      messages.add_message(request,
                           _messages['after_end']['level'],
                           _messages['after_end']['text'])
      return HttpResponseRedirect('/challenges/')

   if request.method == 'POST':
      form = ChallengeValidationForm(request.POST)

      if form.is_valid():
         key = form.cleaned_data['key']

         if key == Challenge.objects.get(pk=pk).key:
            # Key is valid
            messages.add_message(request,
                                 _messages['valid_key']['level'],
                                 _messages['valid_key']['text'])

            team = request.user.team_set.filter()[:1].get()
            challenge = Challenge.objects.get(pk=pk)
            try:
               Validation.objects.filter(challenge=challenge)[:1].get()
               # Not a breakthrough
               try:
                  Validation.objects.get(challenge=challenge, team=team)
                  # Team has already validated this challenge
                  messages.add_message(request,
                                       _messages['already_done']['level'],
                                       _messages['already_done']['text'])
               except Validation.DoesNotExist:
                  # Validation was not already registered, creating it
                  validation = Validation(team=team,
                                          user=request.user,
                                          challenge=challenge)
                  validation.save()
                  team.is_active = True
                  team.save()

            except Validation.DoesNotExist:
               # Breakthrough !
               messages.add_message(request,
                                    _messages['breakthrough']['level'],
                                    _messages['breakthrough']['text'])
               validation = Validation(team=team,
                                       user=request.user,
                                       challenge=challenge)
               validation.save()
               team.is_active = True
               team.save()

         else:
            # Key is not valid
            messages.add_message(request,
                                 _messages['invalid_key']['level'],
                                 _messages['invalid_key']['text'])

   else:
      form = ChallengeValidationForm()
      messages.add_message(request,
                           _messages['invalid_key']['level'],
                           _messages['invalid_key']['text'])

   return HttpResponseRedirect('/challenges/')
Esempio n. 2
0
class CheckPublicPages(TestCase):
    """Check if all public pages are accessible to anonymous users."""
    def setUp(self):
        self.now = timezone.now()

        self.client = ValidatingClient()
        self.user = User.objects.create_user('test_user', '*****@*****.**', 'secret')
        self.user.save()

        self.team = Team(name='team', is_active=True)
        self.team.save()
        self.team.members.add(self.user)
        self.team.save()

        self.category = Category(name='category')
        self.category.save()

        self.challenge = Challenge(category=self.category,
                                   name='challenge', key='12345')
        self.challenge.save()

        self.validation = Validation(date=timezone.now(),
                                     user=self.user,
                                     team=self.team,
                                     challenge=self.challenge)
        self.validation.save()

    def tearDown(self):
        self.validation.delete()

        self.team.delete()
        self.user.delete()

        self.challenge.delete()
        self.category.delete()

    def test_public_homepage(self):
        # Before contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

        # During contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

        # After contest
        with self.settings(CONTEST_BEGIN_DATE=two_days_before(),
                           CONTEST_END_DATE=one_day_before()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

    def test_public_team_list_empty(self):
        self.team.delete()

        response = self.client.get(reverse('team_list'))
        self.assertEqual(response.status_code, 200)

        self.team.save()

    def test_public_team_list(self):
        response = self.client.get(reverse('team_list'))
        self.assertEqual(response.status_code, 200)

    def test_public_team_1(self):
        response = self.client.get('/team/1/')
        self.assertEqual(response.status_code, 200)

    def test_public_contestant_list_empty(self):
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            self.user.delete()

            response = self.client.get(reverse('contestant_list'))
            self.assertEqual(response.status_code, 200)

        self.user.save()

    def test_public_contestant_list(self):
        response = self.client.get(reverse('contestant_list'))
        self.assertEqual(response.status_code, 200)

    def test_public_contestant_1(self):
        response = self.client.get('/contestant/1/')
        self.assertEqual(response.status_code, 200)

    def test_public_challenge_list_empty(self):
        self.challenge.delete()

        # Before contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

        # During contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

        # After contest
        with self.settings(CONTEST_BEGIN_DATE=two_days_before(),
                           CONTEST_END_DATE=one_day_before()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

        self.challenge.save()

    def test_public_challenge_list(self):
        # Before contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

        # During contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

        # After contest
        with self.settings(CONTEST_BEGIN_DATE=two_days_before(),
                           CONTEST_END_DATE=one_day_before()):
            response = self.client.get(reverse('challenges'))
            self.assertEqual(response.status_code, 200)

    def test_public_ranking_list_empty(self):
        self.validation.delete()
        self.team.is_active = False
        self.team.save()

        response = self.client.get(reverse('ranking'))
        self.assertEqual(response.status_code, 200)

        self.team.is_active = True
        self.team.save()
        self.validation.save()

    def test_public_ranking_list(self):
        # Before contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            response = self.client.get(reverse('ranking'))
            self.assertEqual(response.status_code, 200)

        # During contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('ranking'))
            self.assertEqual(response.status_code, 200)

        # After contest
        with self.settings(CONTEST_BEGIN_DATE=two_days_before(),
                           CONTEST_END_DATE=one_day_before()):
            response = self.client.get(reverse('ranking'))
            self.assertEqual(response.status_code, 200)

    def test_public_rules(self):
        response = self.client.get(reverse('rules'))
        self.assertEqual(response.status_code, 200)

    def test_public_about(self):
        response = self.client.get(reverse('about'))
        self.assertEqual(response.status_code, 200)

    def test_public_login(self):
        response = self.client.get('/accounts/login/')
        self.assertEqual(response.status_code, 200)

    def test_public_account_signup(self):
        response = self.client.get('/accounts/signup/')
        self.assertEqual(response.status_code, 200)
Esempio n. 3
0
class CheckLoggedUserPages(TestCase):
    """Check if a logged user can access to private and public pages."""
    def setUp(self):
        self.now = timezone.now()

        self.client = ValidatingClient()

        self.user = User.objects.create_user('test_user', '*****@*****.**', 'secret')
        self.user.save()
        self.client.login(username='******', password='******')

        self.team = Team(name='team', is_active=True)
        self.team.save()
        self.team.members.add(self.user)
        self.team.save()

        self.user0 = User.objects.create_user('test_user0', '*****@*****.**', 'secret')
        self.user0.save()

        self.team0 = Team(name='team0', is_active=True)
        self.team0.save()
        self.team0.members.add(self.user0)
        self.team0.save()

        self.category = Category(name='category')
        self.category.save()

        self.challenge = Challenge(category=self.category,
                                   name='challenge', key='12345')
        self.challenge.save()

        self.validation = Validation(date=self.now,
                                     user=self.user,
                                     team=self.team,
                                     challenge=self.challenge)
        self.validation.save()

        self.validation0 = Validation(date=self.now,
                                     user=self.user0,
                                     team=self.team0,
                                     challenge=self.challenge)
        self.validation0.save()

    def tearDown(self):
        self.validation0.delete()
        self.validation.delete()

        self.team0.delete()
        self.user0.delete()

        self.team.delete()
        self.user.delete()

        self.challenge.delete()
        self.category.delete()

    def test_logged_user_accounts_logout(self):
        response = self.client.get('/accounts/logout/')
        self.assertEqual(response.status_code, 200)

    def test_logged_user_accounts_settings(self):
        response = self.client.get('/accounts/settings/')
        self.assertEqual(response.status_code, 200)

    def test_logged_user_accounts_password(self):
        response = self.client.get('/accounts/password/')
        self.assertEqual(response.status_code, 200)

    def test_logged_user_accounts_delete(self):
        response = self.client.get('/accounts/delete/')
        self.assertEqual(response.status_code, 200)

    def test_logged_user_homepage(self):
        # Before contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

        # During contest
        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

        # After contest
        with self.settings(CONTEST_BEGIN_DATE=two_days_before(),
                           CONTEST_END_DATE=one_day_before()):
            response = self.client.get(reverse('home'))
            self.assertEqual(response.status_code, 200)

    def test_logged_user_team_list(self):
        with self.settings(CONTEST_BEGIN_DATE=one_day_after(),
                           CONTEST_END_DATE=two_days_after()):
            self.team.delete()
            response = self.client.get(reverse('team_list'))
            self.assertEqual(response.status_code, 200)
            self.team.save()

        with self.settings(CONTEST_BEGIN_DATE=one_day_before(),
                           CONTEST_END_DATE=one_day_after()):
            response = self.client.get(reverse('team_list'))
            self.assertEqual(response.status_code, 200)

    def test_logged_user_team_create_with_a_team(self):
        response = self.client.get(reverse('team_create'), follow=True)
        self.assertRedirects(response, '/?next=/team/create/',
                             status_code=302, target_status_code=200)

    def test_logged_user_team_quit(self):
        response = self.client.get('/team/quit/1/')
        self.assertEqual(response.status_code, 200)

    def test_logged_user_non_existing_team_quit(self):
        response = self.client.get('/team/quit/10/')
        self.assertEqual(response.status_code, 404)

    def test_logged_user_contestant_list(self):
        response = self.client.get(reverse('contestant_list'))
        self.assertEqual(response.status_code, 200)

    def test_logged_user_challenge_list(self):
        response = self.client.get(reverse('challenges'))
        self.assertEqual(response.status_code, 200)

    def test_logged_user_ranking_list(self):
        response = self.client.get(reverse('ranking'))
        self.assertEqual(response.status_code, 200)

    def test_logged_user_rules(self):
        response = self.client.get(reverse('rules'))
        self.assertEqual(response.status_code, 200)

    def test_logged_user_about(self):
        response = self.client.get(reverse('about'))
        self.assertEqual(response.status_code, 200)
Esempio n. 4
0
def validate(request, pk):
   errors = []
   _messages = {
      "invalid_key": {
         "level": messages.ERROR,
         "text": _("Sorry, wrong key. Try again !")
         },
      "valid_key": {
         "level": messages.SUCCESS,
         "text": _("Congratulation, you found the key !")
         },
      "breakthrough": {
         "level": messages.WARNING,
         "text": _("Great, you just made a breakthrough !")
         },
      "already_done": {
         "level": messages.INFO,
         "text": _("This challenge was already done by your team !")
         },
      "before_start": {
         "level": messages.INFO,
         "text": _("The contest is not yet started !")
         },
      "after_end": {
         "level": messages.INFO,
         "text": _("The contest is finished !")
         },
      }

   # Check if the contest is open
   now = timezone.now()

   if (now <= begin_date()):
      messages.add_message(request,
                           _messages['before_start']['level'],
                           _messages['before_start']['text'])

      return HttpResponseRedirect('/challenges/')

   if (now >= end_date()):
      messages.add_message(request,
                           _messages['after_end']['level'],
                           _messages['after_end']['text'])
      return HttpResponseRedirect('/challenges/')

   if request.method == 'POST':
      form = ChallengeValidationForm(request.POST)

      if form.is_valid():
         key = form.cleaned_data['key']

         if key == Challenge.objects.get(pk=pk).key:
            # Key is valid
            messages.add_message(request,
                                 _messages['valid_key']['level'],
                                 _messages['valid_key']['text'])

            team = request.user.team_set.filter()[:1].get()
            challenge = Challenge.objects.get(pk=pk)
            try:
               Validation.objects.filter(challenge=challenge)[:1].get()
               # Not a breakthrough
               try:
                  Validation.objects.get(challenge=challenge, team=team)
                  # Team has already validated this challenge
                  messages.add_message(request,
                                       _messages['already_done']['level'],
                                       _messages['already_done']['text'])

                  return HttpResponseRedirect('/challenges/')

               except Validation.DoesNotExist:
                  # Validation was not already registered, creating it
                  validation = Validation(date=now,
                                          team=team,
                                          user=request.user,
                                          challenge=challenge)
                  validation.save()
                  team.is_active = True
                  team.save()

            except Validation.DoesNotExist:
               # Breakthrough !
               messages.add_message(request,
                                    _messages['breakthrough']['level'],
                                    _messages['breakthrough']['text'])
               validation = Validation(date=now,
                                       team=team,
                                       user=request.user,
                                       challenge=challenge)
               validation.save()
               team.is_active = True
               team.save()

            # Recompute score for everybody #
            # ############################# #
            teams =  Team.objects.filter(is_active=True).all()
            teams_count = teams.count()

            # Compute the score for each challenge and the first team
            challenge_scores = {}
            for challenge in Challenge.objects.all():
               validations = Validation.objects.filter(challenge=challenge)

               first_validation = validations.first()
               if (first_validation is not None):
                  first_team = first_validation.team
               else:
                  first_team = None

               count = validations.count()

               # challenge_score contains the score for a challenge and the
               # team which make de the breakthrough (None otherwise).
               challenge_scores[challenge.pk] = \
                           (teams_count * (teams_count - count + 1), first_team)

            # Compute the score for each team
            for team  in teams:
               score = 0
               breakthroughs = 0
               validations = Validation.objects.filter(team=team)
               for validation in validations:
                  score_challenge, first_team = challenge_scores[validation.challenge.pk]
                  score += score_challenge
                  # Get the bonus if team has a breakthrough
                  if (team == first_team):
                     score += teams_count
                     breakthroughs += 1

               team.score = score
               team.breakthroughs = breakthroughs
               team.save()

         else:
            # Key is not valid
            messages.add_message(request,
                                 _messages['invalid_key']['level'],
                                 _messages['invalid_key']['text'])

   else:
      form = ChallengeValidationForm()
      messages.add_message(request,
                           _messages['invalid_key']['level'],
                           _messages['invalid_key']['text'])

   return HttpResponseRedirect('/challenges/')