-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathtest_resampling.py
More file actions
1696 lines (1501 loc) · 59.7 KB
/
test_resampling.py
File metadata and controls
1696 lines (1501 loc) · 59.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# License: MIT
# Copyright © 2022 Frequenz Energy-as-a-Service GmbH
"""Tests for the `TimeSeriesResampler` class."""
import asyncio
import logging
from collections.abc import AsyncIterator
from datetime import datetime, timedelta, timezone
from typing import Literal
from unittest.mock import AsyncMock, MagicMock
import async_solipsism
import pytest
import time_machine
from frequenz.channels import Broadcast, SenderError
from frequenz.quantities import Quantity
from frequenz.sdk.timeseries import (
DEFAULT_BUFFER_LEN_MAX,
DEFAULT_BUFFER_LEN_WARN,
ResamplerConfig,
ResamplerConfig2,
ResamplingFunction,
Sample,
Sink,
Source,
SourceProperties,
)
from frequenz.sdk.timeseries._resampling._exceptions import (
ResamplingError,
SourceStoppedError,
)
from frequenz.sdk.timeseries._resampling._resampler import Resampler, _ResamplingHelper
from ..utils import a_sequence
# We relax some pylint checks as for tests they don't make a lot of sense for this test.
# pylint: disable=too-many-lines,disable=too-many-locals
@pytest.fixture(autouse=True)
def event_loop_policy() -> async_solipsism.EventLoopPolicy:
"""Return an event loop policy that uses the async solipsism event loop."""
return async_solipsism.EventLoopPolicy()
@pytest.fixture
async def source_chan() -> AsyncIterator[Broadcast[Sample[Quantity]]]:
"""Create a broadcast channel of samples."""
chan = Broadcast[Sample[Quantity]](name="test")
yield chan
await chan.close()
def as_float_tuple(sample: Sample[Quantity]) -> tuple[datetime, float]:
"""Convert a sample to a tuple of datetime and float value."""
assert sample.value is not None, "Sample value should not be None"
return (sample.timestamp, sample.value.base_value)
async def _advance_time(fake_time: time_machine.Coordinates, seconds: float) -> None:
"""Advance the time by the given number of seconds.
This advances both the wall clock and the time machine fake time.
Args:
fake_time: The time machine fake time.
seconds: The number of seconds to advance the time by.
"""
await asyncio.sleep(seconds)
fake_time.shift(seconds)
# pylint: disable-next=too-many-arguments,too-many-positional-arguments
async def _assert_no_more_samples(
resampler: Resampler,
initial_time: datetime,
sink_mock: AsyncMock,
resampling_fun_mock: MagicMock,
fake_time: time_machine.Coordinates,
resampling_period_s: float,
current_iteration: int,
) -> None:
"""Assert that no more samples are received, so resampling emits None."""
# Resample 3 more times making sure no more valid samples are used
for i in range(3):
# Third resampling run (no more samples)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
iteration_delta = resampling_period_s * (current_iteration + i)
iteration_time = initial_time + timedelta(seconds=iteration_delta)
assert datetime.now(timezone.utc) == iteration_time
sink_mock.assert_called_once_with(Sample(iteration_time, None))
resampling_fun_mock.assert_not_called()
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
@pytest.mark.parametrize("init_len", list(range(1, DEFAULT_BUFFER_LEN_WARN + 1, 16)))
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampler_config_len_ok(
init_len: int,
config_class: type[ResamplerConfig],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test checks on the resampling buffer."""
config = config_class(
resampling_period=timedelta(seconds=1.0),
initial_buffer_len=init_len,
)
assert config.initial_buffer_len == init_len
# Ignore errors produced by wrongly finalized gRPC server in unrelated tests
assert _filter_logs(caplog.record_tuples, logger_name="") == []
@pytest.mark.parametrize(
"init_len",
range(DEFAULT_BUFFER_LEN_WARN + 1, DEFAULT_BUFFER_LEN_MAX + 1, 64),
)
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampler_config_len_warn(
init_len: int, config_class: type[ResamplerConfig], caplog: pytest.LogCaptureFixture
) -> None:
"""Test checks on the resampling buffer."""
config = config_class(
resampling_period=timedelta(seconds=1.0),
initial_buffer_len=init_len,
)
assert config.initial_buffer_len == init_len
# Ignore errors produced by wrongly finalized gRPC server in unrelated tests
assert _filter_logs(
caplog.record_tuples, logger_name="frequenz.sdk.timeseries._resampling._config"
) == [
(
"frequenz.sdk.timeseries._resampling._config",
logging.WARNING,
f"initial_buffer_len ({init_len}) is bigger than "
f"warn_buffer_len ({DEFAULT_BUFFER_LEN_WARN})",
)
]
@pytest.mark.parametrize(
"init_len",
list(range(-2, 1)) + [DEFAULT_BUFFER_LEN_MAX + 1, DEFAULT_BUFFER_LEN_MAX + 2],
)
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampler_config_len_error(
init_len: int, config_class: type[ResamplerConfig]
) -> None:
"""Test checks on the resampling buffer."""
with pytest.raises(ValueError):
_ = config_class(
resampling_period=timedelta(seconds=1.0),
initial_buffer_len=init_len,
)
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_helper_buffer_too_big(
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test checks on the resampling buffer."""
config = config_class(
resampling_period=timedelta(seconds=DEFAULT_BUFFER_LEN_MAX + 1),
max_data_age_in_periods=1,
)
helper = _ResamplingHelper("test", config)
for i in range(DEFAULT_BUFFER_LEN_MAX + 1):
sample = (datetime.now(timezone.utc), i)
helper.add_sample(sample)
await _advance_time(fake_time, 1)
_ = helper.resample(datetime.now(timezone.utc))
# Ignore errors produced by wrongly finalized gRPC server in unrelated tests
assert (
"frequenz.sdk.timeseries._resampling._resampler",
logging.ERROR,
f"The new buffer length ({DEFAULT_BUFFER_LEN_MAX + 1}) "
f"for timeseries test is too big, using {DEFAULT_BUFFER_LEN_MAX} instead",
) in _filter_logs(
caplog.record_tuples,
)
# pylint: disable=protected-access
assert helper._buffer.maxlen == DEFAULT_BUFFER_LEN_MAX
@pytest.mark.parametrize(
"resampling_period_s,now,align_to,result",
(
(
1.0,
datetime(2020, 1, 1, 2, 3, 5, 300000, tzinfo=timezone.utc),
datetime(2020, 1, 1, tzinfo=timezone.utc),
(
datetime(2020, 1, 1, 2, 3, 7, tzinfo=timezone.utc),
timedelta(seconds=0.7),
),
),
(
3.0,
datetime(2020, 1, 1, 2, 3, 5, 300000, tzinfo=timezone.utc),
datetime(2020, 1, 1, 0, 0, 5, tzinfo=timezone.utc),
(
datetime(2020, 1, 1, 2, 3, 11, tzinfo=timezone.utc),
timedelta(seconds=2.7),
),
),
(
10.0,
datetime(2020, 1, 1, 2, 3, 5, 300000, tzinfo=timezone.utc),
datetime(2020, 1, 1, 0, 0, 5, tzinfo=timezone.utc),
(
datetime(2020, 1, 1, 2, 3, 25, tzinfo=timezone.utc),
timedelta(seconds=9.7),
),
),
# Future align_to
(
10.0,
datetime(2020, 1, 1, 2, 3, 5, 300000, tzinfo=timezone.utc),
datetime(2020, 1, 1, 2, 3, 18, tzinfo=timezone.utc),
(
datetime(2020, 1, 1, 2, 3, 18, tzinfo=timezone.utc),
timedelta(seconds=2.7),
),
),
),
)
async def test_calculate_window_end_trivial_cases(
fake_time: time_machine.Coordinates,
resampling_period_s: float,
now: datetime,
align_to: datetime,
result: tuple[datetime, timedelta],
) -> None:
"""Test the calculation of the resampling window end for simple cases."""
resampling_period = timedelta(seconds=resampling_period_s)
resampler = Resampler(
ResamplerConfig(
resampling_period=resampling_period,
align_to=align_to,
)
)
fake_time.move_to(now)
# pylint: disable-next=protected-access
assert resampler._calculate_window_end() == result
# Repeat the test with align_to=None, so the result should be align to now
# instead
resampler_now = Resampler(
ResamplerConfig(
resampling_period=resampling_period,
align_to=now,
)
)
resampler_none = Resampler(
ResamplerConfig(
resampling_period=resampling_period,
align_to=None,
)
)
fake_time.move_to(now)
# pylint: disable=protected-access
none_result = resampler_none._calculate_window_end()
assert resampler_now._calculate_window_end() == none_result
assert none_result[0] == now + resampling_period
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampling_window_size_is_constant(
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
) -> None:
"""Test resampling window size is consistent."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = config_class(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=1.0,
resampling_function=resampling_fun_mock,
initial_buffer_len=4,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# t(s) 0 1 2 2.5 3 4
# |----------|----------R----|-----|----------R-----> (no more samples)
# value 5.0 12.0 2.0 4.0 5.0
#
# R = resampling is done
# Send a few samples and run a resample tick, advancing the fake time by one period
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1), value=Quantity(12.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
await _advance_time(
fake_time, resampling_period_s
) # timer matches resampling period
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 2
assert asyncio.get_event_loop().time() == 2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(as_float_tuple(sample1s)), config, source_props
)
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Second resampling run
sample2_5s = Sample(timestamp + timedelta(seconds=2.5), value=Quantity(2.0))
sample3s = Sample(timestamp + timedelta(seconds=3), value=Quantity(4.0))
sample4s = Sample(timestamp + timedelta(seconds=4), value=Quantity(5.0))
await source_sender.send(sample2_5s)
await source_sender.send(sample3s)
await source_sender.send(sample4s)
await _advance_time(
fake_time, resampling_period_s + 0.5
) # Timer fired with some delay
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 4.5
sink_mock.assert_called_once_with(
Sample(
# But the sample still gets 4s as timestamp, because we are keeping
# the window size constant, not dependent on when the timer fired
timestamp + timedelta(seconds=resampling_period_s * 2),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample2_5s),
as_float_tuple(sample3s),
as_float_tuple(sample4s),
),
config,
source_props,
)
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Not parametrized because now warnings are handled by the wall clock timer when the
# wall clock timer is used, not the resampler, so it should be tested in the wall clock
# timer tests.
async def test_timer_errors_are_logged( # pylint: disable=too-many-statements
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that big differences between the expected window end and the fired timer are logged."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = ResamplerConfig(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=2.0,
resampling_function=resampling_fun_mock,
initial_buffer_len=4,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# trigger T = 2.0 T = 4.1998 T = 6.3998
# t(s) 0 1 2 2.5 3 4|4.5 5 6 |
# |-----|-----R--|--|-----R+-|--|-----R---+---> (no more samples)
# value 5.0 12.0 2.0 4.0 5.0 2.0 4.0 5.0
#
# R = resampling is done
# T = timer tick
# Send a few samples and run a resample tick, advancing the fake time by one period
# No log message should be produced
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1.0), value=Quantity(12.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
# Here we need to advance only the wall clock because the resampler timer is not yet
# started, otherwise the loop time will be advanced twice
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == pytest.approx(2)
assert asyncio.get_running_loop().time() == pytest.approx(2)
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample0s),
as_float_tuple(sample1s),
),
config,
source_props,
)
assert not [
*_filter_logs(
caplog.record_tuples,
logger_level=logging.WARNING,
)
]
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Second resampling run, now with 9.99% delay
sample2_5s = Sample(timestamp + timedelta(seconds=2.5), value=Quantity(2.0))
sample3s = Sample(timestamp + timedelta(seconds=3), value=Quantity(4.0))
sample4s = Sample(timestamp + timedelta(seconds=4), value=Quantity(5.0))
await source_sender.send(sample2_5s)
await source_sender.send(sample3s)
await source_sender.send(sample4s)
await _advance_time(
fake_time, resampling_period_s * 1.0999
) # Timer is delayed 9.99%
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == pytest.approx(4.1998)
assert asyncio.get_running_loop().time() == pytest.approx(4.1998)
sink_mock.assert_called_once_with(
Sample(
# But the sample still gets 4s as timestamp, because we are keeping
# the window size constant, not dependent on when the timer fired
timestamp + timedelta(seconds=resampling_period_s * 2),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample1s),
as_float_tuple(sample2_5s),
as_float_tuple(sample3s),
as_float_tuple(sample4s),
),
config,
source_props,
)
assert not [
*_filter_logs(
caplog.record_tuples,
logger_level=logging.WARNING,
)
]
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Third resampling run, now with 10% delay
sample4_5s = Sample(timestamp + timedelta(seconds=4.5), value=Quantity(2.0))
sample5s = Sample(timestamp + timedelta(seconds=5), value=Quantity(4.0))
sample6s = Sample(timestamp + timedelta(seconds=6), value=Quantity(5.0))
await source_sender.send(sample4_5s)
await source_sender.send(sample5s)
await source_sender.send(sample6s)
await _advance_time(fake_time, resampling_period_s * 1.10) # Timer delayed 10%
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == pytest.approx(6.3998)
assert asyncio.get_running_loop().time() == pytest.approx(6.3998)
sink_mock.assert_called_once_with(
Sample(
# But the sample still gets 4s as timestamp, because we are keeping
# the window size constant, not dependent on when the timer fired
timestamp + timedelta(seconds=resampling_period_s * 3),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample3s),
as_float_tuple(sample4s),
as_float_tuple(sample4_5s),
as_float_tuple(sample5s),
as_float_tuple(sample6s),
),
config,
source_props,
)
assert (
"frequenz.sdk.timeseries._resampling._resampler",
logging.WARNING,
"The resampling task woke up too late. Resampling should have started at "
"1970-01-01 00:00:06+00:00, but it started at 1970-01-01 "
"00:00:06.399800+00:00 (tolerance: 0:00:00.200000, difference: "
"0:00:00.399800; resampling period: 0:00:02)",
) in _filter_logs(caplog.record_tuples, logger_level=logging.WARNING)
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_future_samples_not_included(
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
) -> None:
"""Test that future samples are not included in the resampling."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = config_class(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=2.0,
resampling_function=resampling_fun_mock,
initial_buffer_len=4,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# t(s) 0 1 1.9 2 3 4 4.1 4.2
# |----------|--------|--R----------|----------R--|---|------------>
# value 5.0 7.0 4.0 3.0 timer fires
# (with ts=2.1)
#
# R = resampling is done
# Send a few samples and run a resample tick, advancing the fake time by one period
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1), value=Quantity(12.0))
sample2_1s = Sample(timestamp + timedelta(seconds=2.1), value=Quantity(7.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
await source_sender.send(sample2_1s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample0s),
as_float_tuple(sample1s),
),
config,
source_props, # sample2_1s is not here
)
assert source_props == SourceProperties(
sampling_start=timestamp, received_samples=3, sampling_period=None
)
assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Second resampling run
sample3s = Sample(timestamp + timedelta(seconds=3), value=Quantity(4.0))
sample4_1s = Sample(timestamp + timedelta(seconds=4.1), value=Quantity(3.0))
await source_sender.send(sample3s)
await source_sender.send(sample4_1s)
await _advance_time(fake_time, resampling_period_s + 0.2)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 4.2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s * 2),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample1s),
as_float_tuple(sample2_1s),
as_float_tuple(sample3s),
),
config,
source_props, # sample4_1s is not here
)
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampling_with_one_window(
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
) -> None:
"""Test resampling with one resampling window (saving samples of the last period only)."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = config_class(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=1.0,
resampling_function=resampling_fun_mock,
initial_buffer_len=4,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# t(s) 0 1 2 2.5 3 4
# |----------|----------R----|-----|----------R-----> (no more samples)
# value 5.0 12.0 0.0 4.0 5.0
#
# R = resampling is done
# Send a few samples and run a resample tick, advancing the fake time by one period
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1), value=Quantity(12.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample1s),
),
config,
source_props,
)
assert source_props == SourceProperties(
sampling_start=timestamp, received_samples=2, sampling_period=None
)
assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Second resampling run
sample2_5s = Sample(timestamp + timedelta(seconds=2.5), value=Quantity.zero())
sample3s = Sample(timestamp + timedelta(seconds=3), value=Quantity(4.0))
sample4s = Sample(timestamp + timedelta(seconds=4), value=Quantity(5.0))
await source_sender.send(sample2_5s)
await source_sender.send(sample3s)
await source_sender.send(sample4s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 4
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s * 2),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample2_5s),
as_float_tuple(sample3s),
as_float_tuple(sample4s),
),
config,
source_props,
)
# By now we have a full buffer (5 samples and a buffer of length 4), which
# we received in 4 seconds, so we have an input period of 0.8s.
assert source_props == SourceProperties(
sampling_start=timestamp,
received_samples=5,
sampling_period=timedelta(seconds=0.8),
)
# The buffer should be able to hold 2 seconds of data, and data is coming
# every 0.8 seconds, so we should be able to store 3 samples.
assert _get_buffer_len(resampler, source_receiver) == 3
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
await _assert_no_more_samples(
resampler,
timestamp,
sink_mock,
resampling_fun_mock,
fake_time,
resampling_period_s,
current_iteration=3,
)
assert source_props == SourceProperties(
sampling_start=timestamp,
received_samples=5,
sampling_period=timedelta(seconds=0.8),
)
assert _get_buffer_len(resampler, source_receiver) == 3
# Even when a lot could be refactored to use smaller functions, I'm allowing
# too many statements because it makes following failures in tests more easy
# when the code is very flat.
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-many-statements
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
) -> None:
"""Test resampling with 1.5 resampling windows."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = config_class(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=1.5,
resampling_function=resampling_fun_mock,
initial_buffer_len=7,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# t(s) 0 1 2 2.5 3 4 5 6
# |----------|----------R----|-----|----------R----------|----------R-----> (no more)
# value 5.0 12.0 2.0 4.0 5.0 1.0 3.0
#
# R = resampling is done
# Send a few samples and run a resample tick, advancing the fake time by one period
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1), value=Quantity(12.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample0s),
as_float_tuple(sample1s),
),
config,
source_props,
)
assert source_props == SourceProperties(
sampling_start=timestamp, received_samples=2, sampling_period=None
)
assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Second resampling run
sample2_5s = Sample(timestamp + timedelta(seconds=2.5), value=Quantity(2.0))
sample3s = Sample(timestamp + timedelta(seconds=3), value=Quantity(4.0))
sample4s = Sample(timestamp + timedelta(seconds=4), value=Quantity(5.0))
await source_sender.send(sample2_5s)
await source_sender.send(sample3s)
await source_sender.send(sample4s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 4
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s * 2),
Quantity(expected_resampled_value),
)
)
# It should include samples in the interval (1, 4] seconds
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample2_5s),
as_float_tuple(sample3s),
as_float_tuple(sample4s),
),
config,
source_props,
)
assert source_props == SourceProperties(
sampling_start=timestamp, received_samples=5, sampling_period=None
)
assert _get_buffer_len(resampler, source_receiver) == config.initial_buffer_len
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Third resampling run
sample5s = Sample(timestamp + timedelta(seconds=5), value=Quantity(1.0))
sample6s = Sample(timestamp + timedelta(seconds=6), value=Quantity(3.0))
await source_sender.send(sample5s)
await source_sender.send(sample6s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 6
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s * 3),
Quantity(expected_resampled_value),
)
)
# It should include samples in the interval (3, 6] seconds
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample4s),
as_float_tuple(sample5s),
as_float_tuple(sample6s),
),
config,
source_props,
)
# By now we have a full buffer (7 samples and a buffer of length 6), which
# we received in 4 seconds, so we have an input period of 6/7s.
assert source_props == SourceProperties(
sampling_start=timestamp,
received_samples=7,
sampling_period=timedelta(seconds=6 / 7),
)
# The buffer should be able to hold 2 * 1.5 (3) seconds of data, and data
# is coming every 6/7 seconds (~0.857s), so we should be able to store
# 4 samples.
assert _get_buffer_len(resampler, source_receiver) == 4
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
# Fourth resampling run
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 8
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s * 4),
Quantity(expected_resampled_value),
)
)
# It should include samples in the interval (5, 8] seconds
resampling_fun_mock.assert_called_once_with(
a_sequence(as_float_tuple(sample6s)),
config,
source_props,
)
sink_mock.reset_mock()
resampling_fun_mock.reset_mock()
await _assert_no_more_samples(
resampler,
timestamp,
sink_mock,
resampling_fun_mock,
fake_time,
resampling_period_s,
current_iteration=5,
)
assert source_props == SourceProperties(
sampling_start=timestamp,
received_samples=7,
sampling_period=timedelta(seconds=6 / 7),
)
assert _get_buffer_len(resampler, source_receiver) == 4
# Even when a lot could be refactored to use smaller functions, I'm allowing
# too many statements because it makes following failures in tests more easy
# when the code is very flat.
@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2])
async def test_resampling_with_two_windows( # pylint: disable=too-many-statements
config_class: type[ResamplerConfig],
fake_time: time_machine.Coordinates,
source_chan: Broadcast[Sample[Quantity]],
) -> None:
"""Test resampling with 2 resampling windows."""
timestamp = datetime.now(timezone.utc)
resampling_period_s = 2
expected_resampled_value = 42.0
resampling_fun_mock = MagicMock(
spec=ResamplingFunction, return_value=expected_resampled_value
)
config = config_class(
resampling_period=timedelta(seconds=resampling_period_s),
max_data_age_in_periods=2.0,
resampling_function=resampling_fun_mock,
initial_buffer_len=16,
)
resampler = Resampler(config)
source_receiver = source_chan.new_receiver()
source_sender = source_chan.new_sender()
sink_mock = AsyncMock(spec=Sink, return_value=True)
resampler.add_timeseries("test", source_receiver, sink_mock)
source_props = resampler.get_source_properties(source_receiver)
# Test timeline
#
# t(s) 0 1 2 2.5 3 4 5 6
# |----------|----------R----|-----|----------R----------|----------R-----> (no more)
# value 5.0 12.0 2.0 4.0 5.0 1.0 3.0
#
# R = resampling is done
# Send a few samples and run a resample tick, advancing the fake time by one period
sample0s = Sample(timestamp, value=Quantity(5.0))
sample1s = Sample(timestamp + timedelta(seconds=1), value=Quantity(12.0))
await source_sender.send(sample0s)
await source_sender.send(sample1s)
await _advance_time(fake_time, resampling_period_s)
await resampler.resample(one_shot=True)
assert datetime.now(timezone.utc).timestamp() == 2
sink_mock.assert_called_once_with(
Sample(
timestamp + timedelta(seconds=resampling_period_s),
Quantity(expected_resampled_value),
)
)
resampling_fun_mock.assert_called_once_with(
a_sequence(
as_float_tuple(sample0s),
as_float_tuple(sample1s),