测试登录用户是否看到未发布的问题

时间:2019-07-01 13:19:04

标签: python django testing

编辑


这是我的考试:

def test_admin_sees_unpublished_questions(self):
    """
    Logged-in admin users see unpublished questions on the index page.
    """
    # create admin user and log her in
    password = 'password'
    my_admin = User.objects.create_superuser('myuser', 'myemail@test.com', password)
    user = authenticate(username="myuser", password="password")
    if user is not None:
        print(user.username)
    else:
        print('Not found!')
    self.client.login(username=my_admin.username, password=password)
    #create future question and check she can see it
    create_question(question_text="Unpublished question.", days=5)
    response = self.client.get(reverse('polls:index'))
    self.assertContains('Please review these unpublished questions:')
    self.assertEqual(response.context["user"], user)
    self.assertQuerysetEqual(
        response.context['unpublished_question_list'],
        ['<Question: Unpublished question.>']
    )

有点混乱。有几行检查上下文中是否有用户,这些用户似乎都显示response.context [“ user”]。

这是我的观点:


class IndexView(generic.ListView):
    template_name = 'polls/index.html'

    def get_queryset(self):
        """
        Return the last five published questions (not including those set to be
        published in the future).
        """

        queryset = Question.objects.filter(
                        pub_date__lte=timezone.now()
                    ).exclude(
                        #question without choices
                        choice=None
                    ).order_by('-pub_date')[:5]
        return queryset

    def get_context_data(self, **kwargs):
        """
        Override get_context_data to add another variable to the context.
        """
        context = super(IndexView, self).get_context_data(**kwargs)
        context['unpublished_question_list'] = Question.objects.filter(pub_date__gte=timezone.now())
        print(context)
        return context

我正在为django民意调查应用程序教程编写测试。

我想编写一个测试,该测试可以登录用户,并在将来创建具有发布日期的问题模型的实例,并确保该登录用户可以看到此问题。

我尝试使用

self.assertContains('Please review these unpublished questions: ') 

在测试方法中,因为我的模板如下所示:

{% if user.is_authenticated %}
        <p>Hello, {{ user.username }}. Please review these unpublished questions: </p>
        {% if unpublished_question_list %} etc

但即使

self.assertEqual(response.context["user"], user)

之后通过测试

self.client.login(username=my_admin.username, password=password)

我的模板似乎无法正确呈现给测试客户端。

一些帮助将不胜感激!

AssertionError:错误不是正确的:找不到'请回复这些未发布的问题:'

0 个答案:

没有答案