Man*_*o22 3 python django django-testing
我想练习在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")
Run Code Online (Sandbox Code Playgroud)
但是我得到这个:
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no
arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)/$']
Run Code Online (Sandbox Code Playgroud)
如何获得该新创建帖子的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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1661 次 |
| 最近记录: |