Проверка, если вошедшие в систему пользователи видят неопубликованные вопросы - PullRequest
3 голосов
/ 01 июля 2019

EDIT


Вот мой тест:

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: False не соответствует действительности: не удалось найти «Пожалуйста, просмотрите эти неопубликованные вопросы:» в ответ

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...