如何为自定义Django通用视图编写测试?

时间:2018-07-28 11:15:40

标签: django django-testing

我不明白我们应该为Django视图编写测试的方式。因为,我的情况与其他人不同。

我有一个视图,比方说MyView,它继承自基于Django通用类的视图的CreateView。但是,在后台,我的意思是在form_valid函数中,此视图尝试使用Python库连接到远程服务器,然后根据用户的输入获取数据,然后处理其他详细信息并在一切正常的情况下保存对象,如果不是,则返回自定义错误。

如何处理这种观点,以便我编写测试?

(我可以使用类似的方法,但是不好处理可能的错误:

from django.test import Client
c = Client()
c.login(mydetails..)

y = c.post('/url/', {'my': 'data'})

可以,是的,但是在这种情况下,我只检查状态码。 y.status_code无济于事,因为即使表单存在错误,Django也会返回200。

1 个答案:

答案 0 :(得分:1)

为了简化django中的测试框架,测试将模拟客户端请求(例如用户单击链接“ URL”),该URL与将处理请求并向用户返回响应的视图相关联。例如,在测试中,您将断言该视图是否呈现正确的响应和模板。假设我们有一个创建博客的视图,该如何测试?参见下面的代码。

views.py

def createblog_view(request):
    if request.method == 'POST':
        form = BlogForm(request.POST)
        if form.is_valid():
            blog = form.save(commit=False)
            blog.author = request.user  # save the user who created the blog
            blog.save()
            return redirect(blog.get_absolute_url())
    else:
        form = BlogForm()
    context = {'form': form}
    return render(request, 'blog/createblog.html', context)

test.py

class BlogTest(TestCase):
        def setUp(self):
            # this user will be used to create the blog
            self.user = User.objects.create_superuser(
                'foo',
                'foo@test.com',
                'password'
            )

        def test_create_blog(self): # create update and delete a blog
            # log user in and user 
            self.client.login(username='foo', password='password')

            # create new blog
            # expected date from the user, you can put invalid data to test from validation
            form_data = { 
                'title': 'new test blog',
                'body': 'blog body'
            } 
            form = BlogForm(data=blogform_data) # create form indstance 

            """
            simulate post request with self.client.post
            /blog/createblog/ is the url associated with create_blog view
            """
            response = self.client.post('/blog/createblog/', form_data)
            # get number of created blog to be tested later
            num_of_blogs = Blog.objects.all().count()
            # get created blog
            blog = Blog.objects.get(title=form_data['title'])
            # test form validation
            self.assertTrue(blogform.is_valid())
            # test slugify method, if any
            self.assertEqual(blog.slug, 'new-test-blog')
            # test if the blog auther is the same logged in user
            self.assertEqual(blog.author, self.user1)
            # one blog created, test if this is true
            self.assertEqual(num_of_blogs, 1)
            # test redirection after blog created
            self.assertRedirects(
                createblog_response,
                '/blog/new-test-blog/',
                status_code=302,
                target_status_code=200
            )