如何使用Django-oauth-toolkit通过Django-rest-framework测试API端点 [英] How to test an API endpoint with Django-rest-framework using Django-oauth-toolkit for authentication

查看:82
本文介绍了如何使用Django-oauth-toolkit通过Django-rest-framework测试API端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django-rest-framework视图集/路由器来定义API端点。视图集的定义如下:

I have a Django-rest-framework viewset/router to define an API endpoint. The viewset is defined as such:

class DocumentViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    model = Document

路由器定义为

router = DefaultRouter()
router.register(r'documents', viewsets.DocumentViewSet)

具有url模式 url(r'^ api /',include(router.urls))

我可以通过获取正确的访问令牌并将其用于授权,在浏览器中/通过curl达到此端点。但是,尚不清楚如何针对此端点编写测试。

I can hit this endpoint in the browser/through curl just fine by getting the right access token and using it for authorization. However, it's not clear how to write tests against this endpoint.

这是我尝试过的操作:

class DocumentAPITests(APITestCase):
    def test_get_all_documents(self):
        user = User.objects.create_user('test', 'test@test.com', 'test')
        client = APIClient()
        client.credentials(username="test", password="test")
        response = client.get("/api/documents/")
        self.assertEqual(response.status_code, 200) 

使用HTTP 401失败 client.get()调用的响应。使用django-oauth-toolkit进行oauth2身份验证在DRF中测试API端点的正确方法是什么?

This fails with an HTTP 401 response from the client.get() call. What is the right way to test an API endpoint in DRF using django-oauth-toolkit for oauth2 authentication?

推荐答案

编写测试时,您应该旨在从测试本身中提取所有未测试的内容,通常将任何设置代码放入测试的 setUp 方法中。对于使用OAuth进行的API测试,通常包括测试用户,OAuth应用程序和活动访问令牌。

When you are writing tests, you should aim to extract anything you are not testing from the test itself, typically putting any setup code in the setUp method of the test. In the case of API tests with OAuth, this usually includes the test user, OAuth application, and the active access token.

对于 django-oauth -toolkit 和其他Django应用程序,我总是建议查看测试以了解其操作方式。这样一来,您就可以避免进行不必要的API调用,尤其是对于像OAuth这样的多部分进程而言,而只需创建一些所需的模型对象。

For django-oauth-toolkit, and other Django applications, I would always recommend looking at the tests to see how they do it. This allows you to avoid making unneeded API calls, especially for multi-part processes like OAuth, and only create the few model objects that are required.

def setUp(self):
    self.test_user = UserModel.objects.create_user("test_user", "test@user.com", "123456")

    self.application = Application(
        name="Test Application",
        redirect_uris="http://localhost",
        user=self.test_user,
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
    )
    self.application.save()

def test_revoke_access_token(self):
    from datetime import datetime
    from django.utils import timezone

    tok = AccessToken.objects.create(
        user=self.test_user, token='1234567890',
        application=self.application, scope='read write',
        expires=timezone.now() + datetime.timedelta(days=1)
    )

从那里您只需要使用已生成的令牌进行身份验证。您可以通过注入授权标头,或者您也可以使用Django REST Framework提供的 force_authenticate 方法

From there you just need to authenticate using the token that has been generated. You can do this by injecting the Authorization header, or you can use the force_authenticate method provided by Django REST Framework.

这篇关于如何使用Django-oauth-toolkit通过Django-rest-framework测试API端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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