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)
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)
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)
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
def testPicklePercent(self): q = units.ParseExpression('10%') self.assertEqual(q, pickle.loads(pickle.dumps(q)))
def testFloatPercent(self): q = units.ParseExpression('12.5%') self.assertEqual(q.magnitude, 12.5) self.assertEqual(q.units, units.percent)
def testIntPercent(self): q = units.ParseExpression('10%') self.assertEqual(q.magnitude, 10) self.assertEqual(q.units, units.percent)
def testKB(self): self.assertEqual(units.ParseExpression('12KB'), units.ParseExpression('12000 bytes'))
def testKubernetes(self): self.assertEqual(units.ParseExpression('2048Ki'), 2 * units.mebibyte)