前提・実現したいこと
Djangoにてテストを特定し修正を行いたいです。
ここに質問の内容を詳しく書いてください。
下記書籍にてDjangoの勉強をしております。
■動かして学ぶ! Python Django開発入門
https://amzn.to/3vdlf5M
その中でテストを実行したのですが下記のエラーが出力されてしまい成功しません。
またサンプルのソースコードと見比べても間違いがないため、どこを修正すべきかわからず質問させていただきました。
発生している問題・エラーメッセージ
ERROR: test_delete_diary_failure (diary.tests.test_views.TestDiaryDeleteView) 日記削除処理が失敗することを検証する ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/name/venv_private_diary/bin/private_diary/diary/tests/test_views.py", line 113, in test_delete_diary_failure response = self.client.post(reverse_lazy('diary:diary_delete', kwargs={'pk': 999})) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 543, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 357, in post secure=secure, **extra) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 422, in generic return self.request(**r) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 503, in request raise exc_value File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 106, in dispatch user_test_result = self.get_test_func()() File "/Users/name/venv_private_diary/bin/private_diary/diary/views.py", line 43, in test_func diary = Diary.objects.get(pk=self.kwargs['pk']) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name diary.models.Diary.DoesNotExist: Diary matching query does not exist. ====================================================================== ERROR: test_update_diary_failure (diary.tests.test_views.TestDiaryUpdateView) 日記編集処理が失敗することを検証する ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/name/venv_private_diary/bin/private_diary/diary/tests/test_views.py", line 85, in test_update_diary_failure response = self.client.post(reverse_lazy('diary:diary_update', kwargs={'pk': 999})) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 543, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 357, in post secure=secure, **extra) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 422, in generic return self.request(**r) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/test/client.py", line 503, in request raise exc_value File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 106, in dispatch user_test_result = self.get_test_func()() File "/Users/name/venv_private_diary/bin/private_diary/diary/views.py", line 43, in test_func diary = Diary.objects.get(pk=self.kwargs['pk']) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/name/venv_private_diary/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name diary.models.Diary.DoesNotExist: Diary matching query does not exist. ---------------------------------------------------------------------- Ran 7 tests in 4.641s FAILED (errors=2) Destroying test database for alias 'default'... Process finished with exit code 1
該当のソースコード
test_views.py
Python
1from django.contrib.auth import get_user_model 2from django.test import TestCase 3from django.urls import reverse_lazy 4 5from ..models import Diary 6 7(・・略・・) 8 9class TestDiaryUpdateView(LoggedInTestCase): 10 """DiaryUpdateView用のテストクラス""" 11 12(・・略・・) 13 14 def test_update_diary_failure(self): # テスト失敗箇所 15 """日記編集処理が失敗することを検証する""" 16 17 # 日記編集処理(Post)を実行 18 response = self.client.post(reverse_lazy('diary:diary_update', kwargs={'pk': 999})) 19 20 # 存在しない日記データを編集しようとしてエラーになることを検証 21 self.assertEqual(response.status_code, 404) 22 23 24class TestDiaryDeleteView(LoggedInTestCase): 25 """DiaryDeleteView用のテストクラス""" 26 27(・・略・・) 28 29 def test_delete_diary_failure(self): # テスト失敗箇所 30 """日記削除処理が失敗することを検証する""" 31 32 # 日記削除処理(Post)を実行 33 response = self.client.post(reverse_lazy('diary:diary_delete', kwargs={'pk': 999})) 34 35 # 存在しない日記データを削除しようとしてエラーになることを検証 36 self.assertEqual(response.status_code, 404)
views.py
Python
1import logging 2 3from django.contrib import messages 4from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin 5from django.urls import reverse_lazy 6from django.views import generic 7 8from .forms import InquiryForm, DiaryCreateForm 9from .models import Diary 10 11logger = logging.getLogger(__name__) 12 13(・・略・・) 14 15class OnlyYouMixin(UserPassesTestMixin): 16 # 以下test_func関数がFalseを返すと、raise_exceptionがTrueの場合は403ページに遷移し、False(デフォルト)の場合はログインページに遷移 17 raise_exception = True 18 19 def test_func(self): 20 # URLに埋め込まれた主キーから日記データを1件取得 21 diary = Diary.objects.get(pk=self.kwargs['pk']) # 両方のテスト失敗箇所(line 43) 22 # ログインユーザーと日記データの作成ユーザーを比較し、異なればraise_exceptionの設定に従う 23 return self.request.user == diary.user 24 25(・・略・・) 26 27class DiaryUpdateView(LoginRequiredMixin, OnlyYouMixin, generic.UpdateView): 28 model = Diary 29 template_name = 'diary_update.html' 30 form_class = DiaryCreateForm 31 32 def get_success_url(self): 33 return reverse_lazy('diary:diary_detail', kwargs={'pk': self.kwargs['pk']}) 34 35 def form_valid(self, form): 36 messages.success(self.request, "日記を更新しました。") 37 return super().form_valid(form) 38 39 def form_invalid(self, form): 40 messages.error(self.request, "日記の更新に失敗しました。") 41 return super().form_invalid(form) 42 43class DiaryDeleteView(LoginRequiredMixin, OnlyYouMixin, generic.DeleteView): 44 model = Diary 45 template_name = 'diary_delete.html' 46 success_url = reverse_lazy('diary:diary_list') 47 48 def delete(self, request, *args, **kwargs): 49 messages.success(self.request, "日記を削除しました。") 50 return super().delete(request, *args, **kwargs)
試したこと
サンプルコードを見比べて誤字を修正しました。
補足情報
macOS Big Sur ver 11.6
Python 3.7.12
Django 2.2.2
回答1件
あなたの回答
tips
プレビュー