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)
Esempio n. 2
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)
    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)
Esempio n. 4
0
def write_new(request, methods=['POST']):
	if request.POST['question'] and request.POST['choice1'] and request.POST['choice2']:
		q=Question()
		q.title=request.POST['question']
		q.save()
		c1=Choice()
		c1.questions=q
		c1.options=request.POST['choice1']
		c1.save()
		c2=Choice()
		c2.questions=q
		c2.options=request.POST['choice2']
		c2.save()
		if request.POST['choice3']:
			c3=Choice()
			c3.questions=q
			c3.options=request.POST['choice3']
			c3.save()
			if request.POST['choice4']:
				c4=Choice()
				c4.questions=q
				c4.options=request.POST['choice4']
				c4.save()
				if request.POST['choice5']:
					c5=Choice()
					c5.questions=q
					c5.options=request.POST['choice5']
					c5.save()
	return HttpResponseRedirect('/poll/')
Esempio n. 5
0
    def handle(self, *args, **options):
        # delete Questionnaire.objects.filter(id__gt=3).delete()
        # reset index ALTER TABLE table_name AUTO_INCREMENT = 1;
        gene_time = options['gene_num']
        origin_count = Questionnaire.objects.count()
        for i in range(gene_time):
            polls_orders = origin_count + i + 1
            print(polls_orders)
            pub_date = timezone.now() - datetime.timedelta(days=(400 - i))
            questionnaire = Questionnaire(
                questionnaire_name="测试问卷{}".format(polls_orders),
                pub_date=pub_date,
                detail_info="用于测试的问卷")
            questionnaire.save()
            for j in range(4):
                question = Question(question_text="测试问题{}".format(j + 1),
                                    question_type=1,
                                    questionnaire=questionnaire)
                question.save()
                for k in range(4):
                    choice = Choice(choice_text="测试选项{}".format(k + 1),
                                    votes=random.randint(50, 200),
                                    question=question)
                    choice.save()

            self.stdout.write(
                self.style.SUCCESS('Successfully generate test questionnaire'))
Esempio n. 6
0
    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)

        # 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())
Esempio n. 7
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 we create a Choice object
        choice = Choice()

        # Link it to our poll
        choice.poll = poll
        choice.choice = 'Doing fine...'
        choice.votes = 3
        choice.save()

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

        # Finally, check that its attributes have been saved
        choice_from_db = poll_choices[0]
        self.assertEquals(choice_from_db, choice)
        self.assertEquals(choice_from_db.choice, 'Doing fine...')
        self.assertEquals(choice_from_db.votes, 3)
def generate_elements(count=1):
    """
    this guy generates db elements for testing
    """
    for k in range(count):
        question = ""

        for i in range(choice((2, 3, 4, 5, 6, 7))):
            question = " ".join((question, choice(WORDS)))

        question = question[1:] + "?"
        question = question[0].upper() + question[1:]
        q = Question(question_text=question, pub_date=timezone.now())
        q.save()
        print(q.id, q.question_text)

        for choicecount in range(choice((2, 3))):
            choicetxt = ""

            for choicewords in range(choice((2, 3, 4, 5))):
                choicetxt = " ".join((choicetxt, choice(WORDS)))

            choicetxt = choicetxt[1:]
            choicetxt = choicetxt[0].upper() + choicetxt[1:] + "."
            # print('\t', choicetxt)

            ch = Choice(question=q, choice_text=choicetxt, votes=choice((0, 1, 2, 3, 4, 5)))
            ch.save()

            print("\t", ch.question.id, ch.choice_text)
Esempio n. 9
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)
Esempio n. 10
0
def add_choice(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        new_choice = Choice(    poll = p,
                choice_text = request.POST['choice_text'],
                choice_desc = request.POST['choice_desc'],
                proposer = request.POST['proposer'],
                votes = 1
               );
        new_choice.save()
    except IntegrityError:
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_propose_message': request.POST['choice_text'] + u": 이미 존재하는 이름입니다.",
        })

    try:
        if 'suggest_subscribe_check' in request.POST.keys():
            subscribe_check = True
        else:
            subscribe_check = False
        new_voter = Voter(poll=p, 
                    choice=new_choice, 
                    email=request.POST['proposer'], 
                    subscription=subscribe_check)
        new_voter.save()
    except Exception as err:
        print err.message, type(err)

    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    #return HttpResponseRedirect(reverse('results', args=(p.id,)))
    return render(request, 'polls/results.html', {'poll': p})
