django RequestFactory丢失了URL kwargs [英] django RequestFactory loses url kwargs

查看:52
本文介绍了django RequestFactory丢失了URL kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从使用Django测试客户端切换到RequestFactory,以加快测试速度。但是,RequestFactory生成的请求不能为视图提供正确的 kwargs



示例:这是我的观点

  class SomeView(View) :
def get(self,request,* args,** kwargs):
return JsonResponse({'your kwargs':str(kwargs)})

with urlconf

  url(r'^ some_view /(?P< some_kwarg> [\-0-9a-fA-F] +)/ $',
views.SomeView.as_view(),
name ='some_view'),

和两个测试:

  def test_different_kwargs():

c = Client()
response = c.get(
reverse('bots:some_view',
kwargs = {'some_kwarg':'12345'}),

print('\n\nTestClient的响应:',response.content.decode())

rf = RequestFactory()
请求= rf.get(
反向('bots:some_view',
kwargs = {'some_kwarg':'12345'}),

response = SomeView.as_view()(request)
print('\n\n对请求的响应stFactory:',response.content.decode())

它们产生的是:

 对TestClient的响应:{ your kwargs: {'some_kwarg':'12345'}} 
RequestFactory的响应: { your kwargs: {}}

那么,<$ c $的意义是什么c> RequestFactory 是否丢失网址垃圾?还是有某种方法可以将它们放入视图中?

解决方案

编辑2020-03-07: 为了获得更多测试经验,我更新了答案,以消除对功能测试的困惑,并添加了一些建议。



有答案有两个方面。



快速解答:如何将 kwargs 放入风景?您需要将代码更改为此:

  def test_different_kwargs():
kwargs = {'some_kwarg':' 12345'}
url = reverse('bots:some_view',kwargs = kwargs)
c = Client()
response = c.get(url)
print('\ TestClient的n\nResponse:',response.content.decode())

rf = RequestFactory()
request = rf.get(url)
response = SomeView。 as_view()(request,** kwargs)
print('\n\nResponse for RequestFactory:',response.content.decode())

长答案
然后 RequestFactory Client
已经开发了这里:Django测试RequestFactory与客户端
,但我想完成一点。



在功能方面 Client 处理用于处理响应包括中间件和URL解析(URL匹配和参数提取)。另一方面, RequestFactory ,仅构建一个请求对象,让用户负责添加适当的属性并调用适当的视图函数或视图方法。



在第二种情况下,调用 ClassView.as_view()(request,* args,** kwargs)。 / p>

测试方面, Client 专注于集成测试(您将测试所有不同部分是否装配在一起:中间件,基于类/功能的视图,模板,模板标签),这是您在此处测试的端到端机制。



客户端-> {UrlResolver->中间件->视图->中间件-> TemplateResponse}->测试



使用 RequestFactory 您可以专注于测试较小的部分,基于类的视图方法,函数视图,中间件方法等。在这种意义上, RequestFactory 是与单元测试相关。



请参见请求工厂参考



如果您对单元测试和模拟方法感兴趣,则没有太多文献报道,但是您可以看一下本文(在隔离中测试Django视图) [ https://matthewdaly.co .uk / blog / 2015/08/02 / testing-django-views-in-isolation /]



最后,这一切都取决于如何您有很多时间可以专注于测试。集成/功能/单元测试有不同的优点和缺点。



建议(可能会有偏差):如果您开发网站,我建议以下内容:




  • 通过测试路线及其预期行为重点进行集成测试;

  • 添加单位/业务逻辑集成测试(Django中的模型);



使用 RequestFactory 将花费您更多时间,并且不会比使用 Client API带来太多好处。
使用 Client API,您将更接近网站的使用方式和行为。


I am trying to switch from using Django Test Client to RequestFactory to speed up my tests. However, requests generated by RequestFactory do not supply proper kwargs to views.

Example: this is my view

class SomeView(View):
    def get(self, request, *args, **kwargs):
        return JsonResponse({'your kwargs': str(kwargs)})

with urlconf

url(r'^some_view/(?P<some_kwarg>[\-0-9a-fA-F]+)/$',
    views.SomeView.as_view(),
    name='some_view'),

and two tests:

def test_different_kwargs():

    c = Client()
    response = c.get(
        reverse('bots:some_view',
                kwargs={'some_kwarg': '12345'}),
    )
    print('\n\nResponse for TestClient: ', response.content.decode())

    rf = RequestFactory()
    request = rf.get(
        reverse('bots:some_view',
                kwargs={'some_kwarg': '12345'}),
    )
    response = SomeView.as_view()(request)
    print('\n\nResponse for RequestFactory: ', response.content.decode())

What they produce is:

Response for TestClient:  {"your kwargs": "{'some_kwarg': '12345'}"}
Response for RequestFactory:  {"your kwargs": "{}"}

So, what's the point of RequestFactory if it loses url kwargs? Or is there a way to put them into the view somehow?

解决方案

EDIT 2020-03-07: As gain I more experience in testing, I updated my answer to remove confusion around functional testing and I added some advises.

There are two aspects to your answer.

Quick answer: how to put the kwargs in the view? You need to change your code to this:

def test_different_kwargs():
    kwargs={'some_kwarg': '12345'}
    url = reverse('bots:some_view', kwargs=kwargs)
    c = Client()
    response = c.get(url)
    print('\n\nResponse for TestClient: ', response.content.decode())

    rf = RequestFactory()
    request = rf.get(url)
    response = SomeView.as_view()(request, **kwargs)
    print('\n\nResponse for RequestFactory: ', response.content.decode())

Long answer: Then the difference between RequestFactory and Client: It has been developed a bit here: Django test RequestFactory vs Client but I would like to complete it a bit.

In terms of functionality Client handle the whole stack used to process the response including middlewares and url resolutions (url matching and parameters extraction). On the other side RequestFactory, just build a request object, leaving the responsibility to the user to add the proper attributes and to call the appropriate view functions or view methods.

Hence the call to ClassView.as_view()(request, *args, **kwargs) in the second case.

In terms of testing, Client is focused on integration testing (you will test that all the different parts fit together: middlewares, class-based/function view, template, templatetags), it's the end-to-end mechanism that you are testing here.

Client -> { UrlResolver -> Middleware -> View -> Middlewares -> TemplateResponse } -> Tests

Using RequestFactory you can focus on testing smaller parts, a class-based view method, a function view, a middleware method etc. In that sense RequestFactory is more related to unit testing.

See Request Factory Reference

If you are interest in unit tests and mocking methods, there is not much literature on this but you can look at this article (Testing Django Views in Isolation)[https://matthewdaly.co.uk/blog/2015/08/02/testing-django-views-in-isolation/].

In the end it all depends on how much you time can focus on testing. Integration/Functional/Unit testings have different advantages and drawbacks.

Advises (may be biased): If you develop a website, I advise the following:

  • focus on integration testing by testing routes and their expected behaviors ;
  • add unit/integration tests for your business logic (models in Django) ;

Unit testing parts using RequestFactory will take you more time and won't bring much benefits over using the Client API. Using Client API you will be closer to how your website will be used and how it will behave.

这篇关于django RequestFactory丢失了URL kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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