Python,Django,教程,测试详细信息视图,错误

时间:2016-03-03 09:02:51

标签: python django django-testing

我正在通过Django教程,并在教程5>中遇到了错误。 '测试详细信息视图'

当我跑步时:

if(ret == 0) { //child process } else { //parent process }

在终端,我收到了这条消息:

python manage.py test polls

这是我在tests.py中与'使用过去的问题测试详细视图'相关的代码(它是后面的函数)。

Creating test database for alias 'default'...
.F.......
======================================================================
FAIL: test_detail_view_with_a_past_question (polls.tests.QuestionIndexDetailTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/theoford/Documents/python/04_django_intro/mysite/polls/tests.py", line 115, in test_detail_view_with_a_past_question
    status_code=200)
  File "/Library/Python/2.7/site-packages/django/test/testcases.py", line 398, in assertContains
    msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: Couldn't find 'Past Question.' in response

----------------------------------------------------------------------
Ran 9 tests in 0.030s

FAILED (failures=1)
Destroying test database for alias 'default'...

我是Stackoverflow社区的新手,所以如果这个问题的格式和表达不正确,不完整或不恰当,我会道歉,但是对于推进这个问题的任何帮助都将非常感激。

views.py:

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

    def test_detail_view_with_a_past_question(self):
        """
        The detail view of a question with a pub_date in the past should
        display the question's text.
        """
        past_question = create_question(question_text='Past Question.',
                                        days=-5)
        response = self.client.get(reverse('polls:detail',
                                   args=(past_question.id,)))
        self.assertContains(response, past_question.question_text,
                            status_code=200)

2 个答案:

答案 0 :(得分:0)

您想查看过去的问题。'在response.content,而不是response。将test_detail_view_with_a_past_question的最后一行更改为:

self.assertContains(response.content, past_question.question_text,
                        status_code=200)

答案 1 :(得分:0)

就我而言,测试用例以两种方式通过:

  1. 通过将属性 pk_url_kwargs 添加到 views.py 中的 DetailView,其值为 'question_id'

    pk_url_kwargs = 'question_id'

  1. 通过将 urls.py 中的“question_id”更改为“pk”

    path('/', views.DetailView.as_view(), name='detail'),

原因:

据我所知,通用 DetailView 默认根据名为 'pk' 或 'slug' 的参数查找对象——(选择一个主键等于名为 'pk' 的变量值的对象) , 但在教程中 urls.py 额外的整数参数被命名为 'question_id' 所以我们需要更改 views.py 中的 pk_url_kwargs 或 urls.py 中的参数名称。

相关问题