diff --git a/libraries/libapparmor/swig/python/test/buildpath.py b/libraries/libapparmor/swig/python/test/buildpath.py index cfa05c01f..a9c4728a2 100644 --- a/libraries/libapparmor/swig/python/test/buildpath.py +++ b/libraries/libapparmor/swig/python/test/buildpath.py @@ -11,4 +11,4 @@ if tuple(map(int, setuptools.__version__.split("."))) >= (62, 1): identifier = sys.implementation.cache_tag else: identifier = "%d.%d" % sys.version_info[:2] -print("lib.%s-%s" % (sysconfig.get_platform(), identifier)) +print("lib.{}-{}".format(sysconfig.get_platform(), identifier)) diff --git a/libraries/libapparmor/swig/python/test/test_python.py.in b/libraries/libapparmor/swig/python/test/test_python.py.in index 02b4c39ee..54a1e4f05 100644 --- a/libraries/libapparmor/swig/python/test/test_python.py.in +++ b/libraries/libapparmor/swig/python/test/test_python.py.in @@ -64,8 +64,8 @@ class AAPythonBindingsTests(unittest.TestCase): self.maxDiff = None def _runtest(self, testname): - infile = "%s.in" % (testname) - outfile = "%s.out" % (testname) + infile = testname + ".in" + outfile = testname + ".out" # infile *should* only contain one line with open(os.path.join(TESTDIR, infile), 'r') as f: line = f.read() @@ -78,7 +78,7 @@ class AAPythonBindingsTests(unittest.TestCase): expected = self.parse_output_file(outfile) self.assertEqual(expected, record, "expected records did not match\n" - "expected = %s\nactual = %s" % (expected, record)) + "expected = {}\nactual = {}".format(expected, record)) def parse_output_file(self, outfile): """parse testcase .out file and return dict""" @@ -93,7 +93,7 @@ class AAPythonBindingsTests(unittest.TestCase): count += 1 if line == "START": self.assertEqual(count, 1, - "Unexpected output format in %s" % (outfile)) + "Unexpected output format in " + outfile) continue else: key, value = line.split(": ", 1) @@ -141,8 +141,8 @@ def main(): for f in find_testcases(TESTDIR): def stub_test(self, testname=f): self._runtest(testname) - stub_test.__doc__ = "test %s" % (f) - setattr(AAPythonBindingsTests, 'test_%s' % (f), stub_test) + stub_test.__doc__ = "test " + f + setattr(AAPythonBindingsTests, 'test_' + f, stub_test) return unittest.main(verbosity=2) diff --git a/parser/tst/caching.py b/parser/tst/caching.py index fe5d6cfa2..9df65e2aa 100755 --- a/parser/tst/caching.py +++ b/parser/tst/caching.py @@ -41,7 +41,7 @@ PROFILE_CONTENTS = ''' /bin/ping mixr, /etc/modules.conf r, } -''' % (ABSTRACTION) +''' % (ABSTRACTION,) PROFILE = 'sbin.pingy' config = None @@ -91,7 +91,7 @@ class AAParserCachingCommon(testlib.AATestTemplate): """teardown for each test""" if not self.do_cleanup: - print("\n===> Skipping cleanup, leaving testfiles behind in '%s'" % (self.tmp_dir)) + print("\n===> Skipping cleanup, leaving testfiles behind in '{}'".format(self.tmp_dir)) else: if os.path.exists(self.tmp_dir): shutil.rmtree(self.tmp_dir) @@ -102,7 +102,7 @@ class AAParserCachingCommon(testlib.AATestTemplate): rc, report = self.run_cmd(cmd) if rc != 0: if "unrecognized option '--print-cache-dir'" not in report: - self.fail('Unknown apparmor_parser error:\n%s' % report) + self.fail('Unknown apparmor_parser error:\n' + report) cache_dir = os.path.join(self.tmp_dir, 'cache') else: @@ -116,10 +116,10 @@ class AAParserCachingCommon(testlib.AATestTemplate): def assert_path_exists(self, path, expected=True): if expected: self.assertTrue(os.path.exists(path), - 'test did not create file %s, when it was expected to do so' % path) + 'test did not create file {}, when it was expected to do so'.format(path)) else: self.assertFalse(os.path.exists(path), - 'test created file %s, when it was not expected to do so' % path) + 'test created file {}, when it was not expected to do so'.format(path)) def is_apparmorfs_mounted(self): return os.path.exists("/sys/kernel/security/apparmor") @@ -139,11 +139,11 @@ class AAParserCachingCommon(testlib.AATestTemplate): if expected: self.assertEqual( expected_output, features, - "features contents differ, expected:\n%s\nresult:\n%s" % (expected_output, features)) + "features contents differ, expected:\n{}\nresult:\n{}".format(expected_output, features)) else: self.assertNotEqual( expected_output, features, - "features contents equal, expected:\n%s\nresult:\n%s" % (expected_output, features)) + "features contents equal, expected:\n{}\nresult:\n{}".format(expected_output, features)) class AAParserBasicCachingTests(AAParserCachingCommon): @@ -210,7 +210,7 @@ class AAParserAltCacheBasicTests(AAParserBasicCachingTests): def tearDown(self): if os.listdir(self.unused_cache_loc): - self.fail("original cache dir '%s' not empty" % self.unused_cache_loc) + self.fail("original cache dir '{}' not empty".format(self.unused_cache_loc)) super().tearDown() @@ -517,7 +517,7 @@ class AAParserAltCacheTests(AAParserCachingTests): def tearDown(self): if self.check_orig_cache and os.listdir(self.orig_cache_dir): - self.fail("original cache dir '%s' not empty" % self.orig_cache_dir) + self.fail("original cache dir '{}' not empty".format(self.orig_cache_dir)) super().tearDown() def test_cache_purge_leaves_original_cache_alone(self): @@ -534,7 +534,7 @@ class AAParserAltCacheTests(AAParserCachingTests): for f in filelist: if not os.path.exists(os.path.join(self.orig_cache_dir, f)): - self.fail('cache purge removed %s, was not supposed to' % (os.path.join(self.orig_cache_dir, f))) + self.fail('cache purge removed {}, was not supposed to'.format(os.path.join(self.orig_cache_dir, f))) def main(): diff --git a/parser/tst/errors.py b/parser/tst/errors.py index 579fc7200..ad4900c55 100755 --- a/parser/tst/errors.py +++ b/parser/tst/errors.py @@ -32,7 +32,7 @@ class AAErrorTests(testlib.AATestTemplate): cmd = self.cmd_prefix + [profile] (rc, out, outerr) = self._run_cmd(cmd, stdout=subprocess.DEVNULL) - report = "\nCommand: %s\nExit value:%s\nSTDERR\n%s" % (" ".join(cmd), rc, outerr) + report = "\nCommand: {}\nExit value:{}\nSTDERR\n{}".format(" ".join(cmd), rc, outerr) if is_error: self.assertNotEqual(rc, 0, report) else: diff --git a/parser/tst/gen-dbus.py b/parser/tst/gen-dbus.py index 544d0f64a..9ded94002 100755 --- a/parser/tst/gen-dbus.py +++ b/parser/tst/gen-dbus.py @@ -25,7 +25,7 @@ def get_rule(quantifier, perms, session, name, path, interface, member, peer): for part in (quantifier, 'dbus', perms, session, name, path, interface, member, peer): if part: - result += ' %s' % part + result += ' ' + part result += ',\n' @@ -37,14 +37,14 @@ def gen_file(test, xres, quantifier, perms, session, name, path, interface, memb content = '' content += '#\n' - content += '#=DESCRIPTION %s\n' % test - content += '#=EXRESULT %s\n' % xres + content += '#=DESCRIPTION {}\n'.format(test) + content += '#=EXRESULT {}\n'.format(xres) content += '#\n' content += '/usr/bin/foo {\n' content += get_rule(quantifier, perms, session, name, path, interface, member, peer) content += '}\n' - write_file('simple_tests/generated_dbus', '%s-%s.sd' % (test, count), content) + write_file('simple_tests/generated_dbus', '{}-{}.sd'.format(test, count), content) count += 1 @@ -158,4 +158,4 @@ gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(name=1) peer=(name=2)', ' gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(label=1) peer=(label=2)', '', '', '', '', '', '') gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(name=1) peer=(label=2)', '', '', '', '', '', '') -print('Generated %s dbus tests' % count) +print('Generated {} dbus tests'.format(count)) diff --git a/parser/tst/gen-xtrans.py b/parser/tst/gen-xtrans.py index 6eceae2ad..d916028b9 100755 --- a/parser/tst/gen-xtrans.py +++ b/parser/tst/gen-xtrans.py @@ -66,9 +66,9 @@ def gen_list(): for trans in trans_types: if trans in trans_modifiers: for mod in trans_modifiers[trans]: - output.append("%s%sx" % (trans, mod)) + output.append("{}{}x".format(trans, mod)) - output.append("%sx" % trans) + output.append("{}x".format(trans)) return output @@ -80,19 +80,19 @@ def test_gen_list(): actual = gen_list() if actual != expected: - raise Exception("gen_list produced unexpected result, expected %s, got %s" % (expected, actual)) + raise Exception("gen_list produced unexpected result, expected {}, got {}".format(expected, actual)) def build_rule(leading, qual, name, perm, target): rule = '' if leading: - rule += "\t%s %s %s" % (qual, perm, name) + rule += "\t{} {} {}".format(qual, perm, name) else: - rule += "\t%s %s %s" % (qual, name, perm) + rule += "\t{} {} {}".format(qual, name, perm) if target: - rule += " -> %s" % target + rule += " -> {}".format(target) rule += ",\n" @@ -105,8 +105,8 @@ def gen_file(name, xres, leading1, qual1, rule1, perm1, target1, leading2, qual2 content = '' content += "#\n" - content += "#=DESCRIPTION %s\n" % name - content += "#=EXRESULT %s\n" % xres + content += "#=DESCRIPTION {}\n".format(name) + content += "#=EXRESULT {}\n".format(xres) content += "#\n" content += "/usr/bin/foo {\n" content += build_rule(leading1, qual1, rule1, perm1, target1) @@ -197,10 +197,10 @@ def gen_safe_perms(name, xres, invert, rule1, rule2): if (not invert or qual): file = prefix_safe + '/' + name + '-' + invert + '-' + q + qual + '-' + 'rule-' + i + t + '.sd' - gen_file(file, xres, 0, '%s %s' % (q, qual), rule1, i, t, 1, q, rule2, i, t) + gen_file(file, xres, 0, '{} {}'.format(q, qual), rule1, i, t, 1, q, rule2, i, t) file = prefix_safe + '/' + name + '-' + invert + '-' + q + qual + i + '-' + 'rule-' + t + '.sd' - gen_file(file, xres, 0, q, rule1, i, t, 1, '%s %s' % (q, qual), rule2, i, t) + gen_file(file, xres, 0, q, rule1, i, t, 1, '{} {}'.format(q, qual), rule2, i, t) test_gen_list() @@ -225,4 +225,4 @@ gen_safe_perms("overlap", "PASS", "inv", "/*", "/bin/cat") gen_safe_perms("dominate", "FAIL", "inv", "/**", "/*") gen_safe_perms("ambiguous", "FAIL", "inv", "/a*", "/*b") -print("Generated %s xtransition interaction tests" % count) +print("Generated {} xtransition interaction tests".format(count)) diff --git a/parser/tst/mk_features_file.py b/parser/tst/mk_features_file.py index 4ee696fd9..c4f421503 100755 --- a/parser/tst/mk_features_file.py +++ b/parser/tst/mk_features_file.py @@ -27,7 +27,7 @@ def main(): config = p.parse_args() if not os.path.exists(config.fdir): - print('Unable to find apparmor features directory "%s"' % config.fdir, file=sys.stderr) + print('Unable to find apparmor features directory "{}"'.format(config.fdir), file=sys.stderr) return 1 features = read_features_dir(config.fdir) diff --git a/parser/tst/testlib.py b/parser/tst/testlib.py index 47166e06a..df52e0db2 100644 --- a/parser/tst/testlib.py +++ b/parser/tst/testlib.py @@ -70,9 +70,9 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass): rc is as long as it's not a specific set of return codes, so can't push the check directly into run_cmd().""" rc, report = self.run_cmd(command, input, stderr, stdout, stdin, timeout) - self.assertEqual(rc, expected_rc, "Got return code %d, expected %d\nCommand run: %s\nOutput: %s" % (rc, expected_rc, (' '.join(command)), report)) + self.assertEqual(rc, expected_rc, "Got return code {}, expected {}\nCommand run: {}\nOutput: {}".format(rc, expected_rc, ' '.join(command), report)) if expected_string: - self.assertIn(expected_string, report, 'Expected message "%s", got: \n%s' % (expected_string, report)) + self.assertIn(expected_string, report, 'Expected message "{}", got: \n{}'.format(expected_string, report)) return report def run_cmd(self, command, input=None, stderr=subprocess.PIPE, stdout=subprocess.PIPE, @@ -81,7 +81,7 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass): return a textual error if it failed.""" if self.debug: - print("\n===> Running command: '%s'" % (' '.join(command))) + print("\n===> Running command: '{}'".format(' '.join(command))) (rc, out, outerr) = self._run_cmd(command, input, stderr, stdout, stdin, timeout) report = out + outerr @@ -154,7 +154,7 @@ def filesystem_time_resolution(): for i in range(10): s = None - with open(os.path.join(tmp_dir, 'test.%d' % i), 'w+') as f: + with open(os.path.join(tmp_dir, 'test.{}'.format(i)), 'w+') as f: s = os.fstat(f.fileno()) if (s.st_mtime == last_stamp): @@ -181,13 +181,13 @@ def read_features_dir(path): for name in sorted(os.listdir(path)): entry = os.path.join(path, name) - result += '%s {' % name + result += name + ' {' if os.path.isfile(entry): with open(entry, 'r') as f: # don't need extra '\n' here as features file contains it - result += '%s' % (f.read()) + result += f.read() elif os.path.isdir(entry): - result += '%s' % (read_features_dir(entry)) + result += read_features_dir(entry) result += '}\n' return result diff --git a/parser/tst/valgrind_simple.py b/parser/tst/valgrind_simple.py index 062024833..7bae874f6 100755 --- a/parser/tst/valgrind_simple.py +++ b/parser/tst/valgrind_simple.py @@ -23,7 +23,9 @@ import testlib DEFAULT_TESTDIR = "./simple_tests/vars" VALGRIND_ERROR_CODE = 151 -VALGRIND_ARGS = ['--leak-check=full', '--error-exitcode=%d' % (VALGRIND_ERROR_CODE)] +VALGRIND_ARGS = [ + '--leak-check=full', '--error-exitcode={}'.format(VALGRIND_ERROR_CODE) +] VALGRIND_SUPPRESSIONS = ''' { @@ -53,8 +55,8 @@ class AAParserValgrindTests(testlib.AATestTemplate): rc, output = self.run_cmd(command, timeout=120) self.assertNotIn( rc, failure_rc, - "valgrind returned error code %d, gave the following output\n%s\ncommand run: %s" - % (rc, output, " ".join(command))) + "valgrind returned error code {}, gave the following output\n{}\ncommand run: {}".format( + rc, output, " ".join(command))) def find_testcases(testdir): @@ -94,8 +96,10 @@ def main(): return rc if not os.path.exists(config.valgrind): - print("Unable to find valgrind at '%s', ensure that it is installed" % (config.valgrind), - file=sys.stderr) + print( + "Unable to find valgrind at '{}', ensure that it is installed".format(config.valgrind), + file=sys.stderr + ) sys.exit(1) verbosity = 1 @@ -106,13 +110,13 @@ def main(): suppression_file = None else: suppression_file = create_suppressions() - VALGRIND_ARGS.append('--suppressions=%s' % (suppression_file)) + VALGRIND_ARGS.append('--suppressions=' + suppression_file) for f in find_testcases(config.testdir): def stub_test(self, testname=f): self._runtest(testname, config) - stub_test.__doc__ = "test %s" % (f) - setattr(AAParserValgrindTests, 'test_%s' % (f), stub_test) + stub_test.__doc__ = "test " + f + setattr(AAParserValgrindTests, 'test_' + f, stub_test) test_suite = unittest.TestSuite() test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(AAParserValgrindTests)) diff --git a/utils/test/common_test.py b/utils/test/common_test.py index 958cbdc13..9318f0d0a 100755 --- a/utils/test/common_test.py +++ b/utils/test/common_test.py @@ -62,8 +62,8 @@ class AAParseTest(unittest.TestCase): parsed = self.parse_function(rule) self.assertEqual( rule, parsed.serialize(), - 'parse object %s returned "%s", expected "%s"' - % (self.parse_function.__doc__, parsed.serialize(), rule)) + 'parse object {} returned "{}", expected "{}"'.format( + self.parse_function.__doc__, parsed.serialize(), rule)) def setup_all_loops(module_name): @@ -89,8 +89,8 @@ def setup_tests_loop(test_class): def stub_test(self, test_data=test_data, expected=expected): self._run_test(test_data, expected) - stub_test.__doc__ = "test '%s'" % str(test_data) - setattr(test_class, 'test_%d' % (i), stub_test) + stub_test.__doc__ = "test '{}'".format(test_data) + setattr(test_class, 'test_{}'.format(i), stub_test) def setup_regex_tests(test_class): @@ -102,8 +102,8 @@ def setup_regex_tests(test_class): def stub_test(self, line=line): self._test_parse_rule(line) - stub_test.__doc__ = "test '%s': %s" % (line, desc) - setattr(test_class, 'test_%d' % (i), stub_test) + stub_test.__doc__ = "test '{}': {}".format(line, desc) + setattr(test_class, 'test_{}'.format(i), stub_test) def setup_aa(aa): diff --git a/utils/test/fake_ldd b/utils/test/fake_ldd index afec6eba9..4d02962d8 100755 --- a/utils/test/fake_ldd +++ b/utils/test/fake_ldd @@ -57,4 +57,4 @@ elif sys.argv[1] == 'TEMPLATE': print('') else: - raise Exception('unknown parameter in fake_ldd: %s' % sys.argv[1]) + raise Exception('unknown parameter in fake_ldd: ' + sys.argv[1]) diff --git a/utils/test/test-aa-decode.py b/utils/test/test-aa-decode.py index 3abac701a..625dc176f 100755 --- a/utils/test/test-aa-decode.py +++ b/utils/test/test-aa-decode.py @@ -66,7 +66,7 @@ class AADecodeTest(unittest.TestCase): expected = 0 rc, report = cmd((aadecode_bin, "--help")) - result = 'Got exit code %d, expected %d\n' % (rc, expected) + result = 'Got exit code {}, expected {}\n'.format(rc, expected) self.assertEqual(expected, rc, result + report) def _run_file_test(self, content, expected): @@ -82,10 +82,10 @@ class AADecodeTest(unittest.TestCase): temp_file.seek(0) rc, report = cmd((aadecode_bin,), stdin=temp_file) - result = 'Got exit code %d, expected %d\n' % (rc, expected_return_code) + result = 'Got exit code {}, expected {}\n'.format(rc, expected_return_code) self.assertEqual(expected_return_code, rc, result + report) for expected_string in expected: - result = 'could not find expected %s in output:\n' % (expected_string) + result = 'could not find expected {} in output:\n'.format(expected_string) self.assertIn(expected_string, report, result + report) def test_simple_decode(self): @@ -96,9 +96,9 @@ class AADecodeTest(unittest.TestCase): test_code = '2F746D702F666F6F20626172' rc, report = cmd((aadecode_bin, test_code)) - result = 'Got exit code %d, expected %d\n' % (rc, expected) + result = 'Got exit code {}, expected {}\n'.format(rc, expected) self.assertEqual(expected, rc, result + report) - result = 'Got output "%s", expected "%s"\n' % (report, expected_output) + result = 'Got output "{}", expected "{}"\n'.format(report, expected_output) self.assertIn(expected_output, report, result + report) def test_simple_filter(self): diff --git a/utils/test/test-aa-easyprof.py b/utils/test/test-aa-easyprof.py index 70653c196..5e0fa9e5d 100755 --- a/utils/test/test-aa-easyprof.py +++ b/utils/test/test-aa-easyprof.py @@ -146,26 +146,26 @@ class T(unittest.TestCase): ###WRITES### } -''' % (self.test_template) +''' % (self.test_template,) with open(os.path.join(self.tmpdir, 'templates', self.test_template), 'w') as f: f.write(contents) # Create a test policygroup self.test_policygroup = "test-policygroup" contents = ''' - # %s + # {} #include #include -''' % (self.test_policygroup) +'''.format(self.test_policygroup) with open(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), 'w') as f: f.write(contents) # setup our conffile self.conffile = os.path.join(self.tmpdir, 'easyprof.conf') contents = ''' -POLICYGROUPS_DIR="%s/policygroups" -TEMPLATES_DIR="%s/templates" -''' % (self.tmpdir, self.tmpdir) +POLICYGROUPS_DIR="{}/policygroups" +TEMPLATES_DIR="{}/templates" +'''.format(self.tmpdir, self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -180,14 +180,14 @@ TEMPLATES_DIR="%s/templates" # args list and override a base path set here base = os.getenv('__AA_BASEDIR') if base: - self.full_args.append('--base=%s' % base) + self.full_args.append('--base=' + base) # Check __AA_PARSER, which may be set by the Makefile, to see if # we should use a non-default apparmor_parser path to verify # policy parser = os.getenv('__AA_PARSER') if parser: - self.full_args.append('--parser=%s' % parser) + self.full_args.append('--parser=' + parser) if debugging: self.full_args.append('-d') @@ -203,13 +203,13 @@ TEMPLATES_DIR="%s/templates" for f in easyprof.get_directory_contents(os.path.join( self.tmpdir, d)): shutil.copy(f, os.path.join(self.test_include_dir, d, - "inc_%s" % os.path.basename(f))) + "inc_" + os.path.basename(f))) def tearDown(self): """Teardown for tests""" if os.path.exists(self.tmpdir): if debugging: - sys.stdout.write("%s\n" % self.tmpdir) + sys.stdout.write(self.tmpdir + "\n") else: recursive_rm(self.tmpdir) @@ -220,8 +220,8 @@ TEMPLATES_DIR="%s/templates" """Test config parsing (invalid POLICYGROUPS_DIR)""" contents = ''' POLICYGROUPS_DIR= -TEMPLATES_DIR="%s/templates" -''' % (self.tmpdir) +TEMPLATES_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -235,9 +235,9 @@ TEMPLATES_DIR="%s/templates" def test_configuration_file_p_empty(self): """Test config parsing (empty POLICYGROUPS_DIR)""" contents = ''' -POLICYGROUPS_DIR="%s" -TEMPLATES_DIR="%s/templates" -''' % ('', self.tmpdir) +POLICYGROUPS_DIR="" +TEMPLATES_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -251,9 +251,9 @@ TEMPLATES_DIR="%s/templates" def test_configuration_file_p_nonexistent(self): """Test config parsing (nonexistent POLICYGROUPS_DIR)""" contents = ''' -POLICYGROUPS_DIR="%s/policygroups" -TEMPLATES_DIR="%s/templates" -''' % ('/nonexistent', self.tmpdir) +POLICYGROUPS_DIR="/nonexistent/policygroups" +TEMPLATES_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -272,14 +272,14 @@ TEMPLATES_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), os.path.join(rel, self.test_policygroup)) args = self.full_args - args += ['--policy-groups-dir', './relative', '--show-policy-group', '--policy-groups=%s' % self.test_policygroup] + args += ['--policy-groups-dir', './relative', '--show-policy-group', '--policy-groups=' + self.test_policygroup] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) # no fallback self.assertTrue(easyp.dirs['policygroups'] == rel, "Not using specified --policy-groups-dir\n" - "Specified dir: %s\nActual dir: %s" % (rel, str(easyp.dirs['policygroups']))) + "Specified dir: {}\nActual dir: {}".format(rel, easyp.dirs['policygroups'])) self.assertFalse(easyp.get_policy_groups() is None, "Could not find policy-groups") def test_policygroups_dir_nonexistent(self): @@ -288,7 +288,7 @@ TEMPLATES_DIR="%s/templates" rel = os.path.join(self.tmpdir, 'nonexistent') args = self.full_args - args += ['--policy-groups-dir', rel, '--show-policy-group', '--policy-groups=%s' % self.test_policygroup] + args += ['--policy-groups-dir', rel, '--show-policy-group', '--policy-groups=' + self.test_policygroup] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) @@ -306,7 +306,7 @@ TEMPLATES_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), os.path.join(valid, self.test_policygroup)) args = self.full_args - args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=%s' % self.test_policygroup] + args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=' + self.test_policygroup] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) @@ -330,21 +330,21 @@ TEMPLATES_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), valid_distro) args = self.full_args - args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=%s' % self.test_policygroup] + args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=' + self.test_policygroup] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) self.assertTrue(easyp.dirs['policygroups'] == valid, "Not using specified --policy-groups-dir") self.assertFalse(easyp.get_policy_groups() is None, "Could not find policy-groups") for f in easyp.get_policy_groups(): - self.assertFalse(os.path.basename(f) == vendor, "Found '%s' in %s" % (vendor, f)) + self.assertFalse(os.path.basename(f) == vendor, "Found '{}' in {}".format(vendor, f)) def test_configuration_file_t_invalid(self): """Test config parsing (invalid TEMPLATES_DIR)""" contents = ''' TEMPLATES_DIR= -POLICYGROUPS_DIR="%s/templates" -''' % (self.tmpdir) +POLICYGROUPS_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -358,9 +358,9 @@ POLICYGROUPS_DIR="%s/templates" def test_configuration_file_t_empty(self): """Test config parsing (empty TEMPLATES_DIR)""" contents = ''' -TEMPLATES_DIR="%s" -POLICYGROUPS_DIR="%s/templates" -''' % ('', self.tmpdir) +TEMPLATES_DIR="" +POLICYGROUPS_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -374,9 +374,9 @@ POLICYGROUPS_DIR="%s/templates" def test_configuration_file_t_nonexistent(self): """Test config parsing (nonexistent TEMPLATES_DIR)""" contents = ''' -TEMPLATES_DIR="%s/policygroups" -POLICYGROUPS_DIR="%s/templates" -''' % ('/nonexistent', self.tmpdir) +TEMPLATES_DIR="/nonexistent/policygroups" +POLICYGROUPS_DIR="{}/templates" +'''.format(self.tmpdir) with open(self.conffile, 'w') as f: f.write(contents) @@ -395,14 +395,14 @@ POLICYGROUPS_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), os.path.join(rel, self.test_template)) args = self.full_args - args += ['--templates-dir', './relative', '--show-template', '--template=%s' % self.test_template] + args += ['--templates-dir', './relative', '--show-template', '--template=' + self.test_template] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) # no fallback self.assertTrue(easyp.dirs['templates'] == rel, "Not using specified --template-dir\n" - "Specified dir: %s\nActual dir: %s" % (rel, str(easyp.dirs['templates']))) + "Specified dir: {}\nActual dir: {}".format(rel, easyp.dirs['templates'])) self.assertFalse(easyp.get_templates() is None, "Could not find templates") def test_templates_dir_nonexistent(self): @@ -411,7 +411,7 @@ POLICYGROUPS_DIR="%s/templates" rel = os.path.join(self.tmpdir, 'nonexistent') args = self.full_args - args += ['--templates-dir', rel, '--show-template', '--template=%s' % self.test_template] + args += ['--templates-dir', rel, '--show-template', '--template=' + self.test_template] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) @@ -429,7 +429,7 @@ POLICYGROUPS_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), os.path.join(valid, self.test_template)) args = self.full_args - args += ['--templates-dir', valid, '--show-template', '--template=%s' % self.test_template] + args += ['--templates-dir', valid, '--show-template', '--template=' + self.test_template] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) @@ -452,14 +452,14 @@ POLICYGROUPS_DIR="%s/templates" shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), valid_distro) args = self.full_args - args += ['--templates-dir', valid, '--show-template', '--template=%s' % self.test_template] + args += ['--templates-dir', valid, '--show-template', '--template=' + self.test_template] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(self.binary, self.options) self.assertTrue(easyp.dirs['templates'] == valid, "Not using specified --template-dir") self.assertFalse(easyp.get_templates() is None, "Could not find templates") for f in easyp.get_templates(): - self.assertFalse(os.path.basename(f) == vendor, "Found '%s' in %s" % (vendor, f)) + self.assertFalse(os.path.basename(f) == vendor, "Found '{}' in {}".format(vendor, f)) # # Binary file tests @@ -518,11 +518,11 @@ POLICYGROUPS_DIR="%s/templates" easyp = easyprof.AppArmorEasyProfile(None, self.options) for i in easyp.get_templates(): - self.assertTrue(os.path.exists(i), "Could not find '%s'" % i) + self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i)) def test_templates_show(self): """Test templates (show)""" - files = glob.glob("%s/templates/*" % self.tmpdir) + files = glob.glob(self.tmpdir + "/templates/*") for f in files: args = self.full_args args += ['--show-template', '--template', f] @@ -530,7 +530,7 @@ POLICYGROUPS_DIR="%s/templates" easyp = easyprof.AppArmorEasyProfile(None, self.options) path = os.path.join(easyp.dirs['templates'], f) - self.assertTrue(os.path.exists(path), "Could not find '%s'" % path) + self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path)) with open(path) as fd: fd.read() @@ -545,39 +545,39 @@ POLICYGROUPS_DIR="%s/templates" args = self.full_args args.append('--list-templates') - args.append('--include-templates-dir=%s' - % os.path.join(self.test_include_dir, 'templates')) + args.append('--include-templates-dir=' + + os.path.join(self.test_include_dir, 'templates')) (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(None, self.options) inc_templates = easyp.get_templates() self.assertTrue(len(inc_templates) == len(orig_templates) * 2, - "templates missing: %s" % inc_templates) + "templates missing: {}".format(inc_templates)) for i in inc_templates: - self.assertTrue(os.path.exists(i), "Could not find '%s'" % i) + self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i)) def test_templates_show_include(self): """Test templates (show with --include-templates-dir)""" - files = glob.glob("%s/templates/*" % self.test_include_dir) + files = glob.glob(self.test_include_dir + "/templates/*") for f in files: args = self.full_args args += ['--show-template', '--template', f, - '--include-templates-dir=%s' - % os.path.join(self.test_include_dir, 'templates')] + '--include-templates-dir=' + + os.path.join(self.test_include_dir, 'templates')] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(None, self.options) path = os.path.join(easyp.dirs['templates_include'], f) - self.assertTrue(os.path.exists(path), "Could not find '%s'" % path) + self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path)) with open(path) as fd: fd.read() bn = os.path.basename(f) # setup() copies everything in the include prefixed with inc_ self.assertTrue(bn.startswith('inc_'), - "'%s' does not start with 'inc_'" % bn) + "'{}' does not start with 'inc_'".format(bn)) # # Policygroups tests @@ -590,11 +590,11 @@ POLICYGROUPS_DIR="%s/templates" easyp = easyprof.AppArmorEasyProfile(None, self.options) for i in easyp.get_policy_groups(): - self.assertTrue(os.path.exists(i), "Could not find '%s'" % i) + self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i)) def test_policygroups_show(self): """Test policygroups (show)""" - files = glob.glob("%s/policygroups/*" % self.tmpdir) + files = glob.glob(self.tmpdir + "/policygroups/*") for f in files: args = self.full_args args += ['--show-policy-group', @@ -603,7 +603,7 @@ POLICYGROUPS_DIR="%s/templates" easyp = easyprof.AppArmorEasyProfile(None, self.options) path = os.path.join(easyp.dirs['policygroups'], f) - self.assertTrue(os.path.exists(path), "Could not find '%s'" % path) + self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path)) with open(path) as fd: fd.read() @@ -618,39 +618,39 @@ POLICYGROUPS_DIR="%s/templates" args = self.full_args args.append('--list-policy-groups') - args.append('--include-policy-groups-dir=%s' - % os.path.join(self.test_include_dir, 'policygroups')) + args.append('--include-policy-groups-dir=' + + os.path.join(self.test_include_dir, 'policygroups')) (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(None, self.options) inc_policy_groups = easyp.get_policy_groups() self.assertTrue(len(inc_policy_groups) == len(orig_policy_groups) * 2, - "policy_groups missing: %s" % inc_policy_groups) + "policy_groups missing: {}".format(inc_policy_groups)) for i in inc_policy_groups: - self.assertTrue(os.path.exists(i), "Could not find '%s'" % i) + self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i)) def test_policygroups_show_include(self): """Test policygroups (show with --include-policy-groups-dir)""" - files = glob.glob("%s/policygroups/*" % self.test_include_dir) + files = glob.glob(self.test_include_dir + "/policygroups/*") for f in files: args = self.full_args args += ['--show-policy-group', '--policy-groups', os.path.basename(f), - '--include-policy-groups-dir=%s' - % os.path.join(self.test_include_dir, 'policygroups')] + '--include-policy-groups-dir=' + + os.path.join(self.test_include_dir, 'policygroups')] (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(None, self.options) path = os.path.join(easyp.dirs['policygroups_include'], f) - self.assertTrue(os.path.exists(path), "Could not find '%s'" % path) + self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path)) with open(path) as fd: fd.read() bn = os.path.basename(f) # setup() copies everything in the include prefixed with inc_ self.assertTrue(bn.startswith('inc_'), - "'%s' does not start with 'inc_'" % bn) + "'{}' does not start with 'inc_'".format(bn)) # # Manifest file argument tests @@ -689,8 +689,8 @@ POLICYGROUPS_DIR="%s/templates" except InterceptedError: raised = True - self.assertTrue(raised, msg="%s and manifest arguments did not " - "raise a parse error" % opt) + self.assertTrue(raised, msg=opt + " and manifest arguments did not " + "raise a parse error") # manifest first args = self.full_args @@ -701,8 +701,8 @@ POLICYGROUPS_DIR="%s/templates" except InterceptedError: raised = True - self.assertTrue(raised, msg="%s and manifest arguments did not " - "raise a parse error" % opt) + self.assertTrue(raised, msg=opt + " and manifest arguments did not " + "raise a parse error") def test_manifest_conflicts_profilename(self): """Test manifest arg conflicts with profile_name arg""" @@ -761,12 +761,12 @@ POLICYGROUPS_DIR="%s/templates" args = self.full_args if template is None: - args.append('--template=%s' % self.test_template) + args.append('--template=' + self.test_template) else: - args.append('--template=%s' % template) + args.append('--template=' + template) if name is not None: - args.append('--name=%s' % name) + args.append('--name=' + name) if extra_args: args += extra_args @@ -788,14 +788,14 @@ POLICYGROUPS_DIR="%s/templates" search_terms.append(self.test_template) for s in search_terms: - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) # ###NAME### should be replaced with self.binary or 'name'. Check for that inv_s = '###NAME###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) if debugging: - sys.stdout.write("%s\n" % p) + sys.stdout.write(p + "\n") return p @@ -812,10 +812,10 @@ POLICYGROUPS_DIR="%s/templates" # ###NAME### should be replaced with self.binary or 'name'. Check for that inv_s = '###NAME###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) if debugging: - sys.stdout.write("%s\n" % p) + sys.stdout.write(p + "\n") return p @@ -831,7 +831,7 @@ POLICYGROUPS_DIR="%s/templates" 'foo"bar', ) for s in bad: - self.assertFalse(easyprof._is_safe(s), "'%s' should be bad" % s) + self.assertFalse(easyprof._is_safe(s), "'{}' should be bad".format(s)) def test_genpolicy_templates_abspath(self): """Test genpolicy (abspath to template)""" @@ -842,12 +842,12 @@ POLICYGROUPS_DIR="%s/templates" contents = f.read() test_string = "#teststring" with open(template, 'w') as f: - f.write(contents + "\n%s\n" % test_string) + f.write(contents + "\n{}\n".format(test_string)) p = self._gen_policy(template=template) for s in (self.test_template, test_string): - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) def test_genpolicy_templates_system(self): """Test genpolicy (system template)""" @@ -868,45 +868,45 @@ POLICYGROUPS_DIR="%s/templates" def test_genpolicy_comment(self): """Test genpolicy (comment)""" s = "test comment" - p = self._gen_policy(extra_args=['--comment=%s' % s]) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + p = self._gen_policy(extra_args=['--comment=' + s]) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###COMMENT###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_author(self): """Test genpolicy (author)""" s = "Archibald Poindexter" - p = self._gen_policy(extra_args=['--author=%s' % s]) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + p = self._gen_policy(extra_args=['--author=' + s]) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###AUTHOR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_copyright(self): """Test genpolicy (copyright)""" s = "2112/01/01" - p = self._gen_policy(extra_args=['--copyright=%s' % s]) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + p = self._gen_policy(extra_args=['--copyright=' + s]) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###COPYRIGHT###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_abstractions(self): """Test genpolicy (single abstraction)""" s = "nameservice" - p = self._gen_policy(extra_args=['--abstractions=%s' % s]) - search = "#include " % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--abstractions=' + s]) + search = "#include ".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###ABSTRACTIONS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_abstractions_multiple(self): """Test genpolicy (multiple abstractions)""" abstractions = "authentication,X,user-tmp" - p = self._gen_policy(extra_args=['--abstractions=%s' % abstractions]) + p = self._gen_policy(extra_args=['--abstractions=' + abstractions]) for s in abstractions.split(','): - search = "#include " % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + search = "#include ".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###ABSTRACTIONS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_abstractions_bad(self): """Test genpolicy (abstractions - bad values)""" @@ -917,16 +917,16 @@ POLICYGROUPS_DIR="%s/templates" ) for s in bad: try: - self._gen_policy(extra_args=['--abstractions=%s' % s]) + self._gen_policy(extra_args=['--abstractions=' + s]) except AppArmorException: continue - raise Exception("abstraction '%s' should be invalid" % s) + raise Exception("abstraction '{}' should be invalid".format(s)) def _create_tmp_base_dir(self, prefix='', abstractions=[], tunables=[]): """Create a temporary base dir layout""" base_name = 'apparmor.d' if prefix: - base_name = '%s-%s' % (prefix, base_name) + base_name = '{}-{}'.format(prefix, base_name) base_dir = os.path.join(self.tmpdir, base_name) abstractions_dir = os.path.join(base_dir, 'abstractions') tunables_dir = os.path.join(base_dir, 'tunables') @@ -938,8 +938,8 @@ POLICYGROUPS_DIR="%s/templates" for f in abstractions: contents = ''' # Abstraction file for testing - /%s r, -''' % (f) + /{} r, +'''.format(f) with open(os.path.join(abstractions_dir, f), 'w') as fd: fd.write(contents) @@ -947,7 +947,7 @@ POLICYGROUPS_DIR="%s/templates" contents = ''' # Tunable file for testing @{AA_TEST_%s}=foo -''' % (f) +''' % (f,) with open(os.path.join(tunables_dir, f), 'w') as fd: fd.write(contents) @@ -959,13 +959,13 @@ POLICYGROUPS_DIR="%s/templates" # The default template #includes the base abstraction and global # tunable so we need to create placeholders base = self._create_tmp_base_dir(abstractions=['base', abstraction], tunables=['global']) - args = ['--abstractions=%s' % abstraction, '--base=%s' % base] + args = ['--abstractions=' + abstraction, '--base=' + base] p = self._gen_policy(extra_args=args) - search = "#include " % abstraction - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + search = "#include ".format(abstraction) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###ABSTRACTIONS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_abstractions_custom_base_bad(self): """Test genpolicy (custom base dir - bad base dirs)""" @@ -973,13 +973,13 @@ POLICYGROUPS_DIR="%s/templates" bad = [None, '/etc/apparmor.d', '/'] for base in bad: try: - args = ['--abstractions=%s' % abstraction] + args = ['--abstractions=' + abstraction] if base: - args.append('--base=%s' % base) + args.append('--base={}'.format(base)) self._gen_policy(extra_args=args) except AppArmorException: continue - raise Exception("abstraction '%s' should be invalid" % abstraction) + raise Exception("abstraction '{}' should be invalid".format(abstraction)) def test_genpolicy_abstractions_custom_include(self): """Test genpolicy (custom include dir)""" @@ -987,12 +987,12 @@ POLICYGROUPS_DIR="%s/templates" # No need to create placeholders for the base abstraction or global # tunable since we're not adjusting the base directory include = self._create_tmp_base_dir(abstractions=[abstraction]) - args = ['--abstractions=%s' % abstraction, '--Include=%s' % include] + args = ['--abstractions=' + abstraction, '--Include=' + include] p = self._gen_policy(extra_args=args) - search = "#include " % abstraction - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + search = "#include ".format(abstraction) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###ABSTRACTIONS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_abstractions_custom_include_bad(self): """Test genpolicy (custom include dir - bad include dirs)""" @@ -1000,13 +1000,13 @@ POLICYGROUPS_DIR="%s/templates" bad = [None, '/etc/apparmor.d', '/'] for include in bad: try: - args = ['--abstractions=%s' % abstraction] + args = ['--abstractions=' + abstraction] if include: - args.append('--Include=%s' % include) + args.append('--Include={}'.format(include)) self._gen_policy(extra_args=args) except AppArmorException: continue - raise Exception("abstraction '%s' should be invalid" % abstraction) + raise Exception("abstraction '{}' should be invalid".format(abstraction)) def test_genpolicy_profile_name_bad(self): """Test genpolicy (profile name - bad values)""" @@ -1017,10 +1017,10 @@ POLICYGROUPS_DIR="%s/templates" ] for s in bad: try: - self._gen_policy(extra_args=['--profile-name=%s' % s]) + self._gen_policy(extra_args=['--profile-name=' + s]) except AppArmorException: continue - raise Exception("profile_name '%s' should be invalid" % s) + raise Exception("profile_name '{}' should be invalid".format(s)) def test_genpolicy_policy_group_bad(self): """Test genpolicy (policy group - bad values)""" @@ -1031,42 +1031,42 @@ POLICYGROUPS_DIR="%s/templates" ] for s in bad: try: - self._gen_policy(extra_args=['--policy-groups=%s' % s]) + self._gen_policy(extra_args=['--policy-groups=' + s]) except AppArmorException: continue - raise Exception("policy group '%s' should be invalid" % s) + raise Exception("policy group '{}' should be invalid".format(s)) def test_genpolicy_policygroups(self): """Test genpolicy (single policygroup)""" groups = self.test_policygroup - p = self._gen_policy(extra_args=['--policy-groups=%s' % groups]) + p = self._gen_policy(extra_args=['--policy-groups=' + groups]) for s in ('#include ', '#include '): - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###POLICYGROUPS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_policygroups_multiple(self): """Test genpolicy (multiple policygroups)""" test_policygroup2 = "test-policygroup2" contents = ''' - # %s + # {} #include #include -''' % (self.test_policygroup) +'''.format(self.test_policygroup) with open(os.path.join(self.tmpdir, 'policygroups', test_policygroup2), 'w') as f: f.write(contents) - groups = "%s,%s" % (self.test_policygroup, test_policygroup2) - p = self._gen_policy(extra_args=['--policy-groups=%s' % groups]) + groups = "{},{}".format(self.test_policygroup, test_policygroup2) + p = self._gen_policy(extra_args=['--policy-groups=' + groups]) for s in ('#include ', '#include ', '#include ', '#include '): - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###POLICYGROUPS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_policygroups_nonexistent(self): """Test genpolicy (nonexistent policygroup)""" @@ -1079,68 +1079,68 @@ POLICYGROUPS_DIR="%s/templates" def test_genpolicy_readpath_file(self): """Test genpolicy (read-path file)""" s = "/opt/test-foo" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search = "%s rk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--read-path=' + s]) + search = "{} rk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_home_file(self): """Test genpolicy (read-path file in /home)""" s = "/home/*/test-foo" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search = "owner %s rk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--read-path=' + s]) + search = "owner {} rk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_homevar_file(self): """Test genpolicy (read-path file in @{HOME})""" s = "@{HOME}/test-foo" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search = "owner %s rk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--read-path=' + s]) + search = "owner {} rk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_homedirs_file(self): """Test genpolicy (read-path file in @{HOMEDIRS})""" s = "@{HOMEDIRS}/test-foo" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search = "owner %s rk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--read-path=' + s]) + search = "owner {} rk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_dir(self): """Test genpolicy (read-path directory/)""" s = "/opt/test-foo-dir/" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search_terms = ["%s rk," % s, "%s** rk," % s] + p = self._gen_policy(extra_args=['--read-path=' + s]) + search_terms = ["{} rk,".format(s), "{}** rk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_dir_glob(self): """Test genpolicy (read-path directory/*)""" s = "/opt/test-foo-dir/*" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search_terms = ["%s rk," % os.path.dirname(s), "%s rk," % s] + p = self._gen_policy(extra_args=['--read-path=' + s]) + search_terms = ["{} rk,".format(os.path.dirname(s)), "{} rk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_dir_glob_all(self): """Test genpolicy (read-path directory/**)""" s = "/opt/test-foo-dir/**" - p = self._gen_policy(extra_args=['--read-path=%s' % s]) - search_terms = ["%s rk," % os.path.dirname(s), "%s rk," % s] + p = self._gen_policy(extra_args=['--read-path=' + s]) + search_terms = ["{} rk,".format(os.path.dirname(s)), "{} rk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_multiple(self): """Test genpolicy (read-path multiple)""" @@ -1156,31 +1156,31 @@ POLICYGROUPS_DIR="%s/templates" args = [] search_terms = [] for s in paths: - args.append('--read-path=%s' % s) + args.append('--read-path=' + s) # This mimics easyprof.gen_path_rule() owner = "" if s.startswith('/home/') or s.startswith("@{HOME"): owner = "owner " if s.endswith('/'): - search_terms.append("%s rk," % (s)) - search_terms.append("%s%s** rk," % (owner, s)) + search_terms.append("{} rk,".format(s)) + search_terms.append("{}{}** rk,".format(owner, s)) elif s.endswith('/**') or s.endswith('/*'): - search_terms.append("%s rk," % (os.path.dirname(s))) - search_terms.append("%s%s rk," % (owner, s)) + search_terms.append("{} rk,".format(os.path.dirname(s))) + search_terms.append("{}{} rk,".format(owner, s)) else: - search_terms.append("%s%s rk," % (owner, s)) + search_terms.append("{}{} rk,".format(owner, s)) p = self._gen_policy(extra_args=args) for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_readpath_bad(self): """Test genpolicy (read-path bad)""" s = "bar" try: - self._gen_policy(extra_args=['--read-path=%s' % s]) + self._gen_policy(extra_args=['--read-path=' + s]) except AppArmorException: return raise Exception("read-path should be invalid") @@ -1188,68 +1188,68 @@ POLICYGROUPS_DIR="%s/templates" def test_genpolicy_writepath_file(self): """Test genpolicy (write-path file)""" s = "/opt/test-foo" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search = "%s rwk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--write-path=' + s]) + search = "{} rwk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_home_file(self): """Test genpolicy (write-path file in /home)""" s = "/home/*/test-foo" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search = "owner %s rwk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--write-path=' + s]) + search = "owner {} rwk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_homevar_file(self): """Test genpolicy (write-path file in @{HOME})""" s = "@{HOME}/test-foo" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search = "owner %s rwk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--write-path=' + s]) + search = "owner {} rwk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_homedirs_file(self): """Test genpolicy (write-path file in @{HOMEDIRS})""" s = "@{HOMEDIRS}/test-foo" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search = "owner %s rwk," % s - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + p = self._gen_policy(extra_args=['--write-path=' + s]) + search = "owner {} rwk,".format(s) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_dir(self): """Test genpolicy (write-path directory/)""" s = "/opt/test-foo-dir/" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search_terms = ["%s rwk," % s, "%s** rwk," % s] + p = self._gen_policy(extra_args=['--write-path=' + s]) + search_terms = ["{} rwk,".format(s), "{}** rwk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_dir_glob(self): """Test genpolicy (write-path directory/*)""" s = "/opt/test-foo-dir/*" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search_terms = ["%s rwk," % os.path.dirname(s), "%s rwk," % s] + p = self._gen_policy(extra_args=['--write-path=' + s]) + search_terms = ["{} rwk,".format(os.path.dirname(s)), "{} rwk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_dir_glob_all(self): """Test genpolicy (write-path directory/**)""" s = "/opt/test-foo-dir/**" - p = self._gen_policy(extra_args=['--write-path=%s' % s]) - search_terms = ["%s rwk," % os.path.dirname(s), "%s rwk," % s] + p = self._gen_policy(extra_args=['--write-path=' + s]) + search_terms = ["{} rwk,".format(os.path.dirname(s)), "{} rwk,".format(s)] for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_multiple(self): """Test genpolicy (write-path multiple)""" @@ -1265,31 +1265,31 @@ POLICYGROUPS_DIR="%s/templates" args = [] search_terms = [] for s in paths: - args.append('--write-path=%s' % s) + args.append('--write-path=' + s) # This mimics easyprof.gen_path_rule() owner = "" if s.startswith('/home/') or s.startswith("@{HOME"): owner = "owner " if s.endswith('/'): - search_terms.append("%s rwk," % (s)) - search_terms.append("%s%s** rwk," % (owner, s)) + search_terms.append("{} rwk,".format(s)) + search_terms.append("{}{}** rwk,".format(owner, s)) elif s.endswith('/**') or s.endswith('/*'): - search_terms.append("%s rwk," % (os.path.dirname(s))) - search_terms.append("%s%s rwk," % (owner, s)) + search_terms.append("{} rwk,".format(os.path.dirname(s))) + search_terms.append("{}{} rwk,".format(owner, s)) else: - search_terms.append("%s%s rwk," % (owner, s)) + search_terms.append("{}{} rwk,".format(owner, s)) p = self._gen_policy(extra_args=args) for search in search_terms: - self.assertTrue(search in p, "Could not find '%s' in:\n%s" % (search, p)) + self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p)) inv_s = '###READPATH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_writepath_bad(self): """Test genpolicy (write-path bad)""" s = "bar" try: - self._gen_policy(extra_args=['--write-path=%s' % s]) + self._gen_policy(extra_args=['--write-path=' + s]) except AppArmorException: return raise Exception("write-path should be invalid") @@ -1297,27 +1297,27 @@ POLICYGROUPS_DIR="%s/templates" def test_genpolicy_templatevar(self): """Test genpolicy (template-var single)""" s = "@{FOO}=bar" - p = self._gen_policy(extra_args=['--template-var=%s' % s]) + p = self._gen_policy(extra_args=['--template-var=' + s]) k, v = s.split('=') - s = '%s="%s"' % (k, v) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + s = '{}="{}"'.format(k, v) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###TEMPLATEVAR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_templatevar_multiple(self): """Test genpolicy (template-var multiple)""" variables = ['@{FOO}=bar', '@{BAR}=baz'] args = [] for s in variables: - args.append('--template-var=%s' % s) + args.append('--template-var=' + s) p = self._gen_policy(extra_args=args) for s in variables: k, v = s.split('=') - s = '%s="%s"' % (k, v) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + s = '{}="{}"'.format(k, v) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###TEMPLATEVAR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_templatevar_bad(self): """Test genpolicy (template-var - bad values)""" @@ -1334,7 +1334,7 @@ POLICYGROUPS_DIR="%s/templates" ] for s in bad: try: - self._gen_policy(extra_args=['--template-var=%s' % s]) + self._gen_policy(extra_args=['--template-var=' + s]) except AppArmorException: continue raise Exception("template-var should be invalid") @@ -1373,33 +1373,33 @@ POLICYGROUPS_DIR="%s/templates" def test_genpolicy_with_binary_with_profile_name(self): """Test genpolicy (binary with profile name)""" profile_name = "some-profile-name" - p = self._gen_policy(extra_args=['--profile-name=%s' % profile_name]) + p = self._gen_policy(extra_args=['--profile-name=' + profile_name]) s = 'profile "%s" "%s" {' % (profile_name, self.binary) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###PROFILEATTACH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_with_binary_without_profile_name(self): """Test genpolicy (binary without profile name)""" p = self._gen_policy() - s = '"%s" {' % (self.binary) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + s = '"%s" {' % (self.binary,) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###PROFILEATTACH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_genpolicy_without_binary_with_profile_name(self): """Test genpolicy (no binary with profile name)""" profile_name = "some-profile-name" args = self.full_args - args.append('--profile-name=%s' % profile_name) + args.append('--profile-name=' + profile_name) (self.options, self.args) = easyprof.parse_args(args) easyp = easyprof.AppArmorEasyProfile(None, self.options) params = easyprof.gen_policy_params(None, self.options) p = easyp.gen_policy(**params) - s = 'profile "%s" {' % (profile_name) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + s = 'profile "%s" {' % (profile_name,) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###PROFILEATTACH###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) # manifest tests @@ -1462,9 +1462,9 @@ POLICYGROUPS_DIR="%s/templates" m = Manifest("test_gen_manifest_policy") m.add_comment(s) p = self._gen_manifest_policy(m) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###COMMENT###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_author(self): """Test gen manifest policy (author)""" @@ -1472,9 +1472,9 @@ POLICYGROUPS_DIR="%s/templates" m = Manifest("test_gen_manifest_policy") m.add_author(s) p = self._gen_manifest_policy(m) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###AUTHOR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_copyright(self): """Test genpolicy (copyright)""" @@ -1482,9 +1482,9 @@ POLICYGROUPS_DIR="%s/templates" m = Manifest("test_gen_manifest_policy") m.add_copyright(s) p = self._gen_manifest_policy(m) - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###COPYRIGHT###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_policygroups(self): """Test gen manifest policy (single policygroup)""" @@ -1494,22 +1494,22 @@ POLICYGROUPS_DIR="%s/templates" p = self._gen_manifest_policy(m) for s in ('#include ', '#include '): - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###POLICYGROUPS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_policygroups_multiple(self): """Test genpolicy (multiple policygroups)""" test_policygroup2 = "test-policygroup2" contents = ''' - # %s + # {} #include #include -''' % (self.test_policygroup) +'''.format(self.test_policygroup) with open(os.path.join(self.tmpdir, 'policygroups', test_policygroup2), 'w') as f: f.write(contents) - groups = "%s,%s" % (self.test_policygroup, test_policygroup2) + groups = "{},{}".format(self.test_policygroup, test_policygroup2) m = Manifest("test_gen_manifest_policy") m.add_policygroups(groups) p = self._gen_manifest_policy(m) @@ -1518,9 +1518,9 @@ POLICYGROUPS_DIR="%s/templates" '#include ', '#include ', '#include '): - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###POLICYGROUPS###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_policygroups_nonexistent(self): """Test gen manifest policy (nonexistent policygroup)""" @@ -1539,9 +1539,9 @@ POLICYGROUPS_DIR="%s/templates" m.add_template_variable("FOO", "bar") p = self._gen_manifest_policy(m) s = '@{FOO}="bar"' - self.assertTrue(s in p, "Could not find '%s' in:\n%s" % (s, p)) + self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p)) inv_s = '###TEMPLATEVAR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_templatevar_multiple(self): """Test gen manifest policy (template-var multiple)""" @@ -1553,9 +1553,9 @@ POLICYGROUPS_DIR="%s/templates" p = self._gen_manifest_policy(m) for s in variables: str_s = '@{%s}="%s"' % (s[0], s[1]) - self.assertTrue(str_s in p, "Could not find '%s' in:\n%s" % (str_s, p)) + self.assertTrue(str_s in p, "Could not find '{}' in:\n{}".format(str_s, p)) inv_s = '###TEMPLATEVAR###' - self.assertFalse(inv_s in p, "Found '%s' in :\n%s" % (inv_s, p)) + self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p)) def test_gen_manifest_policy_invalid_keys(self): """Test gen manifest policy (invalid keys)""" @@ -1591,7 +1591,7 @@ POLICYGROUPS_DIR="%s/templates" easyprof.parse_manifest(j, self.options) except AppArmorException: continue - raise Exception("'%s' should be invalid" % k) + raise Exception("'{}' should be invalid".format(k)) def test_gen_manifest(self): """Test gen_manifest""" @@ -1830,9 +1830,9 @@ POLICYGROUPS_DIR="%s/templates" raise params = easyprof.gen_policy_params(binary, options) if expected: - self.assertTrue(easyprof.verify_manifest(params, args), "params=%s\nmanifest=%s" % (params, m)) + self.assertTrue(easyprof.verify_manifest(params, args), "params={}\nmanifest={}".format(params, m)) else: - self.assertFalse(easyprof.verify_manifest(params, args), "params=%s\nmanifest=%s" % (params, m)) + self.assertFalse(easyprof.verify_manifest(params, args), "params={}\nmanifest={}".format(params, m)) def test_verify_manifest_full(self): """Test verify_manifest (full)""" @@ -2040,7 +2040,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % v +}''' % (v,) self._verify_manifest(m, expected=False) def test_manifest_invalid(self): @@ -2102,7 +2102,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % v +}''' % (v,) args = self.full_args args.append("--manifest=/dev/null") (self.options, self.args) = easyprof.parse_args(args) @@ -2147,7 +2147,7 @@ POLICYGROUPS_DIR="%s/templates" """Test policy version via manifest (good)""" policy_vendor = "somevendor" policy_version = "1.0" - policy_subdir = "%s/%s" % (policy_vendor, policy_version) + policy_subdir = "{}/{}".format(policy_vendor, policy_version) m = '''{ "security": { "profiles": { @@ -2187,7 +2187,7 @@ POLICYGROUPS_DIR="%s/templates" """Test policy vendor and version via command line args (good)""" policy_version = "1.0" policy_vendor = "somevendor" - policy_subdir = "%s/%s" % (policy_vendor, policy_version) + policy_subdir = "{}/{}".format(policy_vendor, policy_version) # Create the directories for d in ('policygroups', 'templates'): @@ -2196,8 +2196,8 @@ POLICYGROUPS_DIR="%s/templates" # Build up our args args = self.full_args - args.append("--policy-version=%s" % policy_version) - args.append("--policy-vendor=%s" % policy_vendor) + args.append("--policy-version=" + policy_version) + args.append("--policy-vendor=" + policy_vendor) (self.options, self.args) = easyprof.parse_args(args) (self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary]) @@ -2206,12 +2206,12 @@ POLICYGROUPS_DIR="%s/templates" tdir = os.path.join(self.tmpdir, 'templates', policy_subdir) for t in easyp.get_templates(): self.assertTrue(t.startswith(tdir), - "'%s' does not start with '%s'" % (t, tdir)) + "'{}' does not start with '{}'".format(t, tdir)) pdir = os.path.join(self.tmpdir, 'policygroups', policy_subdir) for p in easyp.get_policy_groups(): self.assertTrue(p.startswith(pdir), - "'%s' does not start with '%s'" % (p, pdir)) + "'{}' does not start with '{}'".format(p, pdir)) params = easyprof.gen_policy_params(self.binary, self.options) easyp.gen_policy(**params) @@ -2221,8 +2221,8 @@ POLICYGROUPS_DIR="%s/templates" policy_vendor = "nonexistent" policy_version = "1.0" args = self.full_args - args.append("--policy-version=%s" % policy_version) - args.append("--policy-vendor=%s" % policy_vendor) + args.append("--policy-version=" + policy_version) + args.append("--policy-vendor=" + policy_vendor) (self.options, self.args) = easyprof.parse_args(args) (self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary]) @@ -2243,7 +2243,7 @@ POLICYGROUPS_DIR="%s/templates" ] for policy_version in bad: args = self.full_args - args.append("--policy-version=%s" % policy_version) + args.append("--policy-version=" + policy_version) args.append("--policy-vendor=somevendor") (self.options, self.args) = easyprof.parse_args(args) @@ -2264,7 +2264,7 @@ POLICYGROUPS_DIR="%s/templates" ] for policy_vendor in bad: args = self.full_args - args.append("--policy-vendor=%s" % policy_vendor) + args.append("--policy-vendor=" + policy_vendor) args.append("--policy-version=1.0") (self.options, self.args) = easyprof.parse_args(args) @@ -2356,7 +2356,7 @@ POLICYGROUPS_DIR="%s/templates" for fn in files: f = os.path.join(out_dir, fn) - self.assertTrue(os.path.exists(f), "Could not find '%s'" % f) + self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f)) def test_output_directory_single(self): """Test output_directory (single)""" @@ -2396,7 +2396,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % (files["com.example.foo"]) +}''' % (files["com.example.foo"],) out_dir = os.path.join(self.tmpdir, "output") @@ -2411,7 +2411,7 @@ POLICYGROUPS_DIR="%s/templates" for fn in files: f = os.path.join(out_dir, fn) - self.assertTrue(os.path.exists(f), "Could not find '%s'" % f) + self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f)) def test_output_directory_invalid(self): """Test output_directory (output directory exists as file)""" @@ -2433,7 +2433,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % files["usr.bin.baz"] +}''' % (files["usr.bin.baz"],) out_dir = os.path.join(self.tmpdir, "output") open(out_dir, 'w').close() @@ -2470,7 +2470,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % files["usr.bin.baz"] +}''' % (files["usr.bin.baz"],) out_dir = os.path.join(self.tmpdir, "output") @@ -2507,7 +2507,7 @@ POLICYGROUPS_DIR="%s/templates" } } } -}''' % files["usr.bin.baz"] +}''' % (files["usr.bin.baz"],) out_dir = os.path.join(self.tmpdir, "output") os.mkdir(out_dir) @@ -2532,8 +2532,8 @@ POLICYGROUPS_DIR="%s/templates" # Build up our args args = self.full_args - args.append('--template=%s' % self.test_template) - args.append('--name=%s' % 'foo') + args.append('--template=' + self.test_template) + args.append('--name=foo') args.append(files["usr.bin.baz"]) out_dir = os.path.join(self.tmpdir, "output") @@ -2546,7 +2546,7 @@ POLICYGROUPS_DIR="%s/templates" for fn in files: f = os.path.join(out_dir, fn) - self.assertTrue(os.path.exists(f), "Could not find '%s'" % f) + self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f)) # # utility classes @@ -2560,7 +2560,7 @@ POLICYGROUPS_DIR="%s/templates" 'com.example.app_myapp_1:2.3+ab12~foo', ] for n in names: - self.assertTrue(easyprof.valid_profile_name(n), "'%s' should be valid" % n) + self.assertTrue(easyprof.valid_profile_name(n), "'{}' should be valid".format(n)) def test_valid_profile_name_invalid(self): """Test valid_profile_name (invalid)""" @@ -2602,7 +2602,7 @@ POLICYGROUPS_DIR="%s/templates" '_foo', ] for n in names: - self.assertFalse(easyprof.valid_profile_name(n), "'%s' should be invalid" % n) + self.assertFalse(easyprof.valid_profile_name(n), "'{}' should be invalid".format(n)) def test_valid_path(self): """Test valid_path""" @@ -2616,9 +2616,9 @@ POLICYGROUPS_DIR="%s/templates" 'com.example.app_myapp_1:2.3+ab12~foo', ] for n in names: - self.assertTrue(easyprof.valid_path(n), "'%s' should be valid" % n) + self.assertTrue(easyprof.valid_path(n), "'{}' should be valid".format(n)) for n in names_rel: - self.assertTrue(easyprof.valid_path(n, relative_ok=True), "'%s' should be valid" % n) + self.assertTrue(easyprof.valid_path(n, relative_ok=True), "'{}' should be valid".format(n)) def test_zz_valid_path_invalid(self): """Test valid_path (invalid)""" @@ -2635,9 +2635,9 @@ POLICYGROUPS_DIR="%s/templates" 'com.example.app_"myapp_1:2.3+ab12~foo', ] for n in names: - self.assertFalse(easyprof.valid_path(n, relative_ok=False), "'%s' should be invalid" % n) + self.assertFalse(easyprof.valid_path(n, relative_ok=False), "'{}' should be invalid".format(n)) for n in names_rel: - self.assertFalse(easyprof.valid_path(n, relative_ok=True), "'%s' should be invalid" % n) + self.assertFalse(easyprof.valid_path(n, relative_ok=True), "'{}' should be invalid".format(n)) # diff --git a/utils/test/test-aa-notify.py b/utils/test/test-aa-notify.py index d87e56193..38a8eb24a 100644 --- a/utils/test/test-aa-notify.py +++ b/utils/test/test-aa-notify.py @@ -138,9 +138,9 @@ Feb 4 13:40:38 XPS-13-9370 kernel: [128552.880347] audit: type=1400 audit({epoc expected_output_has = 'usage: aa-notify' return_code, output = cmd(aanotify_bin) - result = 'Got return code %d, expected %d\n' % (return_code, expected_return_code) + result = 'Got return code {}, expected {}\n'.format(return_code, expected_return_code) self.assertEqual(expected_return_code, return_code, result + output) - result = 'Got output "%s", expected "%s"\n' % (output, expected_output_has) + result = 'Got output "{}", expected "{}"\n'.format(output, expected_output_has) self.assertIn(expected_output_has, output, result + output) def test_help_contents(self): @@ -173,7 +173,7 @@ Display AppArmor notifications or messages for DENIED entries. ''' return_code, output = cmd(aanotify_bin + ['--help']) - result = 'Got return code %d, expected %d\n' % (return_code, expected_return_code) + result = 'Got return code {}, expected {}\n'.format(return_code, expected_return_code) self.assertEqual(expected_return_code, return_code, result + output) self.assertIn(expected_output_1, output) @@ -186,9 +186,9 @@ Display AppArmor notifications or messages for DENIED entries. expected_output_has = 'AppArmor denials: 20 (since' return_code, output = cmd(aanotify_bin + ['-f', self.test_logfile, '-s', '100']) - result = 'Got return code %d, expected %d\n' % (return_code, expected_return_code) + result = 'Got return code {}, expected {}\n'.format(return_code, expected_return_code) self.assertEqual(expected_return_code, return_code, result + output) - result = 'Got output "%s", expected "%s"\n' % (output, expected_output_has) + result = 'Got output "{}", expected "{}"\n'.format(output, expected_output_has) self.assertIn(expected_output_has, output, result + output) @unittest.skipUnless(os.path.isfile('/var/log/wtmp'), 'Requires wtmp on system') @@ -201,9 +201,9 @@ Display AppArmor notifications or messages for DENIED entries. return_code, output = cmd(aanotify_bin + ['-f', self.test_logfile, '-l']) if "ERROR: Could not find last login" in output: self.skipTest('Could not find last login') - result = 'Got return code %d, expected %d\n' % (return_code, expected_return_code) + result = 'Got return code {}, expected {}\n'.format(return_code, expected_return_code) self.assertEqual(expected_return_code, return_code, result + output) - result = 'Got output "%s", expected "%s"\n' % (output, expected_output_has) + result = 'Got output "{}", expected "{}"\n'.format(output, expected_output_has) self.assertIn(expected_output_has, output, result + output) @unittest.skipUnless(os.path.isfile('/var/log/wtmp'), 'Requires wtmp on system') @@ -277,9 +277,9 @@ AppArmor denials: 10 (since'''.format(logfile=self.test_logfile) return_code, output = cmd(aanotify_bin + ['-f', self.test_logfile, '-l', '-v']) if "ERROR: Could not find last login" in output: self.skipTest('Could not find last login') - result = 'Got return code %d, expected %d\n' % (return_code, expected_return_code) + result = 'Got return code {}, expected {}\n'.format(return_code, expected_return_code) self.assertEqual(expected_return_code, return_code, result + output) - result = 'Got output "%s", expected "%s"\n' % (output, expected_output_has) + result = 'Got output "{}", expected "{}"\n'.format(output, expected_output_has) self.assertIn(expected_output_has, output, result + output) diff --git a/utils/test/test-aa.py b/utils/test/test-aa.py index 12dddd00f..9096341a6 100644 --- a/utils/test/test-aa.py +++ b/utils/test/test-aa.py @@ -59,7 +59,7 @@ class AaTest_check_for_apparmor(AaTestWithTempdir): def test_check_for_apparmor_securityfs_invalid_filesystems(self): filesystems = '' - mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % self.tmpdir) + mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % (self.tmpdir,)) self.assertEqual(None, check_for_apparmor(filesystems, mounts)) def test_check_for_apparmor_securityfs_invalid_mounts(self): @@ -69,13 +69,13 @@ class AaTest_check_for_apparmor(AaTestWithTempdir): def test_check_for_apparmor_invalid_securityfs_path(self): filesystems = write_file(self.tmpdir, 'filesystems', self.FILESYSTEMS_WITH_SECURITYFS) - mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % 'xxx') + mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % ('xxx',)) self.assertEqual(None, check_for_apparmor(filesystems, mounts)) def test_check_for_apparmor_securityfs_mounted(self): filesystems = write_file(self.tmpdir, 'filesystems', self.FILESYSTEMS_WITH_SECURITYFS) - mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % self.tmpdir) - self.assertEqual('%s/security/apparmor' % self.tmpdir, check_for_apparmor(filesystems, mounts)) + mounts = write_file(self.tmpdir, 'mounts', self.MOUNTS_WITH_SECURITYFS % (self.tmpdir,)) + self.assertEqual(self.tmpdir + '/security/apparmor', check_for_apparmor(filesystems, mounts)) class AATest_get_output(AATest): @@ -119,7 +119,7 @@ class AaTest_create_new_profile(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) # load the abstractions we need in the test @@ -139,22 +139,22 @@ class AaTest_create_new_profile(AATest): expected_profiles = [] for prof in exp_profiles: - expected_profiles.append('%s/%s' % (self.tmpdir, prof)) # actual profile names start with tmpdir, prepend it to the expected profile names + expected_profiles.append('{}/{}'.format(self.tmpdir, prof)) # actual profile names start with tmpdir, prepend it to the expected profile names self.assertEqual(list(profile.keys()), expected_profiles) if exp_interpreter_path: self.assertEqual( set(profile[program]['file'].get_clean()), - {'%s ix,' % exp_interpreter_path, '%s r,' % program, '', + {'{} ix,'.format(exp_interpreter_path), '{} r,'.format(program), '', '/AATest/lib64/libtinfo.so.* mr,', '/AATest/lib64/libc.so.* mr,', '/AATest/lib64/libdl.so.* mr,', '/AATest/lib64/libreadline.so.* mr,', '/AATest/lib64/ld-linux-x86-64.so.* mr,'}) else: - self.assertEqual(set(profile[program]['file'].get_clean()), {'%s mr,' % program, ''}) + self.assertEqual(set(profile[program]['file'].get_clean()), {'{} mr,'.format(program), ''}) if exp_abstraction: - self.assertEqual(profile[program]['inc_ie'].get_clean(), ['include ', 'include <%s>' % exp_abstraction, '']) + self.assertEqual(profile[program]['inc_ie'].get_clean(), ['include ', 'include <{}>'.format(exp_abstraction), '']) else: self.assertEqual(profile[program]['inc_ie'].get_clean(), ['include ', '']) @@ -183,7 +183,7 @@ class AaTest_get_interpreter_and_abstraction(AATest): def _run_test(self, params, expected): exp_interpreter_path, exp_abstraction = expected - program = self.writeTmpfile('program', "%s\nfoo\nbar" % params) + program = self.writeTmpfile('program', params + "\nfoo\nbar") interpreter_path, abstraction = get_interpreter_and_abstraction(program) # damn symlinks! @@ -198,12 +198,12 @@ class AaTest_get_interpreter_and_abstraction(AATest): def test_file_not_found(self): self.createTmpdir() - self.assertEqual((None, None), get_interpreter_and_abstraction('%s/file-not-found' % self.tmpdir)) + self.assertEqual((None, None), get_interpreter_and_abstraction(self.tmpdir + '/file-not-found')) class AaTest_get_profile_flags(AaTestWithTempdir): def _test_get_flags(self, profile_header, expected_flags): - file = write_file(self.tmpdir, 'profile', '%s {\n}\n' % profile_header) + file = write_file(self.tmpdir, 'profile', profile_header + ' {\n}\n') flags = get_profile_flags(file, '/foo') self.assertEqual(flags, expected_flags) @@ -238,10 +238,10 @@ class AaTest_change_profile_flags(AaTestWithTempdir): self, profile, old_flags, flags_to_change, set_flag, expected_flags, whitespace='', comment='', more_rules='', expected_more_rules='@-@-@', check_new_flags=True, profile_name='/foo'): if old_flags: - old_flags = ' %s' % old_flags + old_flags = ' ' + old_flags if expected_flags: - expected_flags = ' flags=(%s)' % (expected_flags) + expected_flags = ' flags=({})'.format(expected_flags) else: expected_flags = '' @@ -249,7 +249,7 @@ class AaTest_change_profile_flags(AaTestWithTempdir): expected_more_rules = more_rules if comment: - comment = ' %s' % comment + comment = ' ' + comment dummy_profile_content = ' #include \n capability chown,\n /bar r,' prof_template = '%s%s%s {%s\n%s\n%s\n}\n' @@ -406,7 +406,7 @@ class AaTest_change_profile_flags(AaTestWithTempdir): def test_change_profile_flags_file_not_found(self): with self.assertRaises(IOError): - change_profile_flags('%s/file-not-found' % self.tmpdir, '/foo', 'audit', True) + change_profile_flags(self.tmpdir + '/file-not-found', '/foo', 'audit', True) class AaTest_set_options_audit_mode(AATest): @@ -561,7 +561,7 @@ class AaTest_get_file_perms_1(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) profile = apparmor.aa.ProfileStorage('/test', '/test', 'test-aa.py') @@ -590,7 +590,7 @@ class AaTest_get_file_perms_2(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) # load the abstractions we need in the test @@ -629,7 +629,7 @@ class AaTest_propose_file_rules(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) # load the abstractions we need in the test @@ -671,7 +671,7 @@ class AaTest_propose_file_rules_with_absolute_includes(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) # load the abstractions we need in the test @@ -689,9 +689,9 @@ class AaTest_propose_file_rules_with_absolute_includes(AATest): profile = apparmor.aa.ProfileStorage('/test', '/test', 'test-aa.py') profile['inc_ie'].add(IncludeRule.create_instance('include ')) - profile['inc_ie'].add(IncludeRule.create_instance('include "%s"' % abs_include1)) - profile['inc_ie'].add(IncludeRule.create_instance('include "%s"' % abs_include2)) - profile['inc_ie'].add(IncludeRule.create_instance('include "%s"' % abs_include3)) + profile['inc_ie'].add(IncludeRule.create_instance('include "{}"'.format(abs_include1))) + profile['inc_ie'].add(IncludeRule.create_instance('include "{}"'.format(abs_include2))) + profile['inc_ie'].add(IncludeRule.create_instance('include "{}"'.format(abs_include3))) rule_obj = FileRule(params[0], params[1], None, FileRule.ALL, owner=False, log_event=True) proposals = propose_file_rules(profile, rule_obj) diff --git a/utils/test/test-aare.py b/utils/test/test-aare.py index 7198470bb..4e51a143b 100644 --- a/utils/test/test-aare.py +++ b/utils/test/test-aare.py @@ -138,12 +138,12 @@ class TestConvert_regexpAndAAREMatch(AATest): def _run_test(self, params, expected): regex, path = params parsed_regex = re.compile(convert_regexp(regex)) - self.assertEqual(bool(parsed_regex.search(path)), expected, 'Incorrectly Parsed regex: %s' % regex) + self.assertEqual(bool(parsed_regex.search(path)), expected, 'Incorrectly Parsed regex: ' + regex) aare_obj = AARE(regex, True) - self.assertEqual(aare_obj.match(path), expected, 'Incorrectly parsed AARE object: %s' % regex) + self.assertEqual(aare_obj.match(path), expected, 'Incorrectly parsed AARE object: ' + regex) if not ('*' in path or '{' in path or '}' in path or '?' in path): - self.assertEqual(aare_obj.match(AARE(path, False)), expected, 'Incorrectly parsed AARE object: AARE(%s)' % regex) + self.assertEqual(aare_obj.match(AARE(path, False)), expected, 'Incorrectly parsed AARE object: AARE({})'.format(regex)) def test_multi_usage(self): aare_obj = AARE('/foo/*', True) diff --git a/utils/test/test-abi.py b/utils/test/test-abi.py index 6e165cdcb..39addf475 100644 --- a/utils/test/test-abi.py +++ b/utils/test/test-abi.py @@ -199,11 +199,11 @@ class AbiCoveredTest(AATest): self.assertTrue(AbiRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class AbiCoveredTest_01(AbiCoveredTest): diff --git a/utils/test/test-alias.py b/utils/test/test-alias.py index ccda7bfcd..ef7bb4019 100644 --- a/utils/test/test-alias.py +++ b/utils/test/test-alias.py @@ -176,11 +176,11 @@ class AliasCoveredTest(AATest): self.assertTrue(AliasRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class AliasCoveredTest_01(AliasCoveredTest): diff --git a/utils/test/test-boolean.py b/utils/test/test-boolean.py index 522c9a634..8aca68042 100644 --- a/utils/test/test-boolean.py +++ b/utils/test/test-boolean.py @@ -181,11 +181,11 @@ class BooleanCoveredTest(AATest): self.assertTrue(BooleanRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class BooleanCoveredTest_01(BooleanCoveredTest): diff --git a/utils/test/test-change_profile.py b/utils/test/test-change_profile.py index fd0c0f2de..3c8f4c79a 100644 --- a/utils/test/test-change_profile.py +++ b/utils/test/test-change_profile.py @@ -252,11 +252,11 @@ class ChangeProfileCoveredTest(AATest): self.assertTrue(ChangeProfileRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class ChangeProfileCoveredTest_01(ChangeProfileCoveredTest): diff --git a/utils/test/test-dbus.py b/utils/test/test-dbus.py index fe2492c74..e9ff17bf2 100644 --- a/utils/test/test-dbus.py +++ b/utils/test/test-dbus.py @@ -441,11 +441,11 @@ class DbusCoveredTest(AATest): self.assertTrue(DbusRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class DbusCoveredTest_01(DbusCoveredTest): diff --git a/utils/test/test-file.py b/utils/test/test-file.py index 24bbd41e6..dc908b4c2 100644 --- a/utils/test/test-file.py +++ b/utils/test/test-file.py @@ -464,11 +464,11 @@ class FileCoveredTest(AATest): self.assertTrue(FileRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class FileCoveredTest_01(FileCoveredTest): @@ -892,7 +892,7 @@ class FileValidateAndStoreEditTest(AATest): self.assertEqual(rule_obj.validate_edit(params), expected) rule_obj.store_edit(params) - self.assertEqual(rule_obj.get_raw(), '%s r,' % params) + self.assertEqual(rule_obj.get_raw(), params + ' r,') tests = ( # edited path match diff --git a/utils/test/test-include.py b/utils/test/test-include.py index e5751e5b2..a7a37f98f 100644 --- a/utils/test/test-include.py +++ b/utils/test/test-include.py @@ -249,11 +249,11 @@ class IncludeCoveredTest(AATest): self.assertTrue(IncludeRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class IncludeCoveredTest_01(IncludeCoveredTest): @@ -332,7 +332,7 @@ class IncludeFullPathsTest(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) inc_dir = os.path.join(self.profile_dir, 'abstractions/inc.d') @@ -374,7 +374,7 @@ class IncludeRulesTest(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) write_file(self.profile_dir, 'baz', '/baz r,') diff --git a/utils/test/test-libapparmor-test_multi.py b/utils/test/test-libapparmor-test_multi.py index 1b6973ed7..02fe3c7ae 100644 --- a/utils/test/test-libapparmor-test_multi.py +++ b/utils/test/test-libapparmor-test_multi.py @@ -33,12 +33,12 @@ class TestLibapparmorTestMulti(AATest): expected = self._parse_libapparmor_test_multi(params) loglines = [] - with open_file_read('%s.in' % params) as f_in: + with open_file_read(params + '.in') as f_in: for line in f_in: if line.strip(): loglines.append(line) - self.assertEqual(len(loglines), 1, '%s.in should only contain one line!' % params) + self.assertEqual(len(loglines), 1, params + '.in should only contain one line!') parser = ReadLog('', '', '') parsed_event = parser.parse_event(loglines[0]) @@ -72,11 +72,11 @@ class TestLibapparmorTestMulti(AATest): elif parsed_items['operation'] == 'ptrace' and label == 'name2' and params.endswith('/ptrace_garbage_lp1689667_1'): pass # libapparmor would better qualify this case as invalid event elif not parsed_items.get(label, None): - raise Exception('parsed_items[%s] not set' % label) + raise Exception('parsed_items[{}] not set'.format(label)) elif not expected.get(label, None): - raise Exception('expected[%s] not set' % label) + raise Exception('expected[{}] not set'.format(label)) else: - self.assertEqual(str(parsed_items[label]), expected[label], '%s differs' % label) + self.assertEqual(str(parsed_items[label]), expected[label], label + ' differs') elif expected: self.assertIsNone(parsed_event) # that's why we end up here self.assertEqual(dict(), expected, 'parsed_event is none') # effectively print the content of expected @@ -109,12 +109,12 @@ class TestLibapparmorTestMulti(AATest): def _parse_libapparmor_test_multi(self, file_with_path): """parse the libapparmor test_multi *.in tests and their expected result in *.out""" - with open_file_read('%s.out' % file_with_path) as f_in: + with open_file_read(file_with_path + '.out') as f_in: expected = f_in.readlines() if expected[0].rstrip('\n') != 'START': - raise Exception("%s.out doesn't have 'START' in its first line! (%s)" - % (file_with_path, expected[0])) + raise Exception("{}.out doesn't have 'START' in its first line! ({})".format( + file_with_path, expected[0])) expected.pop(0) @@ -129,8 +129,8 @@ class TestLibapparmorTestMulti(AATest): exresult[label] = value.strip() if not exresult['event_type'].startswith('AA_RECORD_'): - raise Exception("event_type doesn't start with AA_RECORD_: %s in file %s" - % (exresult['event_type'], file_with_path)) + raise Exception("event_type doesn't start with AA_RECORD_: {} in file {}".format( + exresult['event_type'], file_with_path)) exresult['aamode'] = exresult['event_type'].replace('AA_RECORD_', '') if exresult['aamode'] == 'ALLOWED': @@ -189,7 +189,7 @@ class TestLogToProfile(AATest): tests = 'invalid' # filled by parse_test_profiles() def _run_test(self, params, expected): - logfile = '%s.in' % params + logfile = params + '.in' if params.split('/')[-1] in log_to_profile_skip: return @@ -198,7 +198,7 @@ class TestLogToProfile(AATest): if profile is None: return - expected_profile = read_file('%s.profile' % params) + expected_profile = read_file(params + '.profile') if params.split('/')[-1] in log_to_profile_known_failures: self.assertNotEqual(new_profile, expected_profile) # known failure @@ -222,7 +222,7 @@ def logfile_to_profile(logfile): return None, aamode if aamode not in ('PERMITTING', 'REJECTING'): - raise Exception('Unexpected aamode %s' % parsed_event['aamode']) + raise Exception('Unexpected aamode {}'.format(parsed_event['aamode'])) # cleanup apparmor.aa storage apparmor.aa.log = dict() @@ -249,7 +249,7 @@ def logfile_to_profile(logfile): log_dict = apparmor.aa.collapse_log(hashlog, ignore_null_profiles=False) if list(log_dict[aamode].keys()) != [parsed_event['profile']]: - raise Exception('log_dict[%s] contains unexpected keys. Logfile: %s, keys %s' % (aamode, logfile, log_dict.keys())) + raise Exception('log_dict[{}] contains unexpected keys. Logfile: {}, keys {}'.format(aamode, logfile, log_dict.keys())) if '//' in parsed_event['profile']: # log event for a child profile means log_dict only contains the child profile @@ -272,10 +272,10 @@ def logfile_to_profile(logfile): if logfile.split('/')[-1][:-3] in log_to_profile_known_empty_log: # unfortunately this function might be called outside Unittest.TestCase, therefore we can't use assertEqual / assertNotEqual if not log_is_empty: - raise Exception('got non-empty log for logfile in log_to_profile_known_empty_log: %s %s' % (logfile, hashlog)) + raise Exception('got non-empty log for logfile in log_to_profile_known_empty_log: {} {}'.format(logfile, hashlog)) else: if log_is_empty: - raise Exception('got empty log for logfile not in log_to_profile_known_empty_log: %s %s' % (logfile, hashlog)) + raise Exception('got empty log for logfile not in log_to_profile_known_empty_log: {} {}'.format(logfile, hashlog)) new_profile = apparmor.aa.serialize_profile(log_dict[aamode], profile, {}) @@ -297,7 +297,7 @@ def find_test_multi(log_dir): elif file.endswith('.out') or file.endswith('.err') or file.endswith('.profile'): pass else: - raise Exception('Found unknown file %s in libapparmor test_multi' % file) + raise Exception('Found unknown file {} in libapparmor test_multi'.format(file)) return tests diff --git a/utils/test/test-minitools.py b/utils/test/test-minitools.py index f99fc4de7..c6e8b0d24 100755 --- a/utils/test/test-minitools.py +++ b/utils/test/test-minitools.py @@ -29,7 +29,7 @@ class MinitoolsTest(AATest): # copy the local profiles to the test directory # Should be the set of cleanprofile - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) apparmor.profile_dir = self.profile_dir @@ -37,143 +37,152 @@ class MinitoolsTest(AATest): # Path for the program self.test_path = '/usr/sbin/winbindd' # Path for the target file containing profile - self.local_profilename = '%s/usr.sbin.winbindd' % self.profile_dir + self.local_profilename = self.profile_dir + '/usr.sbin.winbindd' def test_audit(self): # Set test profile to audit mode and check if it was correctly set - str(subprocess.check_output( - '%s ./../aa-audit --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True)) + subprocess.check_output( + '{} ./../aa-audit --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), 'audit', - 'Audit flag could not be set in profile %s' % self.local_profilename) + 'Audit flag could not be set in profile ' + self.local_profilename) # Remove audit mode from test profile and check if it was correctly removed subprocess.check_output( - '%s ./../aa-audit --no-reload -d %s -r %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-audit --no-reload -d {} -r {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), shell=True) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), None, - 'Audit flag could not be removed in profile %s' % self.local_profilename) + 'Audit flag could not be removed in profile ' + self.local_profilename) def test_complain(self): # Set test profile to complain mode and check if it was correctly set subprocess.check_output( - '%s ./../aa-complain --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-complain --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) # "manually" create a force-complain symlink (will be deleted by aa-enforce later) - force_complain_dir = '%s/force-complain' % self.profile_dir + force_complain_dir = self.profile_dir + '/force-complain' if not os.path.isdir(force_complain_dir): os.mkdir(force_complain_dir) os.symlink( self.local_profilename, - '%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))) + '{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))) self.assertEqual( - os.path.islink('%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))), True, - 'Failed to create a symlink for %s in force-complain' % self.local_profilename) + 'Failed to create a symlink for {} in force-complain'.format(self.local_profilename)) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), 'complain', - 'Complain flag could not be set in profile %s' % self.local_profilename) + 'Complain flag could not be set in profile ' + self.local_profilename) # Set test profile to enforce mode and check if it was correctly set subprocess.check_output( - '%s ./../aa-enforce --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-enforce --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) self.assertEqual( - os.path.islink('%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from force-complain' % self.local_profilename) + 'Failed to remove symlink for {} from force-complain'.format(self.local_profilename)) self.assertEqual( - os.path.islink('%s/disable/%s' % (self.profile_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/disable/{}'.format(self.profile_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from disable' % self.local_profilename) + 'Failed to remove symlink for {} from disable'.format(self.local_profilename)) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), None, - 'Complain flag could not be removed in profile %s' % self.local_profilename) + 'Complain flag could not be removed in profile ' + self.local_profilename) # Set audit flag and then complain flag in a profile subprocess.check_output( - '%s ./../aa-audit --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-audit --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) subprocess.check_output( - '%s ./../aa-complain --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-complain --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) # "manually" create a force-complain symlink (will be deleted by aa-enforce later) os.symlink( self.local_profilename, - '%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))) + '{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))) self.assertEqual( - os.path.islink('%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))), True, - 'Failed to create a symlink for %s in force-complain' % self.local_profilename) + 'Failed to create a symlink for {} in force-complain'.format(self.local_profilename)) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), 'audit, complain', - 'Complain flag could not be set in profile %s' % self.local_profilename) + 'Complain flag could not be set in profile ' + self.local_profilename) # Remove complain flag first i.e. set to enforce mode subprocess.check_output( - '%s ./../aa-enforce --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-enforce --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) self.assertEqual( - os.path.islink('%s/%s' % (force_complain_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/{}'.format(force_complain_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from force-complain' % self.local_profilename) + 'Failed to remove symlink for {} from force-complain'.format(self.local_profilename)) self.assertEqual( - os.path.islink('%s/disable/%s' % (self.profile_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/disable/{}'.format(self.profile_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from disable' % self.local_profilename) + 'Failed to remove symlink for {} from disable'.format(self.local_profilename)) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), 'audit', - 'Complain flag could not be removed in profile %s' % self.local_profilename) + 'Complain flag could not be removed in profile ' + self.local_profilename) # Remove audit flag subprocess.check_output( - '%s ./../aa-audit --no-reload -d %s -r %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-audit --no-reload -d {} -r {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) def test_enforce(self): # Set test profile to enforce mode and check if it was correctly set subprocess.check_output( - '%s ./../aa-enforce --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-enforce --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) self.assertEqual( - os.path.islink('%s/force-complain/%s' % (self.profile_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/force-complain/{}'.format(self.profile_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from force-complain' % self.local_profilename) + 'Failed to remove symlink for {} from force-complain'.format(self.local_profilename)) self.assertEqual( - os.path.islink('%s/disable/%s' % (self.profile_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/disable/{}'.format(self.profile_dir, os.path.basename(self.local_profilename))), False, - 'Failed to remove symlink for %s from disable' % self.local_profilename) + 'Failed to remove symlink for {} from disable'.format(self.local_profilename)) self.assertEqual( apparmor.get_profile_flags(self.local_profilename, self.test_path), None, - 'Complain flag could not be removed in profile %s' % self.local_profilename) + 'Complain flag could not be removed in profile {}'.format(self.local_profilename)) def test_disable(self): # Disable the test profile and check if it was correctly disabled subprocess.check_output( - '%s ./../aa-disable --no-reload -d %s %s --configdir ./' - % (python_interpreter, self.profile_dir, self.test_path), shell=True) + '{} ./../aa-disable --no-reload -d {} {} --configdir ./'.format( + python_interpreter, self.profile_dir, self.test_path), + shell=True) self.assertEqual( - os.path.islink('%s/disable/%s' % (self.profile_dir, os.path.basename(self.local_profilename))), + os.path.islink('{}/disable/{}'.format(self.profile_dir, os.path.basename(self.local_profilename))), True, - 'Failed to create a symlink for %s in disable' % self.local_profilename) + 'Failed to create a symlink for {} in disable'.format(self.local_profilename)) def test_autodep(self): pass @@ -181,10 +190,10 @@ class MinitoolsTest(AATest): @unittest.skipIf(apparmor.check_for_apparmor() is None, "Securityfs not mounted or doesn't have the apparmor directory.") def test_unconfined(self): output = subprocess.check_output( - '%s ./../aa-unconfined --configdir ./' % python_interpreter, shell=True) + python_interpreter + ' ./../aa-unconfined --configdir ./', shell=True) output_force = subprocess.check_output( - '%s ./../aa-unconfined --paranoid --configdir ./' % python_interpreter, shell=True) + python_interpreter + ' ./../aa-unconfined --paranoid --configdir ./', shell=True) self.assertIsNot(output, '', 'Failed to run aa-unconfined') @@ -194,19 +203,20 @@ class MinitoolsTest(AATest): input_file = 'cleanprof_test.in' output_file = 'cleanprof_test.out' # We position the local testfile - shutil.copy('./%s' % input_file, self.profile_dir) + shutil.copy('./' + input_file, self.profile_dir) # Our silly test program whose profile we wish to clean cleanprof_test = '/usr/bin/a/simple/cleanprof/test/profile' subprocess.check_output( - '%s ./../aa-cleanprof --no-reload -d %s -s %s --configdir ./' - % (python_interpreter, self.profile_dir, cleanprof_test), shell=True) + '{} ./../aa-cleanprof --no-reload -d {} -s {} --configdir ./'.format( + python_interpreter, self.profile_dir, cleanprof_test), + shell=True) # Strip off the first line (#modified line) - subprocess.check_output('sed -i 1d %s/%s' % (self.profile_dir, input_file), shell=True) + subprocess.check_output('sed -i 1d {}/{}'.format(self.profile_dir, input_file), shell=True) - exp_content = read_file('./%s' % output_file) - real_content = read_file('%s/%s' % (self.profile_dir, input_file)) + exp_content = read_file('./' + output_file) + real_content = read_file('{}/{}'.format(self.profile_dir, input_file)) self.maxDiff = None self.assertEqual(exp_content, real_content, 'Failed to cleanup profile properly') diff --git a/utils/test/test-network.py b/utils/test/test-network.py index 8359bded5..f8c4d15e1 100644 --- a/utils/test/test-network.py +++ b/utils/test/test-network.py @@ -254,17 +254,17 @@ class NetworkCoveredTest(AATest): self.assertEqual( obj.is_equal(check_obj), expected[0], - 'Mismatch in is_equal, expected %s' % expected[0]) + 'Mismatch in is_equal, expected {}'.format(expected[0])) self.assertEqual( obj.is_equal(check_obj, True), expected[1], - 'Mismatch in is_equal/strict, expected %s' % expected[1]) + 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) self.assertEqual( obj.is_covered(check_obj), expected[2], - 'Mismatch in is_covered, expected %s' % expected[2]) + 'Mismatch in is_covered, expected {}'.format(expected[2])) self.assertEqual( obj.is_covered(check_obj, True, True), expected[3], - 'Mismatch in is_covered/exact, expected %s' % expected[3]) + 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class NetworkCoveredTest_01(NetworkCoveredTest): diff --git a/utils/test/test-notify.py b/utils/test/test-notify.py index bb2b123d2..45572157d 100644 --- a/utils/test/test-notify.py +++ b/utils/test/test-notify.py @@ -42,7 +42,7 @@ class TestGet_last_login_timestamp(AATest): def _run_test(self, params, expected): filename, user = params - filename = 'wtmp-examples/%s' % filename + filename = 'wtmp-examples/' + filename self.assertEqual(get_last_login_timestamp(user, filename), expected) def test_date_1999(self): diff --git a/utils/test/test-parser-simple-tests.py b/utils/test/test-parser-simple-tests.py index 58c5b43a6..68cd40b89 100644 --- a/utils/test/test-parser-simple-tests.py +++ b/utils/test/test-parser-simple-tests.py @@ -459,7 +459,7 @@ def parse_test_profiles(file_with_path): exresult = False exresult_found = True else: - raise Exception('%s contains unknown EXRESULT %s' % (file_with_path, exresult)) + raise Exception('{} contains unknown EXRESULT {}'.format(file_with_path, exresult)) elif line.upper().startswith('#=DESCRIPTION '): description = line.split()[1] @@ -471,25 +471,25 @@ def parse_test_profiles(file_with_path): disabled = True if not exresult_found: - raise Exception('%s does not contain EXRESULT' % file_with_path) + raise Exception(file_with_path + ' does not contain EXRESULT') if not description: - raise Exception('%s does not contain description' % file_with_path) + raise Exception(file_with_path + ' does not contain description') tools_wrong = False if relfile in exception_not_raised: if exresult: - raise Exception("%s listed in exception_not_raised, but has EXRESULT PASS" % file_with_path) + raise Exception(file_with_path + " listed in exception_not_raised, but has EXRESULT PASS") tools_wrong = 'EXCEPTION_NOT_RAISED' elif relfile.startswith(skip_startswith): return 1 # XXX *** SKIP *** those tests elif relfile in unknown_line: if not exresult: - raise Exception("%s listed in unknown_line, but has EXRESULT FAIL" % file_with_path) + raise Exception(file_with_path + " listed in unknown_line, but has EXRESULT FAIL") tools_wrong = 'UNKNOWN_LINE' elif relfile in syntax_failure: if not exresult: - raise Exception("%s listed in syntax_failure, but has EXRESULT FAIL" % file_with_path) + raise Exception(file_with_path + " listed in syntax_failure, but has EXRESULT FAIL") tools_wrong = 'SYNTAX_FAILURE' params = { @@ -534,9 +534,9 @@ def find_and_setup_test_profiles(profile_dir): skipped += parse_test_profiles(file_with_path) if skipped: - print('Skipping %s test profiles listed in skip_startswith.' % skipped) + print('Skipping {} test profiles listed in skip_startswith.'.format(skipped)) - print('Running %s parser simple_tests...' % len(TestParseParserTests.tests)) + print('Running {} parser simple_tests...'.format(len(TestParseParserTests.tests))) setup_aa(apparmor) diff --git a/utils/test/test-profile-list.py b/utils/test/test-profile-list.py index cd40a445d..b78924380 100644 --- a/utils/test/test-profile-list.py +++ b/utils/test/test-profile-list.py @@ -33,28 +33,28 @@ class TestAdd_profile(AATest): def testEmpty(self): self.assertEqual(self.pl.profile_names, {}) self.assertEqual(self.pl.attachments, {}) - self.assertEqual('%s' % self.pl, "\n".join(['', '', '', '', ''])) + self.assertEqual(str(self.pl), "\n".join(['', '', '', '', ''])) def testAdd_profile_1(self): self.pl.add_profile('/etc/apparmor.d/bin.foo', 'foo', '/bin/foo', self.dummy_profile) self.assertEqual(self.pl.profile_names, {'foo': '/etc/apparmor.d/bin.foo'}) self.assertEqual(self.pl.attachments, {'/bin/foo': '/etc/apparmor.d/bin.foo'}) self.assertEqual(self.pl.profiles_in_file('/etc/apparmor.d/bin.foo'), ['foo']) - self.assertEqual('%s' % self.pl, '\n\n/etc/apparmor.d/bin.foo\n\n') + self.assertEqual(str(self.pl), '\n\n/etc/apparmor.d/bin.foo\n\n') def testAdd_profile_2(self): self.pl.add_profile('/etc/apparmor.d/bin.foo', None, '/bin/foo', self.dummy_profile) self.assertEqual(self.pl.profile_names, {}) self.assertEqual(self.pl.attachments, {'/bin/foo': '/etc/apparmor.d/bin.foo'}) self.assertEqual(self.pl.profiles_in_file('/etc/apparmor.d/bin.foo'), ['/bin/foo']) - self.assertEqual('%s' % self.pl, '\n\n/etc/apparmor.d/bin.foo\n\n') + self.assertEqual(str(self.pl), '\n\n/etc/apparmor.d/bin.foo\n\n') def testAdd_profile_3(self): self.pl.add_profile('/etc/apparmor.d/bin.foo', 'foo', None, self.dummy_profile) self.assertEqual(self.pl.profile_names, {'foo': '/etc/apparmor.d/bin.foo'}) self.assertEqual(self.pl.attachments, {}) self.assertEqual(self.pl.profiles_in_file('/etc/apparmor.d/bin.foo'), ['foo']) - self.assertEqual('%s' % self.pl, '\n\n/etc/apparmor.d/bin.foo\n\n') + self.assertEqual(str(self.pl), '\n\n/etc/apparmor.d/bin.foo\n\n') def testAdd_profileError_1(self): with self.assertRaises(AppArmorBug): @@ -354,7 +354,7 @@ class AaTest_get_all_merged_variables(AATest): self.createTmpdir() # copy the local profiles to the test directory - self.profile_dir = '%s/profiles' % self.tmpdir + self.profile_dir = self.tmpdir + '/profiles' apparmor.aa.profile_dir = self.profile_dir shutil.copytree('../../profiles/apparmor.d/', self.profile_dir, symlinks=True) diff --git a/utils/test/test-ptrace.py b/utils/test/test-ptrace.py index dc198a971..792c5695d 100644 --- a/utils/test/test-ptrace.py +++ b/utils/test/test-ptrace.py @@ -261,11 +261,11 @@ class PtraceCoveredTest(AATest): self.assertTrue(PtraceRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class PtraceCoveredTest_01(PtraceCoveredTest): @@ -511,8 +511,7 @@ class PtraceRulesTest(AATest): self.assertEqual([], ruleset_2.get_clean(2)) # test __repr__() for empty ruleset - as_string = '%s' % ruleset - self.assertEqual(as_string, '') + self.assertEqual(str(ruleset), '') def test_ruleset_1(self): ruleset = PtraceRuleset() @@ -540,9 +539,8 @@ class PtraceRulesTest(AATest): self.assertEqual(expected_clean, ruleset.get_clean()) # test __repr__() for non-empty ruleset - as_string = '%s' % ruleset self.assertEqual( - as_string, '\n ptrace peer=/foo,\n ptrace read,\n') + str(ruleset), '\n ptrace peer=/foo,\n ptrace read,\n') def test_ruleset_2(self): ruleset = PtraceRuleset() diff --git a/utils/test/test-regex_matches.py b/utils/test/test-regex_matches.py index f084dad3c..29c465d58 100644 --- a/utils/test/test-regex_matches.py +++ b/utils/test/test-regex_matches.py @@ -45,7 +45,7 @@ class AANamedRegexTest(AATest): match = matches.group(exp) if match: match = match - self.assertEqual(match, expected[exp], 'Group %s mismatch in rule %s' % (exp, line)) + self.assertEqual(match, expected[exp], 'Group {} mismatch in rule {}'.format(exp, line)) class AARegexHasComma(AATest): @@ -54,9 +54,9 @@ class AARegexHasComma(AATest): def _check(self, line, expected=True): result = aa.RE_RULE_HAS_COMMA.search(line) if expected: - self.assertTrue(result, 'Couldn\'t find a comma in "%s"' % line) + self.assertTrue(result, 'Couldn\'t find a comma in "{}"'.format(line)) else: - self.assertEqual(None, result, 'Found an unexpected comma in "%s"' % line) + self.assertEqual(None, result, 'Found an unexpected comma in "{}"'.format(line)) regex_has_comma_testcases = ( @@ -128,10 +128,10 @@ def setup_has_comma_testcases(): def stub_test_no_comma(self, test_string=test_string): self._check(test_string % ' ', False) - stub_test_comma.__doc__ = "test %s (w/comma)" % (description) - stub_test_no_comma.__doc__ = "test %s (no comma)" % (description) - setattr(AARegexHasComma, 'test_comma_%d' % (i), stub_test_comma) - setattr(AARegexHasComma, 'test_no_comma_%d' % (i), stub_test_no_comma) + stub_test_comma.__doc__ = "test {} (w/comma)".format(description) + stub_test_no_comma.__doc__ = "test {} (no comma)".format(description) + setattr(AARegexHasComma, 'test_comma_{}'.format(i), stub_test_comma) + setattr(AARegexHasComma, 'test_no_comma_{}'.format(i), stub_test_no_comma) class AARegexSplitComment(AATest): @@ -140,16 +140,16 @@ class AARegexSplitComment(AATest): def _check(self, line, expected, comment=None, not_comment=None): result = aa.RE_HAS_COMMENT_SPLIT.search(line) if expected: - self.assertTrue(result, 'Couldn\'t find a comment in "%s"' % line) + self.assertTrue(result, 'Couldn\'t find a comment in "{}"'.format(line)) self.assertEqual( result.group('comment'), comment, - 'Expected comment "%s", got "%s"' % (comment, result.group('comment'))) + 'Expected comment "{}", got "{}"'.format(comment, result.group('comment'))) self.assertEqual( result.group('not_comment'), not_comment, - 'Expected not comment "%s", got "%s"' % (not_comment, result.group('not_comment'))) + 'Expected not comment "{}", got "{}"'.format(not_comment, result.group('not_comment'))) else: - self.assertEqual(None, result, 'Found an unexpected comment "%s" in "%s"' - % ("" if result is None else result.group('comment'), line)) + self.assertEqual(None, result, 'Found an unexpected comment "{}" in "{}"'.format( + "" if result is None else result.group('comment'), line)) # Tuples of (string, expected result), where expected result is False if @@ -184,8 +184,8 @@ def setup_split_comment_testcases(): else: self._check(test_string, True, not_comment=result[0], comment=result[1]) - stub_test.__doc__ = "test '%s'" % (test_string) - setattr(AARegexSplitComment, 'test_split_comment_%d' % (i), stub_test) + stub_test.__doc__ = "test '{}'".format(test_string) + setattr(AARegexSplitComment, 'test_split_comment_{}'.format(i), stub_test) def _regex_test(self, line, expected): @@ -209,7 +209,7 @@ def _regex_test(self, line, expected): for (i, group) in enumerate(groups): if group: group = group.strip() - self.assertEqual(group, expected[i], 'Group %d mismatch in rule %s' % (i, line)) + self.assertEqual(group, expected[i], 'Group {} mismatch in rule {}'.format(i, line)) class AARegexCapability(AARegexTest): @@ -428,7 +428,7 @@ class Test_parse_profile_start_line(AATest): for exp in expected: self.assertEqual( matches[exp], expected[exp], - 'Group %s mismatch in rule %s' % (exp, line)) + 'Group {} mismatch in rule {}'.format(exp, line)) class TestInvalid_parse_profile_start_line(AATest): diff --git a/utils/test/test-rlimit.py b/utils/test/test-rlimit.py index 7be6cc25a..4cfbd5674 100644 --- a/utils/test/test-rlimit.py +++ b/utils/test/test-rlimit.py @@ -244,17 +244,17 @@ class RlimitCoveredTest(AATest): self.assertEqual( obj.is_equal(check_obj), expected[0], - 'Mismatch in is_equal, expected %s' % expected[0]) + 'Mismatch in is_equal, expected {}'.format(expected[0])) self.assertEqual( obj.is_equal(check_obj, True), expected[1], - 'Mismatch in is_equal/strict, expected %s' % expected[1]) + 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) self.assertEqual( obj.is_covered(check_obj), expected[2], - 'Mismatch in is_covered, expected %s' % expected[2]) + 'Mismatch in is_covered, expected {}'.format(expected[2])) self.assertEqual( obj.is_covered(check_obj, True, True), expected[3], - 'Mismatch in is_covered/exact, expected %s' % expected[3]) + 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class RlimitCoveredTest_01(RlimitCoveredTest): diff --git a/utils/test/test-severity.py b/utils/test/test-severity.py index 0d720066d..67d98c0ff 100755 --- a/utils/test/test-severity.py +++ b/utils/test/test-severity.py @@ -29,12 +29,12 @@ class SeverityBaseTest(AATest): def _capability_severity_test(self, cap, expected_rank): rank = self.sev_db.rank_capability(cap) self.assertEqual(rank, expected_rank, - 'expected rank %s, got %s' % (expected_rank, rank)) + 'expected rank {}, got {}'.format(expected_rank, rank)) def _simple_severity_w_perm(self, path, perm, expected_rank): rank = self.sev_db.rank_path(path, perm) self.assertEqual(rank, expected_rank, - 'expected rank %s, got %s' % (expected_rank, rank)) + 'expected rank {}, got {}'.format(expected_rank, rank)) class SeverityTest(SeverityBaseTest): @@ -77,7 +77,7 @@ class SeverityTestCap(SeverityBaseTest): self._capability_severity_test(params, expected) rank = self.sev_db.rank_capability(params) - self.assertEqual(rank, expected, 'expected rank %s, got %s' % (expected, rank)) + self.assertEqual(rank, expected, 'expected rank {}, got {}'.format(expected, rank)) class SeverityVarsTest(SeverityBaseTest): diff --git a/utils/test/test-signal.py b/utils/test/test-signal.py index 8c055c93a..bbb3978ca 100644 --- a/utils/test/test-signal.py +++ b/utils/test/test-signal.py @@ -279,17 +279,17 @@ class SignalCoveredTest(AATest): self.assertEqual( obj.is_equal(check_obj), expected[0], - 'Mismatch in is_equal, expected %s' % expected[0]) + 'Mismatch in is_equal, expected {}'.format(expected[0])) self.assertEqual( obj.is_equal(check_obj, True), expected[1], - 'Mismatch in is_equal/strict, expected %s' % expected[1]) + 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) self.assertEqual( obj.is_covered(check_obj), expected[2], - 'Mismatch in is_covered, expected %s' % expected[2]) + 'Mismatch in is_covered, expected {}'.format(expected[2])) self.assertEqual( obj.is_covered(check_obj, True, True), expected[3], - 'Mismatch in is_covered/exact, expected %s' % expected[3]) + 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class SignalCoveredTest_01(SignalCoveredTest): diff --git a/utils/test/test-variable.py b/utils/test/test-variable.py index 2cdad0337..cddf8ce94 100644 --- a/utils/test/test-variable.py +++ b/utils/test/test-variable.py @@ -230,11 +230,11 @@ class VariableCoveredTest(AATest): self.assertTrue(VariableRule.match(param)) - self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0]) - self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1]) + self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected {}'.format(expected[0])) + self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected {}'.format(expected[1])) - self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2]) - self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3]) + self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected {}'.format(expected[2])) + self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected {}'.format(expected[3])) class VariableCoveredTest_01(VariableCoveredTest): diff --git a/utils/vim/create-apparmor.vim.py b/utils/vim/create-apparmor.vim.py index 5c67e8fc1..2c63e0ea0 100644 --- a/utils/vim/create-apparmor.vim.py +++ b/utils/vim/create-apparmor.vim.py @@ -173,7 +173,7 @@ sys.stdout.write('" do not edit this file - edit apparmor.vim.in or create-appar with open("apparmor.vim.in") as template: for line in template: line = re.sub(regex, my_repl, line.rstrip()) - sys.stdout.write('%s\n' % line) + sys.stdout.write(line + '\n') sys.stdout.write("\n\n\n\n")