Skip to content

Instantly share code, notes, and snippets.

@patrickcurl
Created February 20, 2014 20:08
Show Gist options
  • Save patrickcurl/9122157 to your computer and use it in GitHub Desktop.
Save patrickcurl/9122157 to your computer and use it in GitHub Desktop.
Polls project django tutorial, error during testing.
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date < now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice_text
$ pymanage test polls
Creating test database for alias 'default'...
...EEEEE
======================================================================
ERROR: test_index_view_with_a_future_poll (polls.tests.PollViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Sites\Python\django\tut1\polls\tests.py", line 39, in test_index_view_with
_a_future_poll
self.assertQuerysetEqual(response.context['latest_poll_list'], [])
File "c:\virtualenvs\django-tut\lib\site-packages\django\test\testcases.py", line 8
20, in assertQuerysetEqual
items = six.moves.map(transform, qs)
TypeError: 'instancemethod' object is not iterable
======================================================================
ERROR: test_index_view_with_a_past_poll (polls.tests.PollViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Sites\Python\django\tut1\polls\tests.py", line 29, in test_index_view_with
_a_past_poll
response.context['latest_poll_list'], ['<Poll: Past poll.>']
File "c:\virtualenvs\django-tut\lib\site-packages\django\test\testcases.py", line 8
20, in assertQuerysetEqual
items = six.moves.map(transform, qs)
TypeError: 'instancemethod' object is not iterable
======================================================================
ERROR: test_index_view_with_future_poll_and_past_poll (polls.tests.PollViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Sites\Python\django\tut1\polls\tests.py", line 48, in test_index_view_with
_future_poll_and_past_poll
response.context['latest_poll_list'], ['<Poll: Past poll.>']
File "c:\virtualenvs\django-tut\lib\site-packages\django\test\testcases.py", line 8
20, in assertQuerysetEqual
items = six.moves.map(transform, qs)
TypeError: 'instancemethod' object is not iterable
======================================================================
ERROR: test_index_view_with_no_polls (polls.tests.PollViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Sites\Python\django\tut1\polls\tests.py", line 21, in test_index_view_with
_no_polls
self.assertQuerysetEqual(response.context['latest_poll_list'], [])
File "c:\virtualenvs\django-tut\lib\site-packages\django\test\testcases.py", line 8
20, in assertQuerysetEqual
items = six.moves.map(transform, qs)
TypeError: 'instancemethod' object is not iterable
======================================================================
ERROR: test_index_view_with_two_past_polls (polls.tests.PollViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Sites\Python\django\tut1\polls\tests.py", line 59, in test_index_view_with
_two_past_polls
['<Poll: Past poll 2.>', '<Poll: Past poll 1.>']
File "c:\virtualenvs\django-tut\lib\site-packages\django\test\testcases.py", line 8
20, in assertQuerysetEqual
items = six.moves.map(transform, qs)
TypeError: 'instancemethod' object is not iterable
----------------------------------------------------------------------
Ran 8 tests in 125.176s
FAILED (errors=5)
from django.test import TestCase
from django.core.urlresolvers import reverse
from polls.models import Poll
# Create your tests here.
def create_poll(question, days):
"""
Creates a poll with the given `question` published the given number of `days` offset to now (negative for polls published in the past, positive for polls yet to be published).
"""
return Poll.objects.create(question=question,
pub_date=timezone.now() + datetime.timedelta(days=days))
class PollViewTests(TestCase):
def test_index_view_with_no_polls(self):
"""
If no polls exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_poll_list'], [])
def test_index_view_with_a_past_poll(self):
"""
Polls with pubdate in past should be displayed on index page.
"""
create_poll(question="Past poll.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'], ['<Poll: Past poll.>']
)
def test_index_view_with_a_future_poll(self):
"""
Polls with a pub_date in future should not be displayed yet.
"""
create_poll(question="Future poll.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available", status_code=200)
self.assertQuerysetEqual(response.context['latest_poll_list'], [])
def test_index_view_with_future_poll_and_past_poll(self):
"""
Even if both past and future polls exist, only past polls should be displayed.
"""
create_poll(question="Past poll.", days=-30)
create_poll(question="Future poll.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'], ['<Poll: Past poll.>']
)
def test_index_view_with_two_past_polls(self):
"""
The polls index page may display multiple polls.
"""
create_poll(question="Past poll 1.", days=-30)
create_poll(question="Past poll 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
['<Poll: Past poll 2.>', '<Poll: Past poll 1.>']
)
class PollMethodTests(TestCase):
def test_was_published_recently_with_future_poll(self):
"""
was_published_recently() should return False for polls whose
pub_date is in the future
"""
future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
self.assertEqual(future_poll.was_published_recently(), False)
def test_was_published_recently_with_old_poll(self):
"""
was_published_recently() should return False for polls older than 1 day.
"""
old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
self.assertEqual(old_poll.was_published_recently(), False)
def test_was_published_recently_with_recent_poll(self):
"""
was_published_recently() should return True for polls whose pub_date is within last day.
"""
recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
self.assertEqual(recent_poll.was_published_recently(), True)
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
from django.utils import timezone
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def queryset(self):
"""Return the last five published polls."""
return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.html'
# Create your views here.
# def index(request):
# latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
# context = {'latest_poll_list': latest_poll_list}
# return render(request, 'polls/index.html', context)
# def detail(request, poll_id):
# poll = get_object_or_404(Poll, pk=poll_id)
# return render(request, 'polls/detail.html', {'poll' : poll})
# def results(request, poll_id):
# poll = get_object_or_404(Poll, pk=poll_id)
# return render(request, 'polls/results.html', {'poll': poll})
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay poll voting form
return render(request, 'polls/detail.html',{
'poll': p,
'error_message': "You didn't make a choice!",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HTTPResponseRedirect after successfully dealing w/ post data.
# This prevents duplicate posting of data if user hits back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Copy link

ghost commented Aug 25, 2015

In test.py,
line 19 should read: self.assertQuerysetEqual(response.context'latest_poll_list', [])
line 37 should read: self.assertQuerysetEqual(response.context'latest_poll_list', [])
line 45-47 should read: self.assertQuerysetEqual(
response.context'latest_poll_list', ['<Poll: Past poll.>']
)
lines 55-58 should read: self.assertQuerysetEqual(
response.context'latest_poll_list',
['<Poll: Past poll 2.>', '<Poll: Past poll 1.>']
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment