def _squash_context(*args): """ Unwraps ``RequiresContext`` values, merges them into tuple, and wraps back. .. code:: python >>> from returns.context import RequiresContext >>> from returns.converters import squash_context >>> assert squash_context( ... RequiresContext.from_value(1), ... RequiresContext.from_value('a'), ... RequiresContext.from_value(True), ... )(...) == RequiresContext.from_value((1, 'a', True))(...) See :func:`returns.converters.squash_io` for more docs. """ return RequiresContext(lambda deps: tuple(func(deps) for func in args))
def test_bind_with_context(): """Ensures that functions can be composed and return type is correct.""" binded = bind(_context_function) assert binded(RequiresContext(lambda _: 3))(5) == 8
def _context_function(argument: int) -> RequiresContext[int, int]: return RequiresContext(lambda other: argument + other)
def factory(inner_value: int) -> RequiresContext[float, int]: return RequiresContext(lambda deps: inner_value / deps)
from copy import copy, deepcopy import pytest from returns.context import Context, RequiresContext from returns.primitives.exceptions import ImmutableStateError from returns.primitives.interfaces import Bindable, Instanceable, Mappable @pytest.mark.parametrize('container', [ RequiresContext(lambda deps: deps), RequiresContext.from_value(1), Context.ask(), ]) @pytest.mark.parametrize('protocol', [ Bindable, Mappable, Instanceable, ]) def test_protocols(container, protocol): """Ensures that RequiresContext has all the right protocols.""" assert isinstance(container, protocol) def test_context_immutable(): """Ensures that Context is immutable.""" with pytest.raises(ImmutableStateError): Context().abc = 1 def test_context_immutable_copy():
def test_nonequality(): """Ensures that containers can be compared.""" assert RequiresContext(_same_function) != RequiresContext(str) assert Context[int].unit(1) != Context[int].unit(1) assert Context.unit(1) != Context[int].unit(1) assert Context.unit(1) != Context.unit(1)
def test_equality(): """Ensures that containers can be compared.""" assert RequiresContext(_same_function) == RequiresContext(_same_function) assert Context[int].ask() == Context[int].ask() assert Context[int].ask() == Context.ask() assert Context.ask() == Context.ask()
def factory(number: float) -> RequiresContext[int, str]: return RequiresContext(lambda deps: str(number + deps))
def test_nonequality(): """Ensures that containers can be compared.""" assert RequiresContext(_same_function) != RequiresContext(str) assert RequiresContext.from_value(1) != RequiresContext.from_value(1)