Учебник Django - Тестирование vote(request, question_id)
Я прохожу свой путь через учебник по django и дошел до части 5 - Введение автоматизированного тестирования. Я хочу пойти дальше и написать тест для метода vote в views.py, но не могу понять, как смоделировать поведение. Есть ли способ сделать это?
models.py:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
views.py
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Я пробовал множество вещей в tests.py. Это последняя версия - я знаю, что choice_vote в настоящее время не то, что я хочу, все еще нужно фильтровать:
class QuestionVoteTests(TestCase):
def test_vote(self):
"""
Placeholder for vote method test.
"""
question = create_question(question_text="Question.", days=-5)
self.client.post(
reverse('polls:vote', args=(question.id,))
)
vote(self.client.post, question.id)
choice_vote = Choice.objects.filter(question_id=question.id).values()
print(choice_vote)
#self.assertEqual(choice_vote, 1)
return 0
Я просмотрел ответы о том, как тестировать множественный выбор, но это привело меня только так далеко. Спасибо!
Глядя на приведенный выше код для тестов, возникают некоторые проблемы и вопросы относительно используемого подхода. Добавляю их вместе с приведенным ниже кодом
def test_vote(self):
"""
Placeholder for vote method test.
"""
question = create_question(question_text="Question.", days=-5)
self.client.post(
reverse('polls:vote', args=(question.id,))
)
vote(self.client, question.id) # Why is the vote call made here?
choice_vote = Choice.objects.filter(question_id=question.id).values()
print(choice_vote) # What is the value of choice vote here?
#self.assertEqual(choice_vote, 1)
return 0. # Do not return from test
Кроме этого, что вы видите в журналах при запуске модульных тестов? Вы используете pytest для запуска тестов или команду Django manage.py test?