Fix: pep8 airship-drydock-omni-test fix

Fixes for pep8 test.

Change-Id: Id2b7a187ffe56a47a184314d1a19507a78f7d88a
This commit is contained in:
Roman Gorshunov 2018-11-05 16:17:42 +01:00
parent 756a063c30
commit d5c54eab68
21 changed files with 58 additions and 56 deletions

View File

@ -96,7 +96,7 @@ class HealthCheckCombined(object):
now = self.state_manager.get_now() now = self.state_manager.get_now()
if now is None: if now is None:
raise Exception('None received from database for now()') raise Exception('None received from database for now()')
except Exception as ex: except Exception:
hcm = HealthCheckMessage( hcm = HealthCheckMessage(
msg='Unable to connect to database', error=True) msg='Unable to connect to database', error=True)
health_check.add_detail_msg(msg=hcm) health_check.add_detail_msg(msg=hcm)
@ -110,7 +110,7 @@ class HealthCheckCombined(object):
maas_validation.start() maas_validation.start()
if maas_validation.task.get_status() == ActionResult.Failure: if maas_validation.task.get_status() == ActionResult.Failure:
raise Exception('MaaS task failure') raise Exception('MaaS task failure')
except Exception as ex: except Exception:
hcm = HealthCheckMessage( hcm = HealthCheckMessage(
msg='Unable to connect to MaaS', error=True) msg='Unable to connect to MaaS', error=True)
health_check.add_detail_msg(msg=hcm) health_check.add_detail_msg(msg=hcm)

View File

@ -328,7 +328,7 @@ class TaskResource(StatefulResource):
subtask_errors = req.get_param_as_bool('subtaskerrors') subtask_errors = req.get_param_as_bool('subtaskerrors')
try: try:
layers = int(req.params.get('layers', '0')) layers = int(req.params.get('layers', '0'))
except Exception as ex: except Exception:
layers = 0 layers = 0
first_task = self.get_task(req, resp, task_id, builddata) first_task = self.get_task(req, resp, task_id, builddata)

View File