class VoteTests(base.BaseTestCase):

    def setUp(self):
        super().setUp()

        self.question = Question.objects.create(
            question_text='Is this a test?',
            pub_date=timezone.now()
        )
        self.question.save()

        self.choice1 = Choice(
            question=self.question,
            choice_text='No',
            votes=0,
        )
        self.choice1.save()

        self.choice2 = Choice(
            question=self.question,
            choice_text='Yes',
            votes=0,
        )
        self.choice2.save()

    def test_view(self):
        url = reverse('polls:vote', args=(self.question.id,))
        request = self.request_factory.post(url, {'choice': self.choice2.id})
        response = vote(request, self.question.id)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('polls:results', args=(self.question.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)
def get_question(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = QuestionForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            question_body = request.POST.get('your_question', '')
            new_question = Question(question_text=question_body, pub_date=timezone.now())
            new_question.save()

            characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w',
                          'x','y','z']
            for i in range(0, 5):
                answer_text = 'your_answer_' + characters[i]
                new_answer = request.POST.get(answer_text, '')
                if new_answer != '':
                    new_choice = Choice(question=new_question, choice_text=new_answer, votes=0)
                    new_choice.save()
            # process the data in form.cleansed_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/polls/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = QuestionForm()

    return render(request, 'polls/question.html', {'form': form})
Esempio n. 14
0
def question_page(request, question_pk):
    question = Question.objects.get(pk=question_pk)

    if request.method == 'POST':
        answer = request.POST['answer']
        choice = Choice(question=question, choice_text=answer)
        choice.save()

    return render(request, 'question_detail.html', context={'question': question})
Esempio n. 15
0
def vote(request):
    #we need to check if its before 4pm
    if request.method == "POST":
        form = polls.forms_DK.NameForm(request.POST)
        if form.is_valid():
            your_email = form.cleaned_data["your_email"]
            ratio = str(form.cleaned_data["ratio"])
            django.setup()

            timer_split = get_timer()
            dater = timer_split[0]
            hrs = timer_split[1]
            # we check if the user exists in the database.
            try:
                checking_email = Person.objects.get(email=your_email)
            except:
                address = "registration/"
                return HttpResponseRedirect(address)

            #Checking if its before 4pm cut_hour
            if datetime.datetime.now() < cut_hour:
                print "you can still vote"
                #quering to see if the person voted
                date_query = Choice.objects.filter(date_vote=dater)
                voted = False
                for i in date_query:
                    if i.person_id == checking_email.id:
                        voted = True
                        print "you voted"

                # action if he voted or not
                if voted is False:

                    cc = Choice(date_vote=dater, time_vote=hrs, restaurant_vote_id=ratio, person_id=checking_email.id)
                    cc.save()
                    address = "thank/?email="+your_email+"/"
                    return HttpResponseRedirect(address)
                elif voted is True:
                    message = "you already voted tomorrow try again"
                    return render(request, "thanks.html", {"message": message})

                address = "thank/?email="+your_email+"/"
                return HttpResponseRedirect(address)

            else: # if its after cut_hour
                message = "its after time, talk to your PA he might take your order"
                return render(request, "thanks.html", {"message": message})


    #regular empty forms render for the first time.
    else:
        form = polls.forms_DK.NameForm()
    django.setup()
    all_restaurants = Restaurant.objects.all()

    message = "select the restaurant of your choice before: " + str(cut_hour_12)
    return render(request, "vote_form.html", {"message": message, "all_restaurants": all_restaurants, "form": form})
class VoteTests(base.BaseTestCase):

    def setUp(self):
        super().setUp()

        self.request_factory = RequestFactory()

        self.question = self.create_question(question_text='Some question.', days=0)
        self.question.save()

        self.choice1 = Choice(
            question=self.question,
            choice_text='Choice 1',
            votes=0,
        )
        self.choice1.save()

        self.choice2 = Choice(
            question=self.question,
            choice_text='Choice 2',
            votes=0,
        )
        self.choice2.save()

    def test_vote_counts_with_client(self):
        url = reverse('polls:vote', args=(self.question.id,))
        # follow=True follows the redirect chain so response is the end page
        response = self.client.post(url, {'choice': self.choice2.id}, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "<li>{} -- 0 votes</li>".format(self.choice1.choice_text))
        self.assertContains(response, "<li>{} -- 1 vote</li>".format(self.choice2.choice_text))

    def test_post_redirect_with_client(self):
        url = reverse('polls:vote', args=(self.question.id,))
        response = self.client.post(url, {'choice': self.choice2.id})

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], reverse('polls:results', args=(self.question.id,)))

    def test_logged_in_redirect(self):
        # This test is no different from test_post_redirect, but it
        # shows an example with logging in before calling `post`.
        password = '******'
        user = User(username='******')
        user.set_password(password)
        user.save()

        logged_in = self.client.login(username=user.username, password=password)
        self.assertTrue(logged_in)

        url = reverse('polls:vote', args=(self.question.id,))
        response = self.client.post(url, {'choice': self.choice2.id})

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], reverse('polls:results', args=(self.question.id,)))
Esempio n. 17
0
def test_add_choice_to_no_question():
    """
    Assert Integrity error if a choice is added
    to a question that does not exist
    """
    with pytest.raises(IntegrityError) as excinfo:
        choice = Choice(question_id=33, choice_text="Test choice", votes=23)
        choice.save()

    assert "FOREIGN KEY constraint failed" in str(excinfo)
