title: How to mock flask.g and Flask-RESTful.request while working outside request context
body: <p>I am writing unit-tests for a module that is used as a git-submodule for multiple flask projects. I have a method that uses <strong>Flask-RESTful.request</strong> assuming it is being called as a part of an active http request.</p>
  <p><em>core.helpers.auth.py</em></p>
  <pre><code>from flask import g
  from flask_restful import request
  
  class Auth():
  
      @staticmethod
      def authenticate(f):
          def decorated(*args, **kwargs):
              internalByPass = request.headers.get(&quot;by-pass&quot;)
              shouldByPass = False
              if internalByPass == &quot;internal-bypass-key&quot;:
                  shouldByPass = True
  
              if shouldByPass:
                  g.user = &quot;by_pass&quot;
                  return f(*args, **kwargs)
  
          return decorated
  </code></pre>
  <p>I want to mock <strong>Flask-RESTful.request</strong> and <strong>flask.g</strong> while testing the Auth.authenticate method.
  Here is what I have tried -</p>
  <p><em>core.tests.test_helpers.test_auth.py</em></p>
  <pre><code>import pytest
  from core.helpers import auth
  
  def test_authenticate(mocker):
      mock_flask_request_obj = mocker.patch(&quot;core.helpers.auth.request&quot;)
      mock_flask_request_obj.headers.get.return_value = &quot;internal-bypass-key&quot;
  
      mock_flask_g_obj = mocker.patch(&quot;core.helpers.auth.g&quot;)
      
      @auth.Auth.authenticate
      def test_func(*args, **kwargs):
          return &quot;hello&quot;
  
      assert test_func() == &quot;hello&quot;
      assert mock_flask_g_obj.user == &quot;by_pass&quot;
      assert mock_flask_request_obj.headers.get.assert_called_once_with(&quot;by-pass&quot;)
  </code></pre>
  <p>I am getting the following error <a href="https://i.stack.imgur.com/hQFB1.png" rel="nofollow noreferrer">screenshot of my terminal</a></p>
  <pre><code>(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 = &lt;pytest_mock.plugin.MockerFixture object at 0x108d99160&gt;
  
      def test_authenticate(mocker):
  &gt;       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/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py:1541: in start
      result = self.__enter__()
  /usr/local/Cellar/python@3.9/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/python@3.9/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:
  &gt;           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 =============================================================================================
  </code></pre>
  <p>Is there a way to mock <strong>Flask-RESTful.request</strong> and <strong>flask.g</strong> outside a request context, if not what is the proper way to write a unittest for this method?</p>