【问题标题】:Mock or avoid cognito authentication and group permissions for pytest模拟或避免 pytest 的 cognito 身份验证和组权限
【发布时间】:2021-10-04 09:00:08
【问题描述】:

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

以下示例如何实现 pytest?

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

【问题讨论】:

    标签: python flask pytest amazon-cognito pytest-mock


    【解决方案1】:

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

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

    src/controllers/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 执行类似操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 2017-06-28
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2012-12-02
      • 2022-06-10
      相关资源
      最近更新 更多