def test_form_renders_poll_choices_as_radio_inputs(self):
        # set up a poll with a couple of choices
        poll1 = Poll(question='6 times 7', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(poll=poll1, choice='42', votes=0)
        choice1.save()
        choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=0)
        choice2.save()

        # set up another poll to make sure we only see the right choices
        poll2 = Poll(question='time', pub_date=timezone.now())
        poll2.save()
        choice3 = Choice(poll=poll2, choice='PM', votes=0)
        choice3.save()

        # build a voting form for poll1
        form = PollVoteForm(poll=poll1)

        # check it has a single field called 'vote', which has right choices:
        self.assertEquals(form.fields.keys(), ['vote'])

        # choices are tuples in the format (choice_number, choice_text):
        self.assertEquals(form.fields['vote'].choices, [
            (choice1.id, choice1.choice),
            (choice2.id, choice2.choice),
        ])

        # check it uses radio inputs to render
        self.assertIn('input type="radio"', form.as_p())
Exemple #2
0
    def test_root_url_shows_links_to_all_polls(self):
        # Set up some polls
        poll1 = Poll(question='6 times 7', pub_date=timezone.now())
        poll1.save()
        poll2 = Poll(question="life, the universe and everything",
                     pub_date=timezone.now())
        poll2.save()

        response = self.client.get('/')

        # Check that we've used the right template
        self.assertTemplateUsed(response, 'home.html')

        # Check that we've passed polls to the template
        polls_in_context = response.context['polls']
        self.assertEquals(list(polls_in_context), [poll1, poll2])

        # Check the poll names appear on the page
        self.assertIn(poll1.question, response.content)
        self.assertIn(poll2.question, response.content)

        # Check that the page also contains the urls to individual polls
        poll1_url = reverse('polls.views.poll', args=[
            poll1.id,
        ])
        self.assertIn(poll1_url, response.content)
        poll2_url = reverse('polls.views.poll', args=[
            poll2.id,
        ])
        self.assertIn(poll2_url, response.content)
Exemple #3
0
    def test_was_published_recently_with_future_poll(self):
        """
		was_published_recently() should return False for polls whose
		pub_date is in the future
		"""
        future1_poll = Poll(pub_date=timezone.now() +
                            datetime.timedelta(days=30))
        self.assertEqual(future1_poll.was_published_recently(), False)
        future2_poll = Poll(pub_date=timezone.now() +
                            datetime.timedelta(days=0))
        self.assertEqual(future1_poll.was_published_recently(), False)
Exemple #4
0
def test_poll_filter_name(api_client):
    poll = Poll.objects.bulk_create([
        Poll(title='two poll'),
        Poll(title='one poll'),
    ])
    url = reverse("polls-list")
    resp = api_client.get(url, {'title': 'one poll'})
    assert resp.status_code == HTTP_200_OK

    resp_json = resp.json()
    assert len(resp_json) == 2
    resp_poll = resp_json[1]
    assert resp_poll['title'] == poll[1].title
Exemple #5
0
def objects():
    p = Poll(question="What is your preferred colour?")
    yield p
    yield Choice(choice="Blue", poll=p)
    yield Choice(choice="Red", poll=p)
    yield Choice(choice="Yellow", poll=p)
    yield Choice(choice="other", poll=p)

    p = Poll(question="Do you like Django?")
    yield p
    yield Choice(choice="Yes", poll=p)
    yield Choice(choice="No", poll=p)
    yield Choice(choice="Not yet decided", poll=p)
Exemple #6
0
    def test_was_published_recently(self):
        """
        was_published_recently() should return False for polls whose
        pub_date is in the future, past and True if current
        """
        future_poll = Poll(pub_date=timezone.now() +
                           datetime.timedelta(days=30))
        self.assertEqual(future_poll.was_published_recently(), False)

        past_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
        self.assertEqual(past_poll.was_published_recently(), False)

        current_poll = Poll(pub_date=timezone.now())
        self.assertEqual(current_poll.was_published_recently(), True)
