def _calculate_limit(self, user_input): limit = 0 try: limit = int(user_input) except ValueError: index = 0 digits = ['%s' % num for num in range(0, 10)] + ['.'] while user_input[index] in digits: index += 1 limit = user_input[:index] format = user_input[index:] try: return to_bytes(limit, format) except Exception as qe: msg = 'Failed to convert %s to bytes' % user_input, raiseCLIError( qe, msg, details=[ 'Syntax: containerlimit set <limit>[format] [container]', 'e.g.,: containerlimit set 2.3GB mycontainer', 'Valid formats:', '(*1024): B, KiB, MiB, GiB, TiB', '(*1000): B, KB, MB, GB, TB' ]) return limit
def test_to_bytes(self): from kamaki.cli.utils import to_bytes for v in ('wrong', 'KABUM', 'kbps', 'kibps'): self.assertRaises(ValueError, to_bytes, v, 'B') self.assertRaises(ValueError, to_bytes, 42, v) for v in ([1, 2, 3], ('kb', 'mb'), {'kb': 1, 'byte': 2}): self.assertRaises(TypeError, to_bytes, v, 'B') self.assertRaises(AttributeError, to_bytes, 42, v) kl, ki = 1000, 1024 for size, (unit, factor) in product( (0, 42, 3.14, 1023, 10000), ( ('B', 1), ('b', 1), ('KB', kl), ('KiB', ki), ('mb', kl * kl), ('mIb', ki * ki), ('gB', kl * kl * kl), ('GIB', ki * ki * ki), ('TB', kl * kl * kl * kl), ('tiB', ki * ki * ki * ki))): self.assertEqual(to_bytes(size, unit), int(size * factor))
def _calculate_limit(self, user_input): limit = 0 try: limit = int(user_input) except ValueError: index = 0 digits = [str(num) for num in range(0, 10)] + ['.'] while user_input[index] in digits: index += 1 limit = user_input[:index] format = user_input[index:] try: return to_bytes(limit, format) except Exception as qe: msg = 'Failed to convert %s to bytes' % user_input, raiseCLIError(qe, msg, details=[ 'Syntax: containerlimit set <limit>[format] [container]', 'e.g.,: containerlimit set 2.3GB mycontainer', 'Valid formats:', '(*1024): B, KiB, MiB, GiB, TiB', '(*1000): B, KB, MB, GB, TB']) return limit