def test_match_function_constructor(self, Maybe): x = Maybe.Just(42) y = Maybe.Nothing func = Maybe.match_fn( just=lambda x: x * 2, nothing=lambda: 0, ) assert func(x) == 84 assert func(y) == 0
def test_adt_has_correct_type(self, Maybe): x = Maybe.Just(42) y = Maybe.Nothing assert type(x) is Maybe assert type(y) is Maybe assert isinstance(x, Union) assert isinstance(y, Union) assert issubclass(Maybe, Union)
def test_conditionals(self, Maybe): x = Maybe.Just(42) assert x.just assert not x.nothing y = Maybe.Nothing assert y.nothing assert not y.just
def test_can_access_state_args_attribute(self, Maybe): x = Maybe.Just(42) y = Maybe.Nothing assert x.just_args == (42, ) assert y.nothing_args == () with pytest.raises(AttributeError): assert x.nothing_args with pytest.raises(AttributeError): assert y.just_args
def test_match_function(self, Maybe): x = Maybe.Just(42) y = Maybe.Nothing res = x.match( just=lambda x: x * 2, nothing=lambda: 0, ) assert res == 84 res = y.match( just=lambda x: x * 2, nothing=lambda: 0, ) assert res == 0
def test_match_fn_raises_error_on_non_exaustive_options(self, Maybe): with pytest.raises(ValueError): Maybe.match_fn(just=lambda x: x, ) with pytest.raises(ValueError): Maybe.match_fn( just=lambda x: x, nothing=lambda: 0, other=lambda: 0, ) with pytest.raises(ValueError): Maybe.match_fn( ok=lambda x: x, err=lambda: 0, )
def just(self, Maybe): return Maybe.Just(42)
def test_to_maybe(self, ok, err): assert ok.to_maybe() == Maybe.Just(42) assert err.to_maybe() == Maybe.Nothing
def test_maybe_function_conversions(self, Maybe): assert maybe(42) == Maybe.Just(42) assert maybe(None) == Maybe.Nothing
def test_bitwise(self): x = Maybe.Just(42) y = Maybe.Nothing assert x & y == y assert x | y == x
def test_call(self): x = Maybe.Just(42) y = Maybe.Nothing assert Maybe.call(lambda x, y: x + y, x, x) == Maybe.Just(84) assert Maybe.call(lambda x, y: x + y, x, y) == Maybe.Nothing
def test_then_method(self): x = Maybe.Just(1) y = x.then(lambda x: x + 1).then(lambda x: x + 1) assert y.just assert y.value == 3
def test_adt_has_hash(self, Maybe): assert hash(Maybe.Nothing) != hash(Maybe.Just(1))
def test_adt_matches_instance(self, Maybe): a = Maybe.Just(42) b = Maybe.Nothing assert a.match(just=lambda x: x, nothing=lambda: 0) == 42 assert b.match(just=lambda x: x, nothing=lambda: 0) == 0
def test_equality(self, Maybe): x = Maybe.Just(42) y = Maybe.Nothing assert y == Maybe.Nothing assert x == Maybe.Just(42) assert x != y
def test_adt_repr(self, Maybe): assert repr(Maybe.Just(42)) == 'Just(42)' assert repr(Maybe.Nothing) == 'Nothing'
def test_adt_requires_correct_number_of_arguments(self, Maybe): with pytest.raises(TypeError): Maybe.Just(1, 2) with pytest.raises(TypeError): Maybe.Just()
def test_maybe_chaining(self): x = (Maybe.Just(42) >> (lambda x: 2 * x)).get() y = (Maybe.Nothing >> (lambda x: 2 * x)).get() assert x == 84 assert y == None