How to use the six.PY3 function in six

To help you get started, we’ve selected a few six examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github freeipa / freeipa / ipatests / test_ipalib / test_parameters.py View on Github external
import pytest

import six
from cryptography import x509 as crypto_x509
from cryptography.hazmat.backends import default_backend

from ipatests.util import raises, ClassChecker, read_only
from ipatests.util import dummy_ugettext, assert_equal
from ipatests.data import binary_bytes, utf8_bytes, unicode_str
from ipalib import parameters, text, errors, config, x509
from ipalib.constants import TYPE_ERROR, CALLABLE_ERROR
from ipalib.errors import ValidationError, ConversionError
from ipalib import _
from ipapython.dn import DN

if six.PY3:
    unicode = str
    long = int

NULLS = (None, b'', u'', tuple(), [])

pytestmark = pytest.mark.tier0


class test_DefaultFrom(ClassChecker):
    """
    Test the `ipalib.parameters.DefaultFrom` class.
    """
    _cls = parameters.DefaultFrom

    def test_init(self):
        """
github anymail / django-anymail / tests / test_sendinblue_backend.py View on Github external
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage

import six
from django.core import mail
from django.test import SimpleTestCase, override_settings, tag
from django.utils.timezone import get_fixed_timezone, override as override_current_timezone

from anymail.exceptions import (AnymailAPIError, AnymailConfigurationError, AnymailSerializationError,
                                AnymailUnsupportedFeature)
from anymail.message import attach_inline_image_file
from .mock_requests_backend import RequestsBackendMockAPITestCase, SessionSharingTestCasesMixin
from .utils import sample_image_content, sample_image_path, SAMPLE_IMAGE_FILENAME, AnymailTestMixin

# noinspection PyUnresolvedReferences
longtype = int if six.PY3 else long  # NOQA: F821


@tag('sendinblue')
@override_settings(EMAIL_BACKEND='anymail.backends.sendinblue.EmailBackend',
                   ANYMAIL={'SENDINBLUE_API_KEY': 'test_api_key'})
class SendinBlueBackendMockAPITestCase(RequestsBackendMockAPITestCase):
    # SendinBlue v3 success responses are empty
    DEFAULT_RAW_RESPONSE = b'{"messageId":"<201801020304.1234567890@smtp-relay.mailin.fr>"}'
    DEFAULT_STATUS_CODE = 201  # SendinBlue v3 uses '201 Created' for success (in most cases)

    def setUp(self):
        super(SendinBlueBackendMockAPITestCase, self).setUp()
        # Simple message useful for many tests
        self.message = mail.EmailMultiAlternatives('Subject', 'Text Body', 'from@example.com', ['to@example.com'])
github felipecruz / coopy / tests / unit / test_journal.py View on Github external
def test_setup(self):
        journal = DiskJournal(JOURNAL_DIR, CURRENT_DIR)
        self.assertEquals(JOURNAL_DIR, journal.basedir)

        journal.setup()
        expected_file_name = '%s%s' % (JOURNAL_DIR,
                                      'transaction_000000000000002.log')
        self.assertEquals(expected_file_name,
                          journal.file.name)

        if six.PY3:
            import pickle
        else:
            import cPickle as pickle
        # test hack
        pickle_class = pickle.Pickler(open(expected_file_name, 'rb'))\
                                                            .__class__
        self.assertTrue(isinstance(journal.pickler, pickle_class))
github freeipa / freeipa / ipatests / test_ipalib / test_frontend.py View on Github external
"""

import pytest
import six

from ipatests.util import raises, read_only
from ipatests.util import ClassChecker, create_test_api
from ipatests.util import assert_equal
from ipalib.constants import TYPE_ERROR
from ipalib.base import NameSpace
from ipalib import frontend, backend, plugable, errors, parameters, config
from ipalib import output, messages
from ipalib.parameters import Str
from ipapython.version import API_VERSION

if six.PY3:
    unicode = str


pytestmark = pytest.mark.tier0


def test_RULE_FLAG():
    assert frontend.RULE_FLAG == 'validation_rule'


def test_rule():
    """
    Test the `ipalib.frontend.rule` function.
    """
    flag = frontend.RULE_FLAG
    rule = frontend.rule
