def test_if_in_condition_array_value():
    """Test that we can do if in statement on arrays."""
    test = [
        ['target_value'],
        [
            {
                'condition': 'in',
                'target': [['target_value']],
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
 def select_room_types(self, ctx: Context) -> ResultE[Context]:
     try:
         data = self._roomtypes_repo.select(ctx.house,
                                            user=ctx.user,
                                            detailed=False)
     except Exception as err:
         return self._error(
             f"Error select Room Types for House ID={ctx.house.id}",
             ctx,
             self._case_errors.error,
             exc=err)
     ctx.room_types = {x.id: x for x in data}
     return Success(ctx)
def test_if_in():
    """Test that 1 if (in) statement works."""
    test = [
        'target_value',
        [
            {
                'condition': 'in',
                'target': ['target_value'],
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
def test_if_in_condition_false():
    """Test if in condition False."""
    test = [
        'not_target_value',
        [
            {
                'condition': 'in',
                'target': 'target_value',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('not_target_value')
async def test_inner_value(subtests):
    """Ensure that coroutine correct value is preserved for all units."""
    containers = [
        # We have to define these values inside the test, because
        # otherwise `anyio` will `await` reused coroutines.
        # And they have to be fresh. That's why we use subtests for it.
        FutureResult.from_value(1),
        FutureResult.from_failure(1),
        FutureResult.from_io(IO(1)),
        FutureResult.from_failed_io(IO(1)),
        FutureResult.from_ioresult(IOSuccess(1)),
        FutureResult.from_ioresult(IOFailure(1)),
        FutureResult.from_result(Success(1)),
        FutureResult.from_result(Failure(1)),
        FutureResult.from_future(Future.from_value(1)),
        FutureResult.from_failed_future(Future.from_value(1)),
        FutureResult.from_typecast(Future.from_value(Success(1))),
    ]
    for container in containers:
        with subtests.test(container=container):
            result_inst = await container
            assert result_inst._inner_value._inner_value == 1  # noqa: WPS437
 def write_changelog(self, ctx: Context) -> ResultE[Context]:
     try:
         self._changelog_repo.create(
             ctx.user,
             None,
             ctx.reservation,
             ChangelogActions.CREATE,
             house=ctx.house,
             message='Create a new Reservation',
         )
     except Exception as err:
         Logger.warning(__name__, f"Error write changelog: {err}")
     return Success(ctx)
def test_if_contains():
    """Test that 1 if (contains) statement works."""
    test = [
        'target_value',
        [
            {
                'condition': 'contains',
                'target': '_value',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 8
0
 def check_reservation(self, ctx: Context) -> ResultE[Context]:
     if ctx.reservation.house_id != ctx.house.id:
         return self._error(
             f"Reservation ID={ctx.reservation.id} has House ID={ctx.reservation.house_id} "
             f"but needs to be House ID={ctx.house.id}",
             ctx,
             self._case_errors.missed_reservation,
         )
     if ctx.reservation.status == ReservationStatuses.CLOSE:
         return self._error(
             f"Reservation ID={ctx.reservation.id} is Room-Close", ctx,
             self._case_errors.missed_reservation)
     return Success(ctx)
def test_if_is():
    """Test that 1 if (is) statement works."""
    test = [
        'target_value',
        [
            IfStatement(**{
                'condition': 'is',
                'target': 'target_value',
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
def test_if_not():
    """Test that 1 if (not) statement works."""
    test = [
        'target_value',
        [
            {
                'condition': 'not',
                'target': 'not_target',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 11
0
def test_if_is_condition_objects_value():
    """Test that we can do if is statement on objectss."""
    test = [
        {'val': 'target'},
        [
            IfStatement(**{
                'condition': 'is',
                'target': {'val': 'target'},
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 12
0
def test_if_is_condition_array_value():
    """Test that we can do if is statement on arrays."""
    test = [
        ['target_value'],
        [
            IfStatement(**{
                'condition': 'is',
                'target': ['target_value'],
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 13
0
def test_if_contains_objects_in_array_value():
    """Test that we can do if contains statement on objectss."""
    test = [
        [{'val': 'target'}],
        [
            IfStatement(**{
                'condition': 'contains',
                'target': {'val': 'target'},
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 14
0
def test_if_is_condition_false():
    """Test if condition False."""
    test = [
        'not_target_value',
        [
            IfStatement(**{
                'condition': 'is',
                'target': 'target_value',
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('not_target_value')
def test_if_contains_condition_false():
    """Test if contains condition False."""
    test = [
        'not_target_value',
        [
            {
                'condition': 'contains',
                'target': 'does_not_contain',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('not_target_value')
 def accept_changes(self, ctx: Context) -> ResultE[Context]:
     if ctx.source.is_verified:
         ctx.reservation = ctx.source
         return Success(ctx)
     try:
         data = self._reservations_repo.accept(ctx.source.id,
                                               price_ids=ctx.price_ids)
     except Exception as err:
         return self._error(
             f"Error accept changes for Reservation ID={ctx.source.id} in House ID={ctx.house.id}",
             ctx,
             self._case_errors.error,
             exc=err,
         )
     if data == Nothing:
         return self._error(
             f"Error accept changes for Reservation ID={ctx.source.id} in House ID={ctx.house.id}",
             ctx,
             self._case_errors.error,
         )
     ctx.reservation = data.unwrap()
     return Success(ctx)
def test_if_contains_condition_array_value():
    """Test that we can do if contains statement on arrays."""
    test = [
        ['value', 'target'],
        [
            {
                'condition': 'contains',
                'target': 'target',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 18
0
    def execute(self, house_id: int, pk: int, user: '******') -> ResultE[bool]:
        ctx = Context(house_id=house_id, pk=pk, user=user)

        return flow(
            ctx,
            self.select_house,
            bind_result(self.select_reservation),
            bind_result(self.check_reservation),
            bind_result(self.accept_reservation),
            bind_result(self.confirm_quotation),
            bind_result(self.write_changelog),
            bind_result(lambda x: Success(True)),
        )
def test_if_contains_works_with_non_strings():
    """Test that we can do if contains statement on objectss."""
    test = [
        123,
        [
            {
                'condition': 'contains',
                'target': '123',
                'then': 'value2',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 20
0
def IOSuccess(  # noqa: N802
        inner_value: _NewValueType, ) -> IOResult[_NewValueType, Any]:
    """
    Public unit function of successful :class:`~IOResult` container.

    .. code:: python

      >>> from returns.io import IOSuccess
      >>> str(IOSuccess(1))
      '<IOResult: <Success: 1>>'

    """
    return _IOSuccess(Success(inner_value))
Esempio n. 21
0
 def cancel_reservation(self, ctx: Context) -> ResultE[Context]:
     """Change reservation status and save to repository"""
     if ctx.source.status == ReservationStatuses.CANCEL:
         # Reservation was canceled before
         ctx.reservation = ctx.source
         return Success(ctx)
     ctx.reservation = attr.evolve(ctx.source,
                                   status=ReservationStatuses.CANCEL)
     try:
         data, __ = self._reservations_repo.save(ctx.reservation)
     except Exception as err:
         return self._error(
             f"Error save Reservation ID={ctx.reservation.id}",
             ctx,
             self._case_errors.error,
             exc=err)
     if data == Nothing:
         return self._error(
             f"Error save canceled Reservation ID={ctx.reservation.id}",
             ctx, self._case_errors.error)
     ctx.reservation = data.unwrap()
     return Success(ctx)
Esempio n. 22
0
def test_if_not_condition_array_value_with_int():
    """Test that we can do if not statement on arrays."""
    test = [
        [123],
        [
            IfStatement(**{
                'condition': 'is',
                'target': [123],
                'then': 'value2',
            }),
        ],
    ]
    assert apply_if_statements(*test) == Success('value2')
Esempio n. 23
0
 def __call__(
     self, creat_new_stream_command: CreateNewStreamCommand
 ) -> Result[Stream, FailureDetails]:
     stream = StreamModel(
         name=creat_new_stream_command.stream_name,
         source_type=creat_new_stream_command.source_type,
         source_name=creat_new_stream_command.source_name,
     )
     stream_project = StreamProjectModel(
         stream=stream, project_id=creat_new_stream_command.project_id)
     with database_session() as session:
         session.add(stream_project)
         session.commit()
         return Success(stream.to_entity())
Esempio n. 24
0
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
Esempio n. 25
0
    def get_lightcurve(self, payload: LightcurveServicePayload) -> dict:
        detections = self.get_detections(payload)
        non_detections = self.get_non_detections(payload)
        light_curve_data = [detections, non_detections]
        failure = get_failure_from_list(results_list=light_curve_data)
        if failure:
            return failure
        else:
            light_curve = {
                "detections": light_curve_data[0].unwrap(),
                "non_detections": light_curve_data[1].unwrap(),
            }

            return Success(light_curve)
    def from_value(
        cls, inner_value: _FirstType,
    ) -> RequiresContextResult[_FirstType, Any, NoDeps]:
        """
        Creates new container with ``Success(inner_value)`` as a unit value.

        .. code:: python

          >>> from returns.context import RequiresContextResult
          >>> from returns.result import Success
          >>> assert RequiresContextResult.from_value(1)(...) == Success(1)

        """
        return RequiresContextResult(lambda _: Success(inner_value))
Esempio n. 27
0
def test_if_failed_condition_goes_to_otherwise():
    """Test that we get the then value when condition fails."""
    test = [
        'not_target_value',
        [
            {
                'condition': 'is',
                'target': 'target_value',
                'then': 'no',
                'otherwise': 'yes',
            },
        ],
    ]
    assert apply_if_statements(*test) == Success('yes')
Esempio n. 28
0
    def _get_object_by_id(self, object_id: str, survey_id: str):
        try:
            query_result = (self.db.query(psql_models.Object).filter(
                psql_models.Object.oid == object_id).one_or_none())

            if query_result:
                return Success(query_result)
            else:
                return Failure(
                    ClientErrorException(
                        ObjectNotFound(object_id=object_id,
                                       survey_id=survey_id)))
        except Exception as e:
            return Failure(ServerErrorException(e))
 def select_reservation_room(self, ctx: Context) -> ResultE[Context]:
     pk = cf.get_int_or_none(ctx.room_id) or 0
     if pk <= 0:
         return self._error('Missed Reservation Room ID', ctx,
                            self._case_errors.missed_reservation)
     rooms = {x.id: x for x in ctx.reservation.rooms}
     if pk not in rooms:
         return self._error(
             f"Unknown Room ID={pk} in Reservation ID={ctx.reservation.id} House ID={ctx.house.id}",
             ctx,
             self._case_errors.missed_reservation,
         )
     ctx.reservation_room = rooms[pk]
     return Success(ctx)
 def write_changelog(self, ctx: Context) -> ResultE[Context]:
     try:
         self._changelog_repo.create_manual(
             ctx.user,
             ctx.reservation,
             ChangelogActions.CREATE,
             {},
             house=ctx.house,
             message=
             f"Close Room [{ctx.room.name}] for {ctx.start_date.isoformat()}..{ctx.end_date.isoformat()}",
         )
     except Exception as err:
         Logger.warning(__name__, f"Error write changelog: {err}")
     return Success(ctx)