diff --git a/CHANGELOG.md b/CHANGELOG.md index c9491de344fc8db7eb3b75ee1d9b5370fa66b444..afeb7ae5ee3461e6a1fdca9fecaa4f6d0e0b6624 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 a20a4d1436ed9b231cddebe951a2b802fcfdc3f2..749c5adee87abc58ab227628f05517e04a958711 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 52f76ab5f009773a9e714898e48ffda2fe1c87f4..93d9c4d14e5f2a1cc4a9f0c1e959c5396385f407 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 3877125b3a24158d75875ba272704670b12efd55..ebafc1232707abade6520a8f4a56b3bb3385598f 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 94d727d23097e16f076d7b97e40fafc43351203e..57b20d6d121dfa68f7108f146e4b3bfcd05388cc 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)