2
0
mirror of https://gitlab.com/apparmor/apparmor synced 2025-09-02 23:35:37 +00:00

Use the fact that empty sequences are false.

This commit is contained in:
Mark Grassi
2022-08-09 22:34:16 -04:00
parent 68e3f12c2c
commit 854602c0d9
15 changed files with 25 additions and 26 deletions

View File

@@ -208,7 +208,7 @@ class AAParserAltCacheBasicTests(AAParserBasicCachingTests):
self.cache_dir = self.get_cache_dir()
def tearDown(self):
if len(os.listdir(self.unused_cache_loc)) > 0:
if os.listdir(self.unused_cache_loc):
self.fail("original cache dir '%s' not empty" % self.unused_cache_loc)
super().tearDown()
@@ -515,7 +515,7 @@ class AAParserAltCacheTests(AAParserCachingTests):
self.cache_file = os.path.join(self.cache_dir, PROFILE)
def tearDown(self):
if self.check_orig_cache and len(os.listdir(self.orig_cache_dir)) > 0:
if self.check_orig_cache and os.listdir(self.orig_cache_dir):
self.fail("original cache dir '%s' not empty" % self.orig_cache_dir)
super().tearDown()

View File

@@ -91,7 +91,7 @@ def build_rule(leading, qual, name, perm, target):
else:
rule += "\t%s %s %s" % (qual, name, perm)
if target != "":
if target:
rule += " -> %s" % target
rule += ",\n"

View File

@@ -352,7 +352,7 @@ def get_output(params):
output = output.decode('utf-8').split('\n')
# Remove the extra empty string caused due to \n if present
if output[len(output) - 1] == '':
if not output[-1]:
output.pop()
return (ret, output)
@@ -637,7 +637,7 @@ def change_profile_flags(prof_filename, program, flag, set_flag):
found = False
depth = -1
if not flag or (type(flag) is str and flag.strip() == ''):
if not flag or (type(flag) is str and not flag.strip()):
raise AppArmorBug('New flag for %s is empty' % prof_filename)
with open_file_read(prof_filename) as f_in:

View File

@@ -99,7 +99,7 @@ def recursive_print(src, dpth=0, key=''):
if empty:
print(tabs + '[--- empty ---]')
elif isinstance(src, list) or isinstance(src, tuple):
if len(src) == 0:
if not src:
print(tabs + '[--- empty ---]')
else:
print(tabs + "[")

View File

@@ -610,7 +610,7 @@ class AppArmorEasyProfile:
search = '###VAR###'
prefix = find_prefix(policy, search)
s = "%s# No template variables specified" % prefix
if len(template_var) > 0:
if template_var:
s = "%s# Specified profile variables" % (prefix)
template_var.sort()
for i in template_var:
@@ -620,7 +620,7 @@ class AppArmorEasyProfile:
search = '###READS###'
prefix = find_prefix(policy, search)
s = "%s# No read paths specified" % prefix
if len(read_path) > 0:
if read_path:
s = "%s# Specified read permissions" % (prefix)
read_path.sort()
for i in read_path:
@@ -631,7 +631,7 @@ class AppArmorEasyProfile:
search = '###WRITES###'
prefix = find_prefix(policy, search)
s = "%s# No write paths specified" % prefix
if len(write_path) > 0:
if write_path:
s = "%s# Specified write permissions" % (prefix)
write_path.sort()
for i in write_path:

View File

@@ -138,7 +138,7 @@ def parse_profile_start_line(line, filename):
else:
result[section] = None
if result['flags'] and result['flags'].strip() == '':
if result['flags'] and not result['flags'].strip():
raise AppArmorException(
_('Invalid syntax in %(filename)s: Empty set of flags in line %(line)s.'
% {'filename': filename, 'line': line}))
@@ -204,11 +204,10 @@ def re_match_include_parse(line, rule_name):
path = matches.group('quotedpath')
# LP: 1738880 - parser doesn't handle relative paths everywhere, and
# neither do we (see aa.py)
if rule_name == 'include' and len(path) > 0 and path[0] != '/':
if rule_name == 'include' and path and path[0] != '/':
raise AppArmorException(_('Syntax error: %s must use quoted path or <...>') % rule_name)
# if path is empty or the empty string
if path is None or path == "":
if not path:
raise AppArmorException(_('Syntax error: %s rule with empty filename') % rule_name)
# LP: #1738877 - parser doesn't handle files with spaces in the name

View File

