From 82dd22aefa1bce39fdc87eb3daeb539e6b5bcd6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Ma=C5=9Blanka?= <pmaslanka@smok.co> Date: Fri, 24 Sep 2021 15:08:04 +0200 Subject: [PATCH] added random_word --- CHANGELOG.md | 2 ++ docs/random.rst | 5 +++++ satella/__init__.py | 2 +- satella/random.py | 23 ++++++++++++++++++++++- tests/test_random.py | 9 ++++++++- 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9491de3..afeb7ae5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,3 @@ # v2.17.21 + +* added random_word diff --git a/docs/random.rst b/docs/random.rst index a20a4d14..749c5ade 100644 --- a/docs/random.rst +++ b/docs/random.rst @@ -11,3 +11,8 @@ random_binary ------------- .. autofunction:: satella.random.random_binary + +random_word +----------- + +.. autofunction:: satella.random.random_word diff --git a/satella/__init__.py b/satella/__init__.py index 52f76ab5..93d9c4d1 100644 --- a/satella/__init__.py +++ b/satella/__init__.py @@ -1 +1 @@ -__version__ = '2.17.21a1' +__version__ = '2.17.21a2' diff --git a/satella/random.py b/satella/random.py index 3877125b..ebafc123 100644 --- a/satella/random.py +++ b/satella/random.py @@ -1,8 +1,29 @@ import os import random import typing as tp +import string -__all__ = ['shuffle_together', 'random_binary'] +__all__ = ['shuffle_together', 'random_binary', 'random_word'] + +from satella.coding.typing import T + + +def random_word(length: int, choice: T = string.ascii_lowercase, + join_fun: tp.Callable[[T, ...], T] = lambda *args: ''.join(args)): + """ + Build and return a random word of provided length. + + The word will be built by calling join_fun with length of arguments picked + at random from choice. + + :param length: length of the word + :param choice: a range of characters to use. By default is string.ascii_lowercase + :param join_fun: an argument to be called with randomly picked characters as *args. + Defaults to ''.join(args), so your T must be a string. If you're passing a + different type, remember to alter this function because the default one expects strings! + :return: a random word + """ + return join_fun(*(random.choice(choice) for _ in range(length))) def random_binary(length: int) -> bytes: diff --git a/tests/test_random.py b/tests/test_random.py index 94d727d2..57b20d6d 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -1,8 +1,15 @@ import unittest -from satella.random import shuffle_together, random_binary +from satella.random import shuffle_together, random_binary, random_word +import string class TestRandom(unittest.TestCase): + + def test_random_word(self): + rand_word = random_word(5) + self.assertEqual(len(rand_word), 5) + self.assertTrue(all(y in string.ascii_lowercase for y in rand_word)) + def test_random_binary(self): self.assertFalse(random_binary(0)) self.assertEqual(len(random_binary(10)), 10) -- GitLab