2017-02-06 2 views
0

Djangoテストクライアントを使用して投票アプリケーションをテストしようとしています。このテストでは、私は投票の投票を模擬したPOSTリクエストを作成し、レスポンスのstatus_code(リダイレクトされたことを確認する)と投票数が増えたことを確認します。だから私が読んだものから、私のtests.pyはこのように見てしまった:Djangoテストクライアントを使用して投票アプリケーションをテストする

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を実行した後の最初の問題は、応答ステータスコードを302に変更する必要がありました.302投票を選択して投票ボタンをクリックした後、私は/polls/1/resultsにリダイレクトされます。さらに、投票が実際に登録されていないのは、応答ステータスコードを変更した後、少なくとも投票が増加したかどうかを確認するために、1が間違っているというエラーが表示され、0に変更する必要があります。も機能していません。

+1

あなたは405を取得すべきではありません。これは「方法が許可されていません」という意味です。私の推測では、間違った見方がリクエストを処理しているということです。あなたの 'polls/urls.py'を表示してください。 – Alasdair

+0

'client = Client()'は必要ありません。 Django 'TestCase'を使うときは' self.client'を使います。 – Alasdair

+0

私の投稿を 'views.py'で編集しました。 – Code4fun

答えて

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コールに制限することが、データを変更しているためです。

はリダイレクトに従うと、最終的な結果をテストするためのテスト使用response = client.post(..., follow=True)

https://docs.djangoproject.com/en/1.10/topics/http/decorators/#django.views.decorators.http.require_http_methodsを参照してください。

+0

私はちょうど理解していませんでした、どこにデコレータを追加すればよいのですか、本当にその目的は何ですか? – Code4fun

+0

'@require_http_methods([" POST "])'を使うのは良い考えですが、現在の問題については説明していません。 – Alasdair

+0

「POST」を登録していないと、間違いなく405エラーが発生し、データベースにエントリがない可能性があります。 – Risadinha

関連する問題