The following issues were found

Lib/test/test_context.py
315 issues
Unused variable 'MyContextVar'
Error

Line: 63 Column: 13

              
    def test_context_subclassing_1(self):
        with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
            class MyContextVar(contextvars.ContextVar):
                # Potentially we might want ContextVars to be subclassable.
                pass

        with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
            class MyContext(contextvars.Context):

            

Reported by Pylint.

Unused variable 'MyContext'
Error

Line: 68 Column: 13

                              pass

        with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
            class MyContext(contextvars.Context):
                pass

        with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
            class MyToken(contextvars.Token):
                pass

            

Reported by Pylint.

Unused variable 'MyToken'
Error

Line: 72 Column: 13

                              pass

        with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
            class MyToken(contextvars.Token):
                pass

    def test_context_new_1(self):
        with self.assertRaisesRegex(TypeError, 'any arguments'):
            contextvars.Context(1)

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 88 Column: 13

                      ctx = contextvars.Context()

        with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            ctx[1]
        with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            1 in ctx
        with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            ctx.get(1)


            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 90 Column: 13

                      with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            ctx[1]
        with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            1 in ctx
        with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):
            ctx.get(1)

    def test_context_get_context_1(self):
        ctx = contextvars.copy_context()

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 135 Column: 1

                  def test_context_run_3(self):
        ctx = contextvars.Context()

        def func(*args, **kwargs):
            1 / 0

        with self.assertRaises(ZeroDivisionError):
            ctx.run(func)
        with self.assertRaises(ZeroDivisionError):

            

Reported by Pylint.

Unused argument 'args'
Error

Line: 135 Column: 1

                  def test_context_run_3(self):
        ctx = contextvars.Context()

        def func(*args, **kwargs):
            1 / 0

        with self.assertRaises(ZeroDivisionError):
            ctx.run(func)
        with self.assertRaises(ZeroDivisionError):

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 136 Column: 13

                      ctx = contextvars.Context()

        def func(*args, **kwargs):
            1 / 0

        with self.assertRaises(ZeroDivisionError):
            ctx.run(func)
        with self.assertRaises(ZeroDivisionError):
            ctx.run(func, 1, 2)

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 177 Column: 13

                      def func():
            self.assertIsNone(var.get(None))
            var.set('spam')
            1 / 0

        with self.assertRaises(ZeroDivisionError):
            ctx.run(func)

        self.assertIsNone(var.get(None))

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 256 Column: 13

                      ctx2 = contextvars.copy_context()
        self.assertNotIn(c, ctx2)
        with self.assertRaises(KeyError):
            ctx2[c]
        self.assertEqual(ctx2.get(c, 'aa'), 'aa')
        self.assertEqual(len(ctx2), 0)
        self.assertEqual(list(ctx2), [])

    @isolated_context

            

Reported by Pylint.

Lib/test/test_zoneinfo/test_zoneinfo.py
310 issues
Attempted relative import beyond top-level package
Error

Line: 20 Column: 1

              from datetime import date, datetime, time, timedelta, timezone
from functools import cached_property

from . import _support as test_support
from ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase
from test.support.import_helper import import_module

lzma = import_module('lzma')
py_zoneinfo, c_zoneinfo = test_support.get_modules()

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 21 Column: 1

              from functools import cached_property

from . import _support as test_support
from ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase
from test.support.import_helper import import_module

lzma = import_module('lzma')
py_zoneinfo, c_zoneinfo = test_support.get_modules()


            

Reported by Pylint.

Value 'cls._get_zonedump()' is unsubscriptable
Error

Line: 1906 Column: 16

              
    @classmethod
    def load_transition_examples(cls, key):
        return cls._get_zonedump()[key]

    @classmethod
    def fixed_offset_zones(cls):
        if not cls._FIXED_OFFSET_ZONES:
            cls._populate_fixed_offsets()

            

Reported by Pylint.

Using the global statement
Error

Line: 45 Column: 5

              

def setUpModule():
    global TEMP_DIR
    global ZONEINFO_DATA
    global ZONEINFO_DATA_V1

    TEMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="zoneinfo"))
    ZONEINFO_DATA = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v2")

            

Reported by Pylint.

Using the global statement
Error

Line: 46 Column: 5

              
def setUpModule():
    global TEMP_DIR
    global ZONEINFO_DATA
    global ZONEINFO_DATA_V1

    TEMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="zoneinfo"))
    ZONEINFO_DATA = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v2")
    ZONEINFO_DATA_V1 = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v1", v1=True)

            

