def safe_encode(text, incoming=None,
                encoding='utf-8', errors='strict'):
    if not isinstance(text, six.string_types):
        raise TypeError("%s can't be encoded" % type(text))

    if not incoming:
        incoming = (sys.stdin.encoding or
                    sys.getdefaultencoding())

    if isinstance(text, six.text_type):
        if six.PY3:
            return text.encode(encoding, errors).decode(incoming)
        else:
            return text.encode(encoding, errors)
    elif text and encoding != incoming:
        # Decode text before encoding it with `encoding`
        text = safe_decode(text, incoming, errors)
        if six.PY3:
            return text.encode(encoding, errors).decode(incoming)
        else:
            return text.encode(encoding, errors)

    return text
Called by the ServiceTester in order to test login/facebook, link/facebook, and
dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/strutils.py/safe_encode--crossover with--dataset/ETHPy150Open viewfinderco/viewfinder/backend/www/test/auth_facebook_test.py/_TestAuthFacebookUser