The following issues were found
Lib/test/test_importlib/import_/test___package__.py
47 issues
Line: 9
Column: 1
"""
import unittest
import warnings
from .. import util
class Using__package__:
"""Use of __package__ supersedes the use of __name__/__path__ to calculate
Reported by Pylint.
Line: 38
Column: 14
"""
def import_module(self, globals_):
with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
self.__import__('pkg.fake')
module = self.__import__('',
globals=globals_,
fromlist=['attr'], level=2)
Reported by Pylint.
Line: 40
Column: 17
def import_module(self, globals_):
with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
self.__import__('pkg.fake')
module = self.__import__('',
globals=globals_,
fromlist=['attr'], level=2)
return module
Reported by Pylint.
Line: 41
Column: 26
with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
self.__import__('pkg.fake')
module = self.__import__('',
globals=globals_,
fromlist=['attr'], level=2)
return module
def test_using___package__(self):
Reported by Pylint.
Line: 49
Column: 9
def test_using___package__(self):
# [__package__]
module = self.import_module({'__package__': 'pkg.fake'})
self.assertEqual(module.__name__, 'pkg')
def test_using___name__(self):
# [__name__]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
Reported by Pylint.
Line: 57
Column: 9
warnings.simplefilter("ignore")
module = self.import_module({'__name__': 'pkg.fake',
'__path__': []})
self.assertEqual(module.__name__, 'pkg')
def test_warn_when_using___name__(self):
with self.assertWarns(ImportWarning):
self.import_module({'__name__': 'pkg.fake', '__path__': []})
Reported by Pylint.
Line: 60
Column: 14
self.assertEqual(module.__name__, 'pkg')
def test_warn_when_using___name__(self):
with self.assertWarns(ImportWarning):
self.import_module({'__name__': 'pkg.fake', '__path__': []})
def test_None_as___package__(self):
# [None]
with warnings.catch_warnings():
Reported by Pylint.
Line: 69
Column: 9
warnings.simplefilter("ignore")
module = self.import_module({
'__name__': 'pkg.fake', '__path__': [], '__package__': None })
self.assertEqual(module.__name__, 'pkg')
def test_spec_fallback(self):
# If __package__ isn't defined, fall back on __spec__.parent.
module = self.import_module({'__spec__': FakeSpec('pkg.fake')})
self.assertEqual(module.__name__, 'pkg')
Reported by Pylint.
Line: 74
Column: 9
def test_spec_fallback(self):
# If __package__ isn't defined, fall back on __spec__.parent.
module = self.import_module({'__spec__': FakeSpec('pkg.fake')})
self.assertEqual(module.__name__, 'pkg')
def test_warn_when_package_and_spec_disagree(self):
# Raise an ImportWarning if __package__ != __spec__.parent.
with self.assertWarns(ImportWarning):
self.import_module({'__package__': 'pkg.fake',
Reported by Pylint.
Line: 78
Column: 14
def test_warn_when_package_and_spec_disagree(self):
# Raise an ImportWarning if __package__ != __spec__.parent.
with self.assertWarns(ImportWarning):
self.import_module({'__package__': 'pkg.fake',
'__spec__': FakeSpec('pkg.fakefake')})
def test_bad__package__(self):
globals = {'__package__': '<not real>'}
Reported by Pylint.
Lib/test/test_glob.py
47 issues
Line: 22
Column: 15
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
if not os.path.exists(base):
os.makedirs(base)
create_empty_file(filename)
def setUp(self):
Reported by Pylint.
Line: 329
Column: 13
pattern = os.path.join(base, '**', 'd')
iters = [glob.iglob(pattern, recursive=True) for j in range(100)]
p = base
for i in range(depth):
p = os.path.join(p, 'd')
for it in iters:
self.assertEqual(next(it), p)
Reported by Pylint.
Line: 1
Column: 1
import glob
import os
import shutil
import sys
import unittest
from test.support.os_helper import (TESTFN, skip_unless_symlink,
can_symlink, create_empty_file, change_cwd)
Reported by Pylint.
Line: 11
Column: 1
can_symlink, create_empty_file, change_cwd)
class GlobTests(unittest.TestCase):
dir_fd = None
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
Reported by Pylint.
Line: 11
Column: 1
can_symlink, create_empty_file, change_cwd)
class GlobTests(unittest.TestCase):
dir_fd = None
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
Reported by Pylint.
Line: 14
Column: 5
class GlobTests(unittest.TestCase):
dir_fd = None
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
def joins(self, *tuples):
return [os.path.join(self.tempdir, *parts) for parts in tuples]
Reported by Pylint.
Line: 17
Column: 5
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
def joins(self, *tuples):
return [os.path.join(self.tempdir, *parts) for parts in tuples]
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
Reported by Pylint.
Line: 20
Column: 5
def joins(self, *tuples):
return [os.path.join(self.tempdir, *parts) for parts in tuples]
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
if not os.path.exists(base):
os.makedirs(base)
create_empty_file(filename)
Reported by Pylint.
Line: 52
Column: 5
os.close(self.dir_fd)
shutil.rmtree(self.tempdir)
def glob(self, *parts, **kwargs):
if len(parts) == 1:
pattern = parts[0]
else:
pattern = os.path.join(*parts)
p = os.path.join(self.tempdir, pattern)
Reported by Pylint.
Line: 57
Column: 9
pattern = parts[0]
else:
pattern = os.path.join(*parts)
p = os.path.join(self.tempdir, pattern)
res = glob.glob(p, **kwargs)
self.assertCountEqual(glob.iglob(p, **kwargs), res)
bres = [os.fsencode(x) for x in res]
self.assertCountEqual(glob.glob(os.fsencode(p), **kwargs), bres)
self.assertCountEqual(glob.iglob(os.fsencode(p), **kwargs), bres)
Reported by Pylint.
Lib/test/test_importlib/source/test_source_encoding.py
47 issues
Line: 1
Column: 1
from .. import util
machinery = util.import_importlib('importlib.machinery')
import codecs
import importlib.util
import re
import types
# Because sys.path gets essentially blanked, need to have unicodedata already
Reported by Pylint.
Line: 41
Column: 22
with util.create_modules(self.module_name) as mapping:
with open(mapping[self.module_name], 'wb') as file:
file.write(source)
loader = self.machinery.SourceFileLoader(self.module_name,
mapping[self.module_name])
return self.load(loader)
def create_source(self, encoding):
encoding_line = "# coding={0}".format(encoding)
Reported by Pylint.
Line: 43
Column: 20
file.write(source)
loader = self.machinery.SourceFileLoader(self.module_name,
mapping[self.module_name])
return self.load(loader)
def create_source(self, encoding):
encoding_line = "# coding={0}".format(encoding)
assert CODING_RE.match(encoding_line)
source_lines = [encoding_line.encode('utf-8')]
Reported by Pylint.
Line: 87
Column: 14
# [BOM conflict]
def test_bom_conflict(self):
source = codecs.BOM_UTF8 + self.create_source('latin-1')
with self.assertRaises(SyntaxError):
self.run_test(source)
class EncodingTestPEP451(EncodingTest):
Reported by Pylint.
Line: 130
Column: 22
with util.create_modules(module_name) as mapping:
with open(mapping[module_name], 'wb') as file:
file.write(source)
loader = self.machinery.SourceFileLoader(module_name,
mapping[module_name])
return self.load(loader, module_name)
# [cr]
def test_cr(self):
Reported by Pylint.
Line: 132
Column: 20
file.write(source)
loader = self.machinery.SourceFileLoader(module_name,
mapping[module_name])
return self.load(loader, module_name)
# [cr]
def test_cr(self):
self.run_test(b'\r')
Reported by Pylint.
Line: 11
Column: 1
import types
# Because sys.path gets essentially blanked, need to have unicodedata already
# imported for the parser to use.
import unicodedata
import unittest
import warnings
CODING_RE = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
Reported by Pylint.
Line: 1
Column: 1
from .. import util
machinery = util.import_importlib('importlib.machinery')
import codecs
import importlib.util
import re
import types
# Because sys.path gets essentially blanked, need to have unicodedata already
Reported by Pylint.
Line: 5
Column: 1
machinery = util.import_importlib('importlib.machinery')
import codecs
import importlib.util
import re
import types
# Because sys.path gets essentially blanked, need to have unicodedata already
# imported for the parser to use.
Reported by Pylint.
Line: 5
Column: 1
machinery = util.import_importlib('importlib.machinery')
import codecs
import importlib.util
import re
import types
# Because sys.path gets essentially blanked, need to have unicodedata already
# imported for the parser to use.
Reported by Pylint.
Lib/test/test_copyreg.py
46 issues
Line: 59
Column: 29
mod, func, code)
copyreg.add_extension(mod, func, code)
# Should be in the registry.
self.assertTrue(copyreg._extension_registry[mod, func] == code)
self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
self.assertNotIn(code, copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
Reported by Pylint.
Line: 60
Column: 29
copyreg.add_extension(mod, func, code)
# Should be in the registry.
self.assertTrue(copyreg._extension_registry[mod, func] == code)
self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
self.assertNotIn(code, copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code.
Reported by Pylint.
Line: 62
Column: 36
self.assertTrue(copyreg._extension_registry[mod, func] == code)
self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
self.assertNotIn(code, copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code.
self.assertRaises(ValueError, copyreg.add_extension,
mod, func, code + 1)
Reported by Pylint.
Line: 81
Column: 32
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func[1:], code)
# Can't remove one that isn't registered at all.
if code + 1 not in copyreg._inverted_registry:
self.assertRaises(ValueError, copyreg.remove_extension,
mod[1:], func[1:], code + 1)
finally:
e.restore()
Reported by Pylint.
Line: 89
Column: 39
e.restore()
# Shouldn't be there anymore.
self.assertNotIn((mod, func), copyreg._extension_registry)
# The code *may* be in copyreg._extension_registry, though, if
# we happened to pick on a registered code. So don't check for
# that.
# Check valid codes at the limits.
Reported by Pylint.
Line: 109
Column: 26
mod, func, code)
def test_slotnames(self):
self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
expected = ['_WithLeadingUnderscoreAndPrivate__spam']
self.assertEqual(copyreg._slotnames(_WithLeadingUnderscoreAndPrivate),
Reported by Pylint.
Line: 110
Column: 26
def test_slotnames(self):
self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
expected = ['_WithLeadingUnderscoreAndPrivate__spam']
self.assertEqual(copyreg._slotnames(_WithLeadingUnderscoreAndPrivate),
expected)
Reported by Pylint.
Line: 112
Column: 26
self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
expected = ['_WithLeadingUnderscoreAndPrivate__spam']
self.assertEqual(copyreg._slotnames(_WithLeadingUnderscoreAndPrivate),
expected)
self.assertEqual(copyreg._slotnames(___), ['__spam'])
self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
Reported by Pylint.
Line: 114
Column: 26
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
expected = ['_WithLeadingUnderscoreAndPrivate__spam']
self.assertEqual(copyreg._slotnames(_WithLeadingUnderscoreAndPrivate),
expected)
self.assertEqual(copyreg._slotnames(___), ['__spam'])
self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
expected = ['eggs', 'spam']
expected.sort()
Reported by Pylint.
Line: 116
Column: 26
expected = ['_WithLeadingUnderscoreAndPrivate__spam']
self.assertEqual(copyreg._slotnames(_WithLeadingUnderscoreAndPrivate),
expected)
self.assertEqual(copyreg._slotnames(___), ['__spam'])
self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
expected = ['eggs', 'spam']
expected.sort()
result = copyreg._slotnames(WithInherited)
result.sort()
Reported by Pylint.
Lib/test/test_msilib.py
46 issues
Line: 60
Column: 42
db, db_path = init_database()
try:
sum_info = db.GetSummaryInformation(99)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"Installation Database")
sum_info.SetProperty(msilib.PID_TITLE, "a" * 999)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 999)
Reported by Pylint.
Line: 63
Column: 34
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"Installation Database")
sum_info.SetProperty(msilib.PID_TITLE, "a" * 999)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 999)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1000)
title = sum_info.GetProperty(msilib.PID_TITLE)
Reported by Pylint.
Line: 64
Column: 42
self.assertEqual(title, b"Installation Database")
sum_info.SetProperty(msilib.PID_TITLE, "a" * 999)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 999)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1000)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1000)
Reported by Pylint.
Line: 67
Column: 34
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 999)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1000)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1000)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1001)
title = sum_info.GetProperty(msilib.PID_TITLE)
Reported by Pylint.
Line: 68
Column: 42
self.assertEqual(title, b"a" * 999)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1000)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1000)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1001)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1001)
Reported by Pylint.
Line: 71
Column: 34
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1000)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1001)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1001)
finally:
db = None
sum_info = None
Reported by Pylint.
Line: 72
Column: 42
self.assertEqual(title, b"a" * 1000)
sum_info.SetProperty(msilib.PID_TITLE, "a" * 1001)
title = sum_info.GetProperty(msilib.PID_TITLE)
self.assertEqual(title, b"a" * 1001)
finally:
db = None
sum_info = None
os.unlink(db_path)
Reported by Pylint.
Line: 80
Column: 32
os.unlink(db_path)
def test_database_open_failed(self):
with self.assertRaises(msilib.MSIError) as cm:
msilib.OpenDatabase('non-existent.msi', msilib.MSIDBOPEN_READONLY)
self.assertEqual(str(cm.exception), 'open failed')
def test_database_create_failed(self):
db_path = os.path.join(TESTFN, 'test.msi')
Reported by Pylint.
Line: 81
Column: 53
def test_database_open_failed(self):
with self.assertRaises(msilib.MSIError) as cm:
msilib.OpenDatabase('non-existent.msi', msilib.MSIDBOPEN_READONLY)
self.assertEqual(str(cm.exception), 'open failed')
def test_database_create_failed(self):
db_path = os.path.join(TESTFN, 'test.msi')
with self.assertRaises(msilib.MSIError) as cm:
Reported by Pylint.
Line: 81
Column: 13
def test_database_open_failed(self):
with self.assertRaises(msilib.MSIError) as cm:
msilib.OpenDatabase('non-existent.msi', msilib.MSIDBOPEN_READONLY)
self.assertEqual(str(cm.exception), 'open failed')
def test_database_create_failed(self):
db_path = os.path.join(TESTFN, 'test.msi')
with self.assertRaises(msilib.MSIError) as cm:
Reported by Pylint.
Tools/peg_generator/pegen/first_sets.py
46 issues
Line: 9
Column: 1
from typing import Set, Dict
from pegen.build import build_parser
from pegen.grammar import (
Alt,
Cut,
Gather,
Grammar,
GrammarVisitor,
Reported by Pylint.
Line: 9
Column: 1
from typing import Set, Dict
from pegen.build import build_parser
from pegen.grammar import (
Alt,
Cut,
Gather,
Grammar,
GrammarVisitor,
Reported by Pylint.
Line: 9
Column: 1
from typing import Set, Dict
from pegen.build import build_parser
from pegen.grammar import (
Alt,
Cut,
Gather,
Grammar,
GrammarVisitor,
Reported by Pylint.
Line: 9
Column: 1
from typing import Set, Dict
from pegen.build import build_parser
from pegen.grammar import (
Alt,
Cut,
Gather,
Grammar,
GrammarVisitor,
Reported by Pylint.
Line: 47
Column: 13
self.in_process: Set[str] = set()
def calculate(self) -> Dict[str, Set[str]]:
for name, rule in self.rules.items():
self.visit(rule)
return self.first_sets
def visit_Alt(self, item: Alt) -> Set[str]:
result: Set[str] = set()
Reported by Pylint.
Line: 78
Column: 25
return result
def visit_Cut(self, item: Cut) -> Set[str]:
return set()
def visit_Group(self, item: Group) -> Set[str]:
return self.visit(item.rhs)
Reported by Pylint.
Line: 143
Column: 18
args = argparser.parse_args()
try:
grammar, parser, tokenizer = build_parser(args.grammar_file)
except Exception as err:
print("ERROR: Failed to parse grammar file", file=sys.stderr)
sys.exit(1)
firs_sets = FirstSetCalculator(grammar.rules).calculate()
Reported by Pylint.
Line: 143
Column: 26
args = argparser.parse_args()
try:
grammar, parser, tokenizer = build_parser(args.grammar_file)
except Exception as err:
print("ERROR: Failed to parse grammar file", file=sys.stderr)
sys.exit(1)
firs_sets = FirstSetCalculator(grammar.rules).calculate()
Reported by Pylint.
Line: 144
Column: 5
try:
grammar, parser, tokenizer = build_parser(args.grammar_file)
except Exception as err:
print("ERROR: Failed to parse grammar file", file=sys.stderr)
sys.exit(1)
firs_sets = FirstSetCalculator(grammar.rules).calculate()
pprint.pprint(firs_sets)
Reported by Pylint.
Line: 144
Column: 12
try:
grammar, parser, tokenizer = build_parser(args.grammar_file)
except Exception as err:
print("ERROR: Failed to parse grammar file", file=sys.stderr)
sys.exit(1)
firs_sets = FirstSetCalculator(grammar.rules).calculate()
pprint.pprint(firs_sets)
Reported by Pylint.
Lib/test/test_typing.py
46 issues
Line: 250
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
code = ("import typing\n"
"T = typing.TypeVar('T')\n"
)
exec(code, {})
def test_no_bivariant(self):
with self.assertRaises(ValueError):
TypeVar('T', covariant=True, contravariant=True)
Reported by Bandit.
Line: 544
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
alias = Callable[[int, str], float]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(alias, proto)
loaded = pickle.loads(s)
self.assertEqual(alias.__origin__, loaded.__origin__)
self.assertEqual(alias.__args__, loaded.__args__)
self.assertEqual(alias.__parameters__, loaded.__parameters__)
def test_var_substitution(self):
Reported by Bandit.
Line: 1513
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
c.bar = 'abc'
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(c, proto)
x = pickle.loads(z)
self.assertEqual(x.foo, 42)
self.assertEqual(x.bar, 'abc')
self.assertEqual(x.x, 1)
self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
s = pickle.dumps(P)
Reported by Bandit.
Line: 1519
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
self.assertEqual(x.x, 1)
self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
s = pickle.dumps(P)
D = pickle.loads(s)
class E:
x = 1
self.assertIsInstance(E(), D)
Reported by Bandit.
Line: 2087
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
c.bar = 'abc'
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(c, proto)
x = pickle.loads(z)
self.assertEqual(x.foo, 42)
self.assertEqual(x.bar, 'abc')
self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
samples = [Any, Union, Tuple, Callable, ClassVar,
Union[int, str], ClassVar[List], Tuple[int, ...], Callable[[str], bytes],
Reported by Bandit.
Line: 2097
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
for s in samples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(s, proto)
x = pickle.loads(z)
self.assertEqual(s, x)
more_samples = [List, typing.Iterable, typing.Type, List[int],
typing.Type[typing.Mapping], typing.AbstractSet[Tuple[int, str]]]
for s in more_samples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
Reported by Bandit.
Line: 2104
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
for s in more_samples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(s, proto)
x = pickle.loads(z)
self.assertEqual(s, x)
def test_copy_and_deepcopy(self):
T = TypeVar('T')
class Node(Generic[T]): ...
Reported by Bandit.
Line: 2130
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
Union, Any, Tuple, Callable]:
self.assertIs(copy(X), X)
self.assertIs(deepcopy(X), X)
self.assertIs(pickle.loads(pickle.dumps(X)), X)
# Check that local type variables are copyable.
TL = TypeVar('TL')
TLB = TypeVar('TLB', bound=int)
TLV = TypeVar('TLV', bytes, str)
for X in [TL, TLB, TLV]:
Reported by Bandit.
Line: 2887
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
" def bar(self, b: 'D') -> C: pass\n"
)
ns = {}
exec(code, ns)
hints = get_type_hints(ns['C'].foo)
self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']})
def test_final_forward_ref(self):
self.assertEqual(gth(Loop, globals())['attr'], Final[Loop])
Reported by Bandit.
Line: 2960
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
"""
try:
exec(ASYNCIO_TESTS)
except ImportError:
ASYNCIO = False # multithreading is not enabled
else:
ASYNCIO = True
Reported by Bandit.
Modules/getpath.c
46 issues
Line: 297
Column: 5
CWE codes:
120
Suggestion:
Consider using a function version that stops copying at the end of the buffer
return NULL;
}
wcscpy(new_path, path);
if (add_sep) {
wcscat(new_path, separator);
}
wcscat(new_path, path2);
return new_path;
Reported by FlawFinder.
Line: 299
Column: 9
CWE codes:
120
wcscpy(new_path, path);
if (add_sep) {
wcscat(new_path, separator);
}
wcscat(new_path, path2);
return new_path;
}
Reported by FlawFinder.
Line: 301
Column: 5
CWE codes:
120
if (add_sep) {
wcscat(new_path, separator);
}
wcscat(new_path, path2);
return new_path;
}
static inline int
Reported by FlawFinder.
Line: 1377
Column: 9
CWE codes:
120
Suggestion:
Consider using a function version that stops copying at the end of the buffer
/* Run-time value of $PYTHONPATH goes first */
if (calculate->pythonpath_env) {
wcscpy(buf, calculate->pythonpath_env);
wcscat(buf, delimiter);
}
/* Next is the default zip path */
wcscat(buf, calculate->zip_path);
Reported by FlawFinder.
Line: 1378
Column: 9
CWE codes:
120
/* Run-time value of $PYTHONPATH goes first */
if (calculate->pythonpath_env) {
wcscpy(buf, calculate->pythonpath_env);
wcscat(buf, delimiter);
}
/* Next is the default zip path */
wcscat(buf, calculate->zip_path);
wcscat(buf, delimiter);
Reported by FlawFinder.
Line: 1382
Column: 5
CWE codes:
120
}
/* Next is the default zip path */
wcscat(buf, calculate->zip_path);
wcscat(buf, delimiter);
/* Next goes merge of compile-time $PYTHONPATH with
* dynamically located prefix.
*/
Reported by FlawFinder.
Line: 1383
Column: 5
CWE codes:
120
/* Next is the default zip path */
wcscat(buf, calculate->zip_path);
wcscat(buf, delimiter);
/* Next goes merge of compile-time $PYTHONPATH with
* dynamically located prefix.
*/
defpath = calculate->pythonpath_macro;
Reported by FlawFinder.
Line: 1393
Column: 13
CWE codes:
120
wchar_t *delim = wcschr(defpath, DELIM);
if (!_Py_isabs(defpath)) {
wcscat(buf, calculate->prefix);
if (prefixsz >= 2 && calculate->prefix[prefixsz - 2] != SEP &&
defpath[0] != (delim ? DELIM : L'\0'))
{
/* not empty */
wcscat(buf, separator);
Reported by FlawFinder.
Line: 1398
Column: 17
CWE codes:
120
defpath[0] != (delim ? DELIM : L'\0'))
{
/* not empty */
wcscat(buf, separator);
}
}
if (delim) {
size_t len = delim - defpath + 1;
Reported by FlawFinder.
Line: 1409
Column: 13
CWE codes:
120
buf[end] = '\0';
}
else {
wcscat(buf, defpath);
break;
}
defpath = delim + 1;
}
wcscat(buf, delimiter);
Reported by FlawFinder.
Lib/contextlib.py
46 issues
Line: 78
Column: 13
def __call__(self, func):
@wraps(func)
def inner(*args, **kwds):
with self._recreate_cm():
return func(*args, **kwds)
return inner
class AsyncContextDecorator(object):
Reported by Pylint.
Line: 94
Column: 13
def __call__(self, func):
@wraps(func)
async def inner(*args, **kwds):
async with self._recreate_cm():
return await func(*args, **kwds)
return inner
class _GeneratorContextManagerBase:
Reported by Pylint.
Line: 199
Column: 26
# they are only needed for recreation, which is not possible anymore
del self.args, self.kwds, self.func
try:
return await anext(self.gen)
except StopAsyncIteration:
raise RuntimeError("generator didn't yield") from None
async def __aexit__(self, typ, value, traceback):
if typ is None:
Reported by Pylint.
Line: 206
Column: 23
async def __aexit__(self, typ, value, traceback):
if typ is None:
try:
await anext(self.gen)
except StopAsyncIteration:
return False
else:
raise RuntimeError("generator didn't stop")
else:
Reported by Pylint.
Line: 33
Column: 20
@classmethod
def __subclasshook__(cls, C):
if cls is AbstractContextManager:
return _collections_abc._check_methods(C, "__enter__", "__exit__")
return NotImplemented
class AbstractAsyncContextManager(abc.ABC):
Reported by Pylint.
Line: 55
Column: 20
@classmethod
def __subclasshook__(cls, C):
if cls is AbstractAsyncContextManager:
return _collections_abc._check_methods(C, "__aenter__",
"__aexit__")
return NotImplemented
class ContextDecorator(object):
Reported by Pylint.
Line: 175
Column: 20
):
return False
raise
except BaseException as exc:
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
Reported by Pylint.
Line: 239
Column: 20
):
return False
raise
except BaseException as exc:
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
Reported by Pylint.
Line: 448
Column: 27
@staticmethod
def _create_cb_wrapper(callback, /, *args, **kwds):
def _exit_wrapper(exc_type, exc, tb):
callback(*args, **kwds)
return _exit_wrapper
def __init__(self):
self._exit_callbacks = deque()
Reported by Pylint.
Line: 448
Column: 42
@staticmethod
def _create_cb_wrapper(callback, /, *args, **kwds):
def _exit_wrapper(exc_type, exc, tb):
callback(*args, **kwds)
return _exit_wrapper
def __init__(self):
self._exit_callbacks = deque()
Reported by Pylint.
Lib/idlelib/idle_test/test_textview.py
46 issues
Line: 20
Column: 5
from idlelib.idle_test.mock_tk import Mbox_func
def setUpModule():
global root
root = Tk()
root.withdraw()
def tearDownModule():
global root
Reported by Pylint.
Line: 25
Column: 5
root.withdraw()
def tearDownModule():
global root
root.update_idletasks()
root.destroy()
del root
# If we call ViewWindow or wrapper functions with defaults
Reported by Pylint.
Line: 84
Column: 20
@classmethod
def setUpClass(cls):
cls.root = root = Tk()
root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
Reported by Pylint.
Line: 128
Column: 20
@classmethod
def setUpClass(cls):
cls.root = root = Tk()
root.withdraw()
cls.frame = tv.ViewFrame(root, 'test text')
@classmethod
def tearDownClass(cls):
Reported by Pylint.
Line: 9
Column: 1
information about calls.
"""
from idlelib import textview as tv
from test.support import requires
requires('gui')
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
Reported by Pylint.
Line: 12
Column: 1
from test.support import requires
requires('gui')
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
from tkinter.ttk import Button
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Mbox_func
Reported by Pylint.
Line: 12
Column: 1
from test.support import requires
requires('gui')
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
from tkinter.ttk import Button
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Mbox_func
Reported by Pylint.
Line: 13
Column: 1
requires('gui')
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
from tkinter.ttk import Button
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Mbox_func
Reported by Pylint.
Line: 13
Column: 1
requires('gui')
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
from tkinter.ttk import Button
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Mbox_func
Reported by Pylint.
Line: 14
Column: 1
import os
import unittest
from tkinter import Tk, TclError, CHAR, NONE, WORD
from tkinter.ttk import Button
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Mbox_func
def setUpModule():
Reported by Pylint.