gpt4 book ai didi

python - Django Rest Framework 的测试请求无法由其自己的 Request 类解析

转载 作者:行者123 更新时间:2023-12-01 03:39:57 28 4
gpt4 key购买 nike

我正在编写一个端点来接收和解析 GitHub Webhook payloads使用 Django Rest Framework 3。为了匹配有效负载规范,我正在编写一个有效负载请求工厂并测试它是否生成有效请求。

但是,当尝试测试使用 DRF 的 Request 类生成的请求时,问题就出现了。这是我能想到的最小的失败测试 - 问题是使用 DRF 的 APIRequestFactory 生成的请求似乎无法由 DRF 的 Request 类解析。这是预期的行为吗?

from rest_framework.request import Request
from rest_framework.parsers import JSONParser
from rest_framework.test import APIRequestFactory, APITestCase


class TestRoundtrip(APITestCase):

def test_round_trip(self):
"""
A DRF Request can be loaded into a DRF Request object
"""
request_factory = APIRequestFactory()
request = request_factory.post(
'/',
data={'hello': 'world'},
format='json',
)

result = Request(request, parsers=(JSONParser,))

self.assertEqual(result.data['hello'], 'world')

堆栈跟踪是:

E
======================================================================
ERROR: A DRF Request can be loaded into a DRF Request object
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 380, in __getattribute__
return getattr(self._request, attr)
AttributeError: 'WSGIRequest' object has no attribute 'data'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/james/active/prlint/prlint/github/tests/test_payload_factories/test_roundtrip.py", line 22, in test_round_trip
self.assertEqual(result.data['hello'], 'world')
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 382, in __getattribute__
six.reraise(info[0], info[1], info[2].tb_next)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 186, in data
self._load_data_and_files()
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 246, in _load_data_and_files
self._data, self._files = self._parse()
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/request.py", line 312, in _parse
parsed = parser.parse(stream, media_type, self.parser_context)
File "/home/james/active/prlint/venv/lib/python3.4/site-packages/rest_framework/parsers.py", line 64, in parse
data = stream.read().decode(encoding)
AttributeError: 'str' object has no attribute 'read'

----------------------------------------------------------------------

我显然做了一些愚蠢的事情 - 我搞乱了编码...意识到我需要将解析器列表传递给 Request 以避免 UnsupportedMediaType > 错误,现在我被困在这里了。

我应该做一些不同的事情吗?也许避免使用 APIRequestFactory?或者以不同的方式测试我构建的 GitHub 请求?

<小时/>

更多信息

GitHub 向已注册的具有 X-GitHub-Event header 的 Webhook 发送请求,因此为了测试我的 Webhook DRF 代码,我需要能够在测试时模拟此 header 。

我的成功之路是构建一个自定义请求并使用工厂将有效负载加载到其中。这是我的工厂代码:

def PayloadRequestFactory():
"""
Build a Request, configure it to look like a webhook payload from GitHub.
"""
request_factory = APIRequestFactory()
request = request_factory.post(url, data=PingPayloadFactory())
request.META['HTTP_X_GITHUB_EVENT'] = 'ping'
return request

出现这个问题是因为我想断言 PayloadRequestFactory 正在为各种传递的参数生成有效的请求 - 所以我试图解析它们并断言它们的有效性,但 DRF 的 Request 类似乎无法实现这一点 - 因此我的问题是测试失败。

所以我的问题是 - 我应该如何测试这个 PayloadRequestFactory 是否生成我需要的请求类型?

最佳答案

“哟天哪,我听说你喜欢请求,因为你将请求放在请求中”XD

我会这样做:

from rest_framework.test import APIClient

client = APIClient()
response = client.post('/', {'github': 'payload'}, format='json')
self.assertEqual(response.data, {'github': 'payload'})
# ...or assert something was called, etc.

希望这有帮助

关于python - Django Rest Framework 的测试请求无法由其自己的 Request 类解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757530/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com