From 58116282f69dad432f5fe93b61c0ac90e0ae825a Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Thu, 24 Oct 2024 11:32:21 +0100 Subject: [PATCH] test for loop_from_index --- src/textual/_loop.py | 10 +++++++++- tests/test_loop.py | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/textual/_loop.py b/src/textual/_loop.py index e0ef2b76d..ad4be901f 100644 --- a/src/textual/_loop.py +++ b/src/textual/_loop.py @@ -46,11 +46,17 @@ def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: def loop_from_index( - values: Sequence[T], index: int, direction: Literal[+1, -1] = +1, wrap: bool = True + values: Sequence[T], + index: int, + direction: Literal[-1, +1] = +1, + wrap: bool = True, ) -> Iterable[tuple[int, T]]: """Iterate over values in a sequence from a given starting index, potentially wrapping the index if it would go out of bounds. + Note that the first value to be yielded is a step from `index`, and `index` will be yielded *last*. + + Args: values: A sequence of values. index: Starting index. @@ -60,6 +66,8 @@ def loop_from_index( Yields: A tuple of index and value from the sequence. """ + # Sanity check for devs who miss the typing errors + assert direction in (-1, +1), "direction must be -1 or +1" count = len(values) if wrap: for _ in range(count): diff --git a/tests/test_loop.py b/tests/test_loop.py index 87ef97da7..65b0aa009 100644 --- a/tests/test_loop.py +++ b/tests/test_loop.py @@ -1,4 +1,4 @@ -from textual._loop import loop_first, loop_first_last, loop_last +from textual._loop import loop_first, loop_first_last, loop_from_index, loop_last def test_loop_first(): @@ -26,3 +26,40 @@ def test_loop_first_last(): assert next(iterable) == (False, False, "oranges") assert next(iterable) == (False, False, "pears") assert next(iterable) == (False, True, "lemons") + + +def test_loop_from_index(): + assert list(loop_from_index("abcdefghij", 3)) == [ + (4, "e"), + (5, "f"), + (6, "g"), + (7, "h"), + (8, "i"), + (9, "j"), + (0, "a"), + (1, "b"), + (2, "c"), + (3, "d"), + ] + + assert list(loop_from_index("abcdefghij", 3, direction=-1)) == [ + (2, "c"), + (1, "b"), + (0, "a"), + (9, "j"), + (8, "i"), + (7, "h"), + (6, "g"), + (5, "f"), + (4, "e"), + (3, "d"), + ] + + assert list(loop_from_index("abcdefghij", 3, wrap=False)) == [ + (4, "e"), + (5, "f"), + (6, "g"), + (7, "h"), + (8, "i"), + (9, "j"), + ]