gpt4 book ai didi

python - flask.request mocker.patch.object 不生效

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:35 25 4
gpt4 key购买 nike

在我的 Controller 中我得到了这个端点:

@bp_crawler.route('/insert', methods=['POST'])
def insert_data():
req = requests.CrawledSocialDataRequest.from_json(json.loads(request.data))

然后,我尝试使用 pytestpytest-mock 测试 mocker fixture。

我继续模拟 request 对象,以便 request.data 返回一些对我的单元测试有用的值。

# arrange
data_to_insert = requests.CrawledSocialDataRequest([
requests.CrawledSocialDataRecord('cid0', 'content0', 123.4, ['tag0', 'tag1']),
requests.CrawledSocialDataRecord('cid1', 'content1', 123.4, ['tag1', 'tag2'])
])
request_mock = mocker.patch.object(flask, 'request')
request_mock.data = data_to_insert.serialize()

db_mock = request_mock = mocker.patch.object(api, 'db')

# act
result = controller.insert_data()

一切正常,除非调用了 insert_data()

我得到以下异常:

    controllers/v1/tests/test_crawler.py:30: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

controllers/v1/crawler.py:36: in insert_data
req = requests.CrawledSocialDataRequest.from_json(json.loads(request.data))
/usr/local/lib/python3.7/site-packages/werkzeug/local.py:347: in __getattr__
return getattr(self._get_current_object(), name)
/usr/local/lib/python3.7/site-packages/werkzeug/local.py:306: in _get_current_object
return self.__local()


name = 'request'

def _lookup_req_object(name):
top = _request_ctx_stack.top
if top is None:
> raise RuntimeError(_request_ctx_err_msg)
E RuntimeError: Working outside of request context.
E
E This typically means that you attempted to use functionality that needed
E an active HTTP request. Consult the documentation on testing for
E information about how to avoid this problem.

模拟没有发生,因此 request.data 将控制路由到 flask.globals,使我的单元测试失败。

Github 链接:

最佳答案

事实证明,如果在 _test.py 上你这样做:

import flask
...
request_mock = mocker.patch.object(flask, 'request')

但是在你的 Controller /端点上,你可以

from flask import request
...
x = request.data # this will break

因此,您必须执行 import flask -> x = flask.request.data 才能正常工作,或者更改模拟技术。

关于python - flask.request mocker.patch.object 不生效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957456/

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