Skip to content

Commit eca91fb

Browse files
committed
Nice error message for empty buffer and new test case
Signed-off-by: Jack <[email protected]>
1 parent ac913e7 commit eca91fb

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/frequenz/sdk/timeseries/_moving_window.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,8 @@ def __getitem__(self, key: SupportsIndex | datetime | slice) -> float | ArrayLik
305305
A float if the key is a number or a timestamp.
306306
an numpy array if the key is a slice.
307307
"""
308+
if len(self._buffer) == 0:
309+
raise IndexError("The buffer is empty.")
308310
if isinstance(key, slice):
309311
if isinstance(key.start, int) or isinstance(key.stop, int):
310312
if key.start is None or key.stop is None:
@@ -327,6 +329,7 @@ def __getitem__(self, key: SupportsIndex | datetime | slice) -> float | ArrayLik
327329
_logger.debug("Returning value at time %s ", key)
328330
return self._buffer[self._buffer.datetime_to_index(key)]
329331
elif isinstance(key, SupportsIndex):
332+
_logger.debug("Returning value at index %s ", key)
330333
return self._buffer[key]
331334

332335
raise TypeError(

tests/timeseries/test_moving_window.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ async def test_access_window_by_ts_slice() -> None:
111111
assert np.array_equal(window[time_start:time_end], np.array([3.0, 4.0])) # type: ignore
112112

113113

114+
async def test_access_empty_window() -> None:
115+
"""Test accessing an empty window, should throw IndexError"""
116+
window, _ = init_moving_window(timedelta(seconds=5))
117+
try:
118+
window[42]
119+
except IndexError as index_error:
120+
assert str(index_error) == "The buffer is empty."
121+
else:
122+
assert False
123+
124+
114125
async def test_window_size() -> None:
115126
"""Test the size of the window."""
116127
window, sender = init_moving_window(timedelta(seconds=5))

0 commit comments

Comments
 (0)