使用@user_passes_test装饰器

时间:2017-03-10 13:24:19

标签: django django-views

我的观看文件有:

def is_authorised(user):
    return user.groups.filter(name='bookkeepers').exists()

@login_required
def unauthorised(request):
    context = {'user': request.user}
    return render(request, 'order_book/unauthorised.html', context)

@login_required
@user_passes_test(is_authorised,
                  login_url='/order_book/unauthorised/',
                  redirect_field_name=None)
def book(request):
    return render(request, 'order_book/book.html', {})

我想编写一个测试断言未经授权的登录用户确实被正确重定向,到目前为止,我有这个:

class RestrictedViewsTest(TestCase):

    @classmethod
    def setUpTestData(cls):  # noqa
        """Set up data for the whole TestCase."""
        User.objects.create_user(username='JaneDoe',
                                 email='jane.doe@example.com',
                                 password='s3kr3t')

    def setUp(self):
        auth = self.client.login(username='JaneDoe', password='s3kr3t')
        self.assertTrue(auth)

    def test_book(self):
        response = self.client.get('/order_book/book')
        self.assertEqual(response.status_code, 301, response)
        self.assertTrue(isinstance(response, HttpResponsePermanentRedirect))

    def tearDown(self):
        self.client.logout()

这样可以正常工作,但我无法理解将重定向到url的位置。试图让response['Location']给我'/ order_book / book'这是不对的。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您可以使用assertRedirects方法。

def test_book(self):
    response = self.client.get('/order_book/book/')
    self.assertRedirects(response, '/order_book/unauthorised/', status_code=302, target_status_code=200)