Port short_id to return unicode

This will now use unichr instead of chr to convert
an integer to byte-string. Then these bytes are
encoded and decoded with 'latin-1' to comply with
the existing tests that assert against absolute values.

partial blueprint heat-python34-support

Change-Id: I5b9de1cea54889fa388993b9afa4b45f01fbec4a
This commit is contained in:
Sirushti Murugesan 2015-06-29 09:06:25 +05:30
parent 7a7820c4ff
commit 15cbb894f2
3 changed files with 12 additions and 10 deletions

View File

@ -32,7 +32,7 @@ def _to_byte_string(value, num_bits):
"""
shifts = six.moves.xrange(num_bits - 8, -8, -8)
byte_at = lambda off: (value >> off if off >= 0 else value << -off) & 0xff
return ''.join(chr(byte_at(offset)) for offset in shifts)
return ''.join(six.unichr(byte_at(offset)) for offset in shifts)
def get_id(source_uuid):
@ -49,9 +49,10 @@ def get_id(source_uuid):
# (see RFC4122, Section 4.4)
random_bytes = _to_byte_string(source_uuid.time, 60)
# The first 12 bytes (= 60 bits) of base32-encoded output is our data
encoded = base64.b32encode(random_bytes)[:12]
return encoded.lower()
encoded = base64.b32encode(random_bytes.encode('latin-1'))[:12]
return encoded.lower().decode('latin-1')
def generate_id():

View File

@ -20,16 +20,16 @@ from heat.tests import common
class ShortIdTest(common.HeatTestCase):
def test_byte_string_8(self):
self.assertEqual('\xab', short_id._to_byte_string(0xab, 8))
self.assertEqual('\x05', short_id._to_byte_string(0x05, 8))
self.assertEqual(u'\xab', short_id._to_byte_string(0xab, 8))
self.assertEqual(u'\x05', short_id._to_byte_string(0x05, 8))
def test_byte_string_16(self):
self.assertEqual('\xab\xcd', short_id._to_byte_string(0xabcd, 16))
self.assertEqual('\x0a\xbc', short_id._to_byte_string(0xabc, 16))
self.assertEqual(u'\xab\xcd', short_id._to_byte_string(0xabcd, 16))
self.assertEqual(u'\x0a\xbc', short_id._to_byte_string(0xabc, 16))
def test_byte_string_12(self):
self.assertEqual('\xab\xc0', short_id._to_byte_string(0xabc, 12))
self.assertEqual('\x0a\xb0', short_id._to_byte_string(0x0ab, 12))
self.assertEqual(u'\xab\xc0', short_id._to_byte_string(0xabc, 12))
self.assertEqual(u'\x0a\xb0', short_id._to_byte_string(0x0ab, 12))
def test_byte_string_60(self):
val = 0x111111111111111
@ -67,5 +67,5 @@ class ShortIdTest(common.HeatTestCase):
for id in ids:
self.assertEqual(12, len(id))
self.assertFalse(id.translate(None, allowed_chars))
self.assertEqual(id, id.translate(allowed_chars))
self.assertEqual(1, ids.count(id))

View File

@ -1 +1,2 @@
heat.tests.test_version
heat.tests.test_short_id