forked from apache/beam
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperiodicsequence_test.py
More file actions
339 lines (302 loc) · 11.7 KB
/
Copy pathperiodicsequence_test.py
File metadata and controls
339 lines (302 loc) · 11.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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Unit tests for the PTransform and descendants."""
# pytype: skip-file
import inspect
import logging
import random
import time
import unittest
from parameterized import parameterized
import apache_beam as beam
from apache_beam.io.restriction_trackers import OffsetRange
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.transforms import trigger
from apache_beam.transforms import window
from apache_beam.transforms.periodicsequence import PeriodicImpulse
from apache_beam.transforms.periodicsequence import PeriodicSequence
from apache_beam.transforms.periodicsequence import _sequence_backlog_bytes
from apache_beam.transforms.window import FixedWindows
from apache_beam.utils.timestamp import Timestamp
# Disable frequent lint warning due to pipe operator for chaining transforms.
# pylint: disable=expression-not-assigned
class PeriodicSequenceTest(unittest.TestCase):
def test_periodicsequence_outputs_valid_sequence(self):
start_offset = 1
start_time = time.time() + start_offset
duration = 1
end_time = start_time + duration
interval = 0.25
with TestPipeline() as p:
result = (
p
| 'ImpulseElement' >> beam.Create([(start_time, end_time, interval)])
| 'ImpulseSeqGen' >> PeriodicSequence())
k = [
start_time + x * interval
for x in range(0, int(duration / interval), 1)
]
self.assertEqual(result.is_bounded, False)
assert_that(result, equal_to(k))
def test_periodicsequence_outputs_valid_sequence_in_past(self):
start_offset = -10000
it = time.time() + start_offset
duration = 5
et = it + duration
interval = 1
with TestPipeline() as p:
result = (
p
| 'ImpulseElement' >> beam.Create([(it, et, interval)])
| 'ImpulseSeqGen' >> PeriodicSequence())
k = [it + x * interval for x in range(0, int(duration / interval), 1)]
self.assertEqual(result.is_bounded, False)
assert_that(result, equal_to(k))
def test_periodicsequence_output_size(self):
element = [0, 1000000000, 10]
self.assertEqual(
_sequence_backlog_bytes(element, 100, OffsetRange(10, 100000000)), 0)
self.assertEqual(
_sequence_backlog_bytes(element, 100, OffsetRange(9, 100000000)), 8)
self.assertEqual(
_sequence_backlog_bytes(element, 100, OffsetRange(8, 100000000)), 16)
self.assertEqual(
_sequence_backlog_bytes(element, 101, OffsetRange(9, 100000000)), 8)
self.assertEqual(
_sequence_backlog_bytes(element, 10000, OffsetRange(0, 100000000)),
8 * 10000 / 10)
self.assertEqual(
_sequence_backlog_bytes(element, 10000, OffsetRange(1002, 1003)), 0)
self.assertEqual(
_sequence_backlog_bytes(element, 10100, OffsetRange(1002, 1003)), 8)
class PeriodicImpulseTest(unittest.TestCase):
def test_windowing_on_si(self):
start_offset = -15
it = time.time() + start_offset
duration = 15
et = it + duration
interval = 5
with TestPipeline() as p:
si = (
p
| 'PeriodicImpulse' >> PeriodicImpulse(it, et, interval, True)
| 'AddKey' >> beam.Map(lambda v: ('key', v))
| 'GBK' >> beam.GroupByKey()
| 'SortGBK' >> beam.MapTuple(lambda k, vs: (k, sorted(vs))))
actual = si
k = [('key', [it + x * interval])
for x in range(0, int(duration / interval), 1)]
assert_that(actual, equal_to(k))
def test_default_start(self):
default_parameters = inspect.signature(PeriodicImpulse.__init__).parameters
it = default_parameters["start_timestamp"].default
duration = 1
et = it + duration
interval = 0.5
# Check default `stop_timestamp` is the same type `start_timestamp`
is_same_type = isinstance(
it, type(default_parameters["stop_timestamp"].default))
error = "'start_timestamp' and 'stop_timestamp' have different type"
assert is_same_type, error
with TestPipeline() as p:
result = p | 'PeriodicImpulse' >> PeriodicImpulse(it, et, interval)
k = [it + x * interval for x in range(0, int(duration / interval))]
self.assertEqual(result.is_bounded, False)
assert_that(result, equal_to(k))
@unittest.skip("hard to determine warm-up time and threshold for runners.")
def test_processing_time(self):
warmup_time = 3
threshold = 0.5
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=Timestamp.now() + warmup_time,
data=[10, 20, 30],
fire_interval=2)
| beam.Map(lambda _: time.time())
| beam.WindowInto(
window.GlobalWindows(),
trigger=trigger.Repeatedly(trigger.AfterCount(3)),
accumulation_mode=trigger.AccumulationMode.DISCARDING,
)
| beam.GroupBy()
| beam.FlatMap(lambda x: [v - min(x[1]) for v in x[1]]))
expected = [0, 2, 4]
assert_that(ret, equal_to(expected, lambda x, y: abs(x - y) < threshold))
@parameterized.expand([0.5, 1, 2, 10])
def test_stop_over_by_epsilon(self, interval):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=Timestamp(seconds=1),
stop_timestamp=Timestamp(seconds=1, micros=1),
data=[1, 2],
fire_interval=interval)
| beam.WindowInto(FixedWindows(interval))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [
(0, [1]),
]
assert_that(ret, equal_to(expected))
@parameterized.expand([1, 2])
def test_stop_over_by_interval(self, interval):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=Timestamp(seconds=1),
stop_timestamp=Timestamp(seconds=1 + interval),
data=[1, 2],
fire_interval=interval)
| beam.WindowInto(FixedWindows(interval))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [(0, [1])]
assert_that(ret, equal_to(expected))
@parameterized.expand([1, 2])
def test_stop_over_by_interval_and_epsilon(self, interval):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=Timestamp(seconds=1),
stop_timestamp=Timestamp(seconds=1 + interval, micros=1),
data=[1, 2],
fire_interval=interval)
| beam.WindowInto(FixedWindows(interval))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [(0, [1]), (0, [2])]
assert_that(ret, equal_to(expected))
def test_interval(self):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(data=[1, 2, 3, 4], fire_interval=0.5)
| beam.WindowInto(FixedWindows(0.5))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [(0, [1]), (0, [2]), (0, [3]), (0, [4])]
assert_that(ret, equal_to(expected))
def test_repeat(self):
now = Timestamp.now()
with self.assertWarnsRegex(UserWarning, "not enough to span"):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=now,
stop_timestamp=now + 2.6,
data=[1, 2, 3, 4],
fire_interval=0.5)
| beam.WindowInto(FixedWindows(0.5))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [(0, [1]), (0, [2]), (0, [3]), (0, [4]), (0, [1]), (0, [2])]
assert_that(ret, equal_to(expected))
def test_timestamped_value(self):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
data=[(Timestamp(1), 1), (Timestamp(3), 2), (Timestamp(2), 3),
(Timestamp(1), 4)],
fire_interval=0.5)
| beam.WindowInto(FixedWindows(0.5))
| beam.WithKeys(0)
| beam.GroupByKey())
expected = [(0, [1, 4]), (0, [2]), (0, [3])]
assert_that(ret, equal_to(expected))
def test_not_enough_timestamped_value(self):
now = Timestamp.now()
data = [(Timestamp(1), 1), (Timestamp(2), 2), (Timestamp(3), 3)]
with self.assertRaisesRegex(ValueError, "not enough to span"):
with TestPipeline() as p:
_ = (
p | PeriodicImpulse(
start_timestamp=now,
stop_timestamp=now + 2.6,
data=data,
fire_interval=0.5))
def test_fuzzy_length_and_interval(self):
times = 30
for _ in range(times):
seed = int(time.time() * 1000)
random.seed(seed)
n = int(random.randint(1, 100))
data = list(range(n))
m = random.randint(1, 1000)
interval = m / 1e6
now = Timestamp.now()
try:
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=now, data=data, fire_interval=interval))
assert_that(ret, equal_to(data))
except Exception as e: # pylint: disable=broad-except
logging.error("Error occurred at random seed=%d", seed)
raise e
def test_fuzzy_length_at_minimal_interval(self):
times = 30
for _ in range(times):
seed = int(time.time() * 1000)
seed = 1751135957975
random.seed(seed)
n = int(random.randint(1, 100))
data = list(range(n))
interval = 1e-6
now = Timestamp.now()
try:
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=now, data=data, fire_interval=interval))
assert_that(ret, equal_to(data))
except Exception as e: # pylint: disable=broad-except
logging.error("Error occurred at random seed=%d", seed)
raise e
def test_int_type_input(self):
# This test is to verify that if input timestamps and interval are integers,
# the generated timestamped values are also integers.
# This is necessary for the following test to pass:
# apache_beam.examples.snippets.snippets_test.SlowlyChangingSideInputsTest
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=1, stop_timestamp=5, fire_interval=1))
expected = [1, 2, 3, 4]
assert_that(
ret, equal_to(expected, lambda x, y: type(x) is type(y) and x == y))
def test_float_type_input(self):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=1.0, stop_timestamp=5.0, fire_interval=1))
expected = [1.0, 2.0, 3.0, 4.0]
assert_that(
ret, equal_to(expected, lambda x, y: type(x) is type(y) and x == y))
def test_timestamp_type_input(self):
with TestPipeline() as p:
ret = (
p | PeriodicImpulse(
start_timestamp=Timestamp.of(1),
stop_timestamp=Timestamp.of(5),
fire_interval=1))
expected = [1.0, 2.0, 3.0, 4.0]
assert_that(
ret, equal_to(expected, lambda x, y: type(x) is type(y) and x == y))
if __name__ == '__main__':
unittest.main()