Reported by Pylint.

Using the global statement
Error

Line: 47 Column: 5

              def setUpModule():
    global TEMP_DIR
    global ZONEINFO_DATA
    global ZONEINFO_DATA_V1

    TEMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="zoneinfo"))
    ZONEINFO_DATA = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v2")
    ZONEINFO_DATA_V1 = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v1", v1=True)


            

Reported by Pylint.

Unused variable 'no_peephole_opt'
Error

Line: 321 Column: 21

                                  # Assign a random variable here to disable the peephole
                    # optimizer so that coverage can see this line.
                    # See bpo-2506 for more information.
                    no_peephole_opt = None
                    continue

                # Cases are of the form key, dt, fold, offset
                dt = zt.anomaly_start - timedelta(seconds=1)
                test_group.append((dt, 0, zt.offset_before))

            

Reported by Pylint.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 1408
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                  def test_cache_hit(self):
        zi_in = self.klass("Europe/Dublin")
        pkl = pickle.dumps(zi_in)
        zi_rt = pickle.loads(pkl)

        with self.subTest(test="Is non-pickled ZoneInfo"):
            self.assertIs(zi_in, zi_rt)

        zi_rt2 = pickle.loads(pkl)

            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 1413
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                      with self.subTest(test="Is non-pickled ZoneInfo"):
            self.assertIs(zi_in, zi_rt)

        zi_rt2 = pickle.loads(pkl)
        with self.subTest(test="Is unpickled ZoneInfo"):
            self.assertIs(zi_rt, zi_rt2)

    def test_cache_miss(self):
        zi_in = self.klass("Europe/Dublin")

            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 1423
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

              
        del zi_in
        self.klass.clear_cache()  # Induce a cache miss
        zi_rt = pickle.loads(pkl)
        zi_rt2 = pickle.loads(pkl)

        self.assertIs(zi_rt, zi_rt2)

    def test_no_cache(self):

            

Reported by Bandit.

Lib/test/test_nntplib.py
309 issues
self.handler_class is not callable
Error

Line: 457 Column: 24

                      del self.server

    def make_server(self, *args, **kwargs):
        self.handler = self.handler_class()
        self.sio, file = make_mock_file(self.handler)
        self.server = NNTPServer(file, 'test.server', *args, **kwargs)
        return self.server



            

Reported by Pylint.

Access to member 'body' before its definition line 501
Error

Line: 493 Column: 17

                              line = self._readline()
                if not line:
                    return
                self.body.append(line)
                if line == b".\r\n":
                    break
            try:
                meth, tokens = self.body_callback
                meth(*tokens, body=self.body)

            

Reported by Pylint.

Access to member 'body_callback' before its definition line 500
Error

Line: 497 Column: 32

                              if line == b".\r\n":
                    break
            try:
                meth, tokens = self.body_callback
                meth(*tokens, body=self.body)
            finally:
                self.body_callback = None
                self.body = None
                self.in_body = False

            

Reported by Pylint.

Access to member 'body' before its definition line 501
Error

Line: 498 Column: 36

                                  break
            try:
                meth, tokens = self.body_callback
                meth(*tokens, body=self.body)
            finally:
                self.body_callback = None
                self.body = None
                self.in_body = False
        while True:

            

Reported by Pylint.

function already defined line 1230
Error

Line: 1235 Column: 9

                      resp = self._check_post_ihave_sub(func, *args, file_factory=iterlines)
        self.assertEqual(resp, success_resp)
        # With an iterable of non-terminated lines
        def iterlines(b):
            return iter(b.splitlines(keepends=False))
        resp = self._check_post_ihave_sub(func, *args, file_factory=iterlines)
        self.assertEqual(resp, success_resp)

    def test_post(self):

            

Reported by Pylint.

function already defined line 1440
Error

Line: 1450 Column: 9

                      gives(2000, 6, 23, 13, 56, 24, "20000623", "135624")
        gives(2010, 6, 5, 1, 2, 3, "20100605", "010203")
        # 2) with a date
        def gives(y, M, d, date_str, time_str):
            dt = datetime.date(y, M, d)
            self.assertEqual(nntplib._unparse_datetime(dt),
                             (date_str, time_str))
            self.assertEqual(nntplib._unparse_datetime(dt, False),
                             (date_str, time_str))

            

Reported by Pylint.

function already defined line 1463
Error

