def test_accounts_search_permission(app, test_users, test_community,
                                    login_user):
    """Test permission of listing user accounts."""
    def account_search(user, expected_code):
        headers = [('Content-Type', 'application/json'),
                   ('Accept', 'application/json')]
        with app.app_context():
            url = url_for('invenio_accounts_rest.users_list')
            if user:
                scopes = current_oauth2server.scope_choices()
                allowed_token = Token.create_personal(
                    'allowed_token', user.id,
                    scopes=[s[0] for s in scopes]
                )
                # application authentication token header
                headers.append(('Authorization',
                                'Bearer {}'.format(allowed_token.access_token)))

        with app.test_client() as client:
            if user is not None:
                login_user(user, client)
            res = client.get(url, headers=headers)
            assert res.status_code == expected_code

    # anonymous users can't list accounts
    account_search(None, 401)
    # authenticated users can't list other users' account
    account_search(test_users['normal'], 403)
    # community members cannot list all users' accounts
    account_search(test_community.member, 403)
    # community admins can list all users
    account_search(test_community.admin, 200)
    # admin is allowed to list all accounts
    account_search(test_users['admin'], 200)