2

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 Flask-RESTful.request assuming it is being called as a part of an active http request.

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

I want to mock Flask-RESTful.request and flask.g while testing the Auth.authenticate method. Here is what I have tried -

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")

I am getting the following error 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/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:
>           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 =============================================================================================

Is there a way to mock Flask-RESTful.request and flask.g outside a request context, if not what is the proper way to write a unittest for this method?

vvvvv
  • 25,404
  • 19
  • 49
  • 81

1 Answers1

5

I was able to find a solution using Testing code that requires a Flask app or request context.

The updated code in core.tests.test_helpers.test_auth.py is:

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"
vvvvv
  • 25,404
  • 19
  • 49
  • 81