Line: 1471 Column: 9

                      gives(2000, 6, 23, 13, 56, 24, "000623", "135624")
        gives(2010, 6, 5, 1, 2, 3, "100605", "010203")
        # 2) with a date
        def gives(y, M, d, date_str, time_str):
            dt = datetime.date(y, M, d)
            self.assertEqual(nntplib._unparse_datetime(dt, True),
                             (date_str, time_str))
        gives(1999, 6, 23, "990623", "000000")
        gives(2000, 6, 23, "000623", "000000")

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 1509 Column: 13

                          login=None, password=None):

        class mock_socket_module:
            def create_connection(address, timeout):
                return MockSocket()

        class MockSocket:
            def close(self):
                nonlocal socket_closed

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 1517 Column: 13

                              nonlocal socket_closed
                socket_closed = True

            def makefile(socket, mode):
                handler = handler_class()
                _, file = make_mock_file(handler)
                files.append(file)
                return file


            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 1576 Column: 5

              
class bypass_context:
    """Bypass encryption and actual SSL module"""
    def wrap_socket(sock, **args):
        return sock

@unittest.skipUnless(ssl, 'requires SSL support')
class MockSslTests(MockSocketTests):
    @staticmethod

            

Reported by Pylint.

Lib/test/test_asyncgen.py
308 issues
Undefined variable 'anext'
Error

Line: 379 Column: 34

                      g = ait_class()
        async def consume():
            results = []
            results.append(await anext(g))
            results.append(await anext(g))
            results.append(await anext(g, 'buckle my shoe'))
            return results
        res = self.loop.run_until_complete(consume())
        self.assertEqual(res, [1, 2, 'buckle my shoe'])

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 380 Column: 34

                      async def consume():
            results = []
            results.append(await anext(g))
            results.append(await anext(g))
            results.append(await anext(g, 'buckle my shoe'))
            return results
        res = self.loop.run_until_complete(consume())
        self.assertEqual(res, [1, 2, 'buckle my shoe'])
        with self.assertRaises(StopAsyncIteration):

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 381 Column: 34

                          results = []
            results.append(await anext(g))
            results.append(await anext(g))
            results.append(await anext(g, 'buckle my shoe'))
            return results
        res = self.loop.run_until_complete(consume())
        self.assertEqual(res, [1, 2, 'buckle my shoe'])
        with self.assertRaises(StopAsyncIteration):
            self.loop.run_until_complete(consume())

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 390 Column: 36

              
        async def test_2():
            g1 = ait_class()
            self.assertEqual(await anext(g1), 1)
            self.assertEqual(await anext(g1), 2)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 391 Column: 36

                      async def test_2():
            g1 = ait_class()
            self.assertEqual(await anext(g1), 1)
            self.assertEqual(await anext(g1), 2)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)


            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 393 Column: 23

                          self.assertEqual(await anext(g1), 1)
            self.assertEqual(await anext(g1), 2)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)

            g2 = ait_class()
            self.assertEqual(await anext(g2, "default"), 1)

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 395 Column: 23

                          with self.assertRaises(StopAsyncIteration):
                await anext(g1)
            with self.assertRaises(StopAsyncIteration):
                await anext(g1)

            g2 = ait_class()
            self.assertEqual(await anext(g2, "default"), 1)
            self.assertEqual(await anext(g2, "default"), 2)
            self.assertEqual(await anext(g2, "default"), "default")

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 398 Column: 36

                              await anext(g1)

            g2 = ait_class()
            self.assertEqual(await anext(g2, "default"), 1)
            self.assertEqual(await anext(g2, "default"), 2)
            self.assertEqual(await anext(g2, "default"), "default")
            self.assertEqual(await anext(g2, "default"), "default")

            return "completed"

            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 399 Column: 36

              
            g2 = ait_class()
            self.assertEqual(await anext(g2, "default"), 1)
            self.assertEqual(await anext(g2, "default"), 2)
            self.assertEqual(await anext(g2, "default"), "default")
            self.assertEqual(await anext(g2, "default"), "default")

            return "completed"


            

Reported by Pylint.

Undefined variable 'anext'
Error

Line: 400 Column: 36

                          g2 = ait_class()
            self.assertEqual(await anext(g2, "default"), 1)
            self.assertEqual(await anext(g2, "default"), 2)
            self.assertEqual(await anext(g2, "default"), "default")
            self.assertEqual(await anext(g2, "default"), "default")

            return "completed"

        result = self.loop.run_until_complete(test_2())

            

