在Django中测试put方法

发布于 2024-12-15 05:57:37 字数 644 浏览 3 评论 0原文

我正在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帝王念 2024-12-22 05:57:37

因此,实际执行此操作的方法是使用 raw_post_data 函数。这是一种耻辱,因为据我所知,这破坏了 REST 模型。但是,嘿,它有效。

我基本上将:更改

payload = request.readlines()

为: 。

   payload = request.raw_post_data

在我看来,

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:

payload = request.readlines()

to:

   payload = request.raw_post_data

in my view.

猥琐帝 2024-12-22 05:57:37

我会警告不要因为这样的测试错误而破解您的生产代码。这几乎总是意味着你做错了什么,你应该改正。就我而言,此错误的原因是使用请求对象初始化表单,而不是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文