|
| 1 | + |
| 2 | +import operator |
| 3 | + |
| 4 | +from pytest import raises |
| 5 | + |
| 6 | +from effect import ( |
| 7 | + ComposedDispatcher, Effect, Error, |
| 8 | + base_dispatcher, sync_perform) |
| 9 | +from effect.fold import FoldError, fold_effect |
| 10 | +from effect.testing import SequenceDispatcher |
| 11 | + |
| 12 | + |
| 13 | +def _base_and(dispatcher): |
| 14 | + """Compose base_dispatcher onto the given dispatcher.""" |
| 15 | + return ComposedDispatcher([dispatcher, base_dispatcher]) |
| 16 | + |
| 17 | + |
| 18 | +def test_fold_effect(): |
| 19 | + """ |
| 20 | + :func:`fold_effect` folds the given function over the results of the |
| 21 | + effects. |
| 22 | + """ |
| 23 | + effs = [Effect('a'), Effect('b'), Effect('c')] |
| 24 | + |
| 25 | + dispatcher = SequenceDispatcher([ |
| 26 | + ('a', lambda i: 'Ei'), |
| 27 | + ('b', lambda i: 'Bee'), |
| 28 | + ('c', lambda i: 'Cee'), |
| 29 | + ]) |
| 30 | + eff = fold_effect(operator.add, 'Nil', effs) |
| 31 | + |
| 32 | + with dispatcher.consume(): |
| 33 | + result = sync_perform(_base_and(dispatcher), eff) |
| 34 | + assert result == 'NilEiBeeCee' |
| 35 | + |
| 36 | + |
| 37 | +def test_fold_effect_empty(): |
| 38 | + """ |
| 39 | + Returns an Effect resulting in the initial value when there are no effects. |
| 40 | + """ |
| 41 | + eff = fold_effect(operator.add, 0, []) |
| 42 | + result = sync_perform(base_dispatcher, eff) |
| 43 | + assert result == 0 |
| 44 | + |
| 45 | + |
| 46 | +def test_fold_effect_errors(): |
| 47 | + """ |
| 48 | + When one of the effects in the folding list fails, a FoldError is raised |
| 49 | + with the accumulator so far. |
| 50 | + """ |
| 51 | + effs = [Effect('a'), Effect(Error(ZeroDivisionError('foo'))), Effect('c')] |
| 52 | + |
| 53 | + dispatcher = SequenceDispatcher([ |
| 54 | + ('a', lambda i: 'Ei'), |
| 55 | + ]) |
| 56 | + |
| 57 | + eff = fold_effect(operator.add, 'Nil', effs) |
| 58 | + |
| 59 | + with dispatcher.consume(): |
| 60 | + with raises(FoldError) as excinfo: |
| 61 | + sync_perform(_base_and(dispatcher), eff) |
| 62 | + assert excinfo.value.accumulator == 'NilEi' |
| 63 | + assert excinfo.value.wrapped_exception[0] is ZeroDivisionError |
| 64 | + assert str(excinfo.value.wrapped_exception[1]) == 'foo' |
0 commit comments