Esempio n. 18
0
	def test_choice_can_calculate_its_own_percentage_of_votes(self):
		poll = Poll(question='who?', pub_date=timezone.now())
		poll.save()
		choice1 = Choice(poll=poll, choice='me', votes=2)
		choice1.save()
		choice2 = Choice(poll=poll, choice='you', votes=1)
		choice2.save()

		self.assertEquals(choice1.percentage(),100*2/3.0 )
		self.assertEquals(choice2.percentage(), 100*1/3.0)
Esempio n. 19
0
 def test_unicode(self):
     """
     str(Choice) or unicode(Choice) should be the choice_text
     """
     poll = create_poll(question="Testing unicode", days=0)
     choice = Choice(poll=poll, choice_text="Testing is fun!")
     choice.save()
     self.assertEqual(str(choice), choice.choice_text)
     self.assertEqual(unicode(choice), choice.choice_text)
     self.assertEqual(str(choice), unicode(choice))
Esempio n. 20
0
    def test_list_question_relation(self):
        q = Question(
            question_text="question_text_006", pub_date=timezone.now())
        q.save()
        c = Choice(question=q, choice_text="006_001")
        c.save()

        response = self.client.get(
            reverse("polls:choice-list"), **self.auth_headers)

        self.assertEqual(q.id, json.loads(response.content)[0]["question"])
Esempio n. 21
0
def createdb():
	from django.utils import timezone
	from polls.models import Poll, Choice
	n = int(raw_input("Enter no. of items to create: "))
	for i in xrange(n):
		p = Poll(question="Question = {0}".format(i), pub_date = timezone.now())
		p.save()
		for i in xrange(4):
			cycle = ['a', 'b', 'c', 'd']
			c = Choice(poll = p, choice_text = cycle[i], votes = 0)
			c.save()
Esempio n. 22
0
    def setup_poll1(self):
        poll = Poll(question='Which is better?', pub_date=timezone.now())
        poll.save()

        email_choice = Choice(question=poll, choice_text='Email sign-up')
        email_choice.save()

        external_choice = Choice(question=poll, choice_text='External sign-in')
        external_choice.save()

        return (poll, email_choice, external_choice)
Esempio n. 23
0
 def handle(self, *args, **options):
     for pc in data:
         p = Poll(**pc['poll'])
         p.save()
         self.stdout.write('saved Poll: {}'.format(p))
         for c in pc['choices']:
             c = Choice(**c)
             c.poll = p
             c.save()
             self.stdout.write('saved Choice: {}'.format(c), ending=',')
         self.stdout.write('')
     self.stdout.write('DONE')
