【问题标题】:How to mock an mutation argument in Django?如何在 Django 中模拟突变参数?
【发布时间】:2021-01-26 17:35:55
【问题描述】:

我有一个突变,它有一个装饰器,在他/她进入之前检查用户令牌的权限(范围)。装饰器从 mutate 方法获取输入参数并提取令牌并验证用户是否具有允许的范围之一。

如果我不从代码中删除或模拟 requires_scope 部分,则单元测试不会成功。问题是我不知道我必须模拟什么才能在单元测试中取得成功。我应该模拟输入本身吗?令牌? requires_scopes 装饰器的返回?

mutations.py

class MyMutation(graphene.Mutation):
    success = graphene.Boolean()

    class Arguments:
        input = graphene.Argument(IdInput, required=True)

    @classmethod
    @requires_scopes(['app:first_test_permission', 'app:second_test_permission'])
    def mutate(cls, root, info, input):
        pass

装饰器.py

def get_access_token_from_header(request):
    """
    Obtains the Access Token from the Authorization Header
    """
    header = request.context.META.get('HTTP_AUTHORIZATION', None)
    header = header.split()
    token = header[1]

    return token


def requires_scopes(scopes: list):
    """
    Determines if the required scope is present in the Access Token
    Args:
        scopes (list): The scopes required to access the resource
    """

    def require_scopes(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            token = get_access_token_from_header(args[2])
            decoded = jwt.decode(token, verify=False)

            if decoded.get("scope"):
                token_scopes = set(decoded["scope"].split())
                required_scopes = set(scopes)
                if required_scopes.intersection(token_scopes):
                    return f(*args, **kwargs)

            raise Exception({'message': 'You don\'t have access to this resource'})

        return decorated

    return require_scopes

【问题讨论】:

    标签: python django unit-testing graphene-python


    【解决方案1】:

    我嘲笑了get_access_token_from_header 函数:

    MY_TOKEN = 'mytoken'
    
    @patch('app.decorators.get_access_token_from_header', return_value=MY_TOKEN)
    def test_my_mutation_successfully(self, get_access_token_from_header_mocker):
        pass
    

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 2014-07-14
      • 2011-02-05
      • 1970-01-01
      • 2020-07-15
      • 2019-11-10
      • 2018-10-01
      • 2021-11-27
      • 1970-01-01
      相关资源
      最近更新 更多