Skip to content

Commit 7950fdb

Browse files
Test resampling in MovingWindow
Signed-off-by: Daniel Zullo <[email protected]>
1 parent 0973670 commit 7950fdb

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

tests/timeseries/test_moving_window.py

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,33 @@
55

66
import asyncio
77
from datetime import datetime, timedelta, timezone
8-
from typing import Sequence, Tuple
8+
from typing import Iterator, Sequence, Tuple
99

10+
import async_solipsism
1011
import numpy as np
12+
import pytest
13+
import time_machine
1114
from frequenz.channels import Broadcast, Sender
1215

1316
from frequenz.sdk.timeseries import Sample
1417
from frequenz.sdk.timeseries._moving_window import MovingWindow
18+
from frequenz.sdk.timeseries._resampling import ResamplerConfig
19+
20+
21+
# Setting 'autouse' has no effect as this method replaces the event loop for all tests in the file.
22+
@pytest.fixture()
23+
def event_loop() -> Iterator[async_solipsism.EventLoop]:
24+
"""Replace the loop with one that doesn't interact with the outside world."""
25+
loop = async_solipsism.EventLoop()
26+
yield loop
27+
loop.close()
28+
29+
30+
@pytest.fixture
31+
def fake_time() -> Iterator[time_machine.Coordinates]:
32+
"""Replace real time with a time machine that doesn't automatically tick."""
33+
with time_machine.travel(0, tick=False) as traveller:
34+
yield traveller
1535

1636

1737
async def push_lm_data(sender: Sender[Sample], test_seq: Sequence[float]) -> None:
@@ -82,3 +102,36 @@ async def test_window_size() -> None:
82102
window, sender = init_moving_window(timedelta(seconds=5))
83103
await push_lm_data(sender, range(0, 20))
84104
assert len(window) == 5
105+
106+
107+
# pylint: disable=redefined-outer-name
108+
async def test_resampling_window(fake_time: time_machine.Coordinates) -> None:
109+
"""Test resampling in MovingWindow."""
110+
channel = Broadcast[Sample]("net_power")
111+
sender = channel.new_sender()
112+
113+
window_size = timedelta(seconds=16)
114+
input_sampling = timedelta(seconds=1)
115+
output_sampling = timedelta(seconds=2)
116+
resampler_config = ResamplerConfig(
117+
resampling_period_s=output_sampling.total_seconds()
118+
)
119+
120+
window = MovingWindow(
121+
size=window_size,
122+
resampled_data_recv=channel.new_receiver(),
123+
input_sampling_period=input_sampling,
124+
resampler_config=resampler_config,
125+
)
126+
127+
stream_values = [4.0, 8.0, 2.0, 6.0, 5.0] * 100
128+
for value in stream_values:
129+
timestamp = datetime.now(tz=timezone.utc)
130+
sample = Sample(timestamp, float(value))
131+
await sender.send(sample)
132+
await asyncio.sleep(0.1)
133+
fake_time.shift(0.1)
134+
135+
assert len(window) == window_size / output_sampling
136+
for value in window: # type: ignore
137+
assert 4.9 < value < 5.1

0 commit comments

Comments
 (0)