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 handle(self, *args, **options): for question in args: p = Poll(question=question, pub_date=timezone.now()) p.save() self.stdout.write('Successfully created poll with question "%s"' % p.question )
class PollHttpAdapter(object): def __init__(self, poll = None): self.poll = poll def formatDate(self, dt): return str(dt.strftime('%m/%d/%Y')) def jsonDict(self): return {'id' : self.poll.id , 'question': self.poll.question , 'pub_date': self.formatDate(self.poll.pub_date) } def initFromPost(self, data): # init new objects before filling in their fields self.poll = Poll() # now fill in their fields self.updateFromPost(data) def updateFromPost(self, data): print "saving poll!", data self.poll.question = data.get('question', None) # pub_date self.poll.pub_date = datetime.now() self.poll.save() print 'done'
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)
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('/') template_names_used = [t.name for t in response.templates] self.assertIn('home.html', template_names_used) # check we've passed the 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 the page also contains the urls to individual polls pages 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)
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)
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)
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)
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_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 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 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
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() for _ in range(choice_min, choice_max + 1): 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()
def test_root_url_shows_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 we've used the right template self.assertTemplateUsed(response, 'polls/home.html') # check we've passed the 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 the page also contains the urls to individual polls # pages poll1_url = reverse(pollView, args=[poll1.id,]) self.assertIn(poll1_url, response.content) poll2_url = reverse(pollView, args=[poll2.id,]) self.assertIn(poll2_url, response.content)
def createquestion(request): p=Poll() p.question=request.GET['question'] #p.pub_date=request.getparameter('pub_date') p.pub_date=timezone.now() p.save() return index(request)
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()
def test_create(self): poll = Poll( views=10, stars=10, name='some', ) poll.save() assert Poll.objects.get(pk=poll.pk)
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
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))
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
class PollTest(TestCase): def setUp(self): self.poll = Poll(title='test') self.poll.save() def test_add_question(self): self.poll.add_question('question', ['ans1', 'ans2']) self.assertEquals(1, self.poll.questions.all().count())
class TestPollSample(BaseTestCase): 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() def test_poll_index(self): """ Check if the poll index displays """ # Now display me a poll! url = reverse("poll_index") response = self.client.get(url) # Show them the print! #print response self.assertContains(response, "What is your favorite number?") def test_poll_detail(self): """ Check if the poll detail displays """ # Grab poll again to make sure we get right ID and that # any custom save methods have been fully fired poll = Poll.objects.get(id=self.poll.id) url = reverse("poll_detail", kwargs={"poll_id": poll.id}) response = self.client.get(url) self.assertContains(response, "What is your favorite number?") def test_poll_vote(self): """ vote on a poll """ url = reverse("poll_vote", kwargs={"poll_id": self.poll.id}) # Pick a bad choice out of range data = dict(choice = 10) response = self.client.post(url, data, follow=True) self.assertContains(response, "You didn't select a choice.") # pick a choice in range data = dict(choice = 2) response = self.client.post(url, data, follow=True) self.assertContains(response, "<li>2 -- 1 vote</li>")
def test_was_published_today(self): poll = Poll(question="Django is for the internets", pub_date=datetime.now()) poll.save() self.assertTrue(poll.was_published_today()) poll.pub_date = datetime.now() - timedelta(days=3) poll.save() self.assertFalse(poll.was_published_today())
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)
def test_root_url_show_all_polls(self): 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('/') self.assertIn(poll1.question, response.content) self.assertIn(poll2.question, response.content)
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)
def new_poll(self, **kwargs): """ Generate a new poll """ number = self._poll_numbers.pop() kwargs.setdefault("subject", "Poll Subject %s" % number) kwargs.setdefault("description", "Poll Description %s" % number) if "author" not in kwargs: kwargs["author"] = self.new_user() poll = Poll(**kwargs) poll.save() self._polls.append(poll) return poll
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()
def mutate(self, info, title, description, image_path): poll = Poll(title=title, creator=info.context.user, description=description, image_path=image_path) poll.save() return CreatePoll(creator=poll.creator, id=poll.id, description=poll.description, image_path=poll.image_path, title=poll.title)
def add_edit_poll(request): if request.method == 'POST': form = PollForm(request.POST) if form.is_valid(): #TODO: have pub_date set automatically p = Poll(question=form.cleaned_data['question'], pub_date=timezone.now()) p.save() return HttpResponseRedirect(reverse('poll_detail', args=(p.id,))) else: form = PollForm() return render_to_response('polls/add_edit_poll.html', {'form': form}, context_instance=RequestContext(request))
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_page_shows_poll_title_and_no_votes_message(self): 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('/poll/%d/' % (poll2.id, )) self.assertTemplateUsed(response, 'poll.html') self.assertEquals(response.context['poll'], poll2) self.assertIn(poll2.question, response.content) self.assertIn('Nobody has voted on this poll yet', response.content)
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)
def test_poll_create(self): """ Can we create a poll? * Seems trivial now * But for complex systems what started out as a simple create can get complex * Get your test coverage up! """ poll_count = Poll.objects.count() poll = Poll(question="Why is Python awesome?", pub_date=datetime.now()) poll.save() self.assertTrue(poll_count < Poll.objects.count())
def test_root_url_shows_all_polls_as_links(self): poll1 = Poll(question="does tdd rock?", pub_date=timezone.now()) poll1.save() poll2 = Poll(question="more coffe anymore?", pub_date=timezone.now()) poll2.save() response = self.client.get('/') self.assertTemplateUsed(response, "home.html") self.assertIn(poll1.question, response.content) self.assertIn(poll2.question, response.content)
def addPoll(request): data = json.loads(request.body.decode('utf-8')) try: assert len(data['statement']) > 9 assert len(data['statement']) < 501 poll = Poll(owner=request.user, flow=Flow.objects.get(name=data['flow']), statement=data['statement']) poll.save() except: return HttpResponse(status=404) else: return HttpResponse(status=204)
def publicar(request): if request.user.is_authenticated(): if "pregunta" in request.POST: p = Poll(question=request.POST["pregunta"], pub_date=datetime.datetime.now()) p.save() p.choice_set.create(choice="Si", votes=0) p.choice_set.create(choice="No", votes=0) return render_to_response("polls/publish.html", locals(), context_instance=RequestContext(request)) else: return HttpResponseRedirect("/polls/login/")
def test_creating_a_new_poll_and_saving_it_to_database(self): poll = Poll() poll.question = self.question poll.pub_date = self.pub_date poll.save() all_polls_in_database = Poll.objects.all() self.assertEquals(len(all_polls_in_database), 1) only_poll_in_db = all_polls_in_database[0] self.assertEquals(only_poll_in_db, poll) self.assertEquals(only_poll_in_db.question, self.question) self.assertEquals(only_poll_in_db.pub_date, self.pub_date)
def poll_create(request): if request.method == 'POST': form = PollForm(request.POST, request.FILES) if form.is_valid(): newpoll = Poll(subject=request.POST['subject'], picture=request.FILES['picture'], detail=request.POST['detail'], password=request.POST['password'], create_by=User.objects.get(pk=request.user.id), start_date=request.POST['start_date'], end_date=request.POST['end_date'], create_date=datetime.datetime.now()) newpoll.save() return redirect('index') else: form = PollForm() # if request.user.is_authenticated: return render(request, 'polls/create.html', {'form': form})
def make_metal_poll(bandname, opinions): pub = datetime.datetime.now() marks = '?' * random.randint(1, 5) question = bandname + marks chosen = random.sample(opinions, 5) choices = list() for c in chosen: votes = random.randint(1, 1000) choices.append(Choice(choice=c, votes=votes)) p = Poll(question=question, pub_date=pub) p.save() p.choice_set = choices return p
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)
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)
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/')
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)
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 index(request): latest_question_list = Poll.objects().all() context = {'latest_question_list': latest_question_list} try: question = Poll(question=request.POST['question'], pub_date=timezone.now()) choices = [] for i in range(4): if len(request.POST['answer' + str(i + 1)]) > 0: choices.append(request.POST['answer' + str(i + 1)]) for choice in choices: answer = Choice(choice_text=choice) question.choices.append(answer) question.save() except: print "NOT A POST REQUEST" return render(request, 'polls/index.html', context)
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_creating_a_new_poll_and_saving_it_to_the_database(self): # start by creating a new Poll object with its "question" set poll = Poll() poll.question = "What's up?" poll.pub_date = timezone.now() # check we can save it to the database poll.save() # 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_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)
def test_view_shows_total_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, )) self.assertIn('3 votes', response.content) # also check we only pluralise "votes" if necessary. details! choice2.votes = 0 choice2.save() response = self.client.get('/poll/%d/' % (poll1.id, )) self.assertIn('1 vote', response.content) self.assertNotIn('1 votes', response.content)
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(''', "'"))
def test_view_shows_total_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) self.assertIn('3 votes', response.content) # Also check if we pluralise votes only when necessary choice2.votes = 0 choice2.save() response = self.client.get('/poll/%d/' % poll1.id) self.assertIn('1 vote', response.content) self.assertNotIn('1 votes', response.content)
def save_poll(request): result = {} question = request.POST["question"] try: poll = Poll() poll.question = question poll.save() result["status"] = "SUCCESS" result["msg_status"] = "Su encuesta se ha creado satisfactoriamente" except Exception as error: result["status"] = "FAILURE" result["msg_status"] = "Error en la creacion" return render_to_response('home.html', result, context_instance=RequestContext(request))
def test_creating_a_new_poll_and_saving_it_to_the_database(self): # Create a new poll object wiht its question set poll = Poll() poll.question = "What's up?" poll.pub_date = timezone.now() # Check if we can save it to the db poll.save() # Now check if we can find it in the db again all_polls_in_db = Poll.objects.all() self.assertEqual(len(all_polls_in_db), 1) only_poll_in_db = all_polls_in_db[0] self.assertEqual(only_poll_in_db, poll) # And check that it has saved its two attrbs, question and pub_date self.assertEqual(only_poll_in_db.question, poll.question) self.assertEqual(only_poll_in_db.pub_date, poll.pub_date)