From 7b692ec1616c4c83e89d1be09476be9d7634394c Mon Sep 17 00:00:00 2001 From: Alois Mahdal Date: Tue, 6 May 2014 21:58:31 +0200 Subject: Improve random_string util function When writing new test, I find myself constantly computing the size from desired strength and prefix length, whereas I mostly don't care about the final size at all (plus, one can usually see that from surrounding code). Providing strength simplifies use and the function code. --- src/account/test/TestAccountRaceConditions.py | 2 +- src/account/test/common.py | 4 ++-- src/account/test/methods.py | 10 ++++++---- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/account/test/TestAccountRaceConditions.py b/src/account/test/TestAccountRaceConditions.py index 6125bd3..61785c8 100644 --- a/src/account/test/TestAccountRaceConditions.py +++ b/src/account/test/TestAccountRaceConditions.py @@ -123,7 +123,7 @@ class TestAccountRaceConditions(AccountBase): def setUp(self): self.user_count = 20 # = thread count self.prefix = "user" - self.names = [methods.random_string(size=8, prefix=self.prefix) + self.names = [methods.random_string(strength=8, prefix=self.prefix) for i in xrange(self.user_count)] self.bs = BackupStorage() diff --git a/src/account/test/common.py b/src/account/test/common.py index 862d1d4..8f3eeba 100644 --- a/src/account/test/common.py +++ b/src/account/test/common.py @@ -271,11 +271,11 @@ class BaseCrippler: def _random_binary(self, size=BINARY_LENGTH): chars = ''.join([chr(i) for i in xrange(256)]) - return methods.random_string(size, chars) + return methods.random_string(strength=size, chars=chars) def _random_line(self, size=LINE_LENGTH): chars = string.letters + string.punctuation + " \t" - return methods.random_string(size, chars) + "\n" + return methods.random_string(strength=size, chars=chars) + "\n" def _random_lines(self, size=LINE_LENGTH, count=LINE_COUNT): return "".join([self._random_line(size) for i in xrange(count)]) diff --git a/src/account/test/methods.py b/src/account/test/methods.py index 9c033c5..4043ddf 100644 --- a/src/account/test/methods.py +++ b/src/account/test/methods.py @@ -97,15 +97,17 @@ def create_group(group_name): if not group_exists(group_name): subprocess.check_call(["groupadd", group_name]) -def random_string(size=6, chars=None, prefix=""): +def random_string(strength=6, chars=None, prefix=""): """ Generate a random string, e.g. usable as UID/GID + + strength is count of random characters in the final string. chars + is sequence of characters to choose from, and prefix can be provided + to prepend it to final string. """ if chars is None: chars = string.ascii_uppercase + string.digits - if len(prefix) > size: - raise ValueError("prefix too long: %s > %s" % (len(prefix), size)) - salt = ''.join([random.choice(chars) for x in range(size - len(prefix))]) + salt = ''.join([random.choice(chars) for x in range(strength)]) return prefix + salt def random_shell(): -- cgit