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に変更する必要があります。も機能していません。
あなたは405を取得すべきではありません。これは「方法が許可されていません」という意味です。私の推測では、間違った見方がリクエストを処理しているということです。あなたの 'polls/urls.py'を表示してください。 – Alasdair
'client = Client()'は必要ありません。 Django 'TestCase'を使うときは' self.client'を使います。 – Alasdair
私の投稿を 'views.py'で編集しました。 – Code4fun