Esempio n. 24
0
 def handle(self, *args, **options):
     for pc in data:
         p = Poll(**pc['poll'])
         p.save()
         self.stdout.write('saved Poll: {}'.format(p))
         for c in pc['choices']:
             c = Choice(**c)
             c.poll = p
             c.save()
             self.stdout.write('saved Choice: {}'.format(c), ending=',')
         self.stdout.write('')
     self.stdout.write('DONE')
    def test_creating_new_choice_and_saving_it_to_the_database(self):

        #creating a poll object
        poll = Question(question_text="What are my choices?", pub_date=timezone.now())
        poll.save()

        #creating a choice object
        choice = Choice(question=poll, choice_text="You have no choice", votes=0)
        choice.save()

        #searching in database
        all_choices_in_database = poll.choice_set.all()
        self.assertEquals(all_choices_in_database.count(), 1)
Esempio n. 26
0
def test_add_choice_to_question():
    """
    Test if we can add a choice to a question safely
    """
    pub_date = timezone.now()
    question = Question(question_text="Test question", pub_date=pub_date)
    question.save()
    choice = Choice(question_id=question.id,
                    choice_text="Test choice",
                    votes=23)
    choice.save()
    assert choice.choice_text == "Test choice"
    assert choice.votes == 23
Esempio n. 27
0
    def test_page_shows_choices_using_form(self):
        poll1 = Poll(question='time', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(poll=poll1, choice="PM", votes=0)
        choice1.save()
        choice2 = Choice(poll=poll1, choice="AM", votes=0)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id, ))

        self.assertTrue(isinstance(response.context['form'], PollVoteForm))

        self.assertIn(choice1.choice, response.content)
        self.assertIn(choice2.choice, response.content)
Esempio n. 28
0
    def test_view_shows_percentage_of_votes(self):
        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=2)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id,))

        self.assertIn('33 %: 42', response.content)
        self.assertIn('67 %: The ultimate answer', response.content)

        self.assertNotIn('Nobody has voted', response.content)
Esempio n. 29
0
def add(request):
    question = request.POST.get('question')
    choice1 = request.POST.get('choice1')
    choice2 = request.POST.get('choice2')

    q = Question(question_text=question, pub_date=timezone.now())
    q.save()

    c = Choice(question=q, choice_text=choice1)
    c.save()
    c = Choice(question=q, choice_text=choice2)
    c.save()

    return HttpResponseRedirect(reverse('polls:index'))
