提交 3ed6d8ef 编写于 作者: C Cleber Rosa

Lint: enable W0612 and W0622 checks

These warnings are described as:

 W0612: Used when a variable is defined but not used.
 W0622: Used when a variable or function override a built-in.

After a suggestion from Andrei Stepanov, we decided to immediately
enable these.

Rerefence: https://pagure.io/standard-test-roles/pull-request/144
Reference: https://trello.com/c/Ohh7Q6qj/1183-enable-w-in-travis-make-checkSigned-off-by: NCleber Rosa <crosa@redhat.com>
上级 0efbc030
......@@ -811,7 +811,7 @@ class FileLoader(TestLoader):
mt_tags = safeloader.get_docstring_directives_tags(docstring)
mt_tags.update(class_tags)
methods = [method for method, tags in methods_info]
methods = [method for method, _ in methods_info]
if st.name not in methods:
methods_info.append((st.name, mt_tags))
......
......@@ -529,7 +529,6 @@ class TestRunner(object):
"test %s to not to fill variants."
% (variant, template))
raise NotImplementedError(msg)
params = klass_parameters["params"]
variant_id = varianter.generate_variant_id(var)
return template, {"variant": var,
"variant_id": variant_id,
......
......@@ -136,7 +136,6 @@ def find_class_and_methods(path, method_pattern=None, base_class=None):
result = {}
with open(path) as source_file:
mod = ast.parse(source_file.read(), path)
modules = modules_imported_as(mod)
for statement in mod.body:
if isinstance(statement, ast.ClassDef):
......
......@@ -408,7 +408,7 @@ class Test(unittest.TestCase, TestData):
except EnvironmentError:
pass
else:
self.log.debug(" teststmpdir: %s", self.teststmpdir)
self.log.debug(" teststmpdir: %s", teststmpdir)
self.log.debug(" workdir: %s", self.workdir)
unittest.TestCase.__init__(self, methodName=methodName)
......
......@@ -117,7 +117,7 @@ class DistroPkgInfoLoader(object):
calling :meth:`load_package_info` if it's so.
"""
packages_info = set()
for dirpath, dirnames, filenames in os.walk(self.path):
for dirpath, _, filenames in os.walk(self.path):
for filename in filenames:
path = os.path.join(dirpath, filename)
if self.is_software_package(path):
......
......@@ -55,10 +55,6 @@ class TAPResult(ResultEvents):
description = "TAP - Test Anything Protocol results"
def __init__(self, args):
def silent(msg, *writeargs):
pass
self.__logs = []
self.__open_files = []
output = getattr(args, 'tap', None)
......
......@@ -164,7 +164,6 @@ class Asset(object):
def _compute_hash(self):
result = crypto.hash_file(self.asset_file, algorithm=self.algorithm)
basename = os.path.basename(self.asset_file)
with open(self.hashfile, 'w') as f:
f.write('%s %s\n' % (self.algorithm, result))
......
......@@ -244,7 +244,7 @@ def time_to_seconds(time):
seconds = int(time[:-1]) * mult
else:
seconds = int(time)
except (ValueError, TypeError) as e:
except (ValueError, TypeError):
raise ValueError("Invalid value '%s' for time. Use a string with "
"the number and optionally the time unit (s, m, "
"h or d)." % time)
......
......@@ -37,8 +37,8 @@ def compare(a, b):
def __private():
class Token:
def __init__(self, type, value=None):
self.type = type
def __init__(self, token_type, value=None):
self.type = token_type
self.value = value
def __cmp__(self, o):
......@@ -49,8 +49,8 @@ def __private():
class AST:
def __init__(self, type):
self.type = type
def __init__(self, ast_type):
self.type = ast_type
self._kids = []
def __getitem__(self, i):
......@@ -67,9 +67,9 @@ def __private():
class GdbMiScannerBase(spark.GenericScanner):
def tokenize(self, input):
def tokenize(self, input_message):
self.rv = []
spark.GenericScanner.tokenize(self, input)
spark.GenericScanner.tokenize(self, input_message)
return self.rv
def t_nl(self, s):
......@@ -166,14 +166,14 @@ def __private():
rv.value = token.value
return rv
def nonterminal(self, type, args):
def nonterminal(self, token_type, args):
# Flatten AST a bit by not making nodes if there's only one child.
exclude = [
'record_list'
]
if len(args) == 1 and type not in exclude:
return args[0]
return spark.GenericASTBuilder.nonterminal(self, type, args)
return spark.GenericASTBuilder.nonterminal(self, token_type, args)
def error(self, token, i=0, tokens=None):
if i > 2:
......@@ -189,7 +189,7 @@ def __private():
spark.GenericASTTraversal.__init__(self, ast)
self.postorder()
def __translate_type(self, type):
def __translate_type(self, token_type):
table = {
'^': 'result',
'=': 'notify',
......@@ -199,7 +199,7 @@ def __private():
'@': 'target',
'&': 'log'
}
return table[type]
return table[token_type]
def n_result(self, node):
# result ::= variable = value
......@@ -362,16 +362,16 @@ def __private():
(__the_scanner, __the_parser, __the_interpreter, __the_output) = __private()
def scan(input):
return __the_scanner.tokenize(input)
def scan(input_message):
return __the_scanner.tokenize(input_message)
def parse(tokens):
return __the_parser.parse(tokens)
def process(input):
tokens = scan(input)
def process(input_message):
tokens = scan(input_message)
ast = parse(tokens)
__the_interpreter(ast)
return __the_output(ast.value)
......@@ -358,7 +358,7 @@ class GenericParser:
return self._NULLABLE == sym[0:len(self._NULLABLE)]
def skip(self, lhs_rhs, pos=0):
lhs, rhs = lhs_rhs
_, rhs = lhs_rhs
n = len(rhs)
while pos < n:
if not self.isnullable(rhs[pos]):
......@@ -374,7 +374,7 @@ class GenericParser:
#
kitems = []
for rule, pos in self.states[state].items:
lhs, rhs = rule
_, rhs = rule
if rhs[pos:pos + 1] == (sym,):
kitems.append((rule, self.skip(rule, pos + 1)))
core = kitems
......@@ -398,7 +398,7 @@ class GenericParser:
worklist = X.items
for item in worklist:
rule, pos = item
lhs, rhs = rule
_, rhs = rule
if pos == len(rhs):
X.complete.append(rule)
continue
......@@ -474,19 +474,19 @@ class GenericParser:
rv.append(self.goto(state, t))
return rv
def add(self, set, item, i=None, predecessor=None, causal=None):
def add(self, input_set, item, i=None, predecessor=None, causal=None):
if predecessor is None:
if item not in set:
set.append(item)
if item not in input_set:
input_set.append(item)
else:
key = (item, i)
if item not in set:
if item not in input_set:
self.links[key] = []
set.append(item)
input_set.append(item)
self.links[key].append((predecessor, causal))
def makeSet(self, token, sets, i):
cur, next = sets[i], sets[i + 1]
cur, next_item = sets[i], sets[i + 1]
ttype = token is not None and self.typestring(token) or None
if ttype is not None:
......@@ -500,16 +500,16 @@ class GenericParser:
add = fn(state, arg)
for k in add:
if k is not None:
self.add(next, (k, parent), i + 1, ptr)
self.add(next_item, (k, parent), i + 1, ptr)
nk = self.goto(k, None)
if nk is not None:
self.add(next, (nk, i + 1))
self.add(next_item, (nk, i + 1))
if parent == i:
continue
for rule in self.states[state].complete:
lhs, rhs = rule
lhs, _ = rule
for pitem in sets[parent]:
pstate, pparent = pitem
k = self.goto(pstate, lhs)
......@@ -529,7 +529,7 @@ class GenericParser:
# then duplicates and inlines code to boost speed at the
# cost of extreme ugliness.
#
cur, next = sets[i], sets[i + 1]
cur, next_item = sets[i], sets[i + 1]
ttype = token is not None and self.typestring(token) or None
for item in cur:
......@@ -542,9 +542,9 @@ class GenericParser:
#INLINED --v
new = (k, parent)
key = (new, i + 1)
if new not in next:
if new not in next_item:
self.links[key] = []
next.append(new)
next_item.append(new)
self.links[key].append((ptr, None))
#INLINED --^
#nk = self.goto(k, None)
......@@ -553,24 +553,24 @@ class GenericParser:
#self.add(next, (nk, i+1))
#INLINED --v
new = (nk, i + 1)
if new not in next:
next.append(new)
if new not in next_item:
next_item.append(new)
#INLINED --^
else:
add = self.gotoST(state, token)
for k in add:
if k is not None:
self.add(next, (k, parent), i + 1, ptr)
self.add(next_item, (k, parent), i + 1, ptr)
#nk = self.goto(k, None)
nk = self.edges.get((k, None), None)
if nk is not None:
self.add(next, (nk, i + 1))
self.add(next_item, (nk, i + 1))
if parent == i:
continue
for rule in self.states[state].complete:
lhs, rhs = rule
lhs, _ = rule
for pitem in sets[parent]:
pstate, pparent = pitem
#k = self.goto(pstate, lhs)
......@@ -610,7 +610,7 @@ class GenericParser:
return links[0][1]
choices = []
rule2cause = {}
for p, c in links:
for _, c in links:
rule = c[2]
choices.append(rule)
rule2cause[rule] = c
......@@ -631,7 +631,7 @@ class GenericParser:
return self.rule2func[self.new2old[rule]](attr)
def buildTree(self, nt, item, tokens, k):
state, parent = item
state, _ = item
choices = []
for rule in self.states[state].complete:
......@@ -672,21 +672,21 @@ class GenericParser:
sortlist = []
name2index = {}
for i in range(len(rules)):
lhs, rhs = rule = rules[i]
_, rhs = rule = rules[i]
name = self.rule2name[self.new2old[rule]]
sortlist.append((len(rhs), name))
name2index[name] = i
sortlist.sort()
list = map(lambda a, b: b, sortlist)
return rules[name2index[self.resolve(list)]]
result_list = map(lambda a, b: b, sortlist)
return rules[name2index[self.resolve(result_list)]]
def resolve(self, list):
def resolve(self, input_list):
#
# Resolve ambiguity in favor of the shortest RHS.
# Since we walk the tree from the top down, this
# should effectively resolve in favor of a "shift".
#
return list[0]
return input_list[0]
#
# GenericASTBuilder automagically constructs a concrete/abstract syntax tree
......@@ -706,7 +706,7 @@ class GenericASTBuilder(GenericParser):
def preprocess(self, rule, func):
rebind = (lambda lhs, self=self:
lambda args, lhs=lhs, self=self: self.buildASTNode(args, lhs))
lhs, rhs = rule
lhs, _ = rule
return rule, rebind(lhs)
def buildASTNode(self, args, lhs):
......@@ -721,8 +721,8 @@ class GenericASTBuilder(GenericParser):
def terminal(self, token):
return token
def nonterminal(self, type, args):
rv = self.AST(type)
def nonterminal(self, token_type, args):
rv = self.AST(token_type)
rv[:len(args)] = args
return rv
......@@ -840,11 +840,11 @@ class GenericASTMatcher(GenericParser):
self.match_r(ast)
self.parse(self.input)
def resolve(self, list):
def resolve(self, input_list):
#
# Resolve ambiguity in favor of the longest RHS.
#
return list[-1]
return input_list[-1]
def _dump(tokens, sets, states):
......
......@@ -221,19 +221,20 @@ def string_to_hex(text):
return "".join(map(format_as_hex, text))
def remote_checksum(input):
def remote_checksum(input_message):
"""
Calculates a remote message checksum
:param input: the message input payload, without the start and end markers
:type input: str
:param input_message: the message input payload, without the start and end
markers
:type input_message: str
:returns: two digit checksum
:rtype: str
"""
sum = 0
for i in input:
sum += ord(i)
result = sum % 256
total = 0
for i in input_message:
total += ord(i)
result = total % 256
hexa = "%2x" % result
return hexa.lower()
......@@ -775,7 +776,7 @@ class GDBRemote(object):
raise NotConnectedError
data = remote_encode(command_data)
sent = self._socket.send(data)
self._socket.send(data)
if not self.no_ack_mode:
transmission_result = self._socket.recv(1)
......
......@@ -197,7 +197,7 @@ def write_file_or_fail(filename, data):
"""
fd = os.open(filename, os.O_WRONLY)
try:
ret = os.write(fd, data)
os.write(fd, data)
except OSError as details:
raise GenIOError("The write to %s failed: %s" % (
filename, details))
......@@ -1087,7 +1087,7 @@ class GDBSubProcess(object):
self.gdb.set_break(b, ignore_error=True)
self._run_pre_commands()
result = self.gdb.run(self.args[1:])
self.gdb.run(self.args[1:])
# Collect gdbserver stdout and stderr file information for debugging
# based on its process ID and stream (stdout or stderr)
......
......@@ -356,7 +356,7 @@ class _ServiceResultParser(object):
:type command_list: list
"""
self.commands = command_list
for command, requires_root in self.commands:
for command, _ in self.commands:
setattr(self, command, result_parser(command))
@staticmethod
......@@ -391,7 +391,7 @@ class _ServiceCommandGenerator(object):
:type command_list: list
"""
self.commands = command_list
for command, requires_root in self.commands:
for command, _ in self.commands:
setattr(self, command, command_generator(command))
......
......@@ -1142,8 +1142,7 @@ def main():
parser.add_option('--verbose', dest="debug", action='store_true',
help='include debug messages in console output')
options, args = parser.parse_args()
debug = options.debug
_, args = parser.parse_args()
software_manager = SoftwareManager()
if args:
action = args[0]
......
......@@ -148,7 +148,7 @@ extensions = ['sphinx.ext.autodoc',
master_doc = 'index'
project = u'Avocado'
copyright = u'2014-2015, Red Hat'
copyright = u'2014-2015, Red Hat' # pylint: disable=W0622
version_file = os.path.join(root_path, 'VERSION')
VERSION = genio.read_file(version_file).strip()
......
......@@ -196,7 +196,7 @@ class GdbTest(Test):
g = gdb.GDB()
# Do 100 cycle of target (kind of connects) and disconnects
for i in range(0, 100):
for _ in range(0, 100):
cmd = '-target-select extended-remote :%s' % s.port
r = g.cmd(cmd)
self.assertEqual(r.result.class_, 'connected')
......@@ -221,7 +221,7 @@ class GdbTest(Test):
s = gdb.GDBServer()
g = gdb.GDB()
for i in range(0, 100):
for _ in range(0, 100):
r = g.connect(s.port)
self.assertEqual(r.result.class_, 'connected')
r = g.disconnect()
......
......@@ -496,7 +496,6 @@ class RemoteTestRunner(TestRunner):
paramiko_logger = logging.getLogger('paramiko')
fabric_logger = logging.getLogger('avocado.fabric')
remote_logger = logging.getLogger('avocado.remote')
app_logger = logging.getLogger('avocado.debug')
fmt = ('%(asctime)s %(module)-10.10s L%(lineno)-.4d %('
'levelname)-5.5s| %(message)s')
formatter = logging.Formatter(fmt=fmt, datefmt='%H:%M:%S')
......
......@@ -332,7 +332,7 @@ class VM(object):
ipversion = libvirt.VIR_IP_ADDR_TYPE_IPV4
ifaces = self.domain.interfaceAddresses(querytype)
for iface, data in iteritems(ifaces):
for _, data in iteritems(ifaces):
if data['addrs'] and data['hwaddr'] != '00:00:00:00:00:00':
ip_addr = data['addrs'][0]['addr']
ip_type = data['addrs'][0]['type']
......
......@@ -137,8 +137,7 @@ class MultiplexTests(unittest.TestCase):
cmd_line = ("%s run --job-results-dir %s -m optional_plugins/"
"varianter_yaml_to_mux/tests/.data/empty_file -- "
"passtest.py" % (AVOCADO, self.tmpdir))
result = self.run_and_check(cmd_line, exit_codes.AVOCADO_ALL_OK,
(1, 0))
self.run_and_check(cmd_line, exit_codes.AVOCADO_ALL_OK, (1, 0))
def test_run_mplex_params(self):
for variant_msg in (('/run/short', 'A'),
......
......@@ -228,7 +228,8 @@ class TestMuxTree(unittest.TestCase):
variant1 = next(iter(mux1))
variant2 = next(iter(mux2))
self.assertNotEqual(variant1, variant2)
str_variant = str(variant1)
# test variant __str__()
str(variant1)
variant_list = []
for item in variant1:
variant_list.append("'%s': '%s'" % (item, variant1[item]))
......
......@@ -135,7 +135,7 @@ class App(object):
journal = sqlite3.connect(self.args.journal_path)
journal_cursor = journal.cursor()
flush_result = journal_cursor.execute(flush_sql)
journal_cursor.execute(flush_sql)
journal.commit()
journal_cursor.close()
journal.close()
......
......@@ -163,7 +163,7 @@ results_dir_content() {
if [ "$TRAVIS" == "true" ]; then
run_rc lint 'RESULT=$(mktemp); inspekt lint --exclude=.git --enable W0102,W0611 &>$RESULT || { cat $RESULT; rm $RESULT; exit -1; }; rm $RESULT'
else
run_rc lint 'inspekt lint --exclude=.git --enable W0102,W0611'
run_rc lint 'inspekt lint --exclude=.git --enable W0102,W0611,W0612,W0622'
fi
# Skip checking test_utils_cpu.py due to inspektor bug
run_rc indent 'inspekt indent --exclude=.git,selftests/unit/test_utils_cpu.py'
......
......@@ -47,7 +47,7 @@ def has_snakefood():
with open(os.devnull, 'w') as null:
try:
cmd = ['sfood', '-h']
res = subprocess.call(cmd, stdout=null)
subprocess.call(cmd, stdout=null)
except Exception as e:
print("Could not find sfood utility: %s: %s" % (cmd, e), file=sys.stderr)
print("Did you forget to 'pip install snakefood'?", file=sys.stderr)
......
......@@ -491,7 +491,7 @@ class RunnerOperationTest(unittest.TestCase):
try:
avocado_process.start()
link = os.path.join(self.tmpdir, 'latest')
for trial in range(0, 50):
for _ in range(0, 50):
time.sleep(0.1)
if os.path.exists(link) and os.path.islink(link):
avocado_process.wait()
......@@ -755,7 +755,7 @@ class RunnerSimpleTest(unittest.TestCase):
cmd_line = ("%s --show all --config %s run --job-results-dir %s "
"--sysinfo=on --external-runner %s -- \"'\\\"\\/|?*<>'\""
% (AVOCADO, config_path, self.tmpdir, GNU_ECHO_BINARY))
result = process.run(cmd_line)
process.run(cmd_line)
self.assertTrue(os.path.exists(os.path.join(self.tmpdir, "latest",
"test-results",
"1-\'________\'/")))
......
......@@ -114,7 +114,7 @@ class OutputCheckOnOff(Test):
def image_output_uncapable():
try:
import PIL
import PIL # pylint: disable=W0612
return False
except ImportError:
return True
......
......@@ -41,7 +41,7 @@ class ReplayFailfastTests(unittest.TestCase):
'--job-results-dir %s --sysinfo=off'
% (AVOCADO, self.jobid, self.tmpdir))
expected_rc = exit_codes.AVOCADO_TESTS_FAIL | exit_codes.AVOCADO_JOB_INTERRUPTED
result = self.run_and_check(cmd_line, expected_rc)
self.run_and_check(cmd_line, expected_rc)
def test_run_replay_disable_failfast(self):
cmd_line = ('%s run --replay %s --failfast off '
......
......@@ -160,7 +160,6 @@ class ProcessTest(unittest.TestCase):
def file_lock_action(args):
path, players, max_individual_timeout = args
start = time.time()
max_timeout = max_individual_timeout * players
with FileLock(path, max_timeout):
sleeptime = random.random() / 100
......
......@@ -388,7 +388,7 @@ class LoaderTest(unittest.TestCase):
AVOCADO_FOREIGN_TAGGED_ENABLE,
'avocado_loader_unittest')
avocado_pass_test.save()
test_class, test_parameters = (
test_class, _ = (
self.loader.discover(avocado_pass_test.path, loader.ALL)[0])
self.assertTrue(test_class == 'First', test_class)
avocado_pass_test.remove()
......@@ -399,7 +399,7 @@ class LoaderTest(unittest.TestCase):
'avocado_loader_unittest',
DEFAULT_NON_EXEC_MODE)
avocado_pass_test.save()
test_class, test_parameters = (
test_class, _ = (
self.loader.discover(avocado_pass_test.path, loader.ALL)[0])
self.assertTrue(test_class == loader.NotATest)
avocado_pass_test.remove()
......@@ -421,7 +421,7 @@ class LoaderTest(unittest.TestCase):
AVOCADO_TEST_MULTIPLE_IMPORTS,
'avocado_loader_unittest')
avocado_multiple_imp_test.save()
test_class, test_parameters = (
test_class, _ = (
self.loader.discover(avocado_multiple_imp_test.path, loader.ALL)[0])
self.assertTrue(test_class == 'Second', test_class)
avocado_multiple_imp_test.remove()
......
......@@ -21,7 +21,7 @@ class ResultTest(unittest.TestCase):
def test_result_job_without_id(self):
args = argparse.Namespace()
result = Result(FakeJob(args))
Result(FakeJob(args))
self.assertRaises(AttributeError, Result, FakeJobMissingUniqueId(args))
......
......@@ -36,9 +36,9 @@ class TestSystemd(unittest.TestCase):
command_generator)
def test_all_commands(self):
for cmd, requires_root in ((c, r) for (c, r) in
self.service_command_generator.commands if
c not in ["list", "set_target"]):
for cmd, _ in ((c, r) for (c, r) in
self.service_command_generator.commands if
c not in ["list", "set_target"]):
ret = getattr(
self.service_command_generator, cmd)(self.service_name)
if cmd == "is_enabled":
......@@ -62,9 +62,9 @@ class TestSysVInit(unittest.TestCase):
def test_all_commands(self):
command_name = "service"
for cmd, requires_root in ((c, r) for (c, r) in
self.service_command_generator.commands if
c not in ["list", "set_target"]):
for cmd, _ in ((c, r) for (c, r) in
self.service_command_generator.commands if
c not in ["list", "set_target"]):
ret = getattr(
self.service_command_generator, cmd)(self.service_name)
if cmd == "is_enabled":
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册