@@ -78,7 +78,7 @@ class BaseRule:
if rulepart == self.ALL:
return None, True
elif type(rulepart) is str:
if len(rulepart.strip()) == 0:
if not rulepart.strip():
raise AppArmorBug(
'Passed empty %(partname)s to %(classname)s: %(rulepart)s'
% {'partname': partname, 'classname': self.__class__.__name__, 'rulepart': str(rulepart)})
@@ -503,7 +503,7 @@ def check_and_split_list(lst, allowed_keywords, all_obj, classname, keyword_name
return None, True, None
elif type(lst) is str:
result_list = {lst}
elif type(lst) in (list, tuple, set) and (len(lst) > 0 or allow_empty_list):
elif type(lst) in (list, tuple, set) and (lst or allow_empty_list):
result_list = set(lst)
else:
raise AppArmorBug(

View File

@@ -49,14 +49,14 @@ class CapabilityRule(BaseRule):
else:
if type(cap_list) is str:
self.capability = {cap_list}
elif type(cap_list) == list and len(cap_list) > 0:
elif type(cap_list) == list and cap_list:
self.capability = set(cap_list)
else:
raise AppArmorBug('Passed unknown object to CapabilityRule: %s' % str(cap_list))
# make sure none of the cap_list arguments are blank, in
# case we decide to return one cap per output line
for cap in self.capability:
if len(cap.strip()) == 0:
if not cap.strip():
raise AppArmorBug('Passed empty capability to CapabilityRule: %s' % str(cap_list))
@classmethod

View File

@@ -132,7 +132,7 @@ class DbusRule(BaseRule):
# XXX move to function _split_access()?
access = strip_parenthesis(details.group('access'))
access = access.replace(',', ' ').split() # split by ',' or whitespace
if access == []: # XXX that happens for "dbus ( )," rules - correct behaviour? (also: same for signal rules?)
if not access: # XXX that happens for "dbus ( )," rules - correct behaviour? (also: same for signal rules?)
access = DbusRule.ALL
else:
access = DbusRule.ALL

View File

@@ -154,7 +154,7 @@ class RlimitRule(BaseRule):
def size_to_int(self, value):
number, unit = split_unit(value)
if unit == '':
if not unit:
pass
elif unit == 'K' or unit == 'KB':
number = number * 1024
@@ -170,7 +170,7 @@ class RlimitRule(BaseRule):
def time_to_int(self, value, default_unit):
number, unit = split_unit(value)
if unit == '':
if not unit:
unit = default_unit
if unit in ('us', 'microsecond', 'microseconds'):

View File

@@ -254,7 +254,7 @@ class SandboxXserver():
os.environ['LANG'] = old_lang
os.environ["DISPLAY"] = current
if display == "":
if not display:
raise AppArmorException("Could not find available X display")
# Use dedicated .Xauthority file

View File

@@ -35,7 +35,7 @@ class Severity:
with open_file_read(dbname) as database: # open(dbname, 'r')
for lineno, line in enumerate(database, start=1):
line = line.strip() # or only rstrip and lstrip?
if line == '' or line.startswith('#'):
if not line or line.startswith('#'):
continue
if line.startswith('/'):
try:
@@ -104,7 +104,7 @@ class Severity:
def check_subtree(self, tree, mode, sev, segments):
"""Returns the max severity from the regex tree"""
if len(segments) == 0:
if not segments:
first = ''
else:
first = segments[0]

View File

@@ -784,7 +784,7 @@ POLICYGROUPS_DIR="%s/templates"
if name is not None:
args.append('--name=%s' % name)
if len(extra_args) > 0:
if extra_args:
args += extra_args
args.append(self.binary)

View File

@@ -42,7 +42,7 @@ class NetworkKeywordsTest(AATest):
for af_pair in af_pairs:
af_name = af_pair.lstrip().split(" ")[0]
# skip max af name definition
if len(af_name) > 0 and af_name != "max":
if af_name and af_name != "max":
af_names.append(af_name)
missing_af_names = []

View File

@@ -67,7 +67,7 @@ af_pairs = re.sub('AF_', '', output.strip()).lower().split(",")
for af_pair in af_pairs:
af_name = af_pair.lstrip().split(" ")[0]
# skip max af name definition
if len(af_name) > 0 and af_name != "max":
if af_name and af_name != "max":
af_names.append(af_name)
# TODO: does a "debug" flag exist? Listed in apparmor.vim.in sdFlagKey,