def test_ensure_group():
    """
    Test group creation & removal
    """
    # Use a prefix to make sure we never start with a number
    groupname = 'g' + str(uuid.uuid4())[:8]

    # Validate that no group exists
    with pytest.raises(KeyError):
        grp.getgrnam(groupname)

    try:
        # Create group
        user.ensure_group(groupname)
        # This raises if group doesn't exist
        grp.getgrnam(groupname)

        # Do it again, this should be a noop
        user.ensure_group(groupname)
        grp.getgrnam(groupname)
    finally:
        # Remove the group
        user.remove_group(groupname)
        with pytest.raises(KeyError):
            grp.getgrnam(groupname)
def test_group_membership():
    """
    Test group memberships can be added / removed
    """
    username = '******' + str(uuid.uuid4())[:8]
    groupname = 'g' + str(uuid.uuid4())[:8]

    # Validate that no group exists
    with pytest.raises(KeyError):
        grp.getgrnam(groupname)
    with pytest.raises(KeyError):
        pwd.getpwnam(username)

    try:
        user.ensure_group(groupname)
        user.ensure_user(username)

        user.ensure_user_group(username, groupname)

        assert username in grp.getgrnam(groupname).gr_mem

        # Do it again, this should be a noop
        user.ensure_user_group(username, groupname)

        assert username in grp.getgrnam(groupname).gr_mem

        # Remove it
        user.remove_user_group(username, groupname)
        assert username not in grp.getgrnam(groupname).gr_mem

        # Do it again, this should be a noop
        user.remove_user_group(username, groupname)
        assert username not in grp.getgrnam(groupname).gr_mem
    finally:
        # Remove the group
        user.remove_user(username)
        user.remove_group(groupname)

        with pytest.raises(KeyError):
            grp.getgrnam(groupname)
        with pytest.raises(KeyError):
            pwd.getpwnam(username)