Esempio n. 30
0
    def test_view_shows_percentage_of_votes(self):
        # set up a poll with choices
        poll1 = Question(question_text='6 times 7', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(question=poll1, choice_text='42', votes=1)
        choice1.save()
        choice2 = Choice(question=poll1, choice_text='The Ultimate Answer', votes=2)
        choice2.save()

        response = self.client.get('/polls/%d/results/' % (poll1.id, ))

        # check the percentages of votes are shown, sensibly rounded
        self.assertIn('33 %: 42', response.content)
        self.assertIn('67 %: The Ultimate Answer', response.content)
Esempio n. 31
0
 def setUp(self):
     super(TestPollSample,self).setUp()
     self.poll = Poll(
         question="What is your favorite number?",
         pub_date=datetime.now()
     )
     self.poll.save()
     for i in range(1, 4):
         choice = Choice(
             poll = self.poll,
             choice=str(i),
             votes=0
         )
         choice.save()        
Esempio n. 32
0
def insert_record(request):
    left = request.POST['left']
    right = request.POST['right']
    choice = request.POST['choice']
    usetime = request.POST['usetime']
    userID = request.POST['userID']
    newChoice = Choice(use_time=usetime,
                       left_pic_id=left,
                       right_pic_id=right,
                       choice_num=choice,
                       user_id=userID)
    print("newChoice")
    print(newChoice)
    newChoice.save()
    return JsonResponse({'inserted': True})
Esempio n. 33
0
def create_poll(question, days, choice_text=CHOICE_TEXT):
    """
    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).
    """
    now = timezone.now()
    result = Poll(question=question, pub_date=now + datetime.timedelta(days))
    result.save()

    if choice_text:
        choice = Choice(choice_text=choice_text, poll=result)
        choice.save()

    return result
Esempio n. 34
0
def index(request):
    if request.method=='GET' :
        latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
        return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
    elif request.method== 'POST' :
    	newPoll=Poll(question=request.POST["poll"])
    	newPoll.save()
    	
    for key in request.POST.keys():
      if key.startswith("choice"):
      choice=Choice(poll=newPoll, choice=request.POST[key], votes=0)
      choice.save()
      
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[Poll.objects.count()-1]
	return HttpResponseRedirect('/')
Esempio n. 35
0
    def test_saving_and_retrieving_choices(self):

        choice = Choice()
        choice.choice_text = '1. Demi Moore 2. Julia Roberts'
        choice.votes = 1000
        choice.save()

        saved_choices = Choice.objects.all()
        self.assertEqual(saved_choices.count(), 1)
        saved_choice = saved_choices[0]
        self.assertIn('1. Demi Moore 2. Julia Roberts',
            repr(saved_choice),
        )
        self.assertEqual(saved_choice.choice_text, '1. Demi Moore 2. Julia Roberts')
        self.assertEqual(saved_choice.votes, 1000)
Esempio n. 36
0
	def test_creating_some_choices_for_a_poll(self):
		poll = Poll()
		poll.question = "what's up?"
		poll.pub_date = timezone.now()
		poll.save()

		choice = Choice()
		choice.poll = poll
		choice.choice = 'alright then ...'
		choice.votes = 3
		choice.save()

		# check the database
		poll_choices = poll.choice_set.all()
		self.assertEquals(poll_choices.count(), 1)
		self.assertEquals(poll_choices[0].choice, choice.choice)
Esempio n. 37
0
def test():
    import os
    from django.conf import settings
    from polls.models import Choice
    from django.db.utils import IntegrityError
    from PIL import Image

    for filename in os.listdir(settings.MEDIA_ROOT):
        try:
            Image.open(settings.MEDIA_ROOT + filename)
        except:
            pass
        else:
            if not Choice.objects.filter(image=filename):
                choice = Choice(image=filename)
                choice.save()
    def test_view_shows_percentage_of_votes(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=2)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id, ))

        # check the percentages of votes are shown, sensibly rounded
        self.assertIn('33 %: 42', response.content)
        self.assertIn('67 %: The Ultimate Answer', response.content)

        # and that the 'no-one has voted' message is gone
        self.assertNotIn('No-one has voted', response.content)
    def test_view_shows_percentage_of_votes(self):
        # Set up 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=2)
        choice2.save()

        response = self.client.get("/poll/%d/" % (poll1.id,))

        # Check the percentage of votes are shown, sensibly rounded
        self.assertIn("33 %: 42", response.content)
        self.assertIn("67 %: The Ultimate Answer", response.content)

        # And that no-one has voted message is gone
        self.assertNotIn("No-one has voted", response.content)
Esempio n. 40
0
    def test_page_shows_choices_using_form(self):
        # set up a poll with choices
        poll1 = Poll(question='time', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(poll=poll1, choice="PM", votes=0)
        choice1.save()
        choice2 = Choice(poll=poll1, choice="Gardener's", votes=0)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id, ))

        # check we've passed in a form of the right type
        self.assertTrue(isinstance(response.context['form'], PollVoteForm))

        # and check the form is being used in the template,
        # by checking for the choice text
        self.assertIn(choice1.choice, response.content)
def i_have_a_list_of_polls(step):
    from polls.models import Question, Choice
    from django.utils import timezone

    #create 5 poll question
    for i in range(0, 5):
        question = Question()
        question.question_text = "Question text %s" % i
        question.pub_date = timezone.now()
        question.save()

        # create 5 choice for each question
        for j in range(0, 5):
            choice = Choice()
            choice.choice_text = "Choice text %s" % j
            choice.question = question
            choice.save()
Esempio n. 42
0
    def test_view_can_handle_votes_via_POST(self):
        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()

        post_data = { 'vote': str(choice2.id) }

        poll_url = '/poll/%d/' % (poll1.id,)
        response = self.client.post(poll_url, data=post_data)

        choice_in_db = Choice.objects.get(pk=choice2.id)

        self.assertEquals(choice_in_db.votes, 4)
        self.assertRedirects(response, poll_url)
    def test_view_shows_percentage_of_votes(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=2)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id, ))

        # check the percentages of votes are shown, sensibly rounded
        self.assertIn('33 %: 42', response.content)
        self.assertIn('67 %: The Ultimate Answer', response.content)

        # and that the 'no-one has voted' message is gone
        self.assertNotIn('No-one has voted', response.content)