Exemple #7
0
    def test_was_published_recently_with_future_poll(self):
        """
        was_published_recently() should return False for polls whose
        pub_date is in the future
        """
        future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
        self.assertEqual(future_poll.was_published_recently(), False)
        
        def test_was_published_recently_with_old_poll(self):
            """
            was_published_recently() should return False for polls whose pub_date
            is older than 1 day
            """
            old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
            self.assertEqual(old_poll.was_published_recently(), False)

        def test_was_published_recently_with_recent_poll(self):
            """
            was_published_recently() should return True for polls whose pub_date
            is within the last day
            """
            recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
            self.assertEqual(recent_poll.was_published_recently(), True)
            
        def create_poll(question, days):
            """
            Creates a poll with the given `question` published the given number of
            `days` offset to now (negative for polls published in the past,
            positive for polls that have yet to be published).
            """
            return Poll.objects.create(question=question,
                pub_date=timezone.now() + datetime.timedelta(days=days))
def create(request):
    """
    The logic behind the poll creation form.

    Like the voting form, if you pass it some invalid inputs, it screams at you.
    Otherwise, it leads you the poll's detail view.
    """
    
    import datetime
    
    if len(request.POST['question']) == 0 and len(request.POST['choice']) == 0:
	return render_to_response('pollsIndex.html', {
                      	'error_message': "You need to type a choice and question in.", 'latest_poll_list' : Poll.objects.all().order_by('-pub_date')[:5],
                    	}, context_instance=RequestContext(request))
    elif len(request.POST['choice']) == 0:
	return render_to_response('pollsIndex.html', {
                      	'error_message': "You need to type a choice in.", 'latest_poll_list' : Poll.objects.all().order_by('-pub_date')[:5],
                    	}, context_instance=RequestContext(request))
    elif len(request.POST['question']) == 0:
	return render_to_response('pollsIndex.html', {
                      	'error_message': "You need to type a question in.", 'latest_poll_list' : Poll.objects.all().order_by('-pub_date')[:5],
                    	}, context_instance=RequestContext(request))
    else:
    	p = Poll(question=request.POST['question'], pub_date=datetime.datetime.now())
    	p.save()
    	p.choice_set.create(choice=request.POST['choice'], votes=0)
    	return HttpResponseRedirect(reverse('poll_detail', args=(p.id,)))
    def test_view_can_handle_votes_via_POST(self):
        # set up a poll with choices
        poll1 = Poll(question='6 times 7', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(poll=poll1, choice='42', votes=1)
        choice1.save()
        choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=3)
        choice2.save()

        # set up our POST data - keys and values are strings
        post_data = {'vote': str(choice2.id)}

        # make our request to the view
        poll_url = '/poll/%d/' % (poll1.id, )
        response = self.client.post(poll_url, data=post_data)

        # retrieve the updated choice from the database
        choice_in_db = Choice.objects.get(pk=choice2.id)

        # check it's votes have gone up by 1
        self.assertEquals(choice_in_db.votes, 4)

        # always redirect after a POST - even if, in this case, we go back
        # to the same page.
        self.assertRedirects(response, poll_url)
Exemple #10
0
 def generate_random_single_choice(self):
     user = self.get_random_user()
     title = self.get_random_title()
     poll = Poll(user=user, title=title)
     poll.timestamp = get_timestamp_in_milli()
     poll.date_begin = get_timestamp_in_milli() + 60000 * 60 * 24 * (random.randint(0, 4) - 2)
     poll.date_end = poll.date_begin + 60000 * 60 * 24 * random.randint(5, 30)
     poll.paid = False
     poll.is_active = True
     poll.poll_type = 1
     poll.total_answered_count = 0
     poll.status = APPROVED
     photo_name = self.get_random_photo_name()
     poll.image.save(str(get_timestamp_in_milli()) + photo_name,
         File(open(PHOTO_PATH + photo_name, 'r')))
     poll.save()
     choice_count = random.randint(3, 10)
     for i in xrange(choice_count):
         new_choice = PollChoice()
         new_choice.poll = poll
         new_choice.sc_value = self.get_random_choice()
         new_choice.priority = i + 1
         new_choice.timestamp = get_timestamp_in_milli()
         new_choice.save()
     self.add_random_category(poll)
     self.add_random_keyword(poll)  
     poll.save()
     return poll
