遵循djangoproject的教程之后,我尝试使用urls.py过滤掉下面的urlpattern进行的民意调查。

urlpatterns = patterns('',
    url(r'^$',
        ListView.as_view(
            queryset=Poll.objects.filter(choice__choice_text__isnull=False) \
                .filter(pub_date__lte=timezone.now) \
                .order_by('-pub_date')[:5],
            context_object_name='latest_polls',
            template_name='polls/index.html'),
        name='index'),
    url(r'^(?P<pk>\d+)/$',
        DetailView.as_view(
            queryset=Poll.objects.filter(choice__choice_text__isnull=False) \
                .filter(pub_date__lte=timezone.now),
            model=Poll,
            template_name='polls/detail.html'),
        name='detail'),
    url(r'^(?P<pk>\d+)/results/$',
        DetailView.as_view(
            queryset=Poll.objects.filter(choice__choice_text__isnull=False) \
                .filter(pub_date__lte=timezone.now),
            model=Poll,
            template_name='polls/results.html'),
        name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='vote'),
)


但是,当我从教程中运行测试时,每个创建past_poll的测试都会发生断言错误,类似于以下错误。

AssertionError: Lists differ: [] != ['<Poll: Past poll.>']

Second list contains 1 additional elements.
First extra element 0:
<Poll: Past poll.>

- []
+ ['<Poll: Past poll.>']


在我更改查询集以过滤掉所有不带选择的民意测验之前,测试没有失败。我已经在外壳中测试了过滤器,它可以工作,并且在django服务器上运行该应用程序似乎也没有任何问题。怎么了?

这是我使用的tests.py文件

import datetime

from django.utils import timezone
from django.core.urlresolvers import reverse
from django.test import TestCase

from polls.models import Poll

def create_poll(question, days):
    """
    Creates a poll with the given `question` published the given number of
    `days` offset to now (negative for polls published in the past,
    positive for polls that have yet to be published).
    """
    return Poll.objects.create(question=question,
        pub_date=timezone.now() + datetime.timedelta(days=days))

class PollIndexDetailTests(TestCase):
    def test_detail_view_with_a_future_poll(self):
        """
        The detail view of a poll with a pub_date in the future should
        return a 404 not found.
        """
        future_poll = create_poll(question='Future poll.', days=5)
        response = self.client.get(reverse('polls:detail', args=(future_poll.id,)))
        self.assertEqual(response.status_code, 404)

    def test_detail_view_with_a_past_poll(self):
        """
        The detail view of a poll with a pub_date in the past should display
        the poll's question.
        """
        past_poll = create_poll(question='Past Poll.', days=-5)
        response = self.client.get(reverse('polls:detail', args=(past_poll.id,)))
        self.assertContains(response, past_poll.question, status_code=200)

class PollIndexResultsTests(TestCase):
    def test_results_view_with_a_future_poll(self):
        """
        The results view of a poll with a pub_date in the future should
        return a 404 not found.
        """
        future_poll = create_poll(question='Future poll.', days=5)
        response = self.client.get(reverse('polls:results', args=(future_poll.id,)))
        self.assertEqual(response.status_code, 404)

    def test_results_view_with_a_past_poll(self):
        """
        The results view of a poll with a pub_date in the past should display
        the poll's question.
        """
        past_poll = create_poll(question='Past Poll.', days=-5)
        response = self.client.get(reverse('polls:results', args=(past_poll.id,)))
        self.assertContains(response, past_poll.question, status_code=200)

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_polls'], [])

    def test_index_view_with_a_past_poll(self):
        """
        Polls with a pub_date in the past should be displayed on the index page.
        """
        create_poll(question="Past poll.", days=-30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_polls'],
            ['<Poll: Past poll.>']
        )

    def test_index_view_with_a_future_poll(self):
        """
        Polls with a pub_date in the future should not be displayed on the
        index page.
        """
        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_polls'], [])

    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_polls'],
            ['<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_polls'],
             ['<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 whose pub_date
        is older than 1 day
        """
        old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
        self.assertEqual(old_poll.was_published_recently(), False)

    def test_was_published_recently_with_recent_poll(self):
        """
        was_published_recently() should return True for polls whose pub_date
        is within the last day
        """
        recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
        self.assertEqual(recent_poll.was_published_recently(), True)

最佳答案

我认为问题在于,在测试中,您正在创建一个全新的民意测验,而没有任何选择。在详细视图中,您正在过滤此民意调查。因此它什么也不返回,因此测试失败。

您还可以为刚刚在past_test上创建的民意调查创建一些选择,以便该民意调查通过过滤。

就像是:

...
past_poll = create_poll(question='Past Poll.', days=-5)
past_poll.choice_set.create(choice_text='Choice 1', votes=0)
past_poll.choice_set.create(choice_text='Choice 2', votes=0)
...

关于python - 向民意调查urls.py添加额外的过滤器会导致测试失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15799905/

10-09 03:58