parse_bytes: Add ability to handle 64-bit integers in py2

Signed-off-by: Joffrey F <joffrey@docker.com>
This commit is contained in:
Joffrey F 2015-12-18 14:37:22 -08:00
parent 57b79cb1e7
commit cd66f6c6cd
2 changed files with 38 additions and 16 deletions

View File

@ -486,6 +486,12 @@ def datetime_to_timestamp(dt):
return delta.seconds + delta.days * 24 * 3600 return delta.seconds + delta.days * 24 * 3600
def longint(n):
if six.PY3:
return int(n)
return long(n)
def parse_bytes(s): def parse_bytes(s):
if len(s) == 0: if len(s) == 0:
s = 0 s = 0
@ -506,20 +512,21 @@ def parse_bytes(s):
if suffix in units.keys() or suffix.isdigit(): if suffix in units.keys() or suffix.isdigit():
try: try:
digits = int(digits_part) digits = longint(digits_part)
except ValueError: except ValueError:
message = ('Failed converting the string value for' raise errors.DockerException(
'memory ({0}) to a number.') 'Failed converting the string value for memory ({0}) to'
formatted_message = message.format(digits_part) ' an integer.'.format(digits_part)
raise errors.DockerException(formatted_message) )
s = digits * units[suffix] # Reconvert to long for the final result
s = longint(digits * units[suffix])
else: else:
message = ('The specified value for memory' raise errors.DockerException(
' ({0}) should specify the units. The postfix' 'The specified value for memory ({0}) should specify the'
' should be one of the `b` `k` `m` `g`' ' units. The postfix should be one of the `b` `k` `m` `g`'
' characters') ' characters'.format(s)
raise errors.DockerException(message.format(s)) )
return s return s

View File

@ -5,6 +5,7 @@ import json
import os import os
import os.path import os.path
import shutil import shutil
import sys
import tarfile import tarfile
import tempfile import tempfile
@ -465,14 +466,28 @@ class ParseDeviceTest(base.BaseTestCase):
}) })
class UtilsTest(base.BaseTestCase): class ParseBytesTest(base.BaseTestCase):
longMessage = True def test_parse_bytes_valid(self):
self.assertEqual(parse_bytes("512MB"), 536870912)
self.assertEqual(parse_bytes("512M"), 536870912)
self.assertEqual(parse_bytes("512m"), 536870912)
def test_parse_bytes(self): def test_parse_bytes_invalid(self):
self.assertEqual(parse_bytes("512MB"), (536870912))
self.assertEqual(parse_bytes("512M"), (536870912))
self.assertRaises(DockerException, parse_bytes, "512MK") self.assertRaises(DockerException, parse_bytes, "512MK")
self.assertRaises(DockerException, parse_bytes, "512L") self.assertRaises(DockerException, parse_bytes, "512L")
self.assertRaises(DockerException, parse_bytes, "127.0.0.1K")
def test_parse_bytes_float(self):
self.assertRaises(DockerException, parse_bytes, "1.5k")
def test_parse_bytes_maxint(self):
self.assertEqual(
parse_bytes("{0}k".format(sys.maxsize)), sys.maxsize * 1024
)
class UtilsTest(base.BaseTestCase):
longMessage = True
def test_convert_filters(self): def test_convert_filters(self):
tests = [ tests = [