Jim*_*Jim 17 python testing django oauth-2.0 django-rest-framework
我有一个Django-rest-framework视图集/路由器来定义API端点.视图集定义如下:
class DocumentViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
model = Document
Run Code Online (Sandbox Code Playgroud)
并且路由器被定义为
router = DefaultRouter()
router.register(r'documents', viewsets.DocumentViewSet)
Run Code Online (Sandbox Code Playgroud)
与网址模式 url(r'^api/', include(router.urls))
我可以通过获取正确的访问令牌并将其用于授权,在浏览器/通过curl中点击此端点.但是,目前尚不清楚如何针对此端点编写测试.
这是我尝试过的:
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)
Run Code Online (Sandbox Code Playgroud)
这会因client.get()
呼叫的HTTP 401响应而失败.使用django-oauth-toolkit进行oauth2身份验证,在DRF中测试API端点的正确方法是什么?
Kev*_*own 25
在编写测试时,您应该从测试本身中提取您未测试的任何内容,通常将任何设置代码放在setUp
测试方法中.对于使用OAuth进行API测试的情况,这通常包括测试用户,OAuth应用程序和活动访问令牌.
对于django-oauth-toolkit
和其他Django应用程序,我总是建议查看测试,看看他们是如何做到的.这样可以避免进行不需要的API调用,尤其是对于像OAuth这样的多部分进程,并且只创建所需的少数模型对象.
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)
)
Run Code Online (Sandbox Code Playgroud)
从那里你只需要使用已生成的令牌进行身份验证.您可以通过注入Authorization
标头来执行此操作,也可以使用force_authenticate
Django REST Framework提供的方法.
我对 OAuth2 使用了相同的库,
这对我有用
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)
Run Code Online (Sandbox Code Playgroud)
现在一切都会按预期进行。希望这可以帮助。谢谢
归档时间: |
|
查看次数: |
10566 次 |
最近记录: |