Beispiel #1
0
 def test_rejects_non_string(self):
   self.assertFalse(builtins.is_bytes_or_unicode(False))
   self.assertFalse(builtins.is_bytes_or_unicode(5))
   self.assertFalse(builtins.is_bytes_or_unicode(None))
   self.assertFalse(builtins.is_bytes_or_unicode([]))
   self.assertFalse(builtins.is_bytes_or_unicode(()))
   self.assertFalse(builtins.is_bytes_or_unicode({}))
   self.assertFalse(builtins.is_bytes_or_unicode(object))
Beispiel #2
0
 def test_rejects_non_string(self):
   self.assertFalse(is_bytes_or_unicode(False))
   self.assertFalse(is_bytes_or_unicode(5))
   self.assertFalse(is_bytes_or_unicode(None))
   self.assertFalse(is_bytes_or_unicode([]))
   self.assertFalse(is_bytes_or_unicode(()))
   self.assertFalse(is_bytes_or_unicode({}))
   self.assertFalse(is_bytes_or_unicode(object))
Beispiel #3
0
def chunks(iterable, size, *args, **kwargs):
  """
  Splits an iterable into materialized chunks each of specified size.

  :param iterable:
      The iterable to split. Must be an ordered sequence to guarantee order.
  :param size:
      Chunk size.
  :param padding:
      This must be an iterable or None. So if you want a ``True`` filler,
      use [True] or (True, ) depending on whether the iterable is a list or
      a tuple. Essentially, it must be the same type as the iterable.

      If a pad value is specified appropriate multiples of it will be
      concatenated at the end of the iterable if the size is not an integral
      multiple of the length of the iterable:

          tuple(chunks("aaabccd", 3, "-"))
          -> ("aaa", "bcc", "d--")

          tuple(chunks((1, 1, 1, 2, 2), 3, (None,)))
          -> ((1, 1, 1, ), (2, 2, None))

      If no padding is specified, nothing will be appended if the chunk
      size is not an integral multiple of the length of the iterable. That is,
      the last chunk will have chunk size less than the specified chunk size.
  :yields:
      Generator of materialized chunks.
  """
  length = len(iterable)
  if args or kwargs:
    padding = kwargs["padding"] if kwargs else args[0]
    if padding is None:
      if is_bytes_or_unicode(iterable):
        padding = ""
      elif isinstance(iterable, tuple):
        padding = (padding,)
      else:
        iterable = list(iterable)
        padding = [padding]
    sequence = iterable + (padding * (size - (length % size)))
    for i in range(0, length, size):
      yield sequence[i:i + size]
  else:
    for i in range(0, length, size):
      yield iterable[i:i + size]
Beispiel #4
0
def urlencode_sl(query_params, predicate=None):
    """
    Serializes a dictionary of query parameters into a list of query
    parameters, ``(name, value)`` pairs, sorted first by ``name`` then by
    ``value`` based on the OAuth percent-encoding rules and specification.

    Behaves like :func:`urllib.urlencode` with ``doseq=1``.

    :param query_params:
        Dictionary of query parameters.
    :param predicate:
        A callback that will be called for each query parameter and should
        return ``False`` or a falsy value if that parameter should not be
        included. By default, all query parameters are included. The function
        takes the following method signature::

            def predicate(name, value):
                return is_name_allowed(name) and is_value_allowed(value)
    :returns:
        A list of query parameters, ``(name, value)`` pairs, sorted first by
        ``name`` and then by ``value`` based on the OAuth percent-encoding rules
        and specification.
    """
    query_params = query_params or {}
    encoded_pairs = []
    for k, value in query_params.items():
        # Keys are also percent-encoded according to OAuth spec.
        key = percent_encode(k)
        if predicate and not predicate(k, value):
            continue
        elif is_bytes_or_unicode(value):
            encoded_pairs.append((key, percent_encode(value),))
        elif is_sequence(value):
            # Loop over the sequence.
            if len(value) > 0:
                for i in value:
                    encoded_pairs.append((key, percent_encode(i), ))
            # ``urllib.urlencode()`` doesn't preserve blank lists.
            # Therefore, we're discarding them.
            #else:
            #    # Preserve blank list values.
            #    encoded_pairs.append((k, "", ))
        else:
            encoded_pairs.append((key, percent_encode(value),))
    # Sort after encoding according to the OAuth spec.
    return sorted(encoded_pairs)
Beispiel #5
0
def chunks(iterable, size, *args, **kwargs):
    """Splits an iterable into materialized chunks each of specified size.

  :param iterable:
      The iterable to split. Must be an ordered sequence to guarantee order.
  :param size:
      Chunk size.
  :param padding:
      This must be an iterable or None. So if you want a ``True`` filler,
      use [True] or (True, ) depending on whether the iterable is a list or
      a tuple. Essentially, it must be the same type as the iterable.

      If a pad value is specified appropriate multiples of it will be
      concatenated at the end of the iterable if the size is not an integral
      multiple of the length of the iterable:

          tuple(chunks("aaabccd", 3, "-"))
          -> ("aaa", "bcc", "d--")

          tuple(chunks((1, 1, 1, 2, 2), 3, (None,)))
          -> ((1, 1, 1, ), (2, 2, None))

      If no padding is specified, nothing will be appended if the
      chunk size is not an integral multiple of the length of the
      iterable. That is, the last chunk will have chunk size less than
      the specified chunk size. :yields: Generator of materialized
      chunks.
  """
    length = len(iterable)
    if args or kwargs:
        padding = kwargs["padding"] if kwargs else args[0]
        if padding is None:
            if builtins.is_bytes_or_unicode(iterable):
                padding = ""
            elif isinstance(iterable, tuple):
                padding = (padding, )
            else:
                iterable = list(iterable)
                padding = [padding]
        sequence = iterable + (padding * (size - (length % size)))
        for i in builtins.range(0, length, size):
            yield sequence[i:i + size]
    else:
        for i in builtins.range(0, length, size):
            yield iterable[i:i + size]
