Django测试RequestFactory与Client [英] Django test RequestFactory vs Client

查看:84
本文介绍了Django测试RequestFactory与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 返回一个请求,而 Client 返回响应

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 会执行它所说的-这是创建请求对象。没什么,没什么。

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 并检查响应。请务必查看<$ c $上的文档。 c>客户

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与Client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