from unittest.mock import patch


def cls_attr_mock(request, cls, attr_name, name=None, **kwargs):
    """
    Return a mock for attribute *attr_name* on *cls* where the patch is
    reversed after pytest uses it.
    """
    name = request.fixturename if name is None else name
    _patch = patch.object(cls, attr_name, name=name, **kwargs)
    request.addfinalizer(_patch.stop)
    return _patch.start()