W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
?RequestFactory
?與測(cè)試客戶端共享相同的 API。 但是,?RequestFactory
?不能像瀏覽器那樣運(yùn)行,而是提供一種生成請(qǐng)求實(shí)例的方法,該實(shí)例可用作任何視圖的第一個(gè)參數(shù)。 這意味著您可以像測(cè)試任何其他功能一樣測(cè)試視圖函數(shù)——就像一個(gè)黑匣子一樣,具有確切已知的輸入,可以測(cè)試特定的輸出。
?RequestFactory
?的 API 是測(cè)試客戶端 API 的一個(gè)稍加限制的子集。
get()
?、?post()
?、?put()
?、?delete()
?、?head()
?、?options()
? 和 ?trace()
? 方法。follow
?。因?yàn)檫@只是一個(gè)產(chǎn)生請(qǐng)求的工廠,所以由你來(lái)處理響應(yīng)。下面是一個(gè)使用請(qǐng)求工廠的單元測(cè)試:
from django.contrib.auth.models import AnonymousUser, User
from django.test import RequestFactory, TestCase
from .views import MyView, my_view
class SimpleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
self.user = User.objects.create_user(
username='jacob', email='jacob@…', password='top_secret')
def test_details(self):
# Create an instance of a GET request.
request = self.factory.get('/customer/details')
# Recall that middleware are not supported. You can simulate a
# logged-in user by setting request.user manually.
request.user = self.user
# Or you can simulate an anonymous user by setting request.user to
# an AnonymousUser instance.
request.user = AnonymousUser()
# Test my_view() as if it were deployed at /customer/details
response = my_view(request)
# Use this syntax for class-based views.
response = MyView.as_view()(request)
self.assertEqual(response.status_code, 200)
?RequestFactory
?創(chuàng)建 ?WSGI
?類的請(qǐng)求。如果你想創(chuàng)建 ?ASGI
?類的請(qǐng)求,包括有一個(gè)正確的 ?ASGI scope
?,你可以使用 ?django.test.AsyncRequestFactory
?。
該類與 ?RequestFactory
?直接 API 兼容,唯一的區(qū)別是它返回 ?ASGIRequest
?實(shí)例,而不是 ?WSGIRequest
?實(shí)例。它的所有方法仍然是可同步調(diào)用的。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: