如何测试视图是否用"login_required"修饰? (Django) [英] How to test if a view is decorated with "login_required" (Django)

查看:163
本文介绍了如何测试视图是否用"login_required"修饰? (Django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为用"login_required"修饰的视图进行一些(隔离的)单元测试.示例:

I'm doing some (isolated) unit test for a view which is decorated with "login_required". Example:

@login_required
def my_view(request):
    return HttpResponse('test')

是否可以测试"my_view"功能是否用"login_required"修饰?

Is it possible to test that the "my_view" function is decorated with "login_required"?

我知道我可以使用集成测试(使用测试客户端)来测试行为(将匿名用户重定向到登录页面),但是我想通过隔离测试来进行测试.

I know I can test the behaviour (anonymous user is redirected to login page) with an integration test (using the test client) but I'd like to do it with an isolated test.

有什么主意吗?

谢谢!

推荐答案

当然,必须可以通过某种方式对其进行测试.不过,绝对不值得.编写一个完全隔离的单元测试以检查是否应用了装饰器,只会导致非常复杂的测试.测试错误的可能性比被测试的行为错误的可能性更大.我会强烈劝阻它.

Sure, it must be possible to test it in some way. It's definitely not worth it, though. Writing a fully isolated unit test to check that the decorator is applied will only result in a very complicated test. There is a way higher chance that the test will be wrong than that the tested behaviour is wrong. I would strongly discourage it.

最简单的测试方法是使用Django的Client伪造对关联URL的请求,并检查重定向.如果您使用Django的任何测试用例作为基类:

The easiest way to test it is to use Django's Client to fake a request to the associated url, and check for a redirect. If you're using any of Django's testcases as your base class:

class MyTestCase(django.test.TestCase):
    def test_login_required(self):
        response = self.client.get(reverse(my_view))
        self.assertRedirects(response, reverse('login'))

稍微复杂一点,但更孤立的测试是使用RequestFactory直接创建该请求对象来调用视图. assertRedirects()在这种情况下不起作用,因为它取决于Client设置的属性:

A slightly more complicated, but a bit more isolated test would be to call the view directly using the RequestFactory to create a request object. assertRedirects() won't work in this case, since it depends on attributes set by the Client:

from django.test.client import RequestFactory

class MyTestCase(django.test.TestCase):
    @classmethod
    def setUpClass(cls):
        super(MyTestCase, cls).setUpClass()
        self.rf = RequestFactory()

    def test_login_required(self):
        request = self.rf.get('/path/to/view')
        response = my_view(request, *args, **kwargs)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], login_url)
        ...

这篇关于如何测试视图是否用"login_required"修饰? (Django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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