コード例 #1
0
def StringToBytes(string):
    """Convert an object size, represented as a string, to bytes.

  Args:
    string: the object size, as a string with a quantity and a unit.

  Returns:
    an integer. The number of bytes in the size.

  Raises:
    ValueError, if either the string does not represent an object size
    or if the size does not contain an integer number of bytes.
  """

    try:
        quantity = units.ParseExpression(string)
    except Exception:
        # Catching all exceptions is ugly, but we don't know what sort of
        # exception pint might throw, and we want to turn any of them into
        # ValueError.
        raise ValueError("Couldn't parse size %s" % string)

    try:
        bytes = quantity.m_as(units.byte)
    except units.DimensionalityError:
        raise ValueError("Quantity %s is not a size" % string)

    if bytes != int(bytes):
        raise ValueError("Size %s has a non-integer number (%s) of bytes!" %
                         (string, bytes))

    if bytes < 0:
        raise ValueError("Size %s has a negative number of bytes!" % string)

    return int(bytes)
コード例 #2
0
ファイル: units_test.py プロジェクト: xcnix/avocado-cloudtest
    def testPickleKB(self):
        # Make sure we can pickle and unpickle quantities with the unit we
        # defined ourselves.
        q_prepickle = units.ParseExpression('1KB')
        q_pickled = pickle.dumps(q_prepickle)
        q_postpickle = pickle.loads(q_pickled)

        self.assertEqual(q_prepickle, q_postpickle)
コード例 #3
0
 def node_memory_allocatable(self) -> units.Quantity:
     """Usable memory of each node in cluster in KiB."""
     stdout, _, _ = RunKubectlCommand(
         # TODO(pclay): Take a minimum of all nodes?
         [
             'get', 'nodes', '-o',
             'jsonpath={.items[0].status.allocatable.memory}'
         ])
     return units.ParseExpression(stdout)
コード例 #4
0
    def parse(self, inp):
        """Parse the input.

    Args:
      inp: a string or a units.Quantity. If a string, it has the format
          "<number><units>", as in "12KB", or "2.5GB".

    Returns:
      A units.Quantity.

    Raises:
      ValueError: If the input cannot be parsed, or if it parses to a value with
          improper units.
    """
        if isinstance(inp, units.Quantity):
            quantity = inp
        else:
            try:
                quantity = units.ParseExpression(inp)
            except Exception as e:
                raise ValueError("Couldn't parse unit expression %r: %s" %
                                 (inp, e.message))
            if not isinstance(quantity, units.Quantity):
                raise ValueError(
                    'Expression %r evaluates to a unitless value.' % inp)

        for unit in self.convertible_to:
            try:
                quantity.to(unit)
                break
            except units.DimensionalityError:
                pass
        else:
            raise ValueError(
                'Expression {0!r} is not convertible to an acceptable unit '
                '({1}).'.format(inp,
                                ', '.join(str(u)
                                          for u in self.convertible_to)))

        return quantity
コード例 #5
0
ファイル: units_test.py プロジェクト: xcnix/avocado-cloudtest
 def testPicklePercent(self):
     q = units.ParseExpression('10%')
     self.assertEqual(q, pickle.loads(pickle.dumps(q)))
コード例 #6
0
ファイル: units_test.py プロジェクト: xcnix/avocado-cloudtest
 def testFloatPercent(self):
     q = units.ParseExpression('12.5%')
     self.assertEqual(q.magnitude, 12.5)
     self.assertEqual(q.units, units.percent)
コード例 #7
0
ファイル: units_test.py プロジェクト: xcnix/avocado-cloudtest
 def testIntPercent(self):
     q = units.ParseExpression('10%')
     self.assertEqual(q.magnitude, 10)
     self.assertEqual(q.units, units.percent)
コード例 #8
0
ファイル: units_test.py プロジェクト: xcnix/avocado-cloudtest
 def testKB(self):
     self.assertEqual(units.ParseExpression('12KB'),
                      units.ParseExpression('12000 bytes'))
コード例 #9
0
 def testKubernetes(self):
     self.assertEqual(units.ParseExpression('2048Ki'), 2 * units.mebibyte)