def test_lazy_unary(self): _vals = (14, 28) _eager = lambda x: x for _val in _vals: self.assertEquals((-Lazy(_val)).eval(), -_val) self.assertEquals((+Lazy(_val)).eval(), +_val) self.assertEquals((~Lazy(_val)).eval(), ~_val)
def test_lazy_exception_handling(self): # TypeError raised -> catch self.assertEquals( Try(Lazy(len)(2), TypeError, 'ERROR').eval(), 'ERROR') # TypeError is Exception subclass -> catch self.assertEquals( Try(Lazy(len)(2), Exception, 'ERROR').eval(), 'ERROR') # TypeError is not OSError -> raise with self.assertRaises(TypeError): Try(Lazy(len)(2), OSError, 'ERROR').eval()
def test_lazy_attribute(self): class class_with_attributes: def __init__(self): self.attr = 'value' _instance = class_with_attributes() self.assertEquals(Lazy(_instance).attr.eval(), _instance.attr) _lazy_inexistent_attr = Lazy(_instance).inexistent_attr with self.assertRaises(AttributeError): _lazy_inexistent_attr.eval()
def test_lazy_arithmetic(self): _vals = (14, 28) _eager = lambda x: x for _a, _b in itertools.product(_vals, _vals): for _config in [(Lazy, Lazy), (Lazy, _eager), (_eager, Lazy)]: # simple binary expressions self.assertEquals((_config[0](_a) + _config[1](_b)).eval(), _a + _b) self.assertEquals((_config[0](_a) - _config[1](_b)).eval(), _a - _b) self.assertEquals((_config[0](_a) * _config[1](_b)).eval(), _a * _b) self.assertEquals((_config[0](_a) / _config[1](_b)).eval(), _a / _b) # complex expression self.assertEquals((3 * (Lazy(14) - 22)).eval(), -24)
def test_lazy_callable(self): _vals = (14, 28, "a") doubler_lambda = lambda x: 2 * x def doubler_func(x): return 2 * x class doubler_class: def __call__(self, x): return 2 * x for _callable in (doubler_lambda, doubler_func, doubler_class()): for _val in _vals: # simple binary expressions self.assertEquals((Lazy(_callable)(_val)).eval(), _callable(_val))
def test_double_lazy_eval_roundtrip(self): for _value in self._values: with self.subTest(value=_value): self.assertEquals(Lazy(Lazy(_value)).eval().eval(), _value)
def test_lazy_conditional(self): _vals = (True, False) for _val in _vals: # simple binary expressions self.assertEquals((If(Lazy(_val), 'truey', 'falsy')).eval(), 'truey' if _val else 'falsy')
def test_lazy_hash(self): # ensure hashes are identical self.assertEquals( hash(Lazy((2, 'f', lambda: None))), hash(Lazy((2, 'f', lambda: None))), )