简体   繁体   中英

How to unit test that a function has been decorated?

I have a view that is decorated like this:

@check_has_permission('is_manager')
def view():
   pass

and the decorator looks something like this:

def check_has_permission(group=None):
    def can_user_access(user):
        if user.is_authenticated():
            if group == 'is_staff':
                return user.is_staff()
            elif group == 'is_admin':
                return (
                    user.is_admin() or
                    user.is_staff()
                )
            elif group == 'is_manager':
                return (
                    user.is_manager() or
                    user.is_admin() or
                    user.is_staff()
                )
        return False
    return user_passes_test(can_user_access, login_url=login_url)

How do I write a unit test to confirm the view is decorated with check_has_permission with a group of 'is_manager'?

I'm hoping I can write a set of tests for the decorator itself, then I only have to confirm I'm calling the right group for each view it decorates.

You need to add a seam where you can test.

If your decorator looks like this:

def is_user_in_group(group):
    if user.is_authenticated():
        # ... snip - checks on groups and user ...

    return False


def check_has_permission(group=None):
    def can_user_access(user):
        return is_user_in_group(user, group)
    return user_passes_test(can_user_access, login_url=login_url)

Then your test can mock both is_user_in_group and user_passes_test , call the decorated function, test that is_user_in_group gets called with the correct group, and test that user_passes_test gets called with the return value from your mock of is_user_in_group .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM