Testing
REST框架包括幾個幫助類哭尝,可以擴展Django現(xiàn)有的測試框架只厘,并改進對API請求的支持涌献。
APIRequestFactory
擴展 Django 現(xiàn)有的 RequestFactory
class.
Creating test requests
APIRequestFactory類支持與Django標(biāo)準的RequestFactory類幾乎相同的API描孟。這意味著標(biāo)準的.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
創(chuàng)建請求體的方法,例如post, put 和 patch
掏愁,包含一個 format
參數(shù)歇由,這使得使用除多表單數(shù)據(jù)之外的內(nèi)容類型可以輕松生成請求。 例如:
# Create a JSON POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
默認可使用的格式有 'multipart'
和 'json'
果港。為了與Django現(xiàn)有的 RequestFactory
兼容沦泌,默認格式為 'multipart'
。
要支持更廣泛的請求格式或更改默認格式辛掠,請參閱配置部分.
Explicitly encoding the request body
如果請求體中需要明確的編碼谢谦,你可以設(shè)置 content_type 標(biāo)志。例如:
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
PUT and PATCH with form data
Django RequestFactory和REST框架APIRequestFactory之間值得注意的一個區(qū)別是萝衩,多表單數(shù)據(jù)將被編碼用于除.post()以外的方法回挽。
例如,使用APIRequestFactory猩谊,您可以像這樣做一個PUT的表單請求:
factory = APIRequestFactory()
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
使用Django的RequestFactory千劈,您需要自己對數(shù)據(jù)進行顯式編碼:
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
當(dāng)直接使用請求工廠測試視圖時,能夠直接驗證請求通常很方便牌捷,而不必構(gòu)建正確的身份驗證憑據(jù)。
要強制驗證請求,請使用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)
。 進行調(diào)用時鸿市,可以設(shè)置用戶和令牌中的一個或兩者锯梁。
例如即碗,當(dāng)使用令牌進行強制身份驗證時焰情,可能會執(zhí)行以下操作:
user = User.objects.get(username='olivia')
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.token)
Note:當(dāng)使用 APIRequestFactory
時,返回的是Django標(biāo)準的 HttpRequest剥懒,而不是Rest framwork 的Request對象内舟,該對象只有在生成視圖時生成。
這意味著直接在請求對象上設(shè)置屬性可能并不總是具有你所期望的效果初橘。 例如验游,直接設(shè)置.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創(chuàng)建的請求在傳遞到REST框架視圖時不會應(yīng)用CSRF驗證。 如果需要明確地打開CSRF驗證夜只,可以在實例化工廠時設(shè)置enforce_csrf_checks標(biāo)志垒在。
factory = APIRequestFactory(enforce_csrf_checks=True)
Note:值得注意的是,Django的標(biāo)準RequestFactory不需要包含此選項扔亥,因為當(dāng)使用常規(guī)Django時场躯,CSRF驗證發(fā)生在中間件中,直接測試視圖時不會運行旅挤。 當(dāng)使用REST框架時踢关,CSRF驗證在視圖中進行,因此請求工廠需要禁用視圖級別的CSRF檢查粘茄。
APIClient
擴展了 Django 現(xiàn)有的 Client class.
Making requests
APIClinet 類支持與 Django標(biāo)準的Client類相同的接口签舞。這意味標(biāo)準的.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的常規(guī)Client類完全相同。 這允許您針對包括SessionAuthentication在內(nèi)的任何視圖驗證請求嘹朗。
# Make all requests in the context of a logged in session.
client = APIClient()
client.login(username='lauren', password='secret')
登出是通常調(diào)用 logout 方法师妙。
# Log out
client.logout()
登錄方法適用于測試使用會話認證的API,例如包含AJAX與API交互的網(wǎng)站屹培。