Beispiel #6
0
    def __init__(self,
                 http_client,
                 client_credentials,
                 scopes,
                 use_authorization_header=True,
                 strict=False):
        self._scope = scopes \
                      if is_bytes_or_unicode(scopes) \
                      else SYMBOL_SPACE.join(scopes)

        super(GoogleClient, self).__init__(
            http_client,
            client_credentials=client_credentials,
            temporary_credentials_uri=self._TEMP_URI,
            token_credentials_uri=self._TOKEN_URI,
            authorization_uri=self._AUTH_URI,
            use_authorization_header=use_authorization_header,
            strict=strict,
        )
def select(predicate, iterable):
    """
    Select all items from the sequence for which the predicate is true.

        select(function or None, sequence) -> tuple, list or string.

    :param predicate:
        Predicate function. If ``None``, select all truthy items.
    :param iterable:
        Iterable.
    :returns:
        A sequence of all items for which the predicate is true.
    """
    if isinstance(iterable, list):
        transform = list
    elif is_bytes_or_unicode(iterable):
        transform = lambda w: w[:]
    else:
        transform = tuple
    return transform(filter(predicate, iterable))
Beispiel #8
0
def flatten(iterable, ignore=None):
  """Flattens a nested `iterable`.

  :param ignore:
      Types of iterable objects which should be yielded as-is.

  .. versionadded:: 0.5
  """
  stack = [iter(iterable)]
  while stack:
    try:
      item = stack[-1].next()
      if ignore and isinstance(item, ignore):
        yield item
      elif builtins.is_bytes_or_unicode(item) and len(item) == 1:
        yield item
      else:
        try:
          stack.append(iter(item))
        except TypeError:
          yield item
    except StopIteration:
      stack.pop()
Beispiel #9
0
def flatten(iterable, ignore=None):
    """Flattens a nested `iterable`.

  :param ignore:
      Types of iterable objects which should be yielded as-is.

  .. versionadded:: 0.5
  """
    stack = [iter(iterable)]
    while stack:
        try:
            item = stack[-1].next()
            if ignore and isinstance(item, ignore):
                yield item
            elif builtins.is_bytes_or_unicode(item) and len(item) == 1:
                yield item
            else:
                try:
                    stack.append(iter(item))
                except TypeError:
                    yield item
        except StopIteration:
            stack.pop()
Beispiel #10
0
def query_unflatten(query):
    """
    Given a query string parses it into an un-flattened query parameter
    dictionary or given a parameter dictionary, un-flattens it.

    Example::

        dict(a=1, b=[1, 2], c="")   ->   dict(a[1], b=[1, 2], c=[""])
        a=1&b=1&b=2&c=              ->   dict(a[1], b=[1, 2], c=[""])

    :param query:
        A query parameter dictionary or a query string.
        If this argument is ``None`` an empty dictionary will be returned.
        Any other value will raise a
        :class:`pyoauth.errors.InvalidQueryParametersError` exception.
    :returns:
        An un-flattened query parameter dictionary.
    """
    if is_bytes_or_unicode(query):
        return parse_qs(query)
    elif isinstance(query, dict):
        # Un-flatten the dictionary.
        def _choose(key, value):
            if not isinstance(value, list) and not isinstance(value, tuple):
                return key, [value]
            else:
                return key, list(value)
        return map_dict(_choose, query)
        # Alternative, but slower:
        #return parse_qs(urlencode_s(query))
    elif query is None:
        return {}
    else:
        raise InvalidQueryParametersError(
            "Dictionary or query string required: got `%r` instead" \
            % (query, ))
Beispiel #11
0
 def test_accepts_any_string(self):
   self.assertTrue(builtins.is_bytes_or_unicode(RANDOM_BYTES))
   self.assertTrue(builtins.is_bytes_or_unicode(constants.UTF8_BYTES))
   self.assertTrue(builtins.is_bytes_or_unicode(constants.UTF8_BYTES2))
   self.assertTrue(builtins.is_bytes_or_unicode(constants.UNICODE_STRING))
   self.assertTrue(builtins.is_bytes_or_unicode(constants.UNICODE_STRING2))
 def test_is_string(self):
   self.assertTrue(builtins.is_bytes_or_unicode(random.generate_random_string(64)))
 def test_is_string(self):
     self.assertTrue(is_bytes_or_unicode(_OAuthClient.generate_timestamp()),
                 "Timestamp is not a string.")
 def test_is_string(self):
   self.assertTrue(is_bytes_or_unicode(generate_random_string(64)))
Beispiel #15
0
 def test_accepts_any_string(self):
   self.assertTrue(is_bytes_or_unicode(random_bytes))
   self.assertTrue(is_bytes_or_unicode(utf8_bytes))
   self.assertTrue(is_bytes_or_unicode(utf8_bytes2))
   self.assertTrue(is_bytes_or_unicode(unicode_string))
   self.assertTrue(is_bytes_or_unicode(unicode_string2))
Beispiel #16
0
 def test_accepts_any_string(self):
     self.assertTrue(builtins.is_bytes_or_unicode(RANDOM_BYTES))
     self.assertTrue(builtins.is_bytes_or_unicode(constants.UTF8_BYTES))
     self.assertTrue(builtins.is_bytes_or_unicode(constants.UTF8_BYTES2))
     self.assertTrue(builtins.is_bytes_or_unicode(constants.UNICODE_STRING))
     self.assertTrue(builtins.is_bytes_or_unicode(constants.UNICODE_STRING2))