1

我有一个烧瓶应用程序,我正在尝试为我构建的服务实现 pytest。所有路由都需要 cognito 身份验证或 cognito 组权限。有没有办法可以模拟或避免认知?从我在网上阅读的所有文章中,到目前为止没有任何帮助。

下面的示例将如何实现 pytest?

@app.route('/hello')
@cognito_auth_required
@cognito_group_permissions(["test"])
def hello():
    return 'Hello, World'
4

1 回答 1

0

我在努力做同样的事情时发现了这个问题。我试图修补那些被证明是徒劳的装饰器,直到我做了更多的挖掘。事实证明,由于涉及装饰器的语法糖是在运行时处理的,因此您需要使用绕过函数修补库函数,然后重新加载被测库以使其工作。

我使用的是 unittest 而不是 pytest。但是这个例子,它返回一个包含登录用户子的字典(我们也会模拟这个)应该可以工作:

src/控制器/some_module.py:

@cognito_auth_required
def my_example_function() -> dict:
    return {'your_sub' : current_cognito_jwt['sub']}

src/test/some_test.py

def mock_cognito_auth_required(fn):
    """
    This is a dummy wrapper of @cognito auth required, it passes-through 
    to the
    wrapped fuction without performing any cognito logic.

    """
    @wraps(fn)
    def decorator(*args, **kwargs):
        return fn(*args, **kwargs)
    return decorator

def setUpModule():
    """
    Patches out the decorator (in the library) and reloads the module
    under test.
    """
    patch('flask_cognito.cognito_auth_required', mock_cognito_auth_required).start()
    reload(some_module)

@patch('src.controllers.some_module.current_cognito_jwt')
class TestSomeModule(unittest.TestCase):
    def test_my_example_function(self, mock_current_cognito_jwt):
        mock_current_cognito_jwt.__getitem__.return_value = 'test'
        response = some_module.my_example_function()
        self.assertEqual(response, {'your_sub': 'test'})

您应该能够为 cognito_group_permissions 做类似的事情。

于 2021-10-01T09:14:45.140 回答