|
| 1 | +# ruff: noqa: D100, D101, D102, D103, D104, D107 |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from dataclasses import replace |
| 5 | +from typing import Literal |
| 6 | + |
| 7 | +import pytest |
| 8 | +from immutable import Immutable |
| 9 | + |
| 10 | +from redux.basic_types import ( |
| 11 | + BaseAction, |
| 12 | + CompleteReducerResult, |
| 13 | + CreateStoreOptions, |
| 14 | + FinishAction, |
| 15 | + FinishEvent, |
| 16 | + InitAction, |
| 17 | + InitializationActionError, |
| 18 | +) |
| 19 | +from redux.main import Store |
| 20 | + |
| 21 | + |
| 22 | +class StateType(Immutable): |
| 23 | + value1: int |
| 24 | + value2: int |
| 25 | + |
| 26 | + |
| 27 | +class IncrementAction(BaseAction): |
| 28 | + which: Literal[1, 2] |
| 29 | + |
| 30 | + |
| 31 | +Action = IncrementAction | InitAction | FinishAction |
| 32 | + |
| 33 | + |
| 34 | +def reducer( |
| 35 | + state: StateType | None, |
| 36 | + action: Action, |
| 37 | +) -> StateType | CompleteReducerResult[StateType, Action, FinishEvent]: |
| 38 | + if state is None: |
| 39 | + if isinstance(action, InitAction): |
| 40 | + return StateType(value1=0, value2=0) |
| 41 | + raise InitializationActionError(action) |
| 42 | + |
| 43 | + if isinstance(action, IncrementAction): |
| 44 | + field_name = f'value{action.which}' |
| 45 | + return replace( |
| 46 | + state, |
| 47 | + **{field_name: getattr(state, field_name) + 1}, |
| 48 | + ) |
| 49 | + |
| 50 | + return state |
| 51 | + |
| 52 | + |
| 53 | +StoreType = Store[StateType, Action, FinishEvent] |
| 54 | + |
| 55 | + |
| 56 | +@pytest.fixture |
| 57 | +def store() -> StoreType: |
| 58 | + return Store(reducer, options=CreateStoreOptions(auto_init=True)) |
| 59 | + |
| 60 | + |
| 61 | +def test_autorun_of_view(store: StoreType) -> None: |
| 62 | + @store.autorun( |
| 63 | + lambda state: state.value2, |
| 64 | + lambda state: (state.value1, state.value2), |
| 65 | + ) |
| 66 | + @store.view(lambda state: state.value1) |
| 67 | + def view(value1: int, value2: int) -> tuple[int, int]: |
| 68 | + return (value1, value2) |
| 69 | + |
| 70 | + assert view() == (0, 0) |
| 71 | + |
| 72 | + store.dispatch(IncrementAction(which=1)) |
| 73 | + |
| 74 | + assert view() == (1, 0) |
| 75 | + |
| 76 | + store.dispatch(IncrementAction(which=2)) |
| 77 | + |
| 78 | + assert view() == (1, 1) |
| 79 | + |
| 80 | + store.dispatch(FinishAction()) |
0 commit comments