The following issues were found
Lib/test/test_fractions.py
152 issues
Line: 103
Column: 29
self.assertListEqual(list(map(type, expected)), list(map(type, actual)))
def assertRaisesMessage(self, exc_type, message,
callable, *args, **kwargs):
"""Asserts that callable(*args, **kwargs) raises exc_type(message)."""
try:
callable(*args, **kwargs)
except exc_type as e:
self.assertEqual(message, str(e))
Reported by Pylint.
Line: 286
Column: 9
self.assertEqual((7, 3), _components(r))
# But if you _really_ need to:
r._numerator = 4
r._denominator = 2
self.assertEqual((4, 2), _components(r))
# Which breaks some important operations:
self.assertNotEqual(F(4, 2), r)
Reported by Pylint.
Line: 287
Column: 9
# But if you _really_ need to:
r._numerator = 4
r._denominator = 2
self.assertEqual((4, 2), _components(r))
# Which breaks some important operations:
self.assertNotEqual(F(4, 2), r)
def testFromFloat(self):
Reported by Pylint.
Line: 702
Column: 26
self.assertFalse(2 == F(3, 2))
self.assertTrue(F(4, 2) == 2)
self.assertFalse(F(5, 2) == 2)
self.assertFalse(F(5, 2) == float('nan'))
self.assertFalse(float('nan') == F(3, 7))
self.assertFalse(F(5, 2) == float('inf'))
self.assertFalse(float('-inf') == F(2, 5))
def testStringification(self):
Reported by Pylint.
Line: 703
Column: 26
self.assertTrue(F(4, 2) == 2)
self.assertFalse(F(5, 2) == 2)
self.assertFalse(F(5, 2) == float('nan'))
self.assertFalse(float('nan') == F(3, 7))
self.assertFalse(F(5, 2) == float('inf'))
self.assertFalse(float('-inf') == F(2, 5))
def testStringification(self):
self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
Reported by Pylint.
Line: 758
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
r = F(13, 7)
dr = DummyFraction(13, 7)
for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
self.assertEqual(r, loads(dumps(r, proto)))
self.assertEqual(id(r), id(copy(r)))
self.assertEqual(id(r), id(deepcopy(r)))
self.assertNotEqual(id(dr), id(copy(dr)))
self.assertNotEqual(id(dr), id(deepcopy(dr)))
self.assertTypedEquals(dr, copy(dr))
Reported by Bandit.
Line: 13
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle
import sys
import unittest
from copy import copy, deepcopy
import pickle
from pickle import dumps, loads
F = fractions.Fraction
class DummyFloat(object):
Reported by Bandit.
Line: 14
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle
import unittest
from copy import copy, deepcopy
import pickle
from pickle import dumps, loads
F = fractions.Fraction
class DummyFloat(object):
"""Dummy float class for testing comparisons with Fractions"""
Reported by Bandit.
Line: 15
Column: 1
from copy import copy, deepcopy
import pickle
from pickle import dumps, loads
F = fractions.Fraction
class DummyFloat(object):
"""Dummy float class for testing comparisons with Fractions"""
Reported by Pylint.
Line: 18
Column: 1
F = fractions.Fraction
class DummyFloat(object):
"""Dummy float class for testing comparisons with Fractions"""
def __init__(self, value):
if not isinstance(value, float):
raise TypeError("DummyFloat can only be initialized from float")
Reported by Pylint.
Lib/enum.py
152 issues
Line: 126
Column: 53
digits = s[3:]
if max_bits is not None:
if len(digits) < max_bits:
digits = (sign[-1] * max_bits + digits)[-max_bits:]
return "%s %s" % (sign, digits)
_auto_null = object()
class auto:
Reported by Pylint.
Line: 363
Column: 35
raise TypeError('%r already defined as: %r' % (key, self[key]))
if isinstance(value, auto):
if value.value == _auto_null:
value.value = self._generate_next_value(
key, 1, len(self._member_names), self._last_values[:],
)
self._auto_called = True
value = value.value
self._member_names.append(key)
Reported by Pylint.
Line: 597
Column: 20
`type`, if set, will be mixed in as the first base class.
"""
if names is None: # simple value lookup
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
return cls._create_(
value,
names,
module=module,
Reported by Pylint.
Line: 597
Column: 20
`type`, if set, will be mixed in as the first base class.
"""
if names is None: # simple value lookup
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
return cls._create_(
value,
names,
module=module,
Reported by Pylint.
Line: 599
Column: 16
if names is None: # simple value lookup
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
return cls._create_(
value,
names,
module=module,
qualname=qualname,
type=type,
Reported by Pylint.
Line: 892
Column: 1
EnumMeta = EnumType
class Enum(metaclass=EnumType):
"""
Generic enumeration.
Derive from this class to define new enumerations.
"""
Reported by Pylint.
Line: 950
Column: 5
exc = None
ve_exc = None
def _generate_next_value_(name, start, count, last_values):
"""
Generate the next value when not given.
name: the name of the member
start: the initial start value or None
Reported by Pylint.
Line: 1093
Column: 5
__format__ = str.__format__
def _generate_next_value_(name, start, count, last_values):
"""
Return the lower-cased version of the member name.
"""
return name.lower()
Reported by Pylint.
Line: 1118
Column: 1
STRICT, CONFORM, EJECT, KEEP = FlagBoundary
class Flag(Enum, boundary=STRICT):
"""
Support for flags
"""
def _generate_next_value_(name, start, count, last_values):
Reported by Pylint.
Line: 1123
Column: 5
Support for flags
"""
def _generate_next_value_(name, start, count, last_values):
"""
Generate the next value when not given.
name: the name of the member
start: the initial start value or None
Reported by Pylint.
Lib/test/test_subclassinit.py
151 issues
Line: 89
Column: 17
class Middle:
def __init_subclass__(cls, middle, **kwargs):
super().__init_subclass__(**kwargs)
cls.calls += [middle]
class Right(Base):
def __init_subclass__(cls, right="right", **kwargs):
super().__init_subclass__(**kwargs)
cls.calls += [right]
Reported by Pylint.
Line: 149
Column: 13
def test_set_name_wrong(self):
class Descriptor:
def __set_name__(self):
pass
with self.assertRaises(RuntimeError) as cm:
class NotGoingToWork:
attr = Descriptor()
Reported by Pylint.
Line: 189
Column: 29
class A:
def __init_subclass__(cls):
cls.owner = cls.d.owner
cls.name = cls.d.name
class B(A, metaclass=Meta):
d = Descriptor()
Reported by Pylint.
Line: 190
Column: 28
class A:
def __init_subclass__(cls):
cls.owner = cls.d.owner
cls.name = cls.d.name
class B(A, metaclass=Meta):
d = Descriptor()
self.assertIs(B.owner, B)
Reported by Pylint.
Line: 197
Column: 23
self.assertIs(B.owner, B)
self.assertEqual(B.name, 'd')
self.assertIs(B.meta_owner, B)
self.assertEqual(B.name, 'd')
def test_set_name_modifying_dict(self):
notified = []
class Descriptor:
Reported by Pylint.
Line: 230
Column: 9
types.prepare_class("MyClass", (object,),
dict(metaclass=MyMeta, otherarg=1))
class MyMeta(type):
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
Reported by Pylint.
Line: 235
Column: 13
super().__init__(name, bases, namespace)
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
return super().__new__(cls, name, bases, namespace)
Reported by Pylint.
Line: 238
Column: 9
class MyClass(metaclass=MyMeta, otherarg=1):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
return super().__new__(cls, name, bases, namespace)
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
Reported by Pylint.
Line: 246
Column: 9
super().__init__(name, bases, namespace)
self.otherarg = otherarg
class MyClass(metaclass=MyMeta, otherarg=1):
pass
self.assertEqual(MyClass.otherarg, 1)
def test_errors_changed_pep487(self):
Reported by Pylint.
Line: 262
Column: 9
class MyClass(metaclass=MyMeta):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
self = super().__new__(cls, name, bases, namespace)
self.otherarg = otherarg
return self
Reported by Pylint.
Lib/test/test_bdb.py
150 issues
Line: 556
Column: 5
TEST_MODULE = 'test_module_for_bdb'
TEST_MODULE_FNAME = TEST_MODULE + '.py'
def tfunc_import():
import test_module_for_bdb
test_module_for_bdb.main()
def tfunc_main():
lno = 2
tfunc_first()
Reported by Pylint.
Line: 1025
Column: 13
('return', 3, 'main'), ('step', ),
('return', 1, '<module>'), ('quit', ),
]
import test_module_for_bdb
with TracerRun(self) as tracer:
tracer.runeval('test_module_for_bdb.main()', globals(), locals())
class IssuesTestCase(BaseTestCase):
"""Test fixed bdb issues."""
Reported by Pylint.
Line: 100
Column: 1
info += '\n'
return info
class Bdb(_bdb.Bdb):
"""Extend Bdb to enhance test coverage."""
def trace_dispatch(self, frame, event, arg):
self.currentbp = None
return super().trace_dispatch(frame, event, arg)
Reported by Pylint.
Line: 104
Column: 9
"""Extend Bdb to enhance test coverage."""
def trace_dispatch(self, frame, event, arg):
self.currentbp = None
return super().trace_dispatch(frame, event, arg)
def set_break(self, filename, lineno, temporary=False, cond=None,
funcname=None):
if isinstance(funcname, str):
Reported by Pylint.
Line: 115
Column: 20
else:
module = importlib.import_module(filename[:-3])
globals_ = module.__dict__
func = eval(funcname, globals_)
code = func.__code__
filename = code.co_filename
lineno = code.co_firstlineno
funcname = code.co_name
Reported by Pylint.
Line: 115
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval
else:
module = importlib.import_module(filename[:-3])
globals_ = module.__dict__
func = eval(funcname, globals_)
code = func.__code__
filename = code.co_filename
lineno = code.co_firstlineno
funcname = code.co_name
Reported by Bandit.
Line: 128
Column: 9
return res
def get_stack(self, f, t):
self.stack, self.index = super().get_stack(f, t)
self.frame = self.stack[self.index][0]
return self.stack, self.index
def set_ignore(self, bpnum):
"""Increment the ignore count of Breakpoint number 'bpnum'."""
Reported by Pylint.
Line: 128
Column: 21
return res
def get_stack(self, f, t):
self.stack, self.index = super().get_stack(f, t)
self.frame = self.stack[self.index][0]
return self.stack, self.index
def set_ignore(self, bpnum):
"""Increment the ignore count of Breakpoint number 'bpnum'."""
Reported by Pylint.
Line: 129
Column: 9
def get_stack(self, f, t):
self.stack, self.index = super().get_stack(f, t)
self.frame = self.stack[self.index][0]
return self.stack, self.index
def set_ignore(self, bpnum):
"""Increment the ignore count of Breakpoint number 'bpnum'."""
bp = self.get_bpbynumber(bpnum)
Reported by Pylint.
Line: 155
Column: 9
if not self.index:
raise BdbError('Oldest frame')
self.index -= 1
self.frame = self.stack[self.index][0]
def set_down(self):
"""Move down in the frame stack."""
if self.index + 1 == len(self.stack):
raise BdbError('Newest frame')
Reported by Pylint.
Lib/subprocess.py
150 issues
Line: 121
Column: 35
if self.returncode and self.returncode < 0:
try:
return "Command '%s' died with %r." % (
self.cmd, signal.Signals(-self.returncode))
except ValueError:
return "Command '%s' died with unknown signal %d." % (
self.cmd, -self.returncode)
else:
return "Command '%s' returned non-zero exit status %d." % (
Reported by Pylint.
Line: 373
Column: 1
return 0
def check_output(*popenargs, timeout=None, **kwargs):
r"""Run command with arguments and return its output.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
Reported by Pylint.
Line: 697
Column: 1
_USE_POSIX_SPAWN = _use_posix_spawn()
class Popen:
""" Execute a child program in a new process.
For a complete description of the arguments see the Python documentation.
Arguments:
Reported by Pylint.
Line: 1555
Column: 25
return
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
Reported by Pylint.
Line: 1556
Column: 35
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
Reported by Pylint.
Line: 1557
Column: 25
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
def terminate(self):
Reported by Pylint.
Line: 1558
Column: 35
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
def terminate(self):
"""Terminates the process."""
Reported by Pylint.
Line: 1596
Column: 43
elif stdin == PIPE:
p2cread, p2cwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdin == DEVNULL:
p2cread = self._get_devnull()
elif isinstance(stdin, int):
p2cread = stdin
else:
Reported by Pylint.
Line: 1610
Column: 43
elif stdout == PIPE:
c2pread, c2pwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdout == DEVNULL:
c2pwrite = self._get_devnull()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
Reported by Pylint.
Line: 1624
Column: 43
elif stderr == PIPE:
errread, errwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stderr == STDOUT:
if c2pwrite != -1:
errwrite = c2pwrite
else: # child's stdout is not set, use parent's stdout
errwrite = sys.__stdout__.fileno()
Reported by Pylint.
Lib/ctypes/test/test_strings.py
150 issues
Line: 91
Column: 14
class StringTestCase(unittest.TestCase):
@unittest.skip('test disabled')
def test_basic_strings(self):
cs = c_string("abcdef")
# Cannot call len on a c_string any longer
self.assertRaises(TypeError, len, cs)
self.assertEqual(sizeof(cs), 7)
Reported by Pylint.
Line: 99
Column: 26
# The value property is the string up to the first terminating NUL.
self.assertEqual(cs.value, "abcdef")
self.assertEqual(c_string("abc\000def").value, "abc")
# The raw property is the total buffer contents:
self.assertEqual(cs.raw, "abcdef\000")
self.assertEqual(c_string("abc\000def").raw, "abc\000def\000")
Reported by Pylint.
Line: 103
Column: 26
# The raw property is the total buffer contents:
self.assertEqual(cs.raw, "abcdef\000")
self.assertEqual(c_string("abc\000def").raw, "abc\000def\000")
# We can change the value:
cs.value = "ab"
self.assertEqual(cs.value, "ab")
self.assertEqual(cs.raw, "ab\000\000\000\000\000")
Reported by Pylint.
Line: 114
Column: 38
self.assertEqual(cs.value, "XY")
self.assertEqual(cs.raw, "XY\000\000\000\000\000")
self.assertRaises(TypeError, c_string, "123")
@unittest.skip('test disabled')
def test_sized_strings(self):
# New in releases later than 0.4.0:
Reported by Pylint.
Line: 120
Column: 38
def test_sized_strings(self):
# New in releases later than 0.4.0:
self.assertRaises(TypeError, c_string, None)
# New in releases later than 0.4.0:
# c_string(number) returns an empty string of size number
self.assertEqual(len(c_string(32).raw), 32)
self.assertRaises(ValueError, c_string, -1)
Reported by Pylint.
Line: 124
Column: 30
# New in releases later than 0.4.0:
# c_string(number) returns an empty string of size number
self.assertEqual(len(c_string(32).raw), 32)
self.assertRaises(ValueError, c_string, -1)
self.assertRaises(ValueError, c_string, 0)
# These tests fail, because it is no longer initialized
## self.assertEqual(c_string(2).value, "")
Reported by Pylint.
Line: 125
Column: 39
# New in releases later than 0.4.0:
# c_string(number) returns an empty string of size number
self.assertEqual(len(c_string(32).raw), 32)
self.assertRaises(ValueError, c_string, -1)
self.assertRaises(ValueError, c_string, 0)
# These tests fail, because it is no longer initialized
## self.assertEqual(c_string(2).value, "")
## self.assertEqual(c_string(2).raw, "\000\000")
Reported by Pylint.
Line: 126
Column: 39
# c_string(number) returns an empty string of size number
self.assertEqual(len(c_string(32).raw), 32)
self.assertRaises(ValueError, c_string, -1)
self.assertRaises(ValueError, c_string, 0)
# These tests fail, because it is no longer initialized
## self.assertEqual(c_string(2).value, "")
## self.assertEqual(c_string(2).raw, "\000\000")
self.assertEqual(c_string(2).raw[-1], "\000")
Reported by Pylint.
Line: 131
Column: 26
# These tests fail, because it is no longer initialized
## self.assertEqual(c_string(2).value, "")
## self.assertEqual(c_string(2).raw, "\000\000")
self.assertEqual(c_string(2).raw[-1], "\000")
self.assertEqual(len(c_string(2).raw), 2)
@unittest.skip('test disabled')
def test_initialized_strings(self):
Reported by Pylint.
Line: 132
Column: 30
## self.assertEqual(c_string(2).value, "")
## self.assertEqual(c_string(2).raw, "\000\000")
self.assertEqual(c_string(2).raw[-1], "\000")
self.assertEqual(len(c_string(2).raw), 2)
@unittest.skip('test disabled')
def test_initialized_strings(self):
self.assertEqual(c_string("ab", 4).raw[:2], "ab")
Reported by Pylint.
Lib/test/test_clinic.py
149 issues
Line: 16
Column: 5
test_tools.skip_if_missing('clinic')
with test_tools.imports_under_tool('clinic'):
import clinic
from clinic import DSLParser
class FakeConverter:
def __init__(self, name, args):
Reported by Pylint.
Line: 17
Column: 5
test_tools.skip_if_missing('clinic')
with test_tools.imports_under_tool('clinic'):
import clinic
from clinic import DSLParser
class FakeConverter:
def __init__(self, name, args):
self.name = name
Reported by Pylint.
Line: 86
Column: 9
return name == "module"
def directive(self, name, args):
self.called_directives[name] = args
_module_and_class = clinic.Clinic._module_and_class
class ClinicWholeFileTest(TestCase):
def test_eol(self):
Reported by Pylint.
Line: 38
Column: 25
def __init__(self):
self.used_converters = {}
def get(self, name, default):
return self.used_converters.setdefault(name, FakeConverterFactory(name))
c = clinic.Clinic(language='C', filename = "file")
class FakeClinic:
Reported by Pylint.
Line: 77
Column: 37
sys.exit("Destination does not exist: " + repr(name))
return d
def add_destination(self, name, type, *args):
if name in self.destinations:
sys.exit("Destination already exists: " + repr(name))
self.destinations[name] = clinic.Destination(name, type, self, *args)
def is_directive(self, name):
Reported by Pylint.
Line: 88
Column: 25
def directive(self, name, args):
self.called_directives[name] = args
_module_and_class = clinic.Clinic._module_and_class
class ClinicWholeFileTest(TestCase):
def test_eol(self):
# regression test:
# clinic's block parser didn't recognize
Reported by Pylint.
Line: 100
Column: 9
# so it would spit out an end line for you.
# and since you really already had one,
# the last line of the block got corrupted.
c = clinic.Clinic(clinic.CLanguage(None), filename="file")
raw = "/*[clinic]\nfoo\n[clinic]*/"
cooked = c.parse(raw).splitlines()
end_line = cooked[2].rstrip()
# this test is redundant, it's just here explicitly to catch
# the regression test so we don't forget what it looked like
Reported by Pylint.
Line: 160
Column: 21
class ClinicLinearFormatTest(TestCase):
def _test(self, input, output, **kwargs):
computed = clinic.linear_format(input, **kwargs)
self.assertEqual(output, computed)
def test_empty_strings(self):
self._test('', '')
Reported by Pylint.
Line: 212
Column: 24
""", name='bingle\nbungle\n')
class InertParser:
def __init__(self, clinic):
pass
def parse(self, block):
pass
Reported by Pylint.
Line: 219
Column: 24
pass
class CopyParser:
def __init__(self, clinic):
pass
def parse(self, block):
block.output = block.input
Reported by Pylint.
Lib/test/test_importlib/test_namespace_pkgs.py
148 issues
Line: 63
Column: 55
def setUp(self):
self.resolved_paths = [
os.path.join(self.root, path) for path in self.paths
]
self.ctx = namespace_tree_context(path=self.resolved_paths)
self.ctx.__enter__()
def tearDown(self):
Reported by Pylint.
Line: 66
Column: 9
os.path.join(self.root, path) for path in self.paths
]
self.ctx = namespace_tree_context(path=self.resolved_paths)
self.ctx.__enter__()
def tearDown(self):
# TODO: will we ever want to pass exc_info to __exit__?
self.ctx.__exit__(None, None, None)
Reported by Pylint.
Line: 70
Column: 9
def tearDown(self):
# TODO: will we ever want to pass exc_info to __exit__?
self.ctx.__exit__(None, None, None)
class SingleNamespacePackage(NamespacePackageTest):
paths = ['portion1']
Reported by Pylint.
Line: 77
Column: 9
paths = ['portion1']
def test_simple_package(self):
import foo.one
self.assertEqual(foo.one.attr, 'portion1 foo one')
def test_cant_import_other(self):
with self.assertRaises(ImportError):
import foo.two
Reported by Pylint.
Line: 82
Column: 13
def test_cant_import_other(self):
with self.assertRaises(ImportError):
import foo.two
def test_module_repr(self):
import foo.one
with warnings.catch_warnings():
warnings.simplefilter("ignore")
Reported by Pylint.
Line: 85
Column: 9
import foo.two
def test_module_repr(self):
import foo.one
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.assertEqual(foo.__spec__.loader.module_repr(foo),
"<module 'foo' (namespace)>")
Reported by Pylint.
Line: 97
Column: 9
def test_dynamic_path(self):
# Make sure only 'foo.one' can be imported
import foo.one
self.assertEqual(foo.one.attr, 'portion1 foo one')
with self.assertRaises(ImportError):
import foo.two
Reported by Pylint.
Line: 101
Column: 13
self.assertEqual(foo.one.attr, 'portion1 foo one')
with self.assertRaises(ImportError):
import foo.two
# Now modify sys.path
sys.path.append(os.path.join(self.root, 'portion2'))
# And make sure foo.two is now importable
Reported by Pylint.
Line: 107
Column: 9
sys.path.append(os.path.join(self.root, 'portion2'))
# And make sure foo.two is now importable
import foo.two
self.assertEqual(foo.two.attr, 'portion2 foo two')
class CombinedNamespacePackages(NamespacePackageTest):
paths = ['both_portions']
Reported by Pylint.
Line: 115
Column: 9
paths = ['both_portions']
def test_imports(self):
import foo.one
import foo.two
self.assertEqual(foo.one.attr, 'both_portions foo one')
self.assertEqual(foo.two.attr, 'both_portions foo two')
Reported by Pylint.
Lib/test/test_asyncio/test_locks.py
148 issues
Line: 154
Column: 26
self.assertRaises(
asyncio.CancelledError,
self.loop.run_until_complete, task)
self.assertFalse(lock._waiters)
def test_cancel_race(self):
# Several tasks:
# - A acquires the lock
# - B is blocked in acquire()
Reported by Pylint.
Line: 173
Column: 26
# Setup: A has the lock, b and c are waiting.
lock = asyncio.Lock()
async def lockit(name, blocker):
await lock.acquire()
try:
if blocker is not None:
await blocker
finally:
Reported by Pylint.
Line: 187
Column: 30
self.assertTrue(lock.locked())
tb = self.loop.create_task(lockit('B', None))
test_utils.run_briefly(self.loop)
self.assertEqual(len(lock._waiters), 1)
tc = self.loop.create_task(lockit('C', None))
test_utils.run_briefly(self.loop)
self.assertEqual(len(lock._waiters), 2)
# Create the race and check.
Reported by Pylint.
Line: 190
Column: 30
self.assertEqual(len(lock._waiters), 1)
tc = self.loop.create_task(lockit('C', None))
test_utils.run_briefly(self.loop)
self.assertEqual(len(lock._waiters), 2)
# Create the race and check.
# Without the fix this failed at the last assert.
fa.set_result(None)
tb.cancel()
Reported by Pylint.
Line: 196
Column: 25
# Without the fix this failed at the last assert.
fa.set_result(None)
tb.cancel()
self.assertTrue(lock._waiters[0].cancelled())
test_utils.run_briefly(self.loop)
self.assertFalse(lock.locked())
self.assertTrue(ta.done())
self.assertTrue(tb.cancelled())
self.assertTrue(tc.done())
Reported by Pylint.
Line: 260
Column: 30
tb = self.loop.create_task(lock.acquire())
test_utils.run_briefly(self.loop)
self.assertEqual(len(lock._waiters), 1)
# Create a second waiter, wake up the first, and cancel it.
# Without the fix, the second was not woken up.
tc = self.loop.create_task(lock.acquire())
lock.release()
Reported by Pylint.
Line: 264
Column: 9
# Create a second waiter, wake up the first, and cancel it.
# Without the fix, the second was not woken up.
tc = self.loop.create_task(lock.acquire())
lock.release()
tb.cancel()
test_utils.run_briefly(self.loop)
self.assertTrue(lock.locked())
Reported by Pylint.
Line: 315
Column: 9
self.assertTrue(repr(ev).endswith('[set]>'))
self.assertTrue(RGX_REPR.match(repr(ev)))
ev._waiters.append(mock.Mock())
self.assertTrue('waiters:1' in repr(ev))
self.assertTrue(RGX_REPR.match(repr(ev)))
def test_wait(self):
ev = asyncio.Event()
Reported by Pylint.
Line: 371
Column: 26
self.assertRaises(
asyncio.CancelledError,
self.loop.run_until_complete, wait)
self.assertFalse(ev._waiters)
def test_clear(self):
ev = asyncio.Event()
self.assertFalse(ev.is_set())
Reported by Pylint.
Line: 402
Column: 33
ev.set()
ev.set()
self.assertEqual(1, len(ev._waiters))
test_utils.run_briefly(self.loop)
self.assertEqual([1], result)
self.assertEqual(0, len(ev._waiters))
Reported by Pylint.
Lib/test/test_string.py
146 issues
Line: 46
Column: 26
fmt = string.Formatter()
self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
self.assertRaises(KeyError, fmt.format, "-{arg}-")
self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
self.assertRaises(KeyError, fmt.format, "-{self}-")
self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
'-test-')
self.assertRaises(KeyError, fmt.format, "-{format_string}-")
with self.assertRaisesRegex(TypeError, "format_string"):
Reported by Pylint.
Line: 48
Column: 26
self.assertRaises(KeyError, fmt.format, "-{arg}-")
self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
self.assertRaises(KeyError, fmt.format, "-{self}-")
self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
'-test-')
self.assertRaises(KeyError, fmt.format, "-{format_string}-")
with self.assertRaisesRegex(TypeError, "format_string"):
fmt.format(format_string="-{arg}-", arg='test')
Reported by Pylint.
Line: 59
Column: 26
self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
'foo{}{}'.format('bar', 6))
self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
'foo{1}{num}{1}'.format(None, 'bar', num=6))
self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
'{:^{}}'.format('bar', 6))
self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
'{:^{}} {}'.format('bar', 6, 'X'))
self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
Reported by Pylint.
Line: 118
Column: 21
except KeyError:
return self.namespace[key]
else:
string.Formatter.get_value(key, args, kwds)
fmt = NamespaceFormatter({'greeting':'hello'})
self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
Reported by Pylint.
Line: 429
Column: 12
who='tim', what='ham'),
'tim likes ham')
s = Template('the mapping is $mapping')
eq(s.substitute(dict(foo='none'), mapping='bozo'),
'the mapping is bozo')
eq(s.substitute(dict(mapping='one'), mapping='two'),
'the mapping is two')
s = Template('the self is $self')
Reported by Pylint.
Line: 431
Column: 12
s = Template('the mapping is $mapping')
eq(s.substitute(dict(foo='none'), mapping='bozo'),
'the mapping is bozo')
eq(s.substitute(dict(mapping='one'), mapping='two'),
'the mapping is two')
s = Template('the self is $self')
eq(s.substitute(self='bozo'), 'the self is bozo')
Reported by Pylint.
Line: 435
Column: 12
'the mapping is two')
s = Template('the self is $self')
eq(s.substitute(self='bozo'), 'the self is bozo')
def test_keyword_arguments_safe(self):
eq = self.assertEqual
raises = self.assertRaises
s = Template('$who likes $what')
Reported by Pylint.
Line: 447
Column: 12
who='tim', what='ham'),
'tim likes ham')
s = Template('the mapping is $mapping')
eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
'the mapping is bozo')
eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
'the mapping is two')
d = dict(mapping='one')
raises(TypeError, s.substitute, d, {})
Reported by Pylint.
Line: 449
Column: 12
s = Template('the mapping is $mapping')
eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
'the mapping is bozo')
eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
'the mapping is two')
d = dict(mapping='one')
raises(TypeError, s.substitute, d, {})
raises(TypeError, s.safe_substitute, d, {})
Reported by Pylint.
Line: 456
Column: 12
raises(TypeError, s.safe_substitute, d, {})
s = Template('the self is $self')
eq(s.safe_substitute(self='bozo'), 'the self is bozo')
def test_delimiter_override(self):
eq = self.assertEqual
raises = self.assertRaises
class AmpersandTemplate(Template):
Reported by Pylint.