Esempio n. 1
0
    def test_vote_answer_type_ONE(self):
        Poll.objects.create(
            name='Test_ONE', question='question1',
            begin_date=timezone.now(),
            end_date=timezone.now()+timezone.timedelta(minutes=1),
            answer_type='ONE'
        )

        poll = Poll.objects.get(name='Test_ONE')
        poll.choice_set.add(Choice(choice_text='ans1', created=timezone.now()))
        poll.choice_set.add(Choice(choice_text='ans2', created=timezone.now()))
        poll.choice_set.add(Choice(choice_text='ans3', created=timezone.now()))

        choices = poll.get_ordered_choices()

        self._common_test_for_ONE_and_MANY(poll, choices)

        response = self.client.post(
            '/polls/%s/vote/' % poll.id,
            {
                'choice': [choices[1].id, choices[2].id],
            },
            follow=True
        )

        messages = list(response.context['messages'])
        self.assertEqual(len(messages), 1)
        self.assertEqual('Вы должны выбрать один вариант ответа',
                         str(messages[0]))
        self._check_results(choices, self._last_results)
    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())
    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 add_poll(request):
    if request.method == 'POST':
        form = PollForm(request.POST)
        if form.is_valid():
            new_poll = form.save(commit=False)
            new_poll.owner = request.user
            new_poll.pub_date = datetime.datetime.now()
            new_poll.save()
            new_choice1 = Choice(
                poll=new_poll,
                choice_text=form.cleaned_data['choice1']).save()
            new_choice2 = Choice(
                poll=new_poll,
                choice_text=form.cleaned_data['choice2']).save()

            messages.success(
                request,
                'Poll and Choices Added!',
                extra_tags='alert alert-success alert-dismissible fade show')
            return redirect('polls:list')

    else:
        form = PollForm()
    context = {'form': form}
    return render(request, 'polls/add_poll.htm', context)
Esempio n. 5
0
 def setUpClass(cls):
     u = User.objects.create_user('simeon', '*****@*****.**', 'password')
     p = Poll(user=u, question="Why?", pub_date=dt.now())
     p.save()
     Choice.objects.bulk_create([
         Choice(poll=p, choice="Because", votes=0),
         Choice(poll=p, choice="Because", votes=0)
     ])
     cls.p = p
Esempio n. 6
0
    def _create_choices(self):
        question = Question.objects.get(id=1)
        Choice(question=question, choice_text='Billy Eyelash').save()
        Choice(question=question, choice_text='BLACKPINK').save()
        Choice(question=question, choice_text='Clairo').save()
        Choice(question=question, choice_text='Dua Lipa').save()
        Choice(question=question, choice_text='Taylor Swift').save()

        print("***** ADDING TEST CHOICES TO THE DATABASE *****")
Esempio n. 7
0
 def test_create_choice(self):
     q = Question(question_text="What day is it?", pub_date=timezone.now())
     q.save()
     c1 = Choice(choice_text="Monday", question=q)
     c2 = Choice(choice_text="Tuesday", question=q)
     c3 = Choice(choice_text="Sunday", question=q)
     c1.save()
     c2.save()
     c3.save()
     self.assertEqual(3, len(q.choice_set.all()))
Esempio n. 8
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. 9
0
def create(request):
    """Creates a new poll instance."""
    poll = Poll(question=request.POST['question'],
                pub_date=datetime.datetime.now())
    poll.save()
    choice = Choice(poll=poll, choice=request.POST['choice1'], votes=0)
    choice.save()
    choice = Choice(poll=poll, choice=request.POST['choice2'], votes=0)
    choice.save()
    choice = Choice(poll=poll, choice=request.POST['choice3'], votes=0)
    choice.save()
    return HttpResponseRedirect('/polls/%s' % poll.id)
Esempio n. 10
0
 def setUp(self):
     User.objects.create_user(username='******', password='******')
     self.client.login(username='******', password='******')
     self.question = create_question("1 or 2?", pub_date=-4, end_date=5)
     self.first_choice = Choice(id=1,
                                question=self.question,
                                choice_text="1")
     self.second_choice = Choice(id=2,
                                 question=self.question,
                                 choice_text="2")
     self.first_choice.save()
     self.second_choice.save()
Esempio n. 11
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. 12
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. 13
0
 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()
Esempio n. 14
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. 15
0
def add(request):
    """Adds a new poll to the polls.
   Might be used for mass insertion of polls.
   Is currently commented out in template,
   but fully functional if uncommented"""
    poll = Poll(question=request.POST['question'],
                pub_date=datetime.datetime.now())
    poll.save()
    choice = Choice(poll=poll, choice=request.POST['choice1'], votes=0)
    choice.save()
    choice = Choice(poll=poll, choice=request.POST['choice2'], votes=0)
    choice.save()
    choice = Choice(poll=poll, choice=request.POST['choice3'], votes=0)
    choice.save()
    return HttpResponseRedirect('/polls/')
Esempio n. 16
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()
Esempio n. 17
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. 18
0
 def test_choice_str(self):
     time = timezone.now()
     question = Question(pub_date=time)
     choice = Choice()
     choice.question = question
     choice.choice_text = 'Choice1'
     self.assertEqual(str(choice), 'Choice1')
Esempio n. 19
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)
Esempio n. 20
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. 21
0
 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. 22
0
File: demo.py Progetto: DarioGT/lino
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)
Esempio n. 23
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)
    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. 25
0
    def create_question(self, question_text, choice_texts):
        question = Question(question_text=question_text)
        question.save()

        for choice_text in choice_texts:
            Choice(question=question, choice_text=choice_text).save()

        return question
Esempio n. 26
0
def objects():
    for ln in DATA.splitlines():
        if ln:
            a = ln.split('|')
            q = Question(question_text=a[0].strip())
            yield q
            for choice in a[1:]:
                yield Choice(choice_text=choice.strip(), question=q)
Esempio n. 27
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)

        # also check 0-votes case
        choice1.votes = 0
        choice1.save()
        choice2.votes = 0
        choice2.save()
        self.assertEquals(choice1.percentage(), 0)
        self.assertEquals(choice2.percentage(), 0)
Esempio n. 28
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. 29
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'))
    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(''', "'"))
        self.assertIn(choice2.choice, response.content.replace(''', "'"))