from layercake.batch import BatchProcessor, Result, Status

processor = BatchProcessor()


def test_batch():
    def record_handler(record: bool):
        if record:
            return True
        raise ValueError('Invalid record')

    records = (
        True,
        True,
        False,
    )

    with processor(records=records, handler=record_handler) as p:
        processed_messages = p.process()

        assert processed_messages == (
            Result(Status.SUCCESS, True, True),
            Result(Status.SUCCESS, True, True),
            Result(Status.FAIL, 'ValueError: Invalid record', False),
        )

    assert processor.successes == [True, True]
    assert processor.failures == [False]

    with processor(records=(False,), handler=record_handler):
        processed_messages = processor.process()

        assert processed_messages == (
            Result(Status.FAIL, 'ValueError: Invalid record', False),
        )

    assert processor.successes == []
    assert processor.failures == [False]


def test_batch_context():
    def record_handler(val: int, context: dict):
        return val * context['multiplier']

    with processor(
        records=(2, 3, 4),
        handler=record_handler,
        context={'multiplier': 2},
    ):
        processed_messages = processor.process()

        assert processed_messages == (
            Result(Status.SUCCESS, 4, 2),
            Result(Status.SUCCESS, 6, 3),
            Result(Status.SUCCESS, 8, 4),
        )
