测试-Django REST框架
test.py
测试
没有测试的代码会按设计中断。
— 雅各布·卡普兰-莫斯
REST框架包括一些帮助类,它们扩展Django的现有测试框架,并改进了对发出API请求的支持。
APIRequestFactory
延展Django的存在RequestFactory班级,等级.
创建测试请求
这个APIRequestFactory类支持与Django的标准几乎相同的API。RequestFactory班级,等级。这意味着.get(), .post(), .put(), .patch(), .delete(), .head()和.options()所有方法都可用。
from rest_framework.test import APIRequestFactory# Using the standard RequestFactory API to create a form POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'})
使用format论辩
创建请求体的方法,如post, put和patch,包括format参数,使使用多部分表单数据以外的内容类型生成请求变得容易。例如:
# Create a JSON POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
默认情况下,可用格式如下'multipart'和'json'...与Django现有的RequestFactory默认格式为'multipart'.
若要支持更大范围的请求格式,或更改默认格式,请参阅配置部分。.
显式编码请求主体
如果需要显式编码请求主体,可以通过设置content_type旗子。例如:
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
使用表单数据进行放置和修补
在Django之间有一个值得注意的区别RequestFactory和REST框架的APIRequestFactory多部分表单数据将被编码为其他方法,而不仅仅是.post().
例如,使用APIRequestFactory,您可以发出这样的表单PUT请求:
factory = APIRequestFactory()
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
使用Django‘sRequestFactory,您需要自己对数据进行显式编码:
from django.test.client import encode_multipart, RequestFactoryfactory = RequestFactory()
data = {'title': 'remember to email dave'}
content = encode_multipart('BoUnDaRyStRiNg', data)
content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
request = factory.put('/notes/547/', content, content_type=content_type)
强制认证
在使用请求工厂直接测试视图时,通常可以直接验证请求,而不必构造正确的身份验证凭据。
若要强制验证请求,请使用force_authenticate()方法。
from rest_framework.test import force_authenticatefactory = APIRequestFactory()
user = User.objects.get(username='olivia')
view = AccountDetail.as_view()# Make an authenticated request to the view...
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user)
response = view(request)
该方法的签名是force_authenticate(request, user=None, token=None)...在进行调用时,可以设置用户和令牌的任一或两个。
例如,当使用令牌强制进行身份验证时,可能会执行如下操作:
user = User.objects.get(username='olivia')
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.auth_token)
注: force_authenticate直接集request.user到内存中user举个例子。如果您正在重复使用相同的user跨多个更新保存的测试的实例。user州,你可能需要打电话refresh_from_db()在测试之间。
注*使用时APIRequestFactory,返回的对象是Django的标准HttpRequest,而不是REST框架的Request对象,该对象仅在视图被调用时生成。
这意味着直接在请求对象上设置属性可能并不总是产生预期的效果。例如,设置.token直接没有效果,并设置.user只有在使用会话身份验证时,才能直接工作。
# Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
request.user = user
response = view(request)
强迫CSRF验证
默认情况下,使用APIRequestFactory如果将csrf验证传递给