def outcome(self) -> GameOutcome: if self.home_goals is None and self.guest_goals is None: return GameOutcome.OPEN home_goals: int = Maybe.from_optional(self.home_goals).unwrap() guest_goals: int = Maybe.from_optional(self.guest_goals).unwrap() if home_goals > guest_goals \ or self.forfeiting_team == self.guest_team: return GameOutcome.HOME_WIN if home_goals < guest_goals \ or self.forfeiting_team == self.home_team: return GameOutcome.AWAY_WIN if home_goals == guest_goals: return GameOutcome.TIE raise ValueError('no matching outcome')
def test_should_return_projects_details_one_streams( get_project_details_use_case: GetProjectDetailsUseCase, find_project_by_project_id: Mock, find_streams_by_project: Mock, ) -> None: project_id = uuid4() project = Project( project_id=project_id, title="Test Project Title", created_at=datetime.now(), status=ProjectStatus.ACTIVE, ) project_maybe: Maybe[Project] = Maybe.from_value(project) streams = [ Stream( stream_id=uuid4(), name="Test Stream", source_type=SourceType.TOPIC, source_name="test_one_stream", ), ] find_project_by_project_id.return_value = Success(project_maybe) find_streams_by_project.return_value = Success(StreamList(streams)) actual = get_project_details_use_case(project_id) find_project_by_project_id.assert_called_once() find_streams_by_project.assert_called_once() find_streams_by_project.assert_called_with(project) assert isinstance(actual, Result.success_type) assert project_id == actual.unwrap().project.project_id assert 1 == len(actual.unwrap().streams) assert streams == actual.unwrap().streams
def __call__(self, project_id: UUID) -> Result[Maybe[Project], FailureDetails]: project = ProjectModel.query.filter( ProjectModel.project_id == project_id).first() maybe_project: Maybe[Project] = Maybe.from_value(project).map( lambda _project: _project.to_entity() # type: ignore ) return Success(maybe_project)
def __call__(self, stream_id: UUID) -> Result[Maybe[Stream], FailureDetails]: stream = StreamModel.query.filter( StreamModel.stream_id == stream_id).first() maybe_stream: Maybe[Stream] = Maybe.from_value(stream).map( lambda _stream: _stream.to_entity() # type: ignore ) return Success(maybe_stream)
def __init__(self, context: Context, image: Optional[Image] = None, padding: Insets = Insets(0, 0, 0, 0), visible: bool = True) -> None: self.image = Maybe.from_optional(image) self.padding = padding super().__init__(context, visible)
def test_should_return_stream_details_correctly( get_stream_details_use_case: GetStreamDetailsUseCase, find_stream_by_stream_id: Mock, find_projects_by_stream: Mock, get_stream_by_name: Mock, ) -> None: stream_id = uuid4() stream = Stream( stream_id=stream_id, name="TEST_STREAM", source_type=SourceType.STREAM, source_name="OTHER_STREAM_TEST", ) project_list = [ Project( project_id=uuid4(), title="Project One", created_at=datetime.now(), status=ProjectStatus.ACTIVE, ), Project( project_id=uuid4(), title="Project Two", created_at=datetime.now(), status=ProjectStatus.INACTIVE, ), ] ksql_stream_detailed = KSQLStreamDetailed( name="TEST_STREAM", fields=[ KSQLStreamDetailed.KSQLStreamField( name="field_one", schema=KSQLStreamDetailed.KSQLStreamField. KSQLStreamFieldSchema(type="INT"), ) ], type="STREAM", format="JSON", topic="SOME_TOPIC", ) stream_details = StreamDetails.build(stream, project_list, ksql_stream_detailed) find_stream_by_stream_id.return_value = Success(Maybe.from_value(stream)) find_projects_by_stream.return_value = Success(project_list) get_stream_by_name.return_value = Success(ksql_stream_detailed) actual = get_stream_details_use_case(stream_id) get_stream_by_name.assert_called_once() get_stream_by_name.assert_called_with(stream.name) assert isinstance(actual, Result.success_type) assert isinstance(actual.unwrap(), StreamDetails) assert stream_details == actual.unwrap()
def __init__(self, toolkit: Toolkit, look_and_feel: Optional[LookAndFeel] = None, font_options: Optional[FontOptions] = None, window_manager: Optional[WindowManager] = None, error_handler: Optional[ErrorHandler] = None) -> None: if toolkit is None: raise ValueError("Argument 'toolkit' is required.") super().__init__() from alleycat.ui import WindowManager from alleycat.ui.glass import GlassLookAndFeel self._toolkit = toolkit self._look_and_feel = Maybe.from_optional(look_and_feel).or_else_call(lambda: GlassLookAndFeel(toolkit)) self._font_options = Maybe.from_optional(font_options).or_else_call( lambda: FontOptions(antialias=ANTIALIAS_SUBPIXEL, hint_style=HINT_STYLE_FULL)) self._error_handler = Maybe.from_optional(error_handler).value_or(toolkit.error_handler) self._window_manager = Maybe.from_optional(window_manager) \ .or_else_call(lambda: WindowManager(self.error_handler)) inputs = toolkit.create_inputs(self) assert inputs is not None self._inputs = {i.id: i for i in inputs} self._pollers = [i for i in inputs if isinstance(i, EventLoopAware)] # noinspection PyTypeChecker self.surface = self.observe("window_size").pipe(ops.map(self.toolkit.create_surface)) old_surface = self.observe("surface").pipe( ops.pairwise(), ops.map(lambda s: s[0]), ops.take_until(self.on_dispose)) old_surface.subscribe(Surface.finish, on_error=self.error_handler)
def test_should_return_failure_not_found_when_project_was_not_found( get_project_details_use_case: GetProjectDetailsUseCase, find_project_by_project_id: Mock, ) -> None: project_id = uuid4() project: Maybe[None] = Maybe.from_value(None) find_project_by_project_id.return_value = Success(project) actual = get_project_details_use_case(project_id) find_project_by_project_id.assert_called_once() assert isinstance(actual, Result.failure_type) assert isinstance(actual.failure(), BusinessFailureDetails) assert "NOT_FOUND" == actual.failure().reason
def result_to_maybe( result_container: Result[_ValueType, _ErrorType], ) -> Maybe[_ValueType]: """ Converts ``Result`` container to ``Maybe`` container. .. code:: python >>> from returns.maybe import Some, Nothing >>> from returns.result import Failure, Success >>> assert result_to_maybe(Success(1)) == Some(1) >>> assert result_to_maybe(Failure(1)) == Nothing >>> assert result_to_maybe(Success(None)) == Nothing >>> assert result_to_maybe(Failure(None)) == Nothing """ return Maybe.from_value(result_container.value_or(None))
def __init__(self, context: Context, layout: Optional[Layout] = None, visible: bool = True): from .layout import AbsoluteLayout self._layout = Maybe.from_optional(layout).or_else_call(AbsoluteLayout) self._layout_pending = True self._layout_running = False # noinspection PyTypeChecker self.children = self.layout.observe("children").pipe( ops.map( lambda children: tuple(map(lambda c: c.component, children)))) super().__init__(context, visible) self.observe("size") \ .pipe(ops.filter(lambda _: self.visible), ops.distinct_until_changed()) \ .subscribe(lambda _: self.request_layout(), on_error=self.error_handler)
def test_should_return_failure_when_get_stream_by_name_fails( get_stream_details_use_case: GetStreamDetailsUseCase, find_stream_by_stream_id: Mock, find_projects_by_stream: Mock, get_stream_by_name: Mock, ) -> None: stream_id = uuid4() stream = Stream( stream_id=stream_id, name="TEST_STREAM", source_type=SourceType.STREAM, source_name="OTHER_STREAM_TEST", ) project_list = [ Project( project_id=uuid4(), title="Project One", created_at=datetime.now(), status=ProjectStatus.ACTIVE, ), Project( project_id=uuid4(), title="Project Two", created_at=datetime.now(), status=ProjectStatus.INACTIVE, ), ] failure = FailureDetails(reason="TEST_FIND_STREAM_BY_NAME_FAILS") find_stream_by_stream_id.return_value = Success(Maybe.from_value(stream)) find_projects_by_stream.return_value = Success(project_list) get_stream_by_name.return_value = Failure(failure) actual = get_stream_details_use_case(stream_id) get_stream_by_name.assert_called_once() get_stream_by_name.assert_called_with(stream.name) assert isinstance(actual, Result.failure_type) assert isinstance(actual.failure(), FailureDetails) assert failure == actual.failure()
def resize_handle_at(self, component: Frame, location: Point) -> Maybe[Direction]: (px, py) = (location - component.offset).tuple (x, y, w, h) = component.bounds.tuple handle: Optional[Direction] = None if y <= py <= y + self.resize_handle_size: handle = Direction.North elif y + h - self.resize_handle_size <= py <= y + h: handle = Direction.South if x + w - self.resize_handle_size <= px <= x + w: if handle is None: handle = Direction.East else: handle = Direction.Northeast if handle == Direction.North else Direction.Southeast elif x <= px <= x + self.resize_handle_size: if handle is None: handle = Direction.West else: handle = Direction.Northwest if handle == Direction.North else Direction.Southwest return Maybe.from_optional(handle)
def test_should_return_failure_when_find_projects_by_stream_fails( get_stream_details_use_case: GetStreamDetailsUseCase, find_stream_by_stream_id: Mock, find_projects_by_stream: Mock, ) -> None: stream_id = uuid4() stream = Stream( stream_id=stream_id, name="TEST_STREAM", source_type=SourceType.STREAM, source_name="OTHER_STREAM_TEST", ) failure = FailureDetails(reason="TEST_FIND_PROJECTS_FAILS") find_stream_by_stream_id.return_value = Success(Maybe.from_value(stream)) find_projects_by_stream.return_value = Failure(failure) actual = get_stream_details_use_case(stream_id) find_projects_by_stream.assert_called_once() find_projects_by_stream.assert_called_with(stream) assert isinstance(actual, Result.failure_type) assert isinstance(actual.failure(), FailureDetails) assert failure == actual.failure()
def get_street_address(order: 'shopping.order.Order') -> Maybe[str]: return Maybe.from_optional( order.user).bind_optional(lambda user: user.address).bind_optional( lambda address: address.street, )
def safe_call(self, func: str, *args, **kwargs) -> Maybe: """ Calls mlflow method, if it's enabled and safely does nothing in the opposite case""" return Maybe.from_value(self._get_mlflow()).bind( lambda obj: Maybe.from_value(getattr(obj, func)(*args, **kwargs)))
def result_to_maybe( result_container: Result[_ValueType, _ErrorType], ) -> Maybe[_ValueType]: """Converts ``Result`` container to ``Maybe`` container.""" return Maybe.new(result_container.value_or(None))
def test_maybe_new_some(): """Ensures that `new` works for Some container.""" assert Maybe.from_value(5) == Some(5)
def test_return_false_with_maybe_container(): """Ensures `is_io` function will return False for Maybe.""" assert is_io(Maybe.from_value(None)) is False
def test_maybe_new_nothing(): """Ensures that `new` works for Nothing container.""" assert Maybe.from_value(None) == Nothing
def test_collect_all_maybe(iterable, sequence): """Iterable for ``Maybe`` and ``CollectAll``.""" assert Maybe.from_iterable(iterable, CollectAll) == sequence
def test_apply_with_maybe(): """Ensures that functions can be composed and return type is correct.""" applied = apply(Maybe.from_value(_function)) assert applied(Some(1)) == Some('2') assert applied(Nothing) == Nothing
) from returns.contrib.pytest import ReturnsAsserts from returns.future import Future, FutureResult from returns.io import IO, IOResult from returns.maybe import Maybe from returns.primitives.asserts import assert_equal from returns.primitives.container import BaseContainer from returns.result import Result _containers: Sequence[BaseContainer] = ( Result.from_failure(1), Result.from_value(1), IO(1), IOResult.from_failure(1), IOResult.from_value(1), Maybe.from_value(1), Maybe.from_value(None), Maybe.from_optional(None), Future.from_value(1), FutureResult.from_value(1), FutureResult.from_failure(1), Reader.from_value(1), ReaderResult.from_value(1), ReaderResult.from_failure(1), ReaderIOResult.from_value(1), ReaderIOResult.from_failure(1), ReaderFutureResult.from_value(1), ReaderFutureResult.from_failure(1), )
def maybe_type(obj: Any, expected: Type[T]) -> Maybe[T]: return Maybe.from_value(obj) if isinstance( obj, not_empty(expected)) else Nothing
def test_fail_fast_maybe(iterable, sequence): """Iterable for ``Maybe`` and ``FailFast``.""" assert Maybe.from_iterable(iterable, FailFast) == sequence
from returns.future import Future, FutureResult from returns.io import IO, IOResult from returns.maybe import Maybe from returns.primitives.asserts import assert_equal from returns.primitives.container import BaseContainer from returns.result import Result _containers: Sequence[BaseContainer] = ( Result.from_failure(1), Result.from_value(1), IO(1), IOResult.from_failure(1), IOResult.from_value(1), Maybe.from_value(1), Maybe.from_value(None), Future.from_value(1), FutureResult.from_value(1), FutureResult.from_failure(1), Reader.from_value(1), ReaderResult.from_value(1), ReaderResult.from_failure(1), ReaderIOResult.from_value(1), ReaderIOResult.from_failure(1), ReaderFutureResult.from_value(1), ReaderFutureResult.from_failure(1), )