ajamato commented on a change in pull request #14928: URL: https://github.com/apache/beam/pull/14928#discussion_r653145046
########## File path: sdks/python/apache_beam/io/gcp/bigtableio_test.py ########## @@ -0,0 +1,156 @@ +# +# 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 BigTable service.""" + +# pytype: skip-file +import datetime +import string +import unittest +import uuid +from random import choice + +import apache_beam as beam +from apache_beam.io.gcp.bigtableio import WriteToBigTable +from apache_beam.testing.test_pipeline import TestPipeline + +try: + from google.cloud.bigtable import row, Client, column_family + from google.cloud._helpers import _datetime_from_microseconds, UTC + +except ImportError: + row = None + + +class TestWriteBigTable(unittest.TestCase): + TABLE_PREFIX = "python-test" + instance_id = TABLE_PREFIX + "-" + str(uuid.uuid4())[:8] + cluster_id = TABLE_PREFIX + "-" + str(uuid.uuid4())[:8] + table_id = TABLE_PREFIX + "-" + str(uuid.uuid4())[:8] + number = 50 + LOCATION_ID = "us-east1-b" + + def setUp(self): + try: + from google.cloud.bigtable import enums + self.STORAGE_TYPE = enums.StorageType.HDD + self.INSTANCE_TYPE = enums.Instance.Type.DEVELOPMENT + except ImportError: + self.STORAGE_TYPE = 2 + self.INSTANCE_TYPE = 2 + + self.test_pipeline = TestPipeline(is_integration_test=True) + self.runner_name = type(self.test_pipeline.runner).__name__ + self.project = self.test_pipeline.get_option('project') + self.client = Client(project=self.project, admin=True) + + self._delete_old_instances() + + self.instance = self.client.instance( + self.instance_id, instance_type=self.INSTANCE_TYPE, labels=LABELS) + + if not self.instance.exists(): + cluster = self.instance.cluster( + self.cluster_id, + self.LOCATION_ID, + default_storage_type=self.STORAGE_TYPE) + self.instance.create(clusters=[cluster]) + self.table = self.instance.table(self.table_id) + + if not self.table.exists(): + max_versions_rule = column_family.MaxVersionsGCRule(2) + column_family_id = 'cf1' + column_families = {column_family_id: max_versions_rule} + self.table.create(column_families=column_families) + + def _delete_old_instances(self): + instances = self.client.list_instances() + EXISTING_INSTANCES[:] = instances + + def age_in_hours(micros): + return ( + datetime.datetime.utcnow().replace(tzinfo=UTC) - + (_datetime_from_microseconds(micros))).total_seconds() // 3600 + + CLEAN_INSTANCE = [ + i for instance in EXISTING_INSTANCES for i in instance if ( + LABEL_KEY in i.labels.keys() and + (age_in_hours(int(i.labels[LABEL_KEY])) >= 2)) + ] + + if CLEAN_INSTANCE: + for instance in CLEAN_INSTANCE: + instance.delete() + + def test_write_bigtable(self): + + with TestPipeline() as p: + config_bigtable = { + 'project_id': self.project, + 'instance_id': self.instance, + 'table_id': self.table + } + result = ( + p | 'Generate Direct Rows' >> GenerateTestRows( + self.number, **config_bigtable) | WriteToBigTable()) + + self.assertEqual(len([_ for _ in result]), self.number) + + +EXISTING_INSTANCES = [] +LABEL_KEY = u'python-bigtable-beam' +LABELS = {LABEL_KEY: LABEL_KEY} + + +class GenerateTestRows(beam.PTransform): + def __init__(self, number, project_id=None, instance_id=None, table_id=None): + beam.PTransform.__init__(self) + self.number = number + self.rand = choice(string.ascii_letters + string.digits) + self.column_family_id = 'cf1' + self.beam_options = { + 'project_id': project_id, + 'instance_id': instance_id, + 'table_id': table_id + } + + def _generate(self): + value = ''.join(self.rand for i in range(100)) + + for index in range(self.number): + key = "beam_key%s" % ('{0:07}'.format(index)) + direct_row = row.DirectRow(row_key=key) + for column_id in range(10): + direct_row.set_cell( + self.column_family_id, ('field%s' % column_id).encode('utf-8'), + value, + datetime.datetime.now()) + yield direct_row + + def expand(self, pvalue): Review comment: Please pull out the metrics and make sure they are generated. Example: See: https://github.com/apache/beam/pull/14770/files test_downloader_monitoring_info in sdks/python/apache_beam/io/gcp/gcsio_test.py See https://github.com/apache/beam/pull/13217/files#diff-b271770e95e54fc225fe803e2cf81ee02f246037ad635c59ece121ec981a9de4 See: sdks/python/apache_beam/runners/worker/sdk_worker_test.py test_harness_monitoring_infos_and_metadata() Use a similar approach Invoke the code and then call the MetricsEnvironment to make sure the metric is set with the correct value and labels. Test an ok case and error case. I suggest adding this at the start of your test to keep state clean too: MetricsEnvironment.process_wide_container().reset() (You may need to mock errors in the BigTable client API. Or just make the call on the client directly instead of wrapping it in the helper objects.) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
