From 03bf13f0e25d1b87b1c7a476d0096b238d545ba1 Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Wed, 16 Feb 2022 10:18:24 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- doctest_generated/test_descrtut.py | 4 +- doctest_generated/test_generators.py | 97 +++---- doctest_generated/test_genexps.py | 16 +- doctest_generated/test_itertools.py | 7 +- doctest_generated/test_listcomps.py | 13 +- doctest_generated/test_setcomps.py | 10 +- run_all.py | 4 +- test/_test_multiprocessing.py | 241 ++++++++--------- test/bytecode_helper.py | 11 +- test/curses_tests.py | 6 +- test/datetimetester.py | 153 ++++------- test/fork_wait.py | 13 +- test/list_tests.py | 2 +- test/lock_tests.py | 2 - test/make_ssl_certs.py | 4 +- test/mapping_tests.py | 16 +- test/mock_socket.py | 11 +- test/multibytecodec_support.py | 42 +-- test/pickletester.py | 77 +++--- test/profilee.py | 5 +- test/pydocfodder.py | 6 +- test/pythoninfo.py | 17 +- test/re_tests.py | 375 +++++++++++++++------------ test/reperf.py | 2 +- test/seq_tests.py | 10 +- test/sortperf.py | 15 +- test/string_tests.py | 10 +- test/test__locale.py | 4 +- test/test__osx_support.py | 11 +- test/test_aifc.py | 6 +- test/test_array.py | 42 ++- test/test_ast.py | 17 +- test/test_asyncgen.py | 1 - test/test_asynchat.py | 2 +- test/test_atexit.py | 2 +- test/test_augassign.py | 3 +- test/test_baseexception.py | 10 +- test/test_bigmem.py | 2 +- test/test_binhex.py | 16 +- test/test_binop.py | 10 +- test/test_bisect.py | 9 +- test/test_bool.py | 14 +- test/test_buffer.py | 70 +++-- test/test_builtin.py | 13 +- test/test_bytes.py | 26 +- test/test_calendar.py | 10 +- test/test_capi.py | 16 +- test/test_cgi.py | 14 +- test/test_class.py | 8 +- test/test_cmath.py | 7 +- test/test_code.py | 4 +- test/test_codeccallbacks.py | 71 ++--- test/test_codecs.py | 50 ++-- test/test_collections.py | 67 ++--- test/test_compare.py | 2 +- test/test_compile.py | 19 +- test/test_complex.py | 22 +- test/test_concurrent_futures.py | 15 +- test/test_configparser.py | 44 +--- test/test_context.py | 10 +- test/test_contextlib.py | 16 +- test/test_contextlib_async.py | 20 +- test/test_copy.py | 3 +- test/test_coroutines.py | 20 +- test/test_csv.py | 10 +- test/test_dataclasses.py | 27 +- test/test_dbm_dumb.py | 35 ++- test/test_decimal.py | 61 ++--- test/test_decorators.py | 2 +- test/test_deque.py | 40 ++- update_doctest_generated.py | 17 +- 71 files changed, 909 insertions(+), 1128 deletions(-) diff --git a/doctest_generated/test_descrtut.py b/doctest_generated/test_descrtut.py index f5dcbcf4..bddc3f05 100644 --- a/doctest_generated/test_descrtut.py +++ b/doctest_generated/test_descrtut.py @@ -30,7 +30,7 @@ def getx(self): return self.__x def setx(self, x): - if x < 0: x = 0 + x = max(x, 0) self.__x = x x = property(getx, setx) @@ -99,7 +99,7 @@ def __init__(self): def getx(self): return self.__x def setx(self, x): - if x < 0: x = 0 + x = max(x, 0) self.__x = x x = property(getx, setx) # diff --git a/doctest_generated/test_generators.py b/doctest_generated/test_generators.py index eafa8e21..87016dc9 100644 --- a/doctest_generated/test_generators.py +++ b/doctest_generated/test_generators.py @@ -4,7 +4,7 @@ try: def firstn(g, n): - return [next(g) for i in range(n)] + return [next(g) for _ in range(n)] # def intsfrom(i): while 1: @@ -48,8 +48,7 @@ def sieve(ints): prime = next(ints) yield prime not_divisible_by_prime = exclude_multiples(prime, ints) - for p in sieve(not_divisible_by_prime): - yield p + yield from sieve(not_divisible_by_prime) # except Exception as __e: print("Occurred", type(__e), __e) @@ -114,10 +113,9 @@ def m235(): me_times2 = times(2, m235()) me_times3 = times(3, m235()) me_times5 = times(5, m235()) - for i in merge(merge(me_times2, + yield from merge(merge(me_times2, me_times3), - me_times5): - yield i + me_times5) # # Don't print "too many" of these -- the implementation above is extremely # inefficient: each call of m235() leads to 3 recursive calls, and in @@ -167,10 +165,9 @@ def m235(): me_times2 = times(2, m235) me_times3 = times(3, m235) me_times5 = times(5, m235) - for i in merge(merge(me_times2, + yield from merge(merge(me_times2, me_times3), - me_times5): - yield i + me_times5) # # Print as many of these as you like -- *this* implementation is memory- # efficient. @@ -205,8 +202,7 @@ def sum(g, h): def tail(g): next(g) # throw first away - for x in g: - yield x + yield from g yield a yield b @@ -243,10 +239,9 @@ def tail(g): def m235(): def _m235(): yield 1 - for n in merge(times(2, m2), + yield from merge(times(2, m2), merge(times(3, m3), - times(5, m5))): - yield n + times(5, m5))) m1 = _m235() m2, m3, m5, mRes = tee(m1, 4) return mRes @@ -291,8 +286,7 @@ def _fib(): yield 1 yield 2 next(fibTail) # throw first away - for res in _isum(fibHead, fibTail): - yield res + yield from _isum(fibHead, fibTail) realfib = _fib() fibHead, fibTail, fibRes = tee(realfib, 3) @@ -450,8 +444,7 @@ def gencopy(iterator): try: def g(): - i = next(me) - yield i + yield next(me) except Exception as __e: print("Occurred", type(__e), __e) @@ -618,11 +611,9 @@ def tree(list): try: def inorder(t): if t: - for x in inorder(t.left): - yield x + yield from inorder(t.left) yield t.label - for x in inorder(t.right): - yield x + yield from inorder(t.right) # except Exception as __e: print("Occurred", type(__e), __e) @@ -637,7 +628,7 @@ def inorder(t): try: def g(): - for i in range(3): + for _ in range(3): yield None yield None return @@ -691,8 +682,7 @@ def gcomb(x, k): c.insert(0, first) yield c # If it doesn't contain first, it's a k comb of rest. - for c in gcomb(rest, k): - yield c + yield from gcomb(rest, k) # except Exception as __e: print("Occurred", type(__e), __e) @@ -860,8 +850,7 @@ def __init__(self, name): def generate(self): while not self.parent: yield self - for x in self.parent.generator: - yield x + yield from self.parent.generator def find(self): return next(self.generator) @@ -922,12 +911,11 @@ def f(): # def f(): try: - try: - 1//0 - except ZeroDivisionError: - yield 666 - except: - pass + 1//0 + except ZeroDivisionError: + yield 666 + except: + pass finally: pass # @@ -976,8 +964,7 @@ def f(): try: def f(): - if 0: - yield + pass except Exception as __e: print("Occurred", type(__e), __e) @@ -993,8 +980,7 @@ def f(): try: def f(): - if 0: - yield 1 + pass except Exception as __e: print("Occurred", type(__e), __e) @@ -1010,8 +996,7 @@ def f(): try: def f(): - if "": - yield None + pass except Exception as __e: print("Occurred", type(__e), __e) @@ -1028,25 +1013,6 @@ def f(): try: def f(): return - try: - if x==4: - pass - elif 0: - try: - 1//0 - except SyntaxError: - pass - else: - if 0: - while 12: - x += 1 - yield 2 # don't blink - f(a, b, c, d, e) - else: - pass - except: - x = 1 - return except Exception as __e: print("Occurred", type(__e), __e) @@ -1101,10 +1067,7 @@ def f(self): try: def f(): - if 0: - return - if 0: - yield 2 + pass except Exception as __e: print("Occurred", type(__e), __e) @@ -1315,7 +1278,6 @@ def f(): def f(): yield 1 return - yield 2 # never reached except Exception as __e: print("Occurred", type(__e), __e) @@ -1412,8 +1374,7 @@ def g3(): try: def yrange(n): - for i in range(n): - yield i + yield from range(n) except Exception as __e: print("Occurred", type(__e), __e) @@ -1451,8 +1412,7 @@ def caller(): try: def zrange(n): - for i in yrange(n): - yield i + yield from yrange(n) except Exception as __e: print("Occurred", type(__e), __e) @@ -1661,7 +1621,8 @@ def f(): yield try: - def f(): list(i for i in [(yield 26)]) + def f(): + list([(yield 26)]) except Exception as __e: print("Occurred", type(__e), __e) diff --git a/doctest_generated/test_genexps.py b/doctest_generated/test_genexps.py index 280b10a0..972e78da 100644 --- a/doctest_generated/test_genexps.py +++ b/doctest_generated/test_genexps.py @@ -10,8 +10,7 @@ try: print('Line 8') - print(list((i,j) for i in range(3) for j in range(4) ) - ) + print([(i,j) for i in range(3) for j in range(4)]) except Exception as __e: print("Occurred", type(__e), __e) @@ -19,8 +18,7 @@ try: print('Line 14') - print(list((i,j) for i in range(4) for j in range(i) ) - ) + print([(i,j) for i in range(4) for j in range(i)]) except Exception as __e: print("Occurred", type(__e), __e) @@ -34,8 +32,7 @@ try: print('Line 21') - print(sum(i*i for i in range(100)) - ) + print(sum(i**2 for i in range(100))) except Exception as __e: print("Occurred", type(__e), __e) @@ -51,7 +48,7 @@ try: - g = (i*i for i in range(4)) + g = (i**2 for i in range(4)) except Exception as __e: print("Occurred", type(__e), __e) @@ -75,7 +72,7 @@ try: - g = (i*i for i in range(3)) + g = (i**2 for i in range(3)) except Exception as __e: print("Occurred", type(__e), __e) @@ -338,8 +335,7 @@ def caller(): try: def zrange(n): - for i in yrange(n): - yield i + yield from yrange(n) except Exception as __e: print("Occurred", type(__e), __e) diff --git a/doctest_generated/test_itertools.py b/doctest_generated/test_itertools.py index 3bc8a7aa..01f045c5 100644 --- a/doctest_generated/test_itertools.py +++ b/doctest_generated/test_itertools.py @@ -216,13 +216,12 @@ def unique_everseen(iterable, key=None): # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add - if key is None: - for element in iterable: + for element in iterable: + if key is None: if element not in seen: seen_add(element) yield element - else: - for element in iterable: + else: k = key(element) if k not in seen: seen_add(k) diff --git a/doctest_generated/test_listcomps.py b/doctest_generated/test_listcomps.py index 22c3877c..99c533b3 100644 --- a/doctest_generated/test_listcomps.py +++ b/doctest_generated/test_listcomps.py @@ -1,8 +1,7 @@ try: print('Line 4') - print(sum([i*i for i in range(100) if i&1 == 1]) - ) + print(sum(i*i for i in range(100) if i&1 == 1)) except Exception as __e: print("Occurred", type(__e), __e) @@ -34,8 +33,7 @@ try: print('Line 23') - print(sum([i*i for i in range(100)]) - ) + print(sum(i**2 for i in range(100))) except Exception as __e: print("Occurred", type(__e), __e) @@ -52,7 +50,7 @@ try: def frange(n): - return [i for i in range(n)] + return list(range(n)) except Exception as __e: print("Occurred", type(__e), __e) @@ -83,8 +81,7 @@ def frange(n): try: def grange(n): - for x in [i for i in range(n)]: - yield x + yield from list(range(n)) except Exception as __e: print("Occurred", type(__e), __e) @@ -233,7 +230,7 @@ def test_func(): try: def test_func(): - items = [(lambda: y) for i in range(5)] + items = [lambda: y for _ in range(5)] y = 2 return [x() for x in items] except Exception as __e: diff --git a/doctest_generated/test_setcomps.py b/doctest_generated/test_setcomps.py index 0e121585..685104ba 100644 --- a/doctest_generated/test_setcomps.py +++ b/doctest_generated/test_setcomps.py @@ -43,8 +43,7 @@ try: print('Line 29') - print(sum({i*i for i in range(100)}) - ) + print(sum({i**2 for i in range(100)})) except Exception as __e: print("Occurred", type(__e), __e) @@ -61,7 +60,7 @@ try: def srange(n): - return {i for i in range(n)} + return set(range(n)) except Exception as __e: print("Occurred", type(__e), __e) @@ -92,8 +91,7 @@ def srange(n): try: def grange(n): - for x in {i for i in range(n)}: - yield x + yield from set(range(n)) except Exception as __e: print("Occurred", type(__e), __e) @@ -242,7 +240,7 @@ def test_func(): try: def test_func(): - items = {(lambda: y) for i in range(5)} + items = {lambda: y for _ in range(5)} y = 2 return {x() for x in items} except Exception as __e: diff --git a/run_all.py b/run_all.py index c08e659e..2035f674 100755 --- a/run_all.py +++ b/run_all.py @@ -194,9 +194,7 @@ def checkDir(dirname): if filename == "test_support.py": continue - active = search_mode.consider(dirname, filename) - - if active: + if active := search_mode.consider(dirname, filename): checkPath(dirname, filename) diff --git a/test/_test_multiprocessing.py b/test/_test_multiprocessing.py index 4ae5f976..9b649ef4 100644 --- a/test/_test_multiprocessing.py +++ b/test/_test_multiprocessing.py @@ -91,11 +91,7 @@ def join_process(process): #LOG_LEVEL = logging.DEBUG DELTA = 0.1 -CHECK_TIMINGS = False # making true makes tests take a lot longer - # and can sometimes cause some non-serious - # failures because some calls block a bit - # longer than expected -if CHECK_TIMINGS: +if CHECK_TIMINGS := False: TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4 else: TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1 @@ -356,13 +352,13 @@ def handler(*args): return p.exitcode def test_terminate(self): - exitcode = self._kill_process(multiprocessing.Process.terminate) if os.name != 'nt': + exitcode = self._kill_process(multiprocessing.Process.terminate) self.assertEqual(exitcode, -signal.SIGTERM) def test_kill(self): - exitcode = self._kill_process(multiprocessing.Process.kill) if os.name != 'nt': + exitcode = self._kill_process(multiprocessing.Process.kill) self.assertEqual(exitcode, -signal.SIGKILL) def test_cpu_count(self): @@ -483,8 +479,7 @@ def test_many_processes(self): N = 5 if sm == 'spawn' else 100 # Try to overwhelm the forkserver loop with events - procs = [self.Process(target=self._test_sleep, args=(0.01,)) - for i in range(N)] + procs = [self.Process(target=self._test_sleep, args=(0.01,)) for _ in range(N)] for p in procs: p.start() for p in procs: @@ -492,8 +487,7 @@ def test_many_processes(self): for p in procs: self.assertEqual(p.exitcode, 0) - procs = [self.Process(target=self._sleep_some) - for i in range(N)] + procs = [self.Process(target=self._sleep_some) for _ in range(N)] for p in procs: p.start() time.sleep(0.001) # let the children start... @@ -543,13 +537,16 @@ def test_child_fd_inflation(self): evt = self.Event() q = self.Queue() - procs = [self.Process(target=self._test_child_fd_inflation, args=(evt, q)) - for i in range(N)] + procs = [ + self.Process(target=self._test_child_fd_inflation, args=(evt, q)) + for _ in range(N) + ] + for p in procs: p.start() try: - fd_counts = [q.get() for i in range(N)] + fd_counts = [q.get() for _ in range(N)] self.assertEqual(len(set(fd_counts)), 1, fd_counts) finally: @@ -785,16 +782,10 @@ def test_sys_exit(self): # def queue_empty(q): - if hasattr(q, 'empty'): - return q.empty() - else: - return q.qsize() == 0 + return q.empty() if hasattr(q, 'empty') else q.qsize() == 0 def queue_full(q, maxsize): - if hasattr(q, 'full'): - return q.full() - else: - return q.qsize() == maxsize + return q.full() if hasattr(q, 'full') else q.qsize() == maxsize class _TestQueue(BaseTestCase): @@ -803,7 +794,7 @@ class _TestQueue(BaseTestCase): @classmethod def _test_put(cls, queue, child_can_start, parent_can_continue): child_can_start.wait() - for i in range(6): + for _ in range(6): queue.get() parent_can_continue.set() @@ -983,15 +974,18 @@ def test_qsize(self): @classmethod def _test_task_done(cls, q): - for obj in iter(q.get, None): + for _ in iter(q.get, None): time.sleep(DELTA) q.task_done() def test_task_done(self): queue = self.JoinableQueue() - workers = [self.Process(target=self._test_task_done, args=(queue,)) - for i in range(4)] + workers = [ + self.Process(target=self._test_task_done, args=(queue,)) + for _ in range(4) + ] + for p in workers: p.daemon = True @@ -1012,7 +1006,7 @@ def test_task_done(self): def test_no_import_lock_contention(self): with test.support.temp_cwd(): module_name = 'imported_by_an_imported_module' - with open(module_name + '.py', 'w') as f: + with open(f'{module_name}.py', 'w') as f: f.write("""if 1: import multiprocessing @@ -1204,7 +1198,7 @@ def f(cls, cond, sleeping, woken, timeout=None): cond.release() def assertReachesEventually(self, func, value): - for i in range(10): + for _ in range(10): try: if func() == value: break @@ -1276,7 +1270,7 @@ def test_notify_all(self): woken = self.Semaphore(0) # start some threads/processes which will timeout - for i in range(3): + for _ in range(3): p = self.Process(target=self.f, args=(cond, sleeping, woken, TIMEOUT1)) p.daemon = True @@ -1290,11 +1284,11 @@ def test_notify_all(self): self.addCleanup(t.join) # wait for them all to sleep - for i in range(6): + for _ in range(6): sleeping.acquire() # check they have all timed out - for i in range(6): + for _ in range(6): woken.acquire() self.assertReturnsIfImplemented(0, get_value, woken) @@ -1302,7 +1296,7 @@ def test_notify_all(self): self.check_invariant(cond) # start some more threads/processes - for i in range(3): + for _ in range(3): p = self.Process(target=self.f, args=(cond, sleeping, woken)) p.daemon = True p.start() @@ -1314,7 +1308,7 @@ def test_notify_all(self): self.addCleanup(t.join) # wait for them to all sleep - for i in range(6): + for _ in range(6): sleeping.acquire() # check no process/thread has woken up @@ -1338,7 +1332,7 @@ def test_notify_n(self): woken = self.Semaphore(0) # start some threads/processes - for i in range(3): + for _ in range(3): p = self.Process(target=self.f, args=(cond, sleeping, woken)) p.daemon = True p.start() @@ -1350,7 +1344,7 @@ def test_notify_n(self): self.addCleanup(t.join) # wait for them to all sleep - for i in range(6): + for _ in range(6): sleeping.acquire() # check no process/thread has woken up @@ -1415,7 +1409,7 @@ def test_waitfor(self): self.assertTrue(result) self.assertEqual(state.value, 0) - for i in range(4): + for _ in range(4): time.sleep(0.01) with cond: state.value += 1 @@ -1451,7 +1445,7 @@ def test_waitfor_timeout(self): self.assertTrue(sem.acquire(timeout=TIMEOUT)) # Only increment 3 times, so state == 4 is never reached. - for i in range(3): + for _ in range(3): time.sleep(0.01) with cond: state.value += 1 @@ -1703,7 +1697,7 @@ def test_wait_return(self): """ queue = self.Queue() self.run_threads(self._test_wait_return_f, (self.barrier, queue)) - results = [queue.get() for i in range(self.N)] + results = [queue.get() for _ in range(self.N)] self.assertEqual(results.count(0), 1) close_queue(queue) @@ -1872,14 +1866,14 @@ def test_thousand(self): passes = 1000 lock = self.Lock() conn, child_conn = self.Pipe(False) - for j in range(self.N): + for _ in range(self.N): p = self.Process(target=self._test_thousand_f, args=(self.barrier, passes, child_conn, lock)) p.start() self.addCleanup(p.join) for i in range(passes): - for j in range(self.N): + for _ in range(self.N): self.assertEqual(conn.recv(), i) # @@ -1968,11 +1962,7 @@ def f(cls, seq): @unittest.skipIf(c_int is None, "requires _ctypes") def test_array(self, raw=False): seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831] - if raw: - arr = self.RawArray('i', seq) - else: - arr = self.Array('i', seq) - + arr = self.RawArray('i', seq) if raw else self.Array('i', seq) self.assertEqual(len(arr), len(seq)) self.assertEqual(arr[3], seq[3]) self.assertEqual(list(arr[2:7]), list(seq[2:7])) @@ -2099,7 +2089,7 @@ def test_dict(self): indices = list(range(65, 70)) for i in indices: d[i] = chr(i) - self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices)) + self.assertEqual(d.copy(), {i: chr(i) for i in indices}) self.assertEqual(sorted(d.keys()), indices) self.assertEqual(sorted(d.values()), [chr(i) for i in indices]) self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices]) @@ -2378,7 +2368,7 @@ def test_imap_unordered_handle_iterable_exception(self): expected_values = list(map(sqr, list(range(10)))) with self.assertRaises(SayWhenError): # imap_unordered makes it difficult to anticipate the SayWhenError - for i in range(10): + for _ in range(10): value = next(it) self.assertIn(value, expected_values) expected_values.remove(value) @@ -2388,7 +2378,7 @@ def test_imap_unordered_handle_iterable_exception(self): 2) expected_values = list(map(sqr, list(range(20)))) with self.assertRaises(SayWhenError): - for i in range(20): + for _ in range(20): value = next(it) self.assertIn(value, expected_values) expected_values.remove(value) @@ -2410,8 +2400,9 @@ def test_make_pool(self): def test_terminate(self): result = self.pool.map_async( - time.sleep, [0.1 for i in range(10000)], chunksize=1 - ) + time.sleep, [0.1 for _ in range(10000)], chunksize=1 + ) + self.pool.terminate() join = TimingWrapper(self.pool.join) join() @@ -2446,38 +2437,39 @@ def _test_traceback(cls): def test_traceback(self): # We want ensure that the traceback from the child process is # contained in the traceback raised in the main process. - if self.TYPE == 'processes': - with self.Pool(1) as p: - try: - p.apply(self._test_traceback) - except Exception as e: - exc = e - else: - self.fail('expected RuntimeError') - self.assertIs(type(exc), RuntimeError) - self.assertEqual(exc.args, (123,)) - cause = exc.__cause__ - self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback) - self.assertIn('raise RuntimeError(123) # some comment', cause.tb) - - with test.support.captured_stderr() as f1: - try: - raise exc - except RuntimeError: - sys.excepthook(*sys.exc_info()) - self.assertIn('raise RuntimeError(123) # some comment', - f1.getvalue()) - # _helper_reraises_exception should not make the error - # a remote exception - with self.Pool(1) as p: - try: - p.map(sqr, exception_throwing_generator(1, -1), 1) - except Exception as e: - exc = e - else: - self.fail('expected SayWhenError') - self.assertIs(type(exc), SayWhenError) - self.assertIs(exc.__cause__, None) + if self.TYPE != 'processes': + return + with self.Pool(1) as p: + try: + p.apply(self._test_traceback) + except Exception as e: + exc = e + else: + self.fail('expected RuntimeError') + self.assertIs(type(exc), RuntimeError) + self.assertEqual(exc.args, (123,)) + cause = exc.__cause__ + self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback) + self.assertIn('raise RuntimeError(123) # some comment', cause.tb) + + with test.support.captured_stderr() as f1: + try: + raise exc + except RuntimeError: + sys.excepthook(*sys.exc_info()) + self.assertIn('raise RuntimeError(123) # some comment', + f1.getvalue()) + # _helper_reraises_exception should not make the error + # a remote exception + with self.Pool(1) as p: + try: + p.map(sqr, exception_throwing_generator(1, -1), 1) + except Exception as e: + exc = e + else: + self.fail('expected SayWhenError') + self.assertIs(type(exc), SayWhenError) + self.assertIs(exc.__cause__, None) @classmethod def _test_wrapped_exception(cls): @@ -2512,13 +2504,13 @@ def test_map_no_failfast(self): def test_release_task_refs(self): # Issue #29861: task arguments and results should not be kept # alive after we are done with them. - objs = [CountedObject() for i in range(10)] + objs = [CountedObject() for _ in range(10)] refs = [weakref.ref(o) for o in objs] self.pool.map(identity, objs) del objs time.sleep(DELTA) # let threaded cleanup code run - self.assertEqual(set(wr() for wr in refs), {None}) + self.assertEqual({wr() for wr in refs}, {None}) # With a process pool, copies of the objects are returned, check # they were released too. self.assertEqual(CountedObject.n_instances, 0) @@ -2578,9 +2570,7 @@ def test_pool_worker_lifetime(self): self.assertEqual(3, len(p._pool)) origworkerpids = [w.pid for w in p._pool] # Run many tasks so each worker gets replaced (hopefully) - results = [] - for i in range(100): - results.append(p.apply_async(sqr, (i, ))) + results = [p.apply_async(sqr, (i, )) for i in range(100)] # Fetch the results and verify we got the right answers, # also ensuring all the tasks have completed. for (j, res) in enumerate(results): @@ -2606,9 +2596,7 @@ def test_pool_worker_lifetime_early_close(self): # Issue #10332: closing a pool whose workers have limited lifetimes # before all the tasks completed would make join() hang. p = multiprocessing.Pool(3, maxtasksperchild=1) - results = [] - for i in range(6): - results.append(p.apply_async(sqr, (i, 0.3))) + results = [p.apply_async(sqr, (i, 0.3)) for i in range(6)] p.close() p.join() # check the results @@ -2984,7 +2972,7 @@ def _is_fd_assigned(cls, fd): @classmethod def _writefd(cls, conn, data, create_dummy_fds=False): if create_dummy_fds: - for i in range(0, 256): + for i in range(256): if not cls._is_fd_assigned(i): os.dup2(conn.fileno(), i) fd = reduction.recv_handle(conn) @@ -3174,7 +3162,7 @@ def test_strings(self): p.start() for s in strings: - for i in range(200): + for _ in range(200): if a.poll(0.01): break x = a.recv_bytes() @@ -3395,9 +3383,8 @@ def test_heap(self): heap._lock.acquire() self.addCleanup(heap._lock.release) for L in list(heap._len_to_seq.values()): - for arena, start, stop in L: - all.append((heap._arenas.index(arena), start, stop, - stop-start, 'free')) + all.extend((heap._arenas.index(arena), start, stop, + stop-start, 'free') for arena, start, stop in L) for arena, start, stop in heap._allocated_blocks: all.append((heap._arenas.index(arena), start, stop, stop-start, 'occupied')) @@ -3426,7 +3413,7 @@ def test_free_from_gc(self): # perform numerous block allocations, with cyclic references to make # sure objects are collected asynchronously by the gc - for i in range(5000): + for _ in range(5000): a = multiprocessing.heap.BufferWrapper(1) b = multiprocessing.heap.BufferWrapper(1) # circular references @@ -3561,7 +3548,7 @@ def test_finalize(self): p.start() p.join() - result = [obj for obj in iter(conn.recv, 'STOP')] + result = list(iter(conn.recv, 'STOP')) self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e']) def test_thread_safety(self): @@ -3596,7 +3583,7 @@ def make_finalizers(): try: # Old Foo's get gradually replaced and later # collected by the GC (because of the cyclic ref) - d[random.getrandbits(5)] = {Foo() for i in range(10)} + d[random.getrandbits(5)] = {Foo() for _ in range(10)} except Exception as e: exc = e d.clear() @@ -3631,7 +3618,7 @@ def get_module_names(self): pattern = os.path.join(folder, '*.py') files = glob.glob(pattern) modules = [os.path.splitext(os.path.split(f)[1])[0] for f in files] - modules = ['multiprocessing.' + m for m in modules] + modules = [f'multiprocessing.{m}' for m in modules] modules.remove('multiprocessing.__init__') modules.append('multiprocessing') return modules @@ -3934,7 +3921,7 @@ def test_wait(self, slow=False): procs = [] messages = [] - for i in range(4): + for _ in range(4): r, w = multiprocessing.Pipe(duplex=False) p = multiprocessing.Process(target=self._child_test_wait, args=(w, slow)) p.daemon = True @@ -3978,7 +3965,7 @@ def test_wait_socket(self, slow=False): procs = [] dic = {} - for i in range(4): + for _ in range(4): p = multiprocessing.Process(target=self._child_test_wait_socket, args=(addr, slow)) p.daemon = True @@ -3986,7 +3973,7 @@ def test_wait_socket(self, slow=False): procs.append(p) self.addCleanup(p.join) - for i in range(4): + for _ in range(4): r, _ = l.accept() readers.append(r) dic[r] = [] @@ -3994,13 +3981,12 @@ def test_wait_socket(self, slow=False): while readers: for r in wait(readers): - msg = r.recv(32) - if not msg: - readers.remove(r) - r.close() - else: + if msg := r.recv(32): dic[r].append(msg) + else: + readers.remove(r) + r.close() expected = ''.join('%s\n' % i for i in range(10)).encode('ascii') for v in dic.values(): self.assertEqual(b''.join(v), expected) @@ -4235,17 +4221,16 @@ def get_high_socket_fd(self): # calling socket.fromfd() should produce WSAENOTSOCK even # if there is a handle of the same number. return socket.socket().detach() - else: - # We want to produce a socket with an fd high enough that a - # freshly created child process will not have any fds as high. - fd = socket.socket().detach() - to_close = [] - while fd < 50: - to_close.append(fd) - fd = os.dup(fd) - for x in to_close: - os.close(x) - return fd + # We want to produce a socket with an fd high enough that a + # freshly created child process will not have any fds as high. + fd = socket.socket().detach() + to_close = [] + while fd < 50: + to_close.append(fd) + fd = os.dup(fd) + for x in to_close: + os.close(x) + return fd def close(self, fd): if WIN32: @@ -4414,8 +4399,9 @@ def test_get_all(self): if sys.platform == 'win32': self.assertEqual(methods, ['spawn']) else: - self.assertTrue(methods == ['fork', 'spawn'] or - methods == ['fork', 'spawn', 'forkserver']) + self.assertTrue( + methods in [['fork', 'spawn'], ['fork', 'spawn', 'forkserver']] + ) def test_preload_resources(self): if multiprocessing.get_start_method() != 'forkserver': @@ -4557,15 +4543,15 @@ def tearDownClass(cls): # cycles. Trigger a garbage collection to break these cycles. test.support.gc_collect() - processes = set(multiprocessing.process._dangling) - set(cls.dangling[0]) - if processes: + if processes := set(multiprocessing.process._dangling) - set( + cls.dangling[0] + ): test.support.environment_altered = True print('Warning -- Dangling processes: %s' % processes, file=sys.stderr) processes = None - threads = set(threading._dangling) - set(cls.dangling[1]) - if threads: + if threads := set(threading._dangling) - set(cls.dangling[1]): test.support.environment_altered = True print('Warning -- Dangling threads: %s' % threads, file=sys.stderr) @@ -4741,17 +4727,14 @@ def tearDownModule(): test.support.gc_collect() multiprocessing.set_start_method(old_start_method[0], force=True) - # pause a bit so we don't get warning about dangling threads/processes - processes = set(multiprocessing.process._dangling) - set(dangling[0]) - if processes: + if processes := set(multiprocessing.process._dangling) - set(dangling[0]): need_sleep = True test.support.environment_altered = True print('Warning -- Dangling processes: %s' % processes, file=sys.stderr) processes = None - threads = set(threading._dangling) - set(dangling[1]) - if threads: + if threads := set(threading._dangling) - set(dangling[1]): need_sleep = True test.support.environment_altered = True print('Warning -- Dangling threads: %s' % threads, diff --git a/test/bytecode_helper.py b/test/bytecode_helper.py index 347d6033..a5e71110 100644 --- a/test/bytecode_helper.py +++ b/test/bytecode_helper.py @@ -17,15 +17,16 @@ def get_disassembly_as_string(self, co): def assertInBytecode(self, x, opname, argval=_UNSPECIFIED): """Returns instr if op is found, otherwise throws AssertionError""" for instr in dis.get_instructions(x): - if instr.opname == opname: - if argval is _UNSPECIFIED or instr.argval == argval: - return instr + if instr.opname == opname and ( + argval is _UNSPECIFIED or instr.argval == argval + ): + return instr disassembly = self.get_disassembly_as_string(x) if argval is _UNSPECIFIED: msg = '%s not found in bytecode:\n%s' % (opname, disassembly) else: msg = '(%s,%r) not found in bytecode:\n%s' - msg = msg % (opname, argval, disassembly) + msg %= (opname, argval, disassembly) self.fail(msg) def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): @@ -37,5 +38,5 @@ def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): msg = '%s occurs in bytecode:\n%s' % (opname, disassembly) elif instr.argval == argval: msg = '(%s,%r) occurs in bytecode:\n%s' - msg = msg % (opname, argval, disassembly) + msg %= (opname, argval, disassembly) self.fail(msg) diff --git a/test/curses_tests.py b/test/curses_tests.py index 40e832de..b3a47a10 100755 --- a/test/curses_tests.py +++ b/test/curses_tests.py @@ -13,11 +13,7 @@ def test_textpad(stdscr, insert_mode=False): ncols, nlines = 8, 3 uly, ulx = 3, 2 - if insert_mode: - mode = 'insert mode' - else: - mode = 'overwrite mode' - + mode = 'insert mode' if insert_mode else 'overwrite mode' stdscr.addstr(uly-3, ulx, "Use Ctrl-G to end editing (%s)." % mode) stdscr.addstr(uly-2, ulx, "Be sure to try typing in the lower-right corner.") win = curses.newwin(nlines, ncols, uly, ulx) diff --git a/test/datetimetester.py b/test/datetimetester.py index 7d4cdac9..4f17f6f1 100644 --- a/test/datetimetester.py +++ b/test/datetimetester.py @@ -66,8 +66,8 @@ def test_name_cleanup(self): self.skipTest('Only run for Fast C implementation') datetime = datetime_module - names = set(name for name in dir(datetime) - if not name.startswith('__') and not name.endswith('__')) + names = {name for name in dir(datetime) + if not name.startswith('__') and not name.endswith('__')} allowed = set(['MAXYEAR', 'MINYEAR', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']) @@ -334,7 +334,7 @@ def test_comparison(self): with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO) self.assertIn(timezone(ZERO), {timezone(ZERO)}) self.assertTrue(timezone(ZERO) != None) - self.assertFalse(timezone(ZERO) == None) + self.assertFalse(timezone(ZERO) is None) def test_aware_datetime(self): # test that timezone instances can be used by datetime @@ -592,8 +592,7 @@ def test_hash_equality(self): self.assertEqual(t1, t2) self.assertEqual(hash(t1), hash(t2)) - d = {t1: 1} - d[t2] = 2 + d = {t1: 1, t2: 2} self.assertEqual(len(d), 1) self.assertEqual(d[t1], 2) @@ -667,7 +666,7 @@ def test_str(self): "999999999 days, 23:59:59.999999") def test_repr(self): - name = 'datetime.' + self.theclass.__name__ + name = f'datetime.{self.theclass.__name__}' self.assertEqual(repr(self.theclass(1)), "%s(days=1)" % name) self.assertEqual(repr(self.theclass(10, 2)), @@ -1074,8 +1073,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -1086,8 +1084,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -1181,7 +1178,7 @@ def test_today(self): # We claim that today() is like fromtimestamp(time.time()), so # prove it. - for dummy in range(3): + for _ in range(3): today = self.theclass.today() ts = time.time() todayagain = self.theclass.fromtimestamp(ts) @@ -1341,10 +1338,7 @@ def strftime(self, format_spec): def test_resolution_info(self): # XXX: Should min and max respect subclassing? - if issubclass(self.theclass, datetime): - expected_class = datetime - else: - expected_class = date + expected_class = datetime if issubclass(self.theclass, datetime) else date self.assertIsInstance(self.theclass.min, expected_class) self.assertIsInstance(self.theclass.max, expected_class) self.assertIsInstance(self.theclass.resolution, timedelta) @@ -1506,17 +1500,14 @@ def test_replace(self): base = cls(*args) self.assertEqual(base, base.replace()) - i = 0 - for name, newval in (("year", 2), + for i, (name, newval) in enumerate((("year", 2), ("month", 3), - ("day", 4)): + ("day", 4))): newargs = args[:] newargs[i] = newval expected = cls(*newargs) got = base.replace(**{name: newval}) self.assertEqual(expected, got) - i += 1 - # Out of bounds. base = cls(2000, 2, 29) self.assertRaises(ValueError, base.replace, year=2001) @@ -1940,8 +1931,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -1951,8 +1941,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -2266,12 +2255,11 @@ def test_utcnow(self): # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) - for dummy in range(3): + for _ in range(3): from_now = self.theclass.utcnow() from_timestamp = self.theclass.utcfromtimestamp(time.time()) if abs(from_timestamp - from_now) <= tolerance: break - # Else try again a few times. self.assertLessEqual(abs(from_timestamp - from_now), tolerance) def test_strptime(self): @@ -2348,7 +2336,7 @@ def test_more_strftime(self): for (s, us), z in [((33, 123), "33.000123"), ((33, 0), "33"),]: tz = timezone(-timedelta(hours=2, seconds=s, microseconds=us)) t = t.replace(tzinfo=tz) - self.assertEqual(t.strftime("%z"), "-0200" + z) + self.assertEqual(t.strftime("%z"), f'-0200{z}') def test_extract(self): dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) @@ -2395,21 +2383,18 @@ def test_replace(self): base = cls(*args) self.assertEqual(base, base.replace()) - i = 0 - for name, newval in (("year", 2), + for i, (name, newval) in enumerate((("year", 2), ("month", 3), ("day", 4), ("hour", 5), ("minute", 6), ("second", 7), - ("microsecond", 8)): + ("microsecond", 8))): newargs = args[:] newargs[i] = newval expected = cls(*newargs) got = base.replace(**{name: newval}) self.assertEqual(expected, got) - i += 1 - # Out of bounds. base = cls(2000, 2, 29) self.assertRaises(ValueError, base.replace, year=2001) @@ -2627,9 +2612,9 @@ def test_fromisoformat_timespecs(self): for dt_tuple in datetime_bases: if ts == 'milliseconds': new_microseconds = 1000 * (dt_tuple[6] // 1000) - dt_tuple = dt_tuple[0:6] + (new_microseconds,) + dt_tuple = dt_tuple[:6] + (new_microseconds,) - dt = self.theclass(*(dt_tuple[0:(4 + ip)]), tzinfo=tzi) + dt = self.theclass(*dt_tuple[:4 + ip], tzinfo=tzi) dtstr = dt.isoformat(timespec=ts) with self.subTest(dtstr=dtstr): dt_rt = self.theclass.fromisoformat(dtstr) @@ -2805,8 +2790,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -2816,8 +2800,7 @@ def test_hash_equality(self): self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) - dic = {d: 1} - dic[e] = 2 + dic = {d: 1, e: 2} self.assertEqual(len(dic), 1) self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) @@ -2948,7 +2931,7 @@ def test_str(self): self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00") def test_repr(self): - name = 'datetime.' + self.theclass.__name__ + name = f'datetime.{self.theclass.__name__}' self.assertEqual(repr(self.theclass(1, 2, 3, 4)), "%s(1, 2, 3, 4)" % name) self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), @@ -2999,18 +2982,15 @@ def test_replace(self): base = cls(*args) self.assertEqual(base, base.replace()) - i = 0 - for name, newval in (("hour", 5), + for i, (name, newval) in enumerate((("hour", 5), ("minute", 6), ("second", 7), - ("microsecond", 8)): + ("microsecond", 8))): newargs = args[:] newargs[i] = newval expected = cls(*newargs) got = base.replace(**{name: newval}) self.assertEqual(expected, got) - i += 1 - # Out of bounds. base = cls(1) self.assertRaises(ValueError, base.replace, hour=24) @@ -3070,7 +3050,8 @@ def test_argument_passing(self): cls = self.theclass # A datetime passes itself on, a time passes None. class introspective(tzinfo): - def tzname(self, dt): return dt and "real" or "none" + def tzname(self, dt): + return "real" if dt else "none" def utcoffset(self, dt): return timedelta(minutes = dt and 42 or -42) dst = utcoffset @@ -3379,19 +3360,16 @@ def test_replace(self): base = cls(*args) self.assertEqual(base, base.replace()) - i = 0 - for name, newval in (("hour", 5), + for i, (name, newval) in enumerate((("hour", 5), ("minute", 6), ("second", 7), ("microsecond", 8), - ("tzinfo", zm200)): + ("tzinfo", zm200))): newargs = args[:] newargs[i] = newval expected = cls(*newargs) got = base.replace(**{name: newval}) self.assertEqual(expected, got) - i += 1 - # Ensure we can get rid of a tzinfo. self.assertEqual(base.tzname(), "+100") base2 = base.replace(tzinfo=None) @@ -3510,9 +3488,9 @@ def test_fromisoformat_timespecs(self): for t_tuple in time_bases: if ts == 'milliseconds': new_microseconds = 1000 * (t_tuple[-1] // 1000) - t_tuple = t_tuple[0:-1] + (new_microseconds,) + t_tuple = t_tuple[:-1] + (new_microseconds,) - t = self.theclass(*(t_tuple[0:(1 + ip)]), tzinfo=tzi) + t = self.theclass(*t_tuple[:1 + ip], tzinfo=tzi) tstr = t.isoformat(timespec=ts) with self.subTest(tstr=tstr): t_rt = self.theclass.fromisoformat(tstr) @@ -3742,9 +3720,9 @@ def test_zones(self): self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00") self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00") d = 'datetime.datetime(2002, 3, 19, ' - self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)") - self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)") - self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)") + self.assertEqual(repr(t1), f'{d}7, 47, tzinfo=est)') + self.assertEqual(repr(t2), f'{d}12, 47, tzinfo=utc)') + self.assertEqual(repr(t3), f'{d}13, 47, tzinfo=met)') def test_combine(self): met = FixedOffset(60, "MET") @@ -4051,11 +4029,11 @@ def test_tzinfo_isoformat(self): ofsstr = ofs is not None and d.tzname() or '' tailstr = timestr + ofsstr iso = d.isoformat() - self.assertEqual(iso, datestr + 'T' + tailstr) + self.assertEqual(iso, f'{datestr}T{tailstr}') self.assertEqual(iso, d.isoformat('T')) - self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr) - self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr) - self.assertEqual(str(d), datestr + ' ' + tailstr) + self.assertEqual(d.isoformat('k'), f'{datestr}k{tailstr}') + self.assertEqual(d.isoformat('\u1234'), f'{datestr}ሴ{tailstr}') + self.assertEqual(str(d), f'{datestr} {tailstr}') def test_replace(self): cls = self.theclass @@ -4065,22 +4043,19 @@ def test_replace(self): base = cls(*args) self.assertEqual(base, base.replace()) - i = 0 - for name, newval in (("year", 2), + for i, (name, newval) in enumerate((("year", 2), ("month", 3), ("day", 4), ("hour", 5), ("minute", 6), ("second", 7), ("microsecond", 8), - ("tzinfo", zm200)): + ("tzinfo", zm200))): newargs = args[:] newargs[i] = newval expected = cls(*newargs) got = base.replace(**{name: newval}) self.assertEqual(expected, got) - i += 1 - # Ensure we can get rid of a tzinfo. self.assertEqual(base.tzname(), "+100") base2 = base.replace(tzinfo=None) @@ -4255,8 +4230,7 @@ def newmeth(self, start): # Pain to set up DST-aware tzinfo classes. def first_sunday_on_or_after(dt): - days_to_go = 6 - dt.weekday() - if days_to_go: + if days_to_go := 6 - dt.weekday(): dt += timedelta(days_to_go) return dt @@ -4284,10 +4258,7 @@ def __repr__(self): return self.reprname def tzname(self, dt): - if self.dst(dt): - return self.dstname - else: - return self.stdname + return self.dstname if self.dst(dt) else self.stdname def utcoffset(self, dt): return self.stdoffset + self.dst(dt) @@ -4309,10 +4280,7 @@ def dst(self, dt): # Can't compare naive to aware objects, so strip the timezone from # dt first. - if start <= dt.replace(tzinfo=None) < end: - return HOUR - else: - return ZERO + return HOUR if start <= dt.replace(tzinfo=None) < end else ZERO Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") Central = USTimeZone(-6, "Central", "CST", "CDT") @@ -4511,10 +4479,7 @@ def dst(self, dt): return None # a ValueError should be raised by astimezone(). class tricky_notok(ok): def dst(self, dt): - if dt.year == 2000: - return None - else: - return 10*HOUR + return None if dt.year == 2000 else 10*HOUR dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real) self.assertRaises(ValueError, dt.astimezone, tricky_notok()) @@ -4698,8 +4663,8 @@ def fromutc(self, dt): if off0 == off1: ldt = dt + off0 off1 = ldt.utcoffset() - if off0 == off1: - return ldt + if off0 == off1: + return ldt # Now, we discovered both possible offsets, so # we can just try four possible solutions: for off in [off0, off1]: @@ -4726,10 +4691,7 @@ def __repr__(self): return self.reprname def tzname(self, dt): - if self.dst(dt): - return self.dstname - else: - return self.stdname + return self.dstname if self.dst(dt) else self.stdname def utcoffset(self, dt): return self.stdoffset + self.dst(dt) @@ -5152,10 +5114,7 @@ def fromfile(cls, fileobj): type_indices = array('B') type_indices.fromfile(fileobj, counts[0]) - ttis = [] - for i in range(counts[1]): - ttis.append(struct.unpack(">lbb", fileobj.read(6))) - + ttis = [struct.unpack(">lbb", fileobj.read(6)) for _ in range(counts[1])] abbrs = fileobj.read(counts[2]) # Convert ttis @@ -5167,9 +5126,7 @@ def fromfile(cls, fileobj): for i, idx in enumerate(type_indices): ti[i] = ttis[idx] - self = cls(ut, ti) - - return self + return cls(ut, ti) @classmethod def fromname(cls, name): @@ -5204,10 +5161,7 @@ def fromutc(self, dt): shift = tti_prev[0] - tti[0] fold = (shift > timedelta(0, timestamp - self.ut[idx-1])) dt += tti[0] - if fold: - return dt.replace(fold=1) - else: - return dt + return dt.replace(fold=1) if fold else dt def _find_ti(self, dt, i): timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400 @@ -5449,9 +5403,12 @@ def __init__(self): for name in ZoneInfo.zonenames(): Test = type('ZoneInfoTest[%s]' % name, (ZoneInfoTest,), {}) Test.zonename = name - for method in dir(Test): - if method.startswith('test_'): - tests.append(Test(method)) + tests.extend( + Test(method) + for method in dir(Test) + if method.startswith('test_') + ) + super().__init__(tests) # Iran had a sub-minute UTC offset before 1946. diff --git a/test/fork_wait.py b/test/fork_wait.py index 9850b06a..1577a1da 100644 --- a/test/fork_wait.py +++ b/test/fork_wait.py @@ -44,7 +44,7 @@ def f(self, id): pass def wait_impl(self, cpid): - for i in range(10): + for _ in range(10): # waitpid() shouldn't hang, but some of the buildbots seem to hang # in the forking tests. This is an attempt to fix the problem. spid, status = os.waitpid(cpid, os.WNOHANG) @@ -73,18 +73,11 @@ def test_wait(self): prefork_lives = self.alive.copy() - if sys.platform in ['unixware7']: - cpid = os.fork1() - else: - cpid = os.fork() - + cpid = os.fork1() if sys.platform in ['unixware7'] else os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) - n = 0 - for key in self.alive: - if self.alive[key] != prefork_lives[key]: - n += 1 + n = sum(self.alive[key] != prefork_lives[key] for key in self.alive) os._exit(n) else: # Parent diff --git a/test/list_tests.py b/test/list_tests.py index ed63fda2..03c8453f 100644 --- a/test/list_tests.py +++ b/test/list_tests.py @@ -55,7 +55,7 @@ def test_repr(self): def test_repr_deep(self): a = self.type2test([]) - for i in range(sys.getrecursionlimit() + 100): + for _ in range(sys.getrecursionlimit() + 100): a = self.type2test([a]) self.assertRaises(RecursionError, repr, a) diff --git a/test/lock_tests.py b/test/lock_tests.py index 8c9ca78a..b535c2c1 100644 --- a/test/lock_tests.py +++ b/test/lock_tests.py @@ -844,7 +844,6 @@ def f(): results2.append(True) except RuntimeError: self.barrier.abort() - pass self.run_threads(f) self.assertEqual(len(results1), 0) @@ -900,7 +899,6 @@ def f(): results2.append(True) except RuntimeError: self.barrier.abort() - pass # Synchronize and reset the barrier. Must synchronize first so # that everyone has left it when we reset, and after so that no # one enters it before the reset. diff --git a/test/make_ssl_certs.py b/test/make_ssl_certs.py index b908c40c..1677e3a8 100644 --- a/test/make_ssl_certs.py +++ b/test/make_ssl_certs.py @@ -109,9 +109,9 @@ def make_cert_key(hostname, sign=False, extra_san='', ext='req_x509_extensions_full', key='rsa:2048'): - print("creating cert for " + hostname) + print(f'creating cert for {hostname}') tempnames = [] - for i in range(3): + for _ in range(3): with tempfile.NamedTemporaryFile(delete=False) as f: tempnames.append(f.name) req_file, cert_file, key_file = tempnames diff --git a/test/mapping_tests.py b/test/mapping_tests.py index 53f29f60..b6c39e82 100644 --- a/test/mapping_tests.py +++ b/test/mapping_tests.py @@ -136,8 +136,8 @@ def test_constructor(self): def test_bool(self): self.assertTrue(not self._empty_mapping()) self.assertTrue(self.reference) - self.assertTrue(bool(self._empty_mapping()) is False) - self.assertTrue(bool(self.reference) is True) + self.assertTrue(not bool(self._empty_mapping())) + self.assertTrue(bool(self.reference)) def test_keys(self): d = self._empty_mapping() @@ -312,8 +312,8 @@ def test_bool(self): BasicTestMappingProtocol.test_bool(self) self.assertTrue(not self._empty_mapping()) self.assertTrue(self._full_mapping({"x": "y"})) - self.assertTrue(bool(self._empty_mapping()) is False) - self.assertTrue(bool(self._full_mapping({"x": "y"})) is True) + self.assertTrue(not bool(self._empty_mapping())) + self.assertTrue(bool(self._full_mapping({"x": "y"}))) def test_keys(self): BasicTestMappingProtocol.test_keys(self) @@ -339,7 +339,7 @@ def test_items(self): def test_contains(self): d = self._empty_mapping() self.assertNotIn('a', d) - self.assertTrue(not ('a' in d)) + self.assertTrue('a' not in d) self.assertTrue('a' not in d) d = self._full_mapping({'a': 1, 'b': 2}) self.assertIn('a', d) @@ -512,12 +512,12 @@ def test_popitem(self): b[repr(i)] = i if copymode > 0: b = a.copy() - for i in range(size): + for _ in range(size): ka, va = ta = a.popitem() self.assertEqual(va, int(ka)) kb, vb = tb = b.popitem() self.assertEqual(vb, int(kb)) - self.assertTrue(not(copymode < 0 and ta != tb)) + self.assertTrue(copymode >= 0 or ta == tb) self.assertTrue(not a) self.assertTrue(not b) @@ -622,7 +622,7 @@ def __repr__(self): def test_repr_deep(self): d = self._empty_mapping() - for i in range(sys.getrecursionlimit() + 100): + for _ in range(sys.getrecursionlimit() + 100): d0 = d d = self._empty_mapping() d[1] = d0 diff --git a/test/mock_socket.py b/test/mock_socket.py index b28c4732..72046a97 100644 --- a/test/mock_socket.py +++ b/test/mock_socket.py @@ -50,17 +50,13 @@ def queue_recv(self, line): self.lines.append(line) def recv(self, bufsize, flags=None): - data = self.lines.pop(0) + b'\r\n' - return data + return self.lines.pop(0) + b'\r\n' def fileno(self): return 0 def settimeout(self, timeout): - if timeout is None: - self.timeout = _defaulttimeout - else: - self.timeout = timeout + self.timeout = _defaulttimeout if timeout is None else timeout def gettimeout(self): return self.timeout @@ -88,8 +84,7 @@ def listen(self, backlog): pass def makefile(self, mode='r', bufsize=-1): - handle = MockFile(self.lines) - return handle + return MockFile(self.lines) def sendall(self, buffer, flags=None): self.last = data diff --git a/test/multibytecodec_support.py b/test/multibytecodec_support.py index 813b7aa1..b589d697 100644 --- a/test/multibytecodec_support.py +++ b/test/multibytecodec_support.py @@ -49,10 +49,7 @@ def test_chunkcoding(self): def test_errorhandle(self): for source, scheme, expected in self.codectests: - if isinstance(source, bytes): - func = self.decode - else: - func = self.encode + func = self.decode if isinstance(source, bytes) else self.encode if expected: result = func(source, scheme)[0] if func is self.decode: @@ -145,11 +142,10 @@ def myreplace(exc): def test_callback_backward_index(self): def myreplace(exc): - if myreplace.limit > 0: - myreplace.limit -= 1 - return ('REPLACED', 0) - else: + if myreplace.limit <= 0: return ('TERMINAL', exc.end) + myreplace.limit -= 1 + return ('REPLACED', 0) myreplace.limit = 3 codecs.register_error("test.cjktest", myreplace) self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh', @@ -178,11 +174,7 @@ def test_incrementalencoder(self): ostream = BytesIO() encoder = self.incrementalencoder() while 1: - if sizehint is not None: - data = istream.read(sizehint) - else: - data = istream.read() - + data = istream.read(sizehint) if sizehint is not None else istream.read() if not data: break e = encoder.encode(data) @@ -198,13 +190,12 @@ def test_incrementaldecoder(self): ostream = UTF8Writer(BytesIO()) decoder = self.incrementaldecoder() while 1: - data = istream.read(sizehint) - if not data: - break - else: + if data := istream.read(sizehint): u = decoder.decode(data) ostream.write(u) + else: + break self.assertEqual(ostream.getvalue(), self.tstring[1]) def test_incrementalencoder_error_callback(self): @@ -256,11 +247,7 @@ def test_streamwriter(self): ostream = self.writer(BytesIO()) func = getattr(istream, name) while 1: - if sizehint is not None: - data = func(sizehint) - else: - data = func() - + data = func(sizehint) if sizehint is not None else func() if not data: break if name == "readlines": @@ -288,7 +275,7 @@ def setUp(self): try: self.open_mapping_file().close() # test it to report the error early except (OSError, HTTPException): - self.skipTest("Could not retrieve "+self.mapfileurl) + self.skipTest(f'Could not retrieve {self.mapfileurl}') def open_mapping_file(self): return support.open_urlresource(self.mapfileurl) @@ -353,10 +340,7 @@ def _testpoint(self, csetch, unich): def test_errorhandle(self): for source, scheme, expected in self.codectests: - if isinstance(source, bytes): - func = source.decode - else: - func = source.encode + func = source.decode if isinstance(source, bytes) else source.encode if expected: if isinstance(source, bytes): result = func(self.encoding, scheme) @@ -377,8 +361,8 @@ def test_errorhandle(self): def load_teststring(name): dir = os.path.join(os.path.dirname(__file__), 'cjkencodings') - with open(os.path.join(dir, name + '.txt'), 'rb') as f: + with open(os.path.join(dir, f'{name}.txt'), 'rb') as f: encoded = f.read() - with open(os.path.join(dir, name + '-utf8.txt'), 'rb') as f: + with open(os.path.join(dir, f'{name}-utf8.txt'), 'rb') as f: utf8 = f.read() return encoded, utf8 diff --git a/test/pickletester.py b/test/pickletester.py index 71c2fead..ae019522 100644 --- a/test/pickletester.py +++ b/test/pickletester.py @@ -30,18 +30,17 @@ # Return True if opcode code appears in the pickle, else False. def opcode_in_pickle(code, pickle): - for op, dummy, dummy in pickletools.genops(pickle): - if op.code == code.decode("latin-1"): - return True - return False + return any( + op.code == code.decode("latin-1") + for op, dummy, dummy in pickletools.genops(pickle) + ) # Return the number of times opcode code appears in pickle. def count_opcode(code, pickle): - n = 0 - for op, dummy, dummy in pickletools.genops(pickle): - if op.code == code.decode("latin-1"): - n += 1 - return n + return sum( + op.code == code.decode("latin-1") + for op, dummy, dummy in pickletools.genops(pickle) + ) class UnseekableIO(io.BytesIO): @@ -638,22 +637,19 @@ def create_dynamic_class(name, bases): def create_data(): c = C() - c.foo = 1 - c.bar = 2 - x = [0, 1, 2.0, 3.0+0j] # Append some integer test cases at cPickle.c's internal size # cutoffs. uint1max = 0xff uint2max = 0xffff int4max = 0x7fffffff - x.extend([1, -1, + x = [0, 1, 2.0, 3.0 + 0j, *[1, -1, uint1max, -uint1max, -uint1max-1, uint2max, -uint2max, -uint2max-1, - int4max, -int4max, -int4max-1]) + int4max, -int4max, -int4max-1]] + c.foo = 1 + c.bar = 2 y = ('abc', 'abc', c, c) - x.append(y) - x.append(y) - x.append(5) + x.extend((y, y, 5)) return x @@ -1452,7 +1448,7 @@ def test_long(self): def test_float(self): test_values = [0.0, 4.94e-324, 1e-310, 7e-308, 6.626e-34, 0.1, 0.5, 3.14, 263.44582062374053, 6.022e23, 1e30] - test_values = test_values + [-x for x in test_values] + test_values += [-x for x in test_values] for proto in protocols: for value in test_values: pickle = self.dumps(value, proto) @@ -1462,7 +1458,7 @@ def test_float(self): @run_with_locale('LC_ALL', 'de_DE', 'fr_FR') def test_float_format(self): # make sure that floats are formatted locale independent with proto 0 - self.assertEqual(self.dumps(1.2, 0)[0:3], b'F1.') + self.assertEqual(self.dumps(1.2, 0)[:3], b'F1.') def test_reduce(self): for proto in protocols: @@ -1824,8 +1820,7 @@ def test_simple_newobj(self): self.assertIn(b'\nI64206', s) # INT else: self.assertIn(b'M\xce\xfa', s) # BININT2 - self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), - 2 <= proto) + self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s)) y = self.loads(s) # will raise TypeError if __init__ called self.assert_is_copy(x, y) @@ -1844,8 +1839,7 @@ def test_complex_newobj(self): self.assertIn(b'X\x04\x00\x00\x00FACE', s) # BINUNICODE else: self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE - self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), - 2 <= proto) + self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s)) y = self.loads(s) # will raise TypeError if __init__ called self.assert_is_copy(x, y) @@ -1865,8 +1859,7 @@ def test_complex_newobj_ex(self): else: self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE self.assertFalse(opcode_in_pickle(pickle.NEWOBJ, s)) - self.assertEqual(opcode_in_pickle(pickle.NEWOBJ_EX, s), - 4 <= proto) + self.assertEqual(opcode_in_pickle(pickle.NEWOBJ_EX, s), proto >= 4) y = self.loads(s) # will raise TypeError if __init__ called self.assert_is_copy(x, y) @@ -1956,8 +1949,8 @@ def __reduce__(self): def test_many_puts_and_gets(self): # Test that internal data structures correctly deal with lots of # puts/gets. - keys = ("aaa" + str(i) for i in range(100)) - large_dict = dict((k, [4, 5, 6]) for k in keys) + keys = (f'aaa{str(i)}' for i in range(100)) + large_dict = {k: [4, 5, 6] for k in keys} obj = [dict(large_dict), dict(large_dict), dict(large_dict)] for proto in protocols: @@ -2063,18 +2056,17 @@ def check_frame_opcodes(self, pickled): # in a frame self.assertLessEqual(len(arg), self.FRAME_SIZE_TARGET) - else: # not framed - if (op.name == 'FRAME' or + elif (op.name == 'FRAME' or (op.name in frameless_opcodes and len(arg) > self.FRAME_SIZE_TARGET)): - # Frame or large bytes or str object - if frameless_start is not None: - # Only short data should be written outside of a frame - self.assertLess(pos - frameless_start, - self.FRAME_SIZE_MIN) - frameless_start = None - elif frameless_start is None and op.name != 'PROTO': - frameless_start = pos + # Frame or large bytes or str object + if frameless_start is not None: + # Only short data should be written outside of a frame + self.assertLess(pos - frameless_start, + self.FRAME_SIZE_MIN) + frameless_start = None + elif frameless_start is None and op.name != 'PROTO': + frameless_start = pos if op.name == 'FRAME': self.assertGreaterEqual(arg, self.FRAME_SIZE_MIN) @@ -2139,12 +2131,13 @@ def test_optional_frames(self): def remove_frames(pickled, keep_frame=None): """Remove frame opcodes from the given pickle.""" - frame_starts = [] # 1 byte for the opcode and 8 for the argument frame_opcode_size = 9 - for opcode, _, pos in pickletools.genops(pickled): - if opcode.name == 'FRAME': - frame_starts.append(pos) + frame_starts = [ + pos + for opcode, _, pos in pickletools.genops(pickled) + if opcode.name == 'FRAME' + ] newpickle = bytearray() last_frame_end = 0 @@ -2891,7 +2884,7 @@ def _check_multiple_unpicklings(self, ioclass): N = 5 f = ioclass(pickled * N) unpickler = self.unpickler_class(f) - for i in range(N): + for _ in range(N): if f.seekable(): pos = f.tell() self.assertEqual(unpickler.load(), data1) diff --git a/test/profilee.py b/test/profilee.py index 6ad2c839..4b46b76e 100644 --- a/test/profilee.py +++ b/test/profilee.py @@ -77,8 +77,7 @@ def helper1(): TICKS += 10 hasattr(C(), "foo") # 1 TICKS += 19 - lst = [] - lst.append(42) # 0 + lst = [42] sys.exc_info() # 0 def helper2_indirect(): @@ -100,7 +99,7 @@ def subhelper(): # 10 ticks total: 8 ticks local, 2 ticks in subfunctions global TICKS TICKS += 2 - for i in range(2): # 0 + for _ in range(2): try: C().foo # 1 x 2 except AttributeError: diff --git a/test/pydocfodder.py b/test/pydocfodder.py index 2530320a..56057db6 100644 --- a/test/pydocfodder.py +++ b/test/pydocfodder.py @@ -212,5 +212,7 @@ def __call__(self, inst): x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x') -submodule = types.ModuleType(__name__ + '.submodule', - """A submodule, which should appear in its parent's summary""") +submodule = types.ModuleType( + f'{__name__}.submodule', + """A submodule, which should appear in its parent's summary""", +) diff --git a/test/pythoninfo.py b/test/pythoninfo.py index 9242a36b..3a163527 100644 --- a/test/pythoninfo.py +++ b/test/pythoninfo.py @@ -118,14 +118,11 @@ def collect_sys(info_add): encoding = getattr(stream, 'encoding', None) if not encoding: continue - errors = getattr(stream, 'errors', None) - if errors: + if errors := getattr(stream, 'errors', None): encoding = '%s/%s' % (encoding, errors) info_add('sys.%s.encoding' % name, encoding) - # Were we compiled --with-pydebug or with #define Py_DEBUG? - Py_DEBUG = hasattr(sys, 'gettotalrefcount') - if Py_DEBUG: + if Py_DEBUG := hasattr(sys, 'gettotalrefcount'): text = 'Yes (sys.gettotalrefcount() present)' else: text = 'No (sys.gettotalrefcount() missing)' @@ -262,10 +259,7 @@ def collect_readline(info_add): return def format_attr(attr, value): - if isinstance(value, int): - return "%#x" % value - else: - return value + return "%#x" % value if isinstance(value, int) else value attributes = ( "_READLINE_VERSION", @@ -387,10 +381,7 @@ def collect_ssl(info_add): return def format_attr(attr, value): - if attr.startswith('OP_'): - return '%#8x' % value - else: - return value + return '%#8x' % value if attr.startswith('OP_') else value attributes = ( 'OPENSSL_VERSION', diff --git a/test/re_tests.py b/test/re_tests.py index a379d33a..0df9e301 100755 --- a/test/re_tests.py +++ b/test/re_tests.py @@ -34,73 +34,59 @@ ] -# Test suite (for verifying correctness) -# -# The test suite is a list of 5- or 3-tuples. The 5 parts of a -# complete tuple are: -# element 0: a string containing the pattern -# 1: the string to match against the pattern -# 2: the expected result (SUCCEED, FAIL, SYNTAX_ERROR) -# 3: a string that will be eval()'ed to produce a test string. -# This is an arbitrary Python expression; the available -# variables are "found" (the whole match), and "g1", "g2", ... -# up to "g99" contain the contents of each group, or the -# string 'None' if the group wasn't given a value, or the -# string 'Error' if the group index was out of range; -# also "groups", the return value of m.group() (a tuple). -# 4: The expected result of evaluating the expression. -# If the two don't match, an error is reported. -# -# If the regex isn't expected to work, the latter two elements can be omitted. - +u = '\N{LATIN CAPITAL LETTER A WITH DIAERESIS}' tests = [ - # Test ?P< and ?P= extensions - ('(?Pa)', '', SYNTAX_ERROR), # Begins with a digit - ('(?Pa)', '', SYNTAX_ERROR), # Begins with an illegal char - ('(?Pa)', '', SYNTAX_ERROR), # Begins with an illegal char - - # Same tests, for the ?P= form + ('(?Pa)', '', SYNTAX_ERROR), + ('(?Pa)', '', SYNTAX_ERROR), + ('(?Pa)', '', SYNTAX_ERROR), ('(?Pa)(?P=foo_123', 'aa', SYNTAX_ERROR), ('(?Pa)(?P=1)', 'aa', SYNTAX_ERROR), ('(?Pa)(?P=!)', 'aa', SYNTAX_ERROR), - ('(?Pa)(?P=foo_124', 'aa', SYNTAX_ERROR), # Backref to undefined group - + ('(?Pa)(?P=foo_124', 'aa', SYNTAX_ERROR), ('(?Pa)', 'a', SUCCEED, 'g1', 'a'), ('(?Pa)(?P=foo_123)', 'aa', SUCCEED, 'g1', 'a'), - - # Test octal escapes - ('\\1', 'a', SYNTAX_ERROR), # Backreference - ('[\\1]', '\1', SUCCEED, 'found', '\1'), # Character - ('\\09', chr(0) + '9', SUCCEED, 'found', chr(0) + '9'), + ('\\1', 'a', SYNTAX_ERROR), + ('[\\1]', '\1', SUCCEED, 'found', '\1'), + ('\\09', f'{chr(0)}9', SUCCEED, 'found', f'{chr(0)}9'), ('\\141', 'a', SUCCEED, 'found', 'a'), - ('(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', 'abcdefghijklk9', SUCCEED, 'found+"-"+g11', 'abcdefghijklk9-k'), - - # Test \0 is handled everywhere + ( + '(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', + 'abcdefghijklk9', + SUCCEED, + 'found+"-"+g11', + 'abcdefghijklk9-k', + ), (r'\0', '\0', SUCCEED, 'found', '\0'), (r'[\0a]', '\0', SUCCEED, 'found', '\0'), (r'[a\0]', '\0', SUCCEED, 'found', '\0'), (r'[^a\0]', '\0', FAIL), - - # Test various letter escapes - (r'\a[\b]\f\n\r\t\v', '\a\b\f\n\r\t\v', SUCCEED, 'found', '\a\b\f\n\r\t\v'), - (r'[\a][\b][\f][\n][\r][\t][\v]', '\a\b\f\n\r\t\v', SUCCEED, 'found', '\a\b\f\n\r\t\v'), - # NOTE: not an error under PCRE/PRE: - (r'\u', '', SYNTAX_ERROR), # A Perl escape - # (r'\c\e\g\h\i\j\k\m\o\p\q\y\z', 'ceghijkmopqyz', SUCCEED, 'found', 'ceghijkmopqyz'), + ( + r'\a[\b]\f\n\r\t\v', + '\a\b\f\n\r\t\v', + SUCCEED, + 'found', + '\a\b\f\n\r\t\v', + ), + ( + r'[\a][\b][\f][\n][\r][\t][\v]', + '\a\b\f\n\r\t\v', + SUCCEED, + 'found', + '\a\b\f\n\r\t\v', + ), + (r'\u', '', SYNTAX_ERROR), (r'\xff', '\377', SUCCEED, 'found', chr(255)), - # new \x semantics (r'\x00ffffffffffffff', '\377', FAIL, 'found', chr(255)), (r'\x00f', '\017', FAIL, 'found', chr(15)), (r'\x00fe', '\376', FAIL, 'found', chr(254)), - # (r'\x00ffffffffffffff', '\377', SUCCEED, 'found', chr(255)), - # (r'\x00f', '\017', SUCCEED, 'found', chr(15)), - # (r'\x00fe', '\376', SUCCEED, 'found', chr(254)), - - (r"^\w+=(\\[\000-\277]|[^\n\\])*", "SRC=eval.c g.c blah blah blah \\\\\n\tapes.c", - SUCCEED, 'found', "SRC=eval.c g.c blah blah blah \\\\"), - - # Test that . only matches \n in DOTALL mode + ( + r"^\w+=(\\[\000-\277]|[^\n\\])*", + "SRC=eval.c g.c blah blah blah \\\\\n\tapes.c", + SUCCEED, + 'found', + "SRC=eval.c g.c blah blah blah \\\\", + ), ('a.b', 'acb', SUCCEED, 'found', 'acb'), ('a.b', 'a\nb', FAIL), ('a.*b', 'acc\nccb', FAIL), @@ -110,9 +96,8 @@ ('(?s)a.*b', 'acc\nccb', SUCCEED, 'found', 'acc\nccb'), ('(?s)a.{4,5}b', 'acc\nccb', SUCCEED, 'found', 'acc\nccb'), ('(?s)a.b', 'a\nb', SUCCEED, 'found', 'a\nb'), - - (')', '', SYNTAX_ERROR), # Unmatched right bracket - ('', '', SUCCEED, 'found', ''), # Empty pattern + (')', '', SYNTAX_ERROR), + ('', '', SUCCEED, 'found', ''), ('abc', 'abc', SUCCEED, 'found', 'abc'), ('abc', 'xbc', FAIL), ('abc', 'axc', FAIL), @@ -149,8 +134,6 @@ ('a[b-d]', 'aac', SUCCEED, 'found', 'ac'), ('a[-b]', 'a-', SUCCEED, 'found', 'a-'), ('a[\\-b]', 'a-', SUCCEED, 'found', 'a-'), - # NOTE: not an error under PCRE/PRE: - # ('a[b-]', 'a-', SYNTAX_ERROR), ('a[]b', '-', SYNTAX_ERROR), ('a[', '-', SYNTAX_ERROR), ('a\\', '-', SYNTAX_ERROR), @@ -223,14 +206,38 @@ ('((a)(b)c)(d)', 'abcd', SUCCEED, 'g1+"-"+g2+"-"+g3+"-"+g4', 'abc-a-b-d'), ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', SUCCEED, 'found', 'alpha'), ('^a(bc+|b[eh])g|.h$', 'abh', SUCCEED, 'found+"-"+g1', 'bh-None'), - ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', SUCCEED, 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), - ('(bc+d$|ef*g.|h?i(j|k))', 'ij', SUCCEED, 'found+"-"+g1+"-"+g2', 'ij-ij-j'), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'effgz', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'effgz-effgz-None', + ), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'ij', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'ij-ij-j', + ), ('(bc+d$|ef*g.|h?i(j|k))', 'effg', FAIL), ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', FAIL), - ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', SUCCEED, 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'reffgz', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'effgz-effgz-None', + ), ('(((((((((a)))))))))', 'a', SUCCEED, 'found', 'a'), ('multiple words of text', 'uh-uh', FAIL), - ('multiple words', 'multiple words, yeah', SUCCEED, 'found', 'multiple words'), + ( + 'multiple words', + 'multiple words, yeah', + SUCCEED, + 'found', + 'multiple words', + ), ('(.*)c(.*)', 'abcde', SUCCEED, 'found+"-"+g1+"-"+g2', 'abcde-ab-de'), ('\\((.*), (.*)\\)', '(a, b)', SUCCEED, 'g2+"-"+g1', 'b-a'), ('[k]', 'ab', FAIL), @@ -254,31 +261,40 @@ ('(a)(b)c|ab', 'ab', SUCCEED, 'found+"-"+g1+"-"+g2', 'ab-None-None'), ('(a)+x', 'aaax', SUCCEED, 'found+"-"+g1', 'aaax-a'), ('([ac])+x', 'aacx', SUCCEED, 'found+"-"+g1', 'aacx-c'), - ('([^/]*/)*sub1/', 'd:msgs/tdir/sub1/trial/away.cpp', SUCCEED, 'found+"-"+g1', 'd:msgs/tdir/sub1/-tdir/'), - ('([^.]*)\\.([^:]*):[T ]+(.*)', 'track1.title:TBlah blah blah', SUCCEED, 'found+"-"+g1+"-"+g2+"-"+g3', 'track1.title:TBlah blah blah-track1-title-Blah blah blah'), + ( + '([^/]*/)*sub1/', + 'd:msgs/tdir/sub1/trial/away.cpp', + SUCCEED, + 'found+"-"+g1', + 'd:msgs/tdir/sub1/-tdir/', + ), + ( + '([^.]*)\\.([^:]*):[T ]+(.*)', + 'track1.title:TBlah blah blah', + SUCCEED, + 'found+"-"+g1+"-"+g2+"-"+g3', + 'track1.title:TBlah blah blah-track1-title-Blah blah blah', + ), ('([^N]*N)+', 'abNNxyzN', SUCCEED, 'found+"-"+g1', 'abNNxyzN-xyzN'), ('([^N]*N)+', 'abNNxyz', SUCCEED, 'found+"-"+g1', 'abNN-N'), ('([abc]*)x', 'abcx', SUCCEED, 'found+"-"+g1', 'abcx-abc'), ('([abc]*)x', 'abc', FAIL), ('([xyz]*)x', 'abcx', SUCCEED, 'found+"-"+g1', 'x-'), ('(a)+b|aac', 'aac', SUCCEED, 'found+"-"+g1', 'aac-None'), - - # Test symbolic groups - ('(?Paaa)a', 'aaaa', SYNTAX_ERROR), ('(?Paaa)a', 'aaaa', SUCCEED, 'found+"-"+id', 'aaaa-aaa'), ('(?Paa)(?P=id)', 'aaaa', SUCCEED, 'found+"-"+id', 'aaaa-aa'), ('(?Paa)(?P=xd)', 'aaaa', SYNTAX_ERROR), - - # Test octal escapes/memory references - ('\\1', 'a', SYNTAX_ERROR), - ('\\09', chr(0) + '9', SUCCEED, 'found', chr(0) + '9'), + ('\\09', f'{chr(0)}9', SUCCEED, 'found', f'{chr(0)}9'), ('\\141', 'a', SUCCEED, 'found', 'a'), - ('(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', 'abcdefghijklk9', SUCCEED, 'found+"-"+g11', 'abcdefghijklk9-k'), - - # All tests from Perl - + ( + '(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', + 'abcdefghijklk9', + SUCCEED, + 'found+"-"+g11', + 'abcdefghijklk9-k', + ), ('abc', 'abc', SUCCEED, 'found', 'abc'), ('abc', 'xbc', FAIL), ('abc', 'axc', FAIL), @@ -386,21 +402,42 @@ ('((a)(b)c)(d)', 'abcd', SUCCEED, 'g1+"-"+g2+"-"+g3+"-"+g4', 'abc-a-b-d'), ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', SUCCEED, 'found', 'alpha'), ('^a(bc+|b[eh])g|.h$', 'abh', SUCCEED, 'found+"-"+g1', 'bh-None'), - ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', SUCCEED, 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), - ('(bc+d$|ef*g.|h?i(j|k))', 'ij', SUCCEED, 'found+"-"+g1+"-"+g2', 'ij-ij-j'), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'effgz', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'effgz-effgz-None', + ), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'ij', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'ij-ij-j', + ), ('(bc+d$|ef*g.|h?i(j|k))', 'effg', FAIL), ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', FAIL), - ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', SUCCEED, 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), + ( + '(bc+d$|ef*g.|h?i(j|k))', + 'reffgz', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'effgz-effgz-None', + ), ('((((((((((a))))))))))', 'a', SUCCEED, 'g10', 'a'), ('((((((((((a))))))))))\\10', 'aa', SUCCEED, 'found', 'aa'), -# Python does not have the same rules for \\41 so this is a syntax error -# ('((((((((((a))))))))))\\41', 'aa', FAIL), -# ('((((((((((a))))))))))\\41', 'a!', SUCCEED, 'found', 'a!'), ('((((((((((a))))))))))\\41', '', SYNTAX_ERROR), ('(?i)((((((((((a))))))))))\\41', '', SYNTAX_ERROR), ('(((((((((a)))))))))', 'a', SUCCEED, 'found', 'a'), ('multiple words of text', 'uh-uh', FAIL), - ('multiple words', 'multiple words, yeah', SUCCEED, 'found', 'multiple words'), + ( + 'multiple words', + 'multiple words, yeah', + SUCCEED, + 'found', + 'multiple words', + ), ('(.*)c(.*)', 'abcde', SUCCEED, 'found+"-"+g1+"-"+g2', 'abcde-ab-de'), ('\\((.*), (.*)\\)', '(a, b)', SUCCEED, 'g2+"-"+g1', 'b-a'), ('[k]', 'ab', FAIL), @@ -514,28 +551,60 @@ ('(?i)a[bcd]*dcdcde', 'ADCDCDE', SUCCEED, 'found', 'ADCDCDE'), ('(?i)a[bcd]+dcdcde', 'ADCDCDE', FAIL), ('(?i)(ab|a)b*c', 'ABC', SUCCEED, 'found+"-"+g1', 'ABC-AB'), - ('(?i)((a)(b)c)(d)', 'ABCD', SUCCEED, 'g1+"-"+g2+"-"+g3+"-"+g4', 'ABC-A-B-D'), + ( + '(?i)((a)(b)c)(d)', + 'ABCD', + SUCCEED, + 'g1+"-"+g2+"-"+g3+"-"+g4', + 'ABC-A-B-D', + ), ('(?i)[a-zA-Z_][a-zA-Z0-9_]*', 'ALPHA', SUCCEED, 'found', 'ALPHA'), ('(?i)^a(bc+|b[eh])g|.h$', 'ABH', SUCCEED, 'found+"-"+g1', 'BH-None'), - ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFGZ', SUCCEED, 'found+"-"+g1+"-"+g2', 'EFFGZ-EFFGZ-None'), - ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'IJ', SUCCEED, 'found+"-"+g1+"-"+g2', 'IJ-IJ-J'), + ( + '(?i)(bc+d$|ef*g.|h?i(j|k))', + 'EFFGZ', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'EFFGZ-EFFGZ-None', + ), + ( + '(?i)(bc+d$|ef*g.|h?i(j|k))', + 'IJ', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'IJ-IJ-J', + ), ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFG', FAIL), ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'BCDD', FAIL), - ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'REFFGZ', SUCCEED, 'found+"-"+g1+"-"+g2', 'EFFGZ-EFFGZ-None'), + ( + '(?i)(bc+d$|ef*g.|h?i(j|k))', + 'REFFGZ', + SUCCEED, + 'found+"-"+g1+"-"+g2', + 'EFFGZ-EFFGZ-None', + ), ('(?i)((((((((((a))))))))))', 'A', SUCCEED, 'g10', 'A'), ('(?i)((((((((((a))))))))))\\10', 'AA', SUCCEED, 'found', 'AA'), - #('(?i)((((((((((a))))))))))\\41', 'AA', FAIL), - #('(?i)((((((((((a))))))))))\\41', 'A!', SUCCEED, 'found', 'A!'), ('(?i)(((((((((a)))))))))', 'A', SUCCEED, 'found', 'A'), ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a))))))))))', 'A', SUCCEED, 'g1', 'A'), - ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a|b|c))))))))))', 'C', SUCCEED, 'g1', 'C'), + ( + '(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a|b|c))))))))))', + 'C', + SUCCEED, + 'g1', + 'C', + ), ('(?i)multiple words of text', 'UH-UH', FAIL), - ('(?i)multiple words', 'MULTIPLE WORDS, YEAH', SUCCEED, 'found', 'MULTIPLE WORDS'), + ( + '(?i)multiple words', + 'MULTIPLE WORDS, YEAH', + SUCCEED, + 'found', + 'MULTIPLE WORDS', + ), ('(?i)(.*)c(.*)', 'ABCDE', SUCCEED, 'found+"-"+g1+"-"+g2', 'ABCDE-AB-DE'), ('(?i)\\((.*), (.*)\\)', '(A, B)', SUCCEED, 'g2+"-"+g1', 'B-A'), ('(?i)[k]', 'AB', FAIL), -# ('(?i)abcd', 'ABCD', SUCCEED, 'found+"-"+\\found+"-"+\\\\found', 'ABCD-$&-\\ABCD'), -# ('(?i)a(bc)d', 'ABCD', SUCCEED, 'g1+"-"+\\g1+"-"+\\\\g1', 'BC-$1-\\BC'), ('(?i)a[-]?c', 'AC', SUCCEED, 'found', 'AC'), ('(?i)(abc)\\1', 'ABCABC', SUCCEED, 'g1', 'ABC'), ('(?i)([a-c]*)\\1', 'ABCABC', SUCCEED, 'g1', 'ABC'), @@ -547,124 +616,106 @@ ('a(?:b|c|d)+?(.)', 'ace', SUCCEED, 'g1', 'e'), ('a(?:b|(c|e){1,2}?|d)+?(.)', 'ace', SUCCEED, 'g1 + g2', 'ce'), ('^(.+)?B', 'AB', SUCCEED, 'g1', 'A'), - - # lookbehind: split by : but not if it is escaped by -. - ('(?]*?b', 'a>b', FAIL), - # bug 490573: minimizing repeat problem (r'^a*?$', 'foo', FAIL), - # bug 470582: nested groups problem (r'^((a)c)?(ab)$', 'ab', SUCCEED, 'g1+"-"+g2+"-"+g3', 'None-None-ab'), - # another minimizing repeat problem (capturing groups in assertions) ('^([ab]*?)(?=(b)?)c', 'abc', SUCCEED, 'g1+"-"+g2', 'ab-None'), ('^([ab]*?)(?!(b))c', 'abc', SUCCEED, 'g1+"-"+g2', 'ab-None'), ('^([ab]*?)(?= 10: - L[-10:] = [random.random() for dummy in range(10)] + L[-10:] = [random.random() for _ in range(10)] doit(L) # +sort # Replace 1% of the elements at random. - for dummy in range(n // 100): + for _ in range(n // 100): L[random.randrange(n)] = random.random() doit(L) # %sort diff --git a/test/string_tests.py b/test/string_tests.py index 561b09a2..3d82b3b0 100644 --- a/test/string_tests.py +++ b/test/string_tests.py @@ -42,7 +42,7 @@ def fixtype(self, obj): elif isinstance(obj, list): return [self.fixtype(x) for x in obj] elif isinstance(obj, tuple): - return tuple([self.fixtype(x) for x in obj]) + return tuple(self.fixtype(x) for x in obj) elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) @@ -138,7 +138,7 @@ def test_count(self): teststrings = set() for i in range(base ** digits): entry = [] - for j in range(digits): + for _ in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) @@ -199,7 +199,7 @@ def test_find(self): teststrings = set() for i in range(base ** digits): entry = [] - for j in range(digits): + for _ in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) @@ -246,7 +246,7 @@ def test_rfind(self): teststrings = set() for i in range(base ** digits): entry = [] - for j in range(digits): + for _ in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) @@ -1263,7 +1263,7 @@ def test_floatformatting(self): for prec in range(100): format = '%%.%if' % prec value = 0.01 - for x in range(60): + for _ in range(60): value = value * 3.14159265359 / 3.0 * 10.0 self.checkcall(format, "__mod__", value) diff --git a/test/test__locale.py b/test/test__locale.py index ab4e2479..801479eb 100644 --- a/test/test__locale.py +++ b/test/test__locale.py @@ -57,7 +57,7 @@ def setUpModule(): if "MSC v.1200" in sys.version: def accept(loc): a = loc.split(".") - return not(len(a) == 2 and len(a[-1]) >= 9) + return len(a) != 2 or len(a[-1]) < 9 candidate_locales = [loc for loc in candidate_locales if accept(loc)] # List known locale values to test against when available. @@ -145,6 +145,7 @@ def test_lc_numeric_basic(self): setlocale(LC_CTYPE, loc) except Error: continue + tested = True for li, lc in ((RADIXCHAR, "decimal_point"), (THOUSEP, "thousands_sep")): nl_radixchar = nl_langinfo(li) @@ -158,7 +159,6 @@ def test_lc_numeric_basic(self): "(set to %s, using %s)" % ( nl_radixchar, li_radixchar, loc, set_locale)) - tested = True if not tested: self.skipTest('no suitable locales') diff --git a/test/test__osx_support.py b/test/test__osx_support.py index bcba8caa..32b14cad 100644 --- a/test/test__osx_support.py +++ b/test/test__osx_support.py @@ -31,9 +31,11 @@ def setUp(self): def add_expected_saved_initial_values(self, config_vars, expected_vars): # Ensure that the initial values for all modified config vars # are also saved with modified keys. - expected_vars.update(('_OSX_SUPPORT_INITIAL_'+ k, - config_vars[k]) for k in config_vars - if config_vars[k] != expected_vars[k]) + expected_vars.update( + (f'_OSX_SUPPORT_INITIAL_{k}', config_vars[k]) + for k in config_vars + if config_vars[k] != expected_vars[k] + ) def test__find_executable(self): if self.env['PATH']: @@ -108,8 +110,7 @@ def test__save_modified_value_unchanged(self): def test__supports_universal_builds(self): import platform - mac_ver_tuple = tuple(int(i) for i in - platform.mac_ver()[0].split('.')[0:2]) + mac_ver_tuple = tuple(int(i) for i in platform.mac_ver()[0].split('.')[:2]) self.assertEqual(mac_ver_tuple >= (10, 4), _osx_support._supports_universal_builds()) diff --git a/test/test_aifc.py b/test/test_aifc.py index ff52f5b6..c93e7e6d 100644 --- a/test/test_aifc.py +++ b/test/test_aifc.py @@ -222,9 +222,9 @@ class AIFCLowLevelTest(unittest.TestCase): def test_read_written(self): def read_written(self, what): f = io.BytesIO() - getattr(aifc, '_write_' + what)(f, x) + getattr(aifc, f'_write_{what}')(f, x) f.seek(0) - return getattr(aifc, '_read_' + what)(f) + return getattr(aifc, f'_read_{what}')(f) for x in (-1, 0, 0.1, 1): self.assertEqual(read_written(x, 'float'), x) for x in (float('NaN'), float('Inf')): @@ -419,7 +419,7 @@ def test_write_markers_raises(self): def test_write_aiff_by_extension(self): sampwidth = 2 - filename = TESTFN + '.aiff' + filename = f'{TESTFN}.aiff' fout = self.fout = aifc.open(filename, 'wb') self.addCleanup(unlink, filename) fout.setparams((1, sampwidth, 1, 1, b'ULAW', b'')) diff --git a/test/test_array.py b/test/test_array.py index e9218f3d..aa178aad 100644 --- a/test/test_array.py +++ b/test/test_array.py @@ -214,10 +214,7 @@ def test_buffer_info(self): self.assertEqual(bi[1], len(a)) def test_byteswap(self): - if self.typecode == 'u': - example = '\U00100100' - else: - example = self.example + example = '\U00100100' if self.typecode == 'u' else self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): @@ -303,7 +300,7 @@ def test_iterator_pickle(self): self.assertEqual(list(it), data[1:] + data2) # empty iterator - for i in range(1, len(data)): + for _ in range(1, len(data)): next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) @@ -372,14 +369,13 @@ def test_tofromfile(self): a.tofile(f) f.close() b = array.array(self.typecode) - f = open(support.TESTFN, 'rb') - self.assertRaises(TypeError, b.fromfile) - b.fromfile(f, len(self.example)) - self.assertEqual(b, array.array(self.typecode, self.example)) - self.assertNotEqual(a, b) - self.assertRaises(EOFError, b.fromfile, f, len(self.example)+1) - self.assertEqual(a, b) - f.close() + with open(support.TESTFN, 'rb') as f: + self.assertRaises(TypeError, b.fromfile) + b.fromfile(f, len(self.example)) + self.assertEqual(b, array.array(self.typecode, self.example)) + self.assertNotEqual(a, b) + self.assertRaises(EOFError, b.fromfile, f, len(self.example)+1) + self.assertEqual(a, b) finally: if not f.closed: f.close() @@ -403,13 +399,12 @@ def test_filewrite(self): f.write(a) f.close() b = array.array(self.typecode) - f = open(support.TESTFN, 'rb') - b.fromfile(f, len(self.example)) - self.assertEqual(b, array.array(self.typecode, self.example)) - self.assertNotEqual(a, b) - b.fromfile(f, len(self.example)) - self.assertEqual(a, b) - f.close() + with open(support.TESTFN, 'rb') as f: + b.fromfile(f, len(self.example)) + self.assertEqual(b, array.array(self.typecode, self.example)) + self.assertNotEqual(a, b) + b.fromfile(f, len(self.example)) + self.assertEqual(a, b) finally: if not f.closed: f.close() @@ -973,7 +968,6 @@ def __iter__(self): # pass through errors raised in next() def B(): raise UnicodeError - yield None self.assertRaises(UnicodeError, array.array, self.typecode, B()) def test_coveritertraverse(self): @@ -997,7 +991,7 @@ def test_buffer(self): # the array was not modified. self.assertRaises(BufferError, a.append, a[0]) self.assertEqual(m.tobytes(), expected) - self.assertRaises(BufferError, a.extend, a[0:1]) + self.assertRaises(BufferError, a.extend, a[:1]) self.assertEqual(m.tobytes(), expected) self.assertRaises(BufferError, a.remove, a[0]) self.assertEqual(m.tobytes(), expected) @@ -1031,10 +1025,10 @@ def test_weakref(self): @unittest.skipUnless(hasattr(sys, 'getrefcount'), 'test needs sys.getrefcount()') def test_bug_782369(self): - for i in range(10): + for _ in range(10): b = array.array('B', range(64)) rc = sys.getrefcount(10) - for i in range(10): + for _ in range(10): b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) diff --git a/test/test_ast.py b/test/test_ast.py index 7db40e77..347188b8 100644 --- a/test/test_ast.py +++ b/test/test_ast.py @@ -17,8 +17,7 @@ def to_tuple(t): result.append((t.lineno, t.col_offset)) if t._fields is None: return tuple(result) - for f in t._fields: - result.append(to_tuple(getattr(t, f))) + result.extend(to_tuple(getattr(t, f)) for f in t._fields) return tuple(result) @@ -1039,7 +1038,7 @@ def test_singletons(self): def test_values(self): nested_tuple = (1,) nested_frozenset = frozenset({1}) - for level in range(3): + for _ in range(3): nested_tuple = (nested_tuple, 2) nested_frozenset = frozenset({nested_frozenset, 2}) values = (123, 123.0, 123j, @@ -1073,11 +1072,11 @@ def get_load_const(self, tree): # Compile to bytecode, disassemble and get parameter of LOAD_CONST # instructions co = compile(tree, '', 'exec') - consts = [] - for instr in dis.get_instructions(co): - if instr.opname == 'LOAD_CONST': - consts.append(instr.argval) - return consts + return [ + instr.argval + for instr in dis.get_instructions(co) + if instr.opname == 'LOAD_CONST' + ] @support.cpython_only def test_load_const(self): @@ -1129,7 +1128,7 @@ def main(): if sys.argv[1:] == ['-g']: for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), (eval_tests, "eval")): - print(kind+"_results = [") + print(f'{kind}_results = [') for statement in statements: tree = ast.parse(statement, "?", kind) print("%r," % (to_tuple(tree),)) diff --git a/test/test_asyncgen.py b/test/test_asyncgen.py index 2383ee17..c9edb0a2 100644 --- a/test/test_asyncgen.py +++ b/test/test_asyncgen.py @@ -343,7 +343,6 @@ async def gen(): yield 2 await asyncio.sleep(0.01, loop=self.loop) return - yield 3 res = self.loop.run_until_complete(self.to_list(gen())) self.assertEqual(res, [1, 2]) diff --git a/test/test_asynchat.py b/test/test_asynchat.py index 1d147c74..853ab1dd 100644 --- a/test/test_asynchat.py +++ b/test/test_asynchat.py @@ -42,7 +42,7 @@ def run(self): data = conn.recv(1) if not data: break - self.buffer = self.buffer + data + self.buffer += data # remove the SERVER_QUIT message self.buffer = self.buffer.replace(SERVER_QUIT, b'') diff --git a/test/test_atexit.py b/test/test_atexit.py index 3105f6c3..e4a78e5c 100644 --- a/test/test_atexit.py +++ b/test/test_atexit.py @@ -54,7 +54,7 @@ def test_args(self): "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n") def test_badargs(self): - atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0) + atexit.register(lambda: 1, 0, 0, iter((1,2)), 0, 0) self.assertRaises(TypeError, atexit._run_exitfuncs) def test_order(self): diff --git a/test/test_augassign.py b/test/test_augassign.py index 5930d9e7..51d1bbb2 100644 --- a/test/test_augassign.py +++ b/test/test_augassign.py @@ -5,8 +5,7 @@ class AugAssignTest(unittest.TestCase): def testBasic(self): - x = 2 - x += 1 + x = 2 + 1 x *= 2 x **= 2 x -= 8 diff --git a/test/test_baseexception.py b/test/test_baseexception.py index c3246826..5600d58a 100644 --- a/test/test_baseexception.py +++ b/test/test_baseexception.py @@ -108,9 +108,13 @@ def test_interface_multi_arg(self): def test_interface_no_arg(self): # Make sure that with no args that interface is correct exc = Exception() - results = ([len(exc.args), 0], [exc.args, tuple()], - [str(exc), ''], - [repr(exc), exc.__class__.__name__ + '()']) + results = ( + [len(exc.args), 0], + [exc.args, tuple()], + [str(exc), ''], + [repr(exc), f'{exc.__class__.__name__}()'], + ) + self.interface_test_driver(results) class UsageTests(unittest.TestCase): diff --git a/test/test_bigmem.py b/test/test_bigmem.py index 6133bbca..20ce47a1 100644 --- a/test/test_bigmem.py +++ b/test/test_bigmem.py @@ -516,7 +516,7 @@ def test_slice_and_getitem(self, size): self.assertEqual(s[len(s) - 10], SUBSTR[0]) self.assertEqual(s[-sublen], SUBSTR[0]) self.assertEqual(s[len(s):], _('')) - self.assertEqual(s[len(s) - 1:], SUBSTR[-1:]) + self.assertEqual(s[-1:], SUBSTR[-1:]) self.assertEqual(s[-1:], SUBSTR[-1:]) self.assertEqual(s[len(s) - sublen:], SUBSTR) self.assertEqual(s[-sublen:], SUBSTR) diff --git a/test/test_binhex.py b/test/test_binhex.py index 21f44632..4abea850 100644 --- a/test/test_binhex.py +++ b/test/test_binhex.py @@ -11,8 +11,8 @@ class BinHexTestCase(unittest.TestCase): def setUp(self): - self.fname1 = support.TESTFN + "1" - self.fname2 = support.TESTFN + "2" + self.fname1 = f'{support.TESTFN}1' + self.fname2 = f'{support.TESTFN}2' self.fname3 = support.TESTFN + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__" def tearDown(self): @@ -23,18 +23,14 @@ def tearDown(self): DATA = b'Jack is my hero' def test_binhex(self): - f = open(self.fname1, 'wb') - f.write(self.DATA) - f.close() - + with open(self.fname1, 'wb') as f: + f.write(self.DATA) binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) - f = open(self.fname1, 'rb') - finish = f.readline() - f.close() - + with open(self.fname1, 'rb') as f: + finish = f.readline() self.assertEqual(self.DATA, finish) def test_binhex_error_on_long_filename(self): diff --git a/test/test_binop.py b/test/test_binop.py index 299af09c..4761b94b 100644 --- a/test/test_binop.py +++ b/test/test_binop.py @@ -16,10 +16,7 @@ def isint(x): def isnum(x): """Test whether an object is an instance of a built-in numeric type.""" - for T in int, float, complex: - if isinstance(x, T): - return 1 - return 0 + return next((1 for T in (int, float, complex) if isinstance(x, T)), 0) def isRat(x): """Test whether an object is an instance of the Rat class.""" @@ -311,10 +308,7 @@ def op_sequence(op, *classes): """Return the sequence of operations that results from applying the operation `op` to instances of the given classes.""" log = [] - instances = [] - for c in classes: - instances.append(c(log.append)) - + instances = [c(log.append) for c in classes] try: op(*instances) except TypeError: diff --git a/test/test_bisect.py b/test/test_bisect.py index 580a963f..442d3c81 100644 --- a/test/test_bisect.py +++ b/test/test_bisect.py @@ -154,7 +154,7 @@ def test_large_pyrange(self): def test_random(self, n=25): from random import randrange for i in range(n): - data = [randrange(0, n, 2) for j in range(i)] + data = [randrange(0, n, 2) for _ in range(i)] data.sort() elem = randrange(-1, n+1) ip = self.module.bisect_left(data, elem) @@ -211,12 +211,9 @@ class TestInsort: def test_vsBuiltinSort(self, n=500): from random import choice for insorted in (list(), UserList()): - for i in range(n): + for _ in range(n): digit = choice("0123456789") - if digit in "02468": - f = self.module.insort_left - else: - f = self.module.insort_right + f = self.module.insort_left if digit in "02468" else self.module.insort_right f(insorted, digit) self.assertEqual(sorted(insorted), insorted) diff --git a/test/test_bool.py b/test/test_bool.py index c5a1f1f2..8436c647 100644 --- a/test/test_bool.py +++ b/test/test_bool.py @@ -20,9 +20,8 @@ class C(bool): def test_print(self): try: - fo = open(support.TESTFN, "w") - print(False, True, file=fo) - fo.close() + with open(support.TESTFN, "w") as fo: + print(False, True, file=fo) fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), 'False True\n') finally: @@ -126,7 +125,7 @@ def test_math(self): self.assertEqual(int(a)^b, int(a)^int(b)) self.assertIsNot(int(a)^b, bool(int(a)^int(b))) - self.assertIs(1==1, True) + self.assertIs(True, True) self.assertIs(1==0, False) self.assertIs(0<1, True) self.assertIs(1<0, False) @@ -137,7 +136,7 @@ def test_math(self): self.assertIs(1>=1, True) self.assertIs(0>=1, False) self.assertIs(0!=1, True) - self.assertIs(0!=0, False) + self.assertIs(False, False) x = [1] self.assertIs(x is x, True) @@ -245,9 +244,8 @@ def test_boolean(self): def test_fileclosed(self): try: - f = open(support.TESTFN, "w") - self.assertIs(f.closed, False) - f.close() + with open(support.TESTFN, "w") as f: + self.assertIs(f.closed, False) self.assertIs(f.closed, True) finally: os.remove(support.TESTFN) diff --git a/test/test_buffer.py b/test/test_buffer.py index f302da41..abb0b391 100644 --- a/test/test_buffer.py +++ b/test/test_buffer.py @@ -87,13 +87,13 @@ def native_type_range(fmt): """Return range of a native type.""" if fmt == 'c': - lh = (0, 256) + return 0, 256 elif fmt == '?': - lh = (0, 2) + return 0, 2 elif fmt == 'f': - lh = (-(1<<63), 1<<63) + return -(1<<63), 1<<63 elif fmt == 'd': - lh = (-(1<<1023), 1<<1023) + return -(1<<1023), 1<<1023 else: for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7): try: @@ -101,8 +101,7 @@ def native_type_range(fmt): break except struct.error: pass - lh = (-(1<= 95 and n & 1 else False + zero_stride = bool(n >= 95 and n & 1) strides = [0] * ndim strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1) @@ -517,7 +507,7 @@ def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): strides[ndim-1] = itemsize for i in range(ndim-2, -1, -1): - maxstride *= shape[i+1] if shape[i+1] else 1 + maxstride *= shape[i+1] or 1 if zero_stride: strides[i] = itemsize * randrange(-maxstride, maxstride+1) else: @@ -525,7 +515,7 @@ def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): itemsize * randrange(1, maxstride+1)) imin = imax = 0 - if not 0 in shape: + if 0 not in shape: imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) @@ -576,9 +566,11 @@ def rand_aligned_slices(maxdim=5, maxshape=16): minshape = 0 elif n >= 90: minshape = 1 - all_random = True if randrange(100) >= 80 else False - lshape = [0]*ndim; rshape = [0]*ndim - lslices = [0]*ndim; rslices = [0]*ndim + all_random = randrange(100) >= 80 + lshape = [0]*ndim + rshape = [0]*ndim + lslices = [0]*ndim + rslices = [0]*ndim for n in range(ndim): small = randrange(minshape, maxshape+1) @@ -612,7 +604,7 @@ def randitems_from_structure(fmt, t): """Return a list of random items for structure 't' with format 'fmtchar'.""" memlen, itemsize, _, _, _, _ = t - return gen_items(memlen//itemsize, '#'+fmt, 'numpy') + return gen_items(memlen//itemsize, f'#{fmt}', 'numpy') def ndarray_from_structure(items, fmt, t, flags=0): """Return ndarray from the tuple returned by rand_structure()""" diff --git a/test/test_builtin.py b/test/test_builtin.py index 8f91bc9b..5bc821c2 100644 --- a/test/test_builtin.py +++ b/test/test_builtin.py @@ -41,7 +41,7 @@ def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: - self.sofar.append(n*n) + self.sofar.append(n**2) n += 1 return self.sofar[i] @@ -59,7 +59,7 @@ def __getitem__(self, i): raise IndexError n = len(self.sofar) while n <= i: - self.sofar.append(str(n*n)) + self.sofar.append(str(n**2)) n += 1 return self.sofar[i] @@ -510,9 +510,7 @@ class A: # Verify that dict subclasses work as well class D(dict): def __getitem__(self, key): - if key == 'a': - return 12 - return dict.__getitem__(self, key) + return 12 if key == 'a' else dict.__getitem__(self, key) def keys(self): return list('xyz') @@ -813,9 +811,7 @@ def sqrt(x): ) def plus(*v): - accu = 0 - for i in v: accu = accu + i - return accu + return sum(v) self.assertEqual( list(map(plus, [1, 3, 7])), [1, 3, 7] @@ -847,7 +843,6 @@ def Max(a, b): class BadSeq: def __iter__(self): raise ValueError - yield None self.assertRaises(ValueError, list, map(lambda x: x, BadSeq())) def badfunc(x): raise RuntimeError diff --git a/test/test_bytes.py b/test/test_bytes.py index 1408fb4f..ba05ce16 100644 --- a/test/test_bytes.py +++ b/test/test_bytes.py @@ -71,7 +71,7 @@ def test_empty_sequence(self): def test_from_list(self): ints = list(range(256)) - b = self.type2test(i for i in ints) + b = self.type2test(iter(ints)) self.assertEqual(len(b), 256) self.assertEqual(list(b), ints) @@ -256,8 +256,8 @@ def test_concat(self): self.assertEqual(b1 + b2, b"abcdef") self.assertEqual(b1 + bytes(b"def"), b"abcdef") self.assertEqual(bytes(b"def") + b1, b"defabc") - self.assertRaises(TypeError, lambda: b1 + "def") - self.assertRaises(TypeError, lambda: "abc" + b2) + self.assertRaises(TypeError, lambda: f'{b1}def') + self.assertRaises(TypeError, lambda: f'abc{b2}') def test_repeat(self): for b in b"abc", self.type2test(b"abc"): @@ -1224,7 +1224,7 @@ def test_alloc(self): alloc = b.__alloc__() self.assertGreaterEqual(alloc, 0) seq = [alloc] - for i in range(100): + for _ in range(100): b += b"x" alloc = b.__alloc__() self.assertGreater(alloc, len(b)) # including trailing null byte @@ -1344,7 +1344,7 @@ def test_copied(self): b = bytearray(b'abc') self.assertIsNot(b, b.replace(b'abc', b'cde', 0)) - t = bytearray([i for i in range(256)]) + t = bytearray(list(range(256))) x = bytearray(b'') self.assertIsNot(x, x.translate(t)) @@ -1427,7 +1427,7 @@ def test_iterator_pickling2(self): self.assertEqual(list(it), data[1:]) # empty iterator - for i in range(1, len(orig)): + for _ in range(1, len(orig)): next(itorig) d = pickle.dumps((itorig, orig), proto) it, b = pickle.loads(d) @@ -1480,15 +1480,15 @@ def test_format(self): format(b, 's') def test_compare_bytes_to_bytearray(self): - self.assertEqual(b"abc" == bytes(b"abc"), True) - self.assertEqual(b"ab" != bytes(b"abc"), True) + self.assertEqual(bytes(b"abc") == b"abc", True) + self.assertEqual(bytes(b"abc") != b"ab", True) self.assertEqual(b"ab" <= bytes(b"abc"), True) self.assertEqual(b"ab" < bytes(b"abc"), True) self.assertEqual(b"abc" >= bytes(b"ab"), True) self.assertEqual(b"abc" > bytes(b"ab"), True) - self.assertEqual(b"abc" != bytes(b"abc"), False) - self.assertEqual(b"ab" == bytes(b"abc"), False) + self.assertEqual(bytes(b"abc") != b"abc", False) + self.assertEqual(bytes(b"abc") == b"ab", False) self.assertEqual(b"ab" > bytes(b"abc"), False) self.assertEqual(b"ab" >= bytes(b"abc"), False) self.assertEqual(b"abc" < bytes(b"ab"), False) @@ -1611,15 +1611,13 @@ def test_returns_new_copy(self): method = getattr(val, methname) newval = method(3) self.assertEqual(val, newval) - self.assertIsNot(val, newval, - methname+' returned self on a mutable object') + self.assertIsNot(val, newval, f'{methname} returned self on a mutable object') for expr in ('val.split()[0]', 'val.rsplit()[0]', 'val.partition(b".")[0]', 'val.rpartition(b".")[2]', 'val.splitlines()[0]', 'val.replace(b"", b"")'): newval = eval(expr) self.assertEqual(val, newval) - self.assertIsNot(val, newval, - expr+' returned val on a mutable object') + self.assertIsNot(val, newval, f'{expr} returned val on a mutable object') sep = self.marshal(b'') newval = sep.join([val]) self.assertEqual(val, newval) diff --git a/test/test_calendar.py b/test/test_calendar.py index 6241d114..aeef0316 100644 --- a/test/test_calendar.py +++ b/test/test_calendar.py @@ -518,7 +518,7 @@ def test_illegal_weekday_reported(self): def test_enumerate_weekdays(self): self.assertRaises(IndexError, calendar.day_abbr.__getitem__, -10) self.assertRaises(IndexError, calendar.day_name.__getitem__, 10) - self.assertEqual(len([d for d in calendar.day_abbr]), 7) + self.assertEqual(len(list(calendar.day_abbr)), 7) def test_days(self): for attr in "day_name", "day_abbr": @@ -922,9 +922,12 @@ class TestSubClassingCase(unittest.TestCase): def setUp(self): + + + class CustomHTMLCal(calendar.HTMLCalendar): - cssclasses = [style + " text-nowrap" for style in - calendar.HTMLCalendar.cssclasses] + cssclasses = [f'{style} text-nowrap' for style in + calendar.HTMLCalendar.cssclasses] cssclasses_weekday_head = ["red", "blue", "green", "lilac", "yellow", "orange", "pink"] cssclass_month_head = "text-center month-head" @@ -932,6 +935,7 @@ class CustomHTMLCal(calendar.HTMLCalendar): cssclass_year = "text-italic " cssclass_year_head = "lead " + self.cal = CustomHTMLCal() def test_formatmonthname(self): diff --git a/test/test_capi.py b/test/test_capi.py index c7be3fea..dd1b6dc8 100644 --- a/test/test_capi.py +++ b/test/test_capi.py @@ -338,11 +338,6 @@ def pendingcalls_wait(self, l, n, context = None): #now, stick around until l[0] has grown to 10 count = 0; while len(l) != n: - #this busy loop is where we expect to be interrupted to - #run our callbacks. Note that callbacks are only run on the - #main thread - if False and support.verbose: - print("(%i)"%(len(l),),) for i in range(1000): a = i*i if context and not context.event.is_set(): @@ -350,8 +345,6 @@ def pendingcalls_wait(self, l, n, context = None): count += 1 self.assertTrue(count < 10000, "timeout waiting for %i callbacks, got %i"%(n, len(l))) - if False and support.verbose: - print("(%i)"%(len(l),)) def test_pendingcalls_threaded(self): @@ -368,8 +361,7 @@ class foo(object):pass context.event = threading.Event() threads = [threading.Thread(target=self.pendingcalls_thread, - args=(context,)) - for i in range(context.nThreads)] + args=(context,)) for _ in range(context.nThreads)] with support.start_threads(threads): self.pendingcalls_wait(context.l, n, context) @@ -380,8 +372,6 @@ def pendingcalls_thread(self, context): with context.lock: context.nFinished += 1 nFinished = context.nFinished - if False and support.verbose: - print("finished threads: ", nFinished) if nFinished == context.nThreads: context.event.set() @@ -463,7 +453,7 @@ def test_skipitem(self): continue # test the format unit when not skipped - format = c + "i" + format = f'{c}i' try: _testcapi.parse_tuple_and_keywords(tuple_1, dict_b, format, keywords) @@ -475,7 +465,7 @@ def test_skipitem(self): when_not_skipped = False # test the format unit when skipped - optional_format = "|" + format + optional_format = f'|{format}' try: _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b, optional_format, keywords) diff --git a/test/test_cgi.py b/test/test_cgi.py index 4f2bba14..798ce14e 100644 --- a/test/test_cgi.py +++ b/test/test_cgi.py @@ -113,11 +113,10 @@ def gen_result(data, environ): fake_stdin.seek(0) form = cgi.FieldStorage(fp=fake_stdin, environ=environ, encoding=encoding) - result = {} - for k, v in dict(form).items(): - result[k] = isinstance(v, list) and form.getlist(k) or v.value - - return result + return { + k: isinstance(v, list) and form.getlist(k) or v.value + for k, v in dict(form).items() + } class CgiTests(unittest.TestCase): @@ -224,10 +223,7 @@ def __init__(self, file): def readline(self, size=None): self.numcalls += 1 - if size: - return self.file.readline(size) - else: - return self.file.readline() + return self.file.readline(size) if size else self.file.readline() def __getattr__(self, name): file = self.__dict__['file'] diff --git a/test/test_class.py b/test/test_class.py index aca61871..7e915b73 100644 --- a/test/test_class.py +++ b/test/test_class.py @@ -399,19 +399,19 @@ def testMisc(self): self.assertCallStack([('__ne__', (testme, 1))]) callLst[:] = [] - 1 == testme + testme == 1 self.assertCallStack([('__eq__', (1, testme))]) callLst[:] = [] - 1 < testme + testme > 1 self.assertCallStack([('__gt__', (1, testme))]) callLst[:] = [] - 1 > testme + testme < 1 self.assertCallStack([('__lt__', (1, testme))]) callLst[:] = [] - 1 != testme + testme != 1 self.assertCallStack([('__ne__', (1, testme))]) diff --git a/test/test_cmath.py b/test/test_cmath.py index 0451fb0a..b8e1f7d6 100644 --- a/test/test_cmath.py +++ b/test/test_cmath.py @@ -125,10 +125,9 @@ def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323, # (in theory there are examples where it would be legitimate for a # and b to have opposite signs; in practice these hardly ever # occur). - if not a and not b: - if math.copysign(1., a) != math.copysign(1., b): - self.fail(msg or 'zero has wrong sign: expected {!r}, ' - 'got {!r}'.format(a, b)) + if not a and not b and math.copysign(1.0, a) != math.copysign(1.0, b): + self.fail(msg or 'zero has wrong sign: expected {!r}, ' + 'got {!r}'.format(a, b)) # if a-b overflows, or b is infinite, return False. Again, in # theory there are examples where a is within a few ulps of the diff --git a/test/test_code.py b/test/test_code.py index f4e9432d..56d52b17 100644 --- a/test/test_code.py +++ b/test/test_code.py @@ -128,7 +128,7 @@ def dump(co): """Print out a text representation of a code object.""" for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames", "cellvars", "freevars", "nlocals", "flags"]: - print("%s: %s" % (attr, getattr(co, "co_" + attr))) + print("%s: %s" % (attr, getattr(co, f'co_{attr}'))) print("consts:", tuple(consts(co.co_consts))) # Needed for test_closure_injection below @@ -190,7 +190,7 @@ class List(list): self.assertEqual(obj[0], "Foreign getitem: 1") def isinterned(s): - return s is sys.intern(('_' + s + '_')[1:-1]) + return s is sys.intern(f'_{s}_'[1:-1]) class CodeConstsTest(unittest.TestCase): diff --git a/test/test_codeccallbacks.py b/test/test_codeccallbacks.py index e2e74633..376de8ab 100644 --- a/test/test_codeccallbacks.py +++ b/test/test_codeccallbacks.py @@ -118,9 +118,11 @@ def test_uninamereplace(self): def uninamereplace(exc): if not isinstance(exc, UnicodeEncodeError): raise TypeError("don't know how to handle %r" % exc) - l = [] - for c in exc.object[exc.start:exc.end]: - l.append(unicodedata.name(c, "0x%x" % ord(c))) + l = [ + unicodedata.name(c, "0x%x" % ord(c)) + for c in exc.object[exc.start : exc.end] + ] + return ("\033[1m%s\033[0m" % ", ".join(l), exc.end) codecs.register_error( @@ -195,7 +197,7 @@ def test_charmapencode(self): # mapped through the encoding again. This means, that # to be able to use e.g. the "replace" handler, the # charmap has to have a mapping for "?". - charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh") + charmap = {ord(c): bytes(2*c.upper(), 'ascii') for c in "abcdefgh"} sin = "abc" sout = b"AABBCC" self.assertEqual(codecs.charmap_encode(sin, "strict", charmap)[0], sout) @@ -311,9 +313,9 @@ def test_longstrings(self): # register the handlers under different names, # to prevent the codec from recognizing the name for err in errors: - codecs.register_error("test." + err, codecs.lookup_error(err)) + codecs.register_error(f'test.{err}', codecs.lookup_error(err)) l = 1000 - errors += [ "test." + err for err in errors ] + errors += [f'test.{err}' for err in errors] for uni in [ s*l for s in ("x", "\u3042", "a\xe4") ]: for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15", "utf-8", "utf-7", "utf-16", "utf-32"): @@ -551,10 +553,9 @@ def test_badandgoodxmlcharrefreplaceexceptions(self): s = "".join(chr(c) for c in cs) self.assertEqual( codecs.xmlcharrefreplace_errors( - UnicodeEncodeError("ascii", "a" + s + "b", - 1, 1 + len(s), "ouch") + UnicodeEncodeError("ascii", f'a{s}b', 1, 1 + len(s), "ouch") ), - ("".join("&#%d;" % c for c in cs), 1 + len(s)) + ("".join("&#%d;" % c for c in cs), 1 + len(s)), ) def test_badandgoodbackslashreplaceexceptions(self): @@ -590,16 +591,20 @@ def test_badandgoodbackslashreplaceexceptions(self): with self.subTest(str=s): self.assertEqual( codecs.backslashreplace_errors( - UnicodeEncodeError("ascii", "a" + s + "b", - 1, 1 + len(s), "ouch")), - (r, 1 + len(s)) + UnicodeEncodeError( + "ascii", f'a{s}b', 1, 1 + len(s), "ouch" + ) + ), + (r, 1 + len(s)), ) + self.assertEqual( codecs.backslashreplace_errors( - UnicodeTranslateError("a" + s + "b", - 1, 1 + len(s), "ouch")), - (r, 1 + len(s)) + UnicodeTranslateError(f'a{s}b', 1, 1 + len(s), "ouch") + ), + (r, 1 + len(s)), ) + tests = [ (b"a", "\\x61"), (b"\n", "\\x0a"), @@ -656,9 +661,11 @@ def test_badandgoodnamereplaceexceptions(self): with self.subTest(str=s): self.assertEqual( codecs.namereplace_errors( - UnicodeEncodeError("ascii", "a" + s + "b", - 1, 1 + len(s), "ouch")), - (r, 1 + len(s)) + UnicodeEncodeError( + "ascii", f'a{s}b', 1, 1 + len(s), "ouch" + ) + ), + (r, 1 + len(s)), ) def test_badandgoodsurrogateescapeexceptions(self): @@ -766,10 +773,11 @@ def test_badandgoodsurrogatepassexceptions(self): with self.subTest(encoding=enc, str=s, bytes=b): self.assertEqual( surrogatepass_errors( - UnicodeEncodeError(enc, "a" + s + "b", - 1, 1 + len(s), "ouch")), - (b, 1 + len(s)) + UnicodeEncodeError(enc, f'a{s}b', 1, 1 + len(s), "ouch") + ), + (b, 1 + len(s)), ) + self.assertEqual( surrogatepass_errors( UnicodeDecodeError(enc, bytearray(b"a" + b[:n] + b"b"), @@ -1017,11 +1025,10 @@ def test_mutatingdecodehandler(self): ] def replacing(exc): - if isinstance(exc, UnicodeDecodeError): - exc.object = 42 - return ("\u4242", 0) - else: + if not isinstance(exc, UnicodeDecodeError): raise TypeError("don't know how to handle %r" % exc) + exc.object = 42 + return ("\u4242", 0) codecs.register_error("test.replacing", replacing) with test.support.check_warnings(): @@ -1031,11 +1038,10 @@ def replacing(exc): data.decode(encoding, "test.replacing") def mutating(exc): - if isinstance(exc, UnicodeDecodeError): - exc.object = b"" - return ("\u4242", 0) - else: + if not isinstance(exc, UnicodeDecodeError): raise TypeError("don't know how to handle %r" % exc) + exc.object = b"" + return ("\u4242", 0) codecs.register_error("test.mutating", mutating) # If the decoder doesn't pick up the modified input the following # will lead to an endless loop @@ -1079,11 +1085,10 @@ def forward_shorter_than_end(exc): ) def replace_with_long(exc): - if isinstance(exc, UnicodeDecodeError): - exc.object = b"\x00" * 8 - return ('\ufffd', exc.start) - else: + if not isinstance(exc, UnicodeDecodeError): raise TypeError("don't know how to handle %r" % exc) + exc.object = b"\x00" * 8 + return ('\ufffd', exc.start) codecs.register_error("test.replace_with_long", replace_with_long) self.assertEqual( diff --git a/test/test_codecs.py b/test/test_codecs.py index a59a5e21..038ed3c4 100644 --- a/test/test_codecs.py +++ b/test/test_codecs.py @@ -37,11 +37,11 @@ def read(self, size=-1): if size<0: s = self._buffer self._buffer = self._buffer[:0] # make empty - return s else: s = self._buffer[:size] self._buffer = self._buffer[size:] - return s + + return s class MixInCheckStateHandling: @@ -425,7 +425,7 @@ def test_only_one_bom(self): f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it - self.assertTrue(d == self.spamle or d == self.spambe) + self.assertTrue(d in [self.spamle, self.spambe]) # try to read it back s = io.BytesIO(d) f = reader(s) @@ -609,7 +609,7 @@ def test_only_one_bom(self): f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it - self.assertTrue(d == self.spamle or d == self.spambe) + self.assertTrue(d in [self.spamle, self.spambe]) # try to read it back s = io.BytesIO(d) f = reader(s) @@ -1138,11 +1138,7 @@ def test_stream_bom(self): istream = reader(io.BytesIO(bytestring)) ostream = io.StringIO() while 1: - if sizehint is not None: - data = istream.read(sizehint) - else: - data = istream.read() - + data = istream.read(sizehint) if sizehint is not None else istream.read() if not data: break ostream.write(data) @@ -1160,11 +1156,7 @@ def test_stream_bare(self): istream = reader(io.BytesIO(bytestring)) ostream = io.StringIO() while 1: - if sizehint is not None: - data = istream.read(sizehint) - else: - data = istream.read() - + data = istream.read(sizehint) if sizehint is not None else istream.read() if not data: break ostream.write(data) @@ -2017,9 +2009,7 @@ def test_basics(self): encodedresult += encoder.encode(c) encodedresult += encoder.encode("", True) decoder = codecs.getincrementaldecoder(encoding)() - decodedresult = "" - for c in encodedresult: - decodedresult += decoder.decode(bytes([c])) + decodedresult = "".join(decoder.decode(bytes([c])) for c in encodedresult) decodedresult += decoder.decode(b"", True) self.assertEqual(decodedresult, s, "encoding=%r" % encoding) @@ -2066,9 +2056,7 @@ def test_basics_capi(self): encodedresult += cencoder.encode(c) encodedresult += cencoder.encode("", True) cdecoder = codec_incrementaldecoder(encoding) - decodedresult = "" - for c in encodedresult: - decodedresult += cdecoder.decode(bytes([c])) + decodedresult = "".join(cdecoder.decode(bytes([c])) for c in encodedresult) decodedresult += cdecoder.decode(b"", True) self.assertEqual(decodedresult, s, "encoding=%r" % encoding) @@ -2096,7 +2084,7 @@ def test_seek(self): if encoding in broken_unicode_with_stateful: continue reader = codecs.getreader(encoding)(io.BytesIO(s.encode(encoding))) - for t in range(5): + for _ in range(5): # Test that calling seek resets the internal codec state and buffers reader.seek(0, 0) data = reader.read() @@ -2310,11 +2298,13 @@ def test_decode_with_int2int_map(self): ) self.assertEqual( - codecs.charmap_decode(b"\x00\x01\x02", "strict", - {0: sys.maxunicode, 1: b, 2: c}), - (chr(sys.maxunicode) + "bc", 3) + codecs.charmap_decode( + b"\x00\x01\x02", "strict", {0: sys.maxunicode, 1: b, 2: c} + ), + (f'{chr(sys.maxunicode)}bc', 3), ) + self.assertRaises(TypeError, codecs.charmap_decode, b"\x00\x01\x02", "strict", {0: sys.maxunicode + 1, 1: b, 2: c} @@ -2438,7 +2428,7 @@ def test_raw_decode(self): decode = codecs.unicode_escape_decode for b in range(256): if b != b'\\'[0]: - self.assertEqual(decode(bytes([b]) + b'0'), (chr(b) + '0', 2)) + self.assertEqual(decode(bytes([b]) + b'0'), (f'{chr(b)}0', 2)) def test_escape_encode(self): encode = codecs.unicode_escape_encode @@ -2483,10 +2473,10 @@ def test_escape_decode(self): b = bytes([i]) if b not in b'abfnrtuvx': with self.assertWarns(DeprecationWarning): - check(b"\\" + b, "\\" + chr(i)) + check(b"\\" + b, f'\\{chr(i)}') if b.upper() not in b'UN': with self.assertWarns(DeprecationWarning): - check(b"\\" + b.upper(), "\\" + chr(i-32)) + check(b"\\" + b.upper(), f'\\{chr(i-32)}') with self.assertWarns(DeprecationWarning): check(br"\8", "\\8") with self.assertWarns(DeprecationWarning): @@ -2524,14 +2514,14 @@ def test_raw_encode(self): def test_raw_decode(self): decode = codecs.raw_unicode_escape_decode for b in range(256): - self.assertEqual(decode(bytes([b]) + b'0'), (chr(b) + '0', 2)) + self.assertEqual(decode(bytes([b]) + b'0'), (f'{chr(b)}0', 2)) def test_escape_encode(self): encode = codecs.raw_unicode_escape_encode check = coding_checker(self, encode) for b in range(256): if b not in b'uU': - check('\\' + chr(b), b'\\' + bytes([b])) + check(f'\\{chr(b)}', b'\\' + bytes([b])) check('\u20ac', br'\u20ac') check('\U0001d120', br'\U0001d120') @@ -2540,7 +2530,7 @@ def test_escape_decode(self): check = coding_checker(self, decode) for b in range(256): if b not in b'uU': - check(b'\\' + bytes([b]), '\\' + chr(b)) + check(b'\\' + bytes([b]), f'\\{chr(b)}') check(br"\u20ac", "\u20ac") check(br"\U0001d120", "\U0001d120") diff --git a/test/test_collections.py b/test/test_collections.py index e15c59d3..d00c4799 100644 --- a/test/test_collections.py +++ b/test/test_collections.py @@ -386,8 +386,13 @@ def test_odd_sizes(self): self.assertEqual(Dot(1)._fields, ('d',)) n = 5000 - names = list(set(''.join([choice(string.ascii_letters) - for j in range(10)]) for i in range(n))) + names = list( + { + ''.join([choice(string.ascii_letters) for _ in range(10)]) + for _ in range(n) + } + ) + n = len(names) Big = namedtuple('Big', names) b = Big(*range(n)) @@ -1122,10 +1127,7 @@ async def athrow(self, *args): pass run_async(IgnoreGeneratorExit().aclose()) def test_Sized(self): - non_samples = [None, 42, 3.14, 1j, - _test_gen(), - (x for x in []), - ] + non_samples = [None, 42, 3.14, 1j, _test_gen(), iter([])] for x in non_samples: self.assertNotIsInstance(x, Sized) self.assertFalse(issubclass(type(x), Sized), repr(type(x))) @@ -1140,10 +1142,7 @@ def test_Sized(self): self.validate_isinstance(Sized, '__len__') def test_Container(self): - non_samples = [None, 42, 3.14, 1j, - _test_gen(), - (x for x in []), - ] + non_samples = [None, 42, 3.14, 1j, _test_gen(), iter([])] for x in non_samples: self.assertNotIsInstance(x, Container) self.assertFalse(issubclass(type(x), Container), repr(type(x))) @@ -1158,11 +1157,21 @@ def test_Container(self): self.validate_isinstance(Container, '__contains__') def test_Callable(self): - non_samples = [None, 42, 3.14, 1j, - "", b"", (), [], {}, set(), - _test_gen(), - (x for x in []), - ] + non_samples = [ + None, + 42, + 3.14, + 1j, + "", + b"", + (), + [], + {}, + set(), + _test_gen(), + iter([]), + ] + for x in non_samples: self.assertNotIsInstance(x, Callable) self.assertFalse(issubclass(type(x), Callable), repr(type(x))) @@ -1256,7 +1265,7 @@ def __contains__(self, x): def __iter__(self): return iter(self.contents) def __len__(self): - return len([x for x in self.contents]) + return len(list(self.contents)) s1 = MySet((1, 2, 3)) s2 = MySet((4, 5, 6)) s3 = MySet((1, 5, 6)) @@ -1272,7 +1281,7 @@ def __contains__(self, x): def __iter__(self): return iter(self.contents) def __len__(self): - return len([x for x in self.contents]) + return len(list(self.contents)) s1 = MySet((1,)) s2 = MySet((1, 2)) s3 = MySet((3, 4)) @@ -1294,7 +1303,7 @@ def __contains__(self, x): def __iter__(self): return iter(self.contents) def __len__(self): - return len([x for x in self.contents]) + return len(list(self.contents)) s1 = MySet((1, 2, 3)) s2 = MySet((3, 4, 5)) s3 = s1 & s2 @@ -1788,7 +1797,7 @@ def test_basics(self): self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') self.assertEqual(c.pop('f'), 4) self.assertNotIn('f', c) - for i in range(3): + for _ in range(3): elem, cnt = c.popitem() self.assertNotIn(elem, c) c.clear() @@ -1880,11 +1889,11 @@ def test_multiset_operations(self): self.assertEqual(dict(c), dict(a=10)) elements = 'abcd' - for i in range(1000): + for _ in range(1000): # test random pairs of multisets - p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + p = Counter({elem: randrange(-2,4) for elem in elements}) p.update(e=1, f=-1, g=0) - q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + q = Counter({elem: randrange(-2,4) for elem in elements}) q.update(h=1, i=-1, j=0) for counterop, numberop in [ (Counter.__add__, lambda x, y: max(0, x+y)), @@ -1900,10 +1909,10 @@ def test_multiset_operations(self): self.assertTrue(x>0 for x in result.values()) elements = 'abcdef' - for i in range(100): + for _ in range(100): # verify that random multisets with no repeats are exactly like sets - p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) - q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) + p = Counter({elem: randrange(0, 2) for elem in elements}) + q = Counter({elem: randrange(0, 2) for elem in elements}) for counterop, setop in [ (Counter.__sub__, set.__sub__), (Counter.__or__, set.__or__), @@ -1915,11 +1924,11 @@ def test_multiset_operations(self): def test_inplace_operations(self): elements = 'abcd' - for i in range(1000): + for _ in range(1000): # test random pairs of multisets - p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + p = Counter({elem: randrange(-2,4) for elem in elements}) p.update(e=1, f=-1, g=0) - q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + q = Counter({elem: randrange(-2,4) for elem in elements}) q.update(h=1, i=-1, j=0) for inplace_op, regular_op in [ (Counter.__iadd__, Counter.__add__), @@ -1970,7 +1979,7 @@ def test_helper_function(self): # two paths, one for real dicts and one for other mappings elems = list('abracadabra') - d = dict() + d = {} _count_elements(d, elems) self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) diff --git a/test/test_compare.py b/test/test_compare.py index 471c8dae..a13fe20d 100644 --- a/test/test_compare.py +++ b/test/test_compare.py @@ -37,7 +37,7 @@ def test_comparisons(self): def test_id_comparisons(self): # Ensure default comparison compares id() of args L = [] - for i in range(10): + for _ in range(10): L.insert(len(L)//2, Empty()) for a in L: for b in L: diff --git a/test/test_compile.py b/test/test_compile.py index 95c314f1..3f6217bf 100644 --- a/test/test_compile.py +++ b/test/test_compile.py @@ -96,9 +96,7 @@ class A: # Verify that dict subclasses work as well class D(dict): def __getitem__(self, key): - if key == 'a': - return 12 - return dict.__getitem__(self, key) + return 12 if key == 'a' else dict.__getitem__(self, key) d = D() exec('z = a', g, d) self.assertEqual(d['z'], 12) @@ -194,12 +192,12 @@ def test_unary_minus(self): # 32-bit machine all_one_bits = '0xffffffff' self.assertEqual(eval(all_one_bits), 4294967295) - self.assertEqual(eval("-" + all_one_bits), -4294967295) + self.assertEqual(eval(f'-{all_one_bits}'), -4294967295) elif sys.maxsize == 9223372036854775807: # 64-bit machine all_one_bits = '0xffffffffffffffff' self.assertEqual(eval(all_one_bits), 18446744073709551615) - self.assertEqual(eval("-" + all_one_bits), -18446744073709551615) + self.assertEqual(eval(f'-{all_one_bits}'), -18446744073709551615) else: self.fail("How many bits *does* this machine have???") # Verify treatment of constant folding on -(sys.maxsize+1) @@ -572,7 +570,7 @@ def test_null_terminated(self): # Also test when eval() and exec() do the compilation step self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23) - namespace = dict() + namespace = {} exec(memoryview(b"ax = 123")[1:-1], namespace) self.assertEqual(namespace['x'], 12) @@ -580,13 +578,6 @@ def check_constant(self, func, expected): # Nuitka: Our co_const is not used for storing or accessing constants. return True - for const in func.__code__.co_consts: - if repr(const) == repr(expected): - break - else: - self.fail("unable to find constant %r in %r" - % (expected, func.__code__.co_consts)) - # Merging equal constants is not a strict requirement for the Python # semantics, it's a more an implementation detail. @support.cpython_only @@ -723,7 +714,7 @@ def compile_snippet(i): ns = {} script = """def func():\n""" + i * snippet if async_: - script = "async " + script + script = f'async {script}' code = compile(script, "