The following issues were found
Lib/ctypes/test/test_internals.py
157 issues
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Line: 3
Column: 1
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
# ctypes' types are container types.
#
Reported by Pylint.
Lib/test/test_hashlib.py
157 issues
Line: 226
Column: 9
cons(usedforsecurity=True)
cons(b'', usedforsecurity=True)
hashlib.new("md5", usedforsecurity=True)
hashlib.md5(usedforsecurity=True)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=True)
self._hashlib.openssl_md5(usedforsecurity=True)
def test_usedforsecurity_false(self):
Reported by Pylint.
Line: 237
Column: 9
cons(usedforsecurity=False)
cons(b'', usedforsecurity=False)
hashlib.new("md5", usedforsecurity=False)
hashlib.md5(usedforsecurity=False)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=False)
self._hashlib.openssl_md5(usedforsecurity=False)
def test_unknown_hash(self):
Reported by Pylint.
Line: 81
Column: 9
try:
testdata = support.open_urlresource(url, encoding="utf-8")
except (OSError, HTTPException):
raise unittest.SkipTest("Could not retrieve {}".format(url))
with testdata:
for line in testdata:
line = line.strip()
if line.startswith('#') or not line:
continue
Reported by Pylint.
Line: 225
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b324_hashlib_new.html
for cons in self.hash_constructors:
cons(usedforsecurity=True)
cons(b'', usedforsecurity=True)
hashlib.new("md5", usedforsecurity=True)
hashlib.md5(usedforsecurity=True)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=True)
self._hashlib.openssl_md5(usedforsecurity=True)
Reported by Bandit.
Line: 226
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b303-md5
cons(usedforsecurity=True)
cons(b'', usedforsecurity=True)
hashlib.new("md5", usedforsecurity=True)
hashlib.md5(usedforsecurity=True)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=True)
self._hashlib.openssl_md5(usedforsecurity=True)
def test_usedforsecurity_false(self):
Reported by Bandit.
Line: 236
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b324_hashlib_new.html
for cons in self.hash_constructors:
cons(usedforsecurity=False)
cons(b'', usedforsecurity=False)
hashlib.new("md5", usedforsecurity=False)
hashlib.md5(usedforsecurity=False)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=False)
self._hashlib.openssl_md5(usedforsecurity=False)
Reported by Bandit.
Line: 237
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b303-md5
cons(usedforsecurity=False)
cons(b'', usedforsecurity=False)
hashlib.new("md5", usedforsecurity=False)
hashlib.md5(usedforsecurity=False)
if self._hashlib is not None:
self._hashlib.new("md5", usedforsecurity=False)
self._hashlib.openssl_md5(usedforsecurity=False)
def test_unknown_hash(self):
Reported by Bandit.
Line: 437
Column: 30
# _hashopenssl's variant does not have extra SHA3 attributes
continue
self.assertEqual(capacity + rate, 1600)
self.assertEqual(m._capacity_bits, capacity)
self.assertEqual(m._rate_bits, rate)
self.assertEqual(m._suffix, suffix)
def test_extra_sha3(self):
self.check_sha3('sha3_224', 448, 1152, b'\x06')
Reported by Pylint.
Line: 438
Column: 30
continue
self.assertEqual(capacity + rate, 1600)
self.assertEqual(m._capacity_bits, capacity)
self.assertEqual(m._rate_bits, rate)
self.assertEqual(m._suffix, suffix)
def test_extra_sha3(self):
self.check_sha3('sha3_224', 448, 1152, b'\x06')
self.check_sha3('sha3_256', 512, 1088, b'\x06')
Reported by Pylint.
Line: 439
Column: 30
self.assertEqual(capacity + rate, 1600)
self.assertEqual(m._capacity_bits, capacity)
self.assertEqual(m._rate_bits, rate)
self.assertEqual(m._suffix, suffix)
def test_extra_sha3(self):
self.check_sha3('sha3_224', 448, 1152, b'\x06')
self.check_sha3('sha3_256', 512, 1088, b'\x06')
self.check_sha3('sha3_384', 768, 832, b'\x06')
Reported by Pylint.
Lib/imaplib.py
156 issues
Line: 1370
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html
self.process = subprocess.Popen(self.command,
bufsize=DEFAULT_BUFFER_SIZE,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
shell=True, close_fds=True)
self.writefile = self.process.stdin
self.readfile = self.process.stdout
def read(self, size):
"""Read 'size' bytes from remote."""
Reported by Bandit.
Line: 188
Column: 24
class abort(error): pass # Service errors - close and retry
class readonly(abort): pass # Mailbox status changed to READ-ONLY
def __init__(self, host='', port=IMAP4_PORT, timeout=None):
self.debug = Debug
self.state = 'LOGOUT'
self.literal = None # A literal argument to a command
self.tagged_commands = {} # Tagged commands awaiting response
self.untagged_responses = {} # {typ: [data, ...], ...}
Reported by Pylint.
Line: 221
Column: 9
def _mode_utf8(self):
self.utf8_enabled = True
self._encoding = 'utf-8'
self.Literal = re.compile(_Literal)
self.Untagged_status = re.compile(_Untagged_status)
Reported by Pylint.
Line: 222
Column: 9
def _mode_utf8(self):
self.utf8_enabled = True
self._encoding = 'utf-8'
self.Literal = re.compile(_Literal)
self.Untagged_status = re.compile(_Untagged_status)
def _connect(self):
Reported by Pylint.
Line: 223
Column: 9
def _mode_utf8(self):
self.utf8_enabled = True
self._encoding = 'utf-8'
self.Literal = re.compile(_Literal)
self.Untagged_status = re.compile(_Untagged_status)
def _connect(self):
# Create unique tag for this session,
Reported by Pylint.
Line: 224
Column: 9
self.utf8_enabled = True
self._encoding = 'utf-8'
self.Literal = re.compile(_Literal)
self.Untagged_status = re.compile(_Untagged_status)
def _connect(self):
# Create unique tag for this session,
# and compile tagged response matcher.
Reported by Pylint.
Line: 278
Column: 1
def __enter__(self):
return self
def __exit__(self, *args):
if self.state == "LOGOUT":
return
try:
self.logout()
Reported by Pylint.
Line: 297
Column: 9
# as a default value for host.
if timeout is not None and not timeout:
raise ValueError('Non-blocking socket (timeout=0) is not supported')
host = None if not self.host else self.host
sys.audit("imaplib.open", self, self.host, self.port)
address = (host, self.port)
if timeout is not None:
return socket.create_connection(address, timeout)
return socket.create_connection(address)
Reported by Pylint.
Line: 304
Column: 20
return socket.create_connection(address, timeout)
return socket.create_connection(address)
def open(self, host='', port=IMAP4_PORT, timeout=None):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
Reported by Pylint.
Line: 373
Column: 14
else list of RECENT responses, most recent last.
"""
name = 'RECENT'
typ, dat = self._untagged_response('OK', [None], name)
if dat[-1]:
return typ, dat
typ, dat = self.noop() # Prod server for response
return self._untagged_response(typ, dat, name)
Reported by Pylint.
Lib/ctypes/__init__.py
156 issues
Line: 21
Column: 5
raise Exception("Version number mismatch", __version__, _ctypes_version)
if _os.name == "nt":
from _ctypes import FormatError
DEFAULT_MODE = RTLD_LOCAL
if _os.name == "posix" and _sys.platform == "darwin":
# On OS X 10.3, we use RTLD_GLOBAL as default mode
# because RTLD_LOCAL does not work at least on some
Reported by Pylint.
Line: 110
Column: 5
return CFunctionType
if _os.name == "nt":
from _ctypes import LoadLibrary as _dlopen
from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
_win_functype_cache = {}
def WINFUNCTYPE(restype, *argtypes, **kw):
# docstring set later (very similar to CFUNCTYPE.__doc__)
Reported by Pylint.
Line: 111
Column: 5
if _os.name == "nt":
from _ctypes import LoadLibrary as _dlopen
from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
_win_functype_cache = {}
def WINFUNCTYPE(restype, *argtypes, **kw):
# docstring set later (very similar to CFUNCTYPE.__doc__)
flags = _FUNCFLAG_STDCALL
Reported by Pylint.
Line: 357
Column: 27
Otherwise, name is presented to dlopen() as a file argument.
"""
if name and name.endswith(")") and ".a(" in name:
mode |= ( _os.RTLD_MEMBER | _os.RTLD_NOW )
if _os.name == "nt":
if winmode is not None:
mode = winmode
else:
import nt
Reported by Pylint.
Line: 362
Column: 17
if winmode is not None:
mode = winmode
else:
import nt
mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
if '/' in name or '\\' in name:
self._name = nt._getfullpathname(self._name)
mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
Reported by Pylint.
Line: 414
Column: 5
# XXX Hm, what about HRESULT as normal parameter?
# Mustn't it derive from c_long then?
from _ctypes import _check_HRESULT, _SimpleCData
class HRESULT(_SimpleCData):
_type_ = "l"
# _check_retval_ is called with the function's result when it
# is used as restype. It checks for the FAILED bit, and
# raises an OSError if it is set.
Reported by Pylint.
Line: 460
Column: 43
pydll = LibraryLoader(PyDLL)
if _os.name == "nt":
pythonapi = PyDLL("python dll", None, _sys.dllhandle)
elif _sys.platform == "cygwin":
pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
else:
pythonapi = PyDLL(None)
Reported by Pylint.
Line: 472
Column: 5
oledll = LibraryLoader(OleDLL)
GetLastError = windll.kernel32.GetLastError
from _ctypes import get_last_error, set_last_error
def WinError(code=None, descr=None):
if code is None:
code = GetLastError()
if descr is None:
Reported by Pylint.
Line: 472
Column: 5
oledll = LibraryLoader(OleDLL)
GetLastError = windll.kernel32.GetLastError
from _ctypes import get_last_error, set_last_error
def WinError(code=None, descr=None):
if code is None:
code = GetLastError()
if descr is None:
Reported by Pylint.
Line: 145
Column: 5
def _check_size(typ, typecode=None):
# Check if sizeof(ctypes_type) against struct.calcsize. This
# should protect somewhat against a misconfigured libffi.
from struct import calcsize
if typecode is None:
# Most _type_ codes are the same as used in struct
typecode = typ._type_
actual, required = sizeof(typ), calcsize(typecode)
if actual != required:
Reported by Pylint.
Lib/test/test_email/test_contentmanager.py
155 issues
Line: 21
Column: 42
'null_key': (3, '',),
}
def get_key_as_get_content_key(self, order, key):
def foo_getter(msg, foo=None):
bar = msg['X-Bar-Header']
return foo, bar
cm = ContentManager()
cm.add_get_handler(key, foo_getter)
Reported by Pylint.
Line: 77
Column: 42
'null_key': (11, None,),
}
def set_key_as_set_content_key(self, order, key):
def foo_setter(msg, obj, foo=None):
msg['X-Foo-Header'] = foo
msg.set_payload(obj)
cm = ContentManager()
cm.add_set_handler(key, foo_setter)
Reported by Pylint.
Line: 93
Column: 29
def foo_setter(msg, obj):
msg['X-FooBar-Header'] = 'foo'
msg.set_payload(obj)
def bar_setter(msg, obj):
msg['X-FooBar-Header'] = 'bar'
cm = ContentManager()
cm.add_set_handler(key, foo_setter)
for precedence, key in self.get_key_params.values():
if precedence > order:
Reported by Pylint.
Line: 555
Column: 3
# The choice of base64 for the body encoding is because generator
# doesn't bother with heuristics and uses it unconditionally for utf-8
# text.
# XXX: the first cte should be 7bit, too...that's a generator bug.
# XXX: the line length in the body also looks like a generator bug.
self.assertEqual(m.as_string(maxheaderlen=self.policy.max_line_length),
textwrap.dedent("""\
Subject: Escape report
Content-Type: message/rfc822
Reported by Pylint.
Line: 556
Column: 3
# doesn't bother with heuristics and uses it unconditionally for utf-8
# text.
# XXX: the first cte should be 7bit, too...that's a generator bug.
# XXX: the line length in the body also looks like a generator bug.
self.assertEqual(m.as_string(maxheaderlen=self.policy.max_line_length),
textwrap.dedent("""\
Subject: Escape report
Content-Type: message/rfc822
Content-Transfer-Encoding: 8bit
Reported by Pylint.
Line: 614
Column: 3
def test_set_audio_aif_with_quoted_printable_cte(self):
# Why you would use qp, I don't know, but it is technically supported.
# XXX: the incorrect line length is because binascii.b2a_qp doesn't
# support a line length parameter, but we must use it to get newline
# encoding.
# XXX: what about that lack of tailing newline? Do we actually handle
# that correctly in all cases? That is, if the *source* has an
# unencoded newline, do we add an extra newline to the returned payload
Reported by Pylint.
Line: 617
Column: 3
# XXX: the incorrect line length is because binascii.b2a_qp doesn't
# support a line length parameter, but we must use it to get newline
# encoding.
# XXX: what about that lack of tailing newline? Do we actually handle
# that correctly in all cases? That is, if the *source* has an
# unencoded newline, do we add an extra newline to the returned payload
# or not? And can that actually be disambiguated based on the RFC?
m = self._make_message()
content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100
Reported by Pylint.
Line: 644
Column: 3
MIME-Version: 1.0
""").encode('ascii') +
# XXX: the second \n ought to be a \r, but generator gets it wrong.
# THIS MEANS WE DON'T ACTUALLY SUPPORT THE 'binary' CTE.
b'b\xFFgus\tcon\nt\nent zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' +
b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz')
self.assertEqual(m.get_payload(decode=True), content)
self.assertEqual(m.get_content(), content)
Reported by Pylint.
Line: 752
Column: 3
m.set_content('foo', disposition='foo')
self.assertEqual(m['Content-Disposition'], 'foo')
# XXX: we should have a 'strict' policy mode (beyond raise_on_defect) that
# would cause 'foo' above to raise.
def test_set_filename(self):
m = self._make_message()
m.set_content('foo', filename='bar.txt')
Reported by Pylint.
Line: 1
Column: 1
import unittest
from test.test_email import TestEmailBase, parameterize
import textwrap
from email import policy
from email.message import EmailMessage
from email.contentmanager import ContentManager, raw_data_manager
@parameterize
Reported by Pylint.
Lib/statistics.py
154 issues
Line: 1209
Column: 5
"Square of the standard deviation."
return self._sigma ** 2.0
def __add__(x1, x2):
"""Add a constant or another NormalDist instance.
If *other* is a constant, translate mu by the constant,
leaving sigma unchanged.
Reported by Pylint.
Line: 1223
Column: 5
return NormalDist(x1._mu + x2._mu, hypot(x1._sigma, x2._sigma))
return NormalDist(x1._mu + x2, x1._sigma)
def __sub__(x1, x2):
"""Subtract a constant or another NormalDist instance.
If *other* is a constant, translate by the constant mu,
leaving sigma unchanged.
Reported by Pylint.
Line: 1237
Column: 5
return NormalDist(x1._mu - x2._mu, hypot(x1._sigma, x2._sigma))
return NormalDist(x1._mu - x2, x1._sigma)
def __mul__(x1, x2):
"""Multiply both mu and sigma by a constant.
Used for rescaling, perhaps to change measurement units.
Sigma is scaled with the absolute value of the constant.
"""
Reported by Pylint.
Line: 1245
Column: 5
"""
return NormalDist(x1._mu * x2, x1._sigma * fabs(x2))
def __truediv__(x1, x2):
"""Divide both mu and sigma by a constant.
Used for rescaling, perhaps to change measurement units.
Sigma is scaled with the absolute value of the constant.
"""
Reported by Pylint.
Line: 1253
Column: 5
"""
return NormalDist(x1._mu / x2, x1._sigma / fabs(x2))
def __pos__(x1):
"Return a copy of the instance."
return NormalDist(x1._mu, x1._sigma)
def __neg__(x1):
"Negates mu while keeping sigma the same."
Reported by Pylint.
Line: 1257
Column: 5
"Return a copy of the instance."
return NormalDist(x1._mu, x1._sigma)
def __neg__(x1):
"Negates mu while keeping sigma the same."
return NormalDist(-x1._mu, x1._sigma)
__radd__ = __add__
Reported by Pylint.
Line: 1263
Column: 5
__radd__ = __add__
def __rsub__(x1, x2):
"Subtract a NormalDist from a constant or another NormalDist."
return -(x1 - x2)
__rmul__ = __mul__
Reported by Pylint.
Line: 1269
Column: 5
__rmul__ = __mul__
def __eq__(x1, x2):
"Two NormalDist objects are equal if their mu and sigma are both equal."
if not isinstance(x2, NormalDist):
return NotImplemented
return x1._mu == x2._mu and x1._sigma == x2._sigma
Reported by Pylint.
Line: 203
Column: 3
assert not _isfinite(total)
else:
# Sum all the partial sums using builtin sum.
# FIXME is this faster if we sum them in order of the denominator?
total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
return (T, total, count)
def _isfinite(x):
Reported by Pylint.
Line: 287
Column: 3
if issubclass(T, int) and value.denominator != 1:
T = float
try:
# FIXME: what do we do if this overflows?
return T(value)
except TypeError:
if issubclass(T, Decimal):
return T(value.numerator) / T(value.denominator)
else:
Reported by Pylint.
Lib/test/test_contextlib_async.py
154 issues
Line: 33
Column: 23
async def test_enter(self):
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
manager = DefaultEnter()
self.assertIs(await manager.__aenter__(), manager)
async with manager as context:
Reported by Pylint.
Line: 33
Column: 23
async def test_enter(self):
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
manager = DefaultEnter()
self.assertIs(await manager.__aenter__(), manager)
async with manager as context:
Reported by Pylint.
Line: 33
Column: 23
async def test_enter(self):
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
manager = DefaultEnter()
self.assertIs(await manager.__aenter__(), manager)
async with manager as context:
Reported by Pylint.
Line: 68
Column: 13
pass
with self.assertRaises(TypeError):
MissingAexit()
def test_structural_subclassing(self):
class ManagerFromScratch:
async def __aenter__(self):
return self
Reported by Pylint.
Line: 81
Column: 23
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
self.assertTrue(issubclass(DefaultEnter, AbstractAsyncContextManager))
class NoneAenter(ManagerFromScratch):
__aenter__ = None
Reported by Pylint.
Line: 81
Column: 23
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
self.assertTrue(issubclass(DefaultEnter, AbstractAsyncContextManager))
class NoneAenter(ManagerFromScratch):
__aenter__ = None
Reported by Pylint.
Line: 81
Column: 23
class DefaultEnter(AbstractAsyncContextManager):
async def __aexit__(self, *args):
await super().__aexit__(*args)
self.assertTrue(issubclass(DefaultEnter, AbstractAsyncContextManager))
class NoneAenter(ManagerFromScratch):
__aenter__ = None
Reported by Pylint.
Line: 136
Column: 15
async def whee():
yield
ctx = whee()
await ctx.__aenter__()
# Calling __aexit__ should not result in an exception
self.assertFalse(await ctx.__aexit__(TypeError, TypeError("foo"), None))
@_async_test
async def test_contextmanager_trap_yield_after_throw(self):
Reported by Pylint.
Line: 138
Column: 32
ctx = whee()
await ctx.__aenter__()
# Calling __aexit__ should not result in an exception
self.assertFalse(await ctx.__aexit__(TypeError, TypeError("foo"), None))
@_async_test
async def test_contextmanager_trap_yield_after_throw(self):
@asynccontextmanager
async def whoo():
Reported by Pylint.
Line: 149
Column: 15
except:
yield
ctx = whoo()
await ctx.__aenter__()
with self.assertRaises(RuntimeError):
await ctx.__aexit__(TypeError, TypeError('foo'), None)
@_async_test
async def test_contextmanager_trap_no_yield(self):
Reported by Pylint.
Lib/test/test_strptime.py
154 issues
Line: 18
Column: 26
class getlang_Tests(unittest.TestCase):
"""Test _getlang"""
def test_basic(self):
self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
class LocaleTime_Tests(unittest.TestCase):
"""Tests for _strptime.LocaleTime.
All values are lower-cased when stored in LocaleTime, so make sure to
Reported by Pylint.
Line: 107
Column: 44
def test_lang(self):
# Make sure lang is set to what _getlang() returns
# Assuming locale has not changed between now and when self.LT_ins was created
self.assertEqual(self.LT_ins.lang, _strptime._getlang())
class TimeRETests(unittest.TestCase):
"""Tests for TimeRE."""
Reported by Pylint.
Line: 211
Column: 39
def test_ValueError(self):
# Make sure ValueError is raised when match fails or format is bad
self.assertRaises(ValueError, _strptime._strptime_time, data_string="%d",
format="%A")
for bad_format in ("%", "% ", "%e"):
try:
_strptime._strptime_time("2005", bad_format)
except ValueError:
Reported by Pylint.
Line: 215
Column: 17
format="%A")
for bad_format in ("%", "% ", "%e"):
try:
_strptime._strptime_time("2005", bad_format)
except ValueError:
continue
except Exception as err:
self.fail("'%s' raised %s, not ValueError" %
(bad_format, err.__class__.__name__))
Reported by Pylint.
Line: 218
Column: 20
_strptime._strptime_time("2005", bad_format)
except ValueError:
continue
except Exception as err:
self.fail("'%s' raised %s, not ValueError" %
(bad_format, err.__class__.__name__))
else:
self.fail("'%s' did not raise ValueError" % bad_format)
Reported by Pylint.
Line: 228
Column: 13
# 1. ISO week (%V) is specified, but the year is specified with %Y
# instead of %G
with self.assertRaises(ValueError):
_strptime._strptime("1999 50", "%Y %V")
# 2. ISO year (%G) and ISO week (%V) are specified, but weekday is not
with self.assertRaises(ValueError):
_strptime._strptime("1999 51", "%G %V")
# 3. ISO year (%G) and weekday are specified, but ISO week (%V) is not
for w in ('A', 'a', 'w', 'u'):
Reported by Pylint.
Line: 231
Column: 13
_strptime._strptime("1999 50", "%Y %V")
# 2. ISO year (%G) and ISO week (%V) are specified, but weekday is not
with self.assertRaises(ValueError):
_strptime._strptime("1999 51", "%G %V")
# 3. ISO year (%G) and weekday are specified, but ISO week (%V) is not
for w in ('A', 'a', 'w', 'u'):
with self.assertRaises(ValueError):
_strptime._strptime("1999 51","%G %{}".format(w))
# 4. ISO year is specified alone (e.g. time.strptime('2015', '%G'))
Reported by Pylint.
Line: 235
Column: 17
# 3. ISO year (%G) and weekday are specified, but ISO week (%V) is not
for w in ('A', 'a', 'w', 'u'):
with self.assertRaises(ValueError):
_strptime._strptime("1999 51","%G %{}".format(w))
# 4. ISO year is specified alone (e.g. time.strptime('2015', '%G'))
with self.assertRaises(ValueError):
_strptime._strptime("2015", "%G")
# 5. Julian/ordinal day (%j) is specified with %G, but not %Y
with self.assertRaises(ValueError):
Reported by Pylint.
Line: 238
Column: 13
_strptime._strptime("1999 51","%G %{}".format(w))
# 4. ISO year is specified alone (e.g. time.strptime('2015', '%G'))
with self.assertRaises(ValueError):
_strptime._strptime("2015", "%G")
# 5. Julian/ordinal day (%j) is specified with %G, but not %Y
with self.assertRaises(ValueError):
_strptime._strptime("1999 256", "%G %j")
Reported by Pylint.
Line: 241
Column: 13
_strptime._strptime("2015", "%G")
# 5. Julian/ordinal day (%j) is specified with %G, but not %Y
with self.assertRaises(ValueError):
_strptime._strptime("1999 256", "%G %j")
def test_strptime_exception_context(self):
# check that this doesn't chain exceptions needlessly (see #17572)
with self.assertRaises(ValueError) as e:
Reported by Pylint.
Tools/unicode/makeunicodedata.py
153 issues
Line: 231
Column: 26
if prev_f is None:
prev_f = (i,i)
elif prev_f[1]+1 == i:
prev_f = prev_f[0],i
else:
comp_first_ranges.append(prev_f)
prev_f = (i,i)
if comp_last[i] is not None:
comp_last[i] = l
Reported by Pylint.
Line: 241
Column: 26
if prev_l is None:
prev_l = (i,i)
elif prev_l[1]+1 == i:
prev_l = prev_l[0],i
else:
comp_last_ranges.append(prev_l)
prev_l = (i,i)
comp_first_ranges.append(prev_f)
comp_last_ranges.append(prev_l)
Reported by Pylint.
Line: 1023
Column: 50
field = dataclasses.astuple(s)[:15]
elif s.name[-5:] == "Last>":
if s.name.startswith("<CJK Ideograph"):
cjk_ranges_found.append((field[0],
s.codepoint))
s.name = ""
field = None
elif field:
table[i] = from_row(('%X' % i,) + field[1:])
Reported by Pylint.
Line: 1028
Column: 51
s.name = ""
field = None
elif field:
table[i] = from_row(('%X' % i,) + field[1:])
if cjk_check and cjk_ranges != cjk_ranges_found:
raise ValueError("CJK ranges deviate: have %r" % cjk_ranges_found)
# public attributes
self.filename = UNICODE_DATA % ''
Reported by Pylint.
Line: 206
Column: 21
if not prefix and len(decomp) == 3 and \
char not in unicode.exclusions and \
unicode.table[decomp[1]].canonical_combining_class == "0":
p, l, r = decomp
comp_first[l] = 1
comp_last[r] = 1
comp_pairs.append((l,r,char))
try:
i = decomp_data.index(decomp)
Reported by Pylint.
Line: 294
Column: 3
fprint(" {0,0,0}")
fprint("};\n")
# FIXME: <fl> the following tables could be made static, and
# the support code moved into unicodedatabase.c
fprint("/* string literals */")
fprint("const char *_PyUnicode_CategoryNames[] = {")
for name in CATEGORY_NAMES:
Reported by Pylint.
Line: 682
Column: 12
# build a lexicon string
offset = 0
for w, x in wordlist:
# encoding: bit 7 indicates last character in word (chr(128)
# indicates the last character in an entire string)
ww = w[:-1] + chr(ord(w[-1])+128)
# reuse string tails, when possible
o = lexicon.find(ww)
Reported by Pylint.
Line: 900
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen
else:
url = ('https://www.unicode.org/Public/%s/ucd/'+template) % (version, '')
os.makedirs(DATA_DIR, exist_ok=True)
urllib.request.urlretrieve(url, filename=local)
if local.endswith('.txt'):
return open(local, encoding='utf-8')
else:
# Unihan.zip
return open(local, 'rb')
Reported by Bandit.
Line: 1045
Column: 29
# in order to take advantage of the compression and lookup
# algorithms used for the other characters
pua_index = NAME_ALIASES_START
for char, name, abbrev in UcdFile(NAME_ALIASES, version):
char = int(char, 16)
self.aliases.append((name, char))
# also store the name in the PUA 1
self.table[pua_index].name = name
pua_index += 1
Reported by Pylint.
Line: 1120
Column: 13
table[i].quick_check = quickchecks[i]
with open_data(UNIHAN, version) as file:
zip = zipfile.ZipFile(file)
if version == '3.2.0':
data = zip.open('Unihan-3.2.0.txt').read()
else:
data = zip.open('Unihan_NumericValues.txt').read()
for line in data.decode("utf-8").splitlines():
Reported by Pylint.
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.