Exemple #11
0
 def test_was_published_recently_with_recent_poll(self):
     '''
     was_published_recently should return true with recent poll
     '''
     recent_poll = Poll(pub_date=timezone.now() -
                        datetime.timedelta(hours=1))
     self.assertEqual(recent_poll.was_published_recently(), True)
Exemple #12
0
 def test_was_published_recently_with_future_poll(self):
     '''
     was_published_recently should return false with future poll
     '''
     future_poll = Poll(pub_date=timezone.now() +
                        datetime.timedelta(days=10))
     self.assertEqual(future_poll.was_published_recently(), False)
Exemple #13
0
 def setUpClass(cls):
     super(TestPoll, cls).setUpClass()
     cls.template = Template(title='template')
     cls.poll = Poll(
         title='poll',
         template=cls.template,
     )
Exemple #14
0
    def test_create_some_choices_for_a_poll(self):
        # Create new poll object
        poll = Poll()
        poll.question = "What's up?"
        poll.pub_date = timezone.now()
        poll.save()

        # Create Choice object
        choice = Choice()
        choice.poll = poll
        choice.choice = "doin' fine..."

        # Give it faux votes
        choice.votes = 3
        choice.save()

        # Try to retrieve from DB using poll's reverse lookup.
        poll_choices = poll.choice_set.all()
        self.assertEquals(poll_choices.count(), 1)

        # Finally, check attrbs have been saved
        choice_from_db = poll_choices[0]
        self.assertEqual(choice_from_db, choice)
        self.assertEqual(choice_from_db.choice, "doin' fine...")
        self.assertEqual(choice_from_db.votes, 3)
Exemple #15
0
 def test_was_published_recently_with_old_poll(self):
     """
     was_published_recently() should return False for polls whose pub_date
     is older than 1 day
     """
     old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
     self.assertEqual(old_poll.was_published_recently(), False)
Exemple #16
0
    def test_poll_has_right_fields(self):
        if not models_importable:
            fail(self)

        P = Poll()
        assert check_attrs(
            P, ['choice_set', 'question', 'pub_date', 'was_published_today'])
Exemple #17
0
    def test_was_published_recently_with_recent_question(self):
        """
		was_published_recently() should return True for Poll whose pub_date is within the last day.
		"""
        time = timezone.now() - datetime.timedelta(days=1)
        old_poll = Poll(pub_date=time)
        self.assertEqual(old_poll.was_published_recently(), True)
Exemple #18
0
	def test_was_published_recently_with_recent_poll(self):
		"""
		was_published_recently() should return True for polls whose pub_date
		is within the last day
		"""
		recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
		self.assertEqual(recent_poll.was_published_recently(), True)
Exemple #19
0
    def test_creating_some_choices_for_a_poll(self):
        # start by creating a new Poll object
        poll = Poll()
        poll.question = "What's up?"
        poll.pub_date = timezone.now()
        poll.save()

        # now create a Choice object
        choice = Choice()

        # link it with our Poll
        choice.poll = poll

        # give it some text
        choice.choice = "doin' fine..."

        # and let's say it's had some votes
        choice.votes = 3

        # save it
        choice.save()

        # try retrieving it from the database, using the poll object's reverse
        # lookup
        poll_choices = poll.choice_set.all()
        self.assertEquals(poll_choices.count(), 1)

        # finally, check its attributes have been saved
        choice_from_db = poll_choices[0]
        self.assertEquals(choice_from_db, choice)
        self.assertEquals(choice_from_db.choice, "doin' fine...")
        self.assertEquals(choice_from_db.votes, 3)