github polyaxon / polyaxon / python / http_client / v1 / job / swagger_client / api_client.py View on Github external
NOTE: This class is auto generated by the swagger code generator program.
    Ref: https://github.com/swagger-api/swagger-codegen
    Do not edit the class manually.

    :param configuration: .Configuration object for this client
    :param header_name: a header to pass when making calls to the API.
    :param header_value: a header value to pass when making calls to
        the API.
    :param cookie: a cookie to include in the header when making calls
        to the API
    """

    PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
    NATIVE_TYPES_MAPPING = {
        'int': int,
        'long': int if six.PY3 else long,  # noqa: F821
        'float': float,
        'str': str,
        'bool': bool,
        'date': datetime.date,
        'datetime': datetime.datetime,
        'object': object,
    }

    def __init__(self, configuration=None, header_name=None, header_value=None,
                 cookie=None):
        if configuration is None:
            configuration = Configuration()
        self.configuration = configuration

        # Use the pool property to lazily initialize the ThreadPool.
        self._pool = None
github gusibi / dynamodb-py / dynamodb / helpers.py View on Github external
return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return b' '.join(force_bytes(arg, encoding,
                                             strings_only, errors)
                                 for arg in s)
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors)

if six.PY3:
    smart_str = smart_text
    force_str = force_text
else:
    smart_str = smart_bytes
    force_str = force_bytes
    # backwards compatibility for Python 2
    smart_unicode = smart_text
    force_unicode = force_text

smart_str.__doc__ = """
Apply smart_text in Python 3 and smart_bytes in Python 2.
This is suitable for writing to sys.stdout (for instance).
"""

force_str.__doc__ = """
Apply force_text in Python 3 and force_bytes in Python 2.
github crossbario / crossbar / crossbar / common / checkconfig.py View on Github external
from pprint import pformat

from pygments import highlight, lexers, formatters

from autobahn.websocket.util import parse_url

from autobahn.wamp.message import _URI_PAT_STRICT_NON_EMPTY
from autobahn.wamp.message import _URI_PAT_STRICT_LAST_EMPTY
from autobahn.wamp.uri import convert_starred_uri

from txaio import make_logger

from yaml import Loader, SafeLoader, Dumper, SafeDumper
from yaml.constructor import ConstructorError

if six.PY3:
    from collections.abc import Mapping, Sequence
else:
    from collections import Mapping, Sequence

__all__ = ('check_config',
           'check_config_file',
           'convert_config_file',
           'check_guest')


LATEST_CONFIG_VERSION = 2
"""
The current configuration file version.
"""

NODE_RUN_STANDALONE = u'runmode_standalone'
github Tejalsjsu / DeepGradientCompression / examples / BERT / tokenization.py View on Github external
def printable_text(text):
  """Returns text encoded in a way suitable for print or `tf.logging`."""

  # These functions want `str` for both Python2 and Python3, but in one case
  # it's a Unicode string and in the other it's a byte string.
  if six.PY3:
    if isinstance(text, str):
      return text
    elif isinstance(text, bytes):
      return text.decode("utf-8", "ignore")
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  elif six.PY2:
    if isinstance(text, str):
      return text
    elif isinstance(text, unicode):
      return text.encode("utf-8")
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  else:
    raise ValueError("Not running on Python2 or Python 3?")
github freeipa / freeipa / ipaserver / install / service.py View on Github external
from ipalib.install import certstore, sysrestore
from ipapython import ipautil
from ipapython.dn import DN
from ipapython import kerberos
from ipalib import api, errors, x509
from ipaplatform import services
from ipaplatform.paths import paths
from ipaserver.masters import (
    CONFIGURED_SERVICE, ENABLED_SERVICE, HIDDEN_SERVICE, SERVICE_LIST
)
from ipaserver.servroles import HIDDEN

logger = logging.getLogger(__name__)

if six.PY3:
    unicode = str


def print_msg(message, output_fd=sys.stdout):
    logger.debug("%s", message)
    output_fd.write(message)
    output_fd.write("\n")
    output_fd.flush()


def format_seconds(seconds):
    """Format a number of seconds as an English minutes+seconds message"""
    parts = []
    minutes, seconds = divmod(seconds, 60)
    if minutes:
        parts.append('%d minute' % minutes)
github ansible / ansible-runner / ansible_runner / utils.py View on Github external
"""
    Copied from six==1.12

    Coerce *s* to `str`.
    For Python 2:
      - `unicode` -> encoded to `str`
      - `str` -> `str`
    For Python 3:
      - `str` -> `str`
      - `bytes` -> decoded to `str`
    """
    if not isinstance(s, (text_type, binary_type)):
        raise TypeError("not expecting type '%s'" % type(s))
    if PY2 and isinstance(s, text_type):
        s = s.encode(encoding, errors)
    elif PY3 and isinstance(s, binary_type):
        s = s.decode(encoding, errors)
    return s