Esempio n. 44
0
    def test_view_shows_percentage_of_votes(self):
        # Set up 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=2)
        choice2.save()

        response = self.client.get("/poll/%d/" % (poll1.id, ))

        # Check the percentage of votes are shown, sensibly rounded
        self.assertIn("33 %: 42", response.content)
        self.assertIn("67 %: The Ultimate Answer", response.content)

        # And that no-one has voted message is gone
        self.assertNotIn("No-one has voted", response.content)
Esempio n. 45
0
    def test_creating_a_new_poll_and_saving_it_to_the_database(self):
        poll = Poll()
        poll.question = "what's up?"
        poll.pub_date = timezone.now()

        # check we can save ite to the database
        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)
        
        
        # now check we can find it in the database again
        all_polls_in_database = Poll.objects.all()
        self.assertEquals(len(all_polls_in_database), 1)
        only_poll_in_database = all_polls_in_database[0]
        self.assertEquals(only_poll_in_database, poll)
        
        # and check that it's saved its two attributes: question and
        # pub_date
        self.assertEquals(only_poll_in_database.question, "what's up?")
        self.assertEquals(only_poll_in_database.pub_date, poll.pub_date)
    def test_page_shows_choices_using_form(self):
        # set up a poll with choices
        poll1 = Poll(question='time', pub_date=timezone.now())
        poll1.save()
        choice1 = Choice(poll=poll1, choice="PM", votes=0)
        choice1.save()
        choice2 = Choice(poll=poll1, choice="Gardener's", votes=0)
        choice2.save()

        response = self.client.get('/poll/%d/' % (poll1.id, ))

        # check we've passed in a form of the right type
        self.assertTrue(isinstance(response.context['form'], PollVoteForm))

        # and check the check the form is being used in the template,
        # by checking for the choice text
        self.assertIn(choice1.choice, response.content.replace('&#39;', "'"))
        self.assertIn(choice2.choice, response.content.replace('&#39;', "'"))
Esempio n. 47
0
def save(request):
    qd = request.POST
    quest = ""
    if(qd['createNew'] == "false"):
        id = int(qd['qid'])
        quest = get_object_or_404(Question,pk=id)
        quest.question_text = qd['qt']
        quest.pub_date = datetime.strptime(qd['date'] + ' ' + qd['time'], '%Y-%m-%d %H:%M')
        quest.choice_set.all().delete()
    else:
        quest = Question(question_text=qd['qt'],pub_date=datetime.strptime(qd['date'] + ' ' + qd['time'], '%Y-%m-%d %H:%M'))
        quest.save()
    m = qd['arrayChoice'].split('\0,')
    m[len(m)-1] = m[len(m)-1][:-1]
    for el in m:
        c = Choice(choice_text=el,votes=0,question=quest)
        c.save()
    return redirect('detail',quest.id)
    def test_poll_increases_count(self):
        poll = Poll(question='What is your favorite color?',
                pub_date=datetime.now())
        poll.save()

        choice1 = Choice(poll=poll, choice='Blue', votes=0)
        choice2 = Choice(poll=poll, choice='red', votes=0)

        choice1.save()
        choice2.save()
        c = Client()

        response = c.post(reverse('vote', args=(poll.id, )),
                {'choice': choice1.id,}, follow=True)
#        result_choice = Choice.objects.get(pk=choice1.id)
        result_choice = response.context['object'].choice_set.get(pk=choice1.id)
        self.assertRedirects(response, reverse('poll_results', args=(poll.id,)))
        self.assertEqual(result_choice.votes, 1)
Esempio n. 49
0
def submit_options(request):
    options = dict(request.POST)['option']
    poll_id = request.POST['poll_id']
    p = get_object_or_404(Poll, pk=int(poll_id))
    if isinstance(options, basestring):
        opt = Choice()
        opt.poll = p
        opt.choice_text = options
        opt.votes = 0
        opt.save()
    else:
        for opt in options:
            c = Choice()
            c.poll = p
            c.choice_text = opt
            c.votes = 0
            c.save()
    return HttpResponseRedirect(reverse('polls:index'))