Exemple #20
0
def seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite=False):
    """
    Seeds num_entries poll with random users as owners
    Each poll will be seeded with # choices from choice_min to choice_max
    """
    if overwrite:
        print('Overwriting polls')
        Poll.objects.all().delete()
    users = list(User.objects.all())
    count = 0
    for _ in range(num_entries):
        p = Poll(owner=random.choice(users),
                 text=fake.paragraph(),
                 pub_date=datetime.datetime.now())
        p.save()
        num_choices = random.randrange(choice_min, choice_max + 1)
        for _ in range(num_choices):
            c = Choice(poll=p, choice_text=fake.sentence()).save()
        count += 1
        percent_complete = count / num_entries * 100
        print("Adding {} new Polls: {:.2f}%".format(num_entries,
                                                    percent_complete),
              end='\r',
              flush=True)
    print()
Exemple #21
0
	def test_was_published_recently_with_recent_poll(self):
		"""
		Tests was_published_recently() with a recent date
		to ensure it returns true
		"""
		recent_poll = Poll(pub_date = timezone.now() - datetime.timedelta(hours = 1))
		self.assertEqual(recent_poll.was_published_recently(), True)
Exemple #22
0
    def test_was_published_recently_with_future_poll(self):
        """
        was_published_recently() should return False for polls whose
        pub_date is in the future
        """
        future_poll = Poll(pub_date=timezone.now() +
                           datetime.timedelta(days=30))
        #for i in dir(future_poll):
        #	print(i)
        self.assertEqual(future_poll.was_published_recently(), False)

        def test_was_published_recently_with_old_poll(self):
            """
	    was_published_recently() should return False for polls whose pub_date
	    is older than 1 day
	    """
            old_poll = Poll(pub_date=timezone.now() -
                            datetime.timedelta(days=30))
            self.assertEqual(old_poll.was_published_recently(), False)

        def test_was_published_recently_with_recent_poll(self):
            """
	    was_published_recently() should return True for polls whose pub_date
	    is within the last day
	    """
            recent_poll = Poll(pub_date=timezone.now() -
                               datetime.timedelta(hours=1))
            self.assertEqual(recent_poll.was_published_recently(), True)
Exemple #23
0
 def test_was_published_recently_with_new_poll(self):
     """
     was_published_recently() should return True for polls whose
     pub_date is less than one day old
     """
     new_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
     self.assertEqual(new_poll.was_published_recently(), True)
Exemple #24
0
	def test_was_published_recently_with_old_poll(self):
		"""
		Tests was_published_recently() with an old date
		to ensure it returns false
		"""
		old_poll = Poll(pub_date = timezone.now() - datetime.timedelta(days = 30))
		self.assertEqual(old_poll.was_published_recently(), False)
Exemple #25
0
def newPoll(req):
    poll = Poll()
    f = PollForm(req.POST, instance=poll)
    if f.is_valid():
        foo = f.save()
        return HttpResponse('%s je stranjen' % foo)
    return HttpResponse('Not valid')
Exemple #26
0
    def test_was_published_recently_with_recent_poll(self):
        """
        return True for polls 1 day
        """

        recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=4))
        self.assertEqual(recent_poll.was_published_recently(), True)
Exemple #27
0
    def test_wasPublishedRecently_with_old_poll(self):
        '''
		wasPublishedRecently() should return False for polls which
		are old
		'''
        future_poll = Poll(pubdate=timezone.now() -
                           datetime.timedelta(hours=30))
        self.assertEqual(future_poll.wasPublishedRecently(), False)
Exemple #28
0
 def test_was_published_recently_with_future_poll(self):
     """"
     was_published_recently() should return FAls for polls published 
     with future dates
     """
     future_poll = Poll(pub_date=timezone.now() +
                        datetime.timedelta(days=30))
     self.assertEqual(future_poll.was_published_recently(), False)
Exemple #29
0
 def test_get_queryset(self):
     poll = Poll(owner=self.user_model,
                 statement='Just a test?',
                 flow=self.flow_model)
     poll.save()
     view = self.view(request=self.request)
     polls = Poll.objects.filter(owner=self.user_model)
     self.assertQuerysetEqual(view.get_queryset(), map(repr, polls))
Exemple #30
0
def objects():
    for ln in DATA.splitlines():
        if ln:
            a = ln.split('|')
            p = Poll(question=a[0].strip())
            yield p
            for choice in a[1:]:
                yield Choice(choice=choice.strip(), poll=p)