@@ -69,10 +69,10 @@ def test_project_custom_platform(tmpdir):
"""
project_file = __write_cppcheck_project_file(tmpdir, platform='p1.xml')
- with open(os.path.join(tmpdir, 'p1.xml'), 'wt') as f:
+ with open(os.path.join(tmpdir, 'p1.xml'), 'w') as f:
f.write('\n')
- with open(os.path.join(tmpdir, '1.c'), 'wt') as f:
+ with open(os.path.join(tmpdir, '1.c'), 'w') as f:
f.write("int x;")
ret, stdout, stderr = cppcheck(['--project=' + project_file, '--template=cppcheck1', '-q'])
@@ -87,7 +87,7 @@ def test_project_empty_platform(tmpdir):
"""
project_file = __write_cppcheck_project_file(tmpdir, platform='')
- with open(os.path.join(tmpdir, '1.c'), 'wt') as f:
+ with open(os.path.join(tmpdir, '1.c'), 'w') as f:
f.write("int x;")
ret, stdout, stderr = cppcheck(['--project=' + project_file, '--template=cppcheck1', '-q'])
@@ -102,7 +102,7 @@ def test_project_unspecified_platform(tmpdir):
"""
project_file = __write_cppcheck_project_file(tmpdir, platform='Unspecified')
- with open(os.path.join(tmpdir, '1.c'), 'wt') as f:
+ with open(os.path.join(tmpdir, '1.c'), 'w') as f:
f.write("int x;")
ret, stdout, stderr = cppcheck(['--project=' + project_file, '--template=cppcheck1', '-q'])
@@ -117,7 +117,7 @@ def test_project_unknown_platform(tmpdir):
"""
project_file = __write_cppcheck_project_file(tmpdir, platform='dummy')
- with open(os.path.join(tmpdir, '1.c'), 'wt') as f:
+ with open(os.path.join(tmpdir, '1.c'), 'w') as f:
f.write("int x;")
ret, stdout, stderr = cppcheck(['--project=' + project_file, '--template=cppcheck1'])
@@ -132,7 +132,7 @@ def test_project_empty_fields(tmpdir):
"""
project_file = os.path.join(tmpdir, 'Project.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -229,7 +229,7 @@ def test_project_missing_subproject(tmpdir):
def test_project_std(tmpdir):
- with open(os.path.join(tmpdir, 'bug1.cpp'), 'wt') as f:
+ with open(os.path.join(tmpdir, 'bug1.cpp'), 'w') as f:
f.write("""
#if __cplusplus == 201402L
int x = 123 / 0;
@@ -247,7 +247,7 @@ def test_project_std(tmpdir):
}
]
- with open(compile_commands, 'wt') as f:
+ with open(compile_commands, 'w') as f:
f.write(json.dumps(compilation_db))
ret, stdout, stderr = cppcheck(['--project=' + compile_commands, '--enable=all', '-rp=' + str(tmpdir), '--template=cppcheck1'])
@@ -259,7 +259,7 @@ def test_project_std(tmpdir):
@pytest.mark.skip() # clang-tidy is not available in all cases
def test_clang_tidy(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
int main(int argc)
{
@@ -268,7 +268,7 @@ def test_clang_tidy(tmpdir):
""")
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -280,7 +280,7 @@ def test_clang_tidy(tmpdir):
""".format(test_file))
- args = ['--project={}'.format(project_file)]
+ args = [f'--project={project_file}']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout
@@ -288,18 +288,18 @@ def test_clang_tidy(tmpdir):
# TODO: should detect clang-tidy issue
assert len(lines) == 1
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
assert stderr == ''
def test_project_file_filter(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -308,9 +308,9 @@ def test_project_file_filter(tmpdir):
""".format(test_file))
- args = ['--file-filter=*.cpp', '--project={}'.format(project_file)]
+ args = ['--file-filter=*.cpp', f'--project={project_file}']
out_lines = [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -318,14 +318,14 @@ def test_project_file_filter(tmpdir):
def test_project_file_filter_2(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test.cpp')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test.c')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -335,9 +335,9 @@ def test_project_file_filter_2(tmpdir):
""".format(test_file_1, test_file_2))
- args = ['--file-filter=*.cpp', '--project={}'.format(project_file)]
+ args = ['--file-filter=*.cpp', f'--project={project_file}']
out_lines = [
- 'Checking {} ...'.format(test_file_1)
+ f'Checking {test_file_1} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -345,14 +345,14 @@ def test_project_file_filter_2(tmpdir):
def test_project_file_filter_3(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test.cpp')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test.c')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -362,9 +362,9 @@ def test_project_file_filter_3(tmpdir):
""".format(test_file_1, test_file_2))
- args = ['--file-filter=*.c', '--project={}'.format(project_file)]
+ args = ['--file-filter=*.c', f'--project={project_file}']
out_lines = [
- 'Checking {} ...'.format(test_file_2)
+ f'Checking {test_file_2} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -372,11 +372,11 @@ def test_project_file_filter_3(tmpdir):
def test_project_file_filter_no_match(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -385,7 +385,7 @@ def test_project_file_filter_no_match(tmpdir):
""".format(test_file))
- args = ['--file-filter=*.c', '--project={}'.format(project_file)]
+ args = ['--file-filter=*.c', f'--project={project_file}']
out_lines = [
'cppcheck: error: could not find any files matching the filter.'
]
@@ -395,20 +395,20 @@ def test_project_file_filter_no_match(tmpdir):
def test_project_file_order(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
test_file_b = os.path.join(tmpdir, 'b.c')
- with open(test_file_b, 'wt'):
+ with open(test_file_b, 'w'):
pass
test_file_c = os.path.join(tmpdir, 'c.c')
- with open(test_file_c, 'wt'):
+ with open(test_file_c, 'w'):
pass
test_file_d = os.path.join(tmpdir, 'd.c')
- with open(test_file_d, 'wt'):
+ with open(test_file_d, 'w'):
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -420,19 +420,19 @@ def test_project_file_order(tmpdir):
""".format(test_file_c, test_file_d, test_file_b, test_file_a))
- args = ['--project={}'.format(project_file), '-j1']
+ args = [f'--project={project_file}', '-j1']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_c),
+ f'Checking {test_file_c} ...',
'1/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_d),
+ f'Checking {test_file_d} ...',
'2/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_b),
+ f'Checking {test_file_b} ...',
'3/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_a),
+ f'Checking {test_file_a} ...',
'4/4 files checked 0% done'
]
assert stderr == ''
@@ -440,11 +440,11 @@ def test_project_file_order(tmpdir):
def test_project_file_duplicate(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -455,30 +455,30 @@ def test_project_file_duplicate(tmpdir):
""".format(test_file_a, test_file_a, tmpdir))
- args = ['--project={}'.format(project_file)]
+ args = [f'--project={project_file}']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_a)
+ f'Checking {test_file_a} ...'
]
assert stderr == ''
def test_project_file_duplicate_2(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
test_file_b = os.path.join(tmpdir, 'b.c')
- with open(test_file_b, 'wt'):
+ with open(test_file_b, 'w'):
pass
test_file_c = os.path.join(tmpdir, 'c.c')
- with open(test_file_c, 'wt'):
+ with open(test_file_c, 'w'):
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -494,17 +494,17 @@ def test_project_file_duplicate_2(tmpdir):
""".format(test_file_c, test_file_a, test_file_b, tmpdir, test_file_b, test_file_c, test_file_a, tmpdir))
- args = ['--project={}'.format(project_file), '-j1']
+ args = [f'--project={project_file}', '-j1']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_c),
+ f'Checking {test_file_c} ...',
'1/3 files checked 0% done',
- 'Checking {} ...'.format(test_file_a),
+ f'Checking {test_file_a} ...',
'2/3 files checked 0% done',
- 'Checking {} ...'.format(test_file_b),
+ f'Checking {test_file_b} ...',
'3/3 files checked 0% done'
]
assert stderr == ''
@@ -512,11 +512,11 @@ def test_project_file_duplicate_2(tmpdir):
def test_project_file_ignore(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -525,7 +525,7 @@ def test_project_file_ignore(tmpdir):
""".format(test_file))
- args = ['-itest.cpp', '--project={}'.format(project_file)]
+ args = ['-itest.cpp', f'--project={project_file}']
out_lines = [
'cppcheck: error: could not find or open any of the paths given.',
'cppcheck: Maybe all paths were ignored?'
@@ -536,11 +536,11 @@ def test_project_file_ignore(tmpdir):
def test_project_file_ignore_2(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -552,7 +552,7 @@ def test_project_file_ignore_2(tmpdir):
""".format(test_file))
- args = ['--project={}'.format(project_file)]
+ args = [f'--project={project_file}']
out_lines = [
'cppcheck: error: could not find or open any of the paths given.',
'cppcheck: Maybe all paths were ignored?'
@@ -563,11 +563,11 @@ def test_project_file_ignore_2(tmpdir):
def test_project_file_ignore_3(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
project_file = os.path.join(tmpdir, 'test.cppcheck')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(
"""
@@ -579,7 +579,7 @@ def test_project_file_ignore_3(tmpdir):
""".format(test_file))
- args = ['--project={}'.format(project_file)]
+ args = [f'--project={project_file}']
out_lines = [
'cppcheck: error: could not find or open any of the paths given.',
'cppcheck: Maybe all paths were ignored?'
@@ -591,7 +591,7 @@ def test_project_file_ignore_3(tmpdir):
@pytest.mark.xfail
def test_json_file_ignore(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
compilation_db = [
@@ -602,10 +602,10 @@ def test_json_file_ignore(tmpdir):
]
project_file = os.path.join(tmpdir, 'test.json')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(json.dumps(compilation_db))
- args = ['-itest.cpp', '--project={}'.format(project_file)]
+ args = ['-itest.cpp', f'--project={project_file}']
out_lines = [
'cppcheck: error: no C or C++ source files found.',
'cppcheck: all paths were ignored'
@@ -616,7 +616,7 @@ def test_json_file_ignore(tmpdir):
def test_json_file_ignore_2(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
compilation_db = [
@@ -627,10 +627,10 @@ def test_json_file_ignore_2(tmpdir):
]
project_file = os.path.join(tmpdir, 'test.json')
- with open(project_file, 'wt') as f:
+ with open(project_file, 'w') as f:
f.write(json.dumps(compilation_db))
- args = ['-i{}'.format(test_file), '--project={}'.format(project_file)]
+ args = [f'-i{test_file}', f'--project={project_file}']
out_lines = [
'cppcheck: error: no C or C++ source files found.',
'cppcheck: all paths were ignored'
diff --git a/test/cli/other_test.py b/test/cli/other_test.py
index 99bb3b24f6e..c359f720898 100644
--- a/test/cli/other_test.py
+++ b/test/cli/other_test.py
@@ -1,4 +1,3 @@
-
# python -m pytest test-other.py
import os
@@ -11,7 +10,7 @@
def test_missing_include(tmpdir): # #11283
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
#include "test.h"
""")
@@ -19,18 +18,18 @@ def test_missing_include(tmpdir): # #11283
args = ['--enable=missingInclude', '--template=simple', test_file]
_, _, stderr = cppcheck(args)
- assert stderr == '{}:2:0: information: Include file: "test.h" not found. [missingInclude]\n'.format(test_file)
+ assert stderr == f'{test_file}:2:0: information: Include file: "test.h" not found. [missingInclude]\n'
def __test_missing_include_check_config(tmpdir, use_j):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
#include "test.h"
""")
# TODO: -rp is not working requiring the full path in the assert
- args = '--check-config -rp={} {}'.format(tmpdir, test_file)
+ args = f'--check-config -rp={tmpdir} {test_file}'
if use_j:
args = '-j2 ' + args
@@ -48,7 +47,7 @@ def test_missing_include_check_config_j(tmpdir):
def test_missing_include_inline_suppr(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
// cppcheck-suppress missingInclude
#include "missing.h"
@@ -64,7 +63,7 @@ def test_missing_include_inline_suppr(tmpdir):
def test_preprocessor_error(tmpdir):
test_file = os.path.join(tmpdir, '10866.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('#error test\nx=1;\n')
exitcode, _, stderr = cppcheck(['--error-exitcode=1', test_file])
assert 'preprocessorErrorDirective' in stderr
@@ -80,7 +79,7 @@ def test_preprocessor_error(tmpdir):
@pytest.mark.parametrize("env,color_expected", [({"CLICOLOR_FORCE":"1"}, True), ({"NO_COLOR": "1", "CLICOLOR_FORCE":"1"}, False)])
def test_color_non_tty(tmpdir, env, color_expected):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('#error test\nx=1;\n')
exitcode, _, stderr = cppcheck([test_file], env=env)
@@ -96,7 +95,7 @@ def test_color_non_tty(tmpdir, env, color_expected):
@pytest.mark.parametrize("env,color_expected", [({}, True), ({"NO_COLOR": "1"}, False)])
def test_color_tty(tmpdir, env, color_expected):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('#error test\nx=1;\n')
exitcode, _, stderr = cppcheck([test_file], env=env, tty=True)
@@ -120,20 +119,20 @@ def test_invalid_library(tmpdir):
def test_message_j(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("")
args = ['-j2', test_file]
_, stdout, _ = cppcheck(args)
- assert stdout == "Checking {} ...\n".format(test_file) # we were adding stray \0 characters at the end
+ assert stdout == f"Checking {test_file} ...\n" # we were adding stray \0 characters at the end
# TODO: test missing std.cfg
def test_progress(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
int main(int argc)
{
@@ -147,7 +146,7 @@ def test_progress(tmpdir):
pos = stdout.find('\n')
assert(pos != -1)
pos += 1
- assert stdout[:pos] == "Checking {} ...\n".format(test_file)
+ assert stdout[:pos] == f"Checking {test_file} ...\n"
assert (stdout[pos:] ==
"progress: Tokenize (typedef) 0%\n"
"progress: Tokenize (typedef) 12%\n"
@@ -166,7 +165,7 @@ def test_progress(tmpdir):
def test_progress_j(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
int main(int argc)
{
@@ -177,13 +176,13 @@ def test_progress_j(tmpdir):
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
- assert stdout == "Checking {} ...\n".format(test_file)
+ assert stdout == f"Checking {test_file} ...\n"
assert stderr == ""
def test_execute_addon_failure(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
void f();
""")
@@ -193,12 +192,12 @@ def test_execute_addon_failure(tmpdir):
# provide empty PATH environment variable so python is not found and execution of addon fails
env = {'PATH': ''}
_, _, stderr = cppcheck(args, env)
- assert stderr == '{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to auto detect python [internalError]\n\n^\n'.format(test_file)
+ assert stderr == f'{test_file}:0:0: error: Bailing out from analysis: Checking file failed: Failed to auto detect python [internalError]\n\n^\n'
def test_execute_addon_failure_2(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
void f();
""")
@@ -208,12 +207,12 @@ def test_execute_addon_failure_2(tmpdir):
_, _, stderr = cppcheck(args)
ec = 1 if os.name == 'nt' else 127
- assert stderr == "{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'naming' - exitcode is {} [internalError]\n\n^\n".format(test_file, ec)
+ assert stderr == f"{test_file}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'naming' - exitcode is {ec} [internalError]\n\n^\n"
def test_execute_addon_file0(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('void foo() {}\n')
args = ['--xml', '--addon=misra', '--enable=style', test_file]
@@ -227,7 +226,7 @@ def test_execute_addon_file0(tmpdir):
@pytest.mark.skip
def test_internal_error(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
#include
@@ -241,13 +240,13 @@ def test_internal_error(tmpdir):
args = [test_file]
_, _, stderr = cppcheck(args)
- assert stderr == '{}:0:0: error: Bailing from out analysis: Checking file failed: converting \'1f\' to integer failed - not an integer [internalError]\n\n^\n'.format(test_file)
+ assert stderr == f'{test_file}:0:0: error: Bailing from out analysis: Checking file failed: converting \'1f\' to integer failed - not an integer [internalError]\n\n^\n'
def test_addon_ctu_exitcode(tmpdir):
""" #12440 - Misra ctu violations found => exit code should be non-zero """
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""typedef enum { BLOCK = 0x80U, } E;""")
args = ['--addon=misra', '--enable=style', '--error-exitcode=1', test_file]
exitcode, stdout, stderr = cppcheck(args)
@@ -258,7 +257,7 @@ def test_addon_ctu_exitcode(tmpdir):
# TODO: test with -j2
def test_addon_misra(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
@@ -269,15 +268,15 @@ def test_addon_misra(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:2:1: style: misra violation (use --rule-texts= to get proper output) [misra-c2012-2.3]\ntypedef int MISRA_5_6_VIOLATION;\n^\n'.format(test_file)
+ assert stderr == f'{test_file}:2:1: style: misra violation (use --rule-texts= to get proper output) [misra-c2012-2.3]\ntypedef int MISRA_5_6_VIOLATION;\n^\n'
def test_addon_y2038(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
# TODO: trigger warning
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
extern void f()
{
@@ -292,14 +291,14 @@ def test_addon_y2038(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:4:21: warning: time is Y2038-unsafe [y2038-unsafe-call]\n'.format(test_file)
+ assert stderr == f'{test_file}:4:21: warning: time is Y2038-unsafe [y2038-unsafe-call]\n'
def test_addon_threadsafety(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
extern const char* f()
{
@@ -313,15 +312,15 @@ def test_addon_threadsafety(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:4:12: warning: strerror is MT-unsafe [threadsafety-unsafe-call]\n'.format(test_file)
+ assert stderr == f'{test_file}:4:12: warning: strerror is MT-unsafe [threadsafety-unsafe-call]\n'
def test_addon_naming(tmpdir):
# the addon does nothing without a config
addon_file = os.path.join(tmpdir, 'naming1.json')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
{
"script": "addons/naming.py",
@@ -332,26 +331,26 @@ def test_addon_naming(tmpdir):
""")
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
int Var;
""")
- args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
+ args = [f'--addon={addon_file}', '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:2:1: style: Variable Var violates naming convention [naming-varname]\n'.format(test_file)
+ assert stderr == f'{test_file}:2:1: style: Variable Var violates naming convention [naming-varname]\n'
def test_addon_namingng(tmpdir):
addon_file = os.path.join(tmpdir, 'namingng.json')
addon_config_file = os.path.join(tmpdir, 'namingng.config.json')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
{
"script": "addons/namingng.py",
@@ -361,7 +360,7 @@ def test_addon_namingng(tmpdir):
}
"""%(addon_config_file).replace('\\','\\\\'))
- with open(addon_config_file, 'wt') as f:
+ with open(addon_config_file, 'w') as f:
f.write("""
{
"RE_FILE": [
@@ -395,14 +394,14 @@ def test_addon_namingng(tmpdir):
test_unguarded_include_file_basename = 'test_unguarded.h'
test_unguarded_include_file = os.path.join(tmpdir, test_unguarded_include_file_basename)
- with open(test_unguarded_include_file, 'wt') as f:
+ with open(test_unguarded_include_file, 'w') as f:
f.write("""
void InvalidFunctionUnguarded();
""")
test_include_file_basename = '_test.h'
test_include_file = os.path.join(tmpdir, test_include_file_basename)
- with open(test_include_file, 'wt') as f:
+ with open(test_include_file, 'w') as f:
f.write("""
#ifndef TEST_H
#define TEST_H
@@ -417,7 +416,7 @@ def test_addon_namingng(tmpdir):
test_file_basename = 'test_.cpp'
test_file = os.path.join(tmpdir, test_file_basename)
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
#include "%s"
@@ -454,7 +453,7 @@ class _clz {
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Defines:',
'Undefines:',
'Includes:',
@@ -462,65 +461,65 @@ class _clz {
]
lines = [line for line in stderr.splitlines() if line != '']
expect = [
- '{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_include_file,test_include_file_basename),
+ f'{test_include_file}:0:0: style: File name {test_include_file_basename} violates naming convention [namingng-namingConvention]',
'^',
- '{}:2:9: style: include guard naming violation; TEST_H != _TEST_H [namingng-includeGuardName]'.format(test_include_file),
+ f'{test_include_file}:2:9: style: include guard naming violation; TEST_H != _TEST_H [namingng-includeGuardName]',
'#ifndef TEST_H',
' ^',
- '{}:5:6: style: Function InvalidFunction violates naming convention [namingng-namingConvention]'.format(test_include_file),
+ f'{test_include_file}:5:6: style: Function InvalidFunction violates naming convention [namingng-namingConvention]',
'void InvalidFunction();',
' ^',
- '{}:6:12: style: Global variable _invalid_extern_global violates naming convention [namingng-namingConvention]'.format(test_include_file),
+ f'{test_include_file}:6:12: style: Global variable _invalid_extern_global violates naming convention [namingng-namingConvention]',
'extern int _invalid_extern_global;',
' ^',
- '{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file,test_unguarded_include_file_basename),
+ f'{test_unguarded_include_file}:0:0: style: File name {test_unguarded_include_file_basename} violates naming convention [namingng-namingConvention]',
'^',
- '{}:0:0: style: Missing include guard [namingng-includeGuardMissing]'.format(test_unguarded_include_file),
+ f'{test_unguarded_include_file}:0:0: style: Missing include guard [namingng-includeGuardMissing]',
'^',
- '{}:2:6: style: Function InvalidFunctionUnguarded violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file),
+ f'{test_unguarded_include_file}:2:6: style: Function InvalidFunctionUnguarded violates naming convention [namingng-namingConvention]',
'void InvalidFunctionUnguarded();',
' ^',
- '{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_file,test_file_basename),
+ f'{test_file}:0:0: style: File name {test_file_basename} violates naming convention [namingng-namingConvention]',
'^',
- '{}:7:26: style: Variable _invalid_arg violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:7:26: style: Variable _invalid_arg violates naming convention [namingng-namingConvention]',
'void valid_function2(int _invalid_arg);',
' ^',
- '{}:8:26: style: Variable invalid_arg_ violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:8:26: style: Variable invalid_arg_ violates naming convention [namingng-namingConvention]',
'void valid_function3(int invalid_arg_);',
' ^',
- '{}:10:31: style: Variable invalid_arg32 violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:10:31: style: Variable invalid_arg32 violates naming convention [namingng-namingConvention]',
'void valid_function5(uint32_t invalid_arg32);',
' ^',
- '{}:4:6: style: Function invalid_function_ violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:4:6: style: Function invalid_function_ violates naming convention [namingng-namingConvention]',
'void invalid_function_();',
' ^',
- '{}:5:6: style: Function _invalid_function violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:5:6: style: Function _invalid_function violates naming convention [namingng-namingConvention]',
'void _invalid_function();',
' ^',
- '{}:12:10: style: Function invalid_function7 violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:12:10: style: Function invalid_function7 violates naming convention [namingng-namingConvention]',
'uint16_t invalid_function7(int valid_arg);',
' ^',
- '{}:15:5: style: Global variable _invalid_global violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:15:5: style: Global variable _invalid_global violates naming convention [namingng-namingConvention]',
'int _invalid_global;',
' ^',
- '{}:16:12: style: Global variable _invalid_static_global violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:16:12: style: Global variable _invalid_static_global violates naming convention [namingng-namingConvention]',
'static int _invalid_static_global;',
' ^',
- '{}:20:5: style: Class Constructor _clz violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:20:5: style: Class Constructor _clz violates naming convention [namingng-namingConvention]',
' _clz() : _invalid_public(0), _invalid_private(0), priv_good(0), priv_bad_tmp(0) { }',
' ^',
- '{}:21:9: style: Public member variable _invalid_public violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:21:9: style: Public member variable _invalid_public violates naming convention [namingng-namingConvention]',
' int _invalid_public;',
' ^',
- '{}:23:10: style: Private member variable _invalid_private violates naming convention: required prefix priv_ missing [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:23:10: style: Private member variable _invalid_private violates naming convention: required prefix priv_ missing [namingng-namingConvention]',
' char _invalid_private;',
' ^',
- '{}:25:9: style: Private member variable priv_bad_tmp violates naming convention: illegal suffix _tmp [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:25:9: style: Private member variable priv_bad_tmp violates naming convention: illegal suffix _tmp [namingng-namingConvention]',
' int priv_bad_tmp;',
' ^',
- '{}:28:11: style: Namespace _invalid_namespace violates naming convention [namingng-namingConvention]'.format(test_file),
+ f'{test_file}:28:11: style: Namespace _invalid_namespace violates naming convention [namingng-namingConvention]',
'namespace _invalid_namespace { }',
' ^',
]
@@ -534,7 +533,7 @@ class _clz {
def test_addon_namingng_config(tmpdir):
addon_file = os.path.join(tmpdir, 'namingng.json')
addon_config_file = os.path.join(tmpdir, 'namingng.config.json')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
{
"script": "addons/namingng.py",
@@ -544,7 +543,7 @@ def test_addon_namingng_config(tmpdir):
}
"""%(addon_config_file).replace('\\','\\\\'))
- with open(addon_config_file, 'wt') as f:
+ with open(addon_config_file, 'w') as f:
f.write("""
{
"RE_FILE": "[^/]*[a-z][a-z0-9_]*[a-z0-9]\\.c\\Z",
@@ -587,7 +586,7 @@ def test_addon_namingng_config(tmpdir):
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Defines:',
'Undefines:',
'Includes:',
@@ -621,7 +620,7 @@ def test_addon_namingng_config(tmpdir):
def test_addon_findcasts(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
extern void f(char c)
{
@@ -636,14 +635,14 @@ def test_addon_findcasts(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:4:21: information: found a cast [findcasts-cast]\n'.format(test_file)
+ assert stderr == f'{test_file}:4:21: information: found a cast [findcasts-cast]\n'
def test_addon_misc(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
extern void f()
{
@@ -657,77 +656,77 @@ def test_addon_misc(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == '{}:4:26: style: String concatenation in array initialization, missing comma? [misc-stringConcatInArrayInit]\n'.format(test_file)
+ assert stderr == f'{test_file}:4:26: style: String concatenation in array initialization, missing comma? [misc-stringConcatInArrayInit]\n'
def test_invalid_addon_json(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.json')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
""")
test_file = os.path.join(tmpdir, 'file.cpp')
- with open(test_file, 'wt'):
+ with open(test_file, 'w'):
pass
- args = ['--addon={}'.format(addon_file), test_file]
+ args = [f'--addon={addon_file}', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 1
lines = stdout.splitlines()
assert lines == [
- 'Loading {} failed. syntax error at line 2 near: '.format(addon_file)
+ f'Loading {addon_file} failed. syntax error at line 2 near: '
]
assert stderr == ''
def test_invalid_addon_py(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
raise Exception()
""")
test_file = os.path.join(tmpdir, 'file.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
- args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', test_file]
+ args = [f'--addon={addon_file}', '--enable=all', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
- assert stderr == "{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1 [internalError]\n\n^\n".format(test_file)
+ assert stderr == f"{test_file}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1 [internalError]\n\n^\n"
# TODO: test with -j2
def test_invalid_addon_py_verbose(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
raise Exception()
""")
test_file = os.path.join(tmpdir, 'file.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
- args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', '--verbose', '-j1', test_file]
+ args = [f'--addon={addon_file}', '--enable=all', '--disable=unusedFunction', '--verbose', '-j1', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Defines:',
'Undefines:',
'Includes:',
@@ -747,14 +746,14 @@ def test_invalid_addon_py_verbose(tmpdir):
Exceptio [internalError]
"""
# /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/file.cpp:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 256.: python3 /home/user/CLionProjects/cppcheck/addons/runaddon.py /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/addon1.py --cli /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/file.cpp.24637.dump
- assert stderr.startswith("{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1: ".format(test_file))
+ assert stderr.startswith(f"{test_file}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1: ")
assert stderr.count('Output:\nTraceback')
assert stderr.endswith('raise Exception()\nException [internalError]\n\n^\n')
def test_addon_result(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write("""
print("Checking ...")
print("")
@@ -763,18 +762,18 @@ def test_addon_result(tmpdir):
""")
test_file = os.path.join(tmpdir, 'file.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
- args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', test_file]
+ args = [f'--addon={addon_file}', '--enable=all', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
assert stderr == 'test.cpp:1:1: style: msg [addon1-id]\n\n^\n'
@@ -783,13 +782,13 @@ def test_addon_result(tmpdir):
# #11483
def test_unused_function_include(tmpdir):
test_cpp_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_cpp_file, 'wt') as f:
+ with open(test_cpp_file, 'w') as f:
f.write("""
#include "test.h"
""")
test_h_file = os.path.join(tmpdir, 'test.h')
- with open(test_h_file, 'wt') as f:
+ with open(test_h_file, 'w') as f:
f.write("""
class A {
public:
@@ -802,13 +801,13 @@ class A {
args = ['--enable=unusedFunction', '--inline-suppr', '--template=simple', '-j1', test_cpp_file]
_, _, stderr = cppcheck(args)
- assert stderr == "{}:4:0: style: The function 'f' is never used. [unusedFunction]\n".format(test_h_file)
+ assert stderr == f"{test_h_file}:4:0: style: The function 'f' is never used. [unusedFunction]\n"
# TODO: test with all other types
def test_showtime_top5_file(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write("""
int main(int argc)
{
@@ -849,12 +848,12 @@ def test_missing_addon(tmpdir):
def test_file_filter(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
pass
args = ['--file-filter=*.cpp', test_file]
out_lines = [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -862,15 +861,15 @@ def test_file_filter(tmpdir):
def test_file_filter_2(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test.cpp')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test.c')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
args = ['--file-filter=*.cpp', test_file_1, test_file_2]
out_lines = [
- 'Checking {} ...'.format(test_file_1)
+ f'Checking {test_file_1} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -878,15 +877,15 @@ def test_file_filter_2(tmpdir):
def test_file_filter_3(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test.cpp')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test.c')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
args = ['--file-filter=*.c', test_file_1, test_file_2]
out_lines = [
- 'Checking {} ...'.format(test_file_2)
+ f'Checking {test_file_2} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -894,7 +893,7 @@ def test_file_filter_3(tmpdir):
def test_file_filter_no_match(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt'):
+ with open(test_file, 'w'):
pass
args = ['--file-filter=*.c', test_file]
@@ -907,16 +906,16 @@ def test_file_filter_no_match(tmpdir):
def test_file_order(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
test_file_b = os.path.join(tmpdir, 'b.c')
- with open(test_file_b, 'wt'):
+ with open(test_file_b, 'w'):
pass
test_file_c = os.path.join(tmpdir, 'c.c')
- with open(test_file_c, 'wt'):
+ with open(test_file_c, 'w'):
pass
test_file_d = os.path.join(tmpdir, 'd.c')
- with open(test_file_d, 'wt'):
+ with open(test_file_d, 'w'):
pass
args = [test_file_c, test_file_d, test_file_b, test_file_a, '-j1']
@@ -925,13 +924,13 @@ def test_file_order(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_c),
+ f'Checking {test_file_c} ...',
'1/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_d),
+ f'Checking {test_file_d} ...',
'2/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_b),
+ f'Checking {test_file_b} ...',
'3/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_a),
+ f'Checking {test_file_a} ...',
'4/4 files checked 0% done'
]
assert stderr == ''
@@ -939,27 +938,27 @@ def test_file_order(tmpdir):
def test_markup(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test_1.qml')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test_2.cpp')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
test_file_3 = os.path.join(tmpdir, 'test_3.qml')
- with open(test_file_3, 'wt') as f:
+ with open(test_file_3, 'w') as f:
pass
test_file_4 = os.path.join(tmpdir, 'test_4.cpp')
- with open(test_file_4, 'wt') as f:
+ with open(test_file_4, 'w') as f:
pass
args = ['--library=qt', test_file_1, test_file_2, test_file_3, test_file_4, '-j1']
out_lines = [
- 'Checking {} ...'.format(test_file_2),
+ f'Checking {test_file_2} ...',
'1/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_4),
+ f'Checking {test_file_4} ...',
'2/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_1),
+ f'Checking {test_file_1} ...',
'3/4 files checked 0% done',
- 'Checking {} ...'.format(test_file_3),
+ f'Checking {test_file_3} ...',
'4/4 files checked 0% done'
]
@@ -968,16 +967,16 @@ def test_markup(tmpdir):
def test_markup_j(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test_1.qml')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test_2.cpp')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
test_file_3 = os.path.join(tmpdir, 'test_3.qml')
- with open(test_file_3, 'wt') as f:
+ with open(test_file_3, 'w') as f:
pass
test_file_4 = os.path.join(tmpdir, 'test_4.cpp')
- with open(test_file_4, 'wt') as f:
+ with open(test_file_4, 'w') as f:
pass
args = ['--library=qt', '-j2', test_file_1, test_file_2, test_file_3, test_file_4]
@@ -986,7 +985,7 @@ def test_markup_j(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
for i in range(1, 5):
- lines.remove('{}/4 files checked 0% done'.format(i))
+ lines.remove(f'{i}/4 files checked 0% done')
# this test started to fail in the -j2 injection run when using ThreadExecutor although it always specifies -j2.
# the order of the files in the output changed so just check for the file extentions
@@ -1007,7 +1006,7 @@ def test_markup_j(tmpdir):
def test_valueflow_debug(tmpdir):
test_file_cpp = os.path.join(tmpdir, 'test_1.cpp')
- with open(test_file_cpp, 'wt') as f:
+ with open(test_file_cpp, 'w') as f:
f.write("""
#include "test.h"
@@ -1018,7 +1017,7 @@ def test_valueflow_debug(tmpdir):
"""
)
test_file_h = os.path.join(tmpdir, 'test.h')
- with open(test_file_h, 'wt') as f:
+ with open(test_file_h, 'w') as f:
f.write("""
#include "test2.h"
inline void f1()
@@ -1029,7 +1028,7 @@ def test_valueflow_debug(tmpdir):
)
pass
test_file_h_2 = os.path.join(tmpdir, 'test2.h')
- with open(test_file_h_2, 'wt') as f:
+ with open(test_file_h_2, 'w') as f:
f.write("""
inline void f2()
{
@@ -1093,7 +1092,7 @@ def test_valueflow_debug(tmpdir):
def test_file_duplicate(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
args = [test_file_a, test_file_a, str(tmpdir)]
@@ -1102,20 +1101,20 @@ def test_file_duplicate(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_a)
+ f'Checking {test_file_a} ...'
]
assert stderr == ''
def test_file_duplicate_2(tmpdir):
test_file_a = os.path.join(tmpdir, 'a.c')
- with open(test_file_a, 'wt'):
+ with open(test_file_a, 'w'):
pass
test_file_b = os.path.join(tmpdir, 'b.c')
- with open(test_file_b, 'wt'):
+ with open(test_file_b, 'w'):
pass
test_file_c = os.path.join(tmpdir, 'c.c')
- with open(test_file_c, 'wt'):
+ with open(test_file_c, 'w'):
pass
args = [test_file_c, test_file_a, test_file_b, str(tmpdir), test_file_b, test_file_c, test_file_a, str(tmpdir), '-j1']
@@ -1124,11 +1123,11 @@ def test_file_duplicate_2(tmpdir):
assert exitcode == 0
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file_c),
+ f'Checking {test_file_c} ...',
'1/3 files checked 0% done',
- 'Checking {} ...'.format(test_file_a),
+ f'Checking {test_file_a} ...',
'2/3 files checked 0% done',
- 'Checking {} ...'.format(test_file_b),
+ f'Checking {test_file_b} ...',
'3/3 files checked 0% done'
]
assert stderr == ''
@@ -1136,7 +1135,7 @@ def test_file_duplicate_2(tmpdir):
def test_file_ignore(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt'):
+ with open(test_file, 'w'):
pass
args = ['-itest.cpp', test_file]
@@ -1153,12 +1152,12 @@ def test_build_dir_j_memleak(tmpdir): #12111
os.mkdir(build_dir)
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('int main() {}')
- args = ['--cppcheck-build-dir={}'.format(build_dir), '-j2', test_file]
+ args = [f'--cppcheck-build-dir={build_dir}', '-j2', test_file]
out_lines = [
- 'Checking {} ...'.format(test_file)
+ f'Checking {test_file} ...'
]
assert_cppcheck(args, ec_exp=0, err_exp=[], out_exp=out_lines)
@@ -1166,21 +1165,21 @@ def test_build_dir_j_memleak(tmpdir): #12111
def __test_addon_json_invalid(tmpdir, addon_json, expected):
addon_file = os.path.join(tmpdir, 'invalid.json')
- with open(addon_file, 'wt') as f:
+ with open(addon_file, 'w') as f:
f.write(addon_json)
test_file = os.path.join(tmpdir, 'file.cpp')
- with open(test_file, 'wt'):
+ with open(test_file, 'w'):
pass
- args = ['--addon={}'.format(addon_file), test_file]
+ args = [f'--addon={addon_file}', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 1
lines = stdout.splitlines()
assert len(lines) == 1
assert lines == [
- 'Loading {} failed. {}'.format(addon_file, expected)
+ f'Loading {addon_file} failed. {expected}'
]
assert stderr == ''
@@ -1219,7 +1218,7 @@ def test_addon_json_invalid_script_2(tmpdir):
def test_unknown_extension(tmpdir):
test_file = os.path.join(tmpdir, 'test_2')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
void f() { }
''')
@@ -1232,7 +1231,7 @@ def test_unknown_extension(tmpdir):
def test_rule_file_define_multiple(tmpdir):
rule_file = os.path.join(tmpdir, 'rule_file.xml')
- with open(rule_file, 'wt') as f:
+ with open(rule_file, 'w') as f:
f.write("""
@@ -1255,32 +1254,32 @@ def test_rule_file_define_multiple(tmpdir):
""")
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
#define DEF_1
#define DEF_2
void f() { }
''')
- exitcode, stdout, stderr = cppcheck(['--template=simple', '--rule-file={}'.format(rule_file), '-DDEF_3', test_file])
+ exitcode, stdout, stderr = cppcheck(['--template=simple', f'--rule-file={rule_file}', '-DDEF_3', test_file])
assert exitcode == 0, stderr
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Processing rule: DEF_1',
'Processing rule: DEF_2',
- 'Checking {}: DEF_3=1...'.format(test_file)
+ f'Checking {test_file}: DEF_3=1...'
]
lines = stderr.splitlines()
assert lines == [
- "{}:2:0: error: found 'DEF_1' [ruleId1]".format(test_file),
- "{}:3:0: error: define2 [ruleId2]".format(test_file)
+ f"{test_file}:2:0: error: found 'DEF_1' [ruleId1]",
+ f"{test_file}:3:0: error: define2 [ruleId2]"
]
def test_rule_file_define(tmpdir):
rule_file = os.path.join(tmpdir, 'rule_file.xml')
- with open(rule_file, 'wt') as f:
+ with open(rule_file, 'w') as f:
f.write("""
define
@@ -1289,31 +1288,31 @@ def test_rule_file_define(tmpdir):
""")
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
#define DEF_1
#define DEF_2
void f() { }
''')
- exitcode, stdout, stderr = cppcheck(['--template=simple', '--rule-file={}'.format(rule_file), '-DDEF_3', test_file])
+ exitcode, stdout, stderr = cppcheck(['--template=simple', f'--rule-file={rule_file}', '-DDEF_3', test_file])
assert exitcode == 0, stdout
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Processing rule: DEF_.',
- 'Checking {}: DEF_3=1...'.format(test_file)
+ f'Checking {test_file}: DEF_3=1...'
]
lines = stderr.splitlines()
assert lines == [
- "{}:2:0: style: found 'DEF_1' [rule]".format(test_file),
- "{}:3:0: style: found 'DEF_2' [rule]".format(test_file)
+ f"{test_file}:2:0: style: found 'DEF_1' [rule]",
+ f"{test_file}:3:0: style: found 'DEF_2' [rule]"
]
def test_rule_file_normal(tmpdir):
rule_file = os.path.join(tmpdir, 'rule_file.xml')
- with open(rule_file, 'wt') as f:
+ with open(rule_file, 'w') as f:
f.write("""
int
@@ -1321,7 +1320,7 @@ def test_rule_file_normal(tmpdir):
""")
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
#define DEF_1
#define DEF_2
@@ -1329,22 +1328,22 @@ def test_rule_file_normal(tmpdir):
void f(i32) { }
''')
- exitcode, stdout, stderr = cppcheck(['--template=simple', '--rule-file={}'.format(rule_file), test_file])
+ exitcode, stdout, stderr = cppcheck(['--template=simple', f'--rule-file={rule_file}', test_file])
assert exitcode == 0, stdout
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Processing rule: int',
]
lines = stderr.splitlines()
assert lines == [
- "{}:5:0: style: found 'int' [rule]".format(test_file)
+ f"{test_file}:5:0: style: found 'int' [rule]"
]
def test_rule_file_raw(tmpdir):
rule_file = os.path.join(tmpdir, 'rule_file.xml')
- with open(rule_file, 'wt') as f:
+ with open(rule_file, 'w') as f:
f.write("""
raw
@@ -1353,7 +1352,7 @@ def test_rule_file_raw(tmpdir):
""")
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
#define DEF_1
#define DEF_2
@@ -1361,23 +1360,23 @@ def test_rule_file_raw(tmpdir):
void f(i32) { }
''')
- exitcode, stdout, stderr = cppcheck(['--template=simple', '--rule-file={}'.format(rule_file), test_file])
+ exitcode, stdout, stderr = cppcheck(['--template=simple', f'--rule-file={rule_file}', test_file])
assert exitcode == 0, stdout
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Processing rule: i32',
]
lines = stderr.splitlines()
assert lines == [
- "{}:4:0: style: found 'i32' [rule]".format(test_file),
- "{}:5:0: style: found 'i32' [rule]".format(test_file)
+ f"{test_file}:4:0: style: found 'i32' [rule]",
+ f"{test_file}:5:0: style: found 'i32' [rule]"
]
def test_rule(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('''
#define DEF_1
#define DEF_2
@@ -1388,12 +1387,12 @@ def test_rule(tmpdir):
assert exitcode == 0, stdout
lines = stdout.splitlines()
assert lines == [
- 'Checking {} ...'.format(test_file),
+ f'Checking {test_file} ...',
'Processing rule: f',
]
lines = stderr.splitlines()
assert lines == [
- "{}:4:0: style: found 'f' [rule]".format(test_file)
+ f"{test_file}:4:0: style: found 'f' [rule]"
]
@@ -1401,44 +1400,44 @@ def test_filelist(tmpdir):
list_dir = os.path.join(tmpdir, 'list-dir')
os.mkdir(list_dir)
- with open(os.path.join(list_dir, 'aaa.c'), 'wt'):
+ with open(os.path.join(list_dir, 'aaa.c'), 'w'):
pass
- with open(os.path.join(list_dir, 'zzz.c'), 'wt'):
+ with open(os.path.join(list_dir, 'zzz.c'), 'w'):
pass
- with open(os.path.join(list_dir, 'valueflow.cpp'), 'wt'):
+ with open(os.path.join(list_dir, 'valueflow.cpp'), 'w'):
pass
- with open(os.path.join(list_dir, 'vfvalue.cpp'), 'wt'):
+ with open(os.path.join(list_dir, 'vfvalue.cpp'), 'w'):
pass
- with open(os.path.join(list_dir, 'vf_enumvalue.cpp'), 'wt'):
+ with open(os.path.join(list_dir, 'vf_enumvalue.cpp'), 'w'):
pass
- with open(os.path.join(list_dir, 'vf_analyze.h'), 'wt'):
+ with open(os.path.join(list_dir, 'vf_analyze.h'), 'w'):
pass
sub_dir_1 = os.path.join(list_dir, 'valueflow')
os.mkdir(sub_dir_1)
- with open(os.path.join(sub_dir_1, 'file.cpp'), 'wt'):
+ with open(os.path.join(sub_dir_1, 'file.cpp'), 'w'):
pass
- with open(os.path.join(sub_dir_1, 'file.c'), 'wt'):
+ with open(os.path.join(sub_dir_1, 'file.c'), 'w'):
pass
- with open(os.path.join(sub_dir_1, 'file.h'), 'wt'):
+ with open(os.path.join(sub_dir_1, 'file.h'), 'w'):
pass
sub_dir_2 = os.path.join(list_dir, 'vfvalue')
os.mkdir(sub_dir_2)
- with open(os.path.join(sub_dir_2, 'file.cpp'), 'wt'):
+ with open(os.path.join(sub_dir_2, 'file.cpp'), 'w'):
pass
- with open(os.path.join(sub_dir_2, 'file.c'), 'wt'):
+ with open(os.path.join(sub_dir_2, 'file.c'), 'w'):
pass
- with open(os.path.join(sub_dir_2, 'file.h'), 'wt'):
+ with open(os.path.join(sub_dir_2, 'file.h'), 'w'):
pass
sub_dir_3 = os.path.join(list_dir, 'vf_enumvalue')
os.mkdir(sub_dir_3)
- with open(os.path.join(sub_dir_3, 'file.cpp'), 'wt'):
+ with open(os.path.join(sub_dir_3, 'file.cpp'), 'w'):
pass
- with open(os.path.join(sub_dir_3, 'file.c'), 'wt'):
+ with open(os.path.join(sub_dir_3, 'file.c'), 'w'):
pass
- with open(os.path.join(sub_dir_3, 'file.h'), 'wt'):
+ with open(os.path.join(sub_dir_3, 'file.h'), 'w'):
pass
# TODO: -rp is not applied to "Checking" messages
@@ -1463,16 +1462,16 @@ def test_filelist(tmpdir):
]
assert len(expected), len(lines)
for i in range(1, len(expected)+1):
- lines.remove('{}/11 files checked 0% done'.format(i, len(expected)))
+ lines.remove(f'{i}/11 files checked 0% done')
assert lines == expected
def test_markup_lang(tmpdir):
test_file_1 = os.path.join(tmpdir, 'test_1.qml')
- with open(test_file_1, 'wt') as f:
+ with open(test_file_1, 'w') as f:
pass
test_file_2 = os.path.join(tmpdir, 'test_2.cpp')
- with open(test_file_2, 'wt') as f:
+ with open(test_file_2, 'w') as f:
pass
# do not assert processing markup file with enforced language
@@ -1491,7 +1490,7 @@ def test_markup_lang(tmpdir):
def test_cpp_probe(tmpdir):
test_file = os.path.join(tmpdir, 'test.h')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.writelines([
'class A {};'
])
@@ -1499,7 +1498,7 @@ def test_cpp_probe(tmpdir):
args = ['-q', '--template=simple', '--cpp-header-probe', '--verbose', test_file]
err_lines = [
# TODO: fix that awkward format
- "{}:1:1: error: Code 'classA{{' is invalid C code.: Use --std, -x or --language to enforce C++. Or --cpp-header-probe to identify C++ headers via the Emacs marker. [syntaxError]".format(test_file)
+ f"{test_file}:1:1: error: Code 'classA{{' is invalid C code.: Use --std, -x or --language to enforce C++. Or --cpp-header-probe to identify C++ headers via the Emacs marker. [syntaxError]"
]
assert_cppcheck(args, ec_exp=0, err_exp=err_lines, out_exp=[])
@@ -1507,7 +1506,7 @@ def test_cpp_probe(tmpdir):
def test_cpp_probe_2(tmpdir):
test_file = os.path.join(tmpdir, 'test.h')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.writelines([
'// -*- C++ -*-',
'class A {};'
diff --git a/test/cli/performance_test.py b/test/cli/performance_test.py
index 7311f036261..85e019c13d1 100644
--- a/test/cli/performance_test.py
+++ b/test/cli/performance_test.py
@@ -1,11 +1,9 @@
-
# python -m pytest test-other.py
import os
-import sys
import pytest
-from testutils import cppcheck, assert_cppcheck
+from testutils import cppcheck
@@ -14,7 +12,7 @@ def test_slow_array_many_floats(tmpdir):
# 11649
# cppcheck valueflow takes a long time when an array has many floats
filename = os.path.join(tmpdir, 'hang.c')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write("const float f[] = {\n")
for i in range(20000):
f.write(' 13.6f,\n')
@@ -27,7 +25,7 @@ def test_slow_array_many_strings(tmpdir):
# 11901
# cppcheck valueflow takes a long time when analyzing a file with many strings
filename = os.path.join(tmpdir, 'hang.c')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write("const char *strings[] = {\n")
for i in range(20000):
f.write(' "abc",\n')
@@ -39,7 +37,7 @@ def test_slow_array_many_strings(tmpdir):
def test_slow_long_line(tmpdir):
# simplecpp #314
filename = os.path.join(tmpdir, 'hang.c')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write("#define A() static const int a[] = {\\\n")
for i in range(5000):
f.write(" -123, 456, -789,\\\n")
@@ -51,7 +49,7 @@ def test_slow_long_line(tmpdir):
def test_slow_large_constant_expression(tmpdir):
# 12182
filename = os.path.join(tmpdir, 'hang.c')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write("""
#define FLAG1 0
#define FLAG2 0
@@ -121,7 +119,7 @@ def test_slow_large_constant_expression(tmpdir):
def test_slow_exprid(tmpdir):
# 11885
filename = os.path.join(tmpdir, 'hang.c')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write("""
int foo(int a, int b)
{
@@ -150,7 +148,7 @@ def test_slow_exprid(tmpdir):
def test_slow_initlist_varchanged(tmpdir):
# #12235
filename = os.path.join(tmpdir, 'hang.cpp')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write(r"""
struct T {
int* q;
@@ -191,7 +189,7 @@ def test_slow_initlist_varchanged(tmpdir):
def test_slow_many_scopes(tmpdir):
# #12038
filename = os.path.join(tmpdir, 'hang.cpp')
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write(r"""
#define BLOCK {\
char buf[sizeof("x") + 5 * 3 + 16];\
diff --git a/test/cli/premium_test.py b/test/cli/premium_test.py
index 82d8bc03ef5..e54f2de8320 100644
--- a/test/cli/premium_test.py
+++ b/test/cli/premium_test.py
@@ -1,14 +1,11 @@
-
# python -m pytest premium_test.py
-import logging
import os
import shutil
import sys
import time
-import pytest
-from testutils import cppcheck, assert_cppcheck, __lookup_cppcheck_exe
+from testutils import cppcheck, __lookup_cppcheck_exe
PRODUCT_NAME = 'Cppcheck Premium ' + str(time.time())
@@ -18,11 +15,11 @@ def copy_cppcheck_premium(tmpdir):
# add minimum cfg/std.cfg
test_cfg_folder = tmpdir.mkdir('cfg')
- with open(test_cfg_folder.join('std.cfg'), 'wt') as f:
+ with open(test_cfg_folder.join('std.cfg'), 'w') as f:
f.write('\n')
# add simple cppcheck.cfg
- with open(tmpdir.join('cppcheck.cfg'), 'wt') as f:
+ with open(tmpdir.join('cppcheck.cfg'), 'w') as f:
f.write("""
{
"addons": [],
@@ -41,7 +38,7 @@ def test_misra_c_builtin_style_checks(tmpdir):
return
test_file = os.path.join(tmpdir, 'test.cpp')
- with open(test_file, 'wt') as f:
+ with open(test_file, 'w') as f:
f.write('void foo() { int x; y = 0; }')
exe = copy_cppcheck_premium(tmpdir)
diff --git a/test/cli/proj2_test.py b/test/cli/proj2_test.py
index 868d832ddf0..8e7e9673c63 100644
--- a/test/cli/proj2_test.py
+++ b/test/cli/proj2_test.py
@@ -1,4 +1,3 @@
-
# python -m pytest test-proj2.py
import json
@@ -20,7 +19,7 @@ def realpath(s):
def create_compile_commands():
j = [{'directory': realpath('proj2/a'), 'command': 'gcc -c a.c', 'file': 'a.c'},
{'directory': realpath('proj2'), 'command': 'gcc -c b/b.c', 'file': 'b/b.c'}]
- with open('proj2/' + COMPILE_COMMANDS_JSON, 'wt') as f:
+ with open('proj2/' + COMPILE_COMMANDS_JSON, 'w') as f:
f.write(json.dumps(j))
# Run Cppcheck from project path
diff --git a/test/cli/project_test.py b/test/cli/project_test.py
index 8ac243007ba..cb9a28eddd4 100644
--- a/test/cli/project_test.py
+++ b/test/cli/project_test.py
@@ -9,16 +9,16 @@
@pytest.mark.parametrize("project_ext", ["json", "sln", "vcxproj", "bpr", "cppcheck"])
def test_missing_project(project_ext):
- project_file = "file.{}".format(project_ext)
+ project_file = f"file.{project_ext}"
ret, stdout, stderr = cppcheck(['--project=' + project_file, '--template=cppcheck1'])
assert 1 == ret
- assert "cppcheck: error: failed to open project '{}'. The file does not exist.\n".format(project_file) == stdout
+ assert f"cppcheck: error: failed to open project '{project_file}'. The file does not exist.\n" == stdout
assert "" == stderr
def _test_project_error(tmpdir, ext, content, expected):
- project_file = os.path.join(tmpdir, "file.{}".format(ext))
+ project_file = os.path.join(tmpdir, f"file.{ext}")
with open(project_file, 'w') as f:
if content is not None:
@@ -26,7 +26,7 @@ def _test_project_error(tmpdir, ext, content, expected):
ret, stdout, stderr = cppcheck(['--project=' + str(project_file)])
assert 1 == ret
- assert "cppcheck: error: " + expected + "\ncppcheck: error: failed to load project '{}'. An error occurred.\n".format(project_file) == stdout
+ assert "cppcheck: error: " + expected + f"\ncppcheck: error: failed to load project '{project_file}'. An error occurred.\n" == stdout
assert "" == stderr
diff --git a/test/cli/qml_test.py b/test/cli/qml_test.py
index 485ab597c4e..e8675f45e56 100644
--- a/test/cli/qml_test.py
+++ b/test/cli/qml_test.py
@@ -1,4 +1,3 @@
-
# python3 -m pytest test-qml.py
import os
@@ -16,9 +15,9 @@ def test_unused_functions():
# there are unused functions. But fillSampleData is not unused because that is referenced from main.qml
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -36,13 +35,13 @@ def test_unused_functions_j():
def test_unused_functions_builddir(tmpdir):
build_dir = os.path.join(tmpdir, 'b1')
os.mkdir(build_dir)
- ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--library=qt', '--enable=unusedFunction', '--cppcheck-build-dir={}'.format(build_dir), __project_dir])
+ ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--library=qt', '--enable=unusedFunction', f'--cppcheck-build-dir={build_dir}', __project_dir])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:47:0: style: The function 'fillSampleData' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]".format(__project_dir_sep),
+ f"{__project_dir_sep}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:47:0: style: The function 'fillSampleData' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]",
]
assert ret == 0, stdout
@@ -51,13 +50,13 @@ def test_unused_functions_builddir(tmpdir):
def test_unused_functions_builddir_j(tmpdir):
build_dir = os.path.join(tmpdir, 'b1')
os.mkdir(build_dir)
- ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--library=qt', '--enable=unusedFunction', '-j2', '--cppcheck-build-dir={}'.format(build_dir), __project_dir])
+ ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--library=qt', '--enable=unusedFunction', '-j2', f'--cppcheck-build-dir={build_dir}', __project_dir])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:47:0: style: The function 'fillSampleData' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]".format(__project_dir_sep),
+ f"{__project_dir_sep}samplemodel.cpp:15:0: style: The function 'data' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:47:0: style: The function 'fillSampleData' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:38:0: style: The function 'roleNames' is never used. [unusedFunction]",
+ f"{__project_dir_sep}samplemodel.cpp:9:0: style: The function 'rowCount' is never used. [unusedFunction]",
]
assert ret == 0, stdout
diff --git a/test/cli/suppress-syntaxError_test.py b/test/cli/suppress-syntaxError_test.py
index bc3248c8afb..e4a9db68666 100644
--- a/test/cli/suppress-syntaxError_test.py
+++ b/test/cli/suppress-syntaxError_test.py
@@ -1,7 +1,5 @@
-
# python -m pytest test-suppress-syntaxError.py
-import pytest
from testutils import cppcheck
def test_j():
diff --git a/test/cli/testutils.py b/test/cli/testutils.py
index f33f2c507b8..2cfbc33a49e 100644
--- a/test/cli/testutils.py
+++ b/test/cli/testutils.py
@@ -2,7 +2,6 @@
import logging
import os
import select
-import signal
import subprocess
import time
@@ -41,7 +40,7 @@ def create_gui_project_file(project_file, root_path=None, import_project=None, p
cppcheck_xml += ' \n'
cppcheck_xml += '\n'
- f = open(project_file, 'wt')
+ f = open(project_file, 'w')
f.write(cppcheck_xml)
f.close()
@@ -71,7 +70,7 @@ def __lookup_cppcheck_exe():
if exe_path:
exe_path = os.path.abspath(exe_path)
- print("using '{}'".format(exe_path))
+ print(f"using '{exe_path}'")
return exe_path
diff --git a/test/cli/unused_function_test.py b/test/cli/unused_function_test.py
index 4aa06ade4d0..ae4c1a0e211 100644
--- a/test/cli/unused_function_test.py
+++ b/test/cli/unused_function_test.py
@@ -1,4 +1,3 @@
-
# python3 -m pytest test-unused_function_test.py
import os
@@ -23,9 +22,9 @@ def __create_compdb(tmpdir, projpath):
j.append({
'directory': projpath,
'file': os.path.join(projpath, f),
- 'command': 'gcc -c {}'.format(f)
+ 'command': f'gcc -c {f}'
})
- with open(compile_commands, 'wt') as f:
+ with open(compile_commands, 'w') as f:
f.write(json.dumps(j, indent=4))
return compile_commands
@@ -34,7 +33,7 @@ def test_unused_functions():
ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--enable=unusedFunction', '--inline-suppr', '-j1', __project_dir])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -57,7 +56,7 @@ def test_unused_functions_project():
'-j1'])
assert stdout.splitlines() == []
assert [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
] == stderr.splitlines()
assert ret == 0, stdout
@@ -82,12 +81,12 @@ def test_unused_functions_compdb(tmpdir):
'--template=simple',
'--enable=unusedFunction',
'--inline-suppr',
- '--project={}'.format(compdb_file),
+ f'--project={compdb_file}',
'-j1'
])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -98,7 +97,7 @@ def test_unused_functions_compdb_j(tmpdir):
'--template=simple',
'--enable=unusedFunction',
'--inline-suppr',
- '--project={}'.format(compdb_file),
+ f'--project={compdb_file}',
'-j2'
])
assert stdout.splitlines() == [
@@ -111,10 +110,10 @@ def test_unused_functions_compdb_j(tmpdir):
def test_unused_functions_builddir(tmpdir):
build_dir = os.path.join(tmpdir, 'b1')
os.mkdir(build_dir)
- ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--enable=unusedFunction', '--inline-suppr', '-j1', '--cppcheck-build-dir={}'.format(build_dir), __project_dir])
+ ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--enable=unusedFunction', '--inline-suppr', '-j1', f'--cppcheck-build-dir={build_dir}', __project_dir])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -123,13 +122,13 @@ def test_unused_functions_builddir(tmpdir):
def test_unused_functions_builddir_j(tmpdir):
build_dir = os.path.join(tmpdir, 'b1')
os.mkdir(build_dir)
- ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--enable=unusedFunction', '--inline-suppr', '-j2', '--cppcheck-build-dir={}'.format(build_dir), __project_dir])
+ ret, stdout, stderr = cppcheck(['-q', '--template=simple', '--enable=unusedFunction', '--inline-suppr', '-j2', f'--cppcheck-build-dir={build_dir}', __project_dir])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]",
+ f"{__project_dir_sep}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]",
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]",
+ f"{__project_dir_sep}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -142,11 +141,11 @@ def test_unused_functions_builddir_project(tmpdir):
'--enable=unusedFunction',
'--inline-suppr',
'--project={}'.format(os.path.join(__project_dir, 'unusedFunction.cppcheck')),
- '--cppcheck-build-dir={}'.format(build_dir),
+ f'--cppcheck-build-dir={build_dir}',
'-j1'])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -160,14 +159,14 @@ def test_unused_functions_builddir_project_j(tmpdir):
'--enable=unusedFunction',
'--inline-suppr',
'--project={}'.format(os.path.join(__project_dir, 'unusedFunction.cppcheck')),
- '--cppcheck-build-dir={}'.format(build_dir),
+ f'--cppcheck-build-dir={build_dir}',
'-j2'])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]",
+ f"{__project_dir_sep}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]",
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]",
+ f"{__project_dir_sep}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -180,13 +179,13 @@ def test_unused_functions_builddir_compdb(tmpdir):
'--template=simple',
'--enable=unusedFunction',
'--inline-suppr',
- '--project={}'.format(compdb_file),
- '--cppcheck-build-dir={}'.format(build_dir),
+ f'--project={compdb_file}',
+ f'--cppcheck-build-dir={build_dir}',
'-j1'
])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]"
]
assert ret == 0, stdout
@@ -200,15 +199,15 @@ def test_unused_functions_builddir_compdb_j(tmpdir):
'--template=simple',
'--enable=unusedFunction',
'--inline-suppr',
- '--project={}'.format(compdb_file),
- '--cppcheck-build-dir={}'.format(build_dir),
+ f'--project={compdb_file}',
+ f'--cppcheck-build-dir={build_dir}',
'-j2'
])
assert stdout.splitlines() == []
assert stderr.splitlines() == [
- "{}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]".format(__project_dir_sep),
- "{}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]".format(__project_dir_sep)
+ f"{__project_dir_sep}1.c:4:0: style: The function 'f1' is never used. [unusedFunction]",
+ f"{__project_dir_sep}2.c:4:0: style: The function 'f2' is never used. [unusedFunction]",
+ f"{__project_dir_sep}3.c:3:0: style: The function 'f3_3' is never used. [unusedFunction]",
+ f"{__project_dir_sep}4.c:4:0: style: The function 'f4_1' is never used. [unusedFunction]"
]
assert ret == 0, stdout
diff --git a/test/signal/test-signalhandler.py b/test/signal/test-signalhandler.py
index 2d9939f101d..0beac723f55 100644
--- a/test/signal/test-signalhandler.py
+++ b/test/signal/test-signalhandler.py
@@ -14,7 +14,7 @@ def _lookup_cppcheck_exe(exe_name):
for path in ('', 'bin/', 'bin/debug/'):
exe_path = base + path + exe_name
if os.path.isfile(exe_path):
- print("using '{}'".format(exe_path))
+ print(f"using '{exe_path}'")
return exe_path
return None
diff --git a/test/signal/test-stacktrace.py b/test/signal/test-stacktrace.py
index 8f9e5763207..e03032bda8f 100644
--- a/test/signal/test-stacktrace.py
+++ b/test/signal/test-stacktrace.py
@@ -13,7 +13,7 @@ def _lookup_cppcheck_exe(exe_name):
for path in ('', 'bin/', 'bin/debug/'):
exe_path = base + path + exe_name
if os.path.isfile(exe_path):
- print("using '{}'".format(exe_path))
+ print(f"using '{exe_path}'")
return exe_path
return None
diff --git a/tools/MT-Unsafe.py b/tools/MT-Unsafe.py
index a30395ff011..8a5e2bf16f5 100755
--- a/tools/MT-Unsafe.py
+++ b/tools/MT-Unsafe.py
@@ -56,7 +56,7 @@ def man_search(manpage):
if manpage.endswith('.gz'):
MANPAGE = gzip.open(manpage, 'r')
else:
- MANPAGE = open(manpage, 'r')
+ MANPAGE = open(manpage)
except OSError as filename:
print('cannot open %s' % filename, file=sys.stderr)
return None, None
@@ -94,7 +94,7 @@ def man_search(manpage):
# vprint(1, '%s for %s' % (res, lineread))
if res:
apis.add(res.group(1))
- dprint(1, 'found api %s in %s' % (res.group(1), lineread))
+ dprint(1, 'found api {} in {}'.format(res.group(1), lineread))
next
if 'MT-Unsafe' in lineread:
diff --git a/tools/bisect/bisect_common.py b/tools/bisect/bisect_common.py
index 9b296ad0c17..2021fd98d0c 100644
--- a/tools/bisect/bisect_common.py
+++ b/tools/bisect/bisect_common.py
@@ -12,7 +12,7 @@ def build_cppcheck(bisect_path):
install_path = os.path.join(bisect_path, commit_hash)
cppcheck_path = os.path.join(install_path, 'cppcheck')
if os.path.exists(install_path):
- print('binary for {} already exists'.format(commit_hash))
+ print(f'binary for {commit_hash} already exists')
return cppcheck_path
bisect_repo_dir = os.path.join(bisect_path, 'cppcheck')
@@ -32,11 +32,11 @@ def build_cppcheck(bisect_path):
# TODO: make jobs configurable
# TODO: use "make install"?
# TODO: allow CXXFLAGS overrides to workaround compiling issues in older versions
- print('building {}'.format(commit_hash))
+ print(f'building {commit_hash}')
subprocess.check_call(['make', '-C', bisect_repo_dir, '-j6', 'MATCHCOMPILER=yes', 'CXXFLAGS=-O2 -w -pipe', '-s'])
# TODO: remove folder if installation failed
- print('installing {}'.format(commit_hash))
+ print(f'installing {commit_hash}')
os.mkdir(install_path)
if os.path.exists(os.path.join(bisect_repo_dir, 'cfg')):
shutil.copytree(os.path.join(bisect_repo_dir, 'cfg'), os.path.join(install_path, 'cfg'))
diff --git a/tools/bisect/bisect_hang.py b/tools/bisect/bisect_hang.py
index 4a185a473d9..8dc17ea79fd 100644
--- a/tools/bisect/bisect_hang.py
+++ b/tools/bisect/bisect_hang.py
@@ -11,7 +11,7 @@ def run(cppcheck_path, options, elapsed_time=None):
timeout = elapsed_time * 2
cmd = options.split()
cmd.insert(0, cppcheck_path)
- print('running {}'.format(cppcheck_path))
+ print(f'running {cppcheck_path}')
p = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
p.communicate(timeout=timeout)
@@ -54,7 +54,7 @@ def run(cppcheck_path, options, elapsed_time=None):
# TODO: handle error result
run(cppcheck_path, options)
elapsed_time = time.perf_counter() - t
- print('elapsed_time: {}'.format(elapsed_time))
+ print(f'elapsed_time: {elapsed_time}')
# TODO: write to stdout and redirect all all printing to stderr
sys.exit(round(elapsed_time + .5)) # return the time
@@ -64,7 +64,7 @@ def run(cppcheck_path, options, elapsed_time=None):
if not elapsed_time:
# TODO: handle error result
- print('elapsed_time: {}'.format(run_time))
+ print(f'elapsed_time: {run_time}')
# TODO: write to stdout and redirect all printing to stderr
sys.exit(round(run_time + .5)) # return the time
@@ -74,6 +74,6 @@ def run(cppcheck_path, options, elapsed_time=None):
if not run_res:
sys.exit(EC_BAD if not invert else EC_GOOD) # timeout occurred
-print('run_time: {}'.format(run_time))
+print(f'run_time: {run_time}')
sys.exit(EC_GOOD if not invert else EC_BAD) # no timeout
diff --git a/tools/bisect/bisect_res.py b/tools/bisect/bisect_res.py
index 5d7effedd56..dfcaa8d5693 100644
--- a/tools/bisect/bisect_res.py
+++ b/tools/bisect/bisect_res.py
@@ -7,7 +7,7 @@
def run(cppcheck_path, options):
cmd = options.split()
cmd.insert(0, cppcheck_path)
- print('running {}'.format(cppcheck_path))
+ print(f'running {cppcheck_path}')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = p.communicate()
# only 0 and 1 are well-defined in this case
diff --git a/tools/ci.py b/tools/ci.py
index 27d0f871874..c02da8e8304 100644
--- a/tools/ci.py
+++ b/tools/ci.py
@@ -22,7 +22,7 @@ def upload(file_to_upload, destination):
child.expect('Password:')
child.sendline(password)
child.interact()
- except (IOError, OSError, pexpect.TIMEOUT):
+ except (OSError, pexpect.TIMEOUT):
pass
@@ -34,7 +34,7 @@ def gitpush():
child.expect("Enter passphrase for key '/home/daniel/.ssh/id_rsa':")
child.sendline(password)
child.interact()
- except (IOError, OSError, pexpect.TIMEOUT):
+ except (OSError, pexpect.TIMEOUT):
pass
@@ -72,7 +72,7 @@ def gitpull():
child.expect('Already up-to-date.')
child.interact()
- except (IOError, OSError, pexpect.TIMEOUT):
+ except (OSError, pexpect.TIMEOUT):
pass
except pexpect.EOF:
return True
diff --git a/tools/compare-normal-exhaustive.py b/tools/compare-normal-exhaustive.py
index 7139748331f..812a4941d9b 100755
--- a/tools/compare-normal-exhaustive.py
+++ b/tools/compare-normal-exhaustive.py
@@ -8,12 +8,11 @@
import os
import sys
import random
-import subprocess
def format_float(a, b=1):
if a > 0 and b > 0:
- return '{:.2f}'.format(a / b)
+ return f'{a / b:.2f}'
return 'N/A'
@@ -70,7 +69,7 @@ def format_float(a, b=1):
lib.clone_cppcheck(cppcheck_path, '')
pass
except Exception as e:
- print('Failed to clone Cppcheck repository ({}), retry later'.format(e))
+ print(f'Failed to clone Cppcheck repository ({e}), retry later')
sys.exit(1)
if not lib.compile_cppcheck(cppcheck_path):
diff --git a/tools/compare_ast_symdb.py b/tools/compare_ast_symdb.py
index e4421e9757f..903cf0b6975 100644
--- a/tools/compare_ast_symdb.py
+++ b/tools/compare_ast_symdb.py
@@ -12,7 +12,7 @@
CPPCHECK = os.path.expanduser('~/cppcheck/cppcheck')
def run_cppcheck(cppcheck_parameters:str, clang:str):
- cmd = '{} {} {} --debug --verbose'.format(CPPCHECK, cppcheck_parameters, clang)
+ cmd = f'{CPPCHECK} {cppcheck_parameters} {clang} --debug --verbose'
#print(cmd)
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
comm = p.communicate()
@@ -63,20 +63,20 @@ def compare_ast_symdb(cppcheck_parameters: str):
ast1 = get_ast(debug1)
ast2 = get_ast(debug2)
if ast1 != ast2:
- print("ast is not the same: {}".format(cppcheck_parameters))
- with open('cppcheck.ast', 'wt') as f:
+ print(f"ast is not the same: {cppcheck_parameters}")
+ with open('cppcheck.ast', 'w') as f:
f.write(ast1)
- with open('clang.ast', 'wt') as f:
+ with open('clang.ast', 'w') as f:
f.write(ast2)
same = False
symdb1 = get_symdb(debug1)
symdb2 = get_symdb(debug2)
if symdb1 != symdb2:
- print("symdb is not the same: {}".format(cppcheck_parameters))
- with open('cppcheck.symdb', 'wt') as f:
+ print(f"symdb is not the same: {cppcheck_parameters}")
+ with open('cppcheck.symdb', 'w') as f:
f.write(symdb1)
- with open('clang.symdb', 'wt') as f:
+ with open('clang.symdb', 'w') as f:
f.write(symdb2)
same = False
diff --git a/tools/creduce.py b/tools/creduce.py
index 0ab9f5b9986..198b0c32dbc 100644
--- a/tools/creduce.py
+++ b/tools/creduce.py
@@ -1,4 +1,10 @@
-import argparse, contextlib, multiprocessing, os, tempfile, shutil, subprocess
+import argparse
+import contextlib
+import multiprocessing
+import os
+import tempfile
+import shutil
+import subprocess
@contextlib.contextmanager
def mkdtemp():
@@ -11,7 +17,7 @@ def print_lines(lines):
print(line)
def write_to(file, lines):
- content = list((line + "\n" for line in lines))
+ content = list(line + "\n" for line in lines)
if (len(content) > 0):
with open(file, 'w') as f:
f.writelines(content)
@@ -21,7 +27,7 @@ def make_executable(p):
def quote(s):
text = s.replace("'", "'\"'\"'")
- return "'{}'".format(text)
+ return f"'{text}'"
class ScriptBuilder:
def __init__(self):
@@ -42,8 +48,8 @@ def grep(self, text, file=None):
def check(self, equal_zero=False, result=1):
op = 'eq' if equal_zero else 'ne'
cmds = ['RES=$?',
- 'if [ $RES -{} "0" ]; then'.format(op),
- ' exit {}'.format(result),
+ f'if [ $RES -{op} "0" ]; then',
+ f' exit {result}',
'fi']
self.commands.extend(cmds)
diff --git a/tools/daca2-download.py b/tools/daca2-download.py
index 8a05332abda..4081a3bc8e5 100755
--- a/tools/daca2-download.py
+++ b/tools/daca2-download.py
@@ -41,7 +41,7 @@ def getpackages():
if not wget('ls-lR.gz'):
return []
subprocess.call(['nice', 'gunzip', 'ls-lR.gz'])
- f = open('ls-lR', 'rt')
+ f = open('ls-lR')
lines = f.readlines()
f.close()
subprocess.call(['rm', 'ls-lR'])
@@ -94,7 +94,7 @@ def removeAll():
else:
os.remove(filename)
# pylint: disable=undefined-variable
- except WindowsError as err:
+ except OSError as err:
time.sleep(30)
if count == 0:
print('Failed to cleanup files/folders')
diff --git a/tools/daca2-getpackages.py b/tools/daca2-getpackages.py
index 3d0d8341b89..63e4020c583 100755
--- a/tools/daca2-getpackages.py
+++ b/tools/daca2-getpackages.py
@@ -44,7 +44,7 @@ def getpackages():
subprocess.call(['nice', 'gunzip', 'ls-lR.gz'])
if not os.path.isfile('ls-lR'):
sys.exit(1)
- f = open('ls-lR', 'rt')
+ f = open('ls-lR')
lines = f.readlines()
f.close()
subprocess.call(['rm', 'ls-lR'])
diff --git a/tools/donate-cpu-server.py b/tools/donate-cpu-server.py
index 2e0ceb4918d..5a1cdb82074 100755
--- a/tools/donate-cpu-server.py
+++ b/tools/donate-cpu-server.py
@@ -53,7 +53,7 @@
def print_ts(msg) -> None:
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
- print('[{}] {}'.format(dt, msg))
+ print(f'[{dt}] {msg}')
# Set up an exception hook for all uncaught exceptions so they can be logged
@@ -175,7 +175,7 @@ def latestReport(latestResults: list) -> str:
count = ['0', '0']
lost = 0
added = 0
- for line in open(filename, 'rt'):
+ for line in open(filename):
line = line.strip()
if datestr is None and line.startswith(str(current_year) + '-') or line.startswith(str(current_year - 1) + '-'):
datestr = line
@@ -211,7 +211,7 @@ def crashReport(results_path: str, query_params: dict):
for filename in sorted(glob.glob(os.path.expanduser(results_path + '/*'))):
if not os.path.isfile(filename) or filename.endswith('.diff'):
continue
- with open(filename, 'rt') as file_:
+ with open(filename) as file_:
datestr = None
package_url = None
for line in file_:
@@ -242,7 +242,7 @@ def crashReport(results_path: str, query_params: dict):
if c_head != 'Crash':
break
if package_url is not None:
- pkgs += '{}\n'.format(package_url)
+ pkgs += f'{package_url}\n'
elif line.find(' received signal ') != -1:
crash_line = next(file_, '').strip()
location_index = crash_line.rfind(' at ')
@@ -274,7 +274,7 @@ def crashReport(results_path: str, query_params: dict):
stack_trace.append(m.group('number') + ' ' + m.group('function') + '(...) at ' + m.group('location'))
continue
- print_ts('{} - unmatched stack frame - {}'.format(package, l))
+ print_ts(f'{package} - unmatched stack frame - {l}')
break
key = hash(' '.join(stack_trace))
@@ -313,7 +313,7 @@ def timeoutReport(results_path: str) -> str:
for filename in sorted(glob.glob(os.path.expanduser(results_path + '/*'))):
if not os.path.isfile(filename) or filename.endswith('.diff'):
continue
- with open(filename, 'rt') as file_:
+ with open(filename) as file_:
datestr = None
for line in file_:
line = line.strip()
@@ -360,7 +360,7 @@ def staleReport(results_path: str, query_params: dict) -> str:
for filename in sorted(glob.glob(os.path.expanduser(results_path + '/*'))):
if filename.endswith('.diff') or not os.path.isfile(filename):
continue
- with open(filename, 'rt') as f:
+ with open(filename) as f:
# first line is datetime string
datestr = f.readline().strip()
try:
@@ -424,7 +424,7 @@ def diffReport(resultsPath: str) -> str:
for filename in sorted(glob.glob(resultsPath + '/*.diff')):
if not os.path.isfile(filename):
continue
- with open(filename, 'rt') as f:
+ with open(filename) as f:
data = json.loads(f.read())
uploadedToday = data['date'] == today
for messageId in data['sums']:
@@ -457,7 +457,7 @@ def generate_package_diff_statistics(filename: str) -> None:
sums = {}
- for line in open(filename, 'rt'):
+ for line in open(filename):
line = line.strip()
if line == 'diff:':
is_diff = True
@@ -485,7 +485,7 @@ def generate_package_diff_statistics(filename: str) -> None:
filename_diff = filename + '.diff'
if sums:
- with open(filename_diff, 'wt') as f:
+ with open(filename_diff, 'w') as f:
f.write(json.dumps(output))
elif os.path.isfile(filename_diff):
os.remove(filename_diff)
@@ -497,7 +497,7 @@ def diffMessageIdReport(resultPath: str, messageId: str) -> str:
for filename in sorted(glob.glob(resultPath + '/*.diff')):
if not os.path.isfile(filename):
continue
- with open(filename, 'rt') as f:
+ with open(filename) as f:
diff_stats = json.loads(f.read())
if messageId not in diff_stats['sums']:
continue
@@ -506,7 +506,7 @@ def diffMessageIdReport(resultPath: str, messageId: str) -> str:
url = None
diff = False
- for line in open(filename[:-5], 'rt'):
+ for line in open(filename[:-5]):
if line.startswith('ftp://'):
url = line
elif line == 'diff:\n':
@@ -528,7 +528,7 @@ def diffMessageIdTodayReport(resultPath: str, messageId: str) -> str:
for filename in sorted(glob.glob(resultPath + '/*.diff')):
if not os.path.isfile(filename):
continue
- with open(filename, 'rt') as f:
+ with open(filename) as f:
diff_stats = json.loads(f.read())
if messageId not in diff_stats['sums']:
continue
@@ -540,7 +540,7 @@ def diffMessageIdTodayReport(resultPath: str, messageId: str) -> str:
url = None
diff = False
firstLine = True
- for line in open(filename[:-5], 'rt'):
+ for line in open(filename[:-5]):
if firstLine:
firstLine = False
if not line.startswith(today):
@@ -598,7 +598,7 @@ def summaryReport(resultsPath: str, name: str, prefix: str, marker: str) -> str:
uploadedToday = False
firstLine = True
inResults = False
- for line in open(filename, 'rt'):
+ for line in open(filename):
if firstLine:
if line.startswith(today):
uploadedToday = True
@@ -641,7 +641,7 @@ def summaryReport(resultsPath: str, name: str, prefix: str, marker: str) -> str:
outToday[messageId] += 1
html = '\n'
- html += '{} report\n'.format(name)
+ html += f'{name} report\n'
html += 'HEAD report
\n'
html += 'Uploaded today
'
html += summaryReportFromDict(outToday, prefix, 'today')
@@ -668,7 +668,7 @@ def messageIdReport(resultPath: str, marker: str, messageId: str, query_params:
continue
url = None
inResults = False
- for line in open(filename, 'rt'):
+ for line in open(filename):
if line.startswith('cppcheck: '):
if OLD_VERSION not in line:
# Package results seem to be too old, skip
@@ -715,7 +715,7 @@ def messageIdTodayReport(resultPath: str, messageId: str, marker: str) -> str:
url = None
inResults = False
firstLine = True
- for line in open(filename, 'rt'):
+ for line in open(filename):
if firstLine:
firstLine = False
if not line.startswith(today):
@@ -755,8 +755,8 @@ def timeReport(resultPath: str, show_gt: bool, query_params: dict):
title = 'Time report ({})'.format('regressed' if show_gt else 'improved')
html = '\n'
- html += '{}\n'.format(title)
- html += '{}
\n'.format(title)
+ html += f'{title}\n'
+ html += f'{title}
\n'
html += '\n'
column_width = [40, 10, 10, 10, 10, 10]
html += ''
@@ -774,7 +774,7 @@ def timeReport(resultPath: str, show_gt: bool, query_params: dict):
continue
datestr = None
package_url = None
- for line in open(filename, 'rt'):
+ for line in open(filename):
line = line.strip()
if line.startswith('cppcheck: '):
if OLD_VERSION not in line:
@@ -822,13 +822,13 @@ def timeReport(resultPath: str, show_gt: bool, query_params: dict):
data[pkg_name] = (datestr, split_line[2], split_line[1], time_factor)
if package_url is not None:
- pkgs += '{}\n'.format(package_url)
+ pkgs += f'{package_url}\n'
break
sorted_data = sorted(data.items(), key=lambda kv: kv[1][3], reverse=show_gt)
sorted_dict = collections.OrderedDict(sorted_data)
for key in sorted_dict:
- html += fmt(key, sorted_dict[key][0], sorted_dict[key][1], sorted_dict[key][2], '{:.2f}'.format(sorted_dict[key][3]),
+ html += fmt(key, sorted_dict[key][0], sorted_dict[key][1], sorted_dict[key][2], f'{sorted_dict[key][3]:.2f}',
column_width=column_width) + '\n'
html += '\n'
@@ -844,9 +844,9 @@ def timeReport(resultPath: str, show_gt: bool, query_params: dict):
html += 'Time for all packages (not just the ones listed above):\n'
html += fmt('Total time:',
'',
- '{:.1f}'.format(total_time_base),
- '{:.1f}'.format(total_time_head),
- '{:.2f}'.format(total_time_factor), link=False, column_width=column_width)
+ f'{total_time_base:.1f}',
+ f'{total_time_head:.1f}',
+ f'{total_time_factor:.2f}', link=False, column_width=column_width)
html += '\n'
html += '\n'
@@ -860,8 +860,8 @@ def timeReport(resultPath: str, show_gt: bool, query_params: dict):
def timeReportSlow(resultPath: str) -> str:
title = 'Time report (slowest)'
html = '\n'
- html += '{}\n'.format(title)
- html += '{}
\n'.format(title)
+ html += f'{title}\n'
+ html += f'{title}
\n'
html += '\n'
html += ''
html += fmt('Package', 'Date Time', OLD_VERSION, 'Head', link=False)
@@ -875,7 +875,7 @@ def timeReportSlow(resultPath: str) -> str:
if not os.path.isfile(filename) or filename.endswith('.diff'):
continue
datestr = None
- for line in open(filename, 'rt'):
+ for line in open(filename):
line = line.strip()
if line.startswith('cppcheck: '):
if OLD_VERSION not in line:
@@ -964,7 +964,7 @@ def check_library_report(result_path: str, message_id: str) -> str:
if not os.path.isfile(filename) or filename.endswith('.diff'):
continue
in_results = False
- for line in open(filename, 'rt'):
+ for line in open(filename):
if line.startswith('cppcheck: '):
if OLD_VERSION not in line:
# Package results seem to be too old, skip
@@ -1030,7 +1030,7 @@ def check_library_function_name(result_path: str, function_name: str, query_para
in_results = False
package_url = None
cppcheck_options = None
- for line in open(filename, 'rt'):
+ for line in open(filename):
if line.startswith('cppcheck: '):
if OLD_VERSION not in line:
# Package results seem to be too old, skip
@@ -1052,10 +1052,10 @@ def check_library_function_name(result_path: str, function_name: str, query_para
break
if id not in line:
continue
- if not (' ' + function_name + ' ') in line:
+ if (' ' + function_name + ' ') not in line:
continue
if pkgs is not None and package_url is not None:
- pkgs += '{}\n'.format(package_url.strip())
+ pkgs += f'{package_url.strip()}\n'
break
if package_url:
output_lines_list.append(package_url)
@@ -1112,7 +1112,7 @@ def run(self):
cmd = self.cmd
url, queryParams = self.parse_req(cmd)
if url is None:
- print_ts('invalid request: {}'.format(cmd))
+ print_ts(f'invalid request: {cmd}')
self.connection.close()
return
t_start = time.perf_counter()
@@ -1209,10 +1209,10 @@ def run(self):
print_ts('HTTP/1.1 404 Not Found')
self.connection.send(b'HTTP/1.1 404 Not Found\r\n\r\n')
else:
- with open(filename, 'rt') as f:
+ with open(filename) as f:
data = f.read()
httpGetResponse(self.connection, data, 'text/plain')
- print_ts('{} finished in {}s'.format(url, (time.perf_counter() - t_start)))
+ print_ts(f'{url} finished in {(time.perf_counter() - t_start)}s')
except:
tb = "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
print_ts(tb)
@@ -1232,7 +1232,7 @@ def read_data(connection, cmd, pos_nl, max_data_size, check_done, cmd_name, time
try:
text_received = bytes_received.decode('ascii', 'ignore')
except UnicodeDecodeError as e:
- print_ts('Error: Decoding failed ({}): {}'.format(cmd_name, e))
+ print_ts(f'Error: Decoding failed ({cmd_name}): {e}')
data = None
break
t = 0.0
@@ -1242,22 +1242,22 @@ def read_data(connection, cmd, pos_nl, max_data_size, check_done, cmd_name, time
else:
time.sleep(0.2)
t += 0.2
- except socket.error as e:
- print_ts('Socket error occurred ({}): {}'.format(cmd_name, e))
+ except OSError as e:
+ print_ts(f'Socket error occurred ({cmd_name}): {e}')
data = None
connection.close()
if (timeout > 0) and (t >= timeout):
- print_ts('Timeout occurred ({}).'.format(cmd_name))
+ print_ts(f'Timeout occurred ({cmd_name}).')
data = None
if data and (len(data) >= max_data_size):
- print_ts('Maximum allowed data ({} bytes) exceeded ({}).'.format(max_data_size, cmd_name))
+ print_ts(f'Maximum allowed data ({max_data_size} bytes) exceeded ({cmd_name}).')
data = None
if data and check_done and not data.endswith('\nDONE'):
- print_ts('Incomplete data received ({}).'.format(cmd_name))
+ print_ts(f'Incomplete data received ({cmd_name}).')
data = None
return data
@@ -1273,7 +1273,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
latestResults = []
if os.path.isfile('latest.txt'):
- with open('latest.txt', 'rt') as f:
+ with open('latest.txt') as f:
latestResults = f.read().strip().split(' ')
print_ts('version ' + SERVER_VERSION)
@@ -1286,7 +1286,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
try:
bytes_received = connection.recv(128)
cmd = bytes_received.decode('utf-8', 'ignore')
- except socket.error as e:
+ except OSError as e:
print_ts('Error: Recv error: ' + str(e))
connection.close()
continue
@@ -1296,12 +1296,12 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
continue
pos_nl = cmd.find('\n')
if pos_nl < 1:
- print_ts("No newline found in data: '{}'".format(cmd))
+ print_ts(f"No newline found in data: '{cmd}'")
connection.close()
continue
firstLine = cmd[:pos_nl]
if re.match('[a-zA-Z0-9./ ]+', firstLine) is None:
- print_ts('Unsupported characters found in command: {}'.format(firstLine))
+ print_ts(f'Unsupported characters found in command: {firstLine}')
connection.close()
continue
if cmd.startswith('GET /'):
@@ -1325,7 +1325,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
if pkg is not None:
break
- with open('package-index.txt', 'wt') as f:
+ with open('package-index.txt', 'w') as f:
f.write(str(packageIndex) + '\n')
print_ts('get:' + pkg)
@@ -1376,17 +1376,17 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
print_ts('Unexpected old version. Ignoring result data.')
continue
filename = os.path.join(resultPath, res.group(1))
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write(strDateTime() + '\n' + data)
# track latest added results..
if len(latestResults) >= 20:
latestResults = latestResults[1:]
latestResults.append(filename)
- with open('latest.txt', 'wt') as f:
+ with open('latest.txt', 'w') as f:
f.write(' '.join(latestResults))
# generate package.diff..
generate_package_diff_statistics(filename)
- print_ts('write finished for {} ({} bytes / {}s)'.format(res.group(1), len(data), (time.perf_counter() - t_start)))
+ print_ts(f'write finished for {res.group(1)} ({len(data)} bytes / {(time.perf_counter() - t_start)}s)')
continue
elif cmd.startswith('write_info\nftp://') or cmd.startswith('write_info\nhttp://'):
t_start = time.perf_counter()
@@ -1418,9 +1418,9 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
if not os.path.exists(info_path):
os.mkdir(info_path)
filename = info_path + '/' + res.group(1)
- with open(filename, 'wt') as f:
+ with open(filename, 'w') as f:
f.write(strDateTime() + '\n' + data)
- print_ts('write_info finished for {} ({} bytes / {}s)'.format(res.group(1), len(data), (time.perf_counter() - t_start)))
+ print_ts(f'write_info finished for {res.group(1)} ({len(data)} bytes / {(time.perf_counter() - t_start)}s)')
continue
elif cmd == 'getPackagesCount\n':
packages_count = str(len(packages))
@@ -1435,7 +1435,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
connection.send(pkg.encode('utf-8', 'ignore'))
print_ts('getPackageIdx: ' + pkg)
else:
- print_ts('getPackageIdx: index {} is out of range'.format(request_idx))
+ print_ts(f'getPackageIdx: index {request_idx} is out of range')
connection.close()
continue
elif cmd.startswith('write_nodata\nftp://'):
@@ -1448,7 +1448,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
print_ts('No newline found in data. Ignoring no-data data.')
continue
if pos < 10:
- print_ts('Data is less than 10 characters ({}). Ignoring no-data data.'.format(pos))
+ print_ts(f'Data is less than 10 characters ({pos}). Ignoring no-data data.')
continue
url = data[:pos]
@@ -1459,7 +1459,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
packages[currentIdx] = None
print_ts('write_nodata:' + url)
- with open('packages_nodata.txt', 'at') as f:
+ with open('packages_nodata.txt', 'a') as f:
f.write(url + '\n')
break
if currentIdx == 0:
@@ -1491,22 +1491,22 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
print_ts('work path: ' + workPath)
resultPath = workPath + '/donated-results'
if not os.path.isdir(resultPath):
- print_ts("fatal: result path '{}' is missing".format(resultPath))
+ print_ts(f"fatal: result path '{resultPath}' is missing")
sys.exit(1)
- with open('packages.txt', 'rt') as f:
+ with open('packages.txt') as f:
packages = [val.strip() for val in f.readlines()]
- print_ts('packages: {}'.format(len(packages)))
+ print_ts(f'packages: {len(packages)}')
if os.path.isfile('packages_nodata.txt'):
- with open('packages_nodata.txt', 'rt') as f:
+ with open('packages_nodata.txt') as f:
packages_nodata = [val.strip() for val in f.readlines()]
packages_nodata.sort()
- print_ts('packages_nodata: {}'.format(len(packages_nodata)))
+ print_ts(f'packages_nodata: {len(packages_nodata)}')
- print_ts('removing packages with no files to process'.format(len(packages_nodata)))
+ print_ts('removing packages with no files to process')
packages_nodata_clean = []
for pkg_n in packages_nodata:
if pkg_n in packages:
@@ -1515,13 +1515,13 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
packages_nodata_diff = len(packages_nodata) - len(packages_nodata_clean)
if packages_nodata_diff:
- with open('packages_nodata.txt', 'wt') as f:
+ with open('packages_nodata.txt', 'w') as f:
for pkg in packages_nodata_clean:
f.write(pkg + '\n')
- print_ts('removed {} packages from packages_nodata.txt'.format(packages_nodata_diff))
+ print_ts(f'removed {packages_nodata_diff} packages from packages_nodata.txt')
- print_ts('packages: {}'.format(len(packages)))
+ print_ts(f'packages: {len(packages)}')
if len(packages) == 0:
print_ts('fatal: there are no packages')
@@ -1529,7 +1529,7 @@ def server(server_address_port: int, packages: list, packageIndex: int, resultPa
packageIndex = 0
if os.path.isfile('package-index.txt'):
- with open('package-index.txt', 'rt') as f:
+ with open('package-index.txt') as f:
packageIndex = int(f.read())
if packageIndex < 0 or packageIndex >= len(packages):
packageIndex = 0
diff --git a/tools/donate-cpu.py b/tools/donate-cpu.py
index 142622b1212..82936b9e93e 100755
--- a/tools/donate-cpu.py
+++ b/tools/donate-cpu.py
@@ -55,7 +55,7 @@
print('Stop time:' + stop_time)
elif arg.startswith('-j'):
if not re.match(r'-j\d+', arg):
- print('Argument "{}" is invalid.'.format(arg))
+ print(f'Argument "{arg}" is invalid.')
print('"-j" must be followed by a positive number.')
sys.exit(1)
print('Jobs:' + arg[2:])
@@ -66,7 +66,7 @@
print('Added Package:' + pkg)
elif arg.startswith('--packages='):
pkg_cnt = len(package_urls)
- with open(arg[arg.find('=')+1:], 'rt') as f:
+ with open(arg[arg.find('=')+1:]) as f:
for package_url in f:
package_url = package_url.strip()
if not package_url:
@@ -92,7 +92,7 @@
if max_packages < 0:
max_packages = None
if max_packages is None:
- print('Error: Max. packages value "{}" is invalid. Must be a positive number or 0.'.format(arg_value))
+ print(f'Error: Max. packages value "{arg_value}" is invalid. Must be a positive number or 0.')
sys.exit(1)
# 0 means infinitely, no counting needed.
if max_packages == 0:
@@ -145,7 +145,7 @@
if package_urls:
max_packages = len(package_urls)
if max_packages:
- print('Maximum number of packages to download and analyze: {}'.format(max_packages))
+ print(f'Maximum number of packages to download and analyze: {max_packages}')
if not os.path.exists(work_path):
os.mkdir(work_path)
repo_path = os.path.join(work_path, 'repo')
@@ -158,15 +158,15 @@
try:
lib.try_retry(lib.clone_cppcheck, fargs=(repo_path, migrate_repo_path))
except Exception as e:
- print('Error: Failed to clone Cppcheck ({}), retry later'.format(e))
+ print(f'Error: Failed to clone Cppcheck ({e}), retry later')
sys.exit(1)
while True:
if max_packages:
if packages_processed >= max_packages:
- print('Processed the specified number of {} package(s). Exiting now.'.format(max_packages))
+ print(f'Processed the specified number of {max_packages} package(s). Exiting now.')
break
- print('Processing package {} of the specified {} package(s).'.format(packages_processed + 1, max_packages))
+ print(f'Processing package {packages_processed + 1} of the specified {max_packages} package(s).')
packages_processed += 1
if stop_time:
print('stop_time:' + stop_time + '. Time:' + time.strftime('%H:%M') + '.')
@@ -176,31 +176,31 @@
try:
cppcheck_versions = lib.try_retry(lib.get_cppcheck_versions, max_tries=3, sleep_duration=30.0, sleep_factor=1.0)
except Exception as e:
- print('Failed to get cppcheck versions from server ({}), retry later'.format(e))
+ print(f'Failed to get cppcheck versions from server ({e}), retry later')
sys.exit(1)
for ver in cppcheck_versions:
if ver == 'head':
ver = 'main'
current_cppcheck_dir = os.path.join(work_path, 'tree-'+ver)
if ver != 'main' and lib.has_binary(current_cppcheck_dir):
- print('No need to check Cppcheck-{} for changes - binary already exists'.format(ver))
+ print(f'No need to check Cppcheck-{ver} for changes - binary already exists')
continue
- print('Checking Cppcheck-{} for changes..'.format(ver))
+ print(f'Checking Cppcheck-{ver} for changes..')
try:
has_changes = lib.try_retry(lib.checkout_cppcheck_version, fargs=(repo_path, ver, current_cppcheck_dir), max_tries=3, sleep_duration=30.0, sleep_factor=1.0)
except KeyboardInterrupt as e:
# Passthrough for user abort
raise e
except Exception as e:
- print('Failed to update Cppcheck-{} ({}), retry later'.format(ver, e))
+ print(f'Failed to update Cppcheck-{ver} ({e}), retry later')
sys.exit(1)
if ver == 'main':
if (has_changes or not lib.has_binary(current_cppcheck_dir)) and not lib.compile_cppcheck(current_cppcheck_dir):
- print('Failed to compile Cppcheck-{}, retry later'.format(ver))
+ print(f'Failed to compile Cppcheck-{ver}, retry later')
sys.exit(1)
else:
if not lib.compile_version(current_cppcheck_dir):
- print('Failed to compile Cppcheck-{}, retry later'.format(ver))
+ print(f'Failed to compile Cppcheck-{ver}, retry later')
sys.exit(1)
if package_urls:
package = package_urls[packages_processed-1]
@@ -208,7 +208,7 @@
try:
package = lib.get_package()
except Exception as e:
- print('Error: Failed to get package ({}), retry later'.format(e))
+ print(f'Error: Failed to get package ({e}), retry later')
sys.exit(1)
tgz = lib.download_package(work_path, package, bandwidth_limit)
if tgz is None:
@@ -271,7 +271,7 @@ def get_client_version_head():
count += ' Crash!'
else:
count += ' ' + str(c)
- elapsed_time += " {:.1f}".format(t)
+ elapsed_time += f" {t:.1f}"
results_to_diff.append(errout)
if ver == 'head':
head_info_msg = info
@@ -308,5 +308,5 @@ def get_client_version_head():
if not max_packages or packages_processed < max_packages:
print('Sleep 5 seconds..')
if (client_version_head is not None) and (Version(client_version_head) > Version(lib.get_client_version())):
- print("ATTENTION: A newer client version ({}) is available - please update!".format(client_version_head))
+ print(f"ATTENTION: A newer client version ({client_version_head}) is available - please update!")
time.sleep(5)
diff --git a/tools/donate_cpu_lib.py b/tools/donate_cpu_lib.py
index a2a2aaec994..09dc0b6fad0 100644
--- a/tools/donate_cpu_lib.py
+++ b/tools/donate_cpu_lib.py
@@ -39,11 +39,11 @@ def detect_make():
try:
#print('{} --version'.format(m))
subprocess.check_call([m, '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- except OSError as e:
+ except OSError:
#print("'{}' not found ({})".format(m, e))
continue
- print("using '{}'".format(m))
+ print(f"using '{m}'")
return m
print("Error: a make command ({}) is required".format(','.join(make_cmds)))
@@ -68,13 +68,13 @@ def check_requirements():
#print('{} --version'.format(app))
subprocess.check_call([app, '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
- print("Error: '{}' is required".format(app))
+ print(f"Error: '{app}' is required")
result = False
try:
import psutil
except ImportError as e:
- print("Error: {}. Module is required.".format(e))
+ print(f"Error: {e}. Module is required.")
result = False
return result
@@ -90,12 +90,12 @@ def try_retry(fun, fargs=(), max_tries=5, sleep_duration=5.0, sleep_factor=2.0):
raise e
except BaseException as e:
if i < max_tries - 1:
- print("{} in {}: {}".format(type(e).__name__, fun.__name__, str(e)))
- print("Trying {} again in {} seconds".format(fun.__name__, sleep_duration))
+ print(f"{type(e).__name__} in {fun.__name__}: {str(e)}")
+ print(f"Trying {fun.__name__} again in {sleep_duration} seconds")
time.sleep(sleep_duration)
sleep_duration *= sleep_factor
else:
- print("Maximum number of tries reached for {}".format(fun.__name__))
+ print(f"Maximum number of tries reached for {fun.__name__}")
raise e
@@ -122,7 +122,7 @@ def checkout_cppcheck_version(repo_path, version, cppcheck_path):
if not os.path.isabs(cppcheck_path):
raise ValueError("cppcheck_path is not an absolute path")
if os.path.exists(cppcheck_path):
- print('Checking out {}'.format(version))
+ print(f'Checking out {version}')
subprocess.check_call(['git', 'checkout', '-f', version], cwd=cppcheck_path)
# It is possible to pull branches, not tags
@@ -131,7 +131,7 @@ def checkout_cppcheck_version(repo_path, version, cppcheck_path):
hash_old = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=cppcheck_path).strip()
- print('Pulling {}'.format(version))
+ print(f'Pulling {version}')
subprocess.check_call(['git', 'pull'], cwd=cppcheck_path)
hash_new = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=cppcheck_path).strip()
@@ -142,18 +142,18 @@ def checkout_cppcheck_version(repo_path, version, cppcheck_path):
return has_changes
else:
if version != 'main':
- print('Fetching {}'.format(version))
+ print(f'Fetching {version}')
# Since this is a shallow clone, explicitly fetch the remote version tag
refspec = 'refs/tags/' + version + ':ref/tags/' + version
subprocess.check_call(['git', 'fetch', '--depth=1', 'origin', refspec], cwd=repo_path)
- print('Adding worktree \'{}\' for {}'.format(cppcheck_path, version))
+ print(f'Adding worktree \'{cppcheck_path}\' for {version}')
subprocess.check_call(['git', 'worktree', 'add', cppcheck_path, version], cwd=repo_path)
return True
def get_cppcheck_info(cppcheck_path):
try:
- return subprocess.check_output(['git', 'show', "--pretty=%h (%ci)", 'HEAD', '--no-patch', '--no-notes'], universal_newlines=True, cwd=cppcheck_path).strip()
+ return subprocess.check_output(['git', 'show', "--pretty=%h (%ci)", 'HEAD', '--no-patch', '--no-notes'], text=True, cwd=cppcheck_path).strip()
except:
return ''
@@ -197,7 +197,7 @@ def compile_version(cppcheck_path):
def compile_cppcheck(cppcheck_path):
- print('Compiling {}'.format(os.path.basename(cppcheck_path)))
+ print(f'Compiling {os.path.basename(cppcheck_path)}')
cppcheck_bin = __get_cppcheck_binary(cppcheck_path)
# remove file so interrupted "main" branch compilation is being resumed
@@ -223,7 +223,7 @@ def compile_cppcheck(cppcheck_path):
build_cmd.append('RDYNAMIC=-lshlwapi')
subprocess.check_call(build_cmd, cwd=cppcheck_path, env=build_env)
except Exception as e:
- print('Compilation failed: {}'.format(e))
+ print(f'Compilation failed: {e}')
return False
try:
@@ -232,7 +232,7 @@ def compile_cppcheck(cppcheck_path):
else:
subprocess.check_call([os.path.join(cppcheck_path, 'cppcheck'), '--version'], cwd=cppcheck_path)
except Exception as e:
- print('Running Cppcheck failed: {}'.format(e))
+ print(f'Running Cppcheck failed: {e}')
# remove faulty binary
if os.path.isfile(cppcheck_bin):
os.remove(cppcheck_bin)
@@ -306,7 +306,7 @@ def rmtree_func():
try:
try_retry(rmtree_func, max_tries=5, sleep_duration=30, sleep_factor=1)
except Exception as e:
- print('Failed to cleanup {}: {}'.format(folder_name, e))
+ print(f'Failed to cleanup {folder_name}: {e}')
sys.exit(1)
@@ -442,7 +442,7 @@ def scan_package(cppcheck_path, source_path, libraries, capture_callstack=True,
# TODO: temporarily disabled timing information - use --showtime=top5_summary when next version is released
# Reference for GNU C: https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
- options = '{} --inconclusive --enable={} --inline-suppr --template=daca2'.format(libs, enable)
+ options = f'{libs} --inconclusive --enable={enable} --inline-suppr --template=daca2'
if 'information' in enable:
# TODO: remove missingInclude disabling when it no longer is implied by --enable=information
options += ' --disable=missingInclude --suppress=unmatchedSuppression'
@@ -452,7 +452,7 @@ def scan_package(cppcheck_path, source_path, libraries, capture_callstack=True,
options += ' --check-library --debug-warnings --suppress=autoNoType --suppress=valueFlowBailout' \
' --suppress=bailoutUninitVar --suppress=symbolDatabaseWarning --suppress=normalCheckLevelConditionExpressions'
options += ' -D__GNUC__ --platform=unix64'
- options_rp = options + ' -rp={}'.format(dir_to_scan)
+ options_rp = options + f' -rp={dir_to_scan}'
if __make_cmd == 'msbuild.exe':
cppcheck_cmd = os.path.join(cppcheck_path, 'bin', 'cppcheck.exe') + ' ' + options_rp
cmd = cppcheck_cmd + ' ' + __jobs + ' ' + dir_to_scan
@@ -512,7 +512,7 @@ def scan_package(cppcheck_path, source_path, libraries, capture_callstack=True,
sig_num = int(ie_line[sig_start_pos:ie_line.find(' ', sig_start_pos)])
# break on the first signalled file for now
break
- print('cppcheck finished with ' + str(returncode) + ('' if sig_num == -1 else ' (signal ' + str(sig_num) + ')') + ' in {:.1f}s'.format(elapsed_time))
+ print('cppcheck finished with ' + str(returncode) + ('' if sig_num == -1 else ' (signal ' + str(sig_num) + ')') + f' in {elapsed_time:.1f}s')
options_j = options + ' ' + __jobs
@@ -630,8 +630,8 @@ def __send_all(connection, data):
def __upload(cmd, data, cmd_info):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(__server_address)
- __send_all(sock, '{}\n{}'.format(cmd, data))
- print('{} has been successfully uploaded.'.format(cmd_info))
+ __send_all(sock, f'{cmd}\n{data}')
+ print(f'{cmd_info} has been successfully uploaded.')
return True
@@ -644,7 +644,7 @@ def upload_results(package, results):
try:
try_retry(__upload, fargs=('write\n' + package, results + '\nDONE', 'Result'), max_tries=20, sleep_duration=15, sleep_factor=1)
except Exception as e:
- print('Result upload failed ({})!'.format(e))
+ print(f'Result upload failed ({e})!')
return False
return True
@@ -659,7 +659,7 @@ def upload_info(package, info_output):
try:
try_retry(__upload, fargs=('write_info\n' + package, info_output + '\nDONE', 'Information'), max_tries=20, sleep_duration=15, sleep_factor=1)
except Exception as e:
- print('Information upload failed ({})!'.format(e))
+ print(f'Information upload failed ({e})!')
return False
return True
@@ -669,7 +669,7 @@ def upload_nodata(package):
try:
try_retry(__upload, fargs=('write_nodata\n' + package, '', 'No-data status'), max_tries=3, sleep_duration=30, sleep_factor=1)
except Exception as e:
- print('No-data upload failed ({})!'.format(e))
+ print(f'No-data upload failed ({e})!')
return False
return True
@@ -725,10 +725,10 @@ def __iterate_files(self, path, has_include_cb):
for name in files:
filename = os.path.join(root, name)
try:
- with open(filename, 'rt', errors='ignore') as f:
+ with open(filename, errors='ignore') as f:
filedata = f.read()
has_include_cb(filedata)
- except IOError:
+ except OSError:
pass
def get_libraries(self, folder):
@@ -749,7 +749,7 @@ def has_include(filedata):
del library_includes_re[lib_d]
self.__iterate_files(folder, has_include)
- print('Found libraries: {}'.format(libraries))
+ print(f'Found libraries: {libraries}')
return libraries
diff --git a/tools/extracttests.py b/tools/extracttests.py
index a45c8261d64..cbda331ba67 100755
--- a/tools/extracttests.py
+++ b/tools/extracttests.py
@@ -94,7 +94,7 @@ def parseFile(self, filename):
start_code = None
disable = False
- for line in open(filename, 'r'):
+ for line in open(filename):
# testclass starts
res = re.match('class (' + name + ')', line)
if res is not None:
@@ -383,7 +383,7 @@ def writeHtmlFile(nodes, functionName, filename, errorsOnly):
lines[line_number] += ' // ' + res.group(3)
code = '\n'.join(lines)
else:
- print('filename:%s expected:%s' % (filename, expected))
+ print('filename:{} expected:{}'.format(filename, expected))
# source code
with open(codedir + filename, 'w') as fout:
diff --git a/tools/get_checkers.py b/tools/get_checkers.py
index 4b7c7b3ea64..020a671d96d 100644
--- a/tools/get_checkers.py
+++ b/tools/get_checkers.py
@@ -30,20 +30,20 @@
const std::map allCheckers{""" % (datetime.date.today().year,))
for filename in glob.glob(os.path.expanduser('~/cppchecksolutions/cppcheck/lib/*.cpp')):
- for line in open(filename,'rt'):
+ for line in open(filename):
res = re.match(r'[ \t]*logChecker\(\s*"([:_a-zA-Z0-9]+)"\s*\);.*', line)
if res is None:
continue
req = ''
if line.find('//')>0:
req = line[line.find('//')+2:].strip()
- print(' {"%s","%s"},' % (res.group(1), req))
+ print(' {{"{}","{}"}},'.format(res.group(1), req))
print(" };\n")
print(' const std::map premiumCheckers{')
premium_checkers = []
for filename in sorted(glob.glob(os.path.expanduser('~/cppchecksolutions/addon/src/*.cpp'))):
- for line in open(filename,'rt'):
+ for line in open(filename):
res = re.match(r'[ \t]*logChecker\("([^"]+)"\);.*', line)
if res is None:
continue
@@ -51,7 +51,7 @@
req = line[line.find('//')+2:].strip()
else:
req = ''
- premium_checkers.append(' {"%s","%s"}' % (res.group(1), req))
+ premium_checkers.append(' {{"{}","{}"}}'.format(res.group(1), req))
print(',\n'.join(sorted(premium_checkers)))
print(' };')
diff --git a/tools/listErrorsWithoutCWE.py b/tools/listErrorsWithoutCWE.py
index 0a78ff5bd36..185af5abcce 100755
--- a/tools/listErrorsWithoutCWE.py
+++ b/tools/listErrorsWithoutCWE.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
-from __future__ import print_function
import argparse
import xml.etree.ElementTree as ET
diff --git a/tools/matchcompiler.py b/tools/matchcompiler.py
index 229955f8dcb..a0aaf9a6748 100755
--- a/tools/matchcompiler.py
+++ b/tools/matchcompiler.py
@@ -16,7 +16,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
-import io
import os
import sys
import re
@@ -189,8 +188,8 @@ def _compileCmd(tok):
elif (len(tok) > 2) and (tok[0] == "%"):
print("unhandled:" + tok)
elif tok in tokTypes:
- cond = ' || '.join(['tok->tokType() == Token::{}'.format(tokType) for tokType in tokTypes[tok]])
- return '(({cond}) && tok->str() == MatchCompiler::makeConstString("{tok}"))'.format(cond=cond, tok=tok)
+ cond = ' || '.join([f'tok->tokType() == Token::{tokType}' for tokType in tokTypes[tok]])
+ return f'(({cond}) && tok->str() == MatchCompiler::makeConstString("{tok}"))'
return (
'(tok->str() == MatchCompiler::makeConstString("' + tok + '"))'
)
@@ -679,11 +678,11 @@ def _replaceCStrings(self, line):
def convertFile(self, srcname, destname, line_directive):
self._reset()
- fin = io.open(srcname, "rt", encoding="utf-8")
+ fin = open(srcname, encoding="utf-8")
srclines = fin.readlines()
fin.close()
- code = u''
+ code = ''
modified = False
@@ -708,22 +707,22 @@ def convertFile(self, srcname, destname, line_directive):
code += line
# Compute matchFunctions
- strFunctions = u''
+ strFunctions = ''
for function in self._rawMatchFunctions:
strFunctions += function
- lineno = u''
+ lineno = ''
if line_directive:
- lineno = u'#line 1 "' + srcname + '"\n'
+ lineno = '#line 1 "' + srcname + '"\n'
- header = u'#include "matchcompiler.h"\n'
- header += u'#include \n'
- header += u'#include \n'
+ header = '#include "matchcompiler.h"\n'
+ header += '#include \n'
+ header += '#include \n'
if len(self._rawMatchFunctions):
- header += u'#include "errorlogger.h"\n'
- header += u'#include "token.h"\n'
+ header += '#include "errorlogger.h"\n'
+ header += '#include "token.h"\n'
- fout = io.open(destname, 'wt', encoding="utf-8")
+ fout = open(destname, 'w', encoding="utf-8")
if modified or len(self._rawMatchFunctions):
fout.write(header)
fout.write(strFunctions)
diff --git a/tools/parse-glibc.py b/tools/parse-glibc.py
index a56c4c96550..a757d4c35ca 100644
--- a/tools/parse-glibc.py
+++ b/tools/parse-glibc.py
@@ -33,15 +33,15 @@ def checknonnull(cfg, functionName, nonnull):
def parseheader(cppcheckpath, filename):
- f = open(filename, 'rt')
+ f = open(filename)
data = f.read()
f.close()
- f = open(cppcheckpath + '/cfg/std.cfg', 'rt')
+ f = open(cppcheckpath + '/cfg/std.cfg')
stdcfg = f.read()
f.close()
- f = open(cppcheckpath + '/cfg/posix.cfg', 'rt')
+ f = open(cppcheckpath + '/cfg/posix.cfg')
posixcfg = f.read()
f.close()
diff --git a/tools/reduce.py b/tools/reduce.py
index 595aaff18c8..14de6b8c29c 100755
--- a/tools/reduce.py
+++ b/tools/reduce.py
@@ -75,11 +75,11 @@ class TimeoutExpired(Exception):
else:
# Something could be wrong, for example the command line for Cppcheck (CMD).
# Print the output to give a hint how to fix it.
- print('Error: {}\n{}'.format(comm[0], comm[1]))
+ print(f'Error: {comm[0]}\n{comm[1]}')
return False
def __writefile(self, filename, filedata):
- f = open(filename, 'wt')
+ f = open(filename, 'w')
for line in filedata:
f.write(line)
f.close()
@@ -316,9 +316,9 @@ def show_syntax():
sys.exit(1)
elapsed_time = time.time() - t
reduce.set_elapsed_time(elapsed_time)
- print('elapsed_time: {}'.format(elapsed_time))
+ print(f'elapsed_time: {elapsed_time}')
- with open(arg_file, 'rt') as f:
+ with open(arg_file) as f:
filedata = f.readlines()
reduce.writeorigfile(filedata)
diff --git a/tools/test-my-pr.py b/tools/test-my-pr.py
index 715df3297bb..f5a535301b0 100755
--- a/tools/test-my-pr.py
+++ b/tools/test-my-pr.py
@@ -16,7 +16,7 @@
def format_float(a, b=1):
if a > 0 and b > 0:
- return '{:.2f}'.format(a / b)
+ return f'{a / b:.2f}'
return 'N/A'
@@ -66,14 +66,14 @@ def format_float(a, b=1):
lib.clone_cppcheck(repo_dir, old_repo_dir)
pass
except Exception as e:
- print('Failed to clone Cppcheck repository ({}), retry later'.format(e))
+ print(f'Failed to clone Cppcheck repository ({e}), retry later')
sys.exit(1)
try:
lib.checkout_cppcheck_version(repo_dir, 'main', main_dir)
pass
except Exception as e:
- print('Failed to checkout main ({}), retry later'.format(e))
+ print(f'Failed to checkout main ({e}), retry later')
sys.exit(1)
try:
@@ -91,7 +91,7 @@ def format_float(a, b=1):
subprocess.check_call(['git', 'fetch', '--depth=1', 'origin', commit_id])
subprocess.check_call(['git', 'checkout', '-f', commit_id])
except BaseException as e:
- print('Error: {}'.format(e))
+ print(f'Error: {e}')
print('Failed to switch to common ancestor of your branch and main')
sys.exit(1)
diff --git a/tools/trac-keywords.py b/tools/trac-keywords.py
index 3c0027a9f62..f11af4e240d 100644
--- a/tools/trac-keywords.py
+++ b/tools/trac-keywords.py
@@ -1,4 +1,3 @@
-
import subprocess
import sys