From e4640495d80133f09e7ff83b16894de389a271ef Mon Sep 17 00:00:00 2001 From: Tim Burke Date: Fri, 2 Mar 2018 12:24:09 +0000 Subject: [PATCH] py3: have Timestamp accept bytestrings, better validate input Change-Id: I627894b9496cc85b3b1852e9df4812257df4ac6a --- swift/common/utils.py | 13 +++++++++---- test/unit/common/test_utils.py | 3 +++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/swift/common/utils.py b/swift/common/utils.py index 8209e71898..eaaa21e358 100644 --- a/swift/common/utils.py +++ b/swift/common/utils.py @@ -940,11 +940,16 @@ class Timestamp(object): :param delta: deca-microsecond difference from the base timestamp param, an int """ + if isinstance(timestamp, bytes): + timestamp = timestamp.decode('ascii') if isinstance(timestamp, six.string_types): - parts = timestamp.split('_', 1) - self.timestamp = float(parts.pop(0)) - if parts: - self.offset = int(parts[0], 16) + base, base_offset = timestamp.partition('_')[::2] + self.timestamp = float(base) + if '_' in base_offset: + raise ValueError('invalid literal for int() with base 16: ' + '%r' % base_offset) + if base_offset: + self.offset = int(base_offset, 16) else: self.offset = 0 else: diff --git a/test/unit/common/test_utils.py b/test/unit/common/test_utils.py index bcd7c922c8..eab37a3e5c 100644 --- a/test/unit/common/test_utils.py +++ b/test/unit/common/test_utils.py @@ -183,6 +183,7 @@ class TestTimestamp(unittest.TestCase): def test_invalid_input(self): self.assertRaises(ValueError, utils.Timestamp, time.time(), offset=-1) + self.assertRaises(ValueError, utils.Timestamp, '123.456_78_90') def test_invalid_string_conversion(self): t = utils.Timestamp.now() @@ -390,6 +391,8 @@ class TestTimestamp(unittest.TestCase): expected = '1402436408.91203_00000000000000f0' test_values = ( '1402436408.91203_000000f0', + u'1402436408.91203_000000f0', + b'1402436408.91203_000000f0', '1402436408.912030000_0000000000f0', '1402436408.912029_000000f0', '1402436408.91202999999_0000000000f0',