Reported by Pylint.

Lib/unittest/test/test_runner.py
304 issues
Argument 'function' passed by position and keyword in function call
Error

Line: 412 Column: 13

                          cleanups.append((args, kwargs))

        class Module(object):
            unittest.addModuleCleanup(cleanup, 1, 2, function='hello')
            with self.assertRaises(TypeError):
                unittest.addModuleCleanup(function=cleanup, arg='hello')
            with self.assertRaises(TypeError):
                unittest.addModuleCleanup()
        unittest.case.doModuleCleanups()

            

Reported by Pylint.

No value for argument 'function' in function call
Error

Line: 416 Column: 17

                          with self.assertRaises(TypeError):
                unittest.addModuleCleanup(function=cleanup, arg='hello')
            with self.assertRaises(TypeError):
                unittest.addModuleCleanup()
        unittest.case.doModuleCleanups()
        self.assertEqual(cleanups,
                         [((1, 2), {'function': 'hello'})])

    def test_run_module_cleanUp(self):

            

Reported by Pylint.

No value for argument 'self' in unbound method call
Error

Line: 582 Column: 13

                      with self.assertRaises(TypeError):
            TestableTest.addClassCleanup()
        with self.assertRaises(TypeError):
            unittest.TestCase.addCleanup(cls=TestableTest(), function=cleanup)
        runTests(TestableTest)
        self.assertEqual(cleanups,
                         [((1, 2), {'function': 3, 'cls': 4})])

    def test_addCleanup_arg_errors(self):

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 593 Column: 13

                          cleanups.append((args, kwargs))

        class TestableTest(unittest.TestCase):
            def setUp(self2):
                self2.addCleanup(cleanup, 1, 2, function=3, self=4)
                with self.assertRaises(TypeError):
                    self2.addCleanup(function=cleanup, arg='hello')
            def testNothing(self):
                pass

            

Reported by Pylint.

Argument 'function' passed by position and keyword in method call
Error

Line: 594 Column: 17

              
        class TestableTest(unittest.TestCase):
            def setUp(self2):
                self2.addCleanup(cleanup, 1, 2, function=3, self=4)
                with self.assertRaises(TypeError):
                    self2.addCleanup(function=cleanup, arg='hello')
            def testNothing(self):
                pass


            

Reported by Pylint.

Argument 'self' passed by position and keyword in method call
Error

Line: 594 Column: 17

              
        class TestableTest(unittest.TestCase):
            def setUp(self2):
                self2.addCleanup(cleanup, 1, 2, function=3, self=4)
                with self.assertRaises(TypeError):
                    self2.addCleanup(function=cleanup, arg='hello')
            def testNothing(self):
                pass


            

Reported by Pylint.

Access to a protected member _cleanups of a client class
Error

Line: 55 Column: 26

                              pass

        test = TestableTest('testNothing')
        self.assertEqual(test._cleanups, [])

        cleanups = []

        def cleanup1(*args, **kwargs):
            cleanups.append((1, args, kwargs))

            

Reported by Pylint.

Access to a protected member _cleanups of a client class
Error

Line: 68 Column: 26

                      test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
        test.addCleanup(cleanup2)

        self.assertEqual(test._cleanups,
                         [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
                          (cleanup2, (), {})])

        self.assertTrue(test.doCleanups())
        self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])

            

Reported by Pylint.

Access to a protected member _class_cleanups of a client class
Error

Line: 177 Column: 26

                          def testNothing(self):
                pass
        test = TestableTest('testNothing')
        self.assertEqual(test._class_cleanups, [])
        class_cleanups = []

        def class_cleanup1(*args, **kwargs):
            class_cleanups.append((3, args, kwargs))


            

Reported by Pylint.

Access to a protected member _class_cleanups of a client class
Error

Line: 190 Column: 26

                                                   four='hello', five='goodbye')
        TestableTest.addClassCleanup(class_cleanup2)

        self.assertEqual(test._class_cleanups,
                         [(class_cleanup1, (1, 2, 3),
                           dict(four='hello', five='goodbye')),
                          (class_cleanup2, (), {})])

        TestableTest.doClassCleanups()

            

Reported by Pylint.

Lib/test/test_lzma.py
299 issues
Redefining built-in 'input'
Error

