Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

python - How to mock an mutation argument in Django?

I have a mutation that has a decorator that checks the permissions (scopes) from the user token before s/he goes inside it. The decorator gets the input parameter from the mutate method and extracts the token and verify if the user has one of the allowed scopes.

The unit tests don't succeed if I don't remove or mock the requires_scope part from the code. The problem is that I don't know exactly what I have to mock to succeed in the unit tests. Should I mock the input itself? The token? The return of the requires_scopes decorator?

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

decorators.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
question from:https://stackoverflow.com/questions/65906309/how-to-mock-an-mutation-argument-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I mocked the get_access_token_from_header function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...