Skip to content

Commit b472b4e

Browse files
authored
some Python cleanups based on PyCharm inspections (danmar#2999)
* some Python cleanups based on PyCharm inspections * test-helloworld.py: adjusted assert in test_addon_relative_path()
1 parent 3ec6e85 commit b472b4e

17 files changed

+40
-64
lines changed

addons/cert.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ def str05(data):
314314
# STR07-C
315315
# Use the bounds-checking interfaces for string manipulation
316316
def str07(data):
317-
if(data.standards.c=='c89' or data.standards.c=='c99'):
317+
if data.standards.c=='c89' or data.standards.c=='c99':
318318
return
319319
for token in data.tokenlist:
320320
if not isFunctionCall(token, ('strcpy', 'strcat')):
@@ -324,7 +324,7 @@ def str07(data):
324324
continue
325325
if args[1].isString:
326326
continue
327-
reportError(token, 'style', 'Use the bounds-checking interfaces %s_s()' % (token.str), 'STR07-C')
327+
reportError(token, 'style', 'Use the bounds-checking interfaces %s_s()' % token.str, 'STR07-C')
328328

329329
# STR11-C
330330
# Do not specify the bound of a character array initialized with a string literal

addons/misra.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import argparse
2424
import codecs
2525
import string
26-
from collections import defaultdict
2726

2827
try:
2928
from itertools import izip as zip
@@ -1119,7 +1118,7 @@ def get_num_significant_naming_chars(self, cfg):
11191118
def misra_2_7(self, data):
11201119
for func in data.functions:
11211120
# Skip function with no parameter
1122-
if (len(func.argument) == 0):
1121+
if len(func.argument) == 0:
11231122
continue
11241123
# Setup list of function parameters
11251124
func_param_list = list()
@@ -1130,11 +1129,11 @@ def misra_2_7(self, data):
11301129
if (scope.type == "Function") and (scope.function == func):
11311130
# Search function body: remove referenced function parameter from list
11321131
token = scope.bodyStart
1133-
while (token.next != None and token != scope.bodyEnd and len(func_param_list) > 0):
1134-
if (token.variable != None and token.variable in func_param_list):
1132+
while token.next is not None and token != scope.bodyEnd and len(func_param_list) > 0:
1133+
if token.variable is not None and token.variable in func_param_list:
11351134
func_param_list.remove(token.variable)
11361135
token = token.next
1137-
if (len(func_param_list) > 0):
1136+
if len(func_param_list) > 0:
11381137
# At least one parameter has not been referenced in function body
11391138
self.reportError(func.tokenDef, 2, 7)
11401139

@@ -3074,7 +3073,6 @@ def executeCheck(self, rule_num, check_function, *args):
30743073
check_function(*args)
30753074

30763075
def parseDump(self, dumpfile):
3077-
filename = '.'.join(dumpfile.split('.')[:-1])
30783076
data = cppcheckdata.parsedump(dumpfile)
30793077

30803078
typeBits['CHAR'] = data.platform.char_bit

addons/misra_9.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def __init__(self, elementType, name, valueType, dimensions = None):
1313
self.numInits = 0
1414
self.childIndex = -1
1515

16+
self.flexibleToken = None
1617
self.isFlexible = False
1718
self.structureViolationToken = None
1819

@@ -24,7 +25,7 @@ def __repr__(self):
2425
inits += 'D'
2526
if not (self.isPositional or self.isDesignated) and self.numInits == 0:
2627
inits += '_'
27-
if (self.numInits > 1):
28+
if self.numInits > 1:
2829
inits += str(self.numInits)
2930

3031
attrs = ["childIndex", "elementType", "valueType"]
@@ -59,7 +60,7 @@ def getInitDump(self):
5960
t.append('D')
6061
if self.numInits == 0:
6162
t.append('_')
62-
if (self.numInits > 1):
63+
if self.numInits > 1:
6364
t.append(str(self.numInits))
6465

6566
myDump = "".join(t)
@@ -165,7 +166,7 @@ def markStuctureViolation(self, token):
165166
self.structureViolationToken = token
166167

167168
def markAsFlexibleArray(self, token):
168-
self.flexibleToken = token;
169+
self.flexibleToken = token
169170
self.isFlexible = True
170171

171172
def markAsCurrent(self):
@@ -371,7 +372,7 @@ def unwindAndContinue(self):
371372

372373
self.root = self.root.parent
373374

374-
if self.token.astParent == None:
375+
if self.token.astParent is None:
375376
self.token = None
376377
break
377378

addons/test/test-misra.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import pytest
1111
import re
1212
import sys
13-
import subprocess
1413

1514
from .util import dump_create, dump_remove, convert_json_output
1615

htmlreport/cppcheck-htmlreport

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ if __name__ == '__main__':
491491
with io.open(source_filename, 'r', encoding=options.source_encoding) as input_file:
492492
content = input_file.read()
493493
except IOError:
494-
if (error['id'] == 'unmatchedSuppression'):
494+
if error['id'] == 'unmatchedSuppression':
495495
continue # file not found, bail out
496496
else:
497497
sys.stderr.write("ERROR: Source file '%s' not found.\n" %
@@ -592,13 +592,13 @@ if __name__ == '__main__':
592592
output_file.write('\n <tr><th>Line</th><th>Id</th><th>CWE</th><th>Severity</th><th>Message</th></tr>')
593593
for filename, data in sorted(files.items()):
594594
if filename in decode_errors: # don't print a link but a note
595-
output_file.write("\n <tr><td colspan=\"5\">%s</td></tr>" % (filename))
595+
output_file.write("\n <tr><td colspan=\"5\">%s</td></tr>" % filename)
596596
output_file.write("\n <tr><td colspan=\"5\"> Could not generated due to UnicodeDecodeError</td></tr>")
597597
else:
598598
if filename.endswith('*'): # assume unmatched suppression
599599
output_file.write(
600600
"\n <tr><td colspan=\"5\">%s</td></tr>" %
601-
(filename))
601+
filename)
602602
else:
603603
output_file.write(
604604
"\n <tr><td colspan=\"5\"><a href=\"%s\">%s</a></td></tr>" %
@@ -640,7 +640,7 @@ if __name__ == '__main__':
640640
output_file.write('\n </table>')
641641
output_file.write(HTML_FOOTER % contentHandler.versionCppcheck)
642642

643-
if (decode_errors):
643+
if decode_errors:
644644
sys.stderr.write("\nGenerating html failed for the following files: " + ' '.join(decode_errors))
645645
sys.stderr.write("\nConsider changing source-encoding (for example: \"htmlreport ... --source-encoding=\"iso8859-1\"\"\n")
646646

@@ -653,7 +653,7 @@ if __name__ == '__main__':
653653
stats_countlist = {}
654654

655655
for filename, data in sorted(files.items()):
656-
if (filename == ''):
656+
if filename == '':
657657
continue
658658
stats_tmplist = []
659659
for error in sorted(data['errors'], key=lambda k: k['line']):
@@ -679,11 +679,11 @@ if __name__ == '__main__':
679679
for filename in stats_countlist:
680680
try: # also bail out if we have a file with no sev-results
681681
_sum += stats_countlist[filename][sev]
682-
stats_templist[filename] = (int)(stats_countlist[filename][sev]) # file : amount,
682+
stats_templist[filename] = int(stats_countlist[filename][sev]) # file : amount,
683683
except KeyError:
684684
continue
685685
# don't print "0 style" etc, if no style warnings were found
686-
if (_sum == 0):
686+
if _sum == 0:
687687
continue
688688
except KeyError:
689689
continue
@@ -697,12 +697,12 @@ if __name__ == '__main__':
697697
for i in stats_list_sorted: # printing loop
698698
# for aesthetics: if it's the first iteration of the loop, get
699699
# the max length of the number string
700-
if (it == 0):
700+
if it == 0:
701701
LENGTH = len(str(i[1])) # <- length of longest number, now get the difference and try to make other numbers align to it
702702

703703
stats_file.write("&#160;" * 3 + str(i[1]) + "&#160;" * (1 + LENGTH - len(str(i[1]))) + "<a href=\"" + files[i[0]]['htmlfile'] + "\"> " + i[0] + "</a><br>\n")
704704
it += 1
705-
if (it == 10): # print only the top 10
705+
if it == 10: # print only the top 10
706706
break
707707
stats_file.write("</p>\n")
708708

htmlreport/test_htmlreport.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def runCheck(source_filename=None, xml_version='1', xml_filename=None):
106106
with open(os.path.join(output_directory, 'index.html')) as index_file:
107107
index_contents = index_file.read()
108108

109-
yield (index_contents, output_directory)
109+
yield index_contents, output_directory
110110

111111
shutil.rmtree(output_directory)
112112

test/bug-hunting/cve.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import glob
44
import logging
55
import os
6-
import re
7-
import shutil
86
import sys
97
import subprocess
108

test/bug-hunting/itc.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# https://github.com/regehr/itc-benchmarks
44

55

6-
import glob
76
import os
87
import re
98
import shutil
@@ -82,7 +81,7 @@ def check(filename):
8281
missing = []
8382
for w in wanted:
8483
if w not in actual:
85-
missing.append(w);
84+
missing.append(w)
8685
if len(missing) > 0:
8786
print('wanted:' + str(wanted))
8887
print('actual:' + str(actual))

test/cli/test-clang-import.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import re
66
import subprocess
7-
from testutils import create_gui_project_file, cppcheck
7+
from testutils import cppcheck
88

99

1010
def get_debug_section(title, stdout):

test/cli/test-helloworld.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def cppcheck_local(args):
1111
os.chdir('helloworld')
1212
ret, stdout, stderr = cppcheck(args)
1313
os.chdir(cwd)
14-
return (ret, stdout, stderr)
14+
return ret, stdout, stderr
1515

1616
def getRelativeProjectPath():
1717
return 'helloworld'
@@ -24,7 +24,7 @@ def getAbsoluteProjectPath():
2424
def getVsConfigs(stdout, filename):
2525
ret = []
2626
for line in stdout.split('\n'):
27-
if not line.startswith('Checking %s ' % (filename)):
27+
if not line.startswith('Checking %s ' % filename):
2828
continue
2929
if not line.endswith('...'):
3030
continue
@@ -38,7 +38,7 @@ def test_relative_path():
3838
ret, stdout, stderr = cppcheck(['--template=cppcheck1', 'helloworld'])
3939
filename = os.path.join('helloworld', 'main.c')
4040
assert ret == 0
41-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
41+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
4242

4343

4444
def test_local_path():
@@ -51,7 +51,7 @@ def test_absolute_path():
5151
ret, stdout, stderr = cppcheck(['--template=cppcheck1', prjpath])
5252
filename = os.path.join(prjpath, 'main.c')
5353
assert ret == 0
54-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
54+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
5555

5656
def test_addon_local_path():
5757
ret, stdout, stderr = cppcheck_local(['--addon=misra', '--template=cppcheck1', '.'])
@@ -72,31 +72,30 @@ def test_addon_relative_path():
7272
ret, stdout, stderr = cppcheck(['--addon=misra', '--template=cppcheck1', prjpath])
7373
filename = os.path.join(prjpath, 'main.c')
7474
assert ret == 0
75-
assert stdout == 'Checking %s ...\n' % (filename)
75+
assert stdout == ('Checking %s ...\n'
76+
'Checking %s: SOME_CONFIG...\n' % (filename, filename))
7677
assert stderr == ('[%s:5]: (error) Division by zero.\n'
7778
'[%s:1]: (style) misra violation (use --rule-texts=<file> to get proper output)\n' % (filename, filename))
7879

79-
def test_addon_relative_path():
80+
def test_addon_with_gui_project():
8081
project_file = 'helloworld/test.cppcheck'
8182
create_gui_project_file(project_file, paths=['.'], addon='misra')
8283
ret, stdout, stderr = cppcheck(['--template=cppcheck1', '--project=' + project_file])
8384
filename = os.path.join('helloworld', 'main.c')
8485
assert ret == 0
85-
assert stdout == 'Checking %s ...\n' % (filename)
86+
assert stdout == 'Checking %s ...\n' % filename
8687
assert stderr == ('[%s:5]: (error) Division by zero.\n'
8788
'[%s:1]: (style) misra violation (use --rule-texts=<file> to get proper output)\n' % (filename, filename))
8889

8990
def test_basepath_relative_path():
9091
prjpath = getRelativeProjectPath()
9192
ret, stdout, stderr = cppcheck([prjpath, '--template=cppcheck1', '-rp=' + prjpath])
92-
filename = os.path.join(prjpath, 'main.c')
9393
assert ret == 0
9494
assert stderr == '[main.c:5]: (error) Division by zero.\n'
9595

9696
def test_basepath_absolute_path():
9797
prjpath = getAbsoluteProjectPath()
9898
ret, stdout, stderr = cppcheck(['--template=cppcheck1', prjpath, '-rp=' + prjpath])
99-
filename = os.path.join(prjpath, 'main.c')
10099
assert ret == 0
101100
assert stderr == '[main.c:5]: (error) Division by zero.\n'
102101

@@ -112,15 +111,15 @@ def test_vs_project_relative_path():
112111
filename = os.path.join(prjpath, 'main.c')
113112
assert ret == 0
114113
assert getVsConfigs(stdout, filename) == 'Debug|Win32 Debug|x64 Release|Win32 Release|x64'
115-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
114+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
116115

117116
def test_vs_project_absolute_path():
118117
prjpath = getAbsoluteProjectPath()
119118
ret, stdout, stderr = cppcheck(['--template=cppcheck1', '--project=' + os.path.join(prjpath, 'helloworld.vcxproj')])
120119
filename = os.path.join(prjpath, 'main.c')
121120
assert ret == 0
122121
assert getVsConfigs(stdout, filename) == 'Debug|Win32 Debug|x64 Release|Win32 Release|x64'
123-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
122+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
124123

125124
def test_cppcheck_project_local_path():
126125
ret, stdout, stderr = cppcheck_local(['--template=cppcheck1', '--platform=win64', '--project=helloworld.cppcheck'])
@@ -134,15 +133,15 @@ def test_cppcheck_project_relative_path():
134133
filename = os.path.join(prjpath, 'main.c')
135134
assert ret == 0
136135
assert getVsConfigs(stdout, filename) == 'Debug|x64'
137-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
136+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
138137

139138
def test_cppcheck_project_absolute_path():
140139
prjpath = getAbsoluteProjectPath()
141140
ret, stdout, stderr = cppcheck(['--template=cppcheck1', '--platform=win64', '--project=' + os.path.join(prjpath, 'helloworld.cppcheck')])
142141
filename = os.path.join(prjpath, 'main.c')
143142
assert ret == 0
144143
assert getVsConfigs(stdout, filename) == 'Debug|x64'
145-
assert stderr == '[%s:5]: (error) Division by zero.\n' % (filename)
144+
assert stderr == '[%s:5]: (error) Division by zero.\n' % filename
146145

147146
def test_suppress_command_line():
148147
prjpath = getRelativeProjectPath()

0 commit comments

Comments
 (0)