def test_bool(): assert bool(Failure(True)) is False assert bool(Success(False)) is True for n in test_range: assert bool(Failure(n)) is False assert bool(Success(n)) is True assert bool(unit(n)) is True
def test_ftry_action(): inc = lambda n: n + 1 dec = lambda n: n - 1 act = ftry(inc) assert act(Failure(1)) == 2 assert act(Success(1)) == 1 act = ftry(failure_handler=inc, success_handler=dec) assert act(Failure(1)) == 2 assert act(Success(1)) == 0
def test_failsafe_decorator_combined(): @failsafe(predicate=bool, failure_on_value=42) def wrap(x): return x assert wrap(True) == Success(True) assert wrap(False) == Failure(False) assert wrap('something') == Success('something') assert wrap('') == Failure('') assert wrap([False]) == Success([False]) assert wrap([]) == Failure([]) assert wrap(1) == Success(1) assert wrap(0) == Failure(0) assert wrap(None) == Failure(None) assert wrap(42) == Failure(42)
def test_recover(): result = Failure(0).recover(lambda v: v + 1) assert result == 1 result = Success(10).recover(lambda v: v + 1) assert isinstance(result, Success) assert result.value == 10
def test_fmap_functor_laws(): identity = lambda a: a f = lambda a: a + 1 g = lambda a: a * 2 f_g = lambda n: f(g(n)) for n in test_range: ft = unit(n) # fmap id == id assert ft.fmap(identity) == identity(ft) # fmap (f . g) == fmap f . fmap g assert ft.fmap(f_g) == ft.fmap(g).fmap(f) value = 42 l = Failure('Something wrong.') r = Success(value) assert l.fmap(f) is l assert r.fmap(f) == Success(f(42))
def test_ordering(): with pytest.raises(TypeError): Failure(1) < 1 with pytest.raises(TypeError): Success(1) < 1 for n in test_range: assert (Failure(n) < Failure(n)) is False assert Failure(n) > Failure(n - 1) assert Failure(n) < Failure(n + 1) assert (Success(n) < Success(n)) is False assert Success(n) > Success(n - 1) assert Success(n) < Success(n + 1) assert Failure(n) < Success(n)
def test_compare(): for n in test_range: assert Failure(n) == Failure(n) assert Success(n) == Success(n) assert Failure(n) != Success(n)
def test_match_failure_and_success(): assert Failure(0).match(lambda v: v + 1, lambda v: v / 2) == 1 assert Success(10).match(lambda v: v + 1, lambda v: v / 2) == 5
def test_match_failure_only(): assert Failure(0).match(lambda v: v + 1) == 1 assert Success(10).match(lambda v: v + 1) == 10