diff options
author | Mats Wichmann <mats@linux.com> | 2022-08-09 07:21:17 -0600 |
---|---|---|
committer | Mats Wichmann <mats@linux.com> | 2022-11-24 12:55:49 -0700 |
commit | be190150e3e095654cae98fc421530b3234d517b (patch) | |
tree | 76d96fa448cc6cc515dc64652341da91aa15fdc7 | |
parent | b34ce73d1696c1e371f83948d7695e011d3453a5 (diff) | |
download | scons-git-be190150e3e095654cae98fc421530b3234d517b.tar.gz |
Use f-strings in framework and framework tests
This is a mostly tool-based conversion (a couple added by hand),
and other changes were not made, to try to keep the diff manageable.
Adds a GitHub Action to run framework tests if framework changes.
Signed-off-by: Mats Wichmann <mats@linux.com>
-rw-r--r-- | .github/workflows/framework_tests.yml | 41 | ||||
-rw-r--r-- | testing/framework/TestCmd.py | 62 | ||||
-rw-r--r-- | testing/framework/TestCmdTests.py | 391 | ||||
-rw-r--r-- | testing/framework/TestCommon.py | 66 | ||||
-rw-r--r-- | testing/framework/TestCommonTests.py | 18 | ||||
-rw-r--r-- | testing/framework/TestSCons.py | 126 | ||||
-rw-r--r-- | testing/framework/TestSConsMSVS.py | 12 | ||||
-rw-r--r-- | testing/framework/TestSCons_time.py | 16 |
8 files changed, 383 insertions, 349 deletions
diff --git a/.github/workflows/framework_tests.yml b/.github/workflows/framework_tests.yml new file mode 100644 index 000000000..fcd6cf929 --- /dev/null +++ b/.github/workflows/framework_tests.yml @@ -0,0 +1,41 @@ +name: Test Framework Tests + +on: + # PR events only on master + push: + branches: + - 'master' + paths: + - 'testing/framework/*' + + pull_request: + branches: + - 'master' + paths: + - 'testing/framework/*' + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + fwtest: + strategy: + matrix: + os: ['ubuntu-latest', 'windows-latest'] + + # The type of runner that the job will run on + runs-on: ${{ matrix.os }} + + steps: + # Checkouut repository under $GITHUB_WORKSPACE + - uses: actions/checkout@v2 + + - name: Set up Python 3.11 ${{ matrix.os }} + uses: actions/setup-python@v2 + with: + python-version: '3.11' + + - name: Test test framework ${{ matrix.os }} + run: | + python runtest.py testing/framework + diff --git a/testing/framework/TestCmd.py b/testing/framework/TestCmd.py index 812314db9..b109843e0 100644 --- a/testing/framework/TestCmd.py +++ b/testing/framework/TestCmd.py @@ -369,7 +369,7 @@ def is_String(e): testprefix = 'testcmd.' if os.name in ('posix', 'nt'): - testprefix += "%s." % str(os.getpid()) + testprefix += f"{os.getpid()}." re_space = re.compile(r'\s') @@ -386,7 +386,7 @@ def _caller(tblist, skip): if name in ("?", "<module>"): name = "" else: - name = " (" + name + ")" + name = f" ({name})" string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name)) atfrom = "\tfrom" return string @@ -404,7 +404,7 @@ def clean_up_ninja_daemon(self, result_type) -> None: for path in Path(self.workdir).rglob('.ninja'): daemon_dir = Path(tempfile.gettempdir()) / ( - "scons_daemon_" + str(hashlib.md5(str(path.resolve()).encode()).hexdigest()) + f"scons_daemon_{str(hashlib.md5(str(path.resolve()).encode()).hexdigest())}" ) pidfiles = [daemon_dir / 'pidfile', path / 'scons_daemon_dirty'] for pidfile in pidfiles: @@ -452,18 +452,18 @@ def fail_test(self=None, condition=True, function=None, skip=0, message=None): sep = " " if self is not None: if self.program: - of = " of " + self.program + of = f" of {self.program}" sep = "\n\t" if self.description: - desc = " [" + self.description + "]" + desc = f" [{self.description}]" sep = "\n\t" at = _caller(traceback.extract_stack(), skip) if message: - msg = "\t%s\n" % message + msg = f"\t{message}\n" else: msg = "" - sys.stderr.write("FAILED test" + of + desc + sep + at + msg) + sys.stderr.write(f"FAILED test{of}{desc}{sep}{at}{msg}") sys.exit(1) @@ -498,14 +498,14 @@ def no_result(self=None, condition=True, function=None, skip=0): sep = " " if self is not None: if self.program: - of = " of " + self.program + of = f" of {self.program}" sep = "\n\t" if self.description: - desc = " [" + self.description + "]" + desc = f" [{self.description}]" sep = "\n\t" at = _caller(traceback.extract_stack(), skip) - sys.stderr.write("NO RESULT for test" + of + desc + sep + at) + sys.stderr.write(f"NO RESULT for test{of}{desc}{sep}{at}") sys.exit(2) @@ -602,7 +602,7 @@ def match_re(lines=None, res=None): if not is_List(res): res = res.split("\n") if len(lines) != len(res): - print("match_re: expected %d lines, found %d" % (len(res), len(lines))) + print(f"match_re: expected {len(res)} lines, found {len(lines)}") return None for i, (line, regex) in enumerate(zip(lines, res)): s = r"^{}$".format(regex) @@ -674,24 +674,24 @@ def simple_diff(a, b, fromfile='', tofile='', sm = difflib.SequenceMatcher(None, a, b) def comma(x1, x2): - return x1 + 1 == x2 and str(x2) or '%s,%s' % (x1 + 1, x2) + return x1 + 1 == x2 and str(x2) or f'{x1 + 1},{x2}' for op, a1, a2, b1, b2 in sm.get_opcodes(): if op == 'delete': - yield "{}d{}{}".format(comma(a1, a2), b1, lineterm) + yield f"{comma(a1, a2)}d{b1}{lineterm}" for l in a[a1:a2]: - yield '< ' + l + yield f"< {l}" elif op == 'insert': - yield "{}a{}{}".format(a1, comma(b1, b2), lineterm) + yield f"{a1}a{comma(b1, b2)}{lineterm}" for l in b[b1:b2]: - yield '> ' + l + yield f"> {l}" elif op == 'replace': - yield "{}c{}{}".format(comma(a1, a2), comma(b1, b2), lineterm) + yield f"{comma(a1, a2)}c{comma(b1, b2)}{lineterm}" for l in a[a1:a2]: - yield '< ' + l - yield '---{}'.format(lineterm) + yield f"< {l}" + yield f'---{lineterm}' for l in b[b1:b2]: - yield '> ' + l + yield f"> {l}" def diff_re(a, b, fromfile='', tofile='', @@ -721,10 +721,10 @@ def diff_re(a, b, fromfile='', tofile='', msg = "Regular expression error in %s: %s" raise re.error(msg % (repr(s), e.args[0])) if not expr.search(bline): - result.append("%sc%s" % (i + 1, i + 1)) - result.append('< ' + repr(a[i])) + result.append(f"{i + 1}c{i + 1}") + result.append(f"< {repr(a[i])}") result.append('---') - result.append('> ' + repr(b[i])) + result.append(f"> {repr(b[i])}") return result @@ -737,7 +737,7 @@ if os.name == 'posix': for c in special: arg = arg.replace(c, slash + c) if re_space.search(arg): - arg = '"' + arg + '"' + arg = f"\"{arg}\"" return arg else: # Windows does not allow special characters in file names @@ -745,7 +745,7 @@ else: # the arg. def escape(arg): if re_space.search(arg): - arg = '"' + arg + '"' + arg = f"\"{arg}\"" return arg if os.name == 'java': @@ -1091,7 +1091,7 @@ class TestCmd: self.cleanup() def __repr__(self): - return "%x" % id(self) + return f"{id(self):x}" banner_char = '=' banner_width = 80 @@ -1139,7 +1139,7 @@ class TestCmd: condition = self.condition if self._preserve[condition]: for dir in self._dirlist: - print("Preserved directory " + dir) + print(f"Preserved directory {dir}") else: list = self._dirlist[:] list.reverse() @@ -1175,7 +1175,7 @@ class TestCmd: cmd = list(interpreter) + cmd if arguments: if isinstance(arguments, dict): - cmd.extend(["%s=%s" % (k, v) for k, v in arguments.items()]) + cmd.extend([f"{k}={v}" for k, v in arguments.items()]) return cmd if isinstance(arguments, str): arguments = arguments.split() @@ -1646,7 +1646,7 @@ class TestCmd: if not os.path.isabs(chdir): chdir = os.path.join(self.workpath(chdir)) if self.verbose: - sys.stderr.write("chdir(" + chdir + ")\n") + sys.stderr.write(f"chdir({chdir})\n") os.chdir(chdir) if not timeout: timeout = self.timeout @@ -1700,12 +1700,12 @@ class TestCmd: write('============ STATUS: %d\n' % self.status) out = self.stdout() if out or self.verbose >= 3: - write('============ BEGIN STDOUT (len=%d):\n' % len(out)) + write(f'============ BEGIN STDOUT (len={len(out)}):\n') write(out) write('============ END STDOUT\n') err = self.stderr() if err or self.verbose >= 3: - write('============ BEGIN STDERR (len=%d)\n' % len(err)) + write(f'============ BEGIN STDERR (len={len(err)})\n') write(err) write('============ END STDERR\n') diff --git a/testing/framework/TestCmdTests.py b/testing/framework/TestCmdTests.py index 057fd6034..1406e0b69 100644 --- a/testing/framework/TestCmdTests.py +++ b/testing/framework/TestCmdTests.py @@ -97,10 +97,10 @@ class TestCmdTestCase(unittest.TestCase): textx = fmt % (t.scriptx, t.scriptx) if sys.platform == 'win32': textx = textx.replace('%', '%%') - textx = '@python -c "%s"' % textx + ' %1 %2 %3 %4 %5 %6 %7 %8 %9\n' + textx = f"@python -c \"{textx}\" %1 %2 %3 %4 %5 %6 %7 %8 %9\n" else: - textx = '#! /usr/bin/env python\n' + textx + '\n' - text1 = 'A first line to be ignored!\n' + fmt % (t.script1, t.script1) + textx = f"#! /usr/bin/env python\n{textx}\n" + text1 = f"A first line to be ignored!\n{fmt % (t.script1, t.script1)}" textout = fmtout % t.scriptout texterr = fmterr % t.scripterr @@ -151,33 +151,27 @@ class TestCmdTestCase(unittest.TestCase): python = sys.executable _stdout, _stderr, _status = self.call_python(indata, python) assert _status == status, ( - "status = %s, expected %s\n" % (str(_status), str(status)) - + "STDOUT ===================\n" - + _stdout - + "STDERR ===================\n" - + _stderr + f"status = {_status}, expected {status}\n" + f"STDOUT ===================\n{_stdout}" + f"STDERR ===================\n{_stderr}" ) assert _stdout == stdout, ( - "Expected STDOUT ==========\n" - + stdout - + "Actual STDOUT ============\n" - + _stdout - + "STDERR ===================\n" - + _stderr + f"Expected STDOUT ==========\n{stdout}" + f"Actual STDOUT ============\n{_stdout}" + f"STDERR ===================\n{_stderr}" ) assert _stderr == stderr, ( - "Expected STDERR ==========\n" - + stderr - + "Actual STDERR ============\n" - + _stderr + f"Expected STDERR ==========\n{stderr}" + f"Actual STDERR ============\n{_stderr}" ) def run_match(self, content, *args): expect = "%s: %s: %s: %s\n" % args content = self.translate_newlines(to_str(content)) - assert content == expect, \ - "Expected %s ==========\n" % args[1] + expect + \ - "Actual %s ============\n" % args[1] + content + assert content == expect, ( + f"Expected {args[1] + expect} ==========\n" + f"Actual {args[1] + content} ============\n" + ) @@ -238,12 +232,12 @@ class cleanup_TestCase(TestCmdTestCase): def test_atexit(self): """Test cleanup when atexit is used""" - self.popen_python("""\ + self.popen_python(f"""\ import atexit import sys import TestCmd -sys.path = [r'%s'] + sys.path +sys.path = [r'{self.orig_cwd}'] + sys.path @atexit.register def cleanup(): @@ -251,7 +245,7 @@ def cleanup(): result = TestCmd.TestCmd(workdir='') sys.exit(0) -""" % self.orig_cwd, stdout='cleanup()\n') +""", stdout='cleanup()\n') class chmod_TestCase(TestCmdTestCase): @@ -273,17 +267,17 @@ class chmod_TestCase(TestCmdTestCase): test.chmod(['sub', 'file2'], stat.S_IWRITE) file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE]) - assert file1_mode == 0o444, '0%o' % file1_mode + assert file1_mode == 0o444, f'0{file1_mode:o}' file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE]) - assert file2_mode == 0o666, '0%o' % file2_mode + assert file2_mode == 0o666, f'0{file2_mode:o}' test.chmod('file1', stat.S_IWRITE) test.chmod(wdir_sub_file2, stat.S_IREAD) file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE]) - assert file1_mode == 0o666, '0%o' % file1_mode + assert file1_mode == 0o666, f'0{file1_mode:o}' file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE]) - assert file2_mode == 0o444, '0%o' % file2_mode + assert file2_mode == 0o444, f'0{file2_mode:o}' else: @@ -291,17 +285,17 @@ class chmod_TestCase(TestCmdTestCase): test.chmod(['sub', 'file2'], 0o760) file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE]) - assert file1_mode == 0o700, '0%o' % file1_mode + assert file1_mode == 0o700, f'0{file1_mode:o}' file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE]) - assert file2_mode == 0o760, '0%o' % file2_mode + assert file2_mode == 0o760, f'0{file2_mode:o}' test.chmod('file1', 0o765) test.chmod(wdir_sub_file2, 0o567) file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE]) - assert file1_mode == 0o765, '0%o' % file1_mode + assert file1_mode == 0o765, f'0{file1_mode:o}' file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE]) - assert file2_mode == 0o567, '0%o' % file2_mode + assert file2_mode == 0o567, f'0{file2_mode:o}' @@ -335,7 +329,7 @@ sys.stderr.write("run2 STDERR third line\\n") combine = 1) output = test.stdout() if output is not None: - raise IndexError("got unexpected output:\n\t`%s'\n" % output) + raise IndexError(f"got unexpected output:\n\t`{output}'\n") # The underlying system subprocess implementations can combine # stdout and stderr in different orders, so we accomodate both. @@ -414,8 +408,8 @@ class diff_TestCase(TestCmdTestCase): def test_diff_custom_function(self): """Test diff() using a custom function""" - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def my_diff(a, b): return [ @@ -428,7 +422,7 @@ def my_diff(a, b): test = TestCmd.TestCmd(diff = my_diff) test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", "STDOUT") sys.exit(0) -""" % self.orig_cwd, +""", stdout = """\ STDOUT========================================================================== ***** @@ -439,13 +433,13 @@ STDOUT========================================================================== """) def test_diff_string(self): - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff = 'diff_re') test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", 'STDOUT') sys.exit(0) -""" % self.orig_cwd, +""", stdout = """\ STDOUT========================================================================== 2c2 @@ -456,12 +450,12 @@ STDOUT========================================================================== def test_error(self): """Test handling a compilation error in TestCmd.diff_re()""" - script_input = """import sys -sys.path = [r'%s'] + sys.path + script_input = f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd assert TestCmd.diff_re([r"a.*(e"], ["abcde"]) sys.exit(0) -""" % self.orig_cwd +""" stdout, stderr, status = self.call_python(script_input) assert status == 1, status expect1 = "Regular expression error in '^a.*(e$': missing )" @@ -471,8 +465,8 @@ sys.exit(0) def test_simple_diff_static_method(self): """Test calling the TestCmd.TestCmd.simple_diff() static method""" - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd result = TestCmd.TestCmd.simple_diff(['a', 'b', 'c', 'e', 'f1'], ['a', 'c', 'd', 'e', 'f2']) @@ -480,12 +474,12 @@ result = list(result) expect = ['2d1', '< b', '3a3', '> d', '5c5', '< f1', '---', '> f2'] assert result == expect, result sys.exit(0) -""" % self.orig_cwd) +""") def test_context_diff_static_method(self): """Test calling the TestCmd.TestCmd.context_diff() static method""" - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd result = TestCmd.TestCmd.context_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'], ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n']) @@ -509,12 +503,12 @@ expect = [ ] assert result == expect, result sys.exit(0) -""" % self.orig_cwd) +""") def test_unified_diff_static_method(self): """Test calling the TestCmd.TestCmd.unified_diff() static method""" - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd result = TestCmd.TestCmd.unified_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'], ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n']) @@ -533,12 +527,12 @@ expect = [ ] assert result == expect, result sys.exit(0) -""" % self.orig_cwd) +""") def test_diff_re_static_method(self): """Test calling the TestCmd.TestCmd.diff_re() static method""" - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd result = TestCmd.TestCmd.diff_re(['a', 'b', 'c', '.', 'f1'], ['a', 'c', 'd', 'e', 'f2']) @@ -559,20 +553,20 @@ expect = [ ] assert result == expect, result sys.exit(0) -""" % self.orig_cwd) +""") class diff_stderr_TestCase(TestCmdTestCase): def test_diff_stderr_default(self): """Test diff_stderr() default behavior""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd() test.diff_stderr('a\nb1\nc\n', 'a\nb2\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 2c2 < b1 @@ -582,9 +576,9 @@ sys.exit(0) def test_diff_stderr_not_affecting_diff_stdout(self): """Test diff_stderr() not affecting diff_stdout() behavior""" - self.popen_python(r""" + self.popen_python(fr""" import sys -sys.path = [r'%s'] + sys.path +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stderr='diff_re') print("diff_stderr:") @@ -592,7 +586,7 @@ test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n') print("diff_stdout:") test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ diff_stderr: diff_stdout: @@ -604,15 +598,15 @@ diff_stdout: def test_diff_stderr_custom_function(self): """Test diff_stderr() using a custom function""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def my_diff(a, b): return ["a:"] + a + ["b:"] + b test = TestCmd.TestCmd(diff_stderr=my_diff) test.diff_stderr('abc', 'def') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ a: abc @@ -622,13 +616,13 @@ def def test_diff_stderr_TestCmd_function(self): """Test diff_stderr() using a TestCmd function""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stderr = TestCmd.diff_re) test.diff_stderr('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -638,13 +632,13 @@ sys.exit(0) def test_diff_stderr_static_method(self): """Test diff_stderr() using a static method""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stderr=TestCmd.TestCmd.diff_re) test.diff_stderr('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -654,13 +648,13 @@ sys.exit(0) def test_diff_stderr_string(self): """Test diff_stderr() using a string to fetch the diff method""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stderr='diff_re') test.diff_stderr('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -673,13 +667,13 @@ sys.exit(0) class diff_stdout_TestCase(TestCmdTestCase): def test_diff_stdout_default(self): """Test diff_stdout() default behavior""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd() test.diff_stdout('a\nb1\nc\n', 'a\nb2\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 2c2 < b1 @@ -689,9 +683,9 @@ sys.exit(0) def test_diff_stdout_not_affecting_diff_stderr(self): """Test diff_stdout() not affecting diff_stderr() behavior""" - self.popen_python(r""" + self.popen_python(fr""" import sys -sys.path = [r'%s'] + sys.path +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stdout='diff_re') print("diff_stdout:") @@ -699,7 +693,7 @@ test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n') print("diff_stderr:") test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ diff_stdout: diff_stderr: @@ -711,15 +705,15 @@ diff_stderr: def test_diff_stdout_custom_function(self): """Test diff_stdout() using a custom function""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def my_diff(a, b): return ["a:"] + a + ["b:"] + b test = TestCmd.TestCmd(diff_stdout=my_diff) test.diff_stdout('abc', 'def') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ a: abc @@ -729,13 +723,13 @@ def def test_diff_stdout_TestCmd_function(self): """Test diff_stdout() using a TestCmd function""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stdout = TestCmd.diff_re) test.diff_stdout('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -745,13 +739,13 @@ sys.exit(0) def test_diff_stdout_static_method(self): """Test diff_stdout() using a static method""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stdout=TestCmd.TestCmd.diff_re) test.diff_stdout('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -761,13 +755,13 @@ sys.exit(0) def test_diff_stdout_string(self): """Test diff_stdout() using a string to fetch the diff method""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(diff_stdout='diff_re') test.diff_stdout('a\n.\n', 'b\nc\n') sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ 1c1 < 'a' @@ -787,12 +781,12 @@ class exit_TestCase(TestCmdTestCase): 'fail_test': "FAILED test at line 5 of <stdin>\n", 'no_result': "NO RESULT for test at line 5 of <stdin>\n"} global ExitError - input = """import sys -sys.path = [r'%s'] + sys.path + input = f"""import sys +sys.path = [r'{cwd}'] + sys.path import TestCmd -test = TestCmd.TestCmd(workdir = '%s') -test.%s() -""" % (cwd, tempdir, condition) +test = TestCmd.TestCmd(workdir = '{tempdir}') +test.{condition}() +""" stdout, stderr, status = self.call_python(input, python="python") if close_true[condition]: unexpected = (status != 0) @@ -805,7 +799,7 @@ test.%s() msg = "Expected exit status %d, got %d\n" raise ExitError(msg % (exit_status[condition], status)) if stderr != result_string[condition]: - msg = "Expected error output:\n%sGot error output:\n%s" + msg = "Expected error output:\n%s\nGot error output:\n%s" raise ExitError(msg % (result_string[condition], stderr)) if preserved: if not os.path.exists(tempdir): @@ -862,40 +856,40 @@ sys.stderr.write("run: STDERR\\n") os.chdir(run_env.workdir) # Everything before this prepared our "source directory." # Now do the real test. - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd TestCmd.fail_test(condition = 1) -""" % self.orig_cwd, status = 1, stderr = "FAILED test at line 4 of <stdin>\n") +""", status = 1, stderr = "FAILED test at line 4 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() test.fail_test(condition = (test.status == 0)) -""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin>\n" % run_env.workpath('run')) +""", status = 1, stderr = f"FAILED test of {run_env.workpath('run')}\n\tat line 6 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', description = 'xyzzy', workdir = '') test.run() test.fail_test(condition = (test.status == 0)) -""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s [xyzzy]\n\tat line 6 of <stdin>\n" % run_env.workpath('run')) +""", status = 1, stderr = f"FAILED test of {run_env.workpath('run')} [xyzzy]\n\tat line 6 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() def xxx(): sys.stderr.write("printed on failure\\n") test.fail_test(condition = (test.status == 0), function = xxx) -""" % self.orig_cwd, status = 1, stderr = "printed on failure\nFAILED test of %s\n\tat line 8 of <stdin>\n" % run_env.workpath('run')) +""", status = 1, stderr = f"printed on failure\nFAILED test of {run_env.workpath('run')}\n\tat line 8 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def test1(self): self.run() @@ -903,10 +897,10 @@ def test1(self): def test2(self): test1(self) test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')) -""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run')) +""", status = 1, stderr = f"FAILED test of {run_env.workpath('run')}\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def test1(self): self.run() @@ -914,7 +908,7 @@ def test1(self): def test2(self): test1(self) test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')) -""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run')) +""", status = 1, stderr = f"FAILED test of {run_env.workpath('run')}\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n") @@ -1062,12 +1056,12 @@ class match_re_dotall_TestCase(TestCmdTestCase): # Everything before this prepared our "source directory." # Now do the real test. try: - script_input = """import sys -sys.path = [r'%s'] + sys.path + script_input = f"""import sys +sys.path = [r'{cwd}'] + sys.path import TestCmd assert TestCmd.match_re_dotall("abcde", r"a.*(e") sys.exit(0) -""" % cwd +""" stdout, stderr, status = self.call_python(script_input) assert status == 1, status expect1 = "Regular expression error in '^a.*(e$': missing )" @@ -1135,12 +1129,14 @@ class match_re_TestCase(TestCmdTestCase): # Everything before this prepared our "source directory." # Now do the real test. try: - script_input = """import sys -sys.path = [r'%s'] + sys.path + script_input = f"""import sys +sys.path = [r'{cwd}'] + sys.path import TestCmd -assert TestCmd.match_re("abcde\\n", "a.*(e\\n") +assert TestCmd.match_re("abcde\ +", "a.*(e\ +") sys.exit(0) -""" % cwd +""" stdout, stderr, status = self.call_python(script_input) assert status == 1, status expect1 = "Regular expression error in '^a.*(e$': missing )" @@ -1345,40 +1341,40 @@ sys.stderr.write("run: STDERR\\n") os.chdir(run_env.workdir) # Everything before this prepared our "source directory." # Now do the real test. - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd TestCmd.no_result(condition = 1) -""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test at line 4 of <stdin>\n") +""", status = 2, stderr = "NO RESULT for test at line 4 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() test.no_result(condition = (test.status == 0)) -""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 6 of <stdin>\n" % run_env.workpath('run')) +""", status = 2, stderr = f"NO RESULT for test of {run_env.workpath('run')}\n\tat line 6 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', description = 'xyzzy', workdir = '') test.run() test.no_result(condition = (test.status == 0)) -""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s [xyzzy]\n\tat line 6 of <stdin>\n" % run_env.workpath('run')) +""", status = 2, stderr = f"NO RESULT for test of {run_env.workpath('run')} [xyzzy]\n\tat line 6 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() def xxx(): sys.stderr.write("printed on no result\\n") test.no_result(condition = (test.status == 0), function = xxx) -""" % self.orig_cwd, status = 2, stderr = "printed on no result\nNO RESULT for test of %s\n\tat line 8 of <stdin>\n" % run_env.workpath('run')) +""", status = 2, stderr = f"printed on no result\nNO RESULT for test of {run_env.workpath('run')}\n\tat line 8 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def test1(self): self.run() @@ -1386,10 +1382,10 @@ def test1(self): def test2(self): test1(self) test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')) -""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run')) +""", status = 2, stderr = f"NO RESULT for test of {run_env.workpath('run')}\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd def test1(self): self.run() @@ -1397,7 +1393,7 @@ def test1(self): def test2(self): test1(self) test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')) -""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run')) +""", status = 2, stderr = f"NO RESULT for test of {run_env.workpath('run')}\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n") @@ -1412,29 +1408,29 @@ sys.stderr.write("run: STDERR\\n") os.chdir(run_env.workdir) # Everything before this prepared our "source directory." # Now do the real test. - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd TestCmd.pass_test(condition = 1) -""" % self.orig_cwd, stderr = "PASSED\n") +""", stderr = "PASSED\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() test.pass_test(condition = (test.status == 0)) -""" % self.orig_cwd, stderr = "PASSED\n") +""", stderr = "PASSED\n") - self.popen_python("""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '') test.run() def brag(): sys.stderr.write("printed on success\\n") test.pass_test(condition = (test.status == 0), function = brag) -""" % self.orig_cwd, stderr = "printed on success\nPASSED\n") +""", stderr = "printed on success\nPASSED\n") # TODO(sgk): SHOULD ALSO TEST FAILURE CONDITIONS @@ -1453,7 +1449,7 @@ class preserve_TestCase(TestCmdTestCase): else: test.cleanup() o = io.getvalue() - assert o == stdout, "o = `%s', stdout = `%s'" % (o, stdout) + assert o == stdout, f"o = `{o}', stdout = `{stdout}'" finally: sys.stdout = save @@ -1474,7 +1470,7 @@ class preserve_TestCase(TestCmdTestCase): try: test.write('file2', "Test file #2\n") test.preserve('pass_test') - cleanup_test(test, 'pass_test', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'pass_test', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) cleanup_test(test, 'fail_test') assert not os.path.exists(wdir) @@ -1488,7 +1484,7 @@ class preserve_TestCase(TestCmdTestCase): try: test.write('file3', "Test file #3\n") test.preserve('fail_test') - cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'fail_test', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) cleanup_test(test, 'pass_test') assert not os.path.exists(wdir) @@ -1502,9 +1498,9 @@ class preserve_TestCase(TestCmdTestCase): try: test.write('file4', "Test file #4\n") test.preserve('fail_test', 'no_result') - cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'fail_test', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) - cleanup_test(test, 'no_result', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'no_result', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) cleanup_test(test, 'pass_test') assert not os.path.exists(wdir) @@ -1517,11 +1513,11 @@ class preserve_TestCase(TestCmdTestCase): wdir = test.workdir try: test.preserve() - cleanup_test(test, 'pass_test', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'pass_test', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) - cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'fail_test', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) - cleanup_test(test, 'no_result', "Preserved directory %s\n" % wdir) + cleanup_test(test, 'no_result', f"Preserved directory {wdir}\n") assert os.path.isdir(wdir) finally: if os.path.exists(wdir): @@ -1626,7 +1622,7 @@ class rmdir_TestCase(TestCmdTestCase): else: raise Exception("did not catch expected SConsEnvironmentError") - assert os.path.isdir(s_d_o), "%s is gone?" % s_d_o + assert os.path.isdir(s_d_o), f"{s_d_o} is gone?" try: test.rmdir(['sub']) @@ -1635,21 +1631,21 @@ class rmdir_TestCase(TestCmdTestCase): else: raise Exception("did not catch expected SConsEnvironmentError") - assert os.path.isdir(s_d_o), "%s is gone?" % s_d_o + assert os.path.isdir(s_d_o), f"{s_d_o} is gone?" test.rmdir(['sub', 'dir', 'one']) - assert not os.path.exists(s_d_o), "%s exists?" % s_d_o - assert os.path.isdir(s_d), "%s is gone?" % s_d + assert not os.path.exists(s_d_o), f"{s_d_o} exists?" + assert os.path.isdir(s_d), f"{s_d} is gone?" test.rmdir(['sub', 'dir']) - assert not os.path.exists(s_d), "%s exists?" % s_d - assert os.path.isdir(s), "%s is gone?" % s + assert not os.path.exists(s_d), f"{s_d} exists?" + assert os.path.isdir(s), f"{s} is gone?" test.rmdir('sub') - assert not os.path.exists(s), "%s exists?" % s + assert not os.path.exists(s), f"{s} exists?" @@ -1854,7 +1850,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert o == '', o e = sys.stderr.getvalue() - expect = 'python "%s" "arg1 arg2"\n' % t.script_path + expect = f'python "{t.script_path}" "arg1 arg2\"\n' assert expect == e, (expect, e) testx = TestCmd.TestCmd(program = t.scriptx, @@ -1863,7 +1859,7 @@ class run_verbose_TestCase(TestCmdTestCase): with closing(StringIO()) as sys.stdout, closing(StringIO()) as sys.stderr: testx.run(arguments = ['arg1 arg2']) - expect = '"%s" "arg1 arg2"\n' % t.scriptx_path + expect = f'"{t.scriptx_path}" "arg1 arg2\"\n' o = sys.stdout.getvalue() assert o == '', o e = sys.stderr.getvalue() @@ -1907,7 +1903,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert expect == o, (expect, o) - expect = 'python "%s" "arg1 arg2"\n' % t.script_path + expect = f'python "{t.script_path}" "arg1 arg2\"\n' e = sys.stderr.getvalue() assert e == expect, (e, expect) @@ -1926,7 +1922,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert expect == o, (expect, o) - expect = '"%s" "arg1 arg2"\n' % t.scriptx_path + expect = f'"{t.scriptx_path}" "arg1 arg2\"\n' e = sys.stderr.getvalue() assert e == expect, (e, expect) @@ -1947,7 +1943,7 @@ class run_verbose_TestCase(TestCmdTestCase): assert expect == o, (expect, o) e = sys.stderr.getvalue() - expect = 'python "%s" "arg1 arg2"\n' % t.scriptout_path + expect = f'python "{t.scriptout_path}" "arg1 arg2\"\n' assert e == expect, (e, expect) test = TestCmd.TestCmd(program = t.scriptout, @@ -1966,7 +1962,7 @@ class run_verbose_TestCase(TestCmdTestCase): assert expect == o, (expect, o) e = sys.stderr.getvalue() - expect = 'python "%s" "arg1 arg2"\n' % t.scriptout_path + expect = f'python "{t.scriptout_path}" "arg1 arg2\"\n' assert e == expect, (e, expect) # Test letting TestCmd() pick up verbose = 2 from the environment. @@ -1988,7 +1984,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert expect == o, (expect, o) - expect = 'python "%s" "arg1 arg2"\n' % t.script_path + expect = f'python "{t.script_path}" "arg1 arg2\"\n' e = sys.stderr.getvalue() assert e == expect, (e, expect) @@ -2006,7 +2002,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert expect == o, (expect, o) - expect = '"%s" "arg1 arg2"\n' % t.scriptx_path + expect = f'"{t.scriptx_path}" "arg1 arg2\"\n' e = sys.stderr.getvalue() assert e == expect, (e, expect) @@ -2024,7 +2020,7 @@ class run_verbose_TestCase(TestCmdTestCase): o = sys.stdout.getvalue() assert o == '', o e = sys.stderr.getvalue() - expect = 'python "%s" "arg1 arg2"\n' % t.script_path + expect = f'python "{t.script_path}" "arg1 arg2\"\n' assert expect == e, (expect, e) testx = TestCmd.TestCmd(program = t.scriptx, @@ -2033,7 +2029,7 @@ class run_verbose_TestCase(TestCmdTestCase): with closing(StringIO()) as sys.stdout, closing(StringIO()) as sys.stderr: testx.run(arguments = ['arg1 arg2']) - expect = '"%s" "arg1 arg2"\n' % t.scriptx_path + expect = f'"{t.scriptx_path}" "arg1 arg2\"\n' o = sys.stdout.getvalue() assert o == '', o e = sys.stderr.getvalue() @@ -2050,21 +2046,20 @@ class run_verbose_TestCase(TestCmdTestCase): class set_diff_function_TestCase(TestCmdTestCase): def test_set_diff_function(self): """Test set_diff_function()""" - self.popen_python(r"""import sys -sys.path = [r'%s'] + sys.path + self.popen_python(fr"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd() test.diff("a\n", "a\n") test.set_diff_function('diff_re') test.diff(".\n", "a\n") sys.exit(0) -""" % self.orig_cwd) +""") def test_set_diff_function_stdout(self): """Test set_diff_function(): stdout""" - self.popen_python("""\ -import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd() print("diff:") @@ -2077,7 +2072,7 @@ test.diff(".\\n", "a\\n") print("diff_stdout:") test.diff_stdout(".\\n", "a\\n") sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ diff: diff_stdout: @@ -2091,9 +2086,8 @@ diff_stdout: def test_set_diff_function_stderr(self): """Test set_diff_function(): stderr """ - self.popen_python("""\ -import sys -sys.path = [r'%s'] + sys.path + self.popen_python(f"""import sys +sys.path = [r'{self.orig_cwd}'] + sys.path import TestCmd test = TestCmd.TestCmd() print("diff:") @@ -2106,7 +2100,7 @@ test.diff(".\\n", "a\\n") print("diff_stderr:") test.diff_stderr(".\\n", "a\\n") sys.exit(0) -""" % self.orig_cwd, +""", stdout="""\ diff: diff_stderr: @@ -2173,13 +2167,13 @@ class sleep_TestCase(TestCmdTestCase): test.sleep() end = time.perf_counter() diff = end - start - assert diff > 0.9, "only slept %f seconds (start %f, end %f), not default" % (diff, start, end) + assert diff > 0.9, f"only slept {diff:f} seconds (start {start:f}, end {end:f}), not default" start = time.perf_counter() test.sleep(3) end = time.perf_counter() diff = end - start - assert diff > 2.9, "only slept %f seconds (start %f, end %f), not 3" % (diff, start, end) + assert diff > 2.9, f"only slept {diff:f} seconds (start {start:f}, end {end:f}), not 3" @@ -2209,7 +2203,7 @@ sys.stderr.write("run2 STDERR second line\\n") pass else: if output is not None: - raise IndexError("got unexpected output:\n" + output) + raise IndexError(f"got unexpected output:\n{output}") test.program_set('run1') test.run(arguments = 'foo bar') test.program_set('run2') @@ -2294,8 +2288,7 @@ class start_TestCase(TestCmdTestCase): t.recv_script = 'script_recv' t.recv_script_path = t.run_env.workpath(t.sub_dir, t.recv_script) t.recv_out_path = t.run_env.workpath('script_recv.out') - text = """\ -import os + text = f"""import os import sys class Unbuffered: @@ -2312,7 +2305,7 @@ sys.stderr = Unbuffered(sys.stderr) sys.stdout.write('script_recv: STDOUT\\n') sys.stderr.write('script_recv: STDERR\\n') -with open(r'%s', 'wb') as logfp: +with open(r'{t.recv_out_path}', 'wb') as logfp: while 1: line = sys.stdin.readline() if not line: @@ -2320,7 +2313,7 @@ with open(r'%s', 'wb') as logfp: logfp.write('script_recv: ' + line) sys.stdout.write('script_recv: STDOUT: ' + line) sys.stderr.write('script_recv: STDERR: ' + line) -""" % t.recv_out_path +""" t.run_env.write(t.recv_script_path, text) os.chmod(t.recv_script_path, 0o644) # XXX UNIX-specific return t @@ -2611,8 +2604,8 @@ script_recv: STDERR: input p.wait() with open(t.recv_out_path, 'rb') as f: result = to_str(f.read()) - expect = 'script_recv: ' + input - assert result == expect, "Result:[%s] should match\nExpected:[%s]" % (result, expect) + expect = f"script_recv: {input}" + assert result == expect, f"Result:[{result}] should match\nExpected:[{expect}]" p = test.start(stdin=1) input = 'send() input to the receive script\n' @@ -2621,7 +2614,7 @@ script_recv: STDERR: input p.wait() with open(t.recv_out_path, 'rb') as f: result = to_str(f.read()) - expect = 'script_recv: ' + input + expect = f"script_recv: {input}" assert result == expect, repr(result) finally: @@ -2681,7 +2674,7 @@ script_recv: STDERR: input to the receive script assert stderr == expect_stderr, stderr with open(t.recv_out_path, 'rb') as f: result = f.read() - expect = ('script_recv: ' + input) * 2 + expect = f"script_recv: {input}" * 2 assert result == expect, (result, stdout, stderr) finally: @@ -2720,13 +2713,15 @@ class stdout_TestCase(TestCmdTestCase): def test_stdout(self): """Test stdout()""" run_env = TestCmd.TestCmd(workdir = '') - run_env.write('run1', """import sys + run_env.write('run1', """\ +import sys sys.stdout.write("run1 STDOUT %s\\n" % sys.argv[1:]) sys.stdout.write("run1 STDOUT second line\\n") sys.stderr.write("run1 STDERR %s\\n" % sys.argv[1:]) sys.stderr.write("run1 STDERR second line\\n") """) - run_env.write('run2', """import sys + run_env.write('run2', """\ +import sys sys.stdout.write("run2 STDOUT %s\\n" % sys.argv[1:]) sys.stdout.write("run2 STDOUT second line\\n") sys.stderr.write("run2 STDERR %s\\n" % sys.argv[1:]) @@ -2738,7 +2733,7 @@ sys.stderr.write("run2 STDERR second line\\n") test = TestCmd.TestCmd(interpreter = 'python', workdir = '') output = test.stdout() if output is not None: - raise IndexError("got unexpected output:\n\t`%s'\n" % output) + raise IndexError(f"got unexpected output:\n\t`{output}'\n") test.program_set('run1') test.run(arguments = 'foo bar') test.program_set('run2') diff --git a/testing/framework/TestCommon.py b/testing/framework/TestCommon.py index df005b341..bba629f40 100644 --- a/testing/framework/TestCommon.py +++ b/testing/framework/TestCommon.py @@ -319,10 +319,10 @@ class TestCommon(TestCmd): file_contents = self.read(file, mode) if not contains(file_contents, required, find): - print("File `%s' does not contain required string." % file) + print(f"File `{file}' does not contain required string.") print(self.banner('Required string ')) print(required) - print(self.banner('%s contents ' % file)) + print(self.banner(f'{file} contents ')) print(file_contents) self.fail_test() @@ -343,9 +343,9 @@ class TestCommon(TestCmd): if not contains(output, input, find): if title is None: title = 'output' - print('Missing expected input from {}:'.format(title)) + print(f'Missing expected input from {title}:') print(input) - print(self.banner(title + ' ')) + print(self.banner(f"{title} ")) print(output) self.fail_test() @@ -367,10 +367,10 @@ class TestCommon(TestCmd): if missing: if title is None: title = 'output' - sys.stdout.write("Missing expected lines from %s:\n" % title) + sys.stdout.write(f"Missing expected lines from {title}:\n") for line in missing: - sys.stdout.write(' ' + repr(line) + '\n') - sys.stdout.write(self.banner(title + ' ') + '\n') + sys.stdout.write(f" {repr(line)}\n") + sys.stdout.write(f"{self.banner(f'{title} ')}\n") sys.stdout.write(output) self.fail_test() @@ -394,10 +394,10 @@ class TestCommon(TestCmd): if counts: if title is None: title = 'output' - sys.stdout.write("Unexpected number of lines from %s:\n" % title) + sys.stdout.write(f"Unexpected number of lines from {title}:\n") for line in counts: - sys.stdout.write(' ' + repr(line) + ": found " + str(counts[line]) + '\n') - sys.stdout.write(self.banner(title + ' ') + '\n') + sys.stdout.write(f" {repr(line)}: found {str(counts[line])}\n") + sys.stdout.write(f"{self.banner(f'{title} ')}\n") sys.stdout.write(output) self.fail_test() @@ -418,10 +418,10 @@ class TestCommon(TestCmd): if title is None: title = 'output' - sys.stdout.write("Missing any expected line from %s:\n" % title) + sys.stdout.write(f"Missing any expected line from {title}:\n") for line in lines: - sys.stdout.write(' ' + repr(line) + '\n') - sys.stdout.write(self.banner(title + ' ') + '\n') + sys.stdout.write(f" {repr(line)}\n") + sys.stdout.write(f"{self.banner(f'{title} ')}\n") sys.stdout.write(output) self.fail_test() @@ -461,15 +461,15 @@ class TestCommon(TestCmd): if title is None: title = 'output' if missing: - sys.stdout.write("Missing expected lines from %s:\n" % title) + sys.stdout.write(f"Missing expected lines from {title}:\n") for line in missing: - sys.stdout.write(' ' + repr(line) + '\n') - sys.stdout.write(self.banner('Missing %s ' % title) + '\n') + sys.stdout.write(f" {repr(line)}\n") + sys.stdout.write(f"{self.banner(f'Missing {title} ')}\n") if out: - sys.stdout.write("Extra unexpected lines from %s:\n" % title) + sys.stdout.write(f"Extra unexpected lines from {title}:\n") for line in out: - sys.stdout.write(' ' + repr(line) + '\n') - sys.stdout.write(self.banner('Extra %s ' % title) + '\n') + sys.stdout.write(f" {repr(line)}\n") + sys.stdout.write(f"{self.banner(f'Extra {title} ')}\n") sys.stdout.flush() self.fail_test() @@ -523,7 +523,7 @@ class TestCommon(TestCmd): except KeyboardInterrupt: raise except: - print("Unexpected contents of `%s'" % file) + print(f"Unexpected contents of `{file}'") self.diff(expect, file_contents, 'contents ') raise @@ -533,10 +533,10 @@ class TestCommon(TestCmd): file_contents = self.read(file, mode) if contains(file_contents, banned, find): - print("File `%s' contains banned string." % file) + print(f"File `{file}' contains banned string.") print(self.banner('Banned string ')) print(banned) - print(self.banner('%s contents ' % file)) + print(self.banner(f'{file} contents ')) print(file_contents) self.fail_test() @@ -559,10 +559,10 @@ class TestCommon(TestCmd): if unexpected: if title is None: title = 'output' - sys.stdout.write("Unexpected lines in %s:\n" % title) + sys.stdout.write(f"Unexpected lines in {title}:\n") for line in unexpected: - sys.stdout.write(' ' + repr(line) + '\n') - sys.stdout.write(self.banner(title + ' ') + '\n') + sys.stdout.write(f" {repr(line)}\n") + sys.stdout.write(f"{self.banner(f'{title} ')}\n") sys.stdout.write(output) self.fail_test() @@ -606,7 +606,7 @@ class TestCommon(TestCmd): Exits FAILED if the file doesn't exist or is empty. """ if not (os.path.exists(file) or os.path.islink(file)): - print("File doesn't exist: `%s'" % file) + print(f"File doesn't exist: `{file}'") self.fail_test(file) try: @@ -615,7 +615,7 @@ class TestCommon(TestCmd): fsize = 0 if fsize == 0: - print("File is empty: `%s'" % file) + print(f"File is empty: `{file}'") self.fail_test(file) def must_not_be_writable(self, *files): @@ -643,8 +643,8 @@ class TestCommon(TestCmd): if _failed(self, status): expect = '' if status != 0: - expect = " (expected %s)" % str(status) - print("%s returned %s%s" % (self.program, _status(self), expect)) + expect = f" (expected {str(status)})" + print(f"{self.program} returned {_status(self)}{expect}") print(self.banner('STDOUT ')) print(actual_stdout) print(self.banner('STDERR ')) @@ -692,7 +692,7 @@ class TestCommon(TestCmd): except IndexError: pass cmd_args = self.command_args(program, interpreter, arguments) - sys.stderr.write('Exception trying to execute: %s\n' % cmd_args) + sys.stderr.write(f'Exception trying to execute: {cmd_args}\n') raise e def finish(self, popen, stdout = None, stderr = '', status = 0, **kw): @@ -801,15 +801,15 @@ class TestCommon(TestCmd): v_split = value.split('\n') e_split = expect.split('\n') if len(v_split) != len(e_split): - print("different number of lines:%d %d" % (len(v_split), len(e_split))) + print(f"different number of lines:{len(v_split)} {len(e_split)}") # breakpoint() for v, e in zip(v_split, e_split): # print("%s:%s"%(v,e)) if v != e: - print("\n[%s]\n[%s]" % (v, e)) + print(f"\n[{v}]\n[{e}]") - return "Expected:\n%s\nGot:\n%s" % (expect, value) + return f"Expected:\n{expect}\nGot:\n{value}" # Local Variables: diff --git a/testing/framework/TestCommonTests.py b/testing/framework/TestCommonTests.py index 67859d81e..d6fb03a97 100644 --- a/testing/framework/TestCommonTests.py +++ b/testing/framework/TestCommonTests.py @@ -49,12 +49,12 @@ def assert_display(expect, result, error=None): pass display = [ '\n', - f'{"EXPECTED: " :*<80}' + '\n', + f"{'EXPECTED: ':*<80}\n", expect, - f'{"GOT: " :*<80}' + '\n', + f"{'GOT: ':*<80}\n", result, - error if error else '', - ('*'*80) + '\n', + '' if error is None else error, + f"{'':*<80}\n", ] return ''.join(display) @@ -349,7 +349,7 @@ class must_contain_TestCase(TestCommonTestCase): """) run_env.run(program=sys.executable, stdin=script) stdout = run_env.stdout() - assert stdout == expect, "got:\n%s\nexpected:\n%s"%(stdout, expect) + assert stdout == expect, f"got:\n{stdout}\nexpected:\n{expect}" stderr = run_env.stderr() assert stderr.find("FAILED") != -1, stderr @@ -1328,7 +1328,7 @@ class must_not_contain_TestCase(TestCommonTestCase): """) run_env.run(program=sys.executable, stdin=script) stdout = run_env.stdout() - assert stdout == expect, "\ngot:\n%s\nexpected:\n%s" % (stdout, expect) + assert stdout == expect, f"\ngot:\n{stdout}\nexpected:\n{expect}" stderr = run_env.stderr() assert stderr.find("FAILED") != -1, stderr @@ -1353,7 +1353,7 @@ class must_not_contain_TestCase(TestCommonTestCase): """) run_env.run(program=sys.executable, stdin=script) stdout = run_env.stdout() - assert stdout == expect, "\ngot:\n%s\nexpected:\n%s" % (stdout, expect) + assert stdout == expect, f"\ngot:\n{stdout}\nexpected:\n{expect}" stderr = run_env.stderr() assert stderr.find("FAILED") != -1, stderr @@ -2384,13 +2384,13 @@ class variables_TestCase(TestCommonTestCase): ] script = "import TestCommon\n" + \ - '\n'.join([ "print(TestCommon.%s)\n" % v for v in variables ]) + '\n'.join([ f"print(TestCommon.{v})\n" for v in variables ]) run_env.run(program=sys.executable, stdin=script) stderr = run_env.stderr() assert stderr == "", stderr script = "from TestCommon import *\n" + \ - '\n'.join([ "print(%s)" % v for v in variables ]) + '\n'.join([ f"print({v})" for v in variables ]) run_env.run(program=sys.executable, stdin=script) stderr = run_env.stderr() assert stderr == "", stderr diff --git a/testing/framework/TestSCons.py b/testing/framework/TestSCons.py index dea9ab51c..eb907b8f8 100644 --- a/testing/framework/TestSCons.py +++ b/testing/framework/TestSCons.py @@ -67,7 +67,7 @@ python_version_supported_str = "3.6.0" # str of lowest non-deprecated version # version in build/testing/framework/TestSCons.py contains the actual version # string of the packages that have been built. SConsVersion = '__VERSION__' -if SConsVersion == '__' + 'VERSION' + '__': +if SConsVersion == f"__VERSION__": SConsVersion = default_version __all__.extend([ @@ -126,7 +126,7 @@ file_expr = r"""File "[^"]*", line \d+, in [^\n]+ # re.escape escapes too much. def re_escape(str): for c in '\\.[]()*+?': # Not an exhaustive list. - str = str.replace(c, '\\' + c) + str = str.replace(c, f"\\{c}") return str @@ -370,7 +370,7 @@ class TestSCons(TestCommon): """ env = self.Environment(ENV) if env: - v = env.subst('$' + var) + v = env.subst(f"${var}") if not v: return None if prog is None: @@ -495,12 +495,12 @@ class TestSCons(TestCommon): """ s = "" for arg in arguments.split(): - s = s + "scons: `%s' is up to date.\n" % arg + s = f"{s}scons: `{arg}' is up to date.\n" kw['arguments'] = arguments stdout = self.wrap_stdout(read_str=read_str, build_str=s) # Append '.*' so that timing output that comes after the # up-to-date output is okay. - kw['stdout'] = re.escape(stdout) + '.*' + kw['stdout'] = f"{re.escape(stdout)}.*" kw['match'] = self.match_re_dotall self.run(**kw) @@ -511,8 +511,8 @@ class TestSCons(TestCommon): """ s = "" for arg in arguments.split(): - s = s + "(?!scons: `%s' is up to date.)" % re.escape(arg) - s = '(' + s + '[^\n]*\n)*' + s = f"{s}(?!scons: `{re.escape(arg)}' is up to date.)" + s = f"({s}[^\n]*\n)*" kw['arguments'] = arguments stdout = re.escape(self.wrap_stdout(build_str='ARGUMENTSGOHERE')) kw['stdout'] = stdout.replace('ARGUMENTSGOHERE', s) @@ -524,7 +524,7 @@ class TestSCons(TestCommon): Verifies expected behavior for options that are not yet implemented: a warning message, and exit status 1. """ - msg = "Warning: the %s option is not yet implemented\n" % option + msg = f"Warning: the {option} option is not yet implemented\n" kw['stderr'] = msg if arguments: # If it's a long option and the argument string begins with '=', @@ -532,14 +532,14 @@ class TestSCons(TestCommon): if option[:2] == '--' and arguments[0] == '=': kw['arguments'] = option + arguments else: - kw['arguments'] = option + ' ' + arguments + kw['arguments'] = f"{option} {arguments}" return self.run(**kw) def deprecated_wrap(self, msg): """ Calculate the pattern that matches a deprecation warning. """ - return '\nscons: warning: ' + re_escape(msg) + '\n' + file_expr + return f"\nscons: warning: {re_escape(msg)}\n{file_expr}" def deprecated_fatal(self, warn, msg): """ @@ -601,11 +601,11 @@ class TestSCons(TestCommon): def RunPair(option, expected): # run the same test with the option on the command line and # then with the option passed via SetOption(). - self.run(options='--warn=' + option, + self.run(options=f"--warn={option}", arguments='.', stderr=expected, match=match_re_dotall) - self.run(options='WARN=' + option, + self.run(options=f"WARN={option}", arguments='.', stderr=expected, match=match_re_dotall) @@ -617,8 +617,8 @@ class TestSCons(TestCommon): RunPair(warn, warning) # warning disabled, should get either nothing or mandatory message - expect = """()|(Can not disable mandataory warning: 'no-%s'\n\n%s)""" % (warn, warning) - RunPair('no-' + warn, expect) + expect = f"""()|(Can not disable mandataory warning: 'no-{warn}'\n\n{warning})""" + RunPair(f"no-{warn}", expect) return warning @@ -658,7 +658,7 @@ class TestSCons(TestCommon): # x = x.replace('<string>', file) # x = x.replace('line 1,', 'line %s,' % line) # x="\n".join(x) - x = 'File "%s", line %s, in <module>\n' % (file, line) + x = f'File "{file}", line {line}, in <module>\n' return x def normalize_ps(self, s): @@ -751,7 +751,7 @@ class TestSCons(TestCommon): if hash_format is None and current_hash_algorithm == 'md5': return ".sconsign" else: - database_prefix=".sconsign_%s" % current_hash_algorithm + database_prefix=f".sconsign_{current_hash_algorithm}" return database_prefix @@ -797,13 +797,13 @@ class TestSCons(TestCommon): if version: if sys.platform == 'win32': patterns = [ - 'C:/Program Files*/Java/jdk*%s*/bin' % version, + f'C:/Program Files*/Java/jdk*{version}*/bin', ] else: patterns = [ - '/usr/java/jdk%s*/bin' % version, - '/usr/lib/jvm/*-%s*/bin' % version, - '/usr/local/j2sdk%s*/bin' % version, + f'/usr/java/jdk{version}*/bin', + f'/usr/lib/jvm/*-{version}*/bin', + f'/usr/local/j2sdk{version}*/bin', ] java_path = self.paths(patterns) + [env['ENV']['PATH']] else: @@ -848,10 +848,10 @@ class TestSCons(TestCommon): '/usr/lib/jvm/default-java/include/jni.h', '/usr/lib/jvm/java-*-oracle/include/jni.h'] else: - jni_dirs = ['/System/Library/Frameworks/JavaVM.framework/Versions/%s*/Headers/jni.h' % version] - jni_dirs.extend(['/usr/lib/jvm/java-*-sun-%s*/include/jni.h' % version, - '/usr/lib/jvm/java-%s*-openjdk*/include/jni.h' % version, - '/usr/java/jdk%s*/include/jni.h' % version]) + jni_dirs = [f'/System/Library/Frameworks/JavaVM.framework/Versions/{version}*/Headers/jni.h'] + jni_dirs.extend([f'/usr/lib/jvm/java-*-sun-{version}*/include/jni.h', + f'/usr/lib/jvm/java-{version}*-openjdk*/include/jni.h', + f'/usr/java/jdk{version}*/include/jni.h']) dirs = self.paths(jni_dirs) if not dirs: return None @@ -896,10 +896,10 @@ class TestSCons(TestCommon): if os.path.exists(home): return home else: - if java_home.find('jdk%s' % version) != -1: + if java_home.find(f'jdk{version}') != -1: return java_home for home in [ - '/System/Library/Frameworks/JavaVM.framework/Versions/%s/Home' % version, + f'/System/Library/Frameworks/JavaVM.framework/Versions/{version}/Home', # osx 10.10 '/System/Library/Frameworks/JavaVM.framework/Versions/Current/' ]: @@ -909,7 +909,7 @@ class TestSCons(TestCommon): home = '' else: jar = self.java_where_jar(version) - home = os.path.normpath('%s/..' % jar) + home = os.path.normpath(f'{jar}/..') if home and os.path.isdir(home): return home @@ -934,7 +934,7 @@ class TestSCons(TestCommon): or b"Unable to locate a Java Runtime" in cp.stdout ): self.skip_test( - "Could not find Java " + java_bin_name + ", skipping test.\n", + f"Could not find Java {java_bin_name}, skipping test.\n", from_fw=True, ) @@ -1003,7 +1003,7 @@ class TestSCons(TestCommon): status=None) # Note recent versions output version info to stdout instead of stderr if version: - verf = 'javac %s' % version + verf = f'javac {version}' if self.stderr().find(verf) == -1 and self.stdout().find(verf) == -1: fmt = "Could not find javac for Java version %s, skipping test(s).\n" self.skip_test(fmt % version, from_fw=True) @@ -1174,8 +1174,8 @@ else: self.QT = self.workpath(dir) self.QT_LIB = 'myqt' - self.QT_MOC = '%s %s' % (_python_, self.workpath(dir, 'bin', 'mymoc.py')) - self.QT_UIC = '%s %s' % (_python_, self.workpath(dir, 'bin', 'myuic.py')) + self.QT_MOC = f"{_python_} {self.workpath(dir, 'bin', 'mymoc.py')}" + self.QT_UIC = f"{_python_} {self.workpath(dir, 'bin', 'myuic.py')}" self.QT_LIB_DIR = self.workpath(dir, 'lib') def Qt_create_SConstruct(self, place): @@ -1241,7 +1241,7 @@ SConscript(sconscript) """ if check_platform: if sys.platform != 'win32': - msg = "Skipping Visual C/C++ test on non-Windows platform '%s'\n" % sys.platform + msg = f"Skipping Visual C/C++ test on non-Windows platform '{sys.platform}'\n" self.skip_test(msg, from_fw=True) return @@ -1295,14 +1295,14 @@ SConscript(sconscript) if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) - log = "\t" + re.escape("Configure(confdir = %s)" % sconf_dir) + ls + log = f"\t{re.escape(f'Configure(confdir = {sconf_dir})')}" + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) rdstr = "" for check_info in checks: - log = re.escape("scons: Configure: " + check_info.check_string) + ls + log = re.escape(f"scons: Configure: {check_info.check_string}") + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) @@ -1318,9 +1318,9 @@ SConscript(sconscript) # rebuild will pass if ext in ['.c', '.cpp']: log = log + conf_filename + re.escape(" <-") + ls - log = log + r"( \|" + nols + "*" + ls + ")+?" + log = f"{log}( \\|{nols}*{ls})+?" else: - log = log + "(" + nols + "*" + ls + ")*?" + log = f"{log}({nols}*{ls})*?" result_cached = 0 if flag == self.CR: # CR = cached rebuild (up to date)s @@ -1331,10 +1331,10 @@ SConscript(sconscript) re.escape("\" is up to date.") + ls log = log + re.escape("scons: Configure: The original builder " "output was:") + ls - log = log + r"( \|.*" + ls + ")+" + log = f"{log}( \\|.*{ls})+" if flag == self.NCF: # non-cached rebuild failure - log = log + "(" + nols + "*" + ls + ")*?" + log = f"{log}({nols}*{ls})*?" result_cached = 0 if flag == self.CF: # cached rebuild failure @@ -1343,14 +1343,14 @@ SConscript(sconscript) conf_filename + \ re.escape("\" failed in a previous run and all its sources are up to date.") + ls log = log + re.escape("scons: Configure: The original builder output was:") + ls - log = log + r"( \|.*" + ls + ")+" + log = f"{log}( \\|.*{ls})+" if result_cached: - result = "(cached) " + check_info.result + result = f"(cached) {check_info.result}" else: result = check_info.result - rdstr = rdstr + re.escape(check_info.check_string) + re.escape(result) + "\n" + rdstr = f"{rdstr + re.escape(check_info.check_string) + re.escape(result)}\n" - log = log + re.escape("scons: Configure: " + result) + ls + ls + log = log + re.escape(f"scons: Configure: {result}") + ls + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) @@ -1433,7 +1433,7 @@ SConscript(sconscript) if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) - log = "\t" + re.escape("Configure(confdir = %s)" % sconf_dir) + ls + log = f"\t{re.escape(f'Configure(confdir = {sconf_dir})')}" + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) @@ -1441,7 +1441,7 @@ SConscript(sconscript) cnt = 0 for check, result, cache_desc in zip(checks, results, cached): - log = re.escape("scons: Configure: " + check) + ls + log = re.escape(f"scons: Configure: {check}") + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) @@ -1474,9 +1474,9 @@ SConscript(sconscript) # rebuild will pass if ext in ['.c', '.cpp']: log = log + conf_filename + re.escape(" <-") + ls - log = log + r"( \|" + nols + "*" + ls + ")+?" + log = f"{log}( \\|{nols}*{ls})+?" else: - log = log + "(" + nols + "*" + ls + ")*?" + log = f"{log}({nols}*{ls})*?" result_cached = 0 if flag == self.CR: # CR = cached rebuild (up to date)s @@ -1487,10 +1487,10 @@ SConscript(sconscript) re.escape("\" is up to date.") + ls log = log + re.escape("scons: Configure: The original builder " "output was:") + ls - log = log + r"( \|.*" + ls + ")+" + log = f"{log}( \\|.*{ls})+" if flag == self.NCF: # non-cached rebuild failure - log = log + "(" + nols + "*" + ls + ")*?" + log = f"{log}({nols}*{ls})*?" result_cached = 0 if flag == self.CF: # cached rebuild failure @@ -1499,14 +1499,14 @@ SConscript(sconscript) conf_filename + \ re.escape("\" failed in a previous run and all its sources are up to date.") + ls log = log + re.escape("scons: Configure: The original builder output was:") + ls - log = log + r"( \|.*" + ls + ")+" + log = f"{log}( \\|.*{ls})+" # cnt = cnt + 1 if result_cached: - result = "(cached) " + result + result = f"(cached) {result}" - rdstr = rdstr + re.escape(check) + re.escape(result) + "\n" + rdstr = f"{rdstr + re.escape(check) + re.escape(result)}\n" - log = log + re.escape("scons: Configure: " + result) + ls + ls + log = log + re.escape(f"scons: Configure: {result}") + ls + ls if doCheckLog: lastEnd = match_part_of_configlog(log, logfile, lastEnd) @@ -1650,7 +1650,7 @@ else: waited = 0.0 while not os.path.exists(fname): if timeout and waited >= timeout: - sys.stderr.write('timed out waiting for %s to exist\n' % fname) + sys.stderr.write(f'timed out waiting for {fname} to exist\n') if popen: popen.stdin.close() popen.stdin = None @@ -1658,11 +1658,11 @@ else: self.finish(popen) stdout = self.stdout() if stdout: - sys.stdout.write(self.banner('STDOUT ') + '\n') + sys.stdout.write(f"{self.banner('STDOUT ')}\n") sys.stdout.write(stdout) stderr = self.stderr() if stderr: - sys.stderr.write(self.banner('STDERR ') + '\n') + sys.stderr.write(f"{self.banner('STDERR ')}\n") sys.stderr.write(stderr) self.fail_test() time.sleep(1.0) @@ -1807,7 +1807,7 @@ class TimeSCons(TestSCons): if 'options' not in kw and self.variables: options = [] for variable, value in self.variables.items(): - options.append('%s=%s' % (variable, value)) + options.append(f'{variable}={value}') kw['options'] = ' '.join(options) if self.calibrate: self.calibration(*args, **kw) @@ -1821,8 +1821,8 @@ class TimeSCons(TestSCons): fmt = "TRACE: graph=%s name=%s value=%s units=%s" line = fmt % (graph, name, value, units) if sort is not None: - line = line + (' sort=%s' % sort) - line = line + '\n' + line = f"{line} sort={sort}" + line = f"{line}\n" sys.stdout.write(line) sys.stdout.flush() @@ -1866,7 +1866,7 @@ class TimeSCons(TestSCons): options = kw.get('options', '') if additional is not None: options += additional - kw['options'] = options + ' --debug=memory,time' + kw['options'] = f"{options} --debug=memory,time" def startup(self, *args, **kw): """ @@ -1912,8 +1912,8 @@ class TimeSCons(TestSCons): self.run(*args, **kw) for variable in self.calibrate_variables: value = self.variables[variable] - sys.stdout.write('VARIABLE: %s=%s\n' % (variable, value)) - sys.stdout.write('ELAPSED: %s\n' % self.elapsed_time()) + sys.stdout.write(f'VARIABLE: {variable}={value}\n') + sys.stdout.write(f'ELAPSED: {self.elapsed_time()}\n') def null(self, *args, **kw): """ @@ -1997,12 +1997,12 @@ class TimeSCons(TestSCons): """ s = "" for arg in arguments.split(): - s = s + "scons: `%s' is up to date.\n" % arg + s = f"{s}scons: `{arg}' is up to date.\n" kw['arguments'] = arguments stdout = self.wrap_stdout(read_str="REPLACEME", build_str=s) # Append '.*' so that timing output that comes after the # up-to-date output is okay. - stdout = re.escape(stdout) + '.*' + stdout = f"{re.escape(stdout)}.*" stdout = stdout.replace('REPLACEME', read_str) kw['stdout'] = stdout kw['match'] = self.match_re_dotall diff --git a/testing/framework/TestSConsMSVS.py b/testing/framework/TestSConsMSVS.py index 6e5e01bca..b001d79c8 100644 --- a/testing/framework/TestSConsMSVS.py +++ b/testing/framework/TestSConsMSVS.py @@ -690,7 +690,7 @@ print("self._msvs_versions =%%s"%%str(SCons.Tool.MSCommon.query_versions())) orig = 'sys.path = [ join(sys' enginepath = repr(os.path.join(self._cwd, '..', 'engine')) - replace = 'sys.path = [ %s, join(sys' % enginepath + replace = f'sys.path = [ {enginepath}, join(sys' contents = self.read(fname, mode='r') contents = contents.replace(orig, replace) @@ -719,9 +719,9 @@ print("self._msvs_versions =%%s"%%str(SCons.Tool.MSCommon.query_versions())) project_guid = "{B0CC4EE9-0174-51CD-A06A-41D0713E928A}" if 'SCONS_LIB_DIR' in os.environ: - exec_script_main = "from os.path import join; import sys; sys.path = [ r'%s' ] + sys.path; import SCons.Script; SCons.Script.main()" % os.environ['SCONS_LIB_DIR'] + exec_script_main = f"from os.path import join; import sys; sys.path = [ r'{os.environ['SCONS_LIB_DIR']}' ] + sys.path; import SCons.Script; SCons.Script.main()" else: - exec_script_main = "from os.path import join; import sys; sys.path = [ join(sys.prefix, 'Lib', 'site-packages', 'scons-%s'), join(sys.prefix, 'scons-%s'), join(sys.prefix, 'Lib', 'site-packages', 'scons'), join(sys.prefix, 'scons') ] + sys.path; import SCons.Script; SCons.Script.main()" % (self.scons_version, self.scons_version) + exec_script_main = f"from os.path import join; import sys; sys.path = [ join(sys.prefix, 'Lib', 'site-packages', 'scons-{self.scons_version}'), join(sys.prefix, 'scons-{self.scons_version}'), join(sys.prefix, 'Lib', 'site-packages', 'scons'), join(sys.prefix, 'scons') ] + sys.path; import SCons.Script; SCons.Script.main()" exec_script_main_xml = exec_script_main.replace("'", "'") result = input.replace(r'<WORKPATH>', workpath) @@ -823,7 +823,7 @@ print("self._msvs_versions =%%s"%%str(SCons.Tool.MSCommon.query_versions())) elif major > 10: return '12.00' else: - raise SCons.Errors.UserError('Received unexpected VC version %s' % vc_version) + raise SCons.Errors.UserError(f'Received unexpected VC version {vc_version}') def _get_solution_file_vs_number(self, vc_version): """ @@ -846,7 +846,7 @@ print("self._msvs_versions =%%s"%%str(SCons.Tool.MSCommon.query_versions())) elif major == 14 and minor == 2: return '16' else: - raise SCons.Errors.UserError('Received unexpected VC version %s' % vc_version) + raise SCons.Errors.UserError(f'Received unexpected VC version {vc_version}') def _get_vcxproj_file_tools_version(self, vc_version): """ @@ -877,7 +877,7 @@ print("self._msvs_versions =%%s"%%str(SCons.Tool.MSCommon.query_versions())) # ToolsVersion='17' return '17.0' else: - raise SCons.Errors.UserError('Received unexpected VC version %s' % vc_version) + raise SCons.Errors.UserError(f'Received unexpected VC version {vc_version}') def _get_vcxproj_file_cpp_path(self, dirs): """Returns the include paths expected in the .vcxproj file""" diff --git a/testing/framework/TestSCons_time.py b/testing/framework/TestSCons_time.py index e647fe2c2..282a9a69e 100644 --- a/testing/framework/TestSCons_time.py +++ b/testing/framework/TestSCons_time.py @@ -73,8 +73,7 @@ with open('SConstruct', 'r') as f: exec(script) """ -svn_py = """\ -#!/usr/bin/env python +svn_py = f"""#!/usr/bin/env python import os import sys @@ -82,12 +81,11 @@ dir = sys.argv[-1] script_dir = dir + '/scripts' os.makedirs(script_dir) with open(script_dir + '/scons.py', 'w') as f: - f.write(r'''%s''') -""" % scons_py + f.write(r'''{scons_py}''') +""" -git_py = """\ -#!/usr/bin/env python +git_py = f"""#!/usr/bin/env python import os import sys @@ -95,8 +93,8 @@ dir = sys.argv[-1] script_dir = dir + '/scripts' os.makedirs(script_dir) with open(script_dir + '/scons.py', 'w') as f: - f.write(r'''%s''') -""" % scons_py + f.write(r'''{scons_py}''') +""" logfile_contents = """\ @@ -243,7 +241,7 @@ class TestSCons_time(TestCommon): args = (tempdir, 'scons-time-',) + args x = os.path.join(*args) x = re.escape(x) - x = x.replace('time\\-', 'time\\-[^%s]*' % sep) + x = x.replace('time\\-', f'time\\-[^{sep}]*') return x def write_fake_scons_py(self): |