Test(core): doctest reject_random and filter_random

This commit is contained in:
Bertrand Benjamin 2019-01-07 09:24:19 +01:00
parent f04e221f70
commit e0334d3c0f

View File

@ -10,7 +10,7 @@
Function to create random things
"""
from random import randint, choice
import random
__all__ = ["reject_random", "filter_random", "FilterRandom"]
@ -27,12 +27,37 @@ def reject_random(min_value = -10,
:param rejected: rejected values
:param accept_callbacks: list of function for value rejection
:example:
>>> a = reject_random()
>>> a not in [0, 1]
True
>>> a >= -10
True
>>> a <= 10
True
>>> a = reject_random(min_value=3, max_value=11, rejected=[5, 7])
>>> a not in [5, 7]
True
>>> a >= 3
True
>>> a <= 11
True
>>> a = reject_random(accept_callbacks=[lambda x: x%2])
>>> a%2
1
>>> random.seed(0)
>>> reject_random()
2
>>> random.seed(1)
>>> reject_random()
-6
"""
conditions = [lambda x: x not in rejected] + accept_callbacks
candidate = randint(min_value, max_value)
candidate = random.randint(min_value, max_value)
while not all(c(candidate) for c in conditions):
candidate = randint(min_value, max_value)
candidate = random.randint(min_value, max_value)
return candidate
@ -49,6 +74,30 @@ def filter_random(min_value = -10,
:param rejected: rejected values
:param accept_callbacks: list of function for value rejection
:example:
>>> a = filter_random()
>>> a not in [0, 1]
True
>>> a >= -10
True
>>> a <= 10
True
>>> a = filter_random(min_value=3, max_value=11, rejected=[5, 7])
>>> a not in [5, 7]
True
>>> a >= 3
True
>>> a <= 11
True
>>> a = filter_random(accept_callbacks=[lambda x: x%2])
>>> a%2
1
>>> random.seed(0)
>>> filter_random()
-7
>>> random.seed(1)
>>> filter_random()
6
"""
candidates = set(range(min_value, max_value+1))
candidates = {c for c in candidates if c not in rejected}
@ -58,7 +107,7 @@ def filter_random(min_value = -10,
if len(candidates) == 0:
raise OverflowError("There is no candidates for this range and those conditions")
return choice(candidates)
return random.choice(candidates)
class FilterRandom(object):
@ -110,7 +159,7 @@ class FilterRandom(object):
def __call__(self, min_value=-10, max_value=10):
""" Randomly choose on candidate """
self.add_candidates(min_value, max_value)
return choice(self.candidates(min_value, max_value))
return random.choice(self.candidates(min_value, max_value))
# -----------------------------