-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathspannerio_test.py
More file actions
680 lines (600 loc) · 25.4 KB
/
Copy pathspannerio_test.py
File metadata and controls
680 lines (600 loc) · 25.4 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
#
# 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.
#
import datetime
import logging
import random
import string
import typing
import unittest
import mock
import apache_beam as beam
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
# Protect against environments where spanner library is not available.
# pylint: disable=wrong-import-order, wrong-import-position, ungrouped-imports
# pylint: disable=unused-import
try:
from google.cloud import spanner
from apache_beam.io.gcp.experimental.spannerio import create_transaction
from apache_beam.io.gcp.experimental.spannerio import ReadOperation
from apache_beam.io.gcp.experimental.spannerio import ReadFromSpanner
from apache_beam.io.gcp.experimental.spannerio import WriteMutation
from apache_beam.io.gcp.experimental.spannerio import MutationGroup
from apache_beam.io.gcp.experimental.spannerio import WriteToSpanner
from apache_beam.io.gcp.experimental.spannerio import _BatchFn
from apache_beam.io.gcp import resource_identifiers
from apache_beam.metrics import monitoring_infos
from apache_beam.metrics.execution import MetricsEnvironment
from apache_beam.metrics.metricbase import MetricName
except ImportError:
spanner = None
# pylint: enable=wrong-import-order, wrong-import-position, ungrouped-imports
# pylint: enable=unused-import
MAX_DB_NAME_LENGTH = 30
TEST_PROJECT_ID = 'apache-beam-testing'
TEST_INSTANCE_ID = 'beam-test'
TEST_DATABASE_PREFIX = 'spanner-testdb-'
FAKE_TRANSACTION_INFO = {"session_id": "qwerty", "transaction_id": "qwerty"}
FAKE_ROWS = [[1, 'Alice'], [2, 'Bob'], [3, 'Carl'], [4, 'Dan'], [5, 'Evan'],
[6, 'Floyd']]
def _generate_database_name():
mask = string.ascii_lowercase + string.digits
length = MAX_DB_NAME_LENGTH - 1 - len(TEST_DATABASE_PREFIX)
return TEST_DATABASE_PREFIX + ''.join(
random.choice(mask) for i in range(length))
def _generate_test_data():
mask = string.ascii_lowercase + string.digits
length = 100
return [(
'users', ['Key', 'Value'],
[(x, ''.join(random.choice(mask) for _ in range(length)))
for x in range(1, 5)])]
@unittest.skipIf(spanner is None, 'GCP dependencies are not installed.')
@mock.patch('apache_beam.io.gcp.experimental.spannerio.Client')
@mock.patch('apache_beam.io.gcp.experimental.spannerio.BatchSnapshot')
class SpannerReadTest(unittest.TestCase):
def test_read_with_query_batch(
self, mock_batch_snapshot_class, mock_client_class):
mock_snapshot_instance = mock.MagicMock()
mock_snapshot_instance.generate_query_batches.return_value = [{
'query': {
'sql': 'SELECT * FROM users'
}, 'partition': 'test_partition'
} for _ in range(3)]
mock_snapshot_instance.to_dict.return_value = {}
mock_batch_snapshot_instance = mock.MagicMock()
# Prepare process_query_batch return results for three pipelines
mock_batch_snapshot_instance.process_query_batch.side_effect = [
FAKE_ROWS[0:2], FAKE_ROWS[2:4], FAKE_ROWS[4:]
] * 3
mock_client_class.return_value.instance.return_value.database.return_value \
.batch_snapshot.return_value = mock_snapshot_instance
mock_batch_snapshot_class.from_dict.return_value \
= mock_batch_snapshot_instance
ro = [ReadOperation.query("Select * from users")]
with TestPipeline() as pipeline:
read = (
pipeline
| 'read' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
sql="SELECT * FROM users"))
assert_that(read, equal_to(FAKE_ROWS), label='checkRead')
with TestPipeline() as pipeline:
readall = (
pipeline
| 'read all' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
read_operations=ro))
assert_that(readall, equal_to(FAKE_ROWS), label='checkReadAll')
with TestPipeline() as pipeline:
readpipeline = (
pipeline
| 'create reads' >> beam.Create(ro)
| 'reads' >> ReadFromSpanner(
TEST_PROJECT_ID, TEST_INSTANCE_ID, _generate_database_name()))
assert_that(readpipeline, equal_to(FAKE_ROWS), label='checkReadPipeline')
# three pipelines
self.assertEqual(
mock_snapshot_instance.generate_query_batches.call_count, 3)
# three pipelines, each called three times
self.assertEqual(
mock_batch_snapshot_instance.process_query_batch.call_count, 3 * 3)
def test_read_with_table_batch(
self, mock_batch_snapshot_class, mock_client_class):
mock_snapshot_instance = mock.MagicMock()
mock_snapshot_instance.generate_read_batches.return_value = [{
'read': {
'table': 'users',
'keyset': {
'all': True
},
'columns': ['Key', 'Value'],
'index': ''
},
'partition': 'test_partition'
} for _ in range(3)]
mock_snapshot_instance.to_dict.return_value = {}
mock_batch_snapshot_instance = mock.MagicMock()
# Prepare process_read_batch return results for three pipelines
mock_batch_snapshot_instance.process_read_batch.side_effect = [
FAKE_ROWS[0:2], FAKE_ROWS[2:4], FAKE_ROWS[4:]
] * 3
mock_client_class.return_value.instance.return_value.database.return_value \
.batch_snapshot.return_value = mock_snapshot_instance
mock_batch_snapshot_class.from_dict.return_value \
= mock_batch_snapshot_instance
ro = [ReadOperation.table("users", ["Key", "Value"])]
with TestPipeline() as pipeline:
read = (
pipeline
| 'read' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
table="users",
columns=["Key", "Value"]))
assert_that(read, equal_to(FAKE_ROWS), label='checkRead')
with TestPipeline() as pipeline:
readall = (
pipeline
| 'read all' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
read_operations=ro))
assert_that(readall, equal_to(FAKE_ROWS), label='checkReadAll')
with TestPipeline() as pipeline:
readpipeline = (
pipeline
| 'create reads' >> beam.Create(ro)
| 'reads' >> ReadFromSpanner(
TEST_PROJECT_ID, TEST_INSTANCE_ID, _generate_database_name()))
assert_that(readpipeline, equal_to(FAKE_ROWS), label='checkReadPipeline')
# three pipelines
self.assertEqual(mock_snapshot_instance.generate_read_batches.call_count, 3)
# three pipelines, each called three times
self.assertEqual(
mock_batch_snapshot_instance.process_read_batch.call_count, 3 * 3)
with TestPipeline() as pipeline, self.assertRaises(ValueError):
# Test the exception raised at pipeline construction time, when user
# passes the read operations in the constructor and also in the pipeline
_ = (
pipeline | 'reads error' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
table="users"))
def test_read_with_index(self, mock_batch_snapshot_class, mock_client_class):
mock_snapshot_instance = mock.MagicMock()
mock_snapshot_instance.generate_read_batches.return_value = [{
'read': {
'table': 'users',
'keyset': {
'all': True
},
'columns': ['Key', 'Value'],
'index': ''
},
'partition': 'test_partition'
} for _ in range(3)]
mock_batch_snapshot_instance = mock.MagicMock()
# Prepare process_read_batch return results for three pipelines
mock_batch_snapshot_instance.process_read_batch.side_effect = [
FAKE_ROWS[0:2], FAKE_ROWS[2:4], FAKE_ROWS[4:]
] * 3
mock_snapshot_instance.to_dict.return_value = {}
mock_client_class.return_value.instance.return_value.database.return_value \
.batch_snapshot.return_value = mock_snapshot_instance
mock_batch_snapshot_class.from_dict.return_value \
= mock_batch_snapshot_instance
ro = [ReadOperation.table("users", ["Key", "Value"], index="Key")]
with TestPipeline() as pipeline:
read = (
pipeline
| 'read' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
table="users",
columns=["Key", "Value"]))
assert_that(read, equal_to(FAKE_ROWS), label='checkRead')
with TestPipeline() as pipeline:
readall = (
pipeline
| 'read all' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
read_operations=ro))
assert_that(readall, equal_to(FAKE_ROWS), label='checkReadAll')
with TestPipeline() as pipeline:
readpipeline = (
pipeline
| 'create reads' >> beam.Create(ro)
| 'reads' >> ReadFromSpanner(
TEST_PROJECT_ID, TEST_INSTANCE_ID, _generate_database_name()))
assert_that(readpipeline, equal_to(FAKE_ROWS), label='checkReadPipeline')
# three pipelines
self.assertEqual(mock_snapshot_instance.generate_read_batches.call_count, 3)
# three pipelines, each called three times
self.assertEqual(
mock_batch_snapshot_instance.process_read_batch.call_count, 3 * 3)
with TestPipeline() as pipeline, self.assertRaises(ValueError):
# Test the exception raised at pipeline construction time, when user
# passes the read operations in the constructor and also in the pipeline.
_ = (
pipeline | 'reads error' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
table="users"))
def test_read_with_transaction(
self, mock_batch_snapshot_class, mock_client_class):
mock_snapshot_instance = mock.MagicMock()
mock_snapshot_instance.to_dict.return_value = FAKE_TRANSACTION_INFO
mock_transaction_instance = mock.MagicMock()
mock_transaction_instance.execute_sql.return_value = FAKE_ROWS
mock_transaction_instance.read.return_value = FAKE_ROWS
mock_client_class.return_value.instance.return_value.database.return_value \
.batch_snapshot.return_value = mock_snapshot_instance
mock_client_class.return_value.instance.return_value.database.return_value \
.session.return_value.transaction.return_value.__enter__.return_value \
= mock_transaction_instance
ro = [ReadOperation.query("Select * from users")]
with TestPipeline() as p:
transaction = (
p | create_transaction(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
exact_staleness=datetime.timedelta(seconds=10)))
read_query = (
p | 'with query' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
transaction=transaction,
sql="Select * from users"))
assert_that(read_query, equal_to(FAKE_ROWS), label='checkQuery')
read_table = (
p | 'with table' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
transaction=transaction,
table="users",
columns=["Key", "Value"]))
assert_that(read_table, equal_to(FAKE_ROWS), label='checkTable')
read_indexed_table = (
p | 'with index' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
transaction=transaction,
table="users",
index="Key",
columns=["Key", "Value"]))
assert_that(
read_indexed_table, equal_to(FAKE_ROWS), label='checkTableIndex')
read = (
p | 'read all' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
transaction=transaction,
read_operations=ro))
assert_that(read, equal_to(FAKE_ROWS), label='checkReadAll')
read_pipeline = (
p
| 'create read operations' >> beam.Create(ro)
| 'reads' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
transaction=transaction))
assert_that(read_pipeline, equal_to(FAKE_ROWS), label='checkReadPipeline')
# transaction setup once
self.assertEqual(mock_snapshot_instance.to_dict.call_count, 1)
# three pipelines called execute_sql
self.assertEqual(mock_transaction_instance.execute_sql.call_count, 3)
# two pipelines called read
self.assertEqual(mock_transaction_instance.read.call_count, 2)
with TestPipeline() as p, self.assertRaises(ValueError):
# Test the exception raised at pipeline construction time, when user
# passes the read operations in the constructor and also in the pipeline.
transaction = (
p | create_transaction(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
exact_staleness=datetime.timedelta(seconds=10)))
_ = (
p
| 'create read operations2' >> beam.Create(ro)
| 'reads with error' >> ReadFromSpanner(
TEST_PROJECT_ID,
TEST_INSTANCE_ID,
_generate_database_name(),
transaction=transaction,
read_operations=ro))
def test_invalid_transaction(
self, mock_batch_snapshot_class, mock_client_class):
# test exception raises at pipeline execution time
error_string = "Invalid transaction object"
with self.assertRaisesRegex(Exception, error_string), TestPipeline() as p:
transaction = (
p | beam.Create([{
"invalid": "transaction"
}]).with_output_types(typing.Any))
_ = (
p | 'with query' >> ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
transaction=transaction,
sql="Select * from users"))
def test_display_data(self, *args):
dd_sql = ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
sql="Select * from users").display_data()
dd_table = ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
table="users",
columns=['id', 'name']).display_data()
dd_transaction = ReadFromSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
table="users",
columns=['id', 'name'],
transaction={
"transaction_id": "test123", "session_id": "test456"
}).display_data()
self.assertTrue("sql" in dd_sql)
self.assertTrue("table" in dd_table)
self.assertTrue("table" in dd_transaction)
self.assertTrue("transaction" in dd_transaction)
@unittest.skipIf(spanner is None, 'GCP dependencies are not installed.')
@mock.patch('apache_beam.io.gcp.experimental.spannerio.Client')
@mock.patch('google.cloud.spanner_v1.database.BatchCheckout')
class SpannerWriteTest(unittest.TestCase):
def test_spanner_write(self, mock_batch_snapshot_class, mock_batch_checkout):
ks = spanner.KeySet(keys=[[1233], [1234]])
mutations = [
WriteMutation.delete("roles", ks),
WriteMutation.insert(
"roles", ("key", "rolename"), [('1233', "mutations-inset-1233")]),
WriteMutation.insert(
"roles", ("key", "rolename"), [('1234', "mutations-inset-1234")]),
WriteMutation.update(
"roles", ("key", "rolename"),
[('1234', "mutations-inset-1233-updated")]),
]
# TODO(https://github.com/apache/beam/issues/34549): This test relies on
# metrics filtering which doesn't work on Prism yet because Prism renames
# steps (e.g. "Do" becomes "ref_AppliedPTransform_Do_7").
# https://github.com/apache/beam/blob/5f9cd73b7c9a2f37f83971ace3a399d633201dd1/sdks/python/apache_beam/runners/portability/fn_api_runner/fn_runner.py#L1590
p = TestPipeline('FnApiRunner')
_ = (
p
| beam.Create(mutations)
| WriteToSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
max_batch_size_bytes=1024))
res = p.run()
res.wait_until_finish()
metric_results = res.metrics().query(
MetricsFilter().with_name("SpannerBatches"))
batches_counter = metric_results['counters'][0]
self.assertEqual(batches_counter.committed, 2)
self.assertEqual(batches_counter.attempted, 2)
def test_spanner_bundles_size(
self, mock_batch_snapshot_class, mock_batch_checkout):
ks = spanner.KeySet(keys=[[1233], [1234]])
mutations = [
WriteMutation.delete("roles", ks),
WriteMutation.insert(
"roles", ("key", "rolename"), [('1234', "mutations-inset-1234")])
] * 50
# TODO(https://github.com/apache/beam/issues/34549): This test relies on
# metrics filtering which doesn't work on Prism yet because Prism renames
# steps (e.g. "Do" becomes "ref_AppliedPTransform_Do_7").
# https://github.com/apache/beam/blob/5f9cd73b7c9a2f37f83971ace3a399d633201dd1/sdks/python/apache_beam/runners/portability/fn_api_runner/fn_runner.py#L1590
p = TestPipeline('FnApiRunner')
_ = (
p
| beam.Create(mutations)
| WriteToSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
max_batch_size_bytes=1024))
res = p.run()
res.wait_until_finish()
metric_results = res.metrics().query(
MetricsFilter().with_name('SpannerBatches'))
batches_counter = metric_results['counters'][0]
self.assertEqual(batches_counter.committed, 53)
self.assertEqual(batches_counter.attempted, 53)
def test_spanner_write_mutation_groups(
self, mock_batch_snapshot_class, mock_batch_checkout):
ks = spanner.KeySet(keys=[[1233], [1234]])
mutation_groups = [
MutationGroup([
WriteMutation.insert(
"roles", ("key", "rolename"),
[('9001233', "mutations-inset-1233")]),
WriteMutation.insert(
"roles", ("key", "rolename"),
[('9001234', "mutations-inset-1234")])
]),
MutationGroup([
WriteMutation.update(
"roles", ("key", "rolename"),
[('9001234', "mutations-inset-9001233-updated")])
]),
MutationGroup([WriteMutation.delete("roles", ks)])
]
# TODO(https://github.com/apache/beam/issues/34549): This test relies on
# metrics filtering which doesn't work on Prism yet because Prism renames
# steps (e.g. "Do" becomes "ref_AppliedPTransform_Do_7").
# https://github.com/apache/beam/blob/5f9cd73b7c9a2f37f83971ace3a399d633201dd1/sdks/python/apache_beam/runners/portability/fn_api_runner/fn_runner.py#L1590
p = TestPipeline('FnApiRunner')
_ = (
p
| beam.Create(mutation_groups)
| WriteToSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
max_batch_size_bytes=100))
res = p.run()
res.wait_until_finish()
metric_results = res.metrics().query(
MetricsFilter().with_name('SpannerBatches'))
batches_counter = metric_results['counters'][0]
self.assertEqual(batches_counter.committed, 3)
self.assertEqual(batches_counter.attempted, 3)
def test_batch_byte_size(
self, mock_batch_snapshot_class, mock_batch_checkout):
# each mutation group byte size is 58 bytes.
mutation_group = [
MutationGroup([
WriteMutation.insert(
"roles",
("key", "rolename"), [('1234', "mutations-inset-1234")])
])
] * 50
with TestPipeline() as p:
# the total 50 mutation group size will be 2900 (58 * 50)
# if we want to make two batches, so batch size should be 1450 (2900 / 2)
# and each bach should contains 25 mutations.
res = (
p | beam.Create(mutation_group)
| beam.ParDo(
_BatchFn(
max_batch_size_bytes=1450,
max_number_rows=50,
max_number_cells=500))
| beam.Map(lambda x: len(x)))
assert_that(res, equal_to([25] * 2))
def test_batch_disable(self, mock_batch_snapshot_class, mock_batch_checkout):
mutation_group = [
MutationGroup([
WriteMutation.insert(
"roles",
("key", "rolename"), [('1234', "mutations-inset-1234")])
])
] * 4
with TestPipeline() as p:
# to disable to batching, we need to set any of the batching parameters
# either to lower value or zero
res = (
p | beam.Create(mutation_group)
| beam.ParDo(
_BatchFn(
max_batch_size_bytes=1450,
max_number_rows=0,
max_number_cells=500))
| beam.Map(lambda x: len(x)))
assert_that(res, equal_to([1] * 4))
def test_batch_max_rows(self, mock_batch_snapshot_class, mock_batch_checkout):
mutation_group = [
MutationGroup([
WriteMutation.insert(
"roles", ("key", "rolename"),
[
('1234', "mutations-inset-1234"),
('1235', "mutations-inset-1235"),
])
])
] * 50
with TestPipeline() as p:
# There are total 50 mutation groups, each contains two rows.
# The total number of rows will be 100 (50 * 2).
# If each batch contains 10 rows max then batch count should be 10
# (contains 5 mutation groups each).
res = (
p | beam.Create(mutation_group)
| beam.ParDo(
_BatchFn(
max_batch_size_bytes=1048576,
max_number_rows=10,
max_number_cells=500))
| beam.Map(lambda x: len(x)))
assert_that(res, equal_to([5] * 10))
def test_batch_max_cells(
self, mock_batch_snapshot_class, mock_batch_checkout):
mutation_group = [
MutationGroup([
WriteMutation.insert(
"roles", ("key", "rolename"),
[
('1234', "mutations-inset-1234"),
('1235', "mutations-inset-1235"),
])
])
] * 50
with TestPipeline() as p:
# There are total 50 mutation groups, each contains two rows (or 4 cells).
# The total number of cells will be 200 (50 groups * 4 cells).
# If each batch contains 50 cells max then batch count should be 5.
# 4 batches contains 12 mutations groups and the fifth batch should be
# consists of 2 mutation group element.
# No. of mutations groups per batch = Max Cells / Cells per mutation group
# total_batches = Total Number of Cells / Max Cells
res = (
p | beam.Create(mutation_group)
| beam.ParDo(
_BatchFn(
max_batch_size_bytes=1048576,
max_number_rows=500,
max_number_cells=50))
| beam.Map(lambda x: len(x)))
assert_that(res, equal_to([12, 12, 12, 12, 2]))
def test_write_mutation_error(self, *args):
with self.assertRaises(ValueError):
# since `WriteMutation` only accept one operation.
WriteMutation(insert="table-name", update="table-name")
def test_display_data(self, *args):
data = WriteToSpanner(
project_id=TEST_PROJECT_ID,
instance_id=TEST_INSTANCE_ID,
database_id=_generate_database_name(),
max_batch_size_bytes=1024).display_data()
self.assertTrue("project_id" in data)
self.assertTrue("instance_id" in data)
self.assertTrue("pool" in data)
self.assertTrue("database" in data)
self.assertTrue("batch_size" in data)
self.assertTrue("max_number_rows" in data)
self.assertTrue("max_number_cells" in data)
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()