Line: 360 Column: 13

                      blocksize = 10 * 1024 * 1024
        block = random.randbytes(blocksize)
        try:
            input = block * (size // blocksize + 1)
            cdata = lzma.compress(input)
            ddata = lzd.decompress(cdata)
            self.assertEqual(ddata, input)
        finally:
            input = cdata = ddata = None

            

Reported by Pylint.

Unused variable 'i'
Error

Line: 381 Column: 13

                      gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
        lzd = LZMADecompressor()
        refs_before = gettotalrefcount()
        for i in range(100):
            lzd.__init__()
        self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)


class CompressDecompressFunctionTestCase(unittest.TestCase):

            

Reported by Pylint.

Unused variable 'f'
Error

Line: 539 Column: 50

              class FileTestCase(unittest.TestCase):

    def test_init(self):
        with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
            pass
        with LZMAFile(BytesIO(), "w") as f:
            pass
        with LZMAFile(BytesIO(), "x") as f:
            pass

            

Reported by Pylint.

Unused variable 'f'
Error

Line: 560 Column: 38

              
    def test_init_with_filename(self):
        with TempFile(TESTFN, COMPRESSED_XZ):
            with LZMAFile(TESTFN) as f:
                pass
            with LZMAFile(TESTFN, "w") as f:
                pass
            with LZMAFile(TESTFN, "a") as f:
                pass

            

Reported by Pylint.

Access to a protected member _fp of a client class
Error

Line: 688 Column: 18

                      # Test with a real file on disk, opened directly by LZMAFile.
        with TempFile(TESTFN, COMPRESSED_XZ):
            f = LZMAFile(TESTFN)
            fp = f._fp
            f.close()
            # Here, LZMAFile.close() *should* close the underlying file object.
            self.assertTrue(fp.closed)
            # Try closing an already-closed LZMAFile.
            f.close()

            

Reported by Pylint.

Access to a protected member _fp of a client class
Error

Line: 722 Column: 46

                      with TempFile(TESTFN, COMPRESSED_XZ):
            f = LZMAFile(TESTFN)
            try:
                self.assertEqual(f.fileno(), f._fp.fileno())
                self.assertIsInstance(f.fileno(), int)
            finally:
                f.close()
        self.assertRaises(ValueError, f.fileno)


            

Reported by Pylint.

Access to a protected member _buffer of a client class
Error

Line: 1011 Column: 30

                      decomp = LZMAFile(BytesIO(bomb))
        self.assertEqual(decomp.read(1), b'\0')
        max_decomp = 1 + DEFAULT_BUFFER_SIZE
        self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
            "Excessive amount of data was decompressed")

    def test_write(self):
        with BytesIO() as dst:
            with LZMAFile(dst, "w") as f:

            

Reported by Pylint.

Access to a protected member _encode_filter_properties of a client class
Error

Line: 1380 Column: 13

              
    def test__encode_filter_properties(self):
        with self.assertRaises(TypeError):
            lzma._encode_filter_properties(b"not a dict")
        with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": 0x100})
        with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": lzma.FILTER_LZMA2, "junk": 12})
        with self.assertRaises(lzma.LZMAError):

            

Reported by Pylint.

Access to a protected member _encode_filter_properties of a client class
Error

Line: 1382 Column: 13

                      with self.assertRaises(TypeError):
            lzma._encode_filter_properties(b"not a dict")
        with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": 0x100})
        with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": lzma.FILTER_LZMA2, "junk": 12})
        with self.assertRaises(lzma.LZMAError):
            lzma._encode_filter_properties({"id": lzma.FILTER_DELTA,
                                           "dist": 9001})

            

Reported by Pylint.

Access to a protected member _encode_filter_properties of a client class
Error

Line: 1384 Column: 13

                      with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": 0x100})
        with self.assertRaises(ValueError):
            lzma._encode_filter_properties({"id": lzma.FILTER_LZMA2, "junk": 12})
        with self.assertRaises(lzma.LZMAError):
            lzma._encode_filter_properties({"id": lzma.FILTER_DELTA,
                                           "dist": 9001})

        # Test with parameters used by zipfile module.

            

Reported by Pylint.

Lib/test/test_compileall.py
288 issues
Attempted relative import beyond top-level package
Error

Line: 33 Column: 1

              from test.support import os_helper
from test.support import script_helper

from .test_py_compile import without_source_date_epoch
from .test_py_compile import SourceDateEpochTestMeta


def get_pyc(script, opt):
    if not opt:

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 34 Column: 1

              from test.support import script_helper

