def get_rand_name(max_length=None, prefix='test'):
- name = prefix + str(random.randint(1, 0x7fffffff))
- return name[:max_length] if max_length is not None else name
+ """Return a random string.
+
+ The string will start with 'prefix' and will be exactly 'max_length'.
+ If 'max_length' is None, then exactly 8 random characters, each
+ hexadecimal, will be added. In case len(prefix) <= len(max_length),
+ ValueError will be raised to indicate the problem.
+ """
+
+ if max_length:
+ length = max_length - len(prefix)
+ if length <= 0:
+ raise ValueError("'max_length' must be bigger than 'len(prefix)'.")
+
+ suffix = ''.join(str(random.randint(0, 9)) for i in range(length))
+ else:
+ suffix = hex(random.randint(0x10000000, 0x7fffffff))[2:]
+ return prefix + suffix
def bool_from_env(key, strict=False, default=False):
def create_resource(prefix, creation_func, *args, **kwargs):
"""Create a new resource that does not already exist.
+ If prefix isn't 'max_length' in size, a random suffix is concatenated to
+ ensure it is random. Otherwise, 'prefix' is used as is.
+
:param prefix: The prefix for a randomly generated name
:param creation_func: A function taking the name of the resource
to be created as it's first argument. An error is assumed
to indicate a name collision.
:param *args *kwargs: These will be passed to the create function.
"""
+
+ # Don't generate a random name if prefix is already full-length.
+ if len(prefix) == n_const.DEVICE_NAME_MAX_LEN:
+ return creation_func(prefix, *args, **kwargs)
+
while True:
name = base.get_rand_name(
max_length=n_const.DEVICE_NAME_MAX_LEN,