From 21a3fe541ad5b7f23d99ebe6c2385233986a54b1 Mon Sep 17 00:00:00 2001 From: hurlenko <18035960+hurlenko@users.noreply.github.com> Date: Sat, 24 Aug 2024 18:13:20 +0300 Subject: [PATCH] fix:xrevrange to work with exclusive ranges (#319) --- fakeredis/_stream.py | 6 ++++-- test/test_mixins/test_streams_commands.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/fakeredis/_stream.py b/fakeredis/_stream.py index 4978b0ed..c7b1638c 100644 --- a/fakeredis/_stream.py +++ b/fakeredis/_stream.py @@ -433,9 +433,11 @@ def find_index(self, entry_key: StreamEntryKey, from_left: bool = True) -> Tuple return 0, False if from_left: ind = bisect.bisect_left(self._ids, entry_key) + check_idx = ind else: ind = bisect.bisect_right(self._ids, entry_key) - return ind, (ind < len(self._ids) and self._ids[ind] == entry_key) + check_idx = ind - 1 + return ind, (check_idx < len(self._ids) and self._ids[check_idx] == entry_key) def find_index_key_as_str(self, entry_key_str: Union[str, bytes]) -> Tuple[int, bool]: """Find the closest index to entry_key_str in the stream @@ -500,7 +502,7 @@ def _find_index(elem: StreamRangeTest, from_left: bool = True) -> int: return len(self._ids) ind, found = self.find_index(elem.value, from_left) if found and elem.exclusive: - ind += 1 + ind += 1 if from_left else -1 return ind start_ind = _find_index(start) diff --git a/test/test_mixins/test_streams_commands.py b/test/test_mixins/test_streams_commands.py index 8f4bb13c..53a3894c 100644 --- a/test/test_mixins/test_streams_commands.py +++ b/test/test_mixins/test_streams_commands.py @@ -206,6 +206,26 @@ def test_xrevrange(r: redis.Redis): assert get_ids(results) == [m4] +def test_xrevrange_exclusive(r: redis.Redis): + stream = "stream" + m1, m2, m3, m4 = _add_to_stream(r, stream, 4) + + def _exc(key: bytes) -> bytes: + return b"(" + key + + results = r.xrevrange(stream, max=_exc(m4)) + assert get_ids(results) == [m3, m2, m1] + + results = r.xrevrange(stream, max=_exc(m3), min=m2) + assert get_ids(results) == [m2] + + results = r.xrevrange(stream, min=_exc(m3)) + assert get_ids(results) == [m4] + + results = r.xrevrange(stream, min=_exc(m1)) + assert get_ids(results) == [m4, m3, m2] + + def test_xrange(r: redis.Redis): m = r.xadd("stream1", {"foo": "bar"}) assert r.xrange("stream1") == [