Testing
REST框架包括幾個幫助類,可以擴展Django現有的測試框架,并改進對API請求的支持。
APIRequestFactory
擴展 Django 現有的 RequestFactory
class.
Creating test requests
APIRequestFactory類支持與Django標準的RequestFactory類幾乎相同的API。這意味著標準的.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'})
Using the format
argument
創建請求體的方法,例如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'
。
要支持更廣泛的請求格式或更改默認格式,請參閱配置部分.
Explicitly encoding the request body
如果請求體中需要明確的編碼,你可以設置 content_type 標志。例如:
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
PUT and PATCH with form data
Django RequestFactory和REST框架APIRequestFactory之間值得注意的一個區別是,多表單數據將被編碼用于除.post()以外的方法。
例如,使用APIRequestFactory,您可以像這樣做一個PUT的表單請求:
factory = APIRequestFactory()
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
使用Django的RequestFactory,您需要自己對數據進行顯式編碼:
from django.test.client import encode_multipart, RequestFactory
factory = 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)
Forcing authentication
當直接使用請求工廠測試視圖時,能夠直接驗證請求通常很方便,而不必構建正確的身份驗證憑據。
要強制驗證請求,請使用force_authenticate()方法。
from rest_framework.test import force_authenticate
factory = 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.token)
Note:當使用 APIRequestFactory
時,返回的是Django標準的 HttpRequest,而不是Rest framwork 的Request對象,該對象只有在生成視圖時生成。
這意味著直接在請求對象上設置屬性可能并不總是具有你所期望的效果。 例如,直接設置.token將不起作用,直接使用.user只會在會話認證認證時有用。
# Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
request.user = user
response = view(request)
Forcing CSRF validation
默認情況下,使用APIRequestFactory創建的請求在傳遞到REST框架視圖時不會應用CSRF驗證。 如果需要明確地打開CSRF驗證,可以在實例化工廠時設置enforce_csrf_checks標志。
factory = APIRequestFactory(enforce_csrf_checks=True)
Note:值得注意的是,Django的標準RequestFactory不需要包含此選項,因為當使用常規Django時,CSRF驗證發生在中間件中,直接測試視圖時不會運行。 當使用REST框架時,CSRF驗證在視圖中進行,因此請求工廠需要禁用視圖級別的CSRF檢查。
APIClient
Making requests
APIClinet 類支持與 Django標準的Client類相同的接口。這意味標準的.get(), .post(), .put(), .patch(), .delete(), .head() 和 .options() 方法都是可用的。例如:
from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')
要支持更廣泛的請求格式或者改變默認格式,請參閱配置部分。
Authenticating
.login(**kwargs)
登錄方法的功能與Django的常規Client類完全相同。 這允許您針對包括SessionAuthentication在內的任何視圖驗證請求。
# Make all requests in the context of a logged in session.
client = APIClient()
client.login(username='lauren', password='secret')
登出是通常調用 logout 方法。
# Log out
client.logout()
登錄方法適用于測試使用會話認證的API,例如包含AJAX與API交互的網站。