【发布时间】:2014-10-21 11:05:27
【问题描述】:
对我的端点的查询工作正常(只要我传递一个有效的令牌),它返回我的响应数据的 json 表示。
调用我的端点的服务 api 中的代码,在标头中传递一个身份验证令牌:
headers = {'content-type': 'application/json',
'Authorization': 'Token {}'.format(myToken)}
url = 'http://localhost:8000/my_endpoint/'
r = session.get(url=url, params=params, headers=headers)
在views.py中,我有一个方法装饰器,它将调度方法包装在视图上(viewsets.ReadOnlyModelViewSet):
def login_required(f):
def check_login_and_call(request, *args, **kwargs):
authentication = request.META.get('HTTP_AUTHORIZATION', b'')
if isinstance(authentication, str):
authentication = authentication.encode(HTTP_HEADER_ENCODING)
key = authentication.split()
if not key or len(key) != 2:
raise PermissionDenied('Authentication failed.')
user, token = authenticate_credentials(key[1])
return f(request, *args, **kwargs)
return check_login_and_call
我正在尝试编写一个测试来使用令牌验证请求:
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory
from rest_framework.test import APITestCase
from rest_framework.test import force_authenticate
class EndpointViewTest(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.user = User.objects.create_user(
username='user@foo.com', email='user@foo.com', password='top_secret')
self.token = Token.objects.create(user=self.user)
self.token.save()
def test_token_auth(self):
request = self.factory.get('/my_endpoint')
force_authenticate(request, token=self.token.key)
view = views.EndpointViewSet.as_view({'get': 'list'})
response = view(request)
self.assertEqual(response.status_code, 200)
json_response = json.loads(response.render().content)['results']
由于某种原因,我无法获得正确传递此测试令牌的请求。使用 force_authenticate 似乎不会更改我用于验证令牌的标头。当前输出正在引发“PermissionDenied:身份验证失败”。因为没有在请求中设置令牌。
有没有合适的方法在我的测试的请求标头中设置它或重构我首先使用它的方式?
【问题讨论】:
标签: python django authentication integration-testing django-rest-framework