The following issues were found
Modules/_pickle.c
48 issues
Line: 6640
Column: 15
CWE codes:
327
Suggestion:
Use a more secure technique for acquiring random values
load_build(UnpicklerObject *self)
{
PyObject *state, *inst, *slotstate;
PyObject *setstate;
int status = 0;
_Py_IDENTIFIER(__setstate__);
/* Stack is ... instance, state. We want to leave instance at
* the stack top, possibly mutated via instance.__setstate__(state).
Reported by FlawFinder.
Line: 6656
Column: 59
CWE codes:
327
Suggestion:
Use a more secure technique for acquiring random values
inst = self->stack->data[Py_SIZE(self->stack) - 1];
if (_PyObject_LookupAttrId(inst, &PyId___setstate__, &setstate) < 0) {
Py_DECREF(state);
return -1;
}
if (setstate != NULL) {
PyObject *result;
Reported by FlawFinder.
Line: 6660
Column: 9
CWE codes:
327
Suggestion:
Use a more secure technique for acquiring random values
Py_DECREF(state);
return -1;
}
if (setstate != NULL) {
PyObject *result;
/* The explicit __setstate__ is responsible for everything. */
result = _Pickle_FastCall(setstate, state);
Py_DECREF(setstate);
Reported by FlawFinder.
Line: 6664
Column: 35
CWE codes:
327
Suggestion:
Use a more secure technique for acquiring random values
PyObject *result;
/* The explicit __setstate__ is responsible for everything. */
result = _Pickle_FastCall(setstate, state);
Py_DECREF(setstate);
if (result == NULL)
return -1;
Py_DECREF(result);
return 0;
Reported by FlawFinder.
Line: 6665
Column: 19
CWE codes:
327
Suggestion:
Use a more secure technique for acquiring random values
/* The explicit __setstate__ is responsible for everything. */
result = _Pickle_FastCall(setstate, state);
Py_DECREF(setstate);
if (result == NULL)
return -1;
Py_DECREF(result);
return 0;
}
Reported by FlawFinder.
Line: 772
Column: 5
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
for (size_t i = 0; i < self->mt_allocated; i++) {
Py_XINCREF(self->mt_table[i].me_key);
}
memcpy(new->mt_table, self->mt_table,
sizeof(PyMemoEntry) * self->mt_allocated);
return new;
}
Reported by FlawFinder.
Line: 1099
Column: 9
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
}
}
else {
memcpy(buffer + self->output_len, s, data_len);
}
self->output_len += data_len;
return data_len;
}
Reported by FlawFinder.
Line: 1366
Column: 9
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
Py_ssize_t in_buffer = self->input_len - self->next_read_idx;
if (in_buffer > 0) {
Py_ssize_t to_read = Py_MIN(in_buffer, n);
memcpy(buf, self->input_buffer + self->next_read_idx, to_read);
self->next_read_idx += to_read;
buf += to_read;
n -= to_read;
if (n == 0) {
/* Entire read was satisfied from buffer */
Reported by FlawFinder.
Line: 1408
Column: 9
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
Py_DECREF(data);
return bad_readline();
}
memcpy(buf, PyBytes_AS_STRING(data), n);
Py_DECREF(data);
return n;
}
/* Call readinto() into user buffer */
Reported by FlawFinder.
Line: 1468
Column: 5
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
return -1;
}
memcpy(input_line, line, len);
input_line[len] = '\0';
self->input_line = input_line;
*result = self->input_line;
return len;
}
Reported by FlawFinder.
Lib/unittest/test/test_break.py
48 issues
Line: 69
Column: 25
test(result)
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(result.breakCaught)
def testSecondInterrupt(self):
# Can't use skipIf decorator because the signal handler may have
# been changed after defining this method.
Reported by Pylint.
Line: 95
Column: 25
pass
else:
self.fail("Second KeyboardInterrupt not raised")
self.assertTrue(result.breakCaught)
def testTwoResults(self):
unittest.installHandler()
Reported by Pylint.
Line: 23
Column: 9
def tearDown(self):
signal.signal(signal.SIGINT, self._default_handler)
unittest.signals._results = weakref.WeakKeyDictionary()
unittest.signals._interrupt_handler = None
def testInstallHandler(self):
default_handler = signal.getsignal(signal.SIGINT)
Reported by Pylint.
Line: 24
Column: 9
def tearDown(self):
signal.signal(signal.SIGINT, self._default_handler)
unittest.signals._results = weakref.WeakKeyDictionary()
unittest.signals._interrupt_handler = None
def testInstallHandler(self):
default_handler = signal.getsignal(signal.SIGINT)
unittest.installHandler()
Reported by Pylint.
Line: 38
Column: 25
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(unittest.signals._interrupt_handler.called)
def testRegisterResult(self):
result = unittest.TestResult()
self.assertNotIn(result, unittest.signals._results)
Reported by Pylint.
Line: 42
Column: 34
def testRegisterResult(self):
result = unittest.TestResult()
self.assertNotIn(result, unittest.signals._results)
unittest.registerResult(result)
try:
self.assertIn(result, unittest.signals._results)
finally:
Reported by Pylint.
Line: 46
Column: 35
unittest.registerResult(result)
try:
self.assertIn(result, unittest.signals._results)
finally:
unittest.removeResult(result)
def testInterruptCaught(self):
default_handler = signal.getsignal(signal.SIGINT)
Reported by Pylint.
Line: 111
Column: 18
result3 = unittest.TestResult()
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
try:
test(result)
Reported by Pylint.
Line: 154
Column: 31
runner = unittest.TextTestRunner(stream=io.StringIO())
result = runner.run(unittest.TestSuite())
self.assertIn(result, unittest.signals._results)
def testWeakReferences(self):
# Calling registerResult on a result should not keep it alive
result = unittest.TestResult()
unittest.registerResult(result)
Reported by Pylint.
Line: 204
Column: 13
return result
class Program(unittest.TestProgram):
def __init__(self, catchbreak):
self.exit = False
self.verbosity = verbosity
self.failfast = failfast
self.catchbreak = catchbreak
self.tb_locals = False
Reported by Pylint.
Tools/scripts/fixdiv.py
48 issues
Line: 157
Column: 9
usage("at least one file argument is required")
return 2
if args[1:]:
sys.stderr.write("%s: extra file arguments ignored\n", sys.argv[0])
warnings = readwarnings(args[0])
if warnings is None:
return 1
files = list(warnings.keys())
if not files:
Reported by Pylint.
Line: 146
Column: 12
except getopt.error as msg:
usage(msg)
return 2
for o, a in opts:
if o == "-h":
print(__doc__)
return
if o == "-m":
global multi_ok
Reported by Pylint.
Line: 151
Column: 13
print(__doc__)
return
if o == "-m":
global multi_ok
multi_ok = 1
if not args:
usage("at least one file argument is required")
return 2
if args[1:]:
Reported by Pylint.
Line: 166
Column: 5
print("No classic division warnings read from", args[0])
return
files.sort()
exit = None
for filename in files:
x = process(filename, warnings[filename])
exit = exit or x
return exit
Reported by Pylint.
Line: 199
Column: 13
sys.stderr.write("Warning: ignored input " + line)
continue
filename, lineno, what = m.groups()
list = warnings.get(filename)
if list is None:
warnings[filename] = list = []
list.append((int(lineno), sys.intern(what)))
return warnings
Reported by Pylint.
Line: 205
Column: 23
list.append((int(lineno), sys.intern(what)))
return warnings
def process(filename, list):
print("-"*70)
assert list # if this fails, readwarnings() is broken
try:
fp = open(filename)
except IOError as msg:
Reported by Pylint.
Line: 220
Column: 47
index = 0 # list[:index] has been processed, list[index:] is still to do
g = tokenize.generate_tokens(f.readline)
while 1:
startlineno, endlineno, slashes = lineinfo = scanline(g)
if startlineno is None:
break
assert startlineno <= endlineno is not None
orphans = []
while index < len(list) and list[index][0] < startlineno:
Reported by Pylint.
Line: 259
Column: 21
intlong = []
floatcomplex = []
bad = []
for lineno, what in warnings:
if what in ("int", "long"):
intlong.append(what)
elif what in ("float", "complex"):
floatcomplex.append(what)
else:
Reported by Pylint.
Line: 309
Column: 15
def report(slashes, message):
lastrow = None
for (row, col), line in slashes:
if row != lastrow:
print("*** %s on line %d:" % (message, row))
print("*", chop(line))
lastrow = row
Reported by Pylint.
Line: 316
Column: 28
lastrow = row
class FileContext:
def __init__(self, fp, window=5, lineno=1):
self.fp = fp
self.window = 5
self.lineno = 1
self.eoflookahead = 0
self.lookahead = []
Reported by Pylint.
Lib/distutils/command/bdist_rpm.py
48 issues
Line: 340
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html
q_cmd = r"rpm -q --qf '%s %s\n' --specfile '%s'" % (
src_rpm, non_src_rpm, spec_path)
out = os.popen(q_cmd)
try:
binary_rpms = []
source_rpm = None
while True:
line = out.readline()
Reported by Bandit.
Line: 220
Column: 61
self.ensure_string_list('doc_files')
if isinstance(self.doc_files, list):
for readme in ('README', 'README.txt'):
if os.path.exists(readme) and readme not in self.doc_files:
self.doc_files.append(readme)
self.ensure_string('release', "1")
self.ensure_string('serial') # should it be an int?
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Line: 10
Column: 1
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_rpm(Command):
Reported by Pylint.
Lib/distutils/tests/test_sysconfig.py
48 issues
Line: 144
Column: 26
self.assertEqual(comp.exes['linker_so'],
('env_ldshared --env-ldflags --env-cflags'
' --env-cppflags'))
self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix')
del os.environ['AR']
del os.environ['CC']
del os.environ['CPP']
del os.environ['CXX']
Reported by Pylint.
Line: 171
Column: 26
'sc_cc')
self.assertEqual(comp.exes['linker_so'],
'sc_ldshared')
self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix')
def test_parse_makefile_base(self):
self.makefile = TESTFN
fd = open(self.makefile, 'w')
try:
Reported by Pylint.
Line: 40
Column: 3
self.assertTrue(os.path.isfile(config_h), config_h)
def test_get_python_lib(self):
# XXX doesn't work on Linux when Python was never installed before
#self.assertTrue(os.path.isdir(lib_dir), lib_dir)
# test for pythonxx.lib?
self.assertNotEqual(sysconfig.get_python_lib(),
sysconfig.get_python_lib(prefix=TESTFN))
Reported by Pylint.
Line: 63
Column: 29
# should be a full source checkout.
Python_h = os.path.join(srcdir, 'Include', 'Python.h')
self.assertTrue(os.path.exists(Python_h), Python_h)
self.assertTrue(sysconfig._is_python_source_dir(srcdir))
elif os.name == 'posix':
self.assertEqual(
os.path.dirname(sysconfig.get_makefile_filename()),
srcdir)
Reported by Pylint.
Line: 87
Column: 17
compiler_type = 'unix'
def set_executables(self, **kw):
self.exes = kw
sysconfig_vars = {
'AR': 'sc_ar',
'CC': 'sc_cc',
'CXX': 'sc_cxx',
Reported by Pylint.
Line: 106
Column: 44
comp = compiler()
with contextlib.ExitStack() as cm:
for key, value in sysconfig_vars.items():
cm.enter_context(swap_item(sysconfig._config_vars, key, value))
sysconfig.customize_compiler(comp)
return comp
@unittest.skipUnless(get_default_compiler() == 'unix',
Reported by Pylint.
Line: 246
Column: 9
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_SO_in_vars(self):
vars = sysconfig.get_config_vars()
self.assertIsNotNone(vars['SO'])
self.assertEqual(vars['SO'], vars['EXT_SUFFIX'])
def test_customize_compiler_before_get_config_vars(self):
# Issue #21923: test that a Distribution compiler
Reported by Pylint.
Line: 266
Column: 15
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
outs, errs = p.communicate()
self.assertEqual(0, p.returncode, "Subprocess failed: " + outs)
def test_suite():
suite = unittest.TestSuite()
Reported by Pylint.
Line: 5
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess
import contextlib
import os
import shutil
import subprocess
import sys
import textwrap
import unittest
from distutils import sysconfig
Reported by Bandit.
Line: 18
Column: 1
from test.support.warnings_helper import check_warnings
class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
def setUp(self):
super(SysconfigTestCase, self).setUp()
self.makefile = None
def tearDown(self):
Reported by Pylint.
Lib/fileinput.py
47 issues
Line: 217
Column: 27
"b" not in mode and encoding is None and openhook is None):
import warnings
warnings.warn("'encoding' argument not specified.",
EncodingWarning, 2)
# restrict mode argument to reading modes
if mode not in ('r', 'rU', 'U', 'rb'):
raise ValueError("FileInput opening mode must be one of "
"'r', 'rU', 'U' and 'rb'")
Reported by Pylint.
Line: 321
Column: 5
self.nextfile()
# repeat with next file
def _readline(self):
if not self._files:
if 'b' in self._mode:
return b''
else:
return ''
Reported by Pylint.
Line: 366
Column: 33
else:
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY
fd = os.open(self._filename, mode, perm)
self._output = os.fdopen(fd, self._write_mode, encoding=encoding)
try:
os.chmod(self._filename, perm)
Reported by Pylint.
Line: 78
Column: 1
_state = None
def input(files=None, inplace=False, backup="", *, mode="r", openhook=None,
encoding=None, errors=None):
"""Return an instance of the FileInput class, which can be iterated.
The parameters are passed to the constructor of the FileInput class.
The returned instance, in addition to being an iterator,
Reported by Pylint.
Line: 86
Column: 5
The returned instance, in addition to being an iterator,
keeps global state for the functions of this module,.
"""
global _state
if _state and _state._file:
raise RuntimeError("input() already active")
_state = FileInput(files, inplace, backup, mode=mode, openhook=openhook,
encoding=encoding, errors=errors)
return _state
Reported by Pylint.
Line: 87
Column: 19
keeps global state for the functions of this module,.
"""
global _state
if _state and _state._file:
raise RuntimeError("input() already active")
_state = FileInput(files, inplace, backup, mode=mode, openhook=openhook,
encoding=encoding, errors=errors)
return _state
Reported by Pylint.
Line: 95
Column: 5
def close():
"""Close the sequence."""
global _state
state = _state
_state = None
if state:
state.close()
Reported by Pylint.
Line: 248
Column: 24
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __iter__(self):
return self
Reported by Pylint.
Line: 278
Column: 13
try:
return self.__next__()
except StopIteration:
raise IndexError("end of input reached")
def nextfile(self):
savestdout = self._savestdout
self._savestdout = None
if savestdout:
Reported by Pylint.
Line: 418
Column: 21
__class_getitem__ = classmethod(GenericAlias)
def hook_compressed(filename, mode, *, encoding=None, errors=None):
if encoding is None: # EncodingWarning is emitted in FileInput() already.
encoding = "locale"
ext = os.path.splitext(filename)[1]
if ext == '.gz':
import gzip
Reported by Pylint.
Lib/cProfile.py
47 issues
Line: 16
Column: 12
# Simple interface
def run(statement, filename=None, sort=-1):
return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
filename, sort)
Reported by Pylint.
Line: 18
Column: 32
def run(statement, filename=None, sort=-1):
return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
filename, sort)
run.__doc__ = _pyprofile.run.__doc__
runctx.__doc__ = _pyprofile.runctx.__doc__
Reported by Pylint.
Line: 18
Column: 23
def run(statement, filename=None, sort=-1):
return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
filename, sort)
run.__doc__ = _pyprofile.run.__doc__
runctx.__doc__ = _pyprofile.runctx.__doc__
Reported by Pylint.
Line: 19
Column: 12
return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
filename, sort)
run.__doc__ = _pyprofile.run.__doc__
runctx.__doc__ = _pyprofile.runctx.__doc__
Reported by Pylint.
Line: 56
Column: 9
def snapshot_stats(self):
entries = self.getstats()
self.stats = {}
callersdicts = {}
# call information
for entry in entries:
func = label(entry.code)
nc = entry.callcount # ncalls column of pstats (before '/')
Reported by Pylint.
Line: 94
Column: 9
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.enable()
try:
Reported by Pylint.
Line: 97
Column: 36
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec(cmd, globals, locals)
finally:
self.disable()
Reported by Pylint.
Line: 97
Column: 27
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec(cmd, globals, locals)
finally:
self.disable()
Reported by Pylint.
Line: 100
Column: 13
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec(cmd, globals, locals)
finally:
self.disable()
return self
# This method is more useful to profile a single function call.
Reported by Pylint.
Line: 100
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec(cmd, globals, locals)
finally:
self.disable()
return self
# This method is more useful to profile a single function call.
Reported by Bandit.
Lib/distutils/tests/test_build_ext.py
47 issues
Line: 44
Column: 9
# working directory. Create a temporary working directory to cleanup
# everything at the end of the test.
change_cwd = os_helper.change_cwd(self.tmp_dir)
change_cwd.__enter__()
self.addCleanup(change_cwd.__exit__, None, None, None)
def tearDown(self):
import site
site.USER_BASE = self.old_user_base
Reported by Pylint.
Line: 45
Column: 25
# everything at the end of the test.
change_cwd = os_helper.change_cwd(self.tmp_dir)
change_cwd.__enter__()
self.addCleanup(change_cwd.__exit__, None, None, None)
def tearDown(self):
import site
site.USER_BASE = self.old_user_base
from distutils.command import build_ext
Reported by Pylint.
Line: 291
Column: 26
# check_extensions_list adds in ext the values passed
# when they are in ('include_dirs', 'library_dirs', 'libraries'
# 'extra_objects', 'extra_compile_args', 'extra_link_args')
self.assertEqual(ext.libraries, 'foo')
self.assertFalse(hasattr(ext, 'some'))
# 'macros' element of build info dict must be 1- or 2-tuple
exts = [('foo.bar', {'sources': [''], 'libraries': 'foo',
'some': 'bar', 'macros': [('1', '2', '3'), 'foo']})]
Reported by Pylint.
Line: 301
Column: 26
exts[0][1]['macros'] = [('1', '2'), ('3',)]
cmd.check_extensions_list(exts)
self.assertEqual(exts[0].undef_macros, ['3'])
self.assertEqual(exts[0].define_macros, [('1', '2')])
def test_get_source_files(self):
modules = [Extension('foo', ['xxx'], optional=False)]
dist = Distribution({'name': 'xx', 'ext_modules': modules})
Reported by Pylint.
Line: 302
Column: 26
exts[0][1]['macros'] = [('1', '2'), ('3',)]
cmd.check_extensions_list(exts)
self.assertEqual(exts[0].undef_macros, ['3'])
self.assertEqual(exts[0].define_macros, [('1', '2')])
def test_get_source_files(self):
modules = [Extension('foo', ['xxx'], optional=False)]
dist = Distribution({'name': 'xx', 'ext_modules': modules})
cmd = self.build_ext(dist)
Reported by Pylint.
Line: 36
Column: 9
import site
self.old_user_base = site.USER_BASE
site.USER_BASE = self.mkdtemp()
from distutils.command import build_ext
build_ext.USER_BASE = site.USER_BASE
self.old_config_vars = dict(sysconfig._config_vars)
# bpo-30132: On Windows, a .pdb file may be created in the current
# working directory. Create a temporary working directory to cleanup
Reported by Pylint.
Line: 36
Column: 9
import site
self.old_user_base = site.USER_BASE
site.USER_BASE = self.mkdtemp()
from distutils.command import build_ext
build_ext.USER_BASE = site.USER_BASE
self.old_config_vars = dict(sysconfig._config_vars)
# bpo-30132: On Windows, a .pdb file may be created in the current
# working directory. Create a temporary working directory to cleanup
Reported by Pylint.
Line: 38
Column: 37
site.USER_BASE = self.mkdtemp()
from distutils.command import build_ext
build_ext.USER_BASE = site.USER_BASE
self.old_config_vars = dict(sysconfig._config_vars)
# bpo-30132: On Windows, a .pdb file may be created in the current
# working directory. Create a temporary working directory to cleanup
# everything at the end of the test.
change_cwd = os_helper.change_cwd(self.tmp_dir)
Reported by Pylint.
Line: 50
Column: 9
def tearDown(self):
import site
site.USER_BASE = self.old_user_base
from distutils.command import build_ext
build_ext.USER_BASE = self.old_user_base
sysconfig._config_vars.clear()
sysconfig._config_vars.update(self.old_config_vars)
super(BuildExtTestCase, self).tearDown()
Reported by Pylint.
Line: 50
Column: 9
def tearDown(self):
import site
site.USER_BASE = self.old_user_base
from distutils.command import build_ext
build_ext.USER_BASE = self.old_user_base
sysconfig._config_vars.clear()
sysconfig._config_vars.update(self.old_config_vars)
super(BuildExtTestCase, self).tearDown()
Reported by Pylint.
Lib/test/test_userdict.py
47 issues
Line: 146
Column: 35
def test_init(self):
for kw in 'self', 'other', 'iterable':
self.assertEqual(list(collections.UserDict(**{kw: 42}).items()),
[(kw, 42)])
self.assertEqual(list(collections.UserDict({}, dict=42).items()),
[('dict', 42)])
self.assertEqual(list(collections.UserDict({}, dict=None).items()),
[('dict', None)])
Reported by Pylint.
Line: 148
Column: 31
for kw in 'self', 'other', 'iterable':
self.assertEqual(list(collections.UserDict(**{kw: 42}).items()),
[(kw, 42)])
self.assertEqual(list(collections.UserDict({}, dict=42).items()),
[('dict', 42)])
self.assertEqual(list(collections.UserDict({}, dict=None).items()),
[('dict', None)])
self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()),
[('dict', {'a': 42})])
Reported by Pylint.
Line: 150
Column: 31
[(kw, 42)])
self.assertEqual(list(collections.UserDict({}, dict=42).items()),
[('dict', 42)])
self.assertEqual(list(collections.UserDict({}, dict=None).items()),
[('dict', None)])
self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()),
[('dict', {'a': 42})])
self.assertRaises(TypeError, collections.UserDict, 42)
self.assertRaises(TypeError, collections.UserDict, (), ())
Reported by Pylint.
Line: 54
Column: 9
"{'two': 2, 'one': 1}"))
# Test rich comparison and __len__
all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in all:
for b in all:
self.assertEqual(a == b, len(a) == len(b))
# Test __getitem__
Reported by Pylint.
Line: 1
Column: 1
# Check every path through every method of UserDict
from test import mapping_tests
import unittest
import collections
d0 = {}
d1 = {"one": 1}
d2 = {"one": 1, "two": 2}
Reported by Pylint.
Line: 14
Column: 1
d4 = {"one": None, "two": None}
d5 = {"one": 1, "two": 1}
class UserDictTest(mapping_tests.TestHashMappingProtocol):
type2test = collections.UserDict
def test_all(self):
# Test constructors
u = collections.UserDict()
Reported by Pylint.
Line: 17
Column: 5
class UserDictTest(mapping_tests.TestHashMappingProtocol):
type2test = collections.UserDict
def test_all(self):
# Test constructors
u = collections.UserDict()
u0 = collections.UserDict(d0)
u1 = collections.UserDict(d1)
u2 = collections.UserDict(d2)
Reported by Pylint.
Line: 17
Column: 5
class UserDictTest(mapping_tests.TestHashMappingProtocol):
type2test = collections.UserDict
def test_all(self):
# Test constructors
u = collections.UserDict()
u0 = collections.UserDict(d0)
u1 = collections.UserDict(d1)
u2 = collections.UserDict(d2)
Reported by Pylint.
Line: 17
Column: 5
class UserDictTest(mapping_tests.TestHashMappingProtocol):
type2test = collections.UserDict
def test_all(self):
# Test constructors
u = collections.UserDict()
u0 = collections.UserDict(d0)
u1 = collections.UserDict(d1)
u2 = collections.UserDict(d2)
Reported by Pylint.
Line: 19
Column: 9
def test_all(self):
# Test constructors
u = collections.UserDict()
u0 = collections.UserDict(d0)
u1 = collections.UserDict(d1)
u2 = collections.UserDict(d2)
uu = collections.UserDict(u)
Reported by Pylint.
Lib/test/test_importlib/fixtures.py
47 issues
Line: 52
Column: 9
class Fixtures:
def setUp(self):
self.fixtures = contextlib.ExitStack()
self.addCleanup(self.fixtures.close)
class SiteDir(Fixtures):
def setUp(self):
super(SiteDir, self).setUp()
Reported by Pylint.
Line: 73
Column: 55
def setUp(self):
super(OnSysPath, self).setUp()
self.fixtures.enter_context(self.add_sys_path(self.site_dir))
# Except for python/mypy#731, prefer to define
# FilesDef = Dict[str, Union['FilesDef', str]]
FilesDef = Dict[str, Union[Dict[str, Union[Dict[str, str], str]], str]]
Reported by Pylint.
Line: 236
Column: 9
def setUp(self):
self.fixtures = contextlib.ExitStack()
self.addCleanup(self.fixtures.close)
self.fixtures.enter_context(tempdir_as_cwd())
build_files(self.files)
def build_files(file_defs, prefix=pathlib.Path()):
Reported by Pylint.
Line: 277
Column: 31
class FileBuilder:
def unicode_filename(self):
return FS_NONASCII or self.skip("File system does not support non-ascii.")
def DALS(str):
"Dedent and left-strip"
return textwrap.dedent(str).lstrip()
Reported by Pylint.
Line: 64
Column: 22
class OnSysPath(Fixtures):
@staticmethod
@contextlib.contextmanager
def add_sys_path(dir):
sys.path[:0] = [str(dir)]
try:
yield
finally:
sys.path.remove(str(dir))
Reported by Pylint.
Line: 280
Column: 10
return FS_NONASCII or self.skip("File system does not support non-ascii.")
def DALS(str):
"Dedent and left-strip"
return textwrap.dedent(str).lstrip()
class NullFinder:
Reported by Pylint.
Line: 1
Column: 1
import os
import sys
import copy
import shutil
import pathlib
import tempfile
import textwrap
import contextlib
Reported by Pylint.
Line: 15
Column: 1
@contextlib.contextmanager
def tempdir():
tmpdir = tempfile.mkdtemp()
try:
yield pathlib.Path(tmpdir)
finally:
shutil.rmtree(tmpdir)
Reported by Pylint.
Line: 24
Column: 1
@contextlib.contextmanager
def save_cwd():
orig = os.getcwd()
try:
yield
finally:
os.chdir(orig)
Reported by Pylint.
Line: 33
Column: 1
@contextlib.contextmanager
def tempdir_as_cwd():
with tempdir() as tmp:
with save_cwd():
os.chdir(str(tmp))
yield tmp
Reported by Pylint.