I develop unit tests for the backend of a large flask app. I am testing whether the helper function get_post_args() is handling empty requests correctly:
from flask import requestfrom unittest.mock import patchfrom errors import NoPostArgumentsdef get_post_args() -> Dict[str, Any]: args = request.get_json() if not isinstance(args, dict): raise NoPostArguments("no arguments given for this POST request; request not served" ) return argsdef test_get_post_args_returns_none(): with patch("request.get_json", return_value=None, ): with unittest.TestCase().assertRaises(NoPostArguments): get_post_args()When I run this with pytest, I get the error:
test_get_post_args_returns_none failed: def test_get_post_args_returns_none():> with patch("flask.request.get_json", return_value=None, ):tests\unit_tests\test_arg_validation.py:243: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _..\..\..\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py:1438: in __enter__ original, local = self.get_original()..\..\..\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py:1401: in get_original original = target.__dict__[name]venv02\lib\site-packages\werkzeug\local.py:311: in __get__ obj = instance._get_current_object()_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def _get_current_object() -> T: try: obj = local.get() except LookupError:> raise RuntimeError(unbound_message) from NoneE RuntimeError: Working outside of request context.E E This typically means that you attempted to use functionality that neededE an active HTTP request. Consult the documentation on testing forE information about how to avoid this problem.venv02\lib\site-packages\werkzeug\local.py:508: RuntimeErrorAny ideas on how to correctly mock request.get_json()?