使用 login_required 装饰器的 django 测试视图尊重 DRY

django testing views with login_required decorator respecting DRY

我有一个网站,其中所有视图都将使用@login_required 进行保护,当然,登录视图除外。
但是,如果我不向请求添加经过身份验证的用户,使用装饰器将导致调用这些视图的测试失败。我知道这可以在 setUp() 中完成,但在任何测试中写同一行 class 不符合 DRY 原则。

还有比这更好的方法吗?

正如您所说,您可以将登录移至setUp方法以避免测试class.

中的每个测试重复

如果您不喜欢在每个测试中复制 setUp 方法 class,您可以创建自己的测试用例 class 或 mixin。

class LoggedInTestCase(TestCase):

    def setUp(self):
        user = User.objects.create_user(username='username', password='password')
        self.client.login(username='username', password='password')

class MyTestCase(LoggedInTestCase):
    def test_stuff(self):
        ...

如果您重写子 class 中的 setUp 方法,请记住调用 super().

class MyOtherTestCase(LoggedInTestCase):
    def setUp(self):
        super(MyOtherTestCase, self).setUp()
        # other setUp code goes here

    def test_other_stuff(self):
        ...