|
| 1 | +# ruff: noqa: D100, D101, D102, D103, D104, D107 |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import replace |
| 6 | +from typing import Generator |
| 7 | + |
| 8 | +import pytest |
| 9 | +from immutable import Immutable |
| 10 | + |
| 11 | +from redux.basic_types import ( |
| 12 | + BaseAction, |
| 13 | + CompleteReducerResult, |
| 14 | + CreateStoreOptions, |
| 15 | + FinishAction, |
| 16 | + FinishEvent, |
| 17 | + InitAction, |
| 18 | + InitializationActionError, |
| 19 | +) |
| 20 | +from redux.main import Store |
| 21 | + |
| 22 | + |
| 23 | +class StateType(Immutable): |
| 24 | + value: int |
| 25 | + |
| 26 | + |
| 27 | +class IncrementAction(BaseAction): ... |
| 28 | + |
| 29 | + |
| 30 | +Action = IncrementAction | InitAction | FinishAction |
| 31 | + |
| 32 | + |
| 33 | +def reducer( |
| 34 | + state: StateType | None, |
| 35 | + action: Action, |
| 36 | +) -> StateType | CompleteReducerResult[StateType, Action, FinishEvent]: |
| 37 | + if state is None: |
| 38 | + if isinstance(action, InitAction): |
| 39 | + return StateType(value=0) |
| 40 | + raise InitializationActionError(action) |
| 41 | + |
| 42 | + if isinstance(action, IncrementAction): |
| 43 | + return replace(state, value=state.value + 1) |
| 44 | + |
| 45 | + return state |
| 46 | + |
| 47 | + |
| 48 | +class StoreType(Store[StateType, Action, FinishEvent]): |
| 49 | + @property |
| 50 | + def state(self: StoreType) -> StateType | None: |
| 51 | + return self._state |
| 52 | + |
| 53 | + |
| 54 | +@pytest.fixture() |
| 55 | +def store() -> Generator[StoreType, None, None]: |
| 56 | + store = StoreType(reducer, options=CreateStoreOptions(auto_init=True)) |
| 57 | + yield store |
| 58 | + |
| 59 | + store.dispatch(FinishAction()) |
| 60 | + |
| 61 | + |
| 62 | +# These tests will timeout if they take a long time to run, indicating a performance |
| 63 | +# issue. |
| 64 | + |
| 65 | + |
| 66 | +def test_simple_dispatch(store: StoreType) -> None: |
| 67 | + count = 100000 |
| 68 | + for _ in range(count): |
| 69 | + store.dispatch(IncrementAction()) |
| 70 | + |
| 71 | + assert store.state is not None |
| 72 | + assert store.state.value == count |
| 73 | + |
| 74 | + |
| 75 | +def test_dispatch_with_subscriptions(store: StoreType) -> None: |
| 76 | + for _ in range(1000): |
| 77 | + |
| 78 | + def callback(_: StateType | None) -> None: |
| 79 | + pass |
| 80 | + |
| 81 | + store.subscribe(callback) |
| 82 | + |
| 83 | + count = 500 |
| 84 | + for _ in range(count): |
| 85 | + store.dispatch(IncrementAction()) |
| 86 | + |
| 87 | + assert store.state is not None |
| 88 | + assert store.state.value == count |
0 commit comments