Django 测试 RequestFactory 与客户端 [英] Django test RequestFactory vs Client
问题描述
我正在决定是否应该使用 Django 的 Client
或 RequestFactory
来测试我的视图.
I am trying to decide whether I should use Django's Client
or RequestFactory
to test my views.
我正在使用 DjangoRESTFramework 创建我的服务器,到目前为止它真的很简单:
I am creating my server using DjangoRESTFramework and it's really simple, so far:
class SimpleModelList(generics.ListCreateAPIView):
"""
Retrieve list of all route_areas or create a new one.
"""
queryset = SimpleModel.objects.all()
serializer_class = SimpleModelSerializer
filter_backends = (IsOwnerFilterBackend,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
使用 Django 的 Client
和 RequestFactory
进行测试有什么区别,哪种方法更适合测试 REST 服务器(如果除了更喜欢一个之外还有什么区别)?
What are the differences between testing with Django's Client
and RequestFactory
and which approach is more suited for testing a REST server (if there is any difference besides liking one better)?
我是否应该同时创建测试以便为我的系统提供更好的覆盖率?
Should I create tests with both so as to provide a better coverage for my system?
推荐答案
RequestFactory
和 Client
有一些非常不同的用例.用一句话概括:RequestFactory
返回一个 request
,而 Client
返回一个 response
.
RequestFactory
and Client
have some very different use-cases. To put it in a single sentence: RequestFactory
returns a request
, while Client
returns a response
.
RequestFactory
做它所说的 - 它是一个创建 request
对象的工厂.不多不少.
The RequestFactory
does what it says - it's a factory to create request
objects. Nothing more, nothing less.
Client
用于伪造完整的请求-响应循环.它将创建一个 request
对象,然后通过 WSGI 处理程序传递该对象.此处理程序解析 url,调用适当的中间件,并运行视图.然后它返回响应对象.它还有一个额外的好处,它可以在 response
对象上收集大量额外的数据,这对于测试非常有用.
The Client
is used to fake a complete request-response cycle. It will create a request
object, which it then passes through a WSGI handler. This handler resolves the url, calls the appropriate middleware, and runs the view. It then returns the response object. It has the added benefit that it gathers a lot of extra data on the response
object that is extremely useful for testing.
RequestFactory
实际上不会触及您的任何代码,但 request
对象可用于测试需要有效 请求的代码部分代码>.
Client
运行您的视图,因此为了测试您的视图,您需要使用 Client
并检查响应.请务必查看 Client 上的文档代码>.
The RequestFactory
doesn't actually touch any of your code, but the request
object can be used to test parts of your code that require a valid request
. The Client
runs your views, so in order to test your views, you need to use the Client
and inspect the response. Be sure to check out the documentation on the Client
.
这篇关于Django 测试 RequestFactory 与客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!