[英]How do I test a Django CreateView?
我想練習在Django上進行測試,並且有一個要測試的CreateView。 該視圖允許我創建一個新帖子,我想檢查它是否可以找到沒有發布日期的帖子,但是首先我要測試具有發布日期的帖子,以習慣語法。 這就是我所擁有的:
import datetime
from django.test import TestCase
from django.utils import timezone
from django.urls import reverse
from .models import Post, Comment
# Create your tests here.
class PostListViewTest(TestCase):
def test_published_post(self):
post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()})
response = self.client.get(reverse('blog:post_detail'))
self.assertContains(response, "really important")
但是我得到這個:
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no
arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)/$']
如何獲得該新創建帖子的pk?
謝謝!
您可以直接從數據庫中獲取它。
請注意,您不應在測試中調用兩個視圖。 每個測試應僅調用其實際測試的代碼,因此這應該是兩個單獨的視圖:一個調用創建視圖並斷言該條目位於數據庫中,一個視圖直接創建一個條目然后將詳細信息視圖調用到檢查它是否顯示。 所以:
def test_published_post(self):
self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()})
self.assertEqual(Post.objects.last().title, "Super Important Test")
def test_display_post(self):
post = Post.objects.create(...whatever...)
response = self.client.get(reverse('blog:post_detail', pk=post.pk))
self.assertContains(response, "really important")
您想進行的測試是使用可靠的Django Databse API來重新創建已創建的數據,並查看您的視圖是否代表該數據。
由於您僅創建1個模型實例並保存它。 您可以通過獲取它的pk
model_pk = Post.objects.get(author="manualvarado22").pk
然后應將此pk作為Exception狀態插入到您的URL中。
但是我還建議您進行一次適度的測試,在該測試中,您可以通過django模型API直接檢查數據庫中是否存在新創建的“ Post”。 編輯:
在測試時,django或您使用的測試模塊會創建一個僅用於測試的干凈數據庫,並在測試運行后銷毀它。 因此,如果您想在測試時訪問用戶,則必須在測試設置或測試方法本身中創建該用戶。 否則,用戶表將為空。
有了您的出色回答以及一些額外的SO研究,我終於能夠解決此問題。 這是測試的樣子:
def test_display_no_published_post(self):
test_user = User.objects.create(username="newuser", password="securetestpassword")
post = Post.objects.create(author=test_user, title="Super Important Test", content="This is really important.")
response = self.client.get(reverse('blog:post_detail', kwargs={'pk':post.pk}))
self.assertEqual(response.status_code, 404)
這是創建和詳細視圖:
class PostDetailView(DetailView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now())
class PostCreateView(LoginRequiredMixin, CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.