from .test_py_compile import without_source_date_epoch
from .test_py_compile import SourceDateEpochTestMeta


def get_pyc(script, opt):
    if not opt:
        # Replace None and 0 with ''

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertEqual' member
Error

Line: 92 Column: 9

                      if os.environ.get('SOURCE_DATE_EPOCH'):
            raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
        py_compile.compile(self.source_path)
        self.assertEqual(*self.timestamp_metadata())
        with open(self.bc_path, 'rb') as file:
            bc = file.read()[len(metadata):]
        with open(self.bc_path, 'wb') as file:
            file.write(metadata)
            file.write(bc)

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertNotEqual' member
Error

Line: 98 Column: 9

                      with open(self.bc_path, 'wb') as file:
            file.write(metadata)
            file.write(bc)
        self.assertNotEqual(*self.timestamp_metadata())
        compileall.compile_dir(self.directory, force=False, quiet=True)
        self.assertTrue(*self.timestamp_metadata())

    def test_mtime(self):
        # Test a change in mtime leads to a new .pyc.

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertTrue' member
Error

Line: 100 Column: 9

                          file.write(bc)
        self.assertNotEqual(*self.timestamp_metadata())
        compileall.compile_dir(self.directory, force=False, quiet=True)
        self.assertTrue(*self.timestamp_metadata())

    def test_mtime(self):
        # Test a change in mtime leads to a new .pyc.
        self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
                                          0, 1))

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertTrue' member
Error

