gpt4 book ai didi

python - 如何在请求上下文之外工作时模拟 Flask.g 和 Flask-RESTful.request

转载 作者:行者123 更新时间:2023-12-03 08:17:33 25 4
gpt4 key购买 nike

我正在为一个模块编写单元测试,该模块用作多个 Flask 项目的 git 子模块。我有一个使用 Flask-RESTful.request 的方法,假设它作为事件 http 请求的一部分被调用。

core.helpers.auth.py:

from flask import g
from flask_restful import request

class Auth():

@staticmethod
def authenticate(f):
def decorated(*args, **kwargs):
internalByPass = request.headers.get("by-pass")
shouldByPass = False
if internalByPass == "internal-bypass-key":
shouldByPass = True

if shouldByPass:
g.user = "by_pass"
return f(*args, **kwargs)

return decorated

我想在测试 Auth.authenticate 方法时模拟 Flask-RESTful.requestflask.g 。这是我尝试过的 -

core.tests.test_helpers.test_auth.py

import pytest
from core.helpers import auth

def test_authenticate(mocker):
mock_flask_request_obj = mocker.patch("core.helpers.auth.request")
mock_flask_request_obj.headers.get.return_value = "internal-bypass-key"

mock_flask_g_obj = mocker.patch("core.helpers.auth.g")

@auth.Auth.authenticate
def test_func(*args, **kwargs):
return "hello"

assert test_func() == "hello"
assert mock_flask_g_obj.user == "by_pass"
assert mock_flask_request_obj.headers.get.assert_called_once_with("by-pass")

我收到以下错误 screenshot of my terminal

(env_core_helpers_tests) ➜  core_dome coverage run --source=./core -m pytest -v
Coverage.py warning: --include is ignored because --source is set (include-ignored)
=========================================================================================== test session starts ============================================================================================
platform darwin -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /Users/rajesh_lt/workspace/core_dome/env_core_helpers_tests/bin/python3.9
cachedir: .pytest_cache
rootdir: /Users/rajesh_lt/workspace/core_dome
plugins: mock-3.6.1
collected 1 item

core/tests/test_helpers/test_auth.py::test_authenticate FAILED [100%]

================================================================================================= FAILURES =================================================================================================
____________________________________________________________________________________________ test_authenticate _____________________________________________________________________________________________

mocker = <pytest_mock.plugin.MockerFixture object at 0x108d99160>

def test_authenticate(mocker):
> mock_flask_request_obj = mocker.patch.object(auth.request, mock.MagicMock())

core/tests/test_helpers/test_auth.py:28:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
env_core_helpers_tests/lib/python3.9/site-packages/pytest_mock/plugin.py:219: in object
return self._start_patch(
env_core_helpers_tests/lib/python3.9/site-packages/pytest_mock/plugin.py:183: in _start_patch
mocked = p.start() # type: unittest.mock.MagicMock
/usr/local/Cellar/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8efef7fae6e1e0cebda0b7" rel="noreferrer noopener nofollow">[email protected]</a>/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py:1541: in start
result = self.__enter__()
/usr/local/Cellar/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f888818c909796b8cbd6c1" rel="noreferrer noopener nofollow">[email protected]</a>/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py:1405: in __enter__
original, local = self.get_original()
/usr/local/Cellar/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b6bfb2aea9a886f5e8ff" rel="noreferrer noopener nofollow">[email protected]</a>/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py:1368: in get_original
original = target.__dict__[name]
env_core_helpers_tests/lib/python3.9/site-packages/werkzeug/local.py:422: in __get__
obj = instance._get_current_object()
env_core_helpers_tests/lib/python3.9/site-packages/werkzeug/local.py:544: in _get_current_object
return self.__local() # type: ignore
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

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.

env_core_helpers_tests/lib/python3.9/site-packages/flask/globals.py:33: RuntimeError
========================================================================================= short test summary info ==========================================================================================
FAILED core/tests/test_helpers/test_auth.py::test_authenticate - RuntimeError: Working outside of request context.
============================================================================================ 1 failed in 1.62s =============================================================================================

有没有办法在请求上下文之外模拟 Flask-RESTful.requestflask.g,如果没有,为此编写单元测试的正确方法是什么方法?

最佳答案

我能够使用 Testing code that requires a Flask app or request context 找到解决方案.

core.tests.test_helpers.test_auth.py中更新的代码是:

def test_authenticate():
with flask.Flask(__name__).test_request_context() as flask_context:
flask_context.request.headers = {"by-pass": "internal-bypass-key"}

@auth.Auth.authenticate
def test_func(*args, **kwargs):
return "hello"

assert test_func(2, 3, 4, multiplier=2) == "hello"
assert flask_context.g.user == "by_pass"

关于python - 如何在请求上下文之外工作时模拟 Flask.g 和 Flask-RESTful.request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68904997/

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