def test_conditional2(self): rnd = random() def get(): return rnd.randint(1, 100) size = 1000 conditions = (ChainedCondition().if_then( lambda x: x <= 10, lambda x: 10).if_then(lambda x: x <= 20, lambda x: 20).if_then( lambda x: x <= 30, lambda x: 30).otherwise(lambda x: -1)) out = (Stream.from_supplier(get).limit(size).conditional( conditions).collect(GroupingBy(identity, Counting()))) out_target = defaultdict(int) rnd.reset() for _ in range(size): e = get() if e <= 10: k = 10 elif e <= 20: k = 20 elif e <= 30: k = 30 else: k = -1 out_target[k] += 1 self.assertDictEqual(out, out_target)
def test_4(self): size = 10 eps = 1e-9 class Data: def __init__(self, e): self._e = e def e(self): return self._e def __eq__(self, other) -> bool: return abs(self._e - other._e) <= eps rnd = random() out = (Stream.from_supplier(rnd.random).limit(size).map(Data).sort( key=Data.e, reverse=True).collect(ToList())) rnd.reset() out_target = sorted((Data(rnd.random()) for _ in range(size)), key=Data.e, reverse=True) for o, t in zip(out, out_target): with self.subTest(o=o): self.assertAlmostEqual(o, t)
def test_2(self): size = 1000 rnd = random() square = lambda x: x**2 out = (Stream.from_supplier(rnd.random).limit(size).map(square).sort( reverse=True).collect(ToList())) rnd.reset() out_target = sorted((square(rnd.random()) for _ in range(size)), reverse=True) for o, t in zip(out, out_target): with self.subTest(o=o): self.assertAlmostEqual(o, t, delta=1e-9)
def test_if_else(self): rnd = random() def get(): return rnd.randint(1, 100) size = 1000 out = (Stream.from_supplier(get).limit(size).if_else( lambda x: x < 50, lambda x: 0, lambda x: 1).collect(GroupingBy(identity, Counting()))) out_target = defaultdict(int) rnd.reset() for _ in range(size): out_target[0 if get() < 50 else 1] += 1 self.assertDictEqual(out, out_target)