Line: 118 Column: 9

                              os.unlink(fn)
            except:
                pass
        self.assertTrue(compileall.compile_file(self.source_path,
                                                force=False, quiet=True))
        self.assertTrue(os.path.isfile(self.bc_path) and
                        not os.path.isfile(self.bc_path2))
        os.unlink(self.bc_path)
        self.assertTrue(compileall.compile_dir(self.directory, force=False,

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertTrue' member
Error

Line: 120 Column: 9

                              pass
        self.assertTrue(compileall.compile_file(self.source_path,
                                                force=False, quiet=True))
        self.assertTrue(os.path.isfile(self.bc_path) and
                        not os.path.isfile(self.bc_path2))
        os.unlink(self.bc_path)
        self.assertTrue(compileall.compile_dir(self.directory, force=False,
                                               quiet=True))
        self.assertTrue(os.path.isfile(self.bc_path) and

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertTrue' member
Error

Line: 123 Column: 9

                      self.assertTrue(os.path.isfile(self.bc_path) and
                        not os.path.isfile(self.bc_path2))
        os.unlink(self.bc_path)
        self.assertTrue(compileall.compile_dir(self.directory, force=False,
                                               quiet=True))
        self.assertTrue(os.path.isfile(self.bc_path) and
                        os.path.isfile(self.bc_path2))
        os.unlink(self.bc_path)
        os.unlink(self.bc_path2)

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertTrue' member
Error

Line: 125 Column: 9

                      os.unlink(self.bc_path)
        self.assertTrue(compileall.compile_dir(self.directory, force=False,
                                               quiet=True))
        self.assertTrue(os.path.isfile(self.bc_path) and
                        os.path.isfile(self.bc_path2))
        os.unlink(self.bc_path)
        os.unlink(self.bc_path2)
        # Test against bad files
        self.add_bad_source_file()

            

Reported by Pylint.

Instance of 'CompileallTestsBase' has no 'assertFalse' member
Error

Line: 131 Column: 9

                      os.unlink(self.bc_path2)
        # Test against bad files
        self.add_bad_source_file()
        self.assertFalse(compileall.compile_file(self.bad_source_path,
                                                 force=False, quiet=2))
        self.assertFalse(compileall.compile_dir(self.directory,
                                                force=False, quiet=2))

    def test_compile_file_pathlike(self):

            

Reported by Pylint.

Lib/test/test_optparse.py
286 issues
Instance of 'BaseTest' has no 'parser' member
Error

Line: 62 Column: 38

                      Returns the options and positional args for further testing.
        """

        (options, positional_args) = self.parser.parse_args(args)
        optdict = vars(options)

        self.assertEqual(optdict, expected_opts,
                         """
Options are %(optdict)s.

            

Reported by Pylint.

Instance of 'BaseTest' has no 'parser' member
Error

Line: 144 Column: 13

                      must ensure that self.parser is an InterceptingOptionParser.
        """
        try:
            self.parser.parse_args(cmdline_args)
        except InterceptedError as err:
            self.assertEqual(err.error_message, expected_output)
        else:
            self.assertFalse("expected parse failure")


            

Reported by Pylint.

Instance of 'BaseTest' has no 'parser' member
Error

Line: 160 Column: 17

                      try:
            try:
                sys.stdout = StringIO()
                self.parser.parse_args(cmdline_args)
            finally:
                output = sys.stdout.getvalue()
                sys.stdout = save_stdout

        except InterceptedError as err:

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 1031 Column: 9

                          os.unlink(os_helper.TESTFN)

    class MyOption (Option):
        def check_file(option, opt, value):
            if not os.path.exists(value):
                raise OptionValueError("%s: file does not exist" % value)
            elif not os.path.isfile(value):
                raise OptionValueError("%s: not a regular file" % value)
            return value

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 20 Column: 1

              from test.support import os_helper


import optparse
from optparse import make_option, Option, \
     TitledHelpFormatter, OptionParser, OptionGroup, \
     SUPPRESS_USAGE, OptionError, OptionConflictError, \
     BadOptionError, OptionValueError, Values
from optparse import _match_abbrev

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 21 Column: 1

              

import optparse
from optparse import make_option, Option, \
     TitledHelpFormatter, OptionParser, OptionGroup, \
     SUPPRESS_USAGE, OptionError, OptionConflictError, \
     BadOptionError, OptionValueError, Values
from optparse import _match_abbrev
from optparse import _parse_num

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 25 Column: 1

                   TitledHelpFormatter, OptionParser, OptionGroup, \
     SUPPRESS_USAGE, OptionError, OptionConflictError, \
     BadOptionError, OptionValueError, Values
from optparse import _match_abbrev
from optparse import _parse_num

class InterceptedError(Exception):
    def __init__(self,
                 error_message=None,

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 26 Column: 1

                   SUPPRESS_USAGE, OptionError, OptionConflictError, \
     BadOptionError, OptionValueError, Values
from optparse import _match_abbrev
from optparse import _parse_num

class InterceptedError(Exception):
    def __init__(self,
                 error_message=None,
                 exit_status=None,

            

Reported by Pylint.

__init__ method from base class 'Exception' is not called
Error

Line: 29 Column: 5

              from optparse import _parse_num

class InterceptedError(Exception):
    def __init__(self,
                 error_message=None,
                 exit_status=None,
                 exit_message=None):
        self.error_message = error_message
        self.exit_status = exit_status

            

Reported by Pylint.

Parameters differ from overridden 'assertRaises' method
Error

Line: 79 Column: 5

              
        return (options, positional_args)

    def assertRaises(self,
                     func,
                     args,
                     kwargs,
                     expected_exception,
                     expected_message):

            

Reported by Pylint.

Lib/test/list_tests.py
283 issues
self.type2test is not callable
Error

Line: 17 Column: 26

              
    def test_init(self):
        # Iterable arg is optional
        self.assertEqual(self.type2test([]), self.type2test())

        # Init clears previous values
        a = self.type2test([1, 2, 3])
        a.__init__()
        self.assertEqual(a, self.type2test([]))

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 17 Column: 46

              
    def test_init(self):
        # Iterable arg is optional
        self.assertEqual(self.type2test([]), self.type2test())

        # Init clears previous values
        a = self.type2test([1, 2, 3])
        a.__init__()
        self.assertEqual(a, self.type2test([]))

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 20 Column: 13

                      self.assertEqual(self.type2test([]), self.type2test())

        # Init clears previous values
        a = self.type2test([1, 2, 3])
        a.__init__()
        self.assertEqual(a, self.type2test([]))

        # Init overwrites previous values
        a = self.type2test([1, 2, 3])

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 22 Column: 29

                      # Init clears previous values
        a = self.type2test([1, 2, 3])
        a.__init__()
        self.assertEqual(a, self.type2test([]))

        # Init overwrites previous values
        a = self.type2test([1, 2, 3])
        a.__init__([4, 5, 6])
        self.assertEqual(a, self.type2test([4, 5, 6]))

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 25 Column: 13

                      self.assertEqual(a, self.type2test([]))

        # Init overwrites previous values
        a = self.type2test([1, 2, 3])
        a.__init__([4, 5, 6])
        self.assertEqual(a, self.type2test([4, 5, 6]))

        # Mutables always return a new object
        b = self.type2test(a)

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 27 Column: 29

                      # Init overwrites previous values
        a = self.type2test([1, 2, 3])
        a.__init__([4, 5, 6])
        self.assertEqual(a, self.type2test([4, 5, 6]))

        # Mutables always return a new object
        b = self.type2test(a)
        self.assertNotEqual(id(a), id(b))
        self.assertEqual(a, b)

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 30 Column: 13

                      self.assertEqual(a, self.type2test([4, 5, 6]))

        # Mutables always return a new object
        b = self.type2test(a)
        self.assertNotEqual(id(a), id(b))
        self.assertEqual(a, b)

    def test_getitem_error(self):
        a = []

            

Reported by Pylint.

Sequence index is not an int, slice, or instance with __index__
Error

Line: 38 Column: 13

                      a = []
        msg = "list indices must be integers or slices"
        with self.assertRaisesRegex(TypeError, msg):
            a['a']

    def test_setitem_error(self):
        a = []
        msg = "list indices must be integers or slices"
        with self.assertRaisesRegex(TypeError, msg):

            

Reported by Pylint.

Sequence index is not an int, slice, or instance with __index__
Error

Line: 44 Column: 13

                      a = []
        msg = "list indices must be integers or slices"
        with self.assertRaisesRegex(TypeError, msg):
            a['a'] = "python"

    def test_repr(self):
        l0 = []
        l2 = [0, 1, 2]
        a0 = self.type2test(l0)

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 49 Column: 14

                  def test_repr(self):
        l0 = []
        l2 = [0, 1, 2]
        a0 = self.type2test(l0)
        a2 = self.type2test(l2)

        self.assertEqual(str(a0), str(l0))
        self.assertEqual(repr(a0), repr(l0))
        self.assertEqual(repr(a2), repr(l2))

            

Reported by Pylint.

Lib/test/test_threading.py
283 issues
Cannot import 'traceback' due to syntax error 'invalid syntax (<unknown>, line 576)'
Error

Line: 22 Column: 1

              import subprocess
import signal
import textwrap
import traceback

from unittest import mock
from test import lock_tests
from test import support


            

Reported by Pylint.

The raise statement is not inside an except clause
Error

Line: 1342 Column: 13

              
    def test_bare_raise_in_brand_new_thread(self):
        def bare_raise():
            raise

        class Issue27558(threading.Thread):
            exc = None

            def run(self):

            

Reported by Pylint.

Reimport 'support' (imported line 5)
Error

Line: 26 Column: 1

              
from unittest import mock
from test import lock_tests
from test import support


# Between fork() and exec(), only async-safe functions are allowed (issues
# #12316 and #11870), and fork() from a worker thread is known to trigger
# problems with some operating systems (issue #3863): skip problematic tests

            

Reported by Pylint.

threading.Thread needs the target function
Error

Line: 119 Column: 22

                          self.assertEqual(thread.name, "Thread-2")

        with mock.patch.object(threading, '_counter', return_value=3):
            thread = threading.Thread()
            self.assertEqual(thread.name, "Thread-3")

        with mock.patch.object(threading, '_counter', return_value=5):
            thread = threading.Thread(target=func)
            self.assertEqual(thread.name, "Thread-5 (func)")

            

Reported by Pylint.

Access to a protected member _active of a client class
Error

Line: 183 Column: 13

                          done.wait()
            self.assertEqual(ident[0], tid)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256 KiB)
    def test_various_ops_small_stack(self):
        if verbose:
            print('with 256 KiB thread stack size...')

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 192 Column: 13

                      try:
            threading.stack_size(262144)
        except _thread.error:
            raise unittest.SkipTest(
                'platform does not support changing thread stack size')
        self.test_various_ops()
        threading.stack_size(0)

    # run with a large thread stack size (1 MiB)

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 204 Column: 13

                      try:
            threading.stack_size(0x100000)
        except _thread.error:
            raise unittest.SkipTest(
                'platform does not support changing thread stack size')
        self.test_various_ops()
        threading.stack_size(0)

    def test_foreign_thread(self):

            

Reported by Pylint.

Access to a protected member _active of a client class
Error

Line: 223 Column: 28

                          tid = _thread.start_new_thread(f, (mutex,))
            # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]

            

Reported by Pylint.

Access to a protected member _active of a client class
Error

Line: 224 Column: 31

                          # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]


            

Reported by Pylint.

Access to a protected member _DummyThread of a client class
Error

Line: 224 Column: 55

                          # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]


            

Reported by Pylint.