首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Django-oauth-toolkit使用Django-rest-framework测试API端点

如何使用Django-oauth-toolkit使用Django-rest-framework测试API端点
EN

Stack Overflow用户
提问于 2014-12-25 04:02:38
回答 2查看 13.5K关注 0票数 23

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

代码语言:javascript
复制
class DocumentViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    model = Document

并且路由器被定义为

代码语言:javascript
复制
router = DefaultRouter()
router.register(r'documents', viewsets.DocumentViewSet)

使用url模式url(r'^api/', include(router.urls))

我可以通过curl在浏览器中访问这个端点,只需获得正确的访问令牌并使用它进行授权即可。但是,目前还不清楚如何针对此端点编写测试。

下面是我尝试过的:

代码语言:javascript
复制
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) 

这将失败,并显示来自client.get()调用的HTTP401响应。在DRF中使用django-oauth-toolkit进行oauth2身份验证测试API端点的正确方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-26 03:36:49

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

对于django-oauth-toolkit和其他Django应用程序,我总是推荐looking at the tests to see how they do it。这使您可以避免进行不必要的API调用,特别是对于像OAuth这样的多部分流程,并且只创建所需的少数模型对象。

代码语言:javascript
复制
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)
    )

在那里,您只需要使用已生成的令牌进行身份验证。您可以通过injecting the Authorization header完成此操作,也可以使用Django REST Framework提供的use the force_authenticate method

票数 30
EN

Stack Overflow用户

发布于 2018-05-17 14:32:38

我对OAuth2使用了相同的库,

这对我很有效

代码语言:javascript
复制
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.models import get_access_token_model, 
get_application_model
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.test import APITestCase

Application = get_application_model()
AccessToken = get_access_token_model()
UserModel = get_user_model()

class Test_mytest(APITestCase):

    def setUp(self):

        oauth2_settings._SCOPES = ["read", "write", "scope1", "scope2", "resource1"]

        self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456")

        self.application = Application.objects.create(
                                                name="Test Application",
                                                redirect_uris="http://localhost http://example.com http://example.org",
                                                user=self.test_user,
                                                client_type=Application.CLIENT_CONFIDENTIAL,
                                                authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
                                            )

        self.access_token = AccessToken.objects.create(
                                                    user=self.test_user,
                                                    scope="read write",
                                                    expires=timezone.now() + timezone.timedelta(seconds=300),
                                                    token="secret-access-token-key",
                                                    application=self.application
                                                )
        # read or write as per your choice
        self.access_token.scope = "read"
        self.access_token.save()

        # correct token and correct scope
        self.auth =  "Bearer {0}".format(self.access_token.token)

    def test_success_response(self):

        url = reverse('my_url',)

        # Obtaining the POST response for the input data
        response = self.client.get(url, HTTP_AUTHORIZATION=self.auth)

        # checking wether the response is success
        self.assertEqual(response.status_code, status.HTTP_200_OK)

现在一切都会像预期的那样工作。希望这能有所帮助。谢谢

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27641703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档