Remove uses of assert in production code (#32079)

* Remove uses of assert in production code

* Fix assertion

* Add code smell test for assertions, currently limited to lib/ansible

* Fix assertion

* Add docs for no-assert

* Remove new assert from enos

* Fix assert in module_utils.connection
This commit is contained in:
Matt Martz 2017-11-13 10:51:18 -06:00 committed by ansibot
commit 99d4f5bab4
38 changed files with 195 additions and 89 deletions

View file

@ -285,7 +285,8 @@ def check_dp_status(client, dp_id, status):
:returns: True or False
"""
assert isinstance(status, list)
if not isinstance(status, list):
raise AssertionError()
if pipeline_field(client, dp_id, field="@pipelineState") in status:
return True
else:

View file

@ -380,7 +380,8 @@ class ClcGroup(object):
changed: Boolean- whether a change was made,
group: A clc group object for the group
"""
assert self.root_group, "Implementation Error: Root Group not set"
if not self.root_group:
raise AssertionError("Implementation Error: Root Group not set")
parent = parent_name if parent_name is not None else self.root_group.name
description = group_description
changed = False

View file

@ -237,7 +237,8 @@ class Droplet(JsonfyMixIn):
self.update_attr(json)
def power_on(self):
assert self.status == 'off', 'Can only power on a closed one.'
if self.status != 'off':
raise AssertionError('Can only power on a closed one.')
json = self.manager.power_on_droplet(self.id)
self.update_attr(json)

View file

@ -424,8 +424,10 @@ class PyVmomiDeviceHelper(object):
diskspec.device.backing.diskMode = 'persistent'
diskspec.device.controllerKey = scsi_ctl.device.key
assert self.next_disk_unit_number != 7
assert disk_index != 7
if self.next_disk_unit_number == 7:
raise AssertionError()
if disk_index == 7:
raise AssertionError()
"""
Configure disk unit number.
"""
@ -1127,7 +1129,8 @@ class PyVmomiHelper(PyVmomi):
return datastore, datastore_name
def obj_has_parent(self, obj, parent):
assert obj is not None and parent is not None
if obj is None and parent is None:
raise AssertionError()
current_parent = obj
while True:
@ -1573,7 +1576,7 @@ def main():
result["failed"] = False
else:
# This should not happen
assert False
raise AssertionError()
# VM doesn't exist
else:
if module.params['state'] in ['poweredon', 'poweredoff', 'present', 'restarted', 'suspended']:

View file

@ -342,7 +342,7 @@ class PyVmomiHelper(object):
task = vm.RemoveAllSnapshots()
else:
# This should not happen
assert False
raise AssertionError()
if task:
self.wait_for_task(task)

View file

@ -236,8 +236,9 @@ def set_acl(consul_client, configuration):
acls_as_json = decode_acls_as_json(consul_client.acl.list())
existing_acls_mapped_by_name = dict((acl.name, acl) for acl in acls_as_json if acl.name is not None)
existing_acls_mapped_by_token = dict((acl.token, acl) for acl in acls_as_json)
assert None not in existing_acls_mapped_by_token, "expecting ACL list to be associated to a token: %s" \
% existing_acls_mapped_by_token[None]
if None in existing_acls_mapped_by_token:
raise AssertionError("expecting ACL list to be associated to a token: %s" %
existing_acls_mapped_by_token[None])
if configuration.token is None and configuration.name and configuration.name in existing_acls_mapped_by_name:
# No token but name given so can get token from name
@ -246,8 +247,10 @@ def set_acl(consul_client, configuration):
if configuration.token and configuration.token in existing_acls_mapped_by_token:
return update_acl(consul_client, configuration)
else:
assert configuration.token not in existing_acls_mapped_by_token
assert configuration.name not in existing_acls_mapped_by_name
if configuration.token in existing_acls_mapped_by_token:
raise AssertionError()
if configuration.name in existing_acls_mapped_by_name:
raise AssertionError()
return create_acl(consul_client, configuration)
@ -266,7 +269,8 @@ def update_acl(consul_client, configuration):
rules_as_hcl = encode_rules_as_hcl_string(configuration.rules)
updated_token = consul_client.acl.update(
configuration.token, name=name, type=configuration.token_type, rules=rules_as_hcl)
assert updated_token == configuration.token
if updated_token != configuration.token:
raise AssertionError()
return Output(changed=changed, token=configuration.token, rules=configuration.rules, operation=UPDATE_OPERATION)
@ -379,12 +383,14 @@ def encode_rules_as_json(rules):
rules_as_json = defaultdict(dict)
for rule in rules:
if rule.pattern is not None:
assert rule.pattern not in rules_as_json[rule.scope]
if rule.pattern in rules_as_json[rule.scope]:
raise AssertionError()
rules_as_json[rule.scope][rule.pattern] = {
_POLICY_JSON_PROPERTY: rule.policy
}
else:
assert rule.scope not in rules_as_json
if rule.scope in rules_as_json:
raise AssertionError()
rules_as_json[rule.scope] = rule.policy
return rules_as_json
@ -577,7 +583,8 @@ def get_consul_client(configuration):
token = configuration.management_token
if token is None:
token = configuration.token
assert token is not None, "Expecting the management token to always be set"
if token is None:
raise AssertionError("Expecting the management token to always be set")
return consul.Consul(host=configuration.host, port=configuration.port, scheme=configuration.scheme,
verify=configuration.validate_certs, token=token)

View file

@ -225,16 +225,14 @@ except:
# Optional, only used for XML payload
try:
import lxml.etree
assert lxml.etree # silence pyflakes
import lxml.etree # noqa
HAS_LXML_ETREE = True
except ImportError:
HAS_LXML_ETREE = False
# Optional, only used for XML payload
try:
from xmljson import cobra
assert cobra # silence pyflakes
from xmljson import cobra # noqa
HAS_XMLJSON_COBRA = True
except ImportError:
HAS_XMLJSON_COBRA = False

View file

@ -249,9 +249,7 @@ class BalancerMember(object):
balancer_member_page = fetch_url(self.module, self.management_url)
try:
assert balancer_member_page[1]['status'] == 200
except AssertionError:
if balancer_member_page[1]['status'] != 200:
self.module.fail_json(msg="Could not get balancer_member_page, check for connectivity! " + balancer_member_page[1])
else:
try:
@ -296,9 +294,7 @@ class BalancerMember(object):
request_body = request_body + str(values_mapping[k]) + '=0'
response = fetch_url(self.module, self.management_url, data=str(request_body))
try:
assert response[1]['status'] == 200
except AssertionError:
if response[1]['status'] != 200:
self.module.fail_json(msg="Could not set the member status! " + self.host + " " + response[1]['status'])
attributes = property(get_member_attributes)
@ -323,9 +319,7 @@ class Balancer(object):
def fetch_balancer_page(self):
""" Returns the balancer management html page as a string for later parsing."""
page = fetch_url(self.module, str(self.url))
try:
assert page[1]['status'] == 200
except AssertionError:
if page[1]['status'] != 200:
self.module.fail_json(msg="Could not get balancer page! HTTP status response: " + str(page[1]['status']))
else:
content = page[0].read()
@ -343,9 +337,7 @@ class Balancer(object):
else:
for element in soup.findAll('a')[1::1]:
balancer_member_suffix = str(element.get('href'))
try:
assert balancer_member_suffix is not ''
except AssertionError:
if not balancer_member_suffix:
self.module.fail_json(msg="Argument 'balancer_member_suffix' is empty!")
else:
yield BalancerMember(str(self.base_url + balancer_member_suffix), str(self.url), self.module)