@ -320,12 +320,13 @@ class DestroyNode(BaseMaasAction):
# node release with erase disk will take sometime monitor it # node release with erase disk will take sometime monitor it
attempts = 0 attempts = 0
max_attempts = ( max_attempts = (
config.config_mgr.conf.timeouts.destroy_node * config.config_mgr.conf.timeouts.destroy_node
60) // config.config_mgr.conf.maasdriver.poll_interval * 60) // config.config_mgr.conf.maasdriver.poll_interval
while (attempts < max_attempts and while (attempts < max_attempts
(not machine.status_name.startswith('Ready') and (not machine.status_name.startswith('Ready')
and not machine.status_name.startswith('Failed'))): and not
machine.status_name.startswith('Failed'))):
attempts = attempts + 1 attempts = attempts + 1
time.sleep( time.sleep(
config.config_mgr.conf.maasdriver.poll_interval) config.config_mgr.conf.maasdriver.poll_interval)
@ -373,7 +374,7 @@ class DestroyNode(BaseMaasAction):
# setting power type attibutes to empty string # setting power type attibutes to empty string
# will remove them from maas BMC table # will remove them from maas BMC table
machine.reset_power_parameters() machine.reset_power_parameters()
except AttributeError as attr_er: except AttributeError:
pass pass
machine.delete() machine.delete()
@ -778,7 +779,7 @@ class CreateNetworkTemplate(BaseMaasAction):
ctx_type='network') ctx_type='network')
vlan.update() vlan.update()
dhcp_config_set = True dhcp_config_set = True
except RackControllerConflict as rack_ex: except RackControllerConflict:
msg = ( msg = (
"More than two rack controllers on vlan %s, " "More than two rack controllers on vlan %s, "
"skipping enabling %s." % "skipping enabling %s." %
@ -1207,9 +1208,10 @@ class ConfigureHardware(BaseMaasAction):
* 60 * 60
) // config.config_mgr.conf.maasdriver.poll_interval ) // config.config_mgr.conf.maasdriver.poll_interval
while (attempts < max_attempts and while (attempts < max_attempts
(machine.status_name != 'Ready' and and (machine.status_name != 'Ready'
not machine.status_name.startswith('Failed'))): and not
machine.status_name.startswith('Failed'))):
attempts = attempts + 1 attempts = attempts + 1
time.sleep(config.config_mgr.conf.maasdriver. time.sleep(config.config_mgr.conf.maasdriver.
poll_interval) poll_interval)
@ -1397,7 +1399,7 @@ class ApplyNodeNetworking(BaseMaasAction):
try: try:
machine.release() machine.release()
machine.refresh() machine.refresh()
except errors.DriverError as ex: except errors.DriverError:
msg = ( msg = (
"Node %s could not be released, skipping deployment." "Node %s could not be released, skipping deployment."
% n.name) % n.name)
@ -2203,7 +2205,7 @@ class ApplyNodeStorage(BaseMaasAction):
size_str is interpreted in the context of this device size_str is interpreted in the context of this device
:return size: The calculated size in bytes :return size: The calculated size in bytes
""" """
pattern = '(>?)(\d+)([mMbBgGtT%]{1,2})' pattern = r'(>?)(\d+)([mMbBgGtT%]{1,2})'
regex = re.compile(pattern) regex = re.compile(pattern)
match = regex.match(size_str) match = regex.match(size_str)
@ -2400,8 +2402,8 @@ class DeployNode(BaseMaasAction):
attempts = 0 attempts = 0
max_attempts = ( max_attempts = (
config.config_mgr.conf.timeouts.deploy_node * config.config_mgr.conf.timeouts.deploy_node
60) // config.config_mgr.conf.maasdriver.poll_interval * 60) // config.config_mgr.conf.maasdriver.poll_interval
while (attempts < max_attempts while (attempts < max_attempts
and (not machine.status_name.startswith('Deployed') and (not machine.status_name.startswith('Deployed')

View File

@ -93,7 +93,7 @@ class MaasRequestFactory(object):
def test_authentication(self): def test_authentication(self):
try: try:
resp = self.get('account/', op='list_authorisation_tokens') resp = self.get('account/', op='list_authorisation_tokens')
except requests.Timeout as ex: except requests.Timeout:
raise errors.TransientDriverError("Timeout connection to MaaS") raise errors.TransientDriverError("Timeout connection to MaaS")
except Exception as ex: except Exception as ex:
raise errors.PersistentDriverError( raise errors.PersistentDriverError(

View File

@ -66,7 +66,7 @@ class ResourceBase(object):
""" """
def interpolate_url(self): def interpolate_url(self):
pattern = '\{([a-z_]+)\}' pattern = r'\{([a-z_]+)\}'
regex = re.compile(pattern) regex = re.compile(pattern)
start = 0 start = 0
new_url = self.resource_url new_url = self.resource_url
@ -184,7 +184,7 @@ class ResourceCollectionBase(object):
def interpolate_url(self): def interpolate_url(self):
"""Parse URL for placeholders and replace them with current instance values.""" """Parse URL for placeholders and replace them with current instance values."""
pattern = '\{([a-z_]+)\}' pattern = r'\{([a-z_]+)\}'
regex = re.compile(pattern) regex = re.compile(pattern)
start = 0 start = 0
new_url = self.collection_url new_url = self.collection_url

View File

@ -624,8 +624,8 @@ class Machines(model_base.ResourceCollectionBase):
field = k[13:] field = k[13:]
result = [ result = [
i for i in result if str( i for i in result if str(
getattr(i, 'power_parameters', {}).get(field, None)) == getattr(i, 'power_parameters', {}).
str(v) get(field, None)) == str(v)
] ]
else: else:
result = [ result = [

View File

@ -54,7 +54,7 @@ class NodeResult(model_base.ResourceBase):
"""Decode the result data from base64.""" """Decode the result data from base64."""
try: try:
return base64.b64decode(self.data) return base64.b64decode(self.data)
except binascii.Error as e: except binascii.Error:
return None return None
def get_type_desc(self): def get_type_desc(self):

View File

@ -48,7 +48,7 @@ class BuildData(object):
data_element = data_element.decode('utf-8') data_element = data_element.decode('utf-8')
elif not isinstance(data_element, str): elif not isinstance(data_element, str):
data_element = str(data_element) data_element = str(data_element)
except Exception as ex: except Exception:
raise errors.BuildDataError( raise errors.BuildDataError(
"Error saving build data - data_element type %s could" "Error saving build data - data_element type %s could"
"not be cast to string." % str(type(data_element))) "not be cast to string." % str(type(data_element)))

View File

@ -107,10 +107,10 @@ class BaremetalNode(drydock_provisioner.objects.hostprofile.HostProfile):
try: try:
pn = site_design.get_network(self.primary_network) pn = site_design.get_network(self.primary_network)
domain = pn.dns_domain or "local" domain = pn.dns_domain or "local"
except errors.DesignError as dex: except errors.DesignError:
self.logger.debug("Primary network not found, use domain 'local'.") self.logger.debug("Primary network not found, use domain 'local'.")
domain = "local" domain = "local"
except AttributeError as aex: except AttributeError:
self.logger.debug( self.logger.debug(
"Primary network does not define a domain, use domain 'local'." "Primary network does not define a domain, use domain 'local'."
) )
@ -255,8 +255,8 @@ class BaremetalNode(drydock_provisioner.objects.hostprofile.HostProfile):
:param address: String value that is used to find the logicalname. :param address: String value that is used to find the logicalname.
:return: String value of the logicalname or the alias_name if logicalname is not found. :return: String value of the logicalname or the alias_name if logicalname is not found.
""" """
nodes = xml_root.findall(".//node[businfo='" + bus_type + "@" + nodes = xml_root.findall(".//node[businfo='" + bus_type + "@"
address + "'].logicalname") + address + "'].logicalname")
if len(nodes) >= 1 and nodes[0].text: if len(nodes) >= 1 and nodes[0].text:
if (len(nodes) > 1): if (len(nodes) > 1):
self.logger.info("Multiple nodes found for businfo=%s@%s" % self.logger.info("Multiple nodes found for businfo=%s@%s" %

View File

@ -1118,8 +1118,8 @@ class BootactionReport(BaseAction):
bas = self.state_manager.get_boot_actions_for_node(n) bas = self.state_manager.get_boot_actions_for_node(n)
running_bas = { running_bas = {
k: v k: v
for (k, v) in bas.items() if v.get('action_status') == for (k, v) in bas.items() if v.
hd_fields.ActionResult.Incomplete get('action_status') == hd_fields.ActionResult.Incomplete
} }
if len(running_bas) > 0: if len(running_bas) > 0:
still_running = True still_running = True

View File

@ -269,7 +269,7 @@ class Orchestrator(object):
site_design, site_design,
state_manager=self.state_manager, state_manager=self.state_manager,
resolve_aliases=resolve_aliases) resolve_aliases=resolve_aliases)
except Exception as ex: except Exception:
node_failed.append(n) node_failed.append(n)
self.logger.error( self.logger.error(
"Failed to build applied model for node %s." % n.name) "Failed to build applied model for node %s." % n.name)

View File

@ -29,7 +29,7 @@ class SimpleBytes():
:param size_str: A string representing the desired size :param size_str: A string representing the desired size
:return size: The calculated size in bytes :return size: The calculated size in bytes
""" """
pattern = '(\d+)([mMbBgGtT]{1,2})' pattern = r'(\d+)([mMbBgGtT]{1,2})'
regex = re.compile(pattern) regex = re.compile(pattern)
match = regex.match(size_str) match = regex.match(size_str)

View File

@ -51,7 +51,7 @@ class BootStorageRational(Validators):
self.report_error( self.report_error(
msg, [baremetal_node.doc_ref], msg, [baremetal_node.doc_ref],
"Configure a larger root volume") "Configure a larger root volume")
except errors.InvalidSizeFormat as e: except errors.InvalidSizeFormat:
msg = ( msg = (
'Root volume has an invalid size format on BaremetalNode' 'Root volume has an invalid size format on BaremetalNode'
'%s.' % baremetal_node.name) '%s.' % baremetal_node.name)
@ -74,7 +74,7 @@ class BootStorageRational(Validators):
self.report_error( self.report_error(
msg, [baremetal_node.doc_ref], msg, [baremetal_node.doc_ref],
"Configure a larger boot volume.") "Configure a larger boot volume.")
except errors.InvalidSizeFormat as e: except errors.InvalidSizeFormat:
msg = ( msg = (
'Boot volume has an invalid size format on BaremetalNode ' 'Boot volume has an invalid size format on BaremetalNode '
'%s.' % baremetal_node.name) '%s.' % baremetal_node.name)

View File

@ -45,7 +45,7 @@ class BootactionPackageListValid(Validators):
def __init__(self): def __init__(self):
super().__init__('Bootaction pkg_list Validation', 'DD4002') super().__init__('Bootaction pkg_list Validation', 'DD4002')
version_fields = '(\d+:)?([a-zA-Z0-9.+~-]+)(-[a-zA-Z0-9.+~]+)' version_fields = r'(\d+:)?([a-zA-Z0-9.+~-]+)(-[a-zA-Z0-9.+~]+)'
self.version_fields = re.compile(version_fields) self.version_fields = re.compile(version_fields)
def run_validation(self, site_design, orchestrator=None): def run_validation(self, site_design, orchestrator=None):

View File

@ -30,8 +30,8 @@ class NetworkTrunkingRational(Validators):
for network_link in network_link_list: for network_link in network_link_list:
allowed_networks = network_link.allowed_networks allowed_networks = network_link.allowed_networks
# if allowed networks > 1 trunking must be enabled # if allowed networks > 1 trunking must be enabled
if (len(allowed_networks) > 1 and network_link.trunk_mode == if (len(allowed_networks) > 1 and network_link.
hd_fields.NetworkLinkTrunkingMode.Disabled): trunk_mode == hd_fields.NetworkLinkTrunkingMode.Disabled):
msg = ('If there is more than 1 allowed network,' msg = ('If there is more than 1 allowed network,'
'trunking mode must be enabled') 'trunking mode must be enabled')
self.report_error( self.report_error(

View File

@ -117,7 +117,7 @@ class ReferenceResolver(object):
:param design_uri: Tuple as returned by urllib.parse for the design reference :param design_uri: Tuple as returned by urllib.parse for the design reference
""" """
ks_sess = KeystoneUtils.get_session() ks_sess = KeystoneUtils.get_session()
(new_scheme, foo) = re.subn('^[^+]+\+', '', design_uri.scheme) (new_scheme, foo) = re.subn(r'^[^+]+\+', '', design_uri.scheme)
url = urllib.parse.urlunparse( url = urllib.parse.urlunparse(
(new_scheme, design_uri.netloc, design_uri.path, design_uri.params, (new_scheme, design_uri.netloc, design_uri.path, design_uri.params,
design_uri.query, design_uri.fragment)) design_uri.query, design_uri.fragment))

View File

@ -110,9 +110,9 @@ class DrydockState(object):
""" """
query_text = sql.text( query_text = sql.text(
"SELECT * FROM tasks WHERE " # nosec no strings are user-sourced "SELECT * FROM tasks WHERE " # nosec no strings are user-sourced
"parent_task_id = :parent_task_id AND " "parent_task_id = :parent_task_id AND status "
"status IN ('" + hd_fields.TaskStatus.Terminated + "','" + "IN ('" + hd_fields.TaskStatus.Terminated + "','"
hd_fields.TaskStatus.Complete + "')") + hd_fields.TaskStatus.Complete + "')")
return self._query_subtasks(task_id, query_text, return self._query_subtasks(task_id, query_text,
"Error querying complete subtask: %s") "Error querying complete subtask: %s")
@ -126,9 +126,9 @@ class DrydockState(object):
""" """
query_text = sql.text( query_text = sql.text(
"SELECT * FROM tasks WHERE " # nosec no strings are user-sourced "SELECT * FROM tasks WHERE " # nosec no strings are user-sourced
"parent_task_id = :parent_task_id AND " "parent_task_id = :parent_task_id AND status "
"status NOT IN ['" + hd_fields.TaskStatus.Terminated + "','" + "NOT IN ['" + hd_fields.TaskStatus.Terminated + "','"
hd_fields.TaskStatus.Complete + "']") + hd_fields.TaskStatus.Complete + "']")
return self._query_subtasks(task_id, query_text, return self._query_subtasks(task_id, query_text,
"Error querying active subtask: %s") "Error querying active subtask: %s")

View File

@ -43,13 +43,13 @@ class TestTasksApiUnit(object):
try: try:
response_json['build_data'] response_json['build_data']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error assert key_error
try: try:
response_json['subtask_errors'] response_json['subtask_errors']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error assert key_error
@ -95,7 +95,7 @@ class TestTasksApiUnit(object):
try: try:
response_json['subtask_errors'] response_json['subtask_errors']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error assert key_error
@ -132,7 +132,7 @@ class TestTasksApiUnit(object):
try: try:
response_json['11111111-1111-1111-1111-111111111116'] response_json['11111111-1111-1111-1111-111111111116']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error assert key_error
@ -156,13 +156,13 @@ class TestTasksApiUnit(object):
try: try:
response_json['11111111-1111-1111-1111-111111111116'] response_json['11111111-1111-1111-1111-111111111116']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error is False assert key_error is False
try: try:
response_json['subtask_errors'] response_json['subtask_errors']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error assert key_error
@ -186,7 +186,7 @@ class TestTasksApiUnit(object):
try: try:
response_json['11111111-1111-1111-1111-111111111116'] response_json['11111111-1111-1111-1111-111111111116']
key_error = False key_error = False
except KeyError as ex: except KeyError:
key_error = True key_error = True
assert key_error is False assert key_error is False
assert response_json['subtask_errors'][ assert response_json['subtask_errors'][

View File

@ -54,7 +54,7 @@ class TestMtu(object):
validator = MtuRational() validator = MtuRational()
message_list = validator.execute(site_design, orchestrator=orch) message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile('MTU must be between \d+ and \d+') regex = re.compile(r'MTU must be between \d+ and \d+')
regex_1 = re.compile('MTU must be <= the parent Network Link') regex_1 = re.compile('MTU must be <= the parent Network Link')
for msg in message_list: for msg in message_list:

View File

@ -55,8 +55,8 @@ class TestRationalNetworkLinkBond(object):
validator = RationalNetworkBond() validator = RationalNetworkBond()
message_list = validator.execute(site_design, orchestrator=orch) message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile('Down delay \S+ is less than mon rate \S+') regex = re.compile(r'Down delay \S+ is less than mon rate \S+')
regex_1 = re.compile('Up delay \S+ is less than mon rate \S+') regex_1 = re.compile(r'Up delay \S+ is less than mon rate \S+')
for msg in message_list: for msg in message_list:
msg = msg.to_dict() msg = msg.to_dict()

View File

@ -56,10 +56,10 @@ class TestUniqueNetwork(object):
message_list = validator.execute(site_design, orchestrator=orch) message_list = validator.execute(site_design, orchestrator=orch)
regex = re.compile( regex = re.compile(
'Allowed network .+ duplicated on NetworkLink .+ and NetworkLink .+' r'Allowed network .+ duplicated on NetworkLink .+ and NetworkLink .+'
) )
regex_1 = re.compile( regex_1 = re.compile(
'Interface \S+ attached to network \S+ not allowed on interface link' r'Interface \S+ attached to network \S+ not allowed on interface link'
) )
assert len(message_list) >= 2 assert len(message_list) >= 2