From 92a08daa317ac57d960c5818deb7c6cfb8ef8270 Mon Sep 17 00:00:00 2001 From: Igor Degtiarov Date: Thu, 26 Jun 2014 14:28:26 +0300 Subject: [PATCH] Fix H904 violations and re-enable gating H904 got stricter in hacking 0.9, so fix new violations and re-enable gating. Change-Id: I7a3e9006cfb756da4893b9c0a6139a2e70c9aaf4 --- ceilometer/alarm/evaluator/combination.py | 6 +- ceilometer/api/controllers/v2.py | 37 ++++---- ceilometer/compute/pollsters/net.py | 4 +- ceilometer/compute/pollsters/util.py | 4 +- ceilometer/hardware/inspector/snmp.py | 12 +-- .../network/statistics/opendaylight/driver.py | 8 +- ceilometer/nova_client.py | 4 +- ceilometer/orchestration/notifications.py | 9 +- ceilometer/pipeline.py | 4 +- ceilometer/publisher/rpc.py | 4 +- ceilometer/storage/hbase/inmemory.py | 6 +- ceilometer/storage/impl_db2.py | 10 ++- ceilometer/storage/impl_hbase.py | 23 +++-- ceilometer/storage/impl_sqlalchemy.py | 85 ++++++++++--------- ceilometer/storage/models.py | 6 +- .../versions/003_set_utf8_charset.py | 8 +- .../versions/014_add_event_message_id.py | 6 +- ...onvert_timestamp_as_datetime_to_decimal.py | 4 +- .../versions/021_add_event_types.py | 11 ++- .../versions/023_add_trait_types.py | 12 +-- .../024_event_use_floatingprecision.py | 4 +- .../025_alarm_use_floatingprecision.py | 4 +- .../versions/031_add_new_meter_table.py | 20 ++--- .../versions/034_drop_dump_tables.py | 8 +- .../versions/035_drop_user_project_tables.py | 16 ++-- .../036_drop_sourceassoc_resource_tables.py | 8 +- ceilometer/storage/sqlalchemy/models.py | 8 +- .../tests/alarm/evaluator/test_threshold.py | 8 +- .../tests/api/v2/test_alarm_scenarios.py | 12 +-- ceilometer/tests/api/v2/test_app.py | 22 ++--- .../tests/api/v2/test_event_scenarios.py | 21 +++-- .../tests/compute/pollsters/test_cpu.py | 4 +- .../tests/compute/pollsters/test_diskio.py | 3 +- .../tests/compute/pollsters/test_memory.py | 4 +- .../compute/virt/vmware/test_inspector.py | 19 ++--- .../virt/vmware/test_vsphere_operations.py | 4 +- ceilometer/tests/event/test_endpoint.py | 12 ++- .../statistics/opendaylight/test_driver.py | 26 +++--- ceilometer/tests/pipeline_base.py | 6 +- .../tests/publisher/test_rpc_publisher.py | 4 +- ceilometer/tests/storage/test_impl_mongodb.py | 4 +- .../tests/storage/test_impl_sqlalchemy.py | 4 +- .../tests/storage/test_storage_scenarios.py | 22 +++-- ceilometer/tests/test_bin.py | 43 +++++----- ceilometer/tests/test_notification.py | 8 +- ceilometer/transformer/conversions.py | 6 +- ceilometer/utils.py | 6 +- tox.ini | 3 +- 48 files changed, 284 insertions(+), 288 deletions(-) diff --git a/ceilometer/alarm/evaluator/combination.py b/ceilometer/alarm/evaluator/combination.py index 41ad691ca..2f377c84b 100644 --- a/ceilometer/alarm/evaluator/combination.py +++ b/ceilometer/alarm/evaluator/combination.py @@ -47,9 +47,9 @@ class CombinationEvaluator(evaluator.Evaluator): if not state or state == evaluator.UNKNOWN] sufficient = len(alarms_missing_states) == 0 if not sufficient and alarm.state != evaluator.UNKNOWN: - reason = _('Alarms %(alarm_ids)s' - ' are in unknown state') % \ - {'alarm_ids': ",".join(alarms_missing_states)} + reason = (_('Alarms %(alarm_ids)s' + ' are in unknown state') % + {'alarm_ids': ",".join(alarms_missing_states)}) reason_data = self._reason_data(alarms_missing_states) self._refresh(alarm, evaluator.UNKNOWN, reason, reason_data) return sufficient diff --git a/ceilometer/api/controllers/v2.py b/ceilometer/api/controllers/v2.py index 000dc53d1..32db52fd0 100644 --- a/ceilometer/api/controllers/v2.py +++ b/ceilometer/api/controllers/v2.py @@ -254,19 +254,19 @@ class Query(_Base): raise TypeError() converted_value = self._type_converters[type](self.value) except ValueError: - msg = _('Unable to convert the value %(value)s' - ' to the expected data type %(type)s.') % \ - {'value': self.value, 'type': type} + msg = (_('Unable to convert the value %(value)s' + ' to the expected data type %(type)s.') % + {'value': self.value, 'type': type}) raise ClientSideError(msg) except TypeError: - msg = _('The data type %(type)s is not supported. The supported' - ' data type list is: %(supported)s') % \ - {'type': type, 'supported': self._supported_types} + msg = (_('The data type %(type)s is not supported. The supported' + ' data type list is: %(supported)s') % + {'type': type, 'supported': self._supported_types}) raise ClientSideError(msg) except Exception: - msg = _('Unexpected exception converting %(value)s to' - ' the expected data type %(type)s.') % \ - {'value': self.value, 'type': type} + msg = (_('Unexpected exception converting %(value)s to' + ' the expected data type %(type)s.') % + {'value': self.value, 'type': type}) raise ClientSideError(msg) return converted_value @@ -1553,14 +1553,13 @@ class AlarmThresholdRule(_Base): @property def default_description(self): - return _( - 'Alarm when %(meter_name)s is %(comparison_operator)s a ' - '%(statistic)s of %(threshold)s over %(period)s seconds') % \ - dict(comparison_operator=self.comparison_operator, - statistic=self.statistic, - threshold=self.threshold, - meter_name=self.meter_name, - period=self.period) + return (_('Alarm when %(meter_name)s is %(comparison_operator)s a ' + '%(statistic)s of %(threshold)s over %(period)s seconds') % + dict(comparison_operator=self.comparison_operator, + statistic=self.statistic, + threshold=self.threshold, + meter_name=self.meter_name, + period=self.period)) def as_dict(self): rule = self.as_dict_from_keys(['period', 'comparison_operator', @@ -1624,8 +1623,8 @@ class AlarmTimeConstraint(_Base): def get_description(self): if not self._description: - return 'Time constraint at %s lasting for %s seconds' \ - % (self.start, self.duration) + return ('Time constraint at %s lasting for %s seconds' + % (self.start, self.duration)) return self._description def set_description(self, value): diff --git a/ceilometer/compute/pollsters/net.py b/ceilometer/compute/pollsters/net.py index 4df105d3b..c95c23f53 100644 --- a/ceilometer/compute/pollsters/net.py +++ b/ceilometer/compute/pollsters/net.py @@ -40,8 +40,8 @@ class _Base(plugin.ComputePollster): metadata = copy.copy(vnic_data) resource_metadata = dict(zip(metadata._fields, metadata)) resource_metadata['instance_id'] = instance.id - resource_metadata['instance_type'] = \ - instance.flavor['id'] if instance.flavor else None + resource_metadata['instance_type'] = (instance.flavor['id'] if + instance.flavor else None) if vnic_data.fref is not None: rid = vnic_data.fref diff --git a/ceilometer/compute/pollsters/util.py b/ceilometer/compute/pollsters/util.py index 5c8fd388f..13011f3c1 100644 --- a/ceilometer/compute/pollsters/util.py +++ b/ceilometer/compute/pollsters/util.py @@ -69,8 +69,8 @@ def _get_metadata_from_object(instance): metadata['memory_mb'] = instance.flavor['ram'] metadata['disk_gb'] = instance.flavor['disk'] metadata['ephemeral_gb'] = instance.flavor['ephemeral'] - metadata['root_gb'] = int(metadata['disk_gb']) - \ - int(metadata['ephemeral_gb']) + metadata['root_gb'] = (int(metadata['disk_gb']) - + int(metadata['ephemeral_gb'])) return compute_util.add_reserved_user_metadata(instance.metadata, metadata) diff --git a/ceilometer/hardware/inspector/snmp.py b/ceilometer/hardware/inspector/snmp.py index de90eb9cd..f32503d98 100644 --- a/ceilometer/hardware/inspector/snmp.py +++ b/ceilometer/hardware/inspector/snmp.py @@ -108,14 +108,14 @@ class SNMPInspector(base.Inspector): def inspect_cpu(self, host): # get 1 minute load - cpu_1_min_load = \ - str(self._get_value_from_oid(self._cpu_1_min_load_oid, host)) + cpu_1_min_load = ( + str(self._get_value_from_oid(self._cpu_1_min_load_oid, host))) # get 5 minute load - cpu_5_min_load = \ - str(self._get_value_from_oid(self._cpu_5_min_load_oid, host)) + cpu_5_min_load = ( + str(self._get_value_from_oid(self._cpu_5_min_load_oid, host))) # get 15 minute load - cpu_15_min_load = \ - str(self._get_value_from_oid(self._cpu_15_min_load_oid, host)) + cpu_15_min_load = ( + str(self._get_value_from_oid(self._cpu_15_min_load_oid, host))) yield base.CPUStats(cpu_1_min=float(cpu_1_min_load), cpu_5_min=float(cpu_5_min_load), diff --git a/ceilometer/network/statistics/opendaylight/driver.py b/ceilometer/network/statistics/opendaylight/driver.py index 5c000dadf..999c385c4 100644 --- a/ceilometer/network/statistics/opendaylight/driver.py +++ b/ceilometer/network/statistics/opendaylight/driver.py @@ -157,10 +157,10 @@ class OpenDayLightDriver(driver.Driver): user_links.append(user_link) # get link status to hosts - container_data['active_hosts'] = cs.host_tracker.\ - get_active_hosts(container_name) - container_data['inactive_hosts'] = cs.host_tracker.\ - get_inactive_hosts(container_name) + container_data['active_hosts'] = ( + cs.host_tracker.get_active_hosts(container_name)) + container_data['inactive_hosts'] = ( + cs.host_tracker.get_inactive_hosts(container_name)) container_data['timestamp'] = timeutils.isotime() diff --git a/ceilometer/nova_client.py b/ceilometer/nova_client.py index e8b67b8ef..42476afd5 100644 --- a/ceilometer/nova_client.py +++ b/ceilometer/nova_client.py @@ -108,8 +108,8 @@ class Client(object): attr_defaults = [('kernel_id', None), ('ramdisk_id', None)] - instance.image['name'] = \ - getattr(image, 'name') if image else 'unknown-id-%s' % iid + instance.image['name'] = ( + getattr(image, 'name') if image else 'unknown-id-%s' % iid) image_metadata = getattr(image, 'metadata', None) for attr, default in attr_defaults: diff --git a/ceilometer/orchestration/notifications.py b/ceilometer/orchestration/notifications.py index 83100e0ba..61330d187 100644 --- a/ceilometer/orchestration/notifications.py +++ b/ceilometer/orchestration/notifications.py @@ -56,15 +56,14 @@ class StackCRUD(plugin.NotificationBase): for topic in conf.notification_topics] def process_notification(self, message): - name = message['event_type'] \ - .replace(self.resource_name, 'stack') \ - .replace('.end', '') + name = (message['event_type'].replace(self.resource_name, 'stack') + .replace('.end', '')) project_id = message['payload']['tenant_id'] # Trying to use the trustor_id if trusts is used by Heat, - user_id = message.get('_context_trustor_user_id') or \ - message['_context_user_id'] + user_id = (message.get('_context_trustor_user_id') or + message['_context_user_id']) yield sample.Sample.from_notification( name=name, diff --git a/ceilometer/pipeline.py b/ceilometer/pipeline.py index 6126798bc..3289b49ca 100644 --- a/ceilometer/pipeline.py +++ b/ceilometer/pipeline.py @@ -130,8 +130,8 @@ class Source(object): if not meters: raise PipelineException("No meter specified", self.cfg) - if [x for x in meters if x[0] not in '!*'] and \ - [x for x in meters if x[0] == '!']: + if ([x for x in meters if x[0] not in '!*'] and + [x for x in meters if x[0] == '!']): raise PipelineException( "Both included and excluded meters specified", cfg) diff --git a/ceilometer/publisher/rpc.py b/ceilometer/publisher/rpc.py index 3de9dbc62..12036d92a 100644 --- a/ceilometer/publisher/rpc.py +++ b/ceilometer/publisher/rpc.py @@ -148,8 +148,8 @@ class RPCPublisher(publisher.PublisherBase): # something in the self.local_queue queue = self.local_queue self.local_queue = [] - self.local_queue = self._process_queue(queue, self.policy) + \ - self.local_queue + self.local_queue = (self._process_queue(queue, self.policy) + + self.local_queue) if self.policy == 'queue': self._check_queue_length() diff --git a/ceilometer/storage/hbase/inmemory.py b/ceilometer/storage/hbase/inmemory.py index 4d864e743..8925c17b8 100644 --- a/ceilometer/storage/hbase/inmemory.py +++ b/ceilometer/storage/hbase/inmemory.py @@ -213,9 +213,9 @@ class MTable(object): data = rows[row] r_data = {} for key in data: - if (op == '=' and key.startswith(column)) or \ - (op == '>=' and key >= column) or \ - (op == '<=' and key <= column): + if ((op == '=' and key.startswith(column)) or + (op == '>=' and key >= column) or + (op == '<=' and key <= column)): r_data[key] = data[key] else: raise NotImplementedError("In-memory QualifierFilter " diff --git a/ceilometer/storage/impl_db2.py b/ceilometer/storage/impl_db2.py index 69a590c8e..98604e546 100644 --- a/ceilometer/storage/impl_db2.py +++ b/ceilometer/storage/impl_db2.py @@ -382,10 +382,12 @@ class Connection(pymongo_base.Connection): if period: stat.period = period periods = key.get('timestamp') - stat.period_start = period_start + \ - datetime.timedelta(**(_to_offset(periods))) - stat.period_end = period_start + \ - datetime.timedelta(**(_to_offset(periods + 1))) + stat.period_start = (period_start + + datetime. + timedelta(**(_to_offset(periods)))) + stat.period_end = (period_start + + datetime. + timedelta(**(_to_offset(periods + 1)))) else: stat.period_start = stat.duration_start stat.period_end = stat.duration_end diff --git a/ceilometer/storage/impl_hbase.py b/ceilometer/storage/impl_hbase.py index c69b93bf6..00d43f283 100644 --- a/ceilometer/storage/impl_hbase.py +++ b/ceilometer/storage/impl_hbase.py @@ -176,8 +176,8 @@ class Connection(base.Connection): if Connection._memory_instance is None: LOG.debug(_('Creating a new in-memory HBase ' 'Connection object')) - Connection._memory_instance = \ - hbase_inmemory.MConnectionPool() + Connection._memory_instance = (hbase_inmemory. + MConnectionPool()) self.conn_pool = Connection._memory_instance else: self.conn_pool = self._get_connection_pool(opts) @@ -477,9 +477,9 @@ class Connection(base.Connection): return with self.conn_pool.connection() as conn: meter_table = conn.table(self.METER_TABLE) - q, start, stop, columns = \ - hbase_utils.make_sample_query_from_filter( - sample_filter, require_meter=False) + q, start, stop, columns = (hbase_utils. + make_sample_query_from_filter + (sample_filter, require_meter=False)) LOG.debug(_("Query Meter Table: %s") % q) gen = meter_table.scan(filter=q, row_start=start, row_stop=stop, limit=limit) @@ -508,9 +508,8 @@ class Connection(base.Connection): stat.avg = (stat.sum / float(stat.count)) stat.duration_start = min(ts, stat.duration_start or ts) stat.duration_end = max(ts, stat.duration_end or ts) - stat.duration = \ - timeutils.delta_seconds(stat.duration_start, - stat.duration_end) + stat.duration = (timeutils.delta_seconds(stat.duration_start, + stat.duration_end)) def get_meter_statistics(self, sample_filter, period=None, groupby=None, aggregate=None): @@ -534,8 +533,9 @@ class Connection(base.Connection): with self.conn_pool.connection() as conn: meter_table = conn.table(self.METER_TABLE) - q, start, stop, columns = \ - hbase_utils.make_sample_query_from_filter(sample_filter) + q, start, stop, columns = (hbase_utils. + make_sample_query_from_filter + (sample_filter)) # These fields are used in statistics' calculating columns.extend(['f:timestamp', 'f:counter_volume', 'f:counter_unit']) @@ -575,8 +575,7 @@ class Connection(base.Connection): start_time, ts) / period) * period period_start = start_time + datetime.timedelta(0, offset) - if not results or not results[-1].period_start == \ - period_start: + if not results or not results[-1].period_start == period_start: if period: period_end = period_start + datetime.timedelta( 0, period) diff --git a/ceilometer/storage/impl_sqlalchemy.py b/ceilometer/storage/impl_sqlalchemy.py index 46d0d8354..f55d80fa8 100644 --- a/ceilometer/storage/impl_sqlalchemy.py +++ b/ceilometer/storage/impl_sqlalchemy.py @@ -250,10 +250,10 @@ class Connection(base.Connection): nested = session.connection().dialect.name != 'sqlite' with session.begin(nested=nested, subtransactions=not nested): - obj = session.query(models.Meter)\ - .filter(models.Meter.name == name)\ - .filter(models.Meter.type == type)\ - .filter(models.Meter.unit == unit).first() + obj = (session.query(models.Meter) + .filter(models.Meter.name == name) + .filter(models.Meter.type == type) + .filter(models.Meter.unit == unit).first()) if obj is None: obj = models.Meter(name=name, type=type, unit=unit) session.add(obj) @@ -314,8 +314,8 @@ class Connection(base.Connection): session = self._engine_facade.get_session() with session.begin(): end = timeutils.utcnow() - datetime.timedelta(seconds=ttl) - sample_query = session.query(models.Sample)\ - .filter(models.Sample.timestamp < end) + sample_query = (session.query(models.Sample) + .filter(models.Sample.timestamp < end)) for sample_obj in sample_query.all(): session.delete(sample_obj) @@ -374,15 +374,15 @@ class Connection(base.Connection): for res_id in res_q.all(): # get latest Sample - max_q = session.query(models.Sample)\ - .filter(models.Sample.resource_id == res_id[0]) + max_q = (session.query(models.Sample) + .filter(models.Sample.resource_id == res_id[0])) max_q = _apply_filters(max_q) max_q = max_q.order_by(models.Sample.timestamp.desc(), models.Sample.id.desc()).limit(1) # get the min timestamp value. - min_q = session.query(models.Sample.timestamp)\ - .filter(models.Sample.resource_id == res_id[0]) + min_q = (session.query(models.Sample.timestamp) + .filter(models.Sample.resource_id == res_id[0])) min_q = _apply_filters(min_q) min_q = min_q.order_by(models.Sample.timestamp.asc()).limit(1) @@ -433,17 +433,19 @@ class Connection(base.Connection): # by selecting a record for each (resource_id, meter_id). # max() is used to choice a sample record, so the latest record # is selected for each (resource_id, meter_id). - sample_subq = session.query( - func.max(models.Sample.id).label('id'))\ - .group_by(models.Sample.meter_id, models.Sample.resource_id) + sample_subq = (session.query( + func.max(models.Sample.id).label('id')) + .group_by(models.Sample.meter_id, + models.Sample.resource_id)) sample_subq = sample_subq.subquery() # SELECT sample.* FROM sample INNER JOIN # (SELECT max(sample.id) AS id FROM sample # GROUP BY sample.resource_id, sample.meter_id) AS anon_2 # ON sample.id = anon_2.id - query_sample = session.query(models.MeterSample).\ - join(sample_subq, models.MeterSample.id == sample_subq.c.id) + query_sample = (session.query(models.MeterSample). + join(sample_subq, models.MeterSample.id == + sample_subq.c.id)) query_sample = _apply_filters(query_sample) for sample in query_sample.all(): @@ -563,9 +565,9 @@ class Connection(base.Connection): group_attributes = [getattr(models.Sample, g) for g in groupby] select.extend(group_attributes) - query = session.query(*select).filter( - models.Meter.id == models.Sample.meter_id)\ - .group_by(models.Meter.unit) + query = (session.query(*select).filter( + models.Meter.id == models.Sample.meter_id). + group_by(models.Meter.unit)) if groupby: query = query.group_by(*group_attributes) @@ -972,8 +974,8 @@ class Connection(base.Connection): models.Event.event_type_id] if event_filter.event_type: - event_join_conditions\ - .append(models.EventType.desc == event_filter.event_type) + event_join_conditions.append(models.EventType.desc == + event_filter.event_type) event_query = event_query.join(models.EventType, and_(*event_join_conditions)) @@ -981,16 +983,16 @@ class Connection(base.Connection): # Build up the where conditions event_filter_conditions = [] if event_filter.message_id: - event_filter_conditions\ - .append(models.Event.message_id == event_filter.message_id) + event_filter_conditions.append(models.Event.message_id == + event_filter.message_id) if start: event_filter_conditions.append(models.Event.generated >= start) if end: event_filter_conditions.append(models.Event.generated <= end) if event_filter_conditions: - event_query = event_query\ - .filter(and_(*event_filter_conditions)) + event_query = (event_query. + filter(and_(*event_filter_conditions))) event_models_dict = {} if event_filter.traits_filter: @@ -1013,20 +1015,20 @@ class Connection(base.Connection): elif key == 'float': conditions.append(models.Trait.t_float == value) - trait_query = session.query(models.Trait.event_id)\ - .join(models.TraitType, and_(*conditions)).subquery() + trait_query = (session.query(models.Trait.event_id). + join(models.TraitType, + and_(*conditions)).subquery()) - event_query = event_query\ - .join(trait_query, - models.Event.id == trait_query.c.event_id) + event_query = (event_query. + join(trait_query, models.Event.id == + trait_query.c.event_id)) else: # If there are no trait filters, grab the events from the db - query = session.query(models.Event.id, - models.Event.generated, - models.Event.message_id, - models.EventType.desc)\ - .join(models.EventType, - and_(*event_join_conditions)) + query = (session.query(models.Event.id, + models.Event.generated, + models.Event.message_id, + models.EventType.desc). + join(models.EventType, and_(*event_join_conditions))) if event_filter_conditions: query = query.filter(and_(*event_filter_conditions)) for (id_, generated, message_id, desc_) in query.all(): @@ -1037,10 +1039,11 @@ class Connection(base.Connection): # Build event models for the events event_query = event_query.subquery() - query = session.query(models.Trait)\ - .join(models.TraitType, - models.Trait.trait_type_id == models.TraitType.id)\ - .join(event_query, models.Trait.event_id == event_query.c.id) + query = (session.query(models.Trait). + join(models.TraitType, models.Trait.trait_type_id == + models.TraitType.id). + join(event_query, models.Trait.event_id == + event_query.c.id)) # Now convert the sqlalchemy objects back into Models ... for trait in query.all(): @@ -1065,8 +1068,8 @@ class Connection(base.Connection): session = self._engine_facade.get_session() with session.begin(): - query = session.query(models.EventType.desc)\ - .order_by(models.EventType.desc) + query = (session.query(models.EventType.desc). + order_by(models.EventType.desc)) for name in query.all(): # The query returns a tuple with one element. yield name[0] diff --git a/ceilometer/storage/models.py b/ceilometer/storage/models.py index f61b83f79..d196b151e 100644 --- a/ceilometer/storage/models.py +++ b/ceilometer/storage/models.py @@ -51,9 +51,9 @@ class Event(base.Model): trait_list = [] if self.traits: trait_list = [str(trait) for trait in self.traits] - return "" % \ - (self.message_id, self.event_type, self.generated, - " ".join(trait_list)) + return ("" % + (self.message_id, self.event_type, self.generated, + " ".join(trait_list))) class Trait(base.Model): diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/003_set_utf8_charset.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/003_set_utf8_charset.py index c9cf42568..30824462c 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/003_set_utf8_charset.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/003_set_utf8_charset.py @@ -23,8 +23,8 @@ def upgrade(migrate_engine): for table in tables: sql += "ALTER TABLE %s CONVERT TO CHARACTER SET utf8;" % table sql += "SET foreign_key_checks = 1;" - sql += "ALTER DATABASE %s DEFAULT CHARACTER SET utf8;" \ - % migrate_engine.url.database + sql += ("ALTER DATABASE %s DEFAULT CHARACTER SET utf8;" % + migrate_engine.url.database) migrate_engine.execute(sql) @@ -38,6 +38,6 @@ def downgrade(migrate_engine): for table in tables: sql += "ALTER TABLE %s CONVERT TO CHARACTER SET latin1;" % table sql += "SET foreign_key_checks = 1;" - sql += "ALTER DATABASE %s DEFAULT CHARACTER SET latin1;" \ - % migrate_engine.url.database + sql += ("ALTER DATABASE %s DEFAULT CHARACTER SET latin1;" % + migrate_engine.url.database) migrate_engine.execute(sql) diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/014_add_event_message_id.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/014_add_event_message_id.py index 2d2466566..0347208b8 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/014_add_event_message_id.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/014_add_event_message_id.py @@ -40,10 +40,8 @@ def upgrade(migrate_engine): from_obj=join) for event_id, value in traits.execute(): - event.update().\ - where(event.c.id == event_id).\ - values(message_id=value).\ - execute() + (event.update().where(event.c.id == event_id).values(message_id=value). + execute()) # Leave the Trait, makes the rollback easier and won't really hurt anyone. diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/017_convert_timestamp_as_datetime_to_decimal.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/017_convert_timestamp_as_datetime_to_decimal.py index 0c2664478..669fac7b3 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/017_convert_timestamp_as_datetime_to_decimal.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/017_convert_timestamp_as_datetime_to_decimal.py @@ -38,8 +38,8 @@ def _convert_data_type(table, col, from_t, to_t, pk_attr='id', index=False): query = sa.select([key_attr, orig_col]) for key, value in migration.paged(query): - table.update().where(key_attr == key)\ - .values({temp_col_n: value}).execute() + (table.update().where(key_attr == key).values({temp_col_n: value}). + execute()) orig_col.drop() new_col.alter(name=col) diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/021_add_event_types.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/021_add_event_types.py index 1baae51a9..825e24f5b 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/021_add_event_types.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/021_add_event_types.py @@ -63,10 +63,9 @@ def upgrade(migrate_engine): # and delete the entry from the unique_name table query = select([event.c.id, event.c.unique_name_id]) for key, value in migration.paged(query): - event.update().where(event.c.id == key)\ - .values({"event_type_id": value}).execute() - unique_name.delete()\ - .where(unique_name.c.id == key).execute() + (event.update().where(event.c.id == key). + values({"event_type_id": value}).execute()) + unique_name.delete().where(unique_name.c.id == key).execute() params = {'columns': [event.c.event_type_id], 'refcolumns': [event_type.c.id]} @@ -108,8 +107,8 @@ def downgrade(migrate_engine): # Move data from event_type_id column to unique_name_id column query = select([event.c.id, event.c.event_type_id]) for key, value in migration.paged(query): - event.update().where(event.c.id == key)\ - .values({"unique_name_id": value}).execute() + (event.update().where(event.c.id == key). + values({"unique_name_id": value}).execute()) event.c.event_type_id.drop() params = {'columns': [event.c.unique_name_id], diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/023_add_trait_types.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/023_add_trait_types.py index 1f76f7d4d..cd2c51465 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/023_add_trait_types.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/023_add_trait_types.py @@ -65,8 +65,8 @@ def upgrade(migrate_engine): # Move data from name_id column into trait_type_id column query = select([trait.c.id, trait.c.name_id]) for key, value in migration.paged(query): - trait.update().where(trait.c.id == key)\ - .values({"trait_type_id": value}).execute() + (trait.update().where(trait.c.id == key). + values({"trait_type_id": value}).execute()) trait.c.name_id.drop() @@ -128,14 +128,14 @@ def downgrade(migrate_engine): # copy data from trait_type.data_type into trait.t_type query = select([trait_type.c.id, trait_type.c.data_type]) for key, value in migration.paged(query): - trait.update().where(trait.c.trait_type_id == key)\ - .values({"t_type": value}).execute() + (trait.update().where(trait.c.trait_type_id == key). + values({"t_type": value}).execute()) # Move data from name_id column into trait_type_id column query = select([trait.c.id, trait.c.trait_type_id]) for key, value in migration.paged(query): - trait.update().where(trait.c.id == key)\ - .values({"name_id": value}).execute() + (trait.update().where(trait.c.id == key). + values({"name_id": value}).execute()) # Add a foreign key to the unique_name table params = {'columns': [trait.c.name_id], diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/024_event_use_floatingprecision.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/024_event_use_floatingprecision.py index 837b26808..e7e26e8a8 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/024_event_use_floatingprecision.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/024_event_use_floatingprecision.py @@ -36,8 +36,8 @@ def _convert_data_type(table, col, from_t, to_t, pk_attr='id', index=False): query = sa.select([key_attr, orig_col]) for key, value in migration.paged(query): - table.update().where(key_attr == key)\ - .values({temp_col_n: value}).execute() + (table.update().where(key_attr == key).values({temp_col_n: value}). + execute()) orig_col.drop() new_col.alter(name=col) diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/025_alarm_use_floatingprecision.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/025_alarm_use_floatingprecision.py index 32ca640bf..ab476e272 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/025_alarm_use_floatingprecision.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/025_alarm_use_floatingprecision.py @@ -36,8 +36,8 @@ def _convert_data_type(table, col, from_t, to_t, pk_attr='id'): query = sa.select([key_attr, orig_col]) for key, value in migration.paged(query): - table.update().where(key_attr == key)\ - .values({temp_col_n: value}).execute() + (table.update().where(key_attr == key).values({temp_col_n: value}). + execute()) orig_col.drop() new_col.alter(name=col) diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/031_add_new_meter_table.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/031_add_new_meter_table.py index b02674bf4..c8ed0e6a4 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/031_add_new_meter_table.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/031_add_new_meter_table.py @@ -73,11 +73,11 @@ def upgrade(migrate_engine): index.create(bind=migrate_engine) for row in sa.select([meter]).execute(): - sample.update()\ - .where(sa.and_(sample.c.counter_name == row['name'], - sample.c.counter_type == row['type'], - sample.c.counter_unit == row['unit']))\ - .values({sample.c.meter_id: row['id']}).execute() + (sample.update(). + where(sa.and_(sample.c.counter_name == row['name'], + sample.c.counter_type == row['type'], + sample.c.counter_unit == row['unit'])). + values({sample.c.meter_id: row['id']}).execute()) handle_rid_index(meta) @@ -96,11 +96,11 @@ def downgrade(migrate_engine): sa.Column('counter_unit', sa.String(255)).create(sample) meter = sa.Table('meter', meta, autoload=True) for row in sa.select([meter]).execute(): - sample.update()\ - .where(sample.c.meter_id == row['id'])\ - .values({sample.c.counter_name: row['name'], - sample.c.counter_type: row['type'], - sample.c.counter_unit: row['unit']}).execute() + (sample.update(). + where(sample.c.meter_id == row['id']). + values({sample.c.counter_name: row['name'], + sample.c.counter_type: row['type'], + sample.c.counter_unit: row['unit']}).execute()) params = {'columns': [sample.c.meter_id], 'refcolumns': [meter.c.id]} diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/034_drop_dump_tables.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/034_drop_dump_tables.py index 641c7eff7..8f4e435fd 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/034_drop_dump_tables.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/034_drop_dump_tables.py @@ -21,14 +21,14 @@ def upgrade(migrate_engine): meta = sa.MetaData(bind=migrate_engine) for table_name in TABLES_027: try: - sa.Table('dump027_' + table_name, meta, autoload=True)\ - .drop(checkfirst=True) + (sa.Table('dump027_' + table_name, meta, autoload=True). + drop(checkfirst=True)) except sa.exc.NoSuchTableError: pass for table_name in TABLES_012: try: - sa.Table('dump_' + table_name, meta, autoload=True)\ - .drop(checkfirst=True) + (sa.Table('dump_' + table_name, meta, autoload=True). + drop(checkfirst=True)) except sa.exc.NoSuchTableError: pass diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/035_drop_user_project_tables.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/035_drop_user_project_tables.py index 7b95d7f7d..d1e3778ec 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/035_drop_user_project_tables.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/035_drop_user_project_tables.py @@ -46,11 +46,11 @@ def upgrade(migrate_engine): params = {'columns': [table.c[column]], 'refcolumns': [ref_table.c[ref_column_name]]} - if migrate_engine.name == "mysql" and \ - table_name != 'alarm_history': + if (migrate_engine.name == "mysql" and + table_name != 'alarm_history'): params['name'] = "_".join(('fk', table_name, column)) - elif migrate_engine.name == "postgresql" and \ - table_name == "sample": + elif (migrate_engine.name == "postgresql" and + table_name == "sample"): # The fk contains the old table name params['name'] = "_".join(('meter', column, 'fkey')) @@ -163,11 +163,11 @@ def downgrade(migrate_engine): params = {'columns': [table.c[column]], 'refcolumns': [ref_table.c[ref_column_name]]} - if migrate_engine.name == "mysql" and \ - table_name != 'alarm_history': + if (migrate_engine.name == "mysql" and + table_name != 'alarm_history'): params['name'] = "_".join(('fk', table_name, column)) - elif migrate_engine.name == "postgresql" and \ - table_name == "sample": + elif (migrate_engine.name == "postgresql" and + table_name == "sample"): # The fk contains the old table name params['name'] = "_".join(('meter', column, 'fkey')) diff --git a/ceilometer/storage/sqlalchemy/migrate_repo/versions/036_drop_sourceassoc_resource_tables.py b/ceilometer/storage/sqlalchemy/migrate_repo/versions/036_drop_sourceassoc_resource_tables.py index 931b03d6f..380336e1d 100644 --- a/ceilometer/storage/sqlalchemy/migrate_repo/versions/036_drop_sourceassoc_resource_tables.py +++ b/ceilometer/storage/sqlalchemy/migrate_repo/versions/036_drop_sourceassoc_resource_tables.py @@ -58,11 +58,11 @@ def upgrade(migrate_engine): # move source values to samples sourceassoc = load_tables['sourceassoc'] - query = sa.select([sourceassoc.c.sample_id, sourceassoc.c.source_id])\ - .where(sourceassoc.c.sample_id.isnot(None)) + query = (sa.select([sourceassoc.c.sample_id, sourceassoc.c.source_id]). + where(sourceassoc.c.sample_id.isnot(None))) for sample_id, source_id in migration.paged(query): - sample.update().where(sample_id == sample.c.id)\ - .values({'source_id': source_id}).execute() + (sample.update().where(sample_id == sample.c.id). + values({'source_id': source_id}).execute()) # drop tables for table_name in DROP_TABLES: diff --git a/ceilometer/storage/sqlalchemy/models.py b/ceilometer/storage/sqlalchemy/models.py index 696d9431a..4e48a4c54 100644 --- a/ceilometer/storage/sqlalchemy/models.py +++ b/ceilometer/storage/sqlalchemy/models.py @@ -19,8 +19,8 @@ SQLAlchemy models for Ceilometer data. import json -from sqlalchemy import Column, Integer, String, ForeignKey, \ - Index, UniqueConstraint, BigInteger, join +from sqlalchemy import (Column, Integer, String, ForeignKey, Index, + UniqueConstraint, BigInteger, join) from sqlalchemy import Float, Boolean, Text, DateTime from sqlalchemy.dialects.mysql import DECIMAL from sqlalchemy.ext.declarative import declarative_base @@ -375,8 +375,8 @@ class Trait(Base): def __repr__(self): name = self.trait_type.name if self.trait_type else None - data_type = self.trait_type.data_type if self.trait_type\ - else api_models.Trait.NONE_TYPE + data_type = (self.trait_type.data_type if self.trait_type else + api_models.Trait.NONE_TYPE) return "" % (name, data_type, diff --git a/ceilometer/tests/alarm/evaluator/test_threshold.py b/ceilometer/tests/alarm/evaluator/test_threshold.py index 66d27898f..6a4ca1975 100644 --- a/ceilometer/tests/alarm/evaluator/test_threshold.py +++ b/ceilometer/tests/alarm/evaluator/test_threshold.py @@ -233,8 +233,8 @@ class TestEvaluate(base.TestEvaluatorBase): self._assert_all_alarms('ok') self.assertEqual([], self.api_client.alarms.set_state.call_args_list) - reason = 'Remaining as ok due to 4 samples inside' \ - ' threshold, most recent: 8.0' + reason = ('Remaining as ok due to 4 samples inside' + ' threshold, most recent: 8.0') reason_datas = self._reason_data('inside', 4, 8.0) expected = [mock.call(self.alarms[1], 'ok', reason, reason_datas)] self.assertEqual(expected, self.notifier.notify.call_args_list) @@ -255,8 +255,8 @@ class TestEvaluate(base.TestEvaluatorBase): self._assert_all_alarms('alarm') self.assertEqual([], self.api_client.alarms.set_state.call_args_list) - reason = 'Remaining as alarm due to 4 samples outside' \ - ' threshold, most recent: 7.0' + reason = ('Remaining as alarm due to 4 samples outside' + ' threshold, most recent: 7.0') reason_datas = self._reason_data('outside', 4, 7.0) expected = [mock.call(self.alarms[1], 'alarm', reason, reason_datas)] diff --git a/ceilometer/tests/api/v2/test_alarm_scenarios.py b/ceilometer/tests/api/v2/test_alarm_scenarios.py index 4976a0ba8..f7614f07e 100644 --- a/ceilometer/tests/api/v2/test_alarm_scenarios.py +++ b/ceilometer/tests/api/v2/test_alarm_scenarios.py @@ -1939,12 +1939,12 @@ class TestAlarms(v2.FunctionalTest, class PayloadMatcher(object): def __eq__(self, payload): - return payload['detail']['name'] == 'sent_notification' and \ - payload['type'] == 'creation' and \ - payload['detail']['rule']['meter_name'] == 'ameter' and \ - set(['alarm_id', 'detail', 'event_id', 'on_behalf_of', - 'project_id', 'timestamp', - 'user_id']).issubset(payload.keys()) + return (payload['detail']['name'] == 'sent_notification' and + payload['type'] == 'creation' and + payload['detail']['rule']['meter_name'] == 'ameter' and + set(['alarm_id', 'detail', 'event_id', 'on_behalf_of', + 'project_id', 'timestamp', + 'user_id']).issubset(payload.keys())) endpoint.info.assert_called_once_with( {'instance_uuid': None, diff --git a/ceilometer/tests/api/v2/test_app.py b/ceilometer/tests/api/v2/test_app.py index b75260241..b98898efc 100644 --- a/ceilometer/tests/api/v2/test_app.py +++ b/ceilometer/tests/api/v2/test_app.py @@ -57,15 +57,15 @@ class TestApp(base.BaseTestCase): def test_keystone_middleware_parse_conffile(self): pipeline_conf = self.path_get("etc/ceilometer/pipeline.yaml") api_conf = self.path_get('etc/ceilometer/api_paste.ini') - content = "[DEFAULT]\n"\ - "rpc_backend = fake\n"\ - "pipeline_cfg_file = {0}\n"\ - "api_paste_config = {1}\n"\ - "[{2}]\n"\ - "auth_protocol = file\n"\ - "auth_version = v2.0\n".format(pipeline_conf, - api_conf, - acl.OPT_GROUP_NAME) + content = ("[DEFAULT]\n" + "rpc_backend = fake\n" + "pipeline_cfg_file = {0}\n" + "api_paste_config = {1}\n" + "[{2}]\n" + "auth_protocol = file\n" + "auth_version = v2.0\n".format(pipeline_conf, + api_conf, + acl.OPT_GROUP_NAME)) tmpfile = fileutils.write_to_tempfile(content=content, prefix='ceilometer', @@ -217,8 +217,8 @@ class TestApiMiddleware(v2.FunctionalTest): json.loads(resp.body)['error_message'] ['faultstring']) - with mock.patch('ceilometer.api.controllers.v2.EntityNotFound') \ - as CustomErrorClass: + with mock.patch('ceilometer.api.controllers.' + 'v2.EntityNotFound') as CustomErrorClass: CustomErrorClass.return_value = wsme.exc.ClientSideError( "untranslated_error", status_code=404) resp = self.get_json('/alarms/alarm-id-5', expect_errors=True) diff --git a/ceilometer/tests/api/v2/test_event_scenarios.py b/ceilometer/tests/api/v2/test_event_scenarios.py index 5792eea4a..0e8c50c9b 100644 --- a/ceilometer/tests/api/v2/test_event_scenarios.py +++ b/ceilometer/tests/api/v2/test_event_scenarios.py @@ -36,17 +36,16 @@ class EventTestBase(v2.FunctionalTest, base = 0 self.trait_time = datetime.datetime(2013, 12, 31, 5, 0) for event_type in ['Foo', 'Bar', 'Zoo']: - trait_models = \ - [models.Trait(name, type, value) - for name, type, value in [ - ('trait_A', models.Trait.TEXT_TYPE, - "my_%s_text" % event_type), - ('trait_B', models.Trait.INT_TYPE, - base + 1), - ('trait_C', models.Trait.FLOAT_TYPE, - float(base) + 0.123456), - ('trait_D', models.Trait.DATETIME_TYPE, - self.trait_time)]] + trait_models = [models.Trait(name, type, value) + for name, type, value in [ + ('trait_A', models.Trait.TEXT_TYPE, + "my_%s_text" % event_type), + ('trait_B', models.Trait.INT_TYPE, + base + 1), + ('trait_C', models.Trait.FLOAT_TYPE, + float(base) + 0.123456), + ('trait_D', models.Trait.DATETIME_TYPE, + self.trait_time)]] # Message ID for test will be 'base'. So, message ID for the first # event will be '0', the second '100', and so on. diff --git a/ceilometer/tests/compute/pollsters/test_cpu.py b/ceilometer/tests/compute/pollsters/test_cpu.py index 8a46381d7..783276c05 100644 --- a/ceilometer/tests/compute/pollsters/test_cpu.py +++ b/ceilometer/tests/compute/pollsters/test_cpu.py @@ -94,8 +94,8 @@ class TestCPUUtilPollster(base.TestPollsterBase): def inspect_cpu_util(name, duration): return six.next(next_value) - self.inspector.inspect_cpu_util = \ - mock.Mock(side_effect=inspect_cpu_util) + self.inspector.inspect_cpu_util = (mock. + Mock(side_effect=inspect_cpu_util)) mgr = manager.AgentManager() pollster = cpu.CPUUtilPollster() diff --git a/ceilometer/tests/compute/pollsters/test_diskio.py b/ceilometer/tests/compute/pollsters/test_diskio.py index 6226c43fe..91e6db239 100644 --- a/ceilometer/tests/compute/pollsters/test_diskio.py +++ b/ceilometer/tests/compute/pollsters/test_diskio.py @@ -85,8 +85,7 @@ class TestDiskRatePollsters(base.TestPollsterBase): def setUp(self): super(TestDiskRatePollsters, self).setUp() - self.inspector.inspect_disk_rates = \ - mock.Mock(return_value=self.DISKS) + self.inspector.inspect_disk_rates = mock.Mock(return_value=self.DISKS) @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock()) def _check_get_samples(self, factory, sample_name, expected_volume): diff --git a/ceilometer/tests/compute/pollsters/test_memory.py b/ceilometer/tests/compute/pollsters/test_memory.py index d3cc302a2..f1c805a97 100644 --- a/ceilometer/tests/compute/pollsters/test_memory.py +++ b/ceilometer/tests/compute/pollsters/test_memory.py @@ -37,8 +37,8 @@ class TestMemoryPollster(base.TestPollsterBase): def inspect_memory_usage(instance, duration): return six.next(next_value) - self.inspector.inspect_memory_usage = \ - mock.Mock(side_effect=inspect_memory_usage) + (self.inspector. + inspect_memory_usage) = mock.Mock(side_effect=inspect_memory_usage) mgr = manager.AgentManager() pollster = memory.MemoryUsagePollster() diff --git a/ceilometer/tests/compute/virt/vmware/test_inspector.py b/ceilometer/tests/compute/virt/vmware/test_inspector.py index 1ecd7923c..6c6dd0cb0 100644 --- a/ceilometer/tests/compute/virt/vmware/test_inspector.py +++ b/ceilometer/tests/compute/virt/vmware/test_inspector.py @@ -51,10 +51,10 @@ class TestVsphereInspection(test.BaseTestCase): fake_instance = construct_mock_instance_object(fake_instance_id) self._inspector._ops.get_vm_moid.return_value = fake_instance_moid - self._inspector._ops.get_perf_counter_id.return_value = \ - fake_perf_counter_id - self._inspector._ops.query_vm_aggregate_stats.return_value = \ - fake_memory_value + (self._inspector._ops. + get_perf_counter_id.return_value) = fake_perf_counter_id + (self._inspector._ops.query_vm_aggregate_stats. + return_value) = fake_memory_value memory_stat = self._inspector.inspect_memory_usage(fake_instance) self.assertEqual(fake_stat, memory_stat) @@ -72,10 +72,10 @@ class TestVsphereInspection(test.BaseTestCase): fake_instance = construct_mock_instance_object(fake_instance_id) self._inspector._ops.get_vm_moid.return_value = fake_instance_moid - self._inspector._ops.get_perf_counter_id.return_value = \ - fake_perf_counter_id - self._inspector._ops.query_vm_aggregate_stats.return_value = \ - fake_cpu_util_value * 100 + (self._inspector._ops.get_perf_counter_id. + return_value) = fake_perf_counter_id + (self._inspector._ops.query_vm_aggregate_stats. + return_value) = fake_cpu_util_value * 100 cpu_util_stat = self._inspector.inspect_cpu_util(fake_instance) self.assertEqual(fake_stat, cpu_util_stat) @@ -107,8 +107,7 @@ class TestVsphereInspection(test.BaseTestCase): ops_mock = self._inspector._ops ops_mock.get_vm_moid.return_value = test_vm_moid ops_mock.get_perf_counter_id.side_effect = get_counter_id_side_effect - ops_mock.query_vm_device_stats.side_effect = \ - query_stat_side_effect + ops_mock.query_vm_device_stats.side_effect = query_stat_side_effect result = self._inspector.inspect_vnic_rates(mock.MagicMock()) # validate result diff --git a/ceilometer/tests/compute/virt/vmware/test_vsphere_operations.py b/ceilometer/tests/compute/virt/vmware/test_vsphere_operations.py index 072820975..c81dfb00d 100644 --- a/ceilometer/tests/compute/virt/vmware/test_vsphere_operations.py +++ b/ceilometer/tests/compute/virt/vmware/test_vsphere_operations.py @@ -111,8 +111,8 @@ class VsphereOperationsTest(test.BaseTestCase): counter_info1 = construct_mock_counter_info("a", "b", "c", 1) counter_info2 = construct_mock_counter_info("x", "y", "z", 2) result = mock.MagicMock() - result.objects[0].propSet[0].val.PerfCounterInfo.__iter__. \ - return_value = [counter_info1, counter_info2] + (result.objects[0].propSet[0].val.PerfCounterInfo.__iter__. + return_value) = [counter_info1, counter_info2] return result vim_mock = self._vsphere_ops._api_session._vim diff --git a/ceilometer/tests/event/test_endpoint.py b/ceilometer/tests/event/test_endpoint.py index 658b15d85..15b3330a6 100644 --- a/ceilometer/tests/event/test_endpoint.py +++ b/ceilometer/tests/event/test_endpoint.py @@ -94,10 +94,14 @@ class TestEventEndpoint(tests_base.BaseTestCase): self.mock_dispatcher = mock.MagicMock() self.endpoint = event_endpoint.EventsNotificationEndpoint() - self.endpoint.dispatcher_manager = \ - extension.ExtensionManager.make_test_instance([ - extension.Extension('test', None, None, self.mock_dispatcher) - ]) + (self.endpoint. + dispatcher_manager) = (extension.ExtensionManager. + make_test_instance([extension. + Extension('test', None, + None, + self. + mock_dispatcher) + ])) self.endpoint.event_converter = mock.MagicMock() self.endpoint.event_converter.to_event.return_value = mock.MagicMock( event_type='test.test') diff --git a/ceilometer/tests/network/statistics/opendaylight/test_driver.py b/ceilometer/tests/network/statistics/opendaylight/test_driver.py index 59bef11f6..f85fdc080 100644 --- a/ceilometer/tests/network/statistics/opendaylight/test_driver.py +++ b/ceilometer/tests/network/statistics/opendaylight/test_driver.py @@ -17,7 +17,7 @@ import abc import mock import six from six import moves -from six.moves.urllib import parse as urlparse +from six.moves.urllib import parse as url_parse from ceilometer.network.statistics.opendaylight import driver from ceilometer.openstack.common import test @@ -58,20 +58,20 @@ class _Base(test.BaseTestCase): def inactive_hosts_data(self): pass - fake_odl_url = urlparse.ParseResult('opendaylight', - 'localhost:8080', - 'controller/nb/v2', - None, - None, - None) + fake_odl_url = url_parse.ParseResult('opendaylight', + 'localhost:8080', + 'controller/nb/v2', + None, + None, + None) - fake_params = urlparse.parse_qs('user=admin&password=admin&scheme=http&' - 'container_name=default&auth=basic') + fake_params = url_parse.parse_qs('user=admin&password=admin&scheme=http&' + 'container_name=default&auth=basic') - fake_params_multi_container = \ - urlparse.parse_qs('user=admin&password=admin&scheme=http&' - 'container_name=first&container_name=second&' - 'auth=basic') + fake_params_multi_container = ( + url_parse.parse_qs('user=admin&password=admin&scheme=http&' + 'container_name=first&container_name=second&' + 'auth=basic')) def setUp(self): super(_Base, self).setUp() diff --git a/ceilometer/tests/pipeline_base.py b/ceilometer/tests/pipeline_base.py index 831c1838e..4bc9c219d 100644 --- a/ceilometer/tests/pipeline_base.py +++ b/ceilometer/tests/pipeline_base.py @@ -866,9 +866,9 @@ class BasePipelineTestCase(test.BaseTestCase): def _do_test_rate_of_change_conversion(self, prev, curr, type, expected, offset=1, weight=None): - s = "(resource_metadata.user_metadata.autoscaling_weight or 1.0)" \ - "* (resource_metadata.non.existent or 1.0)" \ - "* (100.0 / (10**9 * (resource_metadata.cpu_number or 1)))" + s = ("(resource_metadata.user_metadata.autoscaling_weight or 1.0)" + "* (resource_metadata.non.existent or 1.0)" + "* (100.0 / (10**9 * (resource_metadata.cpu_number or 1)))") transformer_cfg = [ { 'name': 'rate_of_change', diff --git a/ceilometer/tests/publisher/test_rpc_publisher.py b/ceilometer/tests/publisher/test_rpc_publisher.py index 78ff429e6..5555f32d9 100644 --- a/ceilometer/tests/publisher/test_rpc_publisher.py +++ b/ceilometer/tests/publisher/test_rpc_publisher.py @@ -105,8 +105,8 @@ class TestPublish(tests_base.BaseTestCase): endpoint = mock.MagicMock(['record_metering_data']) collector = messaging.get_rpc_server( self.transport, self.CONF.publisher_rpc.metering_topic, endpoint) - endpoint.record_metering_data.side_effect = \ - lambda *args, **kwds: collector.stop() + endpoint.record_metering_data.side_effect = (lambda *args, **kwds: + collector.stop()) collector.start() eventlet.sleep() diff --git a/ceilometer/tests/storage/test_impl_mongodb.py b/ceilometer/tests/storage/test_impl_mongodb.py index 09869d6c9..dbea9989d 100644 --- a/ceilometer/tests/storage/test_impl_mongodb.py +++ b/ceilometer/tests/storage/test_impl_mongodb.py @@ -188,6 +188,6 @@ class CapabilitiesTest(test_base.BaseTestCase): expected_capabilities = { 'storage': {'production_ready': True}, } - actual_capabilities = impl_mongodb.Connection.\ - get_storage_capabilities() + actual_capabilities = (impl_mongodb.Connection. + get_storage_capabilities()) self.assertEqual(expected_capabilities, actual_capabilities) diff --git a/ceilometer/tests/storage/test_impl_sqlalchemy.py b/ceilometer/tests/storage/test_impl_sqlalchemy.py index 112182baa..047cafa1a 100644 --- a/ceilometer/tests/storage/test_impl_sqlalchemy.py +++ b/ceilometer/tests/storage/test_impl_sqlalchemy.py @@ -240,6 +240,6 @@ class CapabilitiesTest(test_base.BaseTestCase): expected_capabilities = { 'storage': {'production_ready': True}, } - actual_capabilities = impl_sqlalchemy.Connection.\ - get_storage_capabilities() + actual_capabilities = (impl_sqlalchemy. + Connection.get_storage_capabilities()) self.assertEqual(expected_capabilities, actual_capabilities) diff --git a/ceilometer/tests/storage/test_storage_scenarios.py b/ceilometer/tests/storage/test_storage_scenarios.py index 20b2e6dfc..43c5b3bb4 100644 --- a/ceilometer/tests/storage/test_storage_scenarios.py +++ b/ceilometer/tests/storage/test_storage_scenarios.py @@ -2737,16 +2737,15 @@ class GetEventTest(EventTestBase): self.start = datetime.datetime(2013, 12, 31, 5, 0) now = self.start for event_type in ['Foo', 'Bar', 'Zoo', 'Foo', 'Bar', 'Zoo']: - trait_models = \ - [models.Trait(name, dtype, value) - for name, dtype, value in [ - ('trait_A', models.Trait.TEXT_TYPE, - "my_%s_text" % event_type), - ('trait_B', models.Trait.INT_TYPE, - base + 1), - ('trait_C', models.Trait.FLOAT_TYPE, - float(base) + 0.123456), - ('trait_D', models.Trait.DATETIME_TYPE, now)]] + trait_models = [models.Trait(name, dtype, value) + for name, dtype, value in [ + ('trait_A', models.Trait.TEXT_TYPE, + "my_%s_text" % event_type), + ('trait_B', models.Trait.INT_TYPE, + base + 1), + ('trait_C', models.Trait.FLOAT_TYPE, + float(base) + 0.123456), + ('trait_D', models.Trait.DATETIME_TYPE, now)]] self.event_models.append( models.Event("id_%s_%d" % (event_type, base), event_type, now, trait_models)) @@ -2888,8 +2887,7 @@ class GetEventTest(EventTestBase): trait_dict["trait_D"]) def test_get_all_traits(self): - traits = self.conn.\ - get_traits("Foo") + traits = self.conn.get_traits("Foo") traits = [t for t in traits] self.assertEqual(8, len(traits)) diff --git a/ceilometer/tests/test_bin.py b/ceilometer/tests/test_bin.py index 2f4789bbd..61f67a604 100644 --- a/ceilometer/tests/test_bin.py +++ b/ceilometer/tests/test_bin.py @@ -80,9 +80,9 @@ class BinSendSampleTestCase(base.BaseTestCase): def setUp(self): super(BinSendSampleTestCase, self).setUp() pipeline_cfg_file = self.path_get('etc/ceilometer/pipeline.yaml') - content = "[DEFAULT]\n"\ - "rpc_backend=fake\n"\ - "pipeline_cfg_file={0}\n".format(pipeline_cfg_file) + content = ("[DEFAULT]\n" + "rpc_backend=fake\n" + "pipeline_cfg_file={0}\n".format(pipeline_cfg_file)) self.tempfile = fileutils.write_to_tempfile(content=content, prefix='ceilometer', @@ -105,11 +105,10 @@ class BinApiTestCase(base.BaseTestCase): def setUp(self): super(BinApiTestCase, self).setUp() # create api_paste.ini file without authentication - content = \ - "[pipeline:main]\n"\ - "pipeline = api-server\n"\ - "[app:api-server]\n"\ - "paste.app_factory = ceilometer.api.app:app_factory\n" + content = ("[pipeline:main]\n" + "pipeline = api-server\n" + "[app:api-server]\n" + "paste.app_factory = ceilometer.api.app:app_factory\n") self.paste = fileutils.write_to_tempfile(content=content, prefix='api_paste', suffix='.ini') @@ -119,20 +118,20 @@ class BinApiTestCase(base.BaseTestCase): self.http = httplib2.Http() pipeline_cfg_file = self.path_get('etc/ceilometer/pipeline.yaml') policy_file = self.path_get('etc/ceilometer/policy.json') - content = "[DEFAULT]\n"\ - "rpc_backend=fake\n"\ - "auth_strategy=noauth\n"\ - "debug=true\n"\ - "pipeline_cfg_file={0}\n"\ - "policy_file={1}\n"\ - "api_paste_config={2}\n"\ - "[api]\n"\ - "port={3}\n"\ - "[database]\n"\ - "connection=log://localhost\n".format(pipeline_cfg_file, - policy_file, - self.paste, - self.api_port) + content = ("[DEFAULT]\n" + "rpc_backend=fake\n" + "auth_strategy=noauth\n" + "debug=true\n" + "pipeline_cfg_file={0}\n" + "policy_file={1}\n" + "api_paste_config={2}\n" + "[api]\n" + "port={3}\n" + "[database]\n" + "connection=log://localhost\n".format(pipeline_cfg_file, + policy_file, + self.paste, + self.api_port)) self.tempfile = fileutils.write_to_tempfile(content=content, prefix='ceilometer', diff --git a/ceilometer/tests/test_notification.py b/ceilometer/tests/test_notification.py index c334b4771..acc435151 100644 --- a/ceilometer/tests/test_notification.py +++ b/ceilometer/tests/test_notification.py @@ -112,8 +112,8 @@ class TestNotification(tests_base.BaseTestCase): @mock.patch('ceilometer.event.endpoint.EventsNotificationEndpoint') def _do_process_notification_manager_start(self, fake_event_endpoint_class): - with mock.patch.object(self.srv, '_get_notifications_manager') \ - as get_nm: + with mock.patch.object(self.srv, + '_get_notifications_manager') as get_nm: get_nm.side_effect = self.fake_get_notifications_manager self.srv.start() self.fake_event_endpoint = fake_event_endpoint_class.return_value @@ -155,8 +155,8 @@ class TestNotification(tests_base.BaseTestCase): mock.MagicMock()) def test_event_dispatcher_loaded(self): self.CONF.set_override("store_events", True, group="notification") - with mock.patch.object(self.srv, '_get_notifications_manager') \ - as get_nm: + with mock.patch.object(self.srv, + '_get_notifications_manager') as get_nm: get_nm.side_effect = self.fake_get_notifications_manager self.srv.start() self.assertEqual(2, len(self.srv.listeners[0].dispatcher.endpoints)) diff --git a/ceilometer/transformer/conversions.py b/ceilometer/transformer/conversions.py index 6c4fc58e4..db7d07fe9 100644 --- a/ceilometer/transformer/conversions.py +++ b/ceilometer/transformer/conversions.py @@ -239,9 +239,9 @@ class AggregatorTransformer(ScalingTransformer): getattr(sample, field)) def flush(self, context): - expired = self.retention_time and \ - timeutils.is_older_than(self.initial_timestamp, - self.retention_time) + expired = (self.retention_time and + timeutils.is_older_than(self.initial_timestamp, + self.retention_time)) full = self.aggregated_samples >= self.size if full or expired: x = self.samples.values() diff --git a/ceilometer/utils.py b/ceilometer/utils.py index ec0a7a7f8..6d217e2ea 100644 --- a/ceilometer/utils.py +++ b/ceilometer/utils.py @@ -80,9 +80,9 @@ def dt_to_decimal(utc): return None decimal.getcontext().prec = 30 - return decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) + \ - (decimal.Decimal(str(utc.microsecond)) / - decimal.Decimal("1000000.0")) + return (decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) + + (decimal.Decimal(str(utc.microsecond)) / + decimal.Decimal("1000000.0"))) def decimal_to_dt(dec): diff --git a/tox.ini b/tox.ini index fcc177457..36068be43 100644 --- a/tox.ini +++ b/tox.ini @@ -39,8 +39,7 @@ commands = {posargs} [flake8] # H305 imports not grouped correctly # H405 multi line docstring summary not separated with an empty line -# H904 Wrap long lines in parentheses instead of a backslash -ignore = H305,H405,H904 +ignore = H305,H405 builtins = _ exclude=.venv,.git,.tox,dist,doc,./ceilometer/openstack/common,*lib/python*,*egg,tools,nova_tests,build show-source = True