使用Django测试客户端

时间:2017-02-06 14:59:23

标签: python django

我正在尝试使用Django测试客户端测试民意调查应用程序。在这个测试中,我创建了一个POST请求,该命令模拟对轮询的投票,然后检查响应的status_code(检查我是否已被重定向)并验证投票数量是否增加。所以根据我的阅读,我的tests.py最终看起来像这样:

from django.test import Client
from django.test import TestCase
from mysite.polls.models import Question, Choice

class PollTest(TestCase):

    def test_voting(self):
        client = Client()
        # Perform a vote on the poll by mocking a POST request.
        response = client.post('/polls/1/vote/', {'choice': '1',})
        # In the vote view we redirect the user, so check the
        # response status code is 302.
        self.assertEqual(response.status_code, 302)
        # Get the choice and check there is now one vote.
        choice = Choice.objects.get(pk=1)
        self.assertEqual(choice.votes, 1)

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

我的urls.py看起来像这样:

from django.conf.urls import url
from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
   ]

我在运行python manage.py test后遇到的第一个问题是我必须将响应状态代码更改为405,当它应该是302时,因为在选择投票并单击投票按钮后,我得到了重定向到/polls/1/results。此外,投票实际上没有被注册,因为在更改响应状态代码之后,只是为了看看是否至少增加了投票,我得到1错误的错误并且应该更改为0,这意味着投票过程也没有运作。

1 个答案:

答案 0 :(得分:0)

添加以下装饰器以允许POST:

from django.views.decorators.http import require_http_methods

@require_http_methods(["POST"])
def vote(request, poll_id):  # this is your method from above
    p = get_object_or_404(Poll, pk=question_id)
    try:
        ...

否则,此视图默认处理GET方法。与此同时,您确实希望将vote()限制为POST次调用,因为它正在修改您的数据。

请参阅https://docs.djangoproject.com/en/1.10/topics/http/decorators/#django.views.decorators.http.require_http_methods

在测试中使用response = client.post(..., follow=True)来跟踪重定向并测试最终结果。