Python 向polls url.py添加额外筛选器会导致测试失败

Python 向polls url.py添加额外筛选器会导致测试失败,python,django,django-urls,django-testing,Python,Django,Django Urls,Django Testing,在djangoproject的教程之后,我尝试让urls.py使用下面的urlpattern在没有选择的情况下过滤掉轮询 urlpatterns = patterns('', url(r'^$', ListView.as_view( queryset=Poll.objects.filter(choice__choice_text__isnull=False) \ .filter(pub_date__lte=timez

在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'),
)
urlpatterns=patterns(“”,
url(r'^$',
ListView.as_视图(
queryset=Poll.objects.filter(choice\u choice\u text\u isnull=False)\
.filter(发布日期=时区.now)\
.订购人('-pub_date')[:5],
context\u object\u name='latest\u polls',
模板_name='polls/index.html'),
name='index'),
url(r'^(?P\d+/$),
DetailView.as\u视图(
queryset=Poll.objects.filter(choice\u choice\u text\u isnull=False)\
.filter(发布日期=时区.now),
模型=投票,
模板_name='polls/detail.html'),
name='detail'),
url(r'^(?P\d+)/results/$”,
DetailView.as\u视图(
queryset=Poll.objects.filter(choice\u choice\u text\u isnull=False)\
.filter(发布日期=时区.now),
模型=投票,
模板_name='polls/results.html'),
name='results'),
url(r'^(?P\d+)/vote/$,'polls.views.vote',name='vote'),
)
但是,当我运行教程中的测试时,每个创建过去的轮询的测试都会发生断言错误,类似于下面的错误

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

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

- []
+ ['<Poll: Past poll.>']
AssertionError:列表不同:[]!=['']
第二个列表包含1个附加元素。
第一个额外元素0:
- []
+ ['']
在我更改queryset以过滤掉所有没有选择的轮询之前,测试没有失败。我在shell中测试了这个过滤器,它可以工作,在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)
导入日期时间
从django.utils导入时区
从django.core.urlResolver反向导入
从django.test导入TestCase
从polls.models导入Poll
def创建投票(问题,天数):
"""
使用给定的“问题”和给定数量的
`天`到现在的偏移量(过去公布的民意调查为负值,
尚未公布的民调结果为阳性)。
"""
返回Poll.objects.create(question=question,
pub_date=timezone.now()+datetime.timedelta(天=天))
类PollIndexDetailTests(TestCase):
def test_detail_view_与未来民意测验(自我):
"""
未来发布日期为的投票的详细视图应为
返回未找到的404。
"""
未来投票=创建投票(问题=“未来投票”,天数=5)
response=self.client.get(反向('polls:detail',args=(future\u poll.id,))
self.assertEqual(response.status_代码,404)
def test_detail_view_与过去的民意测验(自我):
"""
应显示发布日期在过去的投票的详细视图
民意测验的问题。
"""
过去的投票=创建投票(问题=“过去的投票”,天数=-5)
response=self.client.get(反向('polls:detail',args=(pass_poll.id,))
self.assertContains(响应、过去的投票问题、状态代码=200)
类PollIndexResultsTests(TestCase):
def测试结果查看与未来轮询(自我):
"""
未来发布日期为的民意测验的结果视图应
返回未找到的404。
"""
未来投票=创建投票(问题=“未来投票”,天数=5)
response=self.client.get(反向('polls:results',args=(future\u poll.id.))
self.assertEqual(response.status_代码,404)
def测试结果查看与过去调查(自我):
"""
应显示发布日期在过去的投票结果视图
民意测验的问题。
"""
过去的投票=创建投票(问题=“过去的投票”,天数=-5)
response=self.client.get(反向('polls:results',args=(pass_poll.id.))
self.assertContains(响应、过去的投票问题、状态代码=200)
类PollViewTests(测试用例):
def test_index_view_(无轮询)(自):
"""
如果不存在轮询,则应显示相应的消息。
"""
response=self.client.get(反向('polls:index'))
self.assertEqual(response.status_代码,200)
self.assertContains(响应,“没有可用的轮询”)
self.assertquerystequal(response.context['latest_polls'],[]
def test_index_view_与过去的民意测验(自我):
"""
索引页上应显示过去发布日期的投票。
"""
创建投票(问题=“过去的投票”,天数=-30)
response=self.client.get(反向('polls:index'))
self.assertquerystequal(
response.context['latest_polls'],
['']
)
def test_index_view_与未来民意测验(自我):
"""
带有未来发布日期的投票不应显示在
索引页。
"""
创建投票(问题=“未来投票”,天数=30)
response=self.client.get(反向('polls:index'))
self.assertContains(响应,“没有可用的轮询”,状态代码=200)
self.assertquerystequal(response.context['latest_polls'],[]
def test_index_view_与_future_poll_和_past_poll(自我)一起:
"""
即使过去和未来的民意调查都存在,也应该只保留过去的民意调查
显示。
"""
创建投票(问题=“过去的投票”,天数=-30)
创建投票(问题=“未来投票”,天数=30)
response=self.client.get(反向('polls:index'))
self.assertquerystequal(
response.context['latest_polls'],
['']
)
def test_index_view_与两次过去的民意测验(自我):
"""
轮询索引页面可能显示多个轮询。
"""
创建投票(问题=“过去的投票1”,天数=-30)
创建投票(问题=“过去的投票2”,天数=-5)
response=self.client.get(反向('polls:index'))
self.assertquerystequal(
response.context['lat]
...
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)
...