Django test RequestFactory vs Client

后端 未结 2 807
孤独总比滥情好
孤独总比滥情好 2021-01-31 01:32

I am trying to decide whether I should use Django\'s Client or RequestFactory to test my views.

I am creating my server using DjangoRESTFramewo

2条回答
  •  梦如初夏
    2021-01-31 02:37

    When using Django REST framework request factory would be helpfull to test the permissions.

    EX:

    Class TestPermission(TestCase):
      
        def test_admin_permisiion(self):
            admin_user = User.objects.create(email='admin@gmail.com',password='admin997',is_staff=True)
            factory = RequestFactory()
            request = factory.get('/')
            request.user = admin_user
            permission = IsAdminUser()
            has_permission = permission.has_permission(request, None)
            self.assertTrue(has_permission)
    

    what we have done hear is we created a admin user by setting is_staff=True , then we created a request and assigned the admin as user of the request. request factory helps us do so. then we checked the IsAdminUser() permission from DRF against the request. the test will pass .

    Client is to be used when you need to test the response returned by an Api.

提交回复
热议问题