Django4.0 進(jìn)階測(cè)試主題-請(qǐng)求工廠

2022-03-17 11:48 更新

class RequestFactory

?RequestFactory ?與測(cè)試客戶端共享相同的 API。 但是,?RequestFactory ?不能像瀏覽器那樣運(yùn)行,而是提供一種生成請(qǐng)求實(shí)例的方法,該實(shí)例可用作任何視圖的第一個(gè)參數(shù)。 這意味著您可以像測(cè)試任何其他功能一樣測(cè)試視圖函數(shù)——就像一個(gè)黑匣子一樣,具有確切已知的輸入,可以測(cè)試特定的輸出。

?RequestFactory ?的 API 是測(cè)試客戶端 API 的一個(gè)稍加限制的子集。

  • 它只能訪問(wèn) HTTP 的 ?get()?、?post()?、?put()?、?delete()?、?head()?、?options()? 和 ?trace()? 方法。
  • 這些方法接受所有相同的參數(shù),除了 ?follow?。因?yàn)檫@只是一個(gè)產(chǎn)生請(qǐng)求的工廠,所以由你來(lái)處理響應(yīng)。
  • 它不支持中間件。如果需要視圖正常運(yùn)行,會(huì)話和認(rèn)證屬性必須由測(cè)試本身提供。

例如

下面是一個(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)

AsyncRequestFactory

?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)用的。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)