def test_account_activation_permission(app, test_users, test_community,
                                       login_user):
    """Test deactivating a user account."""
    counter = [0]
    def account_update(user, expected_code, modified_user=None):
        def account_update_sub(patch_content, content_type):
            with app.app_context():
                if modified_user is None:
                    test_user = create_user(
                        'test_user{}'.format(counter[0]))
                else:
                    test_user = modified_user
                counter[0] += 1
                url = url_for(
                    'invenio_accounts_rest.user',
                    user_id=test_user.id,
                )
                db.session.commit()

            headers = [('Content-Type', content_type),
                        ('Accept', 'application/json')]

            with app.test_client() as client:
                if user is not None:
                    login_user(user, client)
                res = client.patch(url, headers=headers,
                                    data=json.dumps(patch_content))
                assert res.status_code == expected_code
        # test with a simple JSON
        account_update_sub({'active': False}, 'application/json')
        # test with a JSON patch
        account_update_sub([{
            'op': 'replace', 'path': '/active','value': False
        }], 'application/json-patch+json')

    # anonymous users can't activate/deactivate accounts
    account_update(None, 401)
    # authenticated users can't activate/deactivate other users' account
    account_update(test_users['normal'], 403)
    # users can't deactivate their own accounts
    account_update(test_users['normal'], 403, test_users['normal'])
    # admin is allowed to activate/deactivate accounts
    account_update(test_users['admin'], 200)