typesafe-monads/tests/test_maybe.py

85 lines
2.1 KiB
Python
Raw Normal View History

2018-10-12 00:44:57 +00:00
import pytest # type: ignore
2018-10-12 18:41:56 +00:00
from typing import Callable, List
2018-10-12 00:44:57 +00:00
from monads.maybe import Maybe, Just, Nothing, maybe, first, last
2018-10-11 05:26:00 +00:00
2018-10-12 18:41:56 +00:00
def test_bind_just() -> None:
m: Maybe[int] = Just(5)
increment: Callable[[int], Maybe[int]] = lambda x: Just(x + 1)
assert Just(6) == m.bind(increment)
def test_bind_nothing() -> None:
m: Maybe[int] = Nothing()
increment: Callable[[int], Maybe[int]] = lambda x: Just(x + 1)
assert Nothing() == m.bind(increment)
def test_apply_just_to_just() -> None:
m: Maybe[int] = Just(5)
increment: Callable[[int], int] = lambda x: x + 1
assert Just(6) == m.apply(Maybe.pure(increment))
def test_apply_just_to_nothing() -> None:
m: Maybe[int] = Nothing()
increment: Callable[[int], int] = lambda x: x + 1
assert Nothing() == m.apply(Maybe.pure(increment))
def test_apply_nothing_to_just() -> None:
m: Maybe[int] = Just(5)
f: Maybe[Callable[[int], int]] = Nothing()
assert Nothing() == m.apply(f)
def test_apply_nothing_to_nothing() -> None:
m: Maybe[int] = Nothing()
f: Maybe[Callable[[int], int]] = Nothing()
assert Nothing() == m.apply(f)
def test_just_withdefault() -> None:
m: Maybe[int] = Just(5)
assert 5 == m.withDefault(0)
def test_nothing_withdefault() -> None:
m: Maybe[int] = Nothing()
assert 0 == m.withDefault(0)
def test_maybe_none() -> None:
2018-10-11 05:26:00 +00:00
assert isinstance(maybe(None), Nothing)
2018-10-12 18:41:56 +00:00
def test_maybe_something() -> None:
2018-10-11 05:26:00 +00:00
assert isinstance(maybe(False), Just)
2018-10-12 18:41:56 +00:00
def test_maybe_boolean_false() -> None:
2018-10-11 05:26:00 +00:00
assert isinstance(maybe(False, predicate=bool), Nothing)
2018-10-12 18:41:56 +00:00
def test_maybe_boolean_true() -> None:
2018-10-11 05:26:00 +00:00
assert isinstance(maybe(True, predicate=bool), Just)
2018-10-12 00:44:57 +00:00
def test_first() -> None:
maybes: List[Maybe[int]] = [Nothing(), Just(1), Just(2)]
assert Just(1) == first(maybes)
2018-10-12 18:41:56 +00:00
2018-10-12 00:44:57 +00:00
def test_last() -> None:
maybes: List[Maybe[int]] = [Just(1), Just(2), Nothing()]
assert Just(2) == last(maybes)
2018-12-03 21:16:04 +00:00
def test_from_empty_list() -> None:
assert Nothing() == Maybe.fromList([])
def test_from_nonempty_list() -> None:
assert Just(2) == Maybe.fromList([2, 4, 6])