def test_edit_not_owned_poll_fails(self):
     """An authenticated user cannot edit polls owned by someone else."""
     assert(self.a_user.is_authenticated())
     another_user = UserFactory(username="******")
     another_user.set_password(DEFAULT_PASSWORD)
     another_user.save()
     alien_poll = another_user.poll_set.create(question="whatever")
     # The logged in user tries to edit the alien_poll
     request = request_factory.post(
             reverse('polls:edit_poll', kwargs={'poll_id':alien_poll.id}),
         )
     request.user = self.a_user
     with self.assertRaises(PermissionDenied):
         response = views.edit_poll(request, poll_id=alien_poll.id)
class NewPollGETTesting(TestCase):
    def setUp(self):
        self.usr = "******"
        self.a_user = UserFactory(username=self.usr)
        self.a_user.set_password(DEFAULT_PASSWORD)
        self.a_user.save()

    def tearDown(self):
        """Delete the created Poll instance."""
        self.client.logout()

    def test_new_poll_not_authenticated_redirects_to_login(self):
        """Not authenticated users accesing new_poll, must be redirected to login page."""
        self.client.logout() # Make sure it's not logged-in
        original = reverse('polls:new_poll')
        response = self.client.get(original)
        destiny = "%s?next=%s"%(reverse('polls:login'), original)
        self.assertRedirects(response, destiny)

    def test_any_authenticated_user_can_create_polls(self):
        """Authenticated users accesing (GET) new_poll, receive 200."""
        request = request_factory.get(reverse('polls:new_poll'))
        request.user = UserFactory()
        response = views.edit_poll(request)
        self.assertEqual(response.status_code, 200)

    def test_new_poll_form_is_unbound(self):
        """When requiring new_poll, the poll_form is not bound to any poll instance."""
        self.client.login(username=self.usr, password=DEFAULT_PASSWORD)
        response = self.client.get(reverse('polls:new_poll'))
        self.assertFalse(response.context['poll_form'].is_bound)

    def __get_new_poll_choices_forms(self):
        self.client.login(username=self.usr, password=DEFAULT_PASSWORD)
        response = self.client.get(reverse('polls:new_poll'))
        return response.context['choices_formset'].forms

    def test_new_poll_choices_formset_has_only_one_form(self):
        """When requiring new_poll, the involved choices_formset has only one InlineChoiceForm."""
        choice_forms = self.__get_new_poll_choices_forms()
        self.assertEqual(len(choice_forms), 1)
        self.assertIsInstance(choice_forms[0], forms.InlineChoiceForm)

    def test_new_poll_choice_form_is_unbound(self):
        """When requiring new_poll, the InlineChoiceForm is unbound."""
        the_choice_form = self.__get_new_poll_choices_forms()[0]
        self.assertFalse(the_choice_form.is_bound)
 def setUp(self):
     self.usr = "******"
     self.a_user = UserFactory(username=self.usr)
     self.a_user.set_password(DEFAULT_PASSWORD)
     self.a_user.save()
     self.client.login(username=self.usr, password=DEFAULT_PASSWORD)
     self.a_question = 'a question?'
     self.a_choice = 'a choice'
