Create temporary unix socket.

    Creates and binds a temporary unix socket that will be closed and removed
    on exit.

    :param sock: If not `None`, will not created a new unix socket, but bind
                 the passed in one instead.
    :param socket_name: The name for the socket file (will be placed in a
                        temporary directory). Do not pass in an absolute path!
    :param close: If `False`, does not close the socket before removing the
                  temporary directory.
    :return: A tuple of `(socket, addr)`, where `addr` is the location of the
             bound socket on the filesystem.

def unix_socket(sock=None, socket_name='tmp.socket', close=True):
    """Create temporary unix socket.

    Creates and binds a temporary unix socket that will be closed and removed
    on exit.

    :param sock: If not `None`, will not created a new unix socket, but bind
                 the passed in one instead.
    :param socket_name: The name for the socket file (will be placed in a
                        temporary directory). Do not pass in an absolute path!
    :param close: If `False`, does not close the socket before removing the
                  temporary directory.
    :return: A tuple of `(socket, addr)`, where `addr` is the location of the
             bound socket on the filesystem.
    """
    sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

    with dir() as dtmp:
        addr = os.path.join(dtmp, socket_name)
        sock.bind(addr)

        try:
            yield sock, addr
        finally:
            if close:
                sock.close()