为轮询添加额外的过滤器urls.py导致测试失败 [英] Adding extra filter to polls urls.py causes tests to fail

查看:196
本文介绍了为轮询添加额外的过滤器urls.py导致测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 。

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 / $' poll.views.vote',name ='vote'),

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

  AssertionError:列表不同:[]!= ['<投票:过去的投票。>'] 

第二个列表包含1个附加元素。
第一个额外的元素0:
<投票:过去的投票>

- []
+ ['<民意调查:过去的投票>']

在我更改查询器之前,过滤出所有没有选择的轮询,测试没有失败。我已经在shell中测试过滤器,并且它在django服务器上运行的应用程序也似乎没有任何问题。发生了什么?



这是我使用的tests.py文件

  import datetime 

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

来自polls.models import Poll

def create_poll(问题,天):

创建一个给定的问题的投票,发布给定的
`days`抵消了现在(过去出现的民意调查是负面的,
对于尚未公布的民意调查显示为正)

return Poll.objects.create = question,
pub_date = timezone.now()+ datetime.timedelta(days = days))

class PollIndexDetailTests(TestCase):
def test_detail_view_with_a_future_poll(self):

将来有一个pub_date的民意测验的详细视图应该是
返回404找不到

future_poll = create_poll(questio n ='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):

以前有pub_date的民意测验的详细视图应该显示
民意调查的问题

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)

将来有一个pub_date的投票结果视图应该
返回404找不到。

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):

结果视图过去有一个pub_date的民意测验显示民意测验的问题。

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)

类PollViewTests(TestCase):
def test_index_view_with_no_polls(self)

如果不存在轮询,则应显示适当的消息。

response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code,200)
self.assertContains答案,没有民意调查可用。)
self.assertQuerysetEqual(response.context ['latest_polls'],[])

def test_index_view_with_a_past_poll(self):

过去使用pub_date进行投票应该显示在索引页面上。

create_poll(question =过去的投票,days = -30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context ['latest_polls'],
['<民意调查:过去的投票>']


def test_index_view_with_a_future_poll (自):

将来不要在
索引页面上显示与pub_date的投票。

create_poll(question =Future poll。,days = 30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response,没有轮询可用,status_code = 200)
self.assertQuerysetEqual(response.context ['latest_polls'],[])

def test_index_view_with_future_poll_and_past_poll(self )

即使过去和未来的投票都存在,只有过去的投票应该是
显示。

create_poll(question =过去的投票,days = -30)
create_poll(question =未来投票,days = 30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context ['latest_polls'],
['<民意调查:过去的投票> ;']


def test_index_view_with_two_past_polls(self):

轮询索引页面可能会显示多个轮询。

create_poll(question =过去的投票1.,days = -30)
create_poll(question =过去的投票2.,days = -5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context ['latest_polls'],
['<投票:过去投票2.>','<民意测验:过去的投票1.>']


class PollMethodTests(TestCase):

def test_was_published_recently_with_future_poll

was_published_recently()应该为
pub_date将来的投票返回False

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()应该为pub_date
的民意调查返回False大于1天

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()应该为pub_date
在最后一天内的投票返回True

recent_poll = Poll(pub_date = timezone.now() - datetime.timedelta(hours = 1))
self.assertEqual(recent_poll.was_published_recently(),True)


解决方案

我认为问题是,在测试中,你正在创建一个全新的民意调查,没有任何选择。在细节视图中,您将过滤此轮询。所以它没有返回任何东西,所以测试失败。



您还可以为previous_test创建的投票创建一些选项,以便此轮询通过过滤。 p>

如下所示:

  ... 
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)
...


Following the tutorial at djangoproject, I have tried to have urls.py filter out the polls with no choices with the urlpattern below.

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'),
)

However, when I run the tests from the tutorial, an assertion error occurs for each test that creates a past_poll, similar to the error below.

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

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

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

Before I changed the queryset to filter out all polls w/o choices the tests didn't fail. I have tested the filter in the shell and it works and running the app on the django server also doesn't seem to have any problems. What is going wrong?

Here is the tests.py file that I used

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)

解决方案

I think the problem is, that on the test, you're creating a brand new poll, without any choices yet. And in the detail-view you're filtering this polls out. So it's returning nothing, and so the test fails.

You could additionally create some choices for the poll you just created on the past_test so this polls pass the filtering.

Something like:

...
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)
...

这篇关于为轮询添加额外的过滤器urls.py导致测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