class EditPollTesting(TestCase):
    def setUp(self):
        self.usr = "******"
        self.a_user = UserFactory(username=self.usr)
        self.a_user.set_password(DEFAULT_PASSWORD)
        self.a_user.save()
        self.client.login(username=self.usr, password=DEFAULT_PASSWORD)
        self.a_question = 'a question?'
        self.poll = self.a_user.poll_set.create(question=self.a_question)
        self.a_choice = 'a choice'
        self.choice = self.poll.choice_set.create(choice=self.a_choice)

    def tearDown(self):
        """Delete the created Poll instance."""
        self.client.logout()
        User.objects.all().delete() # Borra su poll y la choice

    def test_edit_poll_not_authenticated_redirects_to_login(self):
        """Not authenticated users trying edit_poll, must be redirected to login page."""
        self.client.logout() # Make sure it's not logged-in
        original = reverse('polls:edit_poll', kwargs={'poll_id':self.poll.id})
        response = self.client.post(original)
        destiny = "%s?next=%s"%(reverse('polls:login'), original)
        self.assertRedirects(response, destiny)

    def test_edit_not_owned_poll_fails(self):
        """An authenticated user cannot edit polls owned by someone else."""
        assert(self.a_user.is_authenticated())
        another_user = UserFactory(username="******")
        another_user.set_password(DEFAULT_PASSWORD)
        another_user.save()
        alien_poll = another_user.poll_set.create(question="whatever")
        # The logged in user tries to edit the alien_poll
        request = request_factory.post(
                reverse('polls:edit_poll', kwargs={'poll_id':alien_poll.id}),
            )
        request.user = self.a_user
        with self.assertRaises(PermissionDenied):
            response = views.edit_poll(request, poll_id=alien_poll.id)

    def test_edit_poll_empty_question_shows_specific_message(self):
        """Try to edit_poll with an empty question, renders a specific msg"""
        # No extra data (such as the 'question' value)
        invalid_data = aux_initial_management_form()
        request = request_factory.post(
                reverse('polls:edit_poll', kwargs={'poll_id':self.poll.id}),
                data = invalid_data,
            )
        request.user = self.a_user
        response = views.edit_poll(request)
        response.render()
        self.assertContains(response, html.escape(forms.EMPTY_QUESTION_MSG))

    def test_edit_poll_with_duplicated_choices_fail(self):
        """POST to /<id>/edit_poll with duplicated choices, invalids formset."""
        # No extra data (such as the 'question' value)
        choices_values = ['a', 'a']
        invalid_data = aux_initial_management_form(total_forms=2, extra={
                'question': self.a_question,
                "choice_set-0-ORDER" :  1,
                "choice_set-0-choice" : choices_values[0],
                "choice_set-1-ORDER" :  2,
                "choice_set-1-choice" : choices_values[1],
            })
        response = self.client.post(
                reverse('polls:edit_poll', kwargs={'poll_id':self.poll.id}),
                data = invalid_data
            )
        self.assertFalse(response.context['choices_formset'].is_valid())

    def test_edit_poll_choices_strip(self):
        """Choices value is stripped (no starting spaces)."""
        # No extra data (such as the 'question' value)
        extra = {'question': self.a_question}
        choices_values =  [ 
                #(choice id, user given value)
                (1   , u'   a   '), 
                (None, u'\t b \t'), 
                (None, u'\n c \n')
            ]
        desired_values = map(unicode.strip, [c for (i,c) in choices_values])
        valid_data = formset_management_form(choices_values, extra=extra)
        #print valid_data
        request = request_factory.post(
                reverse('polls:edit_poll', kwargs={'poll_id':self.poll.id}),
                data = valid_data,
            )
        request.user = self.a_user
        response = views.edit_poll(request, poll_id=self.poll.id)
        for i, db_choice in enumerate(Choice.objects.all()):
            self.assertEqual(db_choice.choice, desired_values[i])
