Fix unicode handling in get_random_string

get_random_string would often fail in decoding the result of
os.urandom. It would fail because the result of urandom is a bunch
of random bytes and not valid text (i.e., not a valid utf-8
representation).

Turns out that it's unnecessary to decode the result of os.urandom.
It returns six.binary_type whether on py2 or py3, and
binascii.hexlify() takes a six.binary_type as the argument.

binascii.hexlify() returns six.binary_type and we want
get_random_string() to return six.text_type, so convert.

Also, fixed the docstrings to use """.

Closes-Bug: 1514981
Change-Id: I60c31f2c47614beb3ed3c143d7815fdc15f5a0e0
This commit is contained in:
Brant Knudson 2015-11-10 14:23:21 -06:00
parent 49976d2b9b
commit 0feb86ecbb
1 changed files with 10 additions and 11 deletions

View File

@ -11,7 +11,6 @@
# under the License.
import binascii
import os
import os.path
import random
import subprocess
@ -20,27 +19,27 @@ from reno import defaults
def get_notes_dir(args):
"Return the path to the release notes directory."
"""Return the path to the release notes directory."""
return os.path.join(args.relnotesdir, defaults.NOTES_SUBDIR)
def get_random_string(nbytes=8):
"Return a fixed-length random string"
"""Return a fixed-length random string
:rtype: six.text_type
"""
try:
# NOTE(dhellmann): Not all systems support urandom(). When it
# is supported, it returns a str() but under Python 3 we need
# to give a byte string to hexlify() so convert back and forth
# through utf-8.
rand_bytes_bstring = os.urandom(nbytes).encode('utf-8')
val = binascii.hexlify(rand_bytes_bstring).decode('utf-8')
# NOTE(dhellmann): Not all systems support urandom().
# hexlify returns six.binary_type, decode to convert to six.text_type.
val = binascii.hexlify(os.urandom(nbytes)).decode('utf-8')
except Exception as e:
print('ERROR: %s' % e)
print('ERROR, perhaps urandom is not supported: %s' % e)
val = ''.join('%02x' % random.randrange(256)
for i in range(nbytes))
return val
def check_output(*args, **kwds):
"Unicode-aware wrapper for subprocess.check_output"
"""Unicode-aware wrapper for subprocess.check_output"""
raw = subprocess.check_output(*args, **kwds)
return raw.decode('utf-8')