django 测试 client.put 没有数据

标签 django testing put

我正在尝试使用 REST 框架测试 Django View 。 它是这样开始的。

class MoveViewSet(viewsets.ModelViewSet):
    serializer_class = FamilySerializer
    queryset = Family.objects.all()
    http_method_names = ['put']

    def update(self, request, pk=None):
        user = request.mobile_user
        ...
        family_id = request.POST.get('family_id', None)
        ...

在 test.py 中我提出这样的请求。

data = dict(
        join_type='join',
        family_id=target_family.id,
    )
# also tried data = { ... }

header = {
        'Authorization': user.api_key,
        ...
    }
client = Client()
response = client.put(url, data=data, content_type='x-www-form-urlencoded', **header)

### What I've tried ###
# response = client.put(url, data=data, **header)
# response = self.client.put(url, data=data, **header)
# response = client.put(url, data=data, content_type='application/json', **header)

但在 View 中,request.POST.get('paramname', 'default') 出错。 request.POST 参数集为空,当然,request.PUT 为 None。

我检查了中间件,但我也没有在那里找到参数。 我也在中间件的 process_request 中尝试过这个。

def process_request(self, request):
    if request.method == "PUT" and request.content_type != "application/json":
        if hasattr(request, '_post'):
            del request._post
            del request._files
        try:
            request.method = "POST"
            request._load_post_and_files()
            request.method = "PUT"
        except AttributeError as e:
            request.META['REQUEST_METHOD'] = 'POST'
            request._load_post_and_files()
            request.META['REQUEST_METHOD'] = 'PUT'

        request.PUT = request.POST

它给了我这个错误。 AttributeError: 'WSGIRequest' 对象没有属性 'content_type'

如果我发送带有数据的 client.post(),request.POST 有数据,但 put 没有。 如何使用参数测试 client.put()?

最佳答案

请求的content_type属性已添加到 Django 1.10 中。由于您使用的是 Django 1.9,因此您不能使用此属性。您可以检查提到的 request.META.get('HTTP_ACCEPT') 解决方案 here或更新 Django。

关于django 测试 client.put 没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226934/

相关文章:

Django:如何有条件地过滤外键

python - 如何在 Python Django 中从表单实例创建表单集

python - 突然我得到 DJANGO_SETTINGS_MODULE is not defined when using runserver

performance - 如何保持自动化测试的快速?

angularjs - 更新模型时 Angular 2 中的双向绑定(bind)

python - Django:异常值(2013, '2013: Lost connection to MySQL server during query',无)

c# - 单步执行测试时测试成功;否则不

grails - 如何使用 spock 在 Grails 应用程序中测试具有真实事务的服务?

json - URL 编码参数中的 Bool 在 Swift3 中使用 Alamofire 编码为 0 和 1

python - 如何使用 Python 请求和 Clint 监控 HTTP PUT 上传的进度