在Django中测试put方法
我正在我的 Django 应用程序中测试 PUT 方法。但是,当我调用:
payload = '{server_lib_song_id : -1, host_lib_song_id : ' + str(lib_id) + \
', song : "' + song + '", artist : "' + artist + '" , album : "' + \
album +'"}'
response = client.put('/udj/users/' + user_id + '/library/song', \
data=payload, content_type='text/json', \
**{'udj_ticket_hash' : ticket_hash})
在我的测试中,我在视图中收到以下错误:
AttributeError: 'FakePayload' object has no attribute 'readline'
引发此错误的行是:
payload = request.readlines()
那么如何确保我通过 put 请求发送的实际有效负载(不是 FakePayload 对象)是什么获取我认为在我看来要测试的代码?
I'm testing a PUT method in my Django app. However, when I call:
payload = '{server_lib_song_id : -1, host_lib_song_id : ' + str(lib_id) + \
', song : "' + song + '", artist : "' + artist + '" , album : "' + \
album +'"}'
response = client.put('/udj/users/' + user_id + '/library/song', \
data=payload, content_type='text/json', \
**{'udj_ticket_hash' : ticket_hash})
in my test I get the following error in my view:
AttributeError: 'FakePayload' object has no attribute 'readline'
The line which is throwing this error is:
payload = request.readlines()
So how to I ensure that the actual payload I sent with my put request (not a FakePayload object) is what gets to the code I'm trying to test in my view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,实际执行此操作的方法是使用
raw_post_data
函数。这是一种耻辱,因为据我所知,这破坏了 REST 模型。但是,嘿,它有效。我基本上将:更改
为: 。
在我看来,
So the way to actually go about this is to use the
raw_post_data
function. This is a shame because as far as I can tell, this breaks the REST model. But hey, it works.I essentially changed:
to:
in my view.
我会警告不要因为这样的测试错误而破解您的生产代码。这几乎总是意味着你做错了什么,你应该改正。就我而言,此错误的原因是使用请求对象初始化表单,而不是 request.POST 或 request.GET。如果您仍然遇到此错误(希望不会...),请重新检查您的表单初始化或将其发布到此处。
I would caution against hacking your production code for a test error like this. It almost always means that you are doing something wrong, which you should fix. In my case, the cause of this bug was initializing a form with the request object, not request.POST or request.GET. If you are still experiencing this bug (let's hope not...), re-examine your form initialization or post it here.