Esempio n. 50
0
class VotingTests(TestCase):
    def setUp(self):
        User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')
        self.question = create_question("What is your gender?",
                                        pub_date=-4,
                                        end_date=5)
        self.first_choice = Choice(id=1,
                                   question=self.question,
                                   choice_text="male")
        self.second_choice = Choice(id=2,
                                    question=self.question,
                                    choice_text="female")
        self.first_choice.save()
        self.second_choice.save()

    def test_authenticated_user_can_replace_their_vote(self):
        '''test authenticated user can replace their vote in this polls period'''
        response = self.client.post(
            reverse('polls:vote', args=(self.question.id, )),
            {'choice': self.first_choice.id})
        self.first_choice = self.question.choice_set.get(
            pk=self.first_choice.id)
        self.assertEqual(self.first_choice.vote_set.all().count(), 1)
        response = self.client.post(
            reverse('polls:vote', args=(self.question.id, )),
            {'choice': self.second_choice.id})
        self.second_choice = self.question.choice_set.get(
            pk=self.second_choice.id)
        self.first_choice = self.question.choice_set.get(
            pk=self.first_choice.id)
        self.assertEqual(self.second_choice.vote_set.all().count(), 1)
        self.assertEqual(self.first_choice.vote_set.all().count(), 0)

    def test_previous_vote_show(self):
        '''test previos vote show on detail page'''
        response1 = self.client.get(
            reverse('polls:detail', args=(self.question.id, )))
        self.assertContains(response1, "None")
        self.client.post(reverse('polls:vote', args=(self.question.id, )),
                         {'choice': self.first_choice.id})
        response1 = self.client.get(
            reverse('polls:detail', args=(self.question.id, )))
        self.assertNotContains(response1, "None")
Esempio n. 51
0
 def form_valid(self, form):
     choices_list = []
     if isinstance(form.cleaned_data['choice'], Choice):
         choice = form.cleaned_data['choice']
         choice.votes.add(self.request.user)
         choices_list.append(choice)
     elif isinstance(form.cleaned_data['choice'], str):
         choice = Choice(question_id=self.kwargs['question_id'],
                         choice_text=form.cleaned_data['choice'])
         choice.save()
         choice.votes.add(self.request.user)
     else:
         for choice in form.cleaned_data['choice']:
             choice.votes.add(self.request.user)
             choices_list.append(choice)
     bulk_update(choices_list)
     return HttpResponseRedirect(
         reverse('polls:results',
                 args=(self.get_form_kwargs()['question_id'], )))