class NewPollPOSTTesting(TestCase):
    def setUp(self):
        self.usr = "******"
        self.a_user = UserFactory(username=self.usr)
        self.a_user.set_password(DEFAULT_PASSWORD)
        self.a_user.save()
        self.client.login(username=self.usr, password=DEFAULT_PASSWORD)
        self.a_question = 'a question?'
        self.a_choice = 'a choice'

    def tearDown(self):
        """Delete the created Poll instance."""
        self.client.logout()
        self.a_user.delete()

    def test_valid_new_poll_inserts_only_one(self):
        """POST to edit_poll with valid data creates ONE new Poll."""
        assert(len(Poll.objects.all()) == 0)
        valid_data = aux_initial_management_form(extra={
                'question': self.a_question,
            })
        request = request_factory.post(
                reverse('polls:new_poll'),
                data = valid_data
            )
        request.user = self.a_user
        response = views.edit_poll(request)
        self.assertEqual(Poll.objects.all().count(), 1)

    def test_valid_new_poll_redirects_to_voting(self):
        """POST to edit_poll with valid data. redirects to polls:voting."""
        assert(len(Poll.objects.all()) == 0)
        valid_data = aux_initial_management_form(extra={'question': self.a_question})
        response = self.client.post(reverse('polls:new_poll'), data = valid_data)
        self.assertRedirects(
                response, 
                reverse('polls:voting', kwargs={'poll_id':Poll.objects.get(pk=1).pk})
            )

    def test_valid_new_poll_inserts_correct_question(self):
        """POST to edit_poll with valid data creates the correct Poll."""
        valid_data = aux_initial_management_form(extra={
                'question': self.a_question,
            })
        request = request_factory.post(
                reverse('polls:new_poll'),
                data = valid_data
            )
        request.user = self.a_user
        response = views.edit_poll(request)
        self.assertEqual(Poll.objects.get(pk=1).question, self.a_question)

    def test_valid_new_poll_inserts_correct_choices(self):
        """POST to edit_poll with valid data creates the correct Choices."""
        choices_values = ['a', 'b', 'c', 'd']
        valid_data = aux_initial_management_form(total_forms=4, extra={
                'question': self.a_question,
                "choice_set-0-ORDER" :  1,
                "choice_set-0-choice" : choices_values[0],
                "choice_set-1-ORDER" :  2,
                "choice_set-1-choice" : choices_values[1],
                "choice_set-2-ORDER" :  3,
                "choice_set-2-choice" : choices_values[2],
                "choice_set-3-ORDER" :  4,
                "choice_set-3-choice" : choices_values[3],
            })
        request = request_factory.post(
                reverse('polls:new_poll'),
                data = valid_data,
            )
        request.user = self.a_user
        response = views.edit_poll(request)
        db_values = [d.choice for d in Choice.objects.all()]
        self.assertItemsEqual(choices_values, db_values)

    def test_new_poll_empty_question_fails(self):
        """POST to edit_poll with an empty question, results in an invalid form."""
        assert(Poll.objects.all().count() == 0)
        # No extra data (such as the 'question' value)
        invalid_data = aux_initial_management_form()
        response = self.client.post(reverse('polls:new_poll'), data = invalid_data)
        self.assertFalse(response.context['poll_form'].is_valid())

    def test_new_poll_empty_question_shows_specific_message(self):
        """POST to edit_poll with an empty question, renders a specific msg"""
        # No extra data (such as the 'question' value)
        invalid_data = aux_initial_management_form()
        request = request_factory.post(
                reverse('polls:new_poll'),
                data = invalid_data,
            )
        request.user = self.a_user
        response = views.edit_poll(request)
        response.render()
        self.assertContains(response, html.escape(forms.EMPTY_QUESTION_MSG))

    def test_new_poll_empty_question_dont_inserts_in_DB(self):
        """POST to edit_poll with an empty question, does not insert a new poll in the DB."""
        assert(len(Poll.objects.all()) == 0)
        # No extra data (such as the 'question' value)
        invalid_data = aux_initial_management_form()
        response = self.client.post(reverse('polls:new_poll'), data = invalid_data)
        self.assertEqual(Poll.objects.all().count(), 0)
        

    def test_new_poll_duplicated_choices_fail(self):
        """POST to edit_poll with an empty question, renders a specific msg"""
        # No extra data (such as the 'question' value)
        choices_values = ['a', 'a']
        invalid_data = aux_initial_management_form(total_forms=2, extra={
                'question': self.a_question,
                "choice_set-0-ORDER" :  1,
                "choice_set-0-choice" : choices_values[0],
                "choice_set-1-ORDER" :  2,
                "choice_set-1-choice" : choices_values[1],
            })
        response = self.client.post(reverse('polls:new_poll'), data = invalid_data)
        self.assertFalse(response.context['choices_formset'].is_valid())
 def setUp(self):
     self.usr = "******"
     self.a_user = UserFactory(username=self.usr)
     self.a_user.set_password(DEFAULT_PASSWORD)
     self.a_user.save()