如何测试Django CreateView? [英] How do I test a Django CreateView?

查看:87
本文介绍了如何测试Django CreateView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想练习在Django上的测试,并且我有一个要测试的CreateView。该视图允许我创建一个新帖子,我想检查它是否可以找到没有发布日期的帖子,但是首先我要测试具有发布日期的帖子,以习惯语法。这就是我所拥有的:

I want to practice testing on Django, and I have a CreateView I want to test. The view allows me to create a new post and I want to check if it can find posts without a publication date, but first I'm testing posts with published date just to get used to syntax. This is what I have:

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?

How do I get the pk for that newly created post?

谢谢!

推荐答案

您可以直接从数据库中获取它。

You can get it directly from the database.

请注意,您不应在测试中调用两个视图。每个测试应仅调用其实际测试的代码,因此这应该是两个单独的视图:一个调用创建视图并断言该条目位于数据库中,另一个视图直接创建一个条目然后将详细信息视图调用到检查它是否显示。因此:

Note, you shouldn't call two views in your test. Each test should only call the code it is actually testing, so this should be two separate views: one to call the create view and assert that the entry is in the db, and one that creates an entry directly and then calls the detail view to check that it displays. So:

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 CreateView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