Esempio n. 52
0
def get_question(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = QuestionForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            new_question = Question()
            new_question.body = Gymkhana_body.objects.get(
                nameofbody=form.cleaned_data['body'])
            new_question.question_text = form.cleaned_data['question']
            new_question.pub_date = timezone.now()
            new_question.save()

            choice1 = Choice()
            choice1.question = new_question
            choice1.choice_text = form.cleaned_data['choice1']
            choice1.votes = 0
            choice1.save()

            if form.cleaned_data['choice2']:
                choice2 = Choice()
                choice2.question = new_question
                choice2.choice_text = form.cleaned_data['choice2']
                choice2.votes = 0
                choice2.save()

            if form.cleaned_data['choice3']:
                choice3 = Choice()
                choice3.question = new_question
                choice3.choice_text = form.cleaned_data['choice3']
                choice3.votes = 0
                choice3.save()

            if form.cleaned_data['choice4']:
                choice4 = Choice()
                choice4.question = new_question
                choice4.choice_text = form.cleaned_data['choice4']
                choice4.votes = 0
                choice4.save()

            # redirect to a new URL:
            messages.add_message(request, messages.SUCCESS,
                                 'Thanks for your suggestion!')
            return HttpResponseRedirect('/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = QuestionForm()

    return render(request, 'organisation/addquestion.html', {'form': form})
Esempio n. 53
0
def seed(request):
    """Seeds the database with sample polls."""
    samples_path = path.join(path.dirname(__file__), 'samples.json')
    with open(samples_path, 'r') as samples_file:
        samples_polls = json.load(samples_file)

    for sample_poll in samples_polls:
        poll = Question()
        poll.question_text = sample_poll['text']
        poll.pub_date = timezone.now()
        poll.save()

        for sample_choice in sample_poll['choices']:
            choice = Choice()
            choice.question = poll
            choice.choice_text = sample_choice
            choice.votes = 0
            choice.save()

    return HttpResponseRedirect(reverse('polls:question'))
Esempio n. 54
0
    def save(self, request):
        data = self.cleaned_data
        cat = self.getCategoryWithName(data['category'])
        topic = Poll(poll_text=data['poll_text'],
                     category=cat,
                     user=request.user,
                     pub_date=datetime.datetime.now())
        topic.save()
        d = data['choices']
        # Get the choices by splitting on the ",".
        choices = [x.strip() for x in d.split(',')]

        # Save all the choices of the poll.
        for c in choices:
            choice = Choice(poll=topic,
                            choice_text=c,
                            votes=0,
                            user=request.user,
                            pub_date=datetime.datetime.now())
            choice.save()
        return topic
    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())
Esempio n. 56
0
    def test_poll_can_tell_you_its_total_number_of_votes(self):
        p = Poll(question='where', pub_date=timezone.now())
        p.save()
        c1 = Choice(poll=p, choice='here', votes=0)
        c1.save()
        c2 = Choice(poll=p, choice='there', votes=0)
        c2.save()

        self.assertEquals(p.total_votes(), 0)

        c1.votes = 1000
        c1.save()
        c2.votes = 22
        c2.save()
        self.assertEquals(p.total_votes(), 1022)
Esempio n. 57
0
class UserVotingtests(TestCase):
    """Test class for voting."""

    def setUp(self):
        User.objects.create_user(username = '******', password = '******')

    def test_authenticated_user_vote(self):
        """Authenticated user try to vote a question."""
        self.new_question = create_question(question_text='How are you', days=-5)
        self.client.post(reverse('login'), {'username':'******', 'password':'******'}, follow = True)  
        url = reverse('polls:vote', args=(self.new_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_unauthenticated_user_vote(self):
        """Unauthenticated user try to vote a question."""
        self.new_question = create_question(question_text='How are you', days=-5)
        url = reverse('polls:vote', args=(self.new_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)

    def test_replace_user_vote(self):  
        self.new_question = create_question(question_text='How are you', days=-5)
        self.first_choice = Choice(id = 1, question = self.new_question, choice_text = "I'm ok")
        self.second_choice = Choice(id = 2, question = self.new_question, choice_text = "I'm fine")
        self.first_choice.save()
        self.second_choice.save()
        self.client.login(username='******', password='******')
        response = self.client.post(reverse('polls:vote', args=(self.new_question.id,)), {'choice':self.first_choice.id})
        self.first_choice = self.new_question.choice_set.get(pk = self.first_choice.id)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.first_choice.vote_set.all().count(), 1)
        response = self.client.post(reverse('polls:vote', args=(self.new_question.id,)), {'choice':self.second_choice.id})
        self.second_choice = self.new_question.choice_set.get(pk = self.second_choice.id)
        self.first_choice = self.new_question.choice_set.get(pk = self.first_choice.id)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.second_choice.vote_set.all().count(), 1)
        self.assertEqual(self.first_choice.vote_set.all().count(), 0)
Esempio n. 58
0
def save_to_database(polls):

    for poll in polls:
        try:
            Author.objects.get(name=poll['author'])
        except ObjectDoesNotExist:
            author = Author(name=poll['author'], inet=poll['inet'])
            author.save()

        try:
            Question.objects.get(question_text=poll['question'])
            sys.stderr.write("Poll '{0}' is already in the database\n".format(
                poll['question']))
        except ObjectDoesNotExist:
            question = Question(question_text=poll['question'],
                                pub_date=poll['pub_date'],
                                author=author)
            question.save()

            for i in range(1, len(poll.values()) - 3):
                choice = Choice(question=question,
                                choice_text=poll['choice' + str(i)])
                choice.save()
Esempio n. 59
0
    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 db
        choice_in_db = Choice.objects.get(pk=choice2.id)

        # Check that its votes have gone up by 1.
        self.assertEquals(choice_in_db.votes, 4)

        # Always redirect after a post, even if we go back to the same page.
        self.assertRedirects(response, poll_url)