repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future3.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future3.py
"""This is a test""" from __future__ import nested_scopes from __future__ import rested_snopes def f(x): def g(y): return x + y return g result = f(2)(4)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_kqueue.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_kqueue.py
""" Tests for kqueue wrapper. """ import errno import os import select import socket import time import unittest if not hasattr(select, "kqueue"): raise unittest.SkipTest("test works only on BSD") class TestKQueue(unittest.TestCase): def test_create_queue(self): kq = select.kqueue() self.assertTrue(kq.fileno() > 0, kq.fileno()) self.assertTrue(not kq.closed) kq.close() self.assertTrue(kq.closed) self.assertRaises(ValueError, kq.fileno) def test_create_event(self): from operator import lt, le, gt, ge fd = os.open(os.devnull, os.O_WRONLY) self.addCleanup(os.close, fd) ev = select.kevent(fd) other = select.kevent(1000) self.assertEqual(ev.ident, fd) self.assertEqual(ev.filter, select.KQ_FILTER_READ) self.assertEqual(ev.flags, select.KQ_EV_ADD) self.assertEqual(ev.fflags, 0) self.assertEqual(ev.data, 0) self.assertEqual(ev.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) self.assertTrue(ev < other) self.assertTrue(other >= ev) for op in lt, le, gt, ge: self.assertRaises(TypeError, op, ev, None) self.assertRaises(TypeError, op, ev, 1) self.assertRaises(TypeError, op, ev, "ev") ev = select.kevent(fd, select.KQ_FILTER_WRITE) self.assertEqual(ev.ident, fd) self.assertEqual(ev.filter, select.KQ_FILTER_WRITE) self.assertEqual(ev.flags, select.KQ_EV_ADD) self.assertEqual(ev.fflags, 0) self.assertEqual(ev.data, 0) self.assertEqual(ev.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) ev = select.kevent(fd, select.KQ_FILTER_WRITE, select.KQ_EV_ONESHOT) self.assertEqual(ev.ident, fd) self.assertEqual(ev.filter, select.KQ_FILTER_WRITE) self.assertEqual(ev.flags, select.KQ_EV_ONESHOT) self.assertEqual(ev.fflags, 0) self.assertEqual(ev.data, 0) self.assertEqual(ev.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) ev = select.kevent(1, 2, 3, 4, 5, 6) self.assertEqual(ev.ident, 1) self.assertEqual(ev.filter, 2) self.assertEqual(ev.flags, 3) self.assertEqual(ev.fflags, 4) self.assertEqual(ev.data, 5) self.assertEqual(ev.udata, 6) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) bignum = 0x7fff ev = select.kevent(bignum, 1, 2, 3, bignum - 1, bignum) self.assertEqual(ev.ident, bignum) self.assertEqual(ev.filter, 1) self.assertEqual(ev.flags, 2) self.assertEqual(ev.fflags, 3) self.assertEqual(ev.data, bignum - 1) self.assertEqual(ev.udata, bignum) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) # Issue 11973 bignum = 0xffff ev = select.kevent(0, 1, bignum) self.assertEqual(ev.ident, 0) self.assertEqual(ev.filter, 1) self.assertEqual(ev.flags, bignum) self.assertEqual(ev.fflags, 0) self.assertEqual(ev.data, 0) self.assertEqual(ev.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) # Issue 11973 bignum = 0xffffffff ev = select.kevent(0, 1, 2, bignum) self.assertEqual(ev.ident, 0) self.assertEqual(ev.filter, 1) self.assertEqual(ev.flags, 2) self.assertEqual(ev.fflags, bignum) self.assertEqual(ev.data, 0) self.assertEqual(ev.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) def test_queue_event(self): serverSocket = socket.socket() serverSocket.bind(('127.0.0.1', 0)) serverSocket.listen() client = socket.socket() client.setblocking(False) try: client.connect(('127.0.0.1', serverSocket.getsockname()[1])) except OSError as e: self.assertEqual(e.args[0], errno.EINPROGRESS) else: #raise AssertionError("Connect should have raised EINPROGRESS") pass # FreeBSD doesn't raise an exception here server, addr = serverSocket.accept() kq = select.kqueue() kq2 = select.kqueue.fromfd(kq.fileno()) ev = select.kevent(server.fileno(), select.KQ_FILTER_WRITE, select.KQ_EV_ADD | select.KQ_EV_ENABLE) kq.control([ev], 0) ev = select.kevent(server.fileno(), select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE) kq.control([ev], 0) ev = select.kevent(client.fileno(), select.KQ_FILTER_WRITE, select.KQ_EV_ADD | select.KQ_EV_ENABLE) kq2.control([ev], 0) ev = select.kevent(client.fileno(), select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE) kq2.control([ev], 0) events = kq.control(None, 4, 1) events = set((e.ident, e.filter) for e in events) self.assertEqual(events, set([ (client.fileno(), select.KQ_FILTER_WRITE), (server.fileno(), select.KQ_FILTER_WRITE)])) client.send(b"Hello!") server.send(b"world!!!") # We may need to call it several times for i in range(10): events = kq.control(None, 4, 1) if len(events) == 4: break time.sleep(1.0) else: self.fail('timeout waiting for event notifications') events = set((e.ident, e.filter) for e in events) self.assertEqual(events, set([ (client.fileno(), select.KQ_FILTER_WRITE), (client.fileno(), select.KQ_FILTER_READ), (server.fileno(), select.KQ_FILTER_WRITE), (server.fileno(), select.KQ_FILTER_READ)])) # Remove completely client, and server read part ev = select.kevent(client.fileno(), select.KQ_FILTER_WRITE, select.KQ_EV_DELETE) kq.control([ev], 0) ev = select.kevent(client.fileno(), select.KQ_FILTER_READ, select.KQ_EV_DELETE) kq.control([ev], 0) ev = select.kevent(server.fileno(), select.KQ_FILTER_READ, select.KQ_EV_DELETE) kq.control([ev], 0, 0) events = kq.control([], 4, 0.99) events = set((e.ident, e.filter) for e in events) self.assertEqual(events, set([ (server.fileno(), select.KQ_FILTER_WRITE)])) client.close() server.close() serverSocket.close() def testPair(self): kq = select.kqueue() a, b = socket.socketpair() a.send(b'foo') event1 = select.kevent(a, select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE) event2 = select.kevent(b, select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE) r = kq.control([event1, event2], 1, 1) self.assertTrue(r) self.assertFalse(r[0].flags & select.KQ_EV_ERROR) self.assertEqual(b.recv(r[0].data), b'foo') a.close() b.close() kq.close() def test_issue30058(self): # changelist must be an iterable kq = select.kqueue() a, b = socket.socketpair() ev = select.kevent(a, select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE) kq.control([ev], 0) # not a list kq.control((ev,), 0) # __len__ is not consistent with __iter__ class BadList: def __len__(self): return 0 def __iter__(self): for i in range(100): yield ev kq.control(BadList(), 0) # doesn't have __len__ kq.control(iter([ev]), 0) a.close() b.close() kq.close() def test_close(self): open_file = open(__file__, "rb") self.addCleanup(open_file.close) fd = open_file.fileno() kqueue = select.kqueue() # test fileno() method and closed attribute self.assertIsInstance(kqueue.fileno(), int) self.assertFalse(kqueue.closed) # test close() kqueue.close() self.assertTrue(kqueue.closed) self.assertRaises(ValueError, kqueue.fileno) # close() can be called more than once kqueue.close() # operations must fail with ValueError("I/O operation on closed ...") self.assertRaises(ValueError, kqueue.control, None, 4) def test_fd_non_inheritable(self): kqueue = select.kqueue() self.addCleanup(kqueue.close) self.assertEqual(os.get_inheritable(kqueue.fileno()), False) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ctypes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ctypes.py
import unittest from test.support import import_module ctypes_test = import_module('ctypes.test') load_tests = ctypes_test.load_tests if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cmd_line_script.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cmd_line_script.py
# tests command line execution of scripts import contextlib import importlib import importlib.machinery import zipimport import unittest import sys import os import os.path import py_compile import subprocess import io import textwrap from test import support from test.support.script_helper import ( make_pkg, make_script, make_zip_pkg, make_zip_script, assert_python_ok, assert_python_failure, spawn_python, kill_python) verbose = support.verbose example_args = ['test1', 'test2', 'test3'] test_source = """\ # Script may be run with optimisation enabled, so don't rely on assert # statements being executed def assertEqual(lhs, rhs): if lhs != rhs: raise AssertionError('%r != %r' % (lhs, rhs)) def assertIdentical(lhs, rhs): if lhs is not rhs: raise AssertionError('%r is not %r' % (lhs, rhs)) # Check basic code execution result = ['Top level assignment'] def f(): result.append('Lower level reference') f() assertEqual(result, ['Top level assignment', 'Lower level reference']) # Check population of magic variables assertEqual(__name__, '__main__') from importlib.machinery import BuiltinImporter _loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__) print('__loader__==%a' % _loader) print('__file__==%a' % __file__) print('__cached__==%a' % __cached__) print('__package__==%r' % __package__) # Check PEP 451 details import os.path if __package__ is not None: print('__main__ was located through the import system') assertIdentical(__spec__.loader, __loader__) expected_spec_name = os.path.splitext(os.path.basename(__file__))[0] if __package__: expected_spec_name = __package__ + "." + expected_spec_name assertEqual(__spec__.name, expected_spec_name) assertEqual(__spec__.parent, __package__) assertIdentical(__spec__.submodule_search_locations, None) assertEqual(__spec__.origin, __file__) if __spec__.cached is not None: assertEqual(__spec__.cached, __cached__) # Check the sys module import sys assertIdentical(globals(), sys.modules[__name__].__dict__) if __spec__ is not None: # XXX: We're not currently making __main__ available under its real name pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__) from test import test_cmd_line_script example_args_list = test_cmd_line_script.example_args assertEqual(sys.argv[1:], example_args_list) print('sys.argv[0]==%a' % sys.argv[0]) print('sys.path[0]==%a' % sys.path[0]) # Check the working directory import os print('cwd==%a' % os.getcwd()) """ def _make_test_script(script_dir, script_basename, source=test_source): to_return = make_script(script_dir, script_basename, source) importlib.invalidate_caches() return to_return def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source=test_source, depth=1): to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth) importlib.invalidate_caches() return to_return class CmdLineTest(unittest.TestCase): def _check_output(self, script_name, exit_code, data, expected_file, expected_argv0, expected_path0, expected_package, expected_loader, expected_cwd=None): if verbose > 1: print("Output from test script %r:" % script_name) print(repr(data)) self.assertEqual(exit_code, 0) printed_loader = '__loader__==%a' % expected_loader printed_file = '__file__==%a' % expected_file printed_package = '__package__==%r' % expected_package printed_argv0 = 'sys.argv[0]==%a' % expected_argv0 printed_path0 = 'sys.path[0]==%a' % expected_path0 if expected_cwd is None: expected_cwd = os.getcwd() printed_cwd = 'cwd==%a' % expected_cwd if verbose > 1: print('Expected output:') print(printed_file) print(printed_package) print(printed_argv0) print(printed_cwd) self.assertIn(printed_loader.encode('utf-8'), data) self.assertIn(printed_file.encode('utf-8'), data) self.assertIn(printed_package.encode('utf-8'), data) self.assertIn(printed_argv0.encode('utf-8'), data) self.assertIn(printed_path0.encode('utf-8'), data) self.assertIn(printed_cwd.encode('utf-8'), data) def _check_script(self, script_exec_args, expected_file, expected_argv0, expected_path0, expected_package, expected_loader, *cmd_line_switches, cwd=None, **env_vars): if isinstance(script_exec_args, str): script_exec_args = [script_exec_args] run_args = [*support.optim_args_from_interpreter_flags(), *cmd_line_switches, *script_exec_args, *example_args] rc, out, err = assert_python_ok( *run_args, __isolated=False, __cwd=cwd, **env_vars ) self._check_output(script_exec_args, rc, out + err, expected_file, expected_argv0, expected_path0, expected_package, expected_loader, cwd) def _check_import_error(self, script_exec_args, expected_msg, *cmd_line_switches, cwd=None, **env_vars): if isinstance(script_exec_args, str): script_exec_args = (script_exec_args,) else: script_exec_args = tuple(script_exec_args) run_args = cmd_line_switches + script_exec_args rc, out, err = assert_python_failure( *run_args, __isolated=False, __cwd=cwd, **env_vars ) if verbose > 1: print('Output from test script %r:' % script_exec_args) print(repr(err)) print('Expected output: %r' % expected_msg) self.assertIn(expected_msg.encode('utf-8'), err) def test_dash_c_loader(self): rc, out, err = assert_python_ok("-c", "print(__loader__)") expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") self.assertIn(expected, out) def test_stdin_loader(self): # Unfortunately, there's no way to automatically test the fully # interactive REPL, since that code path only gets executed when # stdin is an interactive tty. p = spawn_python() try: p.stdin.write(b"print(__loader__)\n") p.stdin.flush() finally: out = kill_python(p) expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") self.assertIn(expected, out) @contextlib.contextmanager def interactive_python(self, separate_stderr=False): if separate_stderr: p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE) stderr = p.stderr else: p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT) stderr = p.stdout try: # Drain stderr until prompt while True: data = stderr.read(4) if data == b">>> ": break stderr.readline() yield p finally: kill_python(p) stderr.close() def check_repl_stdout_flush(self, separate_stderr=False): with self.interactive_python(separate_stderr) as p: p.stdin.write(b"print('foo')\n") p.stdin.flush() self.assertEqual(b'foo', p.stdout.readline().strip()) def check_repl_stderr_flush(self, separate_stderr=False): with self.interactive_python(separate_stderr) as p: p.stdin.write(b"1/0\n") p.stdin.flush() stderr = p.stderr if separate_stderr else p.stdout self.assertIn(b'Traceback ', stderr.readline()) self.assertIn(b'File "<stdin>"', stderr.readline()) self.assertIn(b'ZeroDivisionError', stderr.readline()) def test_repl_stdout_flush(self): self.check_repl_stdout_flush() def test_repl_stdout_flush_separate_stderr(self): self.check_repl_stdout_flush(True) def test_repl_stderr_flush(self): self.check_repl_stderr_flush() def test_repl_stderr_flush_separate_stderr(self): self.check_repl_stderr_flush(True) def test_basic_script(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') self._check_script(script_name, script_name, script_name, script_dir, None, importlib.machinery.SourceFileLoader) def test_script_compiled(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') py_compile.compile(script_name, doraise=True) os.remove(script_name) pyc_file = support.make_legacy_pyc(script_name) self._check_script(pyc_file, pyc_file, pyc_file, script_dir, None, importlib.machinery.SourcelessFileLoader) def test_directory(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') self._check_script(script_dir, script_name, script_dir, script_dir, '', importlib.machinery.SourceFileLoader) def test_directory_compiled(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') py_compile.compile(script_name, doraise=True) os.remove(script_name) pyc_file = support.make_legacy_pyc(script_name) self._check_script(script_dir, pyc_file, script_dir, script_dir, '', importlib.machinery.SourcelessFileLoader) def test_directory_error(self): with support.temp_dir() as script_dir: msg = "can't find '__main__' module in %r" % script_dir self._check_import_error(script_dir, msg) def test_zipfile(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) self._check_script(zip_name, run_name, zip_name, zip_name, '', zipimport.zipimporter) def test_zipfile_compiled(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') compiled_name = py_compile.compile(script_name, doraise=True) zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, run_name, zip_name, zip_name, '', zipimport.zipimporter) def test_zipfile_error(self): with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'not_main') zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) msg = "can't find '__main__' module in %r" % zip_name self._check_import_error(zip_name, msg) def test_module_in_package(self): with support.temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, 'script') self._check_script(["-m", "test_pkg.script"], script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader, cwd=script_dir) def test_module_in_package_in_zipfile(self): with support.temp_dir() as script_dir: zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script') self._check_script(["-m", "test_pkg.script"], run_name, run_name, script_dir, 'test_pkg', zipimport.zipimporter, PYTHONPATH=zip_name, cwd=script_dir) def test_module_in_subpackage_in_zipfile(self): with support.temp_dir() as script_dir: zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2) self._check_script(["-m", "test_pkg.test_pkg.script"], run_name, run_name, script_dir, 'test_pkg.test_pkg', zipimport.zipimporter, PYTHONPATH=zip_name, cwd=script_dir) def test_package(self): with support.temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') self._check_script(["-m", "test_pkg"], script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader, cwd=script_dir) def test_package_compiled(self): with support.temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) pyc_file = support.make_legacy_pyc(script_name) self._check_script(["-m", "test_pkg"], pyc_file, pyc_file, script_dir, 'test_pkg', importlib.machinery.SourcelessFileLoader, cwd=script_dir) def test_package_error(self): with support.temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) msg = ("'test_pkg' is a package and cannot " "be directly executed") self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir) def test_package_recursion(self): with support.temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) main_dir = os.path.join(pkg_dir, '__main__') make_pkg(main_dir) msg = ("Cannot use package as __main__ module; " "'test_pkg' is a package and cannot " "be directly executed") self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir) def test_issue8202(self): # Make sure package __init__ modules see "-m" in sys.argv0 while # searching for the module to execute with support.temp_dir() as script_dir: with support.change_cwd(path=script_dir): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])") script_name = _make_test_script(pkg_dir, 'script') rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False) if verbose > 1: print(repr(out)) expected = "init_argv0==%r" % '-m' self.assertIn(expected.encode('utf-8'), out) self._check_output(script_name, rc, out, script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader) def test_issue8202_dash_c_file_ignored(self): # Make sure a "-c" file in the current directory # does not alter the value of sys.path[0] with support.temp_dir() as script_dir: with support.change_cwd(path=script_dir): with open("-c", "w") as f: f.write("data") rc, out, err = assert_python_ok('-c', 'import sys; print("sys.path[0]==%r" % sys.path[0])', __isolated=False) if verbose > 1: print(repr(out)) expected = "sys.path[0]==%r" % '' self.assertIn(expected.encode('utf-8'), out) def test_issue8202_dash_m_file_ignored(self): # Make sure a "-m" file in the current directory # does not alter the value of sys.path[0] with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'other') with support.change_cwd(path=script_dir): with open("-m", "w") as f: f.write("data") rc, out, err = assert_python_ok('-m', 'other', *example_args, __isolated=False) self._check_output(script_name, rc, out, script_name, script_name, script_dir, '', importlib.machinery.SourceFileLoader) def test_issue20884(self): # On Windows, script with encoding cookie and LF line ending # will be failed. with support.temp_dir() as script_dir: script_name = os.path.join(script_dir, "issue20884.py") with open(script_name, "w", newline='\n') as f: f.write("#coding: iso-8859-1\n") f.write('"""\n') for _ in range(30): f.write('x'*80 + '\n') f.write('"""\n') with support.change_cwd(path=script_dir): rc, out, err = assert_python_ok(script_name) self.assertEqual(b"", out) self.assertEqual(b"", err) @contextlib.contextmanager def setup_test_pkg(self, *args): with support.temp_dir() as script_dir, \ support.change_cwd(path=script_dir): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir, *args) yield pkg_dir def check_dash_m_failure(self, *args): rc, out, err = assert_python_failure('-m', *args, __isolated=False) if verbose > 1: print(repr(out)) self.assertEqual(rc, 1) return err def test_dash_m_error_code_is_one(self): # If a module is invoked with the -m command line flag # and results in an error that the return code to the # shell is '1' with self.setup_test_pkg() as pkg_dir: script_name = _make_test_script(pkg_dir, 'other', "if __name__ == '__main__': raise ValueError") err = self.check_dash_m_failure('test_pkg.other', *example_args) self.assertIn(b'ValueError', err) def test_dash_m_errors(self): # Exercise error reporting for various invalid package executions tests = ( ('builtins', br'No code object available'), ('builtins.x', br'Error while finding module specification.*' br'ModuleNotFoundError'), ('builtins.x.y', br'Error while finding module specification.*' br'ModuleNotFoundError.*No module named.*not a package'), ('os.path', br'loader.*cannot handle'), ('importlib', br'No module named.*' br'is a package and cannot be directly executed'), ('importlib.nonexistant', br'No module named'), ('.unittest', br'Relative module names not supported'), ) for name, regex in tests: with self.subTest(name): rc, _, err = assert_python_failure('-m', name) self.assertEqual(rc, 1) self.assertRegex(err, regex) self.assertNotIn(b'Traceback', err) def test_dash_m_bad_pyc(self): with support.temp_dir() as script_dir, \ support.change_cwd(path=script_dir): os.mkdir('test_pkg') # Create invalid *.pyc as empty file with open('test_pkg/__init__.pyc', 'wb'): pass err = self.check_dash_m_failure('test_pkg') self.assertRegex(err, br'Error while finding module specification.*' br'ImportError.*bad magic number') self.assertNotIn(b'is a package', err) self.assertNotIn(b'Traceback', err) def test_dash_m_init_traceback(self): # These were wrapped in an ImportError and tracebacks were # suppressed; see Issue 14285 exceptions = (ImportError, AttributeError, TypeError, ValueError) for exception in exceptions: exception = exception.__name__ init = "raise {0}('Exception in __init__.py')".format(exception) with self.subTest(exception), \ self.setup_test_pkg(init) as pkg_dir: err = self.check_dash_m_failure('test_pkg') self.assertIn(exception.encode('ascii'), err) self.assertIn(b'Exception in __init__.py', err) self.assertIn(b'Traceback', err) def test_dash_m_main_traceback(self): # Ensure that an ImportError's traceback is reported with self.setup_test_pkg() as pkg_dir: main = "raise ImportError('Exception in __main__ module')" _make_test_script(pkg_dir, '__main__', main) err = self.check_dash_m_failure('test_pkg') self.assertIn(b'ImportError', err) self.assertIn(b'Exception in __main__ module', err) self.assertIn(b'Traceback', err) def test_pep_409_verbiage(self): # Make sure PEP 409 syntax properly suppresses # the context of an exception script = textwrap.dedent("""\ try: raise ValueError except: raise NameError from None """) with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) text = stderr.decode('ascii').split('\n') self.assertEqual(len(text), 4) self.assertTrue(text[0].startswith('Traceback')) self.assertTrue(text[1].startswith(' File ')) self.assertTrue(text[3].startswith('NameError')) def test_non_ascii(self): # Mac OS X denies the creation of a file with an invalid UTF-8 name. # Windows allows creating a name with an arbitrary bytes name, but # Python cannot a undecodable bytes argument to a subprocess. if (support.TESTFN_UNDECODABLE and sys.platform not in ('win32', 'darwin')): name = os.fsdecode(support.TESTFN_UNDECODABLE) elif support.TESTFN_NONASCII: name = support.TESTFN_NONASCII else: self.skipTest("need support.TESTFN_NONASCII") # Issue #16218 source = 'print(ascii(__file__))\n' script_name = _make_test_script(os.curdir, name, source) self.addCleanup(support.unlink, script_name) rc, stdout, stderr = assert_python_ok(script_name) self.assertEqual( ascii(script_name), stdout.rstrip().decode('ascii'), 'stdout=%r stderr=%r' % (stdout, stderr)) self.assertEqual(0, rc) def test_issue20500_exit_with_exception_value(self): script = textwrap.dedent("""\ import sys error = None try: raise ValueError('some text') except ValueError as err: error = err if error: sys.exit(error) """) with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) text = stderr.decode('ascii') self.assertEqual(text, "some text") def test_syntaxerror_unindented_caret_position(self): script = "1 + 1 = 2\n" with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() # Confirm that the caret is located under the first 1 character self.assertIn("\n 1 + 1 = 2\n ^", text) def test_syntaxerror_indented_caret_position(self): script = textwrap.dedent("""\ if True: 1 + 1 = 2 """) with support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() # Confirm that the caret is located under the first 1 character self.assertIn("\n 1 + 1 = 2\n ^", text) # Try the same with a form feed at the start of the indented line script = ( "if True:\n" "\f 1 + 1 = 2\n" ) script_name = _make_test_script(script_dir, "script", script) exitcode, stdout, stderr = assert_python_failure(script_name) text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read() self.assertNotIn("\f", text) self.assertIn("\n 1 + 1 = 2\n ^", text) def test_consistent_sys_path_for_direct_execution(self): # This test case ensures that the following all give the same # sys.path configuration: # # ./python -s script_dir/__main__.py # ./python -s script_dir # ./python -I script_dir script = textwrap.dedent("""\ import sys for entry in sys.path: print(entry) """) # Always show full path diffs on errors self.maxDiff = None with support.temp_dir() as work_dir, support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__', script) # Reference output comes from directly executing __main__.py # We omit PYTHONPATH and user site to align with isolated mode p = spawn_python("-Es", script_name, cwd=work_dir) out_by_name = kill_python(p).decode().splitlines() self.assertEqual(out_by_name[0], script_dir) self.assertNotIn(work_dir, out_by_name) # Directory execution should give the same output p = spawn_python("-Es", script_dir, cwd=work_dir) out_by_dir = kill_python(p).decode().splitlines() self.assertEqual(out_by_dir, out_by_name) # As should directory execution in isolated mode p = spawn_python("-I", script_dir, cwd=work_dir) out_by_dir_isolated = kill_python(p).decode().splitlines() self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name) def test_consistent_sys_path_for_module_execution(self): # This test case ensures that the following both give the same # sys.path configuration: # ./python -sm script_pkg.__main__ # ./python -sm script_pkg # # And that this fails as unable to find the package: # ./python -Im script_pkg script = textwrap.dedent("""\ import sys for entry in sys.path: print(entry) """) # Always show full path diffs on errors self.maxDiff = None with support.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) script_name = _make_test_script(script_dir, '__main__', script) # Reference output comes from `-m script_pkg.__main__` # We omit PYTHONPATH and user site to better align with the # direct execution test cases p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir) out_by_module = kill_python(p).decode().splitlines() self.assertEqual(out_by_module[0], work_dir) self.assertNotIn(script_dir, out_by_module) # Package execution should give the same output p = spawn_python("-sm", "script_pkg", cwd=work_dir) out_by_package = kill_python(p).decode().splitlines() self.assertEqual(out_by_package, out_by_module) # Isolated mode should fail with an import error exitcode, stdout, stderr = assert_python_failure( "-Im", "script_pkg", cwd=work_dir ) traceback_lines = stderr.decode().splitlines() self.assertIn("No module named script_pkg", traceback_lines[-1]) def test_nonexisting_script(self): # bpo-34783: "./python script.py" must not crash # if the script file doesn't exist. # (Skip test for macOS framework builds because sys.excutable name # is not the actual Python executable file name. script = 'nonexistingscript.py' self.assertFalse(os.path.exists(script)) proc = spawn_python(script, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() self.assertIn(": can't open file ", err) self.assertNotEqual(proc.returncode, 0) def test_main(): support.run_unittest(CmdLineTest) support.reap_children() if __name__ == '__main__': test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_baseexception.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_baseexception.py
import unittest import builtins import os from platform import system as platform_system class ExceptionClassTests(unittest.TestCase): """Tests for anything relating to exception objects themselves (e.g., inheritance hierarchy)""" def test_builtins_new_style(self): self.assertTrue(issubclass(Exception, object)) def verify_instance_interface(self, ins): for attr in ("args", "__str__", "__repr__"): self.assertTrue(hasattr(ins, attr), "%s missing %s attribute" % (ins.__class__.__name__, attr)) def test_inheritance(self): # Make sure the inheritance hierarchy matches the documentation exc_set = set() for object_ in builtins.__dict__.values(): try: if issubclass(object_, BaseException): exc_set.add(object_.__name__) except TypeError: pass inheritance_tree = open(os.path.join(os.path.split(__file__)[0], 'exception_hierarchy.txt')) try: superclass_name = inheritance_tree.readline().rstrip() try: last_exc = getattr(builtins, superclass_name) except AttributeError: self.fail("base class %s not a built-in" % superclass_name) self.assertIn(superclass_name, exc_set, '%s not found' % superclass_name) exc_set.discard(superclass_name) superclasses = [] # Loop will insert base exception last_depth = 0 for exc_line in inheritance_tree: exc_line = exc_line.rstrip() depth = exc_line.rindex('-') exc_name = exc_line[depth+2:] # Slice past space if '(' in exc_name: paren_index = exc_name.index('(') platform_name = exc_name[paren_index+1:-1] exc_name = exc_name[:paren_index-1] # Slice off space if platform_system() != platform_name: exc_set.discard(exc_name) continue if '[' in exc_name: left_bracket = exc_name.index('[') exc_name = exc_name[:left_bracket-1] # cover space try: exc = getattr(builtins, exc_name) except AttributeError: self.fail("%s not a built-in exception" % exc_name) if last_depth < depth: superclasses.append((last_depth, last_exc)) elif last_depth > depth: while superclasses[-1][0] >= depth: superclasses.pop() self.assertTrue(issubclass(exc, superclasses[-1][1]), "%s is not a subclass of %s" % (exc.__name__, superclasses[-1][1].__name__)) try: # Some exceptions require arguments; just skip them self.verify_instance_interface(exc()) except TypeError: pass self.assertIn(exc_name, exc_set) exc_set.discard(exc_name) last_exc = exc last_depth = depth finally: inheritance_tree.close() self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set) interface_tests = ("length", "args", "str", "repr") def interface_test_driver(self, results): for test_name, (given, expected) in zip(self.interface_tests, results): self.assertEqual(given, expected, "%s: %s != %s" % (test_name, given, expected)) def test_interface_single_arg(self): # Make sure interface works properly when given a single argument arg = "spam" exc = Exception(arg) results = ([len(exc.args), 1], [exc.args[0], arg], [str(exc), str(arg)], [repr(exc), '%s(%r)' % (exc.__class__.__name__, arg)]) self.interface_test_driver(results) def test_interface_multi_arg(self): # Make sure interface correct when multiple arguments given arg_count = 3 args = tuple(range(arg_count)) exc = Exception(*args) results = ([len(exc.args), arg_count], [exc.args, args], [str(exc), str(args)], [repr(exc), exc.__class__.__name__ + repr(exc.args)]) self.interface_test_driver(results) 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__ + '()']) self.interface_test_driver(results) class UsageTests(unittest.TestCase): """Test usage of exceptions""" def raise_fails(self, object_): """Make sure that raising 'object_' triggers a TypeError.""" try: raise object_ except TypeError: return # What is expected. self.fail("TypeError expected for raising %s" % type(object_)) def catch_fails(self, object_): """Catching 'object_' should raise a TypeError.""" try: try: raise Exception except object_: pass except TypeError: pass except Exception: self.fail("TypeError expected when catching %s" % type(object_)) try: try: raise Exception except (object_,): pass except TypeError: return except Exception: self.fail("TypeError expected when catching %s as specified in a " "tuple" % type(object_)) def test_raise_new_style_non_exception(self): # You cannot raise a new-style class that does not inherit from # BaseException; the ability was not possible until BaseException's # introduction so no need to support new-style objects that do not # inherit from it. class NewStyleClass(object): pass self.raise_fails(NewStyleClass) self.raise_fails(NewStyleClass()) def test_raise_string(self): # Raising a string raises TypeError. self.raise_fails("spam") def test_catch_non_BaseException(self): # Trying to catch an object that does not inherit from BaseException # is not allowed. class NonBaseException(object): pass self.catch_fails(NonBaseException) self.catch_fails(NonBaseException()) def test_catch_BaseException_instance(self): # Catching an instance of a BaseException subclass won't work. self.catch_fails(BaseException()) def test_catch_string(self): # Catching a string is bad. self.catch_fails("spam") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dictcomps.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dictcomps.py
import unittest # For scope testing. g = "Global variable" class DictComprehensionTest(unittest.TestCase): def test_basics(self): expected = {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19} actual = {k: k + 10 for k in range(10)} self.assertEqual(actual, expected) expected = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} actual = {k: v for k in range(10) for v in range(10) if k == v} self.assertEqual(actual, expected) def test_scope_isolation(self): k = "Local Variable" expected = {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None} actual = {k: None for k in range(10)} self.assertEqual(actual, expected) self.assertEqual(k, "Local Variable") expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6, 55: 6, 56: 6, 57: 6, 58: 6, 59: 6, 63: 7, 64: 7, 65: 7, 66: 7, 67: 7, 68: 7, 69: 7, 72: 8, 73: 8, 74: 8, 75: 8, 76: 8, 77: 8, 78: 8, 79: 8, 81: 9, 82: 9, 83: 9, 84: 9, 85: 9, 86: 9, 87: 9, 88: 9, 89: 9} actual = {k: v for v in range(10) for k in range(v * 9, v * 10)} self.assertEqual(k, "Local Variable") self.assertEqual(actual, expected) def test_scope_isolation_from_global(self): expected = {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None} actual = {g: None for g in range(10)} self.assertEqual(actual, expected) self.assertEqual(g, "Global variable") expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6, 55: 6, 56: 6, 57: 6, 58: 6, 59: 6, 63: 7, 64: 7, 65: 7, 66: 7, 67: 7, 68: 7, 69: 7, 72: 8, 73: 8, 74: 8, 75: 8, 76: 8, 77: 8, 78: 8, 79: 8, 81: 9, 82: 9, 83: 9, 84: 9, 85: 9, 86: 9, 87: 9, 88: 9, 89: 9} actual = {g: v for v in range(10) for g in range(v * 9, v * 10)} self.assertEqual(g, "Global variable") self.assertEqual(actual, expected) def test_global_visibility(self): expected = {0: 'Global variable', 1: 'Global variable', 2: 'Global variable', 3: 'Global variable', 4: 'Global variable', 5: 'Global variable', 6: 'Global variable', 7: 'Global variable', 8: 'Global variable', 9: 'Global variable'} actual = {k: g for k in range(10)} self.assertEqual(actual, expected) def test_local_visibility(self): v = "Local variable" expected = {0: 'Local variable', 1: 'Local variable', 2: 'Local variable', 3: 'Local variable', 4: 'Local variable', 5: 'Local variable', 6: 'Local variable', 7: 'Local variable', 8: 'Local variable', 9: 'Local variable'} actual = {k: v for k in range(10)} self.assertEqual(actual, expected) self.assertEqual(v, "Local variable") def test_illegal_assignment(self): with self.assertRaisesRegex(SyntaxError, "can't assign"): compile("{x: y for y, x in ((1, 2), (3, 4))} = 5", "<test>", "exec") with self.assertRaisesRegex(SyntaxError, "can't assign"): compile("{x: y for y, x in ((1, 2), (3, 4))} += 5", "<test>", "exec") if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_lib2to3.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_lib2to3.py
from lib2to3.tests import load_tests import unittest if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/good_getattr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/good_getattr.py
x = 1 def __dir__(): return ['a', 'b', 'c'] def __getattr__(name): if name == "yolo": raise AttributeError("Deprecated, use whatever instead") return f"There is {name}" y = 2
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bigaddrspace.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bigaddrspace.py
""" These tests are meant to exercise that requests to create objects bigger than what the address space allows are properly met with an OverflowError (rather than crash weirdly). Primarily, this means 32-bit builds with at least 2 GiB of available memory. You need to pass the -M option to regrtest (e.g. "-M 2.1G") for tests to be enabled. """ from test import support from test.support import bigaddrspacetest, MAX_Py_ssize_t import unittest import operator import sys class BytesTest(unittest.TestCase): @bigaddrspacetest def test_concat(self): # Allocate a bytestring that's near the maximum size allowed by # the address space, and then try to build a new, larger one through # concatenation. try: x = b"x" * (MAX_Py_ssize_t - 128) self.assertRaises(OverflowError, operator.add, x, b"x" * 128) finally: x = None @bigaddrspacetest def test_optimized_concat(self): try: x = b"x" * (MAX_Py_ssize_t - 128) with self.assertRaises(OverflowError) as cm: # this statement used a fast path in ceval.c x = x + b"x" * 128 with self.assertRaises(OverflowError) as cm: # this statement used a fast path in ceval.c x += b"x" * 128 finally: x = None @bigaddrspacetest def test_repeat(self): try: x = b"x" * (MAX_Py_ssize_t - 128) self.assertRaises(OverflowError, operator.mul, x, 128) finally: x = None class StrTest(unittest.TestCase): unicodesize = 2 if sys.maxunicode < 65536 else 4 @bigaddrspacetest def test_concat(self): try: # Create a string that would fill almost the address space x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize)) # Unicode objects trigger MemoryError in case an operation that's # going to cause a size overflow is executed self.assertRaises(MemoryError, operator.add, x, x) finally: x = None @bigaddrspacetest def test_optimized_concat(self): try: x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize)) with self.assertRaises(MemoryError) as cm: # this statement uses a fast path in ceval.c x = x + x with self.assertRaises(MemoryError) as cm: # this statement uses a fast path in ceval.c x += x finally: x = None @bigaddrspacetest def test_repeat(self): try: x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize)) self.assertRaises(MemoryError, operator.mul, x, 2) finally: x = None def test_main(): support.run_unittest(BytesTest, StrTest) if __name__ == '__main__': if len(sys.argv) > 1: support.set_memlimit(sys.argv[1]) test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_modulefinder.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_modulefinder.py
import os import errno import importlib.machinery import py_compile import shutil import unittest import tempfile from test import support import modulefinder TEST_DIR = tempfile.mkdtemp() TEST_PATH = [TEST_DIR, os.path.dirname(tempfile.__file__)] # Each test description is a list of 5 items: # # 1. a module name that will be imported by modulefinder # 2. a list of module names that modulefinder is required to find # 3. a list of module names that modulefinder should complain # about because they are not found # 4. a list of module names that modulefinder should complain # about because they MAY be not found # 5. a string specifying packages to create; the format is obvious imo. # # Each package will be created in TEST_DIR, and TEST_DIR will be # removed after the tests again. # Modulefinder searches in a path that contains TEST_DIR, plus # the standard Lib directory. maybe_test = [ "a.module", ["a", "a.module", "sys", "b"], ["c"], ["b.something"], """\ a/__init__.py a/module.py from b import something from c import something b/__init__.py from sys import * """] maybe_test_new = [ "a.module", ["a", "a.module", "sys", "b", "__future__"], ["c"], ["b.something"], """\ a/__init__.py a/module.py from b import something from c import something b/__init__.py from __future__ import absolute_import from sys import * """] package_test = [ "a.module", ["a", "a.b", "a.c", "a.module", "mymodule", "sys"], ["blahblah", "c"], [], """\ mymodule.py a/__init__.py import blahblah from a import b import c a/module.py import sys from a import b as x from a.c import sillyname a/b.py a/c.py from a.module import x import mymodule as sillyname from sys import version_info """] absolute_import_test = [ "a.module", ["a", "a.module", "b", "b.x", "b.y", "b.z", "__future__", "sys", "gc"], ["blahblah", "z"], [], """\ mymodule.py a/__init__.py a/module.py from __future__ import absolute_import import sys # sys import blahblah # fails import gc # gc import b.x # b.x from b import y # b.y from b.z import * # b.z.* a/gc.py a/sys.py import mymodule a/b/__init__.py a/b/x.py a/b/y.py a/b/z.py b/__init__.py import z b/unused.py b/x.py b/y.py b/z.py """] relative_import_test = [ "a.module", ["__future__", "a", "a.module", "a.b", "a.b.y", "a.b.z", "a.b.c", "a.b.c.moduleC", "a.b.c.d", "a.b.c.e", "a.b.x", "gc"], [], [], """\ mymodule.py a/__init__.py from .b import y, z # a.b.y, a.b.z a/module.py from __future__ import absolute_import # __future__ import gc # gc a/gc.py a/sys.py a/b/__init__.py from ..b import x # a.b.x #from a.b.c import moduleC from .c import moduleC # a.b.moduleC a/b/x.py a/b/y.py a/b/z.py a/b/g.py a/b/c/__init__.py from ..c import e # a.b.c.e a/b/c/moduleC.py from ..c import d # a.b.c.d a/b/c/d.py a/b/c/e.py a/b/c/x.py """] relative_import_test_2 = [ "a.module", ["a", "a.module", "a.sys", "a.b", "a.b.y", "a.b.z", "a.b.c", "a.b.c.d", "a.b.c.e", "a.b.c.moduleC", "a.b.c.f", "a.b.x", "a.another"], [], [], """\ mymodule.py a/__init__.py from . import sys # a.sys a/another.py a/module.py from .b import y, z # a.b.y, a.b.z a/gc.py a/sys.py a/b/__init__.py from .c import moduleC # a.b.c.moduleC from .c import d # a.b.c.d a/b/x.py a/b/y.py a/b/z.py a/b/c/__init__.py from . import e # a.b.c.e a/b/c/moduleC.py # from . import f # a.b.c.f from .. import x # a.b.x from ... import another # a.another a/b/c/d.py a/b/c/e.py a/b/c/f.py """] relative_import_test_3 = [ "a.module", ["a", "a.module"], ["a.bar"], [], """\ a/__init__.py def foo(): pass a/module.py from . import foo from . import bar """] relative_import_test_4 = [ "a.module", ["a", "a.module"], [], [], """\ a/__init__.py def foo(): pass a/module.py from . import * """] bytecode_test = [ "a", ["a"], [], [], "" ] def open_file(path): dirname = os.path.dirname(path) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise return open(path, "w") def create_package(source): ofi = None try: for line in source.splitlines(): if line.startswith(" ") or line.startswith("\t"): ofi.write(line.strip() + "\n") else: if ofi: ofi.close() ofi = open_file(os.path.join(TEST_DIR, line.strip())) finally: if ofi: ofi.close() class ModuleFinderTest(unittest.TestCase): def _do_test(self, info, report=False, debug=0, replace_paths=[]): import_this, modules, missing, maybe_missing, source = info create_package(source) try: mf = modulefinder.ModuleFinder(path=TEST_PATH, debug=debug, replace_paths=replace_paths) mf.import_hook(import_this) if report: mf.report() ## # This wouldn't work in general when executed several times: ## opath = sys.path[:] ## sys.path = TEST_PATH ## try: ## __import__(import_this) ## except: ## import traceback; traceback.print_exc() ## sys.path = opath ## return modules = sorted(set(modules)) found = sorted(mf.modules) # check if we found what we expected, not more, not less self.assertEqual(found, modules) # check for missing and maybe missing modules bad, maybe = mf.any_missing_maybe() self.assertEqual(bad, missing) self.assertEqual(maybe, maybe_missing) finally: shutil.rmtree(TEST_DIR) def test_package(self): self._do_test(package_test) def test_maybe(self): self._do_test(maybe_test) def test_maybe_new(self): self._do_test(maybe_test_new) def test_absolute_imports(self): self._do_test(absolute_import_test) def test_relative_imports(self): self._do_test(relative_import_test) def test_relative_imports_2(self): self._do_test(relative_import_test_2) def test_relative_imports_3(self): self._do_test(relative_import_test_3) def test_relative_imports_4(self): self._do_test(relative_import_test_4) def test_bytecode(self): base_path = os.path.join(TEST_DIR, 'a') source_path = base_path + importlib.machinery.SOURCE_SUFFIXES[0] bytecode_path = base_path + importlib.machinery.BYTECODE_SUFFIXES[0] with open_file(source_path) as file: file.write('testing_modulefinder = True\n') py_compile.compile(source_path, cfile=bytecode_path) os.remove(source_path) self._do_test(bytecode_test) def test_replace_paths(self): old_path = os.path.join(TEST_DIR, 'a', 'module.py') new_path = os.path.join(TEST_DIR, 'a', 'spam.py') with support.captured_stdout() as output: self._do_test(maybe_test, debug=2, replace_paths=[(old_path, new_path)]) output = output.getvalue() expected = "co_filename %r changed to %r" % (old_path, new_path) self.assertIn(expected, output) def test_extended_opargs(self): extended_opargs_test = [ "a", ["a", "b"], [], [], """\ a.py %r import b b.py """ % list(range(2**16))] # 2**16 constants self._do_test(extended_opargs_test) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_itertools.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_itertools.py
import unittest from test import support from itertools import * import weakref from decimal import Decimal from fractions import Fraction import operator import random import copy import pickle from functools import reduce import sys import struct import threading maxsize = support.MAX_Py_ssize_t minsize = -maxsize-1 def lzip(*args): return list(zip(*args)) def onearg(x): 'Test function of one argument' return 2*x def errfunc(*args): 'Test function that raises an error' raise ValueError def gen3(): 'Non-restartable source sequence' for i in (0, 1, 2): yield i def isEven(x): 'Test predicate' return x%2==0 def isOdd(x): 'Test predicate' return x%2==1 def tupleize(*args): return args def irange(n): for i in range(n): yield i class StopNow: 'Class emulating an empty iterable.' def __iter__(self): return self def __next__(self): raise StopIteration def take(n, seq): 'Convenience function for partially consuming a long of infinite iterable' return list(islice(seq, n)) def prod(iterable): return reduce(operator.mul, iterable, 1) def fact(n): 'Factorial' return prod(range(1, n+1)) # root level methods for pickling ability def testR(r): return r[0] def testR2(r): return r[2] def underten(x): return x<10 picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto)) for proto in range(pickle.HIGHEST_PROTOCOL + 1)] class TestBasicOps(unittest.TestCase): def pickletest(self, protocol, it, stop=4, take=1, compare=None): """Test that an iterator is the same after pickling, also when part-consumed""" def expand(it, i=0): # Recursively expand iterables, within sensible bounds if i > 10: raise RuntimeError("infinite recursion encountered") if isinstance(it, str): return it try: l = list(islice(it, stop)) except TypeError: return it # can't expand it return [expand(e, i+1) for e in l] # Test the initial copy against the original dump = pickle.dumps(it, protocol) i2 = pickle.loads(dump) self.assertEqual(type(it), type(i2)) a, b = expand(it), expand(i2) self.assertEqual(a, b) if compare: c = expand(compare) self.assertEqual(a, c) # Take from the copy, and create another copy and compare them. i3 = pickle.loads(dump) took = 0 try: for i in range(take): next(i3) took += 1 except StopIteration: pass #in case there is less data than 'take' dump = pickle.dumps(i3, protocol) i4 = pickle.loads(dump) a, b = expand(i3), expand(i4) self.assertEqual(a, b) if compare: c = expand(compare[took:]) self.assertEqual(a, c); def test_accumulate(self): self.assertEqual(list(accumulate(range(10))), # one positional arg [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) self.assertEqual(list(accumulate(iterable=range(10))), # kw arg [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) for typ in int, complex, Decimal, Fraction: # multiple types self.assertEqual( list(accumulate(map(typ, range(10)))), list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]))) self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric self.assertEqual(list(accumulate([])), []) # empty iterable self.assertEqual(list(accumulate([7])), [7]) # iterable of length one self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args self.assertRaises(TypeError, accumulate) # too few args self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6] self.assertEqual(list(accumulate(s, min)), [2, 2, 2, 2, 2, 0, 0, 0, 0, 0]) self.assertEqual(list(accumulate(s, max)), [2, 8, 9, 9, 9, 9, 9, 9, 9, 9]) self.assertEqual(list(accumulate(s, operator.mul)), [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0]) with self.assertRaises(TypeError): list(accumulate(s, chr)) # unary-operation for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, accumulate(range(10))) # test pickling def test_chain(self): def chain2(*iterables): 'Pure python version in the docs' for it in iterables: for element in it: yield element for c in (chain, chain2): self.assertEqual(list(c('abc', 'def')), list('abcdef')) self.assertEqual(list(c('abc')), list('abc')) self.assertEqual(list(c('')), []) self.assertEqual(take(4, c('abc', 'def')), list('abcd')) self.assertRaises(TypeError, list,c(2, 3)) def test_chain_from_iterable(self): self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef')) self.assertEqual(list(chain.from_iterable(['abc'])), list('abc')) self.assertEqual(list(chain.from_iterable([''])), []) self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd')) self.assertRaises(TypeError, list, chain.from_iterable([2, 3])) def test_chain_reducible(self): for oper in [copy.deepcopy] + picklecopiers: it = chain('abc', 'def') self.assertEqual(list(oper(it)), list('abcdef')) self.assertEqual(next(it), 'a') self.assertEqual(list(oper(it)), list('bcdef')) self.assertEqual(list(oper(chain(''))), []) self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd')) self.assertRaises(TypeError, list, oper(chain(2, 3))) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef')) def test_chain_setstate(self): self.assertRaises(TypeError, chain().__setstate__, ()) self.assertRaises(TypeError, chain().__setstate__, []) self.assertRaises(TypeError, chain().__setstate__, 0) self.assertRaises(TypeError, chain().__setstate__, ([],)) self.assertRaises(TypeError, chain().__setstate__, (iter([]), [])) it = chain() it.__setstate__((iter(['abc', 'def']),)) self.assertEqual(list(it), ['a', 'b', 'c', 'd', 'e', 'f']) it = chain() it.__setstate__((iter(['abc', 'def']), iter(['ghi']))) self.assertEqual(list(it), ['ghi', 'a', 'b', 'c', 'd', 'e', 'f']) def test_combinations(self): self.assertRaises(TypeError, combinations, 'abc') # missing r argument self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, combinations, None) # pool is not iterable self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative for op in [lambda a:a] + picklecopiers: self.assertEqual(list(op(combinations('abc', 32))), []) # r > n self.assertEqual(list(op(combinations('ABCD', 2))), [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) testIntermediate = combinations('ABCD', 2) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) self.assertEqual(list(op(combinations(range(4), 3))), [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) testIntermediate = combinations(range(4), 3) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [(0,1,3), (0,2,3), (1,2,3)]) def combinations1(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def combinations2(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) for indices in permutations(range(n), r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) def combinations3(iterable, r): 'Pure python version from cwr()' pool = tuple(iterable) n = len(pool) for indices in combinations_with_replacement(range(n), r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(combinations(values, r)) self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order for c in result: self.assertEqual(len(c), r) # r-length combinations self.assertEqual(len(set(c)), r) # no duplicate elements self.assertEqual(list(c), sorted(c)) # keep original ordering self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(list(c), [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, combinations(values, r)) # test pickling @support.bigaddrspacetest def test_combinations_overflow(self): with self.assertRaises((OverflowError, MemoryError)): combinations("AA", 2**29) # Test implementation detail: tuple re-use @support.impl_detail("tuple reuse is specific to CPython") def test_combinations_tuple_reuse(self): self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1) def test_combinations_with_replacement(self): cwr = combinations_with_replacement self.assertRaises(TypeError, cwr, 'abc') # missing r argument self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, cwr, None) # pool is not iterable self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative for op in [lambda a:a] + picklecopiers: self.assertEqual(list(op(cwr('ABC', 2))), [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]) testIntermediate = cwr('ABC', 2) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]) def cwr1(iterable, r): 'Pure python version shown in the docs' # number items returned: (n+r-1)! / r! / (n-1)! when n>0 pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices) def cwr2(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) for indices in product(range(n), repeat=r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) def numcombs(n, r): if not n: return 0 if r else 1 return fact(n+r-1) / fact(r)/ fact(n-1) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(cwr(values, r)) self.assertEqual(len(result), numcombs(n, r)) # right number of combs self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order regular_combs = list(combinations(values, r)) # compare to combs without replacement if n == 0 or r <= 1: self.assertEqual(result, regular_combs) # cases that should be identical else: self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs for c in result: self.assertEqual(len(c), r) # r-length combinations noruns = [k for k,v in groupby(c)] # combo without consecutive repeats self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive self.assertEqual(list(c), sorted(c)) # keep original ordering self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(noruns, [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, cwr(values,r)) # test pickling @support.bigaddrspacetest def test_combinations_with_replacement_overflow(self): with self.assertRaises((OverflowError, MemoryError)): combinations_with_replacement("AA", 2**30) # Test implementation detail: tuple re-use @support.impl_detail("tuple reuse is specific to CPython") def test_combinations_with_replacement_tuple_reuse(self): cwr = combinations_with_replacement self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1) def test_permutations(self): self.assertRaises(TypeError, permutations) # too few arguments self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, permutations, None) # pool is not iterable self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative self.assertEqual(list(permutations('abc', 32)), []) # r > n self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None self.assertEqual(list(permutations(range(3), 2)), [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]) def permutations1(iterable, r=None): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = list(range(n)) cycles = list(range(n-r+1, n+1))[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return def permutations2(iterable, r=None): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(permutations(values, r)) self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order for p in result: self.assertEqual(len(p), r) # r-length permutations self.assertEqual(len(set(p)), r) # no duplicate elements self.assertTrue(all(e in values for e in p)) # elements taken from input iterable self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version if r == n: self.assertEqual(result, list(permutations(values, None))) # test r as None self.assertEqual(result, list(permutations(values))) # test default r for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, permutations(values, r)) # test pickling @support.bigaddrspacetest def test_permutations_overflow(self): with self.assertRaises((OverflowError, MemoryError)): permutations("A", 2**30) @support.impl_detail("tuple reuse is specific to CPython") def test_permutations_tuple_reuse(self): self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1) def test_combinatorics(self): # Test relationships between product(), permutations(), # combinations() and combinations_with_replacement(). for n in range(6): s = 'ABCDEFG'[:n] for r in range(8): prod = list(product(s, repeat=r)) cwr = list(combinations_with_replacement(s, r)) perm = list(permutations(s, r)) comb = list(combinations(s, r)) # Check size self.assertEqual(len(prod), n**r) self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r)) self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r)) self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # Check lexicographic order without repeated tuples self.assertEqual(prod, sorted(set(prod))) self.assertEqual(cwr, sorted(set(cwr))) self.assertEqual(perm, sorted(set(perm))) self.assertEqual(comb, sorted(set(comb))) # Check interrelationships self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm def test_compress(self): self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF')) self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF')) self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list('')) self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF')) self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC')) self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC')) n = 10000 data = chain.from_iterable(repeat(range(6), n)) selectors = chain.from_iterable(repeat((0, 1))) self.assertEqual(list(compress(data, selectors)), [1,3,5] * n) self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable self.assertRaises(TypeError, compress, range(6)) # too few args self.assertRaises(TypeError, compress, range(6), None) # too many args # check copy, deepcopy, pickle for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers: for data, selectors, result1, result2 in [ ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'), ('ABCDEF', [0,0,0,0,0,0], '', ''), ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'), ('ABCDEF', [1,0,1], 'AC', 'C'), ('ABC', [0,1,1,1,1,1], 'BC', 'C'), ]: self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1)) self.assertEqual(list(op(compress(data, selectors))), list(result1)) testIntermediate = compress(data, selectors) if result1: next(testIntermediate) self.assertEqual(list(op(testIntermediate)), list(result2)) def test_count(self): self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)]) self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)]) self.assertRaises(TypeError, count, 2, 3, 4) self.assertRaises(TypeError, count, 'a') self.assertEqual(take(10, count(maxsize-5)), list(range(maxsize-5, maxsize+5))) self.assertEqual(take(10, count(-maxsize-5)), list(range(-maxsize-5, -maxsize+5))) self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25]) self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j]) self.assertEqual(take(3, count(Decimal('1.1'))), [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')]) self.assertEqual(take(3, count(Fraction(2, 3))), [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)]) BIGINT = 1<<1000 self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2]) c = count(3) self.assertEqual(repr(c), 'count(3)') next(c) self.assertEqual(repr(c), 'count(4)') c = count(-9) self.assertEqual(repr(c), 'count(-9)') next(c) self.assertEqual(next(c), -8) self.assertEqual(repr(count(10.25)), 'count(10.25)') self.assertEqual(repr(count(10.0)), 'count(10.0)') self.assertEqual(type(next(count(10.0))), float) for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5): # Test repr r1 = repr(count(i)) r2 = 'count(%r)'.__mod__(i) self.assertEqual(r1, r2) # check copy, deepcopy, pickle for value in -3, 3, maxsize-5, maxsize+5: c = count(value) self.assertEqual(next(copy.copy(c)), value) self.assertEqual(next(copy.deepcopy(c)), value) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, count(value)) #check proper internal error handling for large "step' sizes count(1, maxsize+5); sys.exc_info() def test_count_with_stride(self): self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(lzip('abc',count(start=2,step=3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(lzip('abc',count(step=-1)), [('a', 0), ('b', -1), ('c', -2)]) self.assertRaises(TypeError, count, 'a', 'b') self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)]) self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)]) self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3))) self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3))) self.assertEqual(take(3, count(10, maxsize+5)), list(range(10, 10+3*(maxsize+5), maxsize+5))) self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5]) self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j]) self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))), [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')]) self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))), [Fraction(2,3), Fraction(17,21), Fraction(20,21)]) BIGINT = 1<<1000 self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT]) self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0])) c = count(3, 5) self.assertEqual(repr(c), 'count(3, 5)') next(c) self.assertEqual(repr(c), 'count(8, 5)') c = count(-9, 0) self.assertEqual(repr(c), 'count(-9, 0)') next(c) self.assertEqual(repr(c), 'count(-9, 0)') c = count(-9, -3) self.assertEqual(repr(c), 'count(-9, -3)') next(c) self.assertEqual(repr(c), 'count(-12, -3)') self.assertEqual(repr(c), 'count(-12, -3)') self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)') self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0 self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)') c = count(10, 1.0) self.assertEqual(type(next(c)), int) self.assertEqual(type(next(c)), float) for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5): for j in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5): # Test repr r1 = repr(count(i, j)) if j == 1: r2 = ('count(%r)' % i) else: r2 = ('count(%r, %r)' % (i, j)) self.assertEqual(r1, r2) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, count(i, j)) def test_cycle(self): self.assertEqual(take(10, cycle('abc')), list('abcabcabca')) self.assertEqual(list(cycle('')), []) self.assertRaises(TypeError, cycle) self.assertRaises(TypeError, cycle, 5) self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0]) # check copy, deepcopy, pickle c = cycle('abc') self.assertEqual(next(c), 'a') #simple copy currently not supported, because __reduce__ returns #an internal iterator #self.assertEqual(take(10, copy.copy(c)), list('bcabcabcab')) self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab')) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))), list('bcabcabcab')) next(c) self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))), list('cabcabcabc')) next(c) next(c) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, cycle('abc')) for proto in range(pickle.HIGHEST_PROTOCOL + 1): # test with partial consumed input iterable it = iter('abcde') c = cycle(it) _ = [next(c) for i in range(2)] # consume 2 of 5 inputs p = pickle.dumps(c, proto) d = pickle.loads(p) # rebuild the cycle object self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab')) # test with completely consumed input iterable it = iter('abcde') c = cycle(it) _ = [next(c) for i in range(7)] # consume 7 of 5 inputs p = pickle.dumps(c, proto) d = pickle.loads(p) # rebuild the cycle object self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab')) def test_cycle_setstate(self): # Verify both modes for restoring state # Mode 0 is efficient. It uses an incompletely consumed input # iterator to build a cycle object and then passes in state with # a list of previously consumed values. There is no data # overlap between the two. c = cycle('defg') c.__setstate__((list('abc'), 0)) self.assertEqual(take(20, c), list('defgabcdefgabcdefgab')) # Mode 1 is inefficient. It starts with a cycle object built # from an iterator over the remaining elements in a partial # cycle and then passes in state with all of the previously # seen values (this overlaps values included in the iterator). c = cycle('defg') c.__setstate__((list('abcdefg'), 1)) self.assertEqual(take(20, c), list('defgabcdefgabcdefgab')) # The first argument to setstate needs to be a tuple with self.assertRaises(TypeError): cycle('defg').__setstate__([list('abcdefg'), 0]) # The first argument in the setstate tuple must be a list with self.assertRaises(TypeError): c = cycle('defg') c.__setstate__((tuple('defg'), 0)) take(20, c) # The second argument in the setstate tuple must be an int with self.assertRaises(TypeError): cycle('defg').__setstate__((list('abcdefg'), 'x')) self.assertRaises(TypeError, cycle('').__setstate__, ()) self.assertRaises(TypeError, cycle('').__setstate__, ([],)) def test_groupby(self): # Check whether it accepts arguments correctly
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dictviews.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dictviews.py
import collections.abc import copy import pickle import sys import unittest class DictSetTest(unittest.TestCase): def test_constructors_not_callable(self): kt = type({}.keys()) self.assertRaises(TypeError, kt, {}) self.assertRaises(TypeError, kt) it = type({}.items()) self.assertRaises(TypeError, it, {}) self.assertRaises(TypeError, it) vt = type({}.values()) self.assertRaises(TypeError, vt, {}) self.assertRaises(TypeError, vt) def test_dict_keys(self): d = {1: 10, "a": "ABC"} keys = d.keys() self.assertEqual(len(keys), 2) self.assertEqual(set(keys), {1, "a"}) self.assertEqual(keys, {1, "a"}) self.assertNotEqual(keys, {1, "a", "b"}) self.assertNotEqual(keys, {1, "b"}) self.assertNotEqual(keys, {1}) self.assertNotEqual(keys, 42) self.assertIn(1, keys) self.assertIn("a", keys) self.assertNotIn(10, keys) self.assertNotIn("Z", keys) self.assertEqual(d.keys(), d.keys()) e = {1: 11, "a": "def"} self.assertEqual(d.keys(), e.keys()) del e["a"] self.assertNotEqual(d.keys(), e.keys()) def test_dict_items(self): d = {1: 10, "a": "ABC"} items = d.items() self.assertEqual(len(items), 2) self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) self.assertEqual(items, {(1, 10), ("a", "ABC")}) self.assertNotEqual(items, {(1, 10), ("a", "ABC"), "junk"}) self.assertNotEqual(items, {(1, 10), ("a", "def")}) self.assertNotEqual(items, {(1, 10)}) self.assertNotEqual(items, 42) self.assertIn((1, 10), items) self.assertIn(("a", "ABC"), items) self.assertNotIn((1, 11), items) self.assertNotIn(1, items) self.assertNotIn((), items) self.assertNotIn((1,), items) self.assertNotIn((1, 2, 3), items) self.assertEqual(d.items(), d.items()) e = d.copy() self.assertEqual(d.items(), e.items()) e["a"] = "def" self.assertNotEqual(d.items(), e.items()) def test_dict_mixed_keys_items(self): d = {(1, 1): 11, (2, 2): 22} e = {1: 1, 2: 2} self.assertEqual(d.keys(), e.items()) self.assertNotEqual(d.items(), e.keys()) def test_dict_values(self): d = {1: 10, "a": "ABC"} values = d.values() self.assertEqual(set(values), {10, "ABC"}) self.assertEqual(len(values), 2) def test_dict_repr(self): d = {1: 10, "a": "ABC"} self.assertIsInstance(repr(d), str) r = repr(d.items()) self.assertIsInstance(r, str) self.assertTrue(r == "dict_items([('a', 'ABC'), (1, 10)])" or r == "dict_items([(1, 10), ('a', 'ABC')])") r = repr(d.keys()) self.assertIsInstance(r, str) self.assertTrue(r == "dict_keys(['a', 1])" or r == "dict_keys([1, 'a'])") r = repr(d.values()) self.assertIsInstance(r, str) self.assertTrue(r == "dict_values(['ABC', 10])" or r == "dict_values([10, 'ABC'])") def test_keys_set_operations(self): d1 = {'a': 1, 'b': 2} d2 = {'b': 3, 'c': 2} d3 = {'d': 4, 'e': 5} self.assertEqual(d1.keys() & d1.keys(), {'a', 'b'}) self.assertEqual(d1.keys() & d2.keys(), {'b'}) self.assertEqual(d1.keys() & d3.keys(), set()) self.assertEqual(d1.keys() & set(d1.keys()), {'a', 'b'}) self.assertEqual(d1.keys() & set(d2.keys()), {'b'}) self.assertEqual(d1.keys() & set(d3.keys()), set()) self.assertEqual(d1.keys() & tuple(d1.keys()), {'a', 'b'}) self.assertEqual(d1.keys() | d1.keys(), {'a', 'b'}) self.assertEqual(d1.keys() | d2.keys(), {'a', 'b', 'c'}) self.assertEqual(d1.keys() | d3.keys(), {'a', 'b', 'd', 'e'}) self.assertEqual(d1.keys() | set(d1.keys()), {'a', 'b'}) self.assertEqual(d1.keys() | set(d2.keys()), {'a', 'b', 'c'}) self.assertEqual(d1.keys() | set(d3.keys()), {'a', 'b', 'd', 'e'}) self.assertEqual(d1.keys() | (1, 2), {'a', 'b', 1, 2}) self.assertEqual(d1.keys() ^ d1.keys(), set()) self.assertEqual(d1.keys() ^ d2.keys(), {'a', 'c'}) self.assertEqual(d1.keys() ^ d3.keys(), {'a', 'b', 'd', 'e'}) self.assertEqual(d1.keys() ^ set(d1.keys()), set()) self.assertEqual(d1.keys() ^ set(d2.keys()), {'a', 'c'}) self.assertEqual(d1.keys() ^ set(d3.keys()), {'a', 'b', 'd', 'e'}) self.assertEqual(d1.keys() ^ tuple(d2.keys()), {'a', 'c'}) self.assertEqual(d1.keys() - d1.keys(), set()) self.assertEqual(d1.keys() - d2.keys(), {'a'}) self.assertEqual(d1.keys() - d3.keys(), {'a', 'b'}) self.assertEqual(d1.keys() - set(d1.keys()), set()) self.assertEqual(d1.keys() - set(d2.keys()), {'a'}) self.assertEqual(d1.keys() - set(d3.keys()), {'a', 'b'}) self.assertEqual(d1.keys() - (0, 1), {'a', 'b'}) self.assertFalse(d1.keys().isdisjoint(d1.keys())) self.assertFalse(d1.keys().isdisjoint(d2.keys())) self.assertFalse(d1.keys().isdisjoint(list(d2.keys()))) self.assertFalse(d1.keys().isdisjoint(set(d2.keys()))) self.assertTrue(d1.keys().isdisjoint({'x', 'y', 'z'})) self.assertTrue(d1.keys().isdisjoint(['x', 'y', 'z'])) self.assertTrue(d1.keys().isdisjoint(set(['x', 'y', 'z']))) self.assertTrue(d1.keys().isdisjoint(set(['x', 'y']))) self.assertTrue(d1.keys().isdisjoint(['x', 'y'])) self.assertTrue(d1.keys().isdisjoint({})) self.assertTrue(d1.keys().isdisjoint(d3.keys())) de = {} self.assertTrue(de.keys().isdisjoint(set())) self.assertTrue(de.keys().isdisjoint([])) self.assertTrue(de.keys().isdisjoint(de.keys())) self.assertTrue(de.keys().isdisjoint([1])) def test_items_set_operations(self): d1 = {'a': 1, 'b': 2} d2 = {'a': 2, 'b': 2} d3 = {'d': 4, 'e': 5} self.assertEqual( d1.items() & d1.items(), {('a', 1), ('b', 2)}) self.assertEqual(d1.items() & d2.items(), {('b', 2)}) self.assertEqual(d1.items() & d3.items(), set()) self.assertEqual(d1.items() & set(d1.items()), {('a', 1), ('b', 2)}) self.assertEqual(d1.items() & set(d2.items()), {('b', 2)}) self.assertEqual(d1.items() & set(d3.items()), set()) self.assertEqual(d1.items() | d1.items(), {('a', 1), ('b', 2)}) self.assertEqual(d1.items() | d2.items(), {('a', 1), ('a', 2), ('b', 2)}) self.assertEqual(d1.items() | d3.items(), {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) self.assertEqual(d1.items() | set(d1.items()), {('a', 1), ('b', 2)}) self.assertEqual(d1.items() | set(d2.items()), {('a', 1), ('a', 2), ('b', 2)}) self.assertEqual(d1.items() | set(d3.items()), {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) self.assertEqual(d1.items() ^ d1.items(), set()) self.assertEqual(d1.items() ^ d2.items(), {('a', 1), ('a', 2)}) self.assertEqual(d1.items() ^ d3.items(), {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) self.assertEqual(d1.items() - d1.items(), set()) self.assertEqual(d1.items() - d2.items(), {('a', 1)}) self.assertEqual(d1.items() - d3.items(), {('a', 1), ('b', 2)}) self.assertEqual(d1.items() - set(d1.items()), set()) self.assertEqual(d1.items() - set(d2.items()), {('a', 1)}) self.assertEqual(d1.items() - set(d3.items()), {('a', 1), ('b', 2)}) self.assertFalse(d1.items().isdisjoint(d1.items())) self.assertFalse(d1.items().isdisjoint(d2.items())) self.assertFalse(d1.items().isdisjoint(list(d2.items()))) self.assertFalse(d1.items().isdisjoint(set(d2.items()))) self.assertTrue(d1.items().isdisjoint({'x', 'y', 'z'})) self.assertTrue(d1.items().isdisjoint(['x', 'y', 'z'])) self.assertTrue(d1.items().isdisjoint(set(['x', 'y', 'z']))) self.assertTrue(d1.items().isdisjoint(set(['x', 'y']))) self.assertTrue(d1.items().isdisjoint({})) self.assertTrue(d1.items().isdisjoint(d3.items())) de = {} self.assertTrue(de.items().isdisjoint(set())) self.assertTrue(de.items().isdisjoint([])) self.assertTrue(de.items().isdisjoint(de.items())) self.assertTrue(de.items().isdisjoint([1])) def test_recursive_repr(self): d = {} d[42] = d.values() r = repr(d) # Cannot perform a stronger test, as the contents of the repr # are implementation-dependent. All we can say is that we # want a str result, not an exception of any sort. self.assertIsInstance(r, str) d[42] = d.items() r = repr(d) # Again. self.assertIsInstance(r, str) def test_deeply_nested_repr(self): d = {} for i in range(sys.getrecursionlimit() + 100): d = {42: d.values()} self.assertRaises(RecursionError, repr, d) def test_copy(self): d = {1: 10, "a": "ABC"} self.assertRaises(TypeError, copy.copy, d.keys()) self.assertRaises(TypeError, copy.copy, d.values()) self.assertRaises(TypeError, copy.copy, d.items()) def test_compare_error(self): class Exc(Exception): pass class BadEq: def __hash__(self): return 7 def __eq__(self, other): raise Exc k1, k2 = BadEq(), BadEq() v1, v2 = BadEq(), BadEq() d = {k1: v1} self.assertIn(k1, d) self.assertIn(k1, d.keys()) self.assertIn(v1, d.values()) self.assertIn((k1, v1), d.items()) self.assertRaises(Exc, d.__contains__, k2) self.assertRaises(Exc, d.keys().__contains__, k2) self.assertRaises(Exc, d.items().__contains__, (k2, v1)) self.assertRaises(Exc, d.items().__contains__, (k1, v2)) with self.assertRaises(Exc): v2 in d.values() def test_pickle(self): d = {1: 10, "a": "ABC"} for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.assertRaises((TypeError, pickle.PicklingError), pickle.dumps, d.keys(), proto) self.assertRaises((TypeError, pickle.PicklingError), pickle.dumps, d.values(), proto) self.assertRaises((TypeError, pickle.PicklingError), pickle.dumps, d.items(), proto) def test_abc_registry(self): d = dict(a=1) self.assertIsInstance(d.keys(), collections.abc.KeysView) self.assertIsInstance(d.keys(), collections.abc.MappingView) self.assertIsInstance(d.keys(), collections.abc.Set) self.assertIsInstance(d.keys(), collections.abc.Sized) self.assertIsInstance(d.keys(), collections.abc.Iterable) self.assertIsInstance(d.keys(), collections.abc.Container) self.assertIsInstance(d.values(), collections.abc.ValuesView) self.assertIsInstance(d.values(), collections.abc.MappingView) self.assertIsInstance(d.values(), collections.abc.Sized) self.assertIsInstance(d.items(), collections.abc.ItemsView) self.assertIsInstance(d.items(), collections.abc.MappingView) self.assertIsInstance(d.items(), collections.abc.Set) self.assertIsInstance(d.items(), collections.abc.Sized) self.assertIsInstance(d.items(), collections.abc.Iterable) self.assertIsInstance(d.items(), collections.abc.Container) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_imaplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_imaplib.py
from test import support from contextlib import contextmanager import errno import imaplib import os.path import socketserver import time import calendar import threading import socket from test.support import (reap_threads, verbose, transient_internet, run_with_tz, run_with_locale, cpython_only) import unittest from unittest import mock from datetime import datetime, timezone, timedelta try: import ssl except ImportError: ssl = None CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert3.pem") CAFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "pycacert.pem") class TestImaplib(unittest.TestCase): def test_Internaldate2tuple(self): t0 = calendar.timegm((2000, 1, 1, 0, 0, 0, -1, -1, -1)) tt = imaplib.Internaldate2tuple( b'25 (INTERNALDATE "01-Jan-2000 00:00:00 +0000")') self.assertEqual(time.mktime(tt), t0) tt = imaplib.Internaldate2tuple( b'25 (INTERNALDATE "01-Jan-2000 11:30:00 +1130")') self.assertEqual(time.mktime(tt), t0) tt = imaplib.Internaldate2tuple( b'25 (INTERNALDATE "31-Dec-1999 12:30:00 -1130")') self.assertEqual(time.mktime(tt), t0) @run_with_tz('MST+07MDT,M4.1.0,M10.5.0') def test_Internaldate2tuple_issue10941(self): self.assertNotEqual(imaplib.Internaldate2tuple( b'25 (INTERNALDATE "02-Apr-2000 02:30:00 +0000")'), imaplib.Internaldate2tuple( b'25 (INTERNALDATE "02-Apr-2000 03:30:00 +0000")')) def timevalues(self): return [2000000000, 2000000000.0, time.localtime(2000000000), (2033, 5, 18, 5, 33, 20, -1, -1, -1), (2033, 5, 18, 5, 33, 20, -1, -1, 1), datetime.fromtimestamp(2000000000, timezone(timedelta(0, 2 * 60 * 60))), '"18-May-2033 05:33:20 +0200"'] @run_with_locale('LC_ALL', 'de_DE', 'fr_FR') # DST rules included to work around quirk where the Gnu C library may not # otherwise restore the previous time zone @run_with_tz('STD-1DST,M3.2.0,M11.1.0') def test_Time2Internaldate(self): expected = '"18-May-2033 05:33:20 +0200"' for t in self.timevalues(): internal = imaplib.Time2Internaldate(t) self.assertEqual(internal, expected) def test_that_Time2Internaldate_returns_a_result(self): # Without tzset, we can check only that it successfully # produces a result, not the correctness of the result itself, # since the result depends on the timezone the machine is in. for t in self.timevalues(): imaplib.Time2Internaldate(t) def test_imap4_host_default_value(self): # Check whether the IMAP4_PORT is truly unavailable. with socket.socket() as s: try: s.connect(('', imaplib.IMAP4_PORT)) self.skipTest( "Cannot run the test with local IMAP server running.") except socket.error: pass # This is the exception that should be raised. expected_errnos = support.get_socket_conn_refused_errs() with self.assertRaises(OSError) as cm: imaplib.IMAP4() self.assertIn(cm.exception.errno, expected_errnos) if ssl: class SecureTCPServer(socketserver.TCPServer): def get_request(self): newsocket, fromaddr = self.socket.accept() context = ssl.SSLContext() context.load_cert_chain(CERTFILE) connstream = context.wrap_socket(newsocket, server_side=True) return connstream, fromaddr IMAP4_SSL = imaplib.IMAP4_SSL else: class SecureTCPServer: pass IMAP4_SSL = None class SimpleIMAPHandler(socketserver.StreamRequestHandler): timeout = 1 continuation = None capabilities = '' def setup(self): super().setup() self.server.logged = None def _send(self, message): if verbose: print("SENT: %r" % message.strip()) self.wfile.write(message) def _send_line(self, message): self._send(message + b'\r\n') def _send_textline(self, message): self._send_line(message.encode('ASCII')) def _send_tagged(self, tag, code, message): self._send_textline(' '.join((tag, code, message))) def handle(self): # Send a welcome message. self._send_textline('* OK IMAP4rev1') while 1: # Gather up input until we receive a line terminator or we timeout. # Accumulate read(1) because it's simpler to handle the differences # between naked sockets and SSL sockets. line = b'' while 1: try: part = self.rfile.read(1) if part == b'': # Naked sockets return empty strings.. return line += part except OSError: # ..but SSLSockets raise exceptions. return if line.endswith(b'\r\n'): break if verbose: print('GOT: %r' % line.strip()) if self.continuation: try: self.continuation.send(line) except StopIteration: self.continuation = None continue splitline = line.decode('ASCII').split() tag = splitline[0] cmd = splitline[1] args = splitline[2:] if hasattr(self, 'cmd_' + cmd): continuation = getattr(self, 'cmd_' + cmd)(tag, args) if continuation: self.continuation = continuation next(continuation) else: self._send_tagged(tag, 'BAD', cmd + ' unknown') def cmd_CAPABILITY(self, tag, args): caps = ('IMAP4rev1 ' + self.capabilities if self.capabilities else 'IMAP4rev1') self._send_textline('* CAPABILITY ' + caps) self._send_tagged(tag, 'OK', 'CAPABILITY completed') def cmd_LOGOUT(self, tag, args): self.server.logged = None self._send_textline('* BYE IMAP4ref1 Server logging out') self._send_tagged(tag, 'OK', 'LOGOUT completed') def cmd_LOGIN(self, tag, args): self.server.logged = args[0] self._send_tagged(tag, 'OK', 'LOGIN completed') class NewIMAPTestsMixin(): client = None def _setup(self, imap_handler, connect=True): """ Sets up imap_handler for tests. imap_handler should inherit from either: - SimpleIMAPHandler - for testing IMAP commands, - socketserver.StreamRequestHandler - if raw access to stream is needed. Returns (client, server). """ class TestTCPServer(self.server_class): def handle_error(self, request, client_address): """ End request and raise the error if one occurs. """ self.close_request(request) self.server_close() raise self.addCleanup(self._cleanup) self.server = self.server_class((support.HOST, 0), imap_handler) self.thread = threading.Thread( name=self._testMethodName+'-server', target=self.server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval': 0.01}) self.thread.daemon = True # In case this function raises. self.thread.start() if connect: self.client = self.imap_class(*self.server.server_address) return self.client, self.server def _cleanup(self): """ Cleans up the test server. This method should not be called manually, it is added to the cleanup queue in the _setup method already. """ # if logout was called already we'd raise an exception trying to # shutdown the client once again if self.client is not None and self.client.state != 'LOGOUT': self.client.shutdown() # cleanup the server self.server.shutdown() self.server.server_close() support.join_thread(self.thread, 3.0) # Explicitly clear the attribute to prevent dangling thread self.thread = None def test_EOF_without_complete_welcome_message(self): # http://bugs.python.org/issue5949 class EOFHandler(socketserver.StreamRequestHandler): def handle(self): self.wfile.write(b'* OK') _, server = self._setup(EOFHandler, connect=False) self.assertRaises(imaplib.IMAP4.abort, self.imap_class, *server.server_address) def test_line_termination(self): class BadNewlineHandler(SimpleIMAPHandler): def cmd_CAPABILITY(self, tag, args): self._send(b'* CAPABILITY IMAP4rev1 AUTH\n') self._send_tagged(tag, 'OK', 'CAPABILITY completed') _, server = self._setup(BadNewlineHandler, connect=False) self.assertRaises(imaplib.IMAP4.abort, self.imap_class, *server.server_address) def test_enable_raises_error_if_not_AUTH(self): class EnableHandler(SimpleIMAPHandler): capabilities = 'AUTH ENABLE UTF8=ACCEPT' client, _ = self._setup(EnableHandler) self.assertFalse(client.utf8_enabled) with self.assertRaisesRegex(imaplib.IMAP4.error, 'ENABLE.*NONAUTH'): client.enable('foo') self.assertFalse(client.utf8_enabled) def test_enable_raises_error_if_no_capability(self): client, _ = self._setup(SimpleIMAPHandler) with self.assertRaisesRegex(imaplib.IMAP4.error, 'does not support ENABLE'): client.enable('foo') def test_enable_UTF8_raises_error_if_not_supported(self): client, _ = self._setup(SimpleIMAPHandler) typ, data = client.login('user', 'pass') self.assertEqual(typ, 'OK') with self.assertRaisesRegex(imaplib.IMAP4.error, 'does not support ENABLE'): client.enable('UTF8=ACCEPT') def test_enable_UTF8_True_append(self): class UTF8AppendServer(SimpleIMAPHandler): capabilities = 'ENABLE UTF8=ACCEPT' def cmd_ENABLE(self, tag, args): self._send_tagged(tag, 'OK', 'ENABLE successful') def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') def cmd_APPEND(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'okay') client, server = self._setup(UTF8AppendServer) self.assertEqual(client._encoding, 'ascii') code, _ = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' code, _ = client.enable('UTF8=ACCEPT') self.assertEqual(code, 'OK') self.assertEqual(client._encoding, 'utf-8') msg_string = 'Subject: üñí©öðé' typ, data = client.append(None, None, None, msg_string.encode('utf-8')) self.assertEqual(typ, 'OK') self.assertEqual(server.response, ('UTF8 (%s)\r\n' % msg_string).encode('utf-8')) def test_search_disallows_charset_in_utf8_mode(self): class UTF8Server(SimpleIMAPHandler): capabilities = 'AUTH ENABLE UTF8=ACCEPT' def cmd_ENABLE(self, tag, args): self._send_tagged(tag, 'OK', 'ENABLE successful') def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') client, _ = self._setup(UTF8Server) typ, _ = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(typ, 'OK') typ, _ = client.enable('UTF8=ACCEPT') self.assertEqual(typ, 'OK') self.assertTrue(client.utf8_enabled) with self.assertRaisesRegex(imaplib.IMAP4.error, 'charset.*UTF8'): client.search('foo', 'bar') def test_bad_auth_name(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_tagged(tag, 'NO', 'unrecognized authentication type {}'.format(args[0])) client, _ = self._setup(MyServer) with self.assertRaisesRegex(imaplib.IMAP4.error, 'unrecognized authentication type METHOD'): client.authenticate('METHOD', lambda: 1) def test_invalid_authentication(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.response = yield self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] invalid') client, _ = self._setup(MyServer) with self.assertRaisesRegex(imaplib.IMAP4.error, r'\[AUTHENTICATIONFAILED\] invalid'): client.authenticate('MYAUTH', lambda x: b'fake') def test_valid_authentication_bytes(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') client, server = self._setup(MyServer) code, _ = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' def test_valid_authentication_plain_text(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') client, server = self._setup(MyServer) code, _ = client.authenticate('MYAUTH', lambda x: 'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' def test_login_cram_md5_bytes(self): class AuthHandler(SimpleIMAPHandler): capabilities = 'LOGINDISABLED AUTH=CRAM-MD5' def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm' 'VzdG9uLm1jaS5uZXQ=') r = yield if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT' b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'): self._send_tagged(tag, 'OK', 'CRAM-MD5 successful') else: self._send_tagged(tag, 'NO', 'No access') client, _ = self._setup(AuthHandler) self.assertTrue('AUTH=CRAM-MD5' in client.capabilities) ret, _ = client.login_cram_md5("tim", b"tanstaaftanstaaf") self.assertEqual(ret, "OK") def test_login_cram_md5_plain_text(self): class AuthHandler(SimpleIMAPHandler): capabilities = 'LOGINDISABLED AUTH=CRAM-MD5' def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm' 'VzdG9uLm1jaS5uZXQ=') r = yield if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT' b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'): self._send_tagged(tag, 'OK', 'CRAM-MD5 successful') else: self._send_tagged(tag, 'NO', 'No access') client, _ = self._setup(AuthHandler) self.assertTrue('AUTH=CRAM-MD5' in client.capabilities) ret, _ = client.login_cram_md5("tim", "tanstaaftanstaaf") self.assertEqual(ret, "OK") def test_aborted_authentication(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.response = yield if self.response == b'*\r\n': self._send_tagged( tag, 'NO', '[AUTHENTICATIONFAILED] aborted') else: self._send_tagged(tag, 'OK', 'MYAUTH successful') client, _ = self._setup(MyServer) with self.assertRaisesRegex(imaplib.IMAP4.error, r'\[AUTHENTICATIONFAILED\] aborted'): client.authenticate('MYAUTH', lambda x: None) @mock.patch('imaplib._MAXLINE', 10) def test_linetoolong(self): class TooLongHandler(SimpleIMAPHandler): def handle(self): # send response line longer than the limit set in the next line self.wfile.write(b'* OK ' + 11 * b'x' + b'\r\n') _, server = self._setup(TooLongHandler, connect=False) with self.assertRaisesRegex(imaplib.IMAP4.error, 'got more than 10 bytes'): self.imap_class(*server.server_address) def test_simple_with_statement(self): _, server = self._setup(SimpleIMAPHandler, connect=False) with self.imap_class(*server.server_address): pass def test_with_statement(self): _, server = self._setup(SimpleIMAPHandler, connect=False) with self.imap_class(*server.server_address) as imap: imap.login('user', 'pass') self.assertEqual(server.logged, 'user') self.assertIsNone(server.logged) def test_with_statement_logout(self): # It is legal to log out explicitly inside the with block _, server = self._setup(SimpleIMAPHandler, connect=False) with self.imap_class(*server.server_address) as imap: imap.login('user', 'pass') self.assertEqual(server.logged, 'user') imap.logout() self.assertIsNone(server.logged) self.assertIsNone(server.logged) # command tests def test_login(self): client, _ = self._setup(SimpleIMAPHandler) typ, data = client.login('user', 'pass') self.assertEqual(typ, 'OK') self.assertEqual(data[0], b'LOGIN completed') self.assertEqual(client.state, 'AUTH') def test_logout(self): client, _ = self._setup(SimpleIMAPHandler) typ, data = client.login('user', 'pass') self.assertEqual(typ, 'OK') self.assertEqual(data[0], b'LOGIN completed') typ, data = client.logout() self.assertEqual(typ, 'BYE', (typ, data)) self.assertEqual(data[0], b'IMAP4ref1 Server logging out', (typ, data)) self.assertEqual(client.state, 'LOGOUT') def test_lsub(self): class LsubCmd(SimpleIMAPHandler): def cmd_LSUB(self, tag, args): self._send_textline('* LSUB () "." directoryA') return self._send_tagged(tag, 'OK', 'LSUB completed') client, _ = self._setup(LsubCmd) client.login('user', 'pass') typ, data = client.lsub() self.assertEqual(typ, 'OK') self.assertEqual(data[0], b'() "." directoryA') class NewIMAPTests(NewIMAPTestsMixin, unittest.TestCase): imap_class = imaplib.IMAP4 server_class = socketserver.TCPServer @unittest.skipUnless(ssl, "SSL not available") class NewIMAPSSLTests(NewIMAPTestsMixin, unittest.TestCase): imap_class = IMAP4_SSL server_class = SecureTCPServer def test_ssl_raises(self): ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ssl_context.verify_mode, ssl.CERT_REQUIRED) self.assertEqual(ssl_context.check_hostname, True) ssl_context.load_verify_locations(CAFILE) with self.assertRaisesRegex(ssl.CertificateError, "IP address mismatch, certificate is not valid for " "'127.0.0.1'"): _, server = self._setup(SimpleIMAPHandler) client = self.imap_class(*server.server_address, ssl_context=ssl_context) client.shutdown() def test_ssl_verified(self): ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_verify_locations(CAFILE) _, server = self._setup(SimpleIMAPHandler) client = self.imap_class("localhost", server.server_address[1], ssl_context=ssl_context) client.shutdown() # Mock the private method _connect(), so mark the test as specific # to CPython stdlib @cpython_only def test_certfile_arg_warn(self): with support.check_warnings(('', DeprecationWarning)): with mock.patch.object(self.imap_class, 'open'): with mock.patch.object(self.imap_class, '_connect'): self.imap_class('localhost', 143, certfile=CERTFILE) class ThreadedNetworkedTests(unittest.TestCase): server_class = socketserver.TCPServer imap_class = imaplib.IMAP4 def make_server(self, addr, hdlr): class MyServer(self.server_class): def handle_error(self, request, client_address): self.close_request(request) self.server_close() raise if verbose: print("creating server") server = MyServer(addr, hdlr) self.assertEqual(server.server_address, server.socket.getsockname()) if verbose: print("server created") print("ADDR =", addr) print("CLASS =", self.server_class) print("HDLR =", server.RequestHandlerClass) t = threading.Thread( name='%s serving' % self.server_class, target=server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval': 0.01}) t.daemon = True # In case this function raises. t.start() if verbose: print("server running") return server, t def reap_server(self, server, thread): if verbose: print("waiting for server") server.shutdown() server.server_close() thread.join() if verbose: print("done") @contextmanager def reaped_server(self, hdlr): server, thread = self.make_server((support.HOST, 0), hdlr) try: yield server finally: self.reap_server(server, thread) @contextmanager def reaped_pair(self, hdlr): with self.reaped_server(hdlr) as server: client = self.imap_class(*server.server_address) try: yield server, client finally: client.logout() @reap_threads def test_connect(self): with self.reaped_server(SimpleIMAPHandler) as server: client = self.imap_class(*server.server_address) client.shutdown() @reap_threads def test_bracket_flags(self): # This violates RFC 3501, which disallows ']' characters in tag names, # but imaplib has allowed producing such tags forever, other programs # also produce them (eg: OtherInbox's Organizer app as of 20140716), # and Gmail, for example, accepts them and produces them. So we # support them. See issue #21815. class BracketFlagHandler(SimpleIMAPHandler): def handle(self): self.flags = ['Answered', 'Flagged', 'Deleted', 'Seen', 'Draft'] super().handle() def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') def cmd_SELECT(self, tag, args): flag_msg = ' \\'.join(self.flags) self._send_line(('* FLAGS (%s)' % flag_msg).encode('ascii')) self._send_line(b'* 2 EXISTS') self._send_line(b'* 0 RECENT') msg = ('* OK [PERMANENTFLAGS %s \\*)] Flags permitted.' % flag_msg) self._send_line(msg.encode('ascii')) self._send_tagged(tag, 'OK', '[READ-WRITE] SELECT completed.') def cmd_STORE(self, tag, args): new_flags = args[2].strip('(').strip(')').split() self.flags.extend(new_flags) flags_msg = '(FLAGS (%s))' % ' \\'.join(self.flags) msg = '* %s FETCH %s' % (args[0], flags_msg) self._send_line(msg.encode('ascii')) self._send_tagged(tag, 'OK', 'STORE completed.') with self.reaped_pair(BracketFlagHandler) as (server, client): code, data = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') client.select('test') typ, [data] = client.store(b'1', "+FLAGS", "[test]") self.assertIn(b'[test]', data) client.select('test') typ, [data] = client.response('PERMANENTFLAGS') self.assertIn(b'[test]', data) @reap_threads def test_issue5949(self): class EOFHandler(socketserver.StreamRequestHandler): def handle(self): # EOF without sending a complete welcome message. self.wfile.write(b'* OK') with self.reaped_server(EOFHandler) as server: self.assertRaises(imaplib.IMAP4.abort, self.imap_class, *server.server_address) @reap_threads def test_line_termination(self): class BadNewlineHandler(SimpleIMAPHandler): def cmd_CAPABILITY(self, tag, args): self._send(b'* CAPABILITY IMAP4rev1 AUTH\n') self._send_tagged(tag, 'OK', 'CAPABILITY completed') with self.reaped_server(BadNewlineHandler) as server: self.assertRaises(imaplib.IMAP4.abort, self.imap_class, *server.server_address) class UTF8Server(SimpleIMAPHandler): capabilities = 'AUTH ENABLE UTF8=ACCEPT' def cmd_ENABLE(self, tag, args): self._send_tagged(tag, 'OK', 'ENABLE successful') def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') @reap_threads def test_enable_raises_error_if_not_AUTH(self): with self.reaped_pair(self.UTF8Server) as (server, client): self.assertFalse(client.utf8_enabled) self.assertRaises(imaplib.IMAP4.error, client.enable, 'foo') self.assertFalse(client.utf8_enabled) # XXX Also need a test that enable after SELECT raises an error. @reap_threads def test_enable_raises_error_if_no_capability(self): class NoEnableServer(self.UTF8Server): capabilities = 'AUTH' with self.reaped_pair(NoEnableServer) as (server, client): self.assertRaises(imaplib.IMAP4.error, client.enable, 'foo') @reap_threads def test_enable_UTF8_raises_error_if_not_supported(self): class NonUTF8Server(SimpleIMAPHandler): pass with self.assertRaises(imaplib.IMAP4.error): with self.reaped_pair(NonUTF8Server) as (server, client): typ, data = client.login('user', 'pass') self.assertEqual(typ, 'OK') client.enable('UTF8=ACCEPT') pass @reap_threads def test_enable_UTF8_True_append(self): class UTF8AppendServer(self.UTF8Server): def cmd_APPEND(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'okay') with self.reaped_pair(UTF8AppendServer) as (server, client): self.assertEqual(client._encoding, 'ascii') code, _ = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' code, _ = client.enable('UTF8=ACCEPT') self.assertEqual(code, 'OK') self.assertEqual(client._encoding, 'utf-8') msg_string = 'Subject: üñí©öðé' typ, data = client.append( None, None, None, msg_string.encode('utf-8')) self.assertEqual(typ, 'OK') self.assertEqual( server.response, ('UTF8 (%s)\r\n' % msg_string).encode('utf-8') ) # XXX also need a test that makes sure that the Literal and Untagged_status # regexes uses unicode in UTF8 mode instead of the default ASCII. @reap_threads def test_search_disallows_charset_in_utf8_mode(self): with self.reaped_pair(self.UTF8Server) as (server, client): typ, _ = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(typ, 'OK') typ, _ = client.enable('UTF8=ACCEPT') self.assertEqual(typ, 'OK') self.assertTrue(client.utf8_enabled) self.assertRaises(imaplib.IMAP4.error, client.search, 'foo', 'bar') @reap_threads def test_bad_auth_name(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_tagged(tag, 'NO', 'unrecognized authentication ' 'type {}'.format(args[0])) with self.reaped_pair(MyServer) as (server, client): with self.assertRaises(imaplib.IMAP4.error): client.authenticate('METHOD', lambda: 1) @reap_threads def test_invalid_authentication(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.response = yield self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] invalid') with self.reaped_pair(MyServer) as (server, client): with self.assertRaises(imaplib.IMAP4.error): code, data = client.authenticate('MYAUTH', lambda x: b'fake') @reap_threads def test_valid_authentication(self): class MyServer(SimpleIMAPHandler): def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+') self.server.response = yield self._send_tagged(tag, 'OK', 'FAKEAUTH successful') with self.reaped_pair(MyServer) as (server, client): code, data = client.authenticate('MYAUTH', lambda x: b'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' with self.reaped_pair(MyServer) as (server, client): code, data = client.authenticate('MYAUTH', lambda x: 'fake') self.assertEqual(code, 'OK') self.assertEqual(server.response, b'ZmFrZQ==\r\n') # b64 encoded 'fake' @reap_threads def test_login_cram_md5(self): class AuthHandler(SimpleIMAPHandler): capabilities = 'LOGINDISABLED AUTH=CRAM-MD5' def cmd_AUTHENTICATE(self, tag, args): self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm' 'VzdG9uLm1jaS5uZXQ=') r = yield if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT' b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'): self._send_tagged(tag, 'OK', 'CRAM-MD5 successful') else: self._send_tagged(tag, 'NO', 'No access') with self.reaped_pair(AuthHandler) as (server, client): self.assertTrue('AUTH=CRAM-MD5' in client.capabilities) ret, data = client.login_cram_md5("tim", "tanstaaftanstaaf") self.assertEqual(ret, "OK")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_locale.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_locale.py
from test.support import verbose, is_android, check_warnings import unittest import locale import sys import codecs import warnings class BaseLocalizedTest(unittest.TestCase): # # Base class for tests using a real locale # @classmethod def setUpClass(cls): if sys.platform == 'darwin': import os tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US") if int(os.uname().release.split('.')[0]) < 10: # The locale test work fine on OSX 10.6, I (ronaldoussoren) # haven't had time yet to verify if tests work on OSX 10.5 # (10.4 is known to be bad) raise unittest.SkipTest("Locale support on MacOSX is minimal") elif sys.platform.startswith("win"): tlocs = ("En", "English") else: tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US.US-ASCII", "en_US") try: oldlocale = locale.setlocale(locale.LC_NUMERIC) for tloc in tlocs: try: locale.setlocale(locale.LC_NUMERIC, tloc) except locale.Error: continue break else: raise unittest.SkipTest("Test locale not supported " "(tried %s)" % (', '.join(tlocs))) cls.enUS_locale = tloc finally: locale.setlocale(locale.LC_NUMERIC, oldlocale) def setUp(self): oldlocale = locale.setlocale(self.locale_type) self.addCleanup(locale.setlocale, self.locale_type, oldlocale) locale.setlocale(self.locale_type, self.enUS_locale) if verbose: print("testing with %r..." % self.enUS_locale, end=' ', flush=True) class BaseCookedTest(unittest.TestCase): # # Base class for tests using cooked localeconv() values # def setUp(self): locale._override_localeconv = self.cooked_values def tearDown(self): locale._override_localeconv = {} class CCookedTest(BaseCookedTest): # A cooked "C" locale cooked_values = { 'currency_symbol': '', 'decimal_point': '.', 'frac_digits': 127, 'grouping': [], 'int_curr_symbol': '', 'int_frac_digits': 127, 'mon_decimal_point': '', 'mon_grouping': [], 'mon_thousands_sep': '', 'n_cs_precedes': 127, 'n_sep_by_space': 127, 'n_sign_posn': 127, 'negative_sign': '', 'p_cs_precedes': 127, 'p_sep_by_space': 127, 'p_sign_posn': 127, 'positive_sign': '', 'thousands_sep': '' } class EnUSCookedTest(BaseCookedTest): # A cooked "en_US" locale cooked_values = { 'currency_symbol': '$', 'decimal_point': '.', 'frac_digits': 2, 'grouping': [3, 3, 0], 'int_curr_symbol': 'USD ', 'int_frac_digits': 2, 'mon_decimal_point': '.', 'mon_grouping': [3, 3, 0], 'mon_thousands_sep': ',', 'n_cs_precedes': 1, 'n_sep_by_space': 0, 'n_sign_posn': 1, 'negative_sign': '-', 'p_cs_precedes': 1, 'p_sep_by_space': 0, 'p_sign_posn': 1, 'positive_sign': '', 'thousands_sep': ',' } class FrFRCookedTest(BaseCookedTest): # A cooked "fr_FR" locale with a space character as decimal separator # and a non-ASCII currency symbol. cooked_values = { 'currency_symbol': '\u20ac', 'decimal_point': ',', 'frac_digits': 2, 'grouping': [3, 3, 0], 'int_curr_symbol': 'EUR ', 'int_frac_digits': 2, 'mon_decimal_point': ',', 'mon_grouping': [3, 3, 0], 'mon_thousands_sep': ' ', 'n_cs_precedes': 0, 'n_sep_by_space': 1, 'n_sign_posn': 1, 'negative_sign': '-', 'p_cs_precedes': 0, 'p_sep_by_space': 1, 'p_sign_posn': 1, 'positive_sign': '', 'thousands_sep': ' ' } class BaseFormattingTest(object): # # Utility functions for formatting tests # def _test_formatfunc(self, format, value, out, func, **format_opts): self.assertEqual( func(format, value, **format_opts), out) def _test_format(self, format, value, out, **format_opts): with check_warnings(('', DeprecationWarning)): self._test_formatfunc(format, value, out, func=locale.format, **format_opts) def _test_format_string(self, format, value, out, **format_opts): self._test_formatfunc(format, value, out, func=locale.format_string, **format_opts) def _test_currency(self, value, out, **format_opts): self.assertEqual(locale.currency(value, **format_opts), out) class EnUSNumberFormatting(BaseFormattingTest): # XXX there is a grouping + padding bug when the thousands separator # is empty but the grouping array contains values (e.g. Solaris 10) def setUp(self): self.sep = locale.localeconv()['thousands_sep'] def test_grouping(self): self._test_format("%f", 1024, grouping=1, out='1%s024.000000' % self.sep) self._test_format("%f", 102, grouping=1, out='102.000000') self._test_format("%f", -42, grouping=1, out='-42.000000') self._test_format("%+f", -42, grouping=1, out='-42.000000') def test_grouping_and_padding(self): self._test_format("%20.f", -42, grouping=1, out='-42'.rjust(20)) if self.sep: self._test_format("%+10.f", -4200, grouping=1, out=('-4%s200' % self.sep).rjust(10)) self._test_format("%-10.f", -4200, grouping=1, out=('-4%s200' % self.sep).ljust(10)) def test_integer_grouping(self): self._test_format("%d", 4200, grouping=True, out='4%s200' % self.sep) self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep) self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep) def test_integer_grouping_and_padding(self): self._test_format("%10d", 4200, grouping=True, out=('4%s200' % self.sep).rjust(10)) self._test_format("%-10d", -4200, grouping=True, out=('-4%s200' % self.sep).ljust(10)) def test_simple(self): self._test_format("%f", 1024, grouping=0, out='1024.000000') self._test_format("%f", 102, grouping=0, out='102.000000') self._test_format("%f", -42, grouping=0, out='-42.000000') self._test_format("%+f", -42, grouping=0, out='-42.000000') def test_padding(self): self._test_format("%20.f", -42, grouping=0, out='-42'.rjust(20)) self._test_format("%+10.f", -4200, grouping=0, out='-4200'.rjust(10)) self._test_format("%-10.f", 4200, grouping=0, out='4200'.ljust(10)) def test_format_deprecation(self): with self.assertWarns(DeprecationWarning): locale.format("%-10.f", 4200, grouping=True) def test_complex_formatting(self): # Spaces in formatting string self._test_format_string("One million is %i", 1000000, grouping=1, out='One million is 1%s000%s000' % (self.sep, self.sep)) self._test_format_string("One million is %i", 1000000, grouping=1, out='One million is 1%s000%s000' % (self.sep, self.sep)) # Dots in formatting string self._test_format_string(".%f.", 1000.0, out='.1000.000000.') # Padding if self.sep: self._test_format_string("--> %10.2f", 4200, grouping=1, out='--> ' + ('4%s200.00' % self.sep).rjust(10)) # Asterisk formats self._test_format_string("%10.*f", (2, 1000), grouping=0, out='1000.00'.rjust(10)) if self.sep: self._test_format_string("%*.*f", (10, 2, 1000), grouping=1, out=('1%s000.00' % self.sep).rjust(10)) # Test more-in-one if self.sep: self._test_format_string("int %i float %.2f str %s", (1000, 1000.0, 'str'), grouping=1, out='int 1%s000 float 1%s000.00 str str' % (self.sep, self.sep)) class TestFormatPatternArg(unittest.TestCase): # Test handling of pattern argument of format def test_onlyOnePattern(self): with check_warnings(('', DeprecationWarning)): # Issue 2522: accept exactly one % pattern, and no extra chars. self.assertRaises(ValueError, locale.format, "%f\n", 'foo') self.assertRaises(ValueError, locale.format, "%f\r", 'foo') self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo') self.assertRaises(ValueError, locale.format, " %f", 'foo') self.assertRaises(ValueError, locale.format, "%fg", 'foo') self.assertRaises(ValueError, locale.format, "%^g", 'foo') self.assertRaises(ValueError, locale.format, "%f%%", 'foo') class TestLocaleFormatString(unittest.TestCase): """General tests on locale.format_string""" def test_percent_escape(self): self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), '%d %f%%d' % (1, 1.0)) self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), ('%(foo)s %%d' % {'foo': 'bar'})) def test_mapping(self): self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}), ('%(foo)s bing.' % {'foo': 'bar'})) self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}), ('%(foo)s' % {'foo': 'bar'})) class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting): # Test number formatting with a real English locale. locale_type = locale.LC_NUMERIC def setUp(self): BaseLocalizedTest.setUp(self) EnUSNumberFormatting.setUp(self) class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting): # Test number formatting with a cooked "en_US" locale. def setUp(self): EnUSCookedTest.setUp(self) EnUSNumberFormatting.setUp(self) def test_currency(self): self._test_currency(50000, "$50000.00") self._test_currency(50000, "$50,000.00", grouping=True) self._test_currency(50000, "USD 50,000.00", grouping=True, international=True) class TestCNumberFormatting(CCookedTest, BaseFormattingTest): # Test number formatting with a cooked "C" locale. def test_grouping(self): self._test_format("%.2f", 12345.67, grouping=True, out='12345.67') def test_grouping_and_padding(self): self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67') class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest): # Test number formatting with a cooked "fr_FR" locale. def test_decimal_point(self): self._test_format("%.2f", 12345.67, out='12345,67') def test_grouping(self): self._test_format("%.2f", 345.67, grouping=True, out='345,67') self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67') def test_grouping_and_padding(self): self._test_format("%6.2f", 345.67, grouping=True, out='345,67') self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67') self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67') self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67') self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67') self._test_format("%-6.2f", 345.67, grouping=True, out='345,67') self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ') self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67') self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67') self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ') def test_integer_grouping(self): self._test_format("%d", 200, grouping=True, out='200') self._test_format("%d", 4200, grouping=True, out='4 200') def test_integer_grouping_and_padding(self): self._test_format("%4d", 4200, grouping=True, out='4 200') self._test_format("%5d", 4200, grouping=True, out='4 200') self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10)) self._test_format("%-4d", 4200, grouping=True, out='4 200') self._test_format("%-5d", 4200, grouping=True, out='4 200') self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10)) def test_currency(self): euro = '\u20ac' self._test_currency(50000, "50000,00 " + euro) self._test_currency(50000, "50 000,00 " + euro, grouping=True) # XXX is the trailing space a bug? self._test_currency(50000, "50 000,00 EUR ", grouping=True, international=True) class TestCollation(unittest.TestCase): # Test string collation functions def test_strcoll(self): self.assertLess(locale.strcoll('a', 'b'), 0) self.assertEqual(locale.strcoll('a', 'a'), 0) self.assertGreater(locale.strcoll('b', 'a'), 0) # embedded null character self.assertRaises(ValueError, locale.strcoll, 'a\0', 'a') self.assertRaises(ValueError, locale.strcoll, 'a', 'a\0') def test_strxfrm(self): self.assertLess(locale.strxfrm('a'), locale.strxfrm('b')) # embedded null character self.assertRaises(ValueError, locale.strxfrm, 'a\0') class TestEnUSCollation(BaseLocalizedTest, TestCollation): # Test string collation functions with a real English locale locale_type = locale.LC_ALL def setUp(self): enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name if enc not in ('utf-8', 'iso8859-1', 'cp1252'): raise unittest.SkipTest('encoding not suitable') if enc != 'iso8859-1' and (sys.platform == 'darwin' or is_android or sys.platform.startswith('freebsd')): raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs') BaseLocalizedTest.setUp(self) @unittest.skipIf(sys.platform.startswith('aix'), 'bpo-29972: broken test on AIX') def test_strcoll_with_diacritic(self): self.assertLess(locale.strcoll('à', 'b'), 0) @unittest.skipIf(sys.platform.startswith('aix'), 'bpo-29972: broken test on AIX') def test_strxfrm_with_diacritic(self): self.assertLess(locale.strxfrm('à'), locale.strxfrm('b')) class NormalizeTest(unittest.TestCase): def check(self, localename, expected): self.assertEqual(locale.normalize(localename), expected, msg=localename) def test_locale_alias(self): for localename, alias in locale.locale_alias.items(): with self.subTest(locale=(localename, alias)): self.check(localename, alias) def test_empty(self): self.check('', '') def test_c(self): self.check('c', 'C') self.check('posix', 'C') def test_english(self): self.check('en', 'en_US.ISO8859-1') self.check('EN', 'en_US.ISO8859-1') self.check('en.iso88591', 'en_US.ISO8859-1') self.check('en_US', 'en_US.ISO8859-1') self.check('en_us', 'en_US.ISO8859-1') self.check('en_GB', 'en_GB.ISO8859-1') self.check('en_US.UTF-8', 'en_US.UTF-8') self.check('en_US.utf8', 'en_US.UTF-8') self.check('en_US:UTF-8', 'en_US.UTF-8') self.check('en_US.ISO8859-1', 'en_US.ISO8859-1') self.check('en_US.US-ASCII', 'en_US.ISO8859-1') self.check('en_US.88591', 'en_US.ISO8859-1') self.check('en_US.885915', 'en_US.ISO8859-15') self.check('english', 'en_EN.ISO8859-1') self.check('english_uk.ascii', 'en_GB.ISO8859-1') def test_hyphenated_encoding(self): self.check('az_AZ.iso88599e', 'az_AZ.ISO8859-9E') self.check('az_AZ.ISO8859-9E', 'az_AZ.ISO8859-9E') self.check('tt_RU.koi8c', 'tt_RU.KOI8-C') self.check('tt_RU.KOI8-C', 'tt_RU.KOI8-C') self.check('lo_LA.cp1133', 'lo_LA.IBM-CP1133') self.check('lo_LA.ibmcp1133', 'lo_LA.IBM-CP1133') self.check('lo_LA.IBM-CP1133', 'lo_LA.IBM-CP1133') self.check('uk_ua.microsoftcp1251', 'uk_UA.CP1251') self.check('uk_ua.microsoft-cp1251', 'uk_UA.CP1251') self.check('ka_ge.georgianacademy', 'ka_GE.GEORGIAN-ACADEMY') self.check('ka_GE.GEORGIAN-ACADEMY', 'ka_GE.GEORGIAN-ACADEMY') self.check('cs_CZ.iso88592', 'cs_CZ.ISO8859-2') self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2') def test_euro_modifier(self): self.check('de_DE@euro', 'de_DE.ISO8859-15') self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15') self.check('de_DE.utf8@euro', 'de_DE.UTF-8') def test_latin_modifier(self): self.check('be_BY.UTF-8@latin', 'be_BY.UTF-8@latin') self.check('sr_RS.UTF-8@latin', 'sr_RS.UTF-8@latin') self.check('sr_RS.UTF-8@latn', 'sr_RS.UTF-8@latin') def test_valencia_modifier(self): self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia') self.check('ca_ES@valencia', 'ca_ES.UTF-8@valencia') self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia') def test_devanagari_modifier(self): self.check('ks_IN.UTF-8@devanagari', 'ks_IN.UTF-8@devanagari') self.check('ks_IN@devanagari', 'ks_IN.UTF-8@devanagari') self.check('ks@devanagari', 'ks_IN.UTF-8@devanagari') self.check('ks_IN.UTF-8', 'ks_IN.UTF-8') self.check('ks_IN', 'ks_IN.UTF-8') self.check('ks', 'ks_IN.UTF-8') self.check('sd_IN.UTF-8@devanagari', 'sd_IN.UTF-8@devanagari') self.check('sd_IN@devanagari', 'sd_IN.UTF-8@devanagari') self.check('sd@devanagari', 'sd_IN.UTF-8@devanagari') self.check('sd_IN.UTF-8', 'sd_IN.UTF-8') self.check('sd_IN', 'sd_IN.UTF-8') self.check('sd', 'sd_IN.UTF-8') def test_euc_encoding(self): self.check('ja_jp.euc', 'ja_JP.eucJP') self.check('ja_jp.eucjp', 'ja_JP.eucJP') self.check('ko_kr.euc', 'ko_KR.eucKR') self.check('ko_kr.euckr', 'ko_KR.eucKR') self.check('zh_cn.euc', 'zh_CN.eucCN') self.check('zh_tw.euc', 'zh_TW.eucTW') self.check('zh_tw.euctw', 'zh_TW.eucTW') def test_japanese(self): self.check('ja', 'ja_JP.eucJP') self.check('ja.jis', 'ja_JP.JIS7') self.check('ja.sjis', 'ja_JP.SJIS') self.check('ja_jp', 'ja_JP.eucJP') self.check('ja_jp.ajec', 'ja_JP.eucJP') self.check('ja_jp.euc', 'ja_JP.eucJP') self.check('ja_jp.eucjp', 'ja_JP.eucJP') self.check('ja_jp.iso-2022-jp', 'ja_JP.JIS7') self.check('ja_jp.iso2022jp', 'ja_JP.JIS7') self.check('ja_jp.jis', 'ja_JP.JIS7') self.check('ja_jp.jis7', 'ja_JP.JIS7') self.check('ja_jp.mscode', 'ja_JP.SJIS') self.check('ja_jp.pck', 'ja_JP.SJIS') self.check('ja_jp.sjis', 'ja_JP.SJIS') self.check('ja_jp.ujis', 'ja_JP.eucJP') self.check('ja_jp.utf8', 'ja_JP.UTF-8') self.check('japan', 'ja_JP.eucJP') self.check('japanese', 'ja_JP.eucJP') self.check('japanese-euc', 'ja_JP.eucJP') self.check('japanese.euc', 'ja_JP.eucJP') self.check('japanese.sjis', 'ja_JP.SJIS') self.check('jp_jp', 'ja_JP.eucJP') class TestMiscellaneous(unittest.TestCase): def test_defaults_UTF8(self): # Issue #18378: on (at least) macOS setting LC_CTYPE to "UTF-8" is # valid. Futhermore LC_CTYPE=UTF is used by the UTF-8 locale coercing # during interpreter startup (on macOS). import _locale import os self.assertEqual(locale._parse_localename('UTF-8'), (None, 'UTF-8')) if hasattr(_locale, '_getdefaultlocale'): orig_getlocale = _locale._getdefaultlocale del _locale._getdefaultlocale else: orig_getlocale = None orig_env = {} try: for key in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'): if key in os.environ: orig_env[key] = os.environ[key] del os.environ[key] os.environ['LC_CTYPE'] = 'UTF-8' self.assertEqual(locale.getdefaultlocale(), (None, 'UTF-8')) finally: for k in orig_env: os.environ[k] = orig_env[k] if 'LC_CTYPE' not in orig_env: del os.environ['LC_CTYPE'] if orig_getlocale is not None: _locale._getdefaultlocale = orig_getlocale def test_getpreferredencoding(self): # Invoke getpreferredencoding to make sure it does not cause exceptions. enc = locale.getpreferredencoding() if enc: # If encoding non-empty, make sure it is valid codecs.lookup(enc) def test_strcoll_3303(self): # test crasher from bug #3303 self.assertRaises(TypeError, locale.strcoll, "a", None) self.assertRaises(TypeError, locale.strcoll, b"a", None) def test_setlocale_category(self): locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_TIME) locale.setlocale(locale.LC_CTYPE) locale.setlocale(locale.LC_COLLATE) locale.setlocale(locale.LC_MONETARY) locale.setlocale(locale.LC_NUMERIC) # crasher from bug #7419 self.assertRaises(locale.Error, locale.setlocale, 12345) def test_getsetlocale_issue1813(self): # Issue #1813: setting and getting the locale under a Turkish locale oldlocale = locale.setlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) try: locale.setlocale(locale.LC_CTYPE, 'tr_TR') except locale.Error: # Unsupported locale on this system self.skipTest('test needs Turkish locale') loc = locale.getlocale(locale.LC_CTYPE) if verbose: print('testing with %a' % (loc,), end=' ', flush=True) locale.setlocale(locale.LC_CTYPE, loc) self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE)) def test_invalid_locale_format_in_localetuple(self): with self.assertRaises(TypeError): locale.setlocale(locale.LC_ALL, b'fi_FI') def test_invalid_iterable_in_localetuple(self): with self.assertRaises(TypeError): locale.setlocale(locale.LC_ALL, (b'not', b'valid')) class BaseDelocalizeTest(BaseLocalizedTest): def _test_delocalize(self, value, out): self.assertEqual(locale.delocalize(value), out) def _test_atof(self, value, out): self.assertEqual(locale.atof(value), out) def _test_atoi(self, value, out): self.assertEqual(locale.atoi(value), out) class TestEnUSDelocalize(EnUSCookedTest, BaseDelocalizeTest): def test_delocalize(self): self._test_delocalize('50000.00', '50000.00') self._test_delocalize('50,000.00', '50000.00') def test_atof(self): self._test_atof('50000.00', 50000.) self._test_atof('50,000.00', 50000.) def test_atoi(self): self._test_atoi('50000', 50000) self._test_atoi('50,000', 50000) class TestCDelocalizeTest(CCookedTest, BaseDelocalizeTest): def test_delocalize(self): self._test_delocalize('50000.00', '50000.00') def test_atof(self): self._test_atof('50000.00', 50000.) def test_atoi(self): self._test_atoi('50000', 50000) class TestfrFRDelocalizeTest(FrFRCookedTest, BaseDelocalizeTest): def test_delocalize(self): self._test_delocalize('50000,00', '50000.00') self._test_delocalize('50 000,00', '50000.00') def test_atof(self): self._test_atof('50000,00', 50000.) self._test_atof('50 000,00', 50000.) def test_atoi(self): self._test_atoi('50000', 50000) self._test_atoi('50 000', 50000) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_finalization.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_finalization.py
""" Tests for object finalization semantics, as outlined in PEP 442. """ import contextlib import gc import unittest import weakref try: from _testcapi import with_tp_del except ImportError: def with_tp_del(cls): class C(object): def __new__(cls, *args, **kwargs): raise TypeError('requires _testcapi.with_tp_del') return C from test import support class NonGCSimpleBase: """ The base class for all the objects under test, equipped with various testing features. """ survivors = [] del_calls = [] tp_del_calls = [] errors = [] _cleaning = False __slots__ = () @classmethod def _cleanup(cls): cls.survivors.clear() cls.errors.clear() gc.garbage.clear() gc.collect() cls.del_calls.clear() cls.tp_del_calls.clear() @classmethod @contextlib.contextmanager def test(cls): """ A context manager to use around all finalization tests. """ with support.disable_gc(): cls.del_calls.clear() cls.tp_del_calls.clear() NonGCSimpleBase._cleaning = False try: yield if cls.errors: raise cls.errors[0] finally: NonGCSimpleBase._cleaning = True cls._cleanup() def check_sanity(self): """ Check the object is sane (non-broken). """ def __del__(self): """ PEP 442 finalizer. Record that this was called, check the object is in a sane state, and invoke a side effect. """ try: if not self._cleaning: self.del_calls.append(id(self)) self.check_sanity() self.side_effect() except Exception as e: self.errors.append(e) def side_effect(self): """ A side effect called on destruction. """ class SimpleBase(NonGCSimpleBase): def __init__(self): self.id_ = id(self) def check_sanity(self): assert self.id_ == id(self) class NonGC(NonGCSimpleBase): __slots__ = () class NonGCResurrector(NonGCSimpleBase): __slots__ = () def side_effect(self): """ Resurrect self by storing self in a class-wide list. """ self.survivors.append(self) class Simple(SimpleBase): pass class SimpleResurrector(NonGCResurrector, SimpleBase): pass class TestBase: def setUp(self): self.old_garbage = gc.garbage[:] gc.garbage[:] = [] def tearDown(self): # None of the tests here should put anything in gc.garbage try: self.assertEqual(gc.garbage, []) finally: del self.old_garbage gc.collect() def assert_del_calls(self, ids): self.assertEqual(sorted(SimpleBase.del_calls), sorted(ids)) def assert_tp_del_calls(self, ids): self.assertEqual(sorted(SimpleBase.tp_del_calls), sorted(ids)) def assert_survivors(self, ids): self.assertEqual(sorted(id(x) for x in SimpleBase.survivors), sorted(ids)) def assert_garbage(self, ids): self.assertEqual(sorted(id(x) for x in gc.garbage), sorted(ids)) def clear_survivors(self): SimpleBase.survivors.clear() class SimpleFinalizationTest(TestBase, unittest.TestCase): """ Test finalization without refcycles. """ def test_simple(self): with SimpleBase.test(): s = Simple() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) def test_simple_resurrect(self): with SimpleBase.test(): s = SimpleResurrector() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors(ids) self.assertIsNot(wr(), None) self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) def test_non_gc(self): with SimpleBase.test(): s = NonGC() self.assertFalse(gc.is_tracked(s)) ids = [id(s)] del s gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) def test_non_gc_resurrect(self): with SimpleBase.test(): s = NonGCResurrector() self.assertFalse(gc.is_tracked(s)) ids = [id(s)] del s gc.collect() self.assert_del_calls(ids) self.assert_survivors(ids) self.clear_survivors() gc.collect() self.assert_del_calls(ids * 2) self.assert_survivors(ids) class SelfCycleBase: def __init__(self): super().__init__() self.ref = self def check_sanity(self): super().check_sanity() assert self.ref is self class SimpleSelfCycle(SelfCycleBase, Simple): pass class SelfCycleResurrector(SelfCycleBase, SimpleResurrector): pass class SuicidalSelfCycle(SelfCycleBase, Simple): def side_effect(self): """ Explicitly break the reference cycle. """ self.ref = None class SelfCycleFinalizationTest(TestBase, unittest.TestCase): """ Test finalization of an object having a single cyclic reference to itself. """ def test_simple(self): with SimpleBase.test(): s = SimpleSelfCycle() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) def test_simple_resurrect(self): # Test that __del__ can resurrect the object being finalized. with SimpleBase.test(): s = SelfCycleResurrector() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors(ids) # XXX is this desirable? self.assertIs(wr(), None) # When trying to destroy the object a second time, __del__ # isn't called anymore (and the object isn't resurrected). self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) def test_simple_suicide(self): # Test the GC is able to deal with an object that kills its last # reference during __del__. with SimpleBase.test(): s = SuicidalSelfCycle() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) class ChainedBase: def chain(self, left): self.suicided = False self.left = left left.right = self def check_sanity(self): super().check_sanity() if self.suicided: assert self.left is None assert self.right is None else: left = self.left if left.suicided: assert left.right is None else: assert left.right is self right = self.right if right.suicided: assert right.left is None else: assert right.left is self class SimpleChained(ChainedBase, Simple): pass class ChainedResurrector(ChainedBase, SimpleResurrector): pass class SuicidalChained(ChainedBase, Simple): def side_effect(self): """ Explicitly break the reference cycle. """ self.suicided = True self.left = None self.right = None class CycleChainFinalizationTest(TestBase, unittest.TestCase): """ Test finalization of a cyclic chain. These tests are similar in spirit to the self-cycle tests above, but the collectable object graph isn't trivial anymore. """ def build_chain(self, classes): nodes = [cls() for cls in classes] for i in range(len(nodes)): nodes[i].chain(nodes[i-1]) return nodes def check_non_resurrecting_chain(self, classes): N = len(classes) with SimpleBase.test(): nodes = self.build_chain(classes) ids = [id(s) for s in nodes] wrs = [weakref.ref(s) for s in nodes] del nodes gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) self.assertEqual([wr() for wr in wrs], [None] * N) gc.collect() self.assert_del_calls(ids) def check_resurrecting_chain(self, classes): N = len(classes) with SimpleBase.test(): nodes = self.build_chain(classes) N = len(nodes) ids = [id(s) for s in nodes] survivor_ids = [id(s) for s in nodes if isinstance(s, SimpleResurrector)] wrs = [weakref.ref(s) for s in nodes] del nodes gc.collect() self.assert_del_calls(ids) self.assert_survivors(survivor_ids) # XXX desirable? self.assertEqual([wr() for wr in wrs], [None] * N) self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) def test_homogenous(self): self.check_non_resurrecting_chain([SimpleChained] * 3) def test_homogenous_resurrect(self): self.check_resurrecting_chain([ChainedResurrector] * 3) def test_homogenous_suicidal(self): self.check_non_resurrecting_chain([SuicidalChained] * 3) def test_heterogenous_suicidal_one(self): self.check_non_resurrecting_chain([SuicidalChained, SimpleChained] * 2) def test_heterogenous_suicidal_two(self): self.check_non_resurrecting_chain( [SuicidalChained] * 2 + [SimpleChained] * 2) def test_heterogenous_resurrect_one(self): self.check_resurrecting_chain([ChainedResurrector, SimpleChained] * 2) def test_heterogenous_resurrect_two(self): self.check_resurrecting_chain( [ChainedResurrector, SimpleChained, SuicidalChained] * 2) def test_heterogenous_resurrect_three(self): self.check_resurrecting_chain( [ChainedResurrector] * 2 + [SimpleChained] * 2 + [SuicidalChained] * 2) # NOTE: the tp_del slot isn't automatically inherited, so we have to call # with_tp_del() for each instantiated class. class LegacyBase(SimpleBase): def __del__(self): try: # Do not invoke side_effect here, since we are now exercising # the tp_del slot. if not self._cleaning: self.del_calls.append(id(self)) self.check_sanity() except Exception as e: self.errors.append(e) def __tp_del__(self): """ Legacy (pre-PEP 442) finalizer, mapped to a tp_del slot. """ try: if not self._cleaning: self.tp_del_calls.append(id(self)) self.check_sanity() self.side_effect() except Exception as e: self.errors.append(e) @with_tp_del class Legacy(LegacyBase): pass @with_tp_del class LegacyResurrector(LegacyBase): def side_effect(self): """ Resurrect self by storing self in a class-wide list. """ self.survivors.append(self) @with_tp_del class LegacySelfCycle(SelfCycleBase, LegacyBase): pass @support.cpython_only class LegacyFinalizationTest(TestBase, unittest.TestCase): """ Test finalization of objects with a tp_del. """ def tearDown(self): # These tests need to clean up a bit more, since they create # uncollectable objects. gc.garbage.clear() gc.collect() super().tearDown() def test_legacy(self): with SimpleBase.test(): s = Legacy() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids) self.assert_survivors([]) self.assertIs(wr(), None) gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids) def test_legacy_resurrect(self): with SimpleBase.test(): s = LegacyResurrector() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids) self.assert_survivors(ids) # weakrefs are cleared before tp_del is called. self.assertIs(wr(), None) self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids * 2) self.assert_survivors(ids) self.assertIs(wr(), None) def test_legacy_self_cycle(self): # Self-cycles with legacy finalizers end up in gc.garbage. with SimpleBase.test(): s = LegacySelfCycle() ids = [id(s)] wr = weakref.ref(s) del s gc.collect() self.assert_del_calls([]) self.assert_tp_del_calls([]) self.assert_survivors([]) self.assert_garbage(ids) self.assertIsNot(wr(), None) # Break the cycle to allow collection gc.garbage[0].ref = None self.assert_garbage([]) self.assertIs(wr(), None) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sysconfig.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sysconfig.py
import unittest import sys import os import subprocess import shutil from copy import copy from test.support import (import_module, TESTFN, unlink, check_warnings, captured_stdout, skip_unless_symlink, change_cwd) import sysconfig from sysconfig import (get_paths, get_platform, get_config_vars, get_path, get_path_names, _INSTALL_SCHEMES, _get_default_scheme, _expand_vars, get_scheme_names, get_config_var, _main) import _osx_support class TestSysConfig(unittest.TestCase): def setUp(self): super(TestSysConfig, self).setUp() self.sys_path = sys.path[:] # patching os.uname if hasattr(os, 'uname'): self.uname = os.uname self._uname = os.uname() else: self.uname = None self._set_uname(('',)*5) os.uname = self._get_uname # saving the environment self.name = os.name self.platform = sys.platform self.version = sys.version self.sep = os.sep self.join = os.path.join self.isabs = os.path.isabs self.splitdrive = os.path.splitdrive self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS) self._added_envvars = [] self._changed_envvars = [] for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'): if var in os.environ: self._changed_envvars.append((var, os.environ[var])) else: self._added_envvars.append(var) def tearDown(self): sys.path[:] = self.sys_path self._cleanup_testfn() if self.uname is not None: os.uname = self.uname else: del os.uname os.name = self.name sys.platform = self.platform sys.version = self.version os.sep = self.sep os.path.join = self.join os.path.isabs = self.isabs os.path.splitdrive = self.splitdrive sysconfig._CONFIG_VARS = self._config_vars[0] sysconfig._CONFIG_VARS.clear() sysconfig._CONFIG_VARS.update(self._config_vars[1]) for var, value in self._changed_envvars: os.environ[var] = value for var in self._added_envvars: os.environ.pop(var, None) super(TestSysConfig, self).tearDown() def _set_uname(self, uname): self._uname = os.uname_result(uname) def _get_uname(self): return self._uname def _cleanup_testfn(self): path = TESTFN if os.path.isfile(path): os.remove(path) elif os.path.isdir(path): shutil.rmtree(path) def test_get_path_names(self): self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS) def test_get_paths(self): scheme = get_paths() default_scheme = _get_default_scheme() wanted = _expand_vars(default_scheme, None) wanted = sorted(wanted.items()) scheme = sorted(scheme.items()) self.assertEqual(scheme, wanted) def test_get_path(self): # XXX make real tests here for scheme in _INSTALL_SCHEMES: for name in _INSTALL_SCHEMES[scheme]: res = get_path(name, scheme) def test_get_config_vars(self): cvars = get_config_vars() self.assertIsInstance(cvars, dict) self.assertTrue(cvars) def test_get_platform(self): # windows XP, 32bits os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Intel)]') sys.platform = 'win32' self.assertEqual(get_platform(), 'win32') # windows XP, amd64 os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Amd64)]') sys.platform = 'win32' self.assertEqual(get_platform(), 'win-amd64') # macbook os.name = 'posix' sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) ' '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]') sys.platform = 'darwin' self._set_uname(('Darwin', 'macziade', '8.11.1', ('Darwin Kernel Version 8.11.1: ' 'Wed Oct 10 18:23:28 PDT 2007; ' 'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC')) _osx_support._remove_original_values(get_config_vars()) get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3' get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g ' '-fwrapv -O3 -Wall -Wstrict-prototypes') maxint = sys.maxsize try: sys.maxsize = 2147483647 self.assertEqual(get_platform(), 'macosx-10.3-ppc') sys.maxsize = 9223372036854775807 self.assertEqual(get_platform(), 'macosx-10.3-ppc64') finally: sys.maxsize = maxint self._set_uname(('Darwin', 'macziade', '8.11.1', ('Darwin Kernel Version 8.11.1: ' 'Wed Oct 10 18:23:28 PDT 2007; ' 'root:xnu-792.25.20~1/RELEASE_I386'), 'i386')) _osx_support._remove_original_values(get_config_vars()) get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3' get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g ' '-fwrapv -O3 -Wall -Wstrict-prototypes') maxint = sys.maxsize try: sys.maxsize = 2147483647 self.assertEqual(get_platform(), 'macosx-10.3-i386') sys.maxsize = 9223372036854775807 self.assertEqual(get_platform(), 'macosx-10.3-x86_64') finally: sys.maxsize = maxint # macbook with fat binaries (fat, universal or fat64) _osx_support._remove_original_values(get_config_vars()) get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4' get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-intel') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat3') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-universal') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat64') for arch in ('ppc', 'i386', 'x86_64', 'ppc64'): _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch %s -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3' % arch) self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch) # linux debian sarge os.name = 'posix' sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) ' '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]') sys.platform = 'linux2' self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7', '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686')) self.assertEqual(get_platform(), 'linux-i686') # XXX more platforms to tests here def test_get_config_h_filename(self): config_h = sysconfig.get_config_h_filename() self.assertTrue(os.path.isfile(config_h), config_h) def test_get_scheme_names(self): wanted = ('nt', 'nt_user', 'osx_framework_user', 'posix_home', 'posix_prefix', 'posix_user') self.assertEqual(get_scheme_names(), wanted) @skip_unless_symlink def test_symlink(self): if sys.platform == "win32" and not os.path.exists(sys.executable): # App symlink appears to not exist, but we want the # real executable here anyway import _winapi real = _winapi.GetModuleFileName(0) else: real = os.path.realpath(sys.executable) link = os.path.abspath(TESTFN) os.symlink(real, link) # On Windows, the EXE needs to know where pythonXY.dll is at so we have # to add the directory to the path. env = None if sys.platform == "win32": env = {k.upper(): os.environ[k] for k in os.environ} env["PATH"] = "{};{}".format( os.path.dirname(real), env.get("PATH", "")) # Requires PYTHONHOME as well since we locate stdlib from the # EXE path and not the DLL path (which should be fixed) env["PYTHONHOME"] = os.path.dirname(real) if sysconfig.is_python_build(True): env["PYTHONPATH"] = os.path.dirname(os.__file__) # Issue 7880 def get(python, env=None): cmd = [python, '-c', 'import sysconfig; print(sysconfig.get_platform())'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() if p.returncode: print((out, err)) self.fail('Non-zero return code {0} (0x{0:08X})' .format(p.returncode)) return out, err try: self.assertEqual(get(real), get(link, env)) finally: unlink(link) def test_user_similar(self): # Issue #8759: make sure the posix scheme for the users # is similar to the global posix_prefix one base = get_config_var('base') user = get_config_var('userbase') # the global scheme mirrors the distinction between prefix and # exec-prefix but not the user scheme, so we have to adapt the paths # before comparing (issue #9100) adapt = sys.base_prefix != sys.base_exec_prefix for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): global_path = get_path(name, 'posix_prefix') if adapt: global_path = global_path.replace(sys.exec_prefix, sys.base_prefix) base = base.replace(sys.exec_prefix, sys.base_prefix) elif sys.base_prefix != sys.prefix: # virtual environment? Likewise, we have to adapt the paths # before comparing global_path = global_path.replace(sys.base_prefix, sys.prefix) base = base.replace(sys.base_prefix, sys.prefix) user_path = get_path(name, 'posix_user') self.assertEqual(user_path, global_path.replace(base, user, 1)) def test_main(self): # just making sure _main() runs and returns things in the stdout with captured_stdout() as output: _main() self.assertTrue(len(output.getvalue().split('\n')) > 0) @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows") def test_ldshared_value(self): ldflags = sysconfig.get_config_var('LDFLAGS') ldshared = sysconfig.get_config_var('LDSHARED') self.assertIn(ldflags, ldshared) @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX") def test_platform_in_subprocess(self): my_platform = sysconfig.get_platform() # Test without MACOSX_DEPLOYMENT_TARGET in the environment env = os.environ.copy() if 'MACOSX_DEPLOYMENT_TARGET' in env: del env['MACOSX_DEPLOYMENT_TARGET'] p = subprocess.Popen([ sys.executable, '-c', 'import sysconfig; print(sysconfig.get_platform())', ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env) test_platform = p.communicate()[0].strip() test_platform = test_platform.decode('utf-8') status = p.wait() self.assertEqual(status, 0) self.assertEqual(my_platform, test_platform) # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and # using a value that is unlikely to be the default one. env = os.environ.copy() env['MACOSX_DEPLOYMENT_TARGET'] = '10.1' p = subprocess.Popen([ sys.executable, '-c', 'import sysconfig; print(sysconfig.get_platform())', ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env) test_platform = p.communicate()[0].strip() test_platform = test_platform.decode('utf-8') status = p.wait() self.assertEqual(status, 0) self.assertEqual(my_platform, test_platform) def test_srcdir(self): # See Issues #15322, #15364. srcdir = sysconfig.get_config_var('srcdir') self.assertTrue(os.path.isabs(srcdir), srcdir) self.assertTrue(os.path.isdir(srcdir), srcdir) if sysconfig._PYTHON_BUILD: # The python executable has not been installed so srcdir # should be a full source checkout. Python_h = os.path.join(srcdir, 'Include', 'Python.h') self.assertTrue(os.path.exists(Python_h), Python_h) self.assertTrue(sysconfig._is_python_source_dir(srcdir)) elif os.name == 'posix': makefile_dir = os.path.dirname(sysconfig.get_makefile_filename()) # Issue #19340: srcdir has been realpath'ed already makefile_dir = os.path.realpath(makefile_dir) self.assertEqual(makefile_dir, srcdir) def test_srcdir_independent_of_cwd(self): # srcdir should be independent of the current working directory # See Issues #15322, #15364. srcdir = sysconfig.get_config_var('srcdir') with change_cwd(os.pardir): srcdir2 = sysconfig.get_config_var('srcdir') self.assertEqual(srcdir, srcdir2) @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None, 'EXT_SUFFIX required for this test') def test_SO_deprecation(self): self.assertWarns(DeprecationWarning, sysconfig.get_config_var, 'SO') @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None, 'EXT_SUFFIX required for this test') def test_SO_value(self): with check_warnings(('', DeprecationWarning)): self.assertEqual(sysconfig.get_config_var('SO'), sysconfig.get_config_var('EXT_SUFFIX')) @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None, 'EXT_SUFFIX required for this test') def test_SO_in_vars(self): vars = sysconfig.get_config_vars() self.assertIsNotNone(vars['SO']) self.assertEqual(vars['SO'], vars['EXT_SUFFIX']) @unittest.skipUnless(sys.platform == 'linux' and hasattr(sys.implementation, '_multiarch'), 'multiarch-specific test') def test_triplet_in_ext_suffix(self): ctypes = import_module('ctypes') import platform, re machine = platform.machine() suffix = sysconfig.get_config_var('EXT_SUFFIX') if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine): self.assertTrue('linux' in suffix, suffix) if re.match('(i[3-6]86|x86_64)$', machine): if ctypes.sizeof(ctypes.c_char_p()) == 4: self.assertTrue(suffix.endswith('i386-linux-gnu.so') or suffix.endswith('x86_64-linux-gnux32.so'), suffix) else: # 8 byte pointer size self.assertTrue(suffix.endswith('x86_64-linux-gnu.so'), suffix) @unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test') def test_osx_ext_suffix(self): suffix = sysconfig.get_config_var('EXT_SUFFIX') self.assertTrue(suffix.endswith('-darwin.so'), suffix) class MakefileTests(unittest.TestCase): @unittest.skipIf(sys.platform.startswith('win'), 'Test is not Windows compatible') def test_get_makefile_filename(self): makefile = sysconfig.get_makefile_filename() self.assertTrue(os.path.isfile(makefile), makefile) def test_parse_makefile(self): self.addCleanup(unlink, TESTFN) with open(TESTFN, "w") as makefile: print("var1=a$(VAR2)", file=makefile) print("VAR2=b$(var3)", file=makefile) print("var3=42", file=makefile) print("var4=$/invalid", file=makefile) print("var5=dollar$$5", file=makefile) print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)" "-x86_64-linux-gnu", file=makefile) vars = sysconfig._parse_makefile(TESTFN) self.assertEqual(vars, { 'var1': 'ab42', 'VAR2': 'b42', 'var3': 42, 'var4': '$/invalid', 'var5': 'dollar$5', 'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu', }) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/__init__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/__init__.py
# Dummy file to make this directory a package.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_charmapcodec.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_charmapcodec.py
""" Python character mapping codec test This uses the test codec in testcodec.py and thus also tests the encodings package lookup scheme. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright 2000 Guido van Rossum. """#" import unittest import codecs # Register a search function which knows about our codec def codec_search_function(encoding): if encoding == 'testcodec': from test import testcodec return tuple(testcodec.getregentry()) return None codecs.register(codec_search_function) # test codec's name (see test/testcodec.py) codecname = 'testcodec' class CharmapCodecTest(unittest.TestCase): def test_constructorx(self): self.assertEqual(str(b'abc', codecname), 'abc') self.assertEqual(str(b'xdef', codecname), 'abcdef') self.assertEqual(str(b'defx', codecname), 'defabc') self.assertEqual(str(b'dxf', codecname), 'dabcf') self.assertEqual(str(b'dxfx', codecname), 'dabcfabc') def test_encodex(self): self.assertEqual('abc'.encode(codecname), b'abc') self.assertEqual('xdef'.encode(codecname), b'abcdef') self.assertEqual('defx'.encode(codecname), b'defabc') self.assertEqual('dxf'.encode(codecname), b'dabcf') self.assertEqual('dxfx'.encode(codecname), b'dabcfabc') def test_constructory(self): self.assertEqual(str(b'ydef', codecname), 'def') self.assertEqual(str(b'defy', codecname), 'def') self.assertEqual(str(b'dyf', codecname), 'df') self.assertEqual(str(b'dyfy', codecname), 'df') def test_maptoundefined(self): self.assertRaises(UnicodeError, str, b'abc\001', codecname) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncgen.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncgen.py
import inspect import types import unittest from test.support import import_module asyncio = import_module("asyncio") class AwaitException(Exception): pass @types.coroutine def awaitable(*, throw=False): if throw: yield ('throw',) else: yield ('result',) def run_until_complete(coro): exc = False while True: try: if exc: exc = False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0] if fut == ('throw',): exc = True def to_list(gen): async def iterate(): res = [] async for i in gen: res.append(i) return res return run_until_complete(iterate()) class AsyncGenSyntaxTest(unittest.TestCase): def test_async_gen_syntax_01(self): code = '''async def foo(): await abc yield from 123 ''' with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'): exec(code, {}, {}) def test_async_gen_syntax_02(self): code = '''async def foo(): yield from 123 ''' with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'): exec(code, {}, {}) def test_async_gen_syntax_03(self): code = '''async def foo(): await abc yield return 123 ''' with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'): exec(code, {}, {}) def test_async_gen_syntax_04(self): code = '''async def foo(): yield return 123 ''' with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'): exec(code, {}, {}) def test_async_gen_syntax_05(self): code = '''async def foo(): if 0: yield return 12 ''' with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'): exec(code, {}, {}) class AsyncGenTest(unittest.TestCase): def compare_generators(self, sync_gen, async_gen): def sync_iterate(g): res = [] while True: try: res.append(g.__next__()) except StopIteration: res.append('STOP') break except Exception as ex: res.append(str(type(ex))) return res def async_iterate(g): res = [] while True: try: g.__anext__().__next__() except StopAsyncIteration: res.append('STOP') break except StopIteration as ex: if ex.args: res.append(ex.args[0]) else: res.append('EMPTY StopIteration') break except Exception as ex: res.append(str(type(ex))) return res sync_gen_result = sync_iterate(sync_gen) async_gen_result = async_iterate(async_gen) self.assertEqual(sync_gen_result, async_gen_result) return async_gen_result def test_async_gen_iteration_01(self): async def gen(): await awaitable() a = yield 123 self.assertIs(a, None) await awaitable() yield 456 await awaitable() yield 789 self.assertEqual(to_list(gen()), [123, 456, 789]) def test_async_gen_iteration_02(self): async def gen(): await awaitable() yield 123 await awaitable() g = gen() ai = g.__aiter__() self.assertEqual(ai.__anext__().__next__(), ('result',)) try: ai.__anext__().__next__() except StopIteration as ex: self.assertEqual(ex.args[0], 123) else: self.fail('StopIteration was not raised') self.assertEqual(ai.__anext__().__next__(), ('result',)) try: ai.__anext__().__next__() except StopAsyncIteration as ex: self.assertFalse(ex.args) else: self.fail('StopAsyncIteration was not raised') def test_async_gen_exception_03(self): async def gen(): await awaitable() yield 123 await awaitable(throw=True) yield 456 with self.assertRaises(AwaitException): to_list(gen()) def test_async_gen_exception_04(self): async def gen(): await awaitable() yield 123 1 / 0 g = gen() ai = g.__aiter__() self.assertEqual(ai.__anext__().__next__(), ('result',)) try: ai.__anext__().__next__() except StopIteration as ex: self.assertEqual(ex.args[0], 123) else: self.fail('StopIteration was not raised') with self.assertRaises(ZeroDivisionError): ai.__anext__().__next__() def test_async_gen_exception_05(self): async def gen(): yield 123 raise StopAsyncIteration with self.assertRaisesRegex(RuntimeError, 'async generator.*StopAsyncIteration'): to_list(gen()) def test_async_gen_exception_06(self): async def gen(): yield 123 raise StopIteration with self.assertRaisesRegex(RuntimeError, 'async generator.*StopIteration'): to_list(gen()) def test_async_gen_exception_07(self): def sync_gen(): try: yield 1 1 / 0 finally: yield 2 yield 3 yield 100 async def async_gen(): try: yield 1 1 / 0 finally: yield 2 yield 3 yield 100 self.compare_generators(sync_gen(), async_gen()) def test_async_gen_exception_08(self): def sync_gen(): try: yield 1 finally: yield 2 1 / 0 yield 3 yield 100 async def async_gen(): try: yield 1 await awaitable() finally: await awaitable() yield 2 1 / 0 yield 3 yield 100 self.compare_generators(sync_gen(), async_gen()) def test_async_gen_exception_09(self): def sync_gen(): try: yield 1 1 / 0 finally: yield 2 yield 3 yield 100 async def async_gen(): try: await awaitable() yield 1 1 / 0 finally: yield 2 await awaitable() yield 3 yield 100 self.compare_generators(sync_gen(), async_gen()) def test_async_gen_exception_10(self): async def gen(): yield 123 with self.assertRaisesRegex(TypeError, "non-None value .* async generator"): gen().__anext__().send(100) def test_async_gen_api_01(self): async def gen(): yield 123 g = gen() self.assertEqual(g.__name__, 'gen') g.__name__ = '123' self.assertEqual(g.__name__, '123') self.assertIn('.gen', g.__qualname__) g.__qualname__ = '123' self.assertEqual(g.__qualname__, '123') self.assertIsNone(g.ag_await) self.assertIsInstance(g.ag_frame, types.FrameType) self.assertFalse(g.ag_running) self.assertIsInstance(g.ag_code, types.CodeType) self.assertTrue(inspect.isawaitable(g.aclose())) class AsyncGenAsyncioTest(unittest.TestCase): def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() self.loop = None async def to_list(self, gen): res = [] async for i in gen: res.append(i) return res def test_async_gen_asyncio_01(self): async def gen(): yield 1 await asyncio.sleep(0.01, loop=self.loop) 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]) def test_async_gen_asyncio_02(self): async def gen(): yield 1 await asyncio.sleep(0.01, loop=self.loop) yield 2 1 / 0 yield 3 with self.assertRaises(ZeroDivisionError): self.loop.run_until_complete(self.to_list(gen())) def test_async_gen_asyncio_03(self): loop = self.loop class Gen: async def __aiter__(self): yield 1 await asyncio.sleep(0.01, loop=loop) yield 2 res = loop.run_until_complete(self.to_list(Gen())) self.assertEqual(res, [1, 2]) def test_async_gen_asyncio_anext_04(self): async def foo(): yield 1 await asyncio.sleep(0.01, loop=self.loop) try: yield 2 yield 3 except ZeroDivisionError: yield 1000 await asyncio.sleep(0.01, loop=self.loop) yield 4 async def run1(): it = foo().__aiter__() self.assertEqual(await it.__anext__(), 1) self.assertEqual(await it.__anext__(), 2) self.assertEqual(await it.__anext__(), 3) self.assertEqual(await it.__anext__(), 4) with self.assertRaises(StopAsyncIteration): await it.__anext__() with self.assertRaises(StopAsyncIteration): await it.__anext__() async def run2(): it = foo().__aiter__() self.assertEqual(await it.__anext__(), 1) self.assertEqual(await it.__anext__(), 2) try: it.__anext__().throw(ZeroDivisionError) except StopIteration as ex: self.assertEqual(ex.args[0], 1000) else: self.fail('StopIteration was not raised') self.assertEqual(await it.__anext__(), 4) with self.assertRaises(StopAsyncIteration): await it.__anext__() self.loop.run_until_complete(run1()) self.loop.run_until_complete(run2()) def test_async_gen_asyncio_anext_05(self): async def foo(): v = yield 1 v = yield v yield v * 100 async def run(): it = foo().__aiter__() try: it.__anext__().send(None) except StopIteration as ex: self.assertEqual(ex.args[0], 1) else: self.fail('StopIteration was not raised') try: it.__anext__().send(10) except StopIteration as ex: self.assertEqual(ex.args[0], 10) else: self.fail('StopIteration was not raised') try: it.__anext__().send(12) except StopIteration as ex: self.assertEqual(ex.args[0], 1200) else: self.fail('StopIteration was not raised') with self.assertRaises(StopAsyncIteration): await it.__anext__() self.loop.run_until_complete(run()) def test_async_gen_asyncio_anext_06(self): DONE = 0 # test synchronous generators def foo(): try: yield except: pass g = foo() g.send(None) with self.assertRaises(StopIteration): g.send(None) # now with asynchronous generators async def gen(): nonlocal DONE try: yield except: pass DONE = 1 async def run(): nonlocal DONE g = gen() await g.asend(None) with self.assertRaises(StopAsyncIteration): await g.asend(None) DONE += 10 self.loop.run_until_complete(run()) self.assertEqual(DONE, 11) def test_async_gen_asyncio_anext_tuple(self): async def foo(): try: yield (1,) except ZeroDivisionError: yield (2,) async def run(): it = foo().__aiter__() self.assertEqual(await it.__anext__(), (1,)) with self.assertRaises(StopIteration) as cm: it.__anext__().throw(ZeroDivisionError) self.assertEqual(cm.exception.args[0], (2,)) with self.assertRaises(StopAsyncIteration): await it.__anext__() self.loop.run_until_complete(run()) def test_async_gen_asyncio_anext_stopiteration(self): async def foo(): try: yield StopIteration(1) except ZeroDivisionError: yield StopIteration(3) async def run(): it = foo().__aiter__() v = await it.__anext__() self.assertIsInstance(v, StopIteration) self.assertEqual(v.value, 1) with self.assertRaises(StopIteration) as cm: it.__anext__().throw(ZeroDivisionError) v = cm.exception.args[0] self.assertIsInstance(v, StopIteration) self.assertEqual(v.value, 3) with self.assertRaises(StopAsyncIteration): await it.__anext__() self.loop.run_until_complete(run()) def test_async_gen_asyncio_aclose_06(self): async def foo(): try: yield 1 1 / 0 finally: await asyncio.sleep(0.01, loop=self.loop) yield 12 async def run(): gen = foo() it = gen.__aiter__() await it.__anext__() await gen.aclose() with self.assertRaisesRegex( RuntimeError, "async generator ignored GeneratorExit"): self.loop.run_until_complete(run()) def test_async_gen_asyncio_aclose_07(self): DONE = 0 async def foo(): nonlocal DONE try: yield 1 1 / 0 finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE += 1 DONE += 1000 async def run(): gen = foo() it = gen.__aiter__() await it.__anext__() await gen.aclose() self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_aclose_08(self): DONE = 0 fut = asyncio.Future(loop=self.loop) async def foo(): nonlocal DONE try: yield 1 await fut DONE += 1000 yield 2 finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE += 1 DONE += 1000 async def run(): gen = foo() it = gen.__aiter__() self.assertEqual(await it.__anext__(), 1) t = self.loop.create_task(it.__anext__()) await asyncio.sleep(0.01, loop=self.loop) await gen.aclose() return t t = self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) # Silence ResourceWarnings fut.cancel() t.cancel() self.loop.run_until_complete(asyncio.sleep(0.01, loop=self.loop)) def test_async_gen_asyncio_gc_aclose_09(self): DONE = 0 async def gen(): nonlocal DONE try: while True: yield 1 finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() await g.__anext__() await g.__anext__() del g await asyncio.sleep(0.1, loop=self.loop) self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_aclose_10(self): DONE = 0 # test synchronous generators def foo(): try: yield except: pass g = foo() g.send(None) g.close() # now with asynchronous generators async def gen(): nonlocal DONE try: yield except: pass DONE = 1 async def run(): nonlocal DONE g = gen() await g.asend(None) await g.aclose() DONE += 10 self.loop.run_until_complete(run()) self.assertEqual(DONE, 11) def test_async_gen_asyncio_aclose_11(self): DONE = 0 # test synchronous generators def foo(): try: yield except: pass yield g = foo() g.send(None) with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'): g.close() # now with asynchronous generators async def gen(): nonlocal DONE try: yield except: pass yield DONE += 1 async def run(): nonlocal DONE g = gen() await g.asend(None) with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'): await g.aclose() DONE += 10 self.loop.run_until_complete(run()) self.assertEqual(DONE, 10) def test_async_gen_asyncio_aclose_12(self): DONE = 0 async def target(): await asyncio.sleep(0.01) 1 / 0 async def foo(): nonlocal DONE task = asyncio.create_task(target()) try: yield 1 finally: try: await task except ZeroDivisionError: DONE = 1 async def run(): gen = foo() it = gen.__aiter__() await it.__anext__() await gen.aclose() self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_asend_01(self): DONE = 0 # Sanity check: def sgen(): v = yield 1 yield v * 2 sg = sgen() v = sg.send(None) self.assertEqual(v, 1) v = sg.send(100) self.assertEqual(v, 200) async def gen(): nonlocal DONE try: await asyncio.sleep(0.01, loop=self.loop) v = yield 1 await asyncio.sleep(0.01, loop=self.loop) yield v * 2 await asyncio.sleep(0.01, loop=self.loop) return finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) v = await g.asend(100) self.assertEqual(v, 200) with self.assertRaises(StopAsyncIteration): await g.asend(None) self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_asend_02(self): DONE = 0 async def sleep_n_crash(delay): await asyncio.sleep(delay, loop=self.loop) 1 / 0 async def gen(): nonlocal DONE try: await asyncio.sleep(0.01, loop=self.loop) v = yield 1 await sleep_n_crash(0.01) DONE += 1000 yield v * 2 finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) await g.asend(100) with self.assertRaises(ZeroDivisionError): self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_asend_03(self): DONE = 0 async def sleep_n_crash(delay): fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop), loop=self.loop) self.loop.call_later(delay / 2, lambda: fut.cancel()) return await fut async def gen(): nonlocal DONE try: await asyncio.sleep(0.01, loop=self.loop) v = yield 1 await sleep_n_crash(0.01) DONE += 1000 yield v * 2 finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) await g.asend(100) with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_athrow_01(self): DONE = 0 class FooEr(Exception): pass # Sanity check: def sgen(): try: v = yield 1 except FooEr: v = 1000 yield v * 2 sg = sgen() v = sg.send(None) self.assertEqual(v, 1) v = sg.throw(FooEr) self.assertEqual(v, 2000) with self.assertRaises(StopIteration): sg.send(None) async def gen(): nonlocal DONE try: await asyncio.sleep(0.01, loop=self.loop) try: v = yield 1 except FooEr: v = 1000 await asyncio.sleep(0.01, loop=self.loop) yield v * 2 await asyncio.sleep(0.01, loop=self.loop) # return finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) v = await g.athrow(FooEr) self.assertEqual(v, 2000) with self.assertRaises(StopAsyncIteration): await g.asend(None) self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_athrow_02(self): DONE = 0 class FooEr(Exception): pass async def sleep_n_crash(delay): fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop), loop=self.loop) self.loop.call_later(delay / 2, lambda: fut.cancel()) return await fut async def gen(): nonlocal DONE try: await asyncio.sleep(0.01, loop=self.loop) try: v = yield 1 except FooEr: await sleep_n_crash(0.01) yield v * 2 await asyncio.sleep(0.01, loop=self.loop) # return finally: await asyncio.sleep(0.01, loop=self.loop) await asyncio.sleep(0.01, loop=self.loop) DONE = 1 async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) try: await g.athrow(FooEr) except asyncio.CancelledError: self.assertEqual(DONE, 1) raise else: self.fail('CancelledError was not raised') with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(run()) self.assertEqual(DONE, 1) def test_async_gen_asyncio_athrow_03(self): DONE = 0 # test synchronous generators def foo(): try: yield except: pass g = foo() g.send(None) with self.assertRaises(StopIteration): g.throw(ValueError) # now with asynchronous generators async def gen(): nonlocal DONE try: yield except: pass DONE = 1 async def run(): nonlocal DONE g = gen() await g.asend(None) with self.assertRaises(StopAsyncIteration): await g.athrow(ValueError) DONE += 10 self.loop.run_until_complete(run()) self.assertEqual(DONE, 11) def test_async_gen_asyncio_athrow_tuple(self): async def gen(): try: yield 1 except ZeroDivisionError: yield (2,) async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) v = await g.athrow(ZeroDivisionError) self.assertEqual(v, (2,)) with self.assertRaises(StopAsyncIteration): await g.asend(None) self.loop.run_until_complete(run()) def test_async_gen_asyncio_athrow_stopiteration(self): async def gen(): try: yield 1 except ZeroDivisionError: yield StopIteration(2) async def run(): g = gen() v = await g.asend(None) self.assertEqual(v, 1) v = await g.athrow(ZeroDivisionError) self.assertIsInstance(v, StopIteration) self.assertEqual(v.value, 2) with self.assertRaises(StopAsyncIteration): await g.asend(None) self.loop.run_until_complete(run()) def test_async_gen_asyncio_shutdown_01(self): finalized = 0 async def waiter(timeout): nonlocal finalized try: await asyncio.sleep(timeout, loop=self.loop) yield 1 finally: await asyncio.sleep(0, loop=self.loop) finalized += 1 async def wait(): async for _ in waiter(1): pass t1 = self.loop.create_task(wait()) t2 = self.loop.create_task(wait()) self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop)) self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.assertEqual(finalized, 2) # Silence warnings t1.cancel() t2.cancel() self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop)) def test_async_gen_asyncio_shutdown_02(self): logged = 0 def logger(loop, context): nonlocal logged self.assertIn('asyncgen', context) expected = 'an error occurred during closing of asynchronous' if expected in context['message']: logged += 1 async def waiter(timeout): try: await asyncio.sleep(timeout, loop=self.loop) yield 1 finally: 1 / 0 async def wait(): async for _ in waiter(1): pass t = self.loop.create_task(wait()) self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop)) self.loop.set_exception_handler(logger) self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.assertEqual(logged, 1) # Silence warnings t.cancel() self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop)) def test_async_gen_expression_01(self): async def arange(n): for i in range(n): await asyncio.sleep(0.01, loop=self.loop) yield i def make_arange(n): # This syntax is legal starting with Python 3.7 return (i * 2 async for i in arange(n)) async def run(): return [i async for i in make_arange(10)] res = self.loop.run_until_complete(run()) self.assertEqual(res, [i * 2 for i in range(10)]) def test_async_gen_expression_02(self): async def wrap(n): await asyncio.sleep(0.01, loop=self.loop) return n def make_arange(n): # This syntax is legal starting with Python 3.7 return (i * 2 for i in range(n) if await wrap(i)) async def run(): return [i async for i in make_arange(10)] res = self.loop.run_until_complete(run()) self.assertEqual(res, [i * 2 for i in range(1, 10)]) def test_asyncgen_nonstarted_hooks_are_cancellable(self): # See https://bugs.python.org/issue38013 messages = [] def exception_handler(loop, context): messages.append(context) async def async_iterate(): yield 1 yield 2 async def main(): loop = asyncio.get_running_loop() loop.set_exception_handler(exception_handler) async for i in async_iterate(): break asyncio.run(main()) self.assertEqual([], messages) def test_async_gen_await_same_anext_coro_twice(self): async def async_iterate(): yield 1 yield 2 async def run(): it = async_iterate() nxt = it.__anext__() await nxt with self.assertRaisesRegex( RuntimeError, r"cannot reuse already awaited __anext__\(\)/asend\(\)" ): await nxt await it.aclose() # prevent unfinished iterator warning self.loop.run_until_complete(run()) def test_async_gen_await_same_aclose_coro_twice(self): async def async_iterate(): yield 1 yield 2 async def run(): it = async_iterate() nxt = it.aclose() await nxt with self.assertRaisesRegex( RuntimeError, r"cannot reuse already awaited aclose\(\)/athrow\(\)" ): await nxt self.loop.run_until_complete(run()) def test_async_gen_aclose_twice_with_different_coros(self): # Regression test for https://bugs.python.org/issue39606 async def async_iterate(): yield 1 yield 2 async def run(): it = async_iterate() await it.aclose() await it.aclose() self.loop.run_until_complete(run()) def test_async_gen_aclose_after_exhaustion(self): # Regression test for https://bugs.python.org/issue39606 async def async_iterate(): yield 1 yield 2 async def run(): it = async_iterate() async for _ in it: pass await it.aclose() self.loop.run_until_complete(run()) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/datetimetester.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/datetimetester.py
"""Test date/time type. See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ import itertools import bisect import copy import decimal import sys import os import pickle import random import re import struct import unittest from array import array from operator import lt, le, gt, ge, eq, ne, truediv, floordiv, mod from test import support from test.support import is_resource_enabled, ALWAYS_EQ, LARGEST, SMALLEST import datetime as datetime_module from datetime import MINYEAR, MAXYEAR from datetime import timedelta from datetime import tzinfo from datetime import time from datetime import timezone from datetime import date, datetime import time as _time import _testcapi # Needed by test_datetime import _strptime # pickle_loads = {pickle.loads, pickle._loads} pickle_choices = [(pickle, pickle, proto) for proto in range(pickle.HIGHEST_PROTOCOL + 1)] assert len(pickle_choices) == pickle.HIGHEST_PROTOCOL + 1 # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. OTHERSTUFF = (10, 34.5, "abc", {}, [], ()) # XXX Copied from test_float. INF = float("inf") NAN = float("nan") ############################################################################# # module tests class TestModule(unittest.TestCase): def test_constants(self): datetime = datetime_module self.assertEqual(datetime.MINYEAR, 1) self.assertEqual(datetime.MAXYEAR, 9999) def test_name_cleanup(self): if '_Pure' in self.__class__.__name__: 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('__')) allowed = set(['MAXYEAR', 'MINYEAR', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo', 'sys']) self.assertEqual(names - allowed, set([])) def test_divide_and_round(self): if '_Fast' in self.__class__.__name__: self.skipTest('Only run for Pure Python implementation') dar = datetime_module._divide_and_round self.assertEqual(dar(-10, -3), 3) self.assertEqual(dar(5, -2), -2) # four cases: (2 signs of a) x (2 signs of b) self.assertEqual(dar(7, 3), 2) self.assertEqual(dar(-7, 3), -2) self.assertEqual(dar(7, -3), -2) self.assertEqual(dar(-7, -3), 2) # ties to even - eight cases: # (2 signs of a) x (2 signs of b) x (even / odd quotient) self.assertEqual(dar(10, 4), 2) self.assertEqual(dar(-10, 4), -2) self.assertEqual(dar(10, -4), -2) self.assertEqual(dar(-10, -4), 2) self.assertEqual(dar(6, 4), 2) self.assertEqual(dar(-6, 4), -2) self.assertEqual(dar(6, -4), -2) self.assertEqual(dar(-6, -4), 2) ############################################################################# # tzinfo tests class FixedOffset(tzinfo): def __init__(self, offset, name, dstoffset=42): if isinstance(offset, int): offset = timedelta(minutes=offset) if isinstance(dstoffset, int): dstoffset = timedelta(minutes=dstoffset) self.__offset = offset self.__name = name self.__dstoffset = dstoffset def __repr__(self): return self.__name.lower() def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return self.__dstoffset class PicklableFixedOffset(FixedOffset): def __init__(self, offset=None, name=None, dstoffset=None): FixedOffset.__init__(self, offset, name, dstoffset) def __getstate__(self): return self.__dict__ class _TZInfo(tzinfo): def utcoffset(self, datetime_module): return random.random() class TestTZInfo(unittest.TestCase): def test_refcnt_crash_bug_22044(self): tz1 = _TZInfo() dt1 = datetime(2014, 7, 21, 11, 32, 3, 0, tz1) with self.assertRaises(TypeError): dt1.utcoffset() def test_non_abstractness(self): # In order to allow subclasses to get pickled, the C implementation # wasn't able to get away with having __init__ raise # NotImplementedError. useless = tzinfo() dt = datetime.max self.assertRaises(NotImplementedError, useless.tzname, dt) self.assertRaises(NotImplementedError, useless.utcoffset, dt) self.assertRaises(NotImplementedError, useless.dst, dt) def test_subclass_must_override(self): class NotEnough(tzinfo): def __init__(self, offset, name): self.__offset = offset self.__name = name self.assertTrue(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") self.assertIsInstance(ne, tzinfo) dt = datetime.now() self.assertRaises(NotImplementedError, ne.tzname, dt) self.assertRaises(NotImplementedError, ne.utcoffset, dt) self.assertRaises(NotImplementedError, ne.dst, dt) def test_normal(self): fo = FixedOffset(3, "Three") self.assertIsInstance(fo, tzinfo) for dt in datetime.now(), None: self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) self.assertEqual(fo.tzname(dt), "Three") self.assertEqual(fo.dst(dt), timedelta(minutes=42)) def test_pickling_base(self): # There's no point to pickling tzinfo objects on their own (they # carry no data), but they need to be picklable anyway else # concrete subclasses can't be pickled. orig = tzinfo.__new__(tzinfo) self.assertIs(type(orig), tzinfo) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertIs(type(derived), tzinfo) def test_pickling_subclass(self): # Make sure we can pickle/unpickle an instance of a subclass. offset = timedelta(minutes=-300) for otype, args in [ (PicklableFixedOffset, (offset, 'cookie')), (timezone, (offset,)), (timezone, (offset, "EST"))]: orig = otype(*args) oname = orig.tzname(None) self.assertIsInstance(orig, tzinfo) self.assertIs(type(orig), otype) self.assertEqual(orig.utcoffset(None), offset) self.assertEqual(orig.tzname(None), oname) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertIsInstance(derived, tzinfo) self.assertIs(type(derived), otype) self.assertEqual(derived.utcoffset(None), offset) self.assertEqual(derived.tzname(None), oname) def test_issue23600(self): DSTDIFF = DSTOFFSET = timedelta(hours=1) class UKSummerTime(tzinfo): """Simple time zone which pretends to always be in summer time, since that's what shows the failure. """ def utcoffset(self, dt): return DSTOFFSET def dst(self, dt): return DSTDIFF def tzname(self, dt): return 'UKSummerTime' tz = UKSummerTime() u = datetime(2014, 4, 26, 12, 1, tzinfo=tz) t = tz.fromutc(u) self.assertEqual(t - t.utcoffset(), u) class TestTimeZone(unittest.TestCase): def setUp(self): self.ACDT = timezone(timedelta(hours=9.5), 'ACDT') self.EST = timezone(-timedelta(hours=5), 'EST') self.DT = datetime(2010, 1, 1) def test_str(self): for tz in [self.ACDT, self.EST, timezone.utc, timezone.min, timezone.max]: self.assertEqual(str(tz), tz.tzname(None)) def test_repr(self): datetime = datetime_module for tz in [self.ACDT, self.EST, timezone.utc, timezone.min, timezone.max]: # test round-trip tzrep = repr(tz) self.assertEqual(tz, eval(tzrep)) def test_class_members(self): limit = timedelta(hours=23, minutes=59) self.assertEqual(timezone.utc.utcoffset(None), ZERO) self.assertEqual(timezone.min.utcoffset(None), -limit) self.assertEqual(timezone.max.utcoffset(None), limit) def test_constructor(self): self.assertIs(timezone.utc, timezone(timedelta(0))) self.assertIsNot(timezone.utc, timezone(timedelta(0), 'UTC')) self.assertEqual(timezone.utc, timezone(timedelta(0), 'UTC')) for subminute in [timedelta(microseconds=1), timedelta(seconds=1)]: tz = timezone(subminute) self.assertNotEqual(tz.utcoffset(None) % timedelta(minutes=1), 0) # invalid offsets for invalid in [timedelta(1, 1), timedelta(1)]: self.assertRaises(ValueError, timezone, invalid) self.assertRaises(ValueError, timezone, -invalid) with self.assertRaises(TypeError): timezone(None) with self.assertRaises(TypeError): timezone(42) with self.assertRaises(TypeError): timezone(ZERO, None) with self.assertRaises(TypeError): timezone(ZERO, 42) with self.assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra') def test_inheritance(self): self.assertIsInstance(timezone.utc, tzinfo) self.assertIsInstance(self.EST, tzinfo) def test_utcoffset(self): dummy = self.DT for h in [0, 1.5, 12]: offset = h * HOUR self.assertEqual(offset, timezone(offset).utcoffset(dummy)) self.assertEqual(-offset, timezone(-offset).utcoffset(dummy)) with self.assertRaises(TypeError): self.EST.utcoffset('') with self.assertRaises(TypeError): self.EST.utcoffset(5) def test_dst(self): self.assertIsNone(timezone.utc.dst(self.DT)) with self.assertRaises(TypeError): self.EST.dst('') with self.assertRaises(TypeError): self.EST.dst(5) def test_tzname(self): self.assertEqual('UTC', timezone.utc.tzname(None)) self.assertEqual('UTC', timezone(ZERO).tzname(None)) self.assertEqual('UTC-05:00', timezone(-5 * HOUR).tzname(None)) self.assertEqual('UTC+09:30', timezone(9.5 * HOUR).tzname(None)) self.assertEqual('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None)) self.assertEqual('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None)) # bpo-34482: Check that surrogates are handled properly. self.assertEqual('\ud800', timezone(ZERO, '\ud800').tzname(None)) # Sub-minute offsets: self.assertEqual('UTC+01:06:40', timezone(timedelta(0, 4000)).tzname(None)) self.assertEqual('UTC-01:06:40', timezone(-timedelta(0, 4000)).tzname(None)) self.assertEqual('UTC+01:06:40.000001', timezone(timedelta(0, 4000, 1)).tzname(None)) self.assertEqual('UTC-01:06:40.000001', timezone(-timedelta(0, 4000, 1)).tzname(None)) with self.assertRaises(TypeError): self.EST.tzname('') with self.assertRaises(TypeError): self.EST.tzname(5) def test_fromutc(self): with self.assertRaises(ValueError): timezone.utc.fromutc(self.DT) with self.assertRaises(TypeError): timezone.utc.fromutc('not datetime') for tz in [self.EST, self.ACDT, Eastern]: utctime = self.DT.replace(tzinfo=tz) local = tz.fromutc(utctime) self.assertEqual(local - utctime, tz.utcoffset(local)) self.assertEqual(local, self.DT.replace(tzinfo=timezone.utc)) def test_comparison(self): self.assertNotEqual(timezone(ZERO), timezone(HOUR)) self.assertEqual(timezone(HOUR), timezone(HOUR)) self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST')) with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO) self.assertIn(timezone(ZERO), {timezone(ZERO)}) self.assertTrue(timezone(ZERO) != None) self.assertFalse(timezone(ZERO) == None) tz = timezone(ZERO) self.assertTrue(tz == ALWAYS_EQ) self.assertFalse(tz != ALWAYS_EQ) self.assertTrue(tz < LARGEST) self.assertFalse(tz > LARGEST) self.assertTrue(tz <= LARGEST) self.assertFalse(tz >= LARGEST) self.assertFalse(tz < SMALLEST) self.assertTrue(tz > SMALLEST) self.assertFalse(tz <= SMALLEST) self.assertTrue(tz >= SMALLEST) def test_aware_datetime(self): # test that timezone instances can be used by datetime t = datetime(1, 1, 1) for tz in [timezone.min, timezone.max, timezone.utc]: self.assertEqual(tz.tzname(t), t.replace(tzinfo=tz).tzname()) self.assertEqual(tz.utcoffset(t), t.replace(tzinfo=tz).utcoffset()) self.assertEqual(tz.dst(t), t.replace(tzinfo=tz).dst()) def test_pickle(self): for tz in self.ACDT, self.EST, timezone.min, timezone.max: for pickler, unpickler, proto in pickle_choices: tz_copy = unpickler.loads(pickler.dumps(tz, proto)) self.assertEqual(tz_copy, tz) tz = timezone.utc for pickler, unpickler, proto in pickle_choices: tz_copy = unpickler.loads(pickler.dumps(tz, proto)) self.assertIs(tz_copy, tz) def test_copy(self): for tz in self.ACDT, self.EST, timezone.min, timezone.max: tz_copy = copy.copy(tz) self.assertEqual(tz_copy, tz) tz = timezone.utc tz_copy = copy.copy(tz) self.assertIs(tz_copy, tz) def test_deepcopy(self): for tz in self.ACDT, self.EST, timezone.min, timezone.max: tz_copy = copy.deepcopy(tz) self.assertEqual(tz_copy, tz) tz = timezone.utc tz_copy = copy.deepcopy(tz) self.assertIs(tz_copy, tz) def test_offset_boundaries(self): # Test timedeltas close to the boundaries time_deltas = [ timedelta(hours=23, minutes=59), timedelta(hours=23, minutes=59, seconds=59), timedelta(hours=23, minutes=59, seconds=59, microseconds=999999), ] time_deltas.extend([-delta for delta in time_deltas]) for delta in time_deltas: with self.subTest(test_type='good', delta=delta): timezone(delta) # Test timedeltas on and outside the boundaries bad_time_deltas = [ timedelta(hours=24), timedelta(hours=24, microseconds=1), ] bad_time_deltas.extend([-delta for delta in bad_time_deltas]) for delta in bad_time_deltas: with self.subTest(test_type='bad', delta=delta): with self.assertRaises(ValueError): timezone(delta) def test_comparison_with_tzinfo(self): # Constructing tzinfo objects directly should not be done by users # and serves only to check the bug described in bpo-37915 self.assertNotEqual(timezone.utc, tzinfo()) self.assertNotEqual(timezone(timedelta(hours=1)), tzinfo()) ############################################################################# # Base class for testing a particular aspect of timedelta, time, date and # datetime comparisons. class HarmlessMixedComparison: # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a # legit constructor. def test_harmless_mixed_comparison(self): me = self.theclass(1, 1, 1) self.assertFalse(me == ()) self.assertTrue(me != ()) self.assertFalse(() == me) self.assertTrue(() != me) self.assertIn(me, [1, 20, [], me]) self.assertIn([], [me, 1, 20, []]) # Comparison to objects of unsupported types should return # NotImplemented which falls back to the right hand side's __eq__ # method. In this case, ALWAYS_EQ.__eq__ always returns True. # ALWAYS_EQ.__ne__ always returns False. self.assertTrue(me == ALWAYS_EQ) self.assertFalse(me != ALWAYS_EQ) # If the other class explicitly defines ordering # relative to our class, it is allowed to do so self.assertTrue(me < LARGEST) self.assertFalse(me > LARGEST) self.assertTrue(me <= LARGEST) self.assertFalse(me >= LARGEST) self.assertFalse(me < SMALLEST) self.assertTrue(me > SMALLEST) self.assertFalse(me <= SMALLEST) self.assertTrue(me >= SMALLEST) def test_harmful_mixed_comparison(self): me = self.theclass(1, 1, 1) self.assertRaises(TypeError, lambda: me < ()) self.assertRaises(TypeError, lambda: me <= ()) self.assertRaises(TypeError, lambda: me > ()) self.assertRaises(TypeError, lambda: me >= ()) self.assertRaises(TypeError, lambda: () < me) self.assertRaises(TypeError, lambda: () <= me) self.assertRaises(TypeError, lambda: () > me) self.assertRaises(TypeError, lambda: () >= me) ############################################################################# # timedelta tests class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): theclass = timedelta def test_constructor(self): eq = self.assertEqual td = timedelta # Check keyword args to constructor eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0)) eq(td(1), td(days=1)) eq(td(0, 1), td(seconds=1)) eq(td(0, 0, 1), td(microseconds=1)) eq(td(weeks=1), td(days=7)) eq(td(days=1), td(hours=24)) eq(td(hours=1), td(minutes=60)) eq(td(minutes=1), td(seconds=60)) eq(td(seconds=1), td(milliseconds=1000)) eq(td(milliseconds=1), td(microseconds=1000)) # Check float args to constructor eq(td(weeks=1.0/7), td(days=1)) eq(td(days=1.0/24), td(hours=1)) eq(td(hours=1.0/60), td(minutes=1)) eq(td(minutes=1.0/60), td(seconds=1)) eq(td(seconds=0.001), td(milliseconds=1)) eq(td(milliseconds=0.001), td(microseconds=1)) def test_computations(self): eq = self.assertEqual td = timedelta a = td(7) # One week b = td(0, 60) # One minute c = td(0, 0, 1000) # One millisecond eq(a+b+c, td(7, 60, 1000)) eq(a-b, td(6, 24*3600 - 60)) eq(b.__rsub__(a), td(6, 24*3600 - 60)) eq(-a, td(-7)) eq(+a, td(7)) eq(-b, td(-1, 24*3600 - 60)) eq(-c, td(-1, 24*3600 - 1, 999000)) eq(abs(a), a) eq(abs(-a), a) eq(td(6, 24*3600), a) eq(td(0, 0, 60*1000000), b) eq(a*10, td(70)) eq(a*10, 10*a) eq(a*10, 10*a) eq(b*10, td(0, 600)) eq(10*b, td(0, 600)) eq(b*10, td(0, 600)) eq(c*10, td(0, 0, 10000)) eq(10*c, td(0, 0, 10000)) eq(c*10, td(0, 0, 10000)) eq(a*-1, -a) eq(b*-2, -b-b) eq(c*-2, -c+-c) eq(b*(60*24), (b*60)*24) eq(b*(60*24), (60*b)*24) eq(c*1000, td(0, 1)) eq(1000*c, td(0, 1)) eq(a//7, td(1)) eq(b//10, td(0, 6)) eq(c//1000, td(0, 0, 1)) eq(a//10, td(0, 7*24*360)) eq(a//3600000, td(0, 0, 7*24*1000)) eq(a/0.5, td(14)) eq(b/0.5, td(0, 120)) eq(a/7, td(1)) eq(b/10, td(0, 6)) eq(c/1000, td(0, 0, 1)) eq(a/10, td(0, 7*24*360)) eq(a/3600000, td(0, 0, 7*24*1000)) # Multiplication by float us = td(microseconds=1) eq((3*us) * 0.5, 2*us) eq((5*us) * 0.5, 2*us) eq(0.5 * (3*us), 2*us) eq(0.5 * (5*us), 2*us) eq((-3*us) * 0.5, -2*us) eq((-5*us) * 0.5, -2*us) # Issue #23521 eq(td(seconds=1) * 0.123456, td(microseconds=123456)) eq(td(seconds=1) * 0.6112295, td(microseconds=611229)) # Division by int and float eq((3*us) / 2, 2*us) eq((5*us) / 2, 2*us) eq((-3*us) / 2.0, -2*us) eq((-5*us) / 2.0, -2*us) eq((3*us) / -2, -2*us) eq((5*us) / -2, -2*us) eq((3*us) / -2.0, -2*us) eq((5*us) / -2.0, -2*us) for i in range(-10, 10): eq((i*us/3)//us, round(i/3)) for i in range(-10, 10): eq((i*us/-3)//us, round(i/-3)) # Issue #23521 eq(td(seconds=1) / (1 / 0.6112295), td(microseconds=611229)) # Issue #11576 eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998), td(0, 0, 1)) eq(td(999999999, 1, 1) - td(999999999, 1, 0), td(0, 0, 1)) def test_disallowed_computations(self): a = timedelta(42) # Add/sub ints or floats should be illegal for i in 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i-a) # Division of int by timedelta doesn't make sense. # Division by zero doesn't make sense. zero = 0 self.assertRaises(TypeError, lambda: zero // a) self.assertRaises(ZeroDivisionError, lambda: a // zero) self.assertRaises(ZeroDivisionError, lambda: a / zero) self.assertRaises(ZeroDivisionError, lambda: a / 0.0) self.assertRaises(TypeError, lambda: a / '') @support.requires_IEEE_754 def test_disallowed_special(self): a = timedelta(42) self.assertRaises(ValueError, a.__mul__, NAN) self.assertRaises(ValueError, a.__truediv__, NAN) def test_basic_attributes(self): days, seconds, us = 1, 7, 31 td = timedelta(days, seconds, us) self.assertEqual(td.days, days) self.assertEqual(td.seconds, seconds) self.assertEqual(td.microseconds, us) def test_total_seconds(self): td = timedelta(days=365) self.assertEqual(td.total_seconds(), 31536000.0) for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]: td = timedelta(seconds=total_seconds) self.assertEqual(td.total_seconds(), total_seconds) # Issue8644: Test that td.total_seconds() has the same # accuracy as td / timedelta(seconds=1). for ms in [-1, -2, -123]: td = timedelta(microseconds=ms) self.assertEqual(td.total_seconds(), td / timedelta(seconds=1)) def test_carries(self): t1 = timedelta(days=100, weeks=-7, hours=-24*(100-49), minutes=-3, seconds=12, microseconds=(3*60 - 12) * 1e6 + 1) t2 = timedelta(microseconds=1) self.assertEqual(t1, t2) def test_hash_equality(self): t1 = timedelta(days=100, weeks=-7, hours=-24*(100-49), minutes=-3, seconds=12, microseconds=(3*60 - 12) * 1000000) t2 = timedelta() self.assertEqual(hash(t1), hash(t2)) t1 += timedelta(weeks=7) t2 += timedelta(days=7*7) self.assertEqual(t1, t2) self.assertEqual(hash(t1), hash(t2)) d = {t1: 1} d[t2] = 2 self.assertEqual(len(d), 1) self.assertEqual(d[t1], 2) def test_pickling(self): args = 12, 34, 56 orig = timedelta(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertEqual(orig, derived) def test_compare(self): t1 = timedelta(2, 3, 4) t2 = timedelta(2, 3, 4) self.assertEqual(t1, t2) self.assertTrue(t1 <= t2) self.assertTrue(t1 >= t2) self.assertFalse(t1 != t2) self.assertFalse(t1 < t2) self.assertFalse(t1 > t2) for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): t2 = timedelta(*args) # this is larger than t1 self.assertTrue(t1 < t2) self.assertTrue(t2 > t1) self.assertTrue(t1 <= t2) self.assertTrue(t2 >= t1) self.assertTrue(t1 != t2) self.assertTrue(t2 != t1) self.assertFalse(t1 == t2) self.assertFalse(t2 == t1) self.assertFalse(t1 > t2) self.assertFalse(t2 < t1) self.assertFalse(t1 >= t2) self.assertFalse(t2 <= t1) for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) self.assertEqual(badarg == t1, False) self.assertEqual(badarg != t1, True) self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) self.assertRaises(TypeError, lambda: badarg > t1) self.assertRaises(TypeError, lambda: badarg >= t1) def test_str(self): td = timedelta eq = self.assertEqual eq(str(td(1)), "1 day, 0:00:00") eq(str(td(-1)), "-1 day, 0:00:00") eq(str(td(2)), "2 days, 0:00:00") eq(str(td(-2)), "-2 days, 0:00:00") eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), "-210 days, 23:12:34") eq(str(td(milliseconds=1)), "0:00:00.001000") eq(str(td(microseconds=3)), "0:00:00.000003") eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)), "999999999 days, 23:59:59.999999") def test_repr(self): name = 'datetime.' + self.theclass.__name__ self.assertEqual(repr(self.theclass(1)), "%s(days=1)" % name) self.assertEqual(repr(self.theclass(10, 2)), "%s(days=10, seconds=2)" % name) self.assertEqual(repr(self.theclass(-10, 2, 400000)), "%s(days=-10, seconds=2, microseconds=400000)" % name) self.assertEqual(repr(self.theclass(seconds=60)), "%s(seconds=60)" % name) self.assertEqual(repr(self.theclass()), "%s(0)" % name) self.assertEqual(repr(self.theclass(microseconds=100)), "%s(microseconds=100)" % name) self.assertEqual(repr(self.theclass(days=1, microseconds=100)), "%s(days=1, microseconds=100)" % name) self.assertEqual(repr(self.theclass(seconds=1, microseconds=100)), "%s(seconds=1, microseconds=100)" % name) def test_roundtrip(self): for td in (timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999), timedelta(days=-999999999), timedelta(days=-999999999, seconds=1), timedelta(days=1, seconds=2, microseconds=3)): # Verify td -> string -> td identity. s = repr(td) self.assertTrue(s.startswith('datetime.')) s = s[9:] td2 = eval(s) self.assertEqual(td, td2) # Verify identity via reconstructing from pieces. td2 = timedelta(td.days, td.seconds, td.microseconds) self.assertEqual(td, td2) def test_resolution_info(self): self.assertIsInstance(timedelta.min, timedelta) self.assertIsInstance(timedelta.max, timedelta) self.assertIsInstance(timedelta.resolution, timedelta) self.assertTrue(timedelta.max > timedelta.min) self.assertEqual(timedelta.min, timedelta(-999999999)) self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) def test_overflow(self): tiny = timedelta.resolution td = timedelta.min + tiny td -= tiny # no problem self.assertRaises(OverflowError, td.__sub__, tiny) self.assertRaises(OverflowError, td.__add__, -tiny) td = timedelta.max - tiny td += tiny # no problem self.assertRaises(OverflowError, td.__add__, tiny) self.assertRaises(OverflowError, td.__sub__, -tiny) self.assertRaises(OverflowError, lambda: -timedelta.max) day = timedelta(1) self.assertRaises(OverflowError, day.__mul__, 10**9) self.assertRaises(OverflowError, day.__mul__, 1e9) self.assertRaises(OverflowError, day.__truediv__, 1e-20) self.assertRaises(OverflowError, day.__truediv__, 1e-10) self.assertRaises(OverflowError, day.__truediv__, 9e-10) @support.requires_IEEE_754 def _test_overflow_special(self): day = timedelta(1) self.assertRaises(OverflowError, day.__mul__, INF) self.assertRaises(OverflowError, day.__mul__, -INF) def test_microsecond_rounding(self): td = timedelta eq = self.assertEqual # Single-field rounding. eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 eq(td(milliseconds=0.5/1000), td(microseconds=0)) eq(td(milliseconds=-0.5/1000), td(microseconds=-0)) eq(td(milliseconds=0.6/1000), td(microseconds=1)) eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) eq(td(milliseconds=1.5/1000), td(microseconds=2)) eq(td(milliseconds=-1.5/1000), td(microseconds=-2)) eq(td(seconds=0.5/10**6), td(microseconds=0)) eq(td(seconds=-0.5/10**6), td(microseconds=-0)) eq(td(seconds=1/2**7), td(microseconds=7812)) eq(td(seconds=-1/2**7), td(microseconds=-7812)) # Rounding due to contributions from more than one field. us_per_hour = 3600e6 us_per_day = us_per_hour * 24 eq(td(days=.4/us_per_day), td(0)) eq(td(hours=.2/us_per_hour), td(0)) eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) eq(td(days=-.4/us_per_day), td(0)) eq(td(hours=-.2/us_per_hour), td(0)) eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) # Test for a patch in Issue 8860 eq(td(microseconds=0.5), 0.5*td(microseconds=1.0)) eq(td(microseconds=0.5)//td.resolution, 0.5*td.resolution//td.resolution) def test_massive_normalization(self): td = timedelta(microseconds=-1) self.assertEqual((td.days, td.seconds, td.microseconds), (-1, 24*3600-1, 999999)) def test_bool(self): self.assertTrue(timedelta(1)) self.assertTrue(timedelta(0, 1)) self.assertTrue(timedelta(0, 0, 1)) self.assertTrue(timedelta(microseconds=1)) self.assertFalse(timedelta(0)) def test_subclass_timedelta(self): class T(timedelta): @staticmethod def from_td(td): return T(td.days, td.seconds, td.microseconds) def as_hours(self): sum = (self.days * 24 + self.seconds / 3600.0 + self.microseconds / 3600e6) return round(sum) t1 = T(days=1) self.assertIs(type(t1), T) self.assertEqual(t1.as_hours(), 24) t2 = T(days=-1, seconds=-3600) self.assertIs(type(t2), T) self.assertEqual(t2.as_hours(), -25) t3 = t1 + t2 self.assertIs(type(t3), timedelta) t4 = T.from_td(t3) self.assertIs(type(t4), T) self.assertEqual(t3.days, t4.days) self.assertEqual(t3.seconds, t4.seconds) self.assertEqual(t3.microseconds, t4.microseconds) self.assertEqual(str(t3), str(t4)) self.assertEqual(t4.as_hours(), -1) def test_division(self):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mod_generics_cache.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mod_generics_cache.py
"""Module for testing the behavior of generics across different modules.""" import sys from textwrap import dedent from typing import TypeVar, Generic, Optional if sys.version_info[:2] >= (3, 6): exec(dedent(""" default_a: Optional['A'] = None default_b: Optional['B'] = None T = TypeVar('T') class A(Generic[T]): some_b: 'B' class B(Generic[T]): class A(Generic[T]): pass my_inner_a1: 'B.A' my_inner_a2: A my_outer_a: 'A' # unless somebody calls get_type_hints with localns=B.__dict__ """)) else: # This should stay in sync with the syntax above. __annotations__ = dict( default_a=Optional['A'], default_b=Optional['B'], ) default_a = None default_b = None T = TypeVar('T') class A(Generic[T]): __annotations__ = dict( some_b='B' ) class B(Generic[T]): class A(Generic[T]): pass __annotations__ = dict( my_inner_a1='B.A', my_inner_a2=A, my_outer_a='A' # unless somebody calls get_type_hints with localns=B.__dict__ )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shlex.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shlex.py
import io import shlex import string import unittest # The original test data set was from shellwords, by Hartmut Goebel. data = r"""x|x| foo bar|foo|bar| foo bar|foo|bar| foo bar |foo|bar| foo bar bla fasel|foo|bar|bla|fasel| x y z xxxx|x|y|z|xxxx| \x bar|\|x|bar| \ x bar|\|x|bar| \ bar|\|bar| foo \x bar|foo|\|x|bar| foo \ x bar|foo|\|x|bar| foo \ bar|foo|\|bar| foo "bar" bla|foo|"bar"|bla| "foo" "bar" "bla"|"foo"|"bar"|"bla"| "foo" bar "bla"|"foo"|bar|"bla"| "foo" bar bla|"foo"|bar|bla| foo 'bar' bla|foo|'bar'|bla| 'foo' 'bar' 'bla'|'foo'|'bar'|'bla'| 'foo' bar 'bla'|'foo'|bar|'bla'| 'foo' bar bla|'foo'|bar|bla| blurb foo"bar"bar"fasel" baz|blurb|foo"bar"bar"fasel"|baz| blurb foo'bar'bar'fasel' baz|blurb|foo'bar'bar'fasel'|baz| ""|""| ''|''| foo "" bar|foo|""|bar| foo '' bar|foo|''|bar| foo "" "" "" bar|foo|""|""|""|bar| foo '' '' '' bar|foo|''|''|''|bar| \""|\|""| "\"|"\"| "foo\ bar"|"foo\ bar"| "foo\\ bar"|"foo\\ bar"| "foo\\ bar\"|"foo\\ bar\"| "foo\\" bar\""|"foo\\"|bar|\|""| "foo\\ bar\" dfadf"|"foo\\ bar\"|dfadf"| "foo\\\ bar\" dfadf"|"foo\\\ bar\"|dfadf"| "foo\\\x bar\" dfadf"|"foo\\\x bar\"|dfadf"| "foo\x bar\" dfadf"|"foo\x bar\"|dfadf"| \''|\|''| 'foo\ bar'|'foo\ bar'| 'foo\\ bar'|'foo\\ bar'| "foo\\\x bar\" df'a\ 'df'|"foo\\\x bar\"|df'a|\|'df'| \"foo"|\|"foo"| \"foo"\x|\|"foo"|\|x| "foo\x"|"foo\x"| "foo\ "|"foo\ "| foo\ xx|foo|\|xx| foo\ x\x|foo|\|x|\|x| foo\ x\x\""|foo|\|x|\|x|\|""| "foo\ x\x"|"foo\ x\x"| "foo\ x\x\\"|"foo\ x\x\\"| "foo\ x\x\\""foobar"|"foo\ x\x\\"|"foobar"| "foo\ x\x\\"\''"foobar"|"foo\ x\x\\"|\|''|"foobar"| "foo\ x\x\\"\'"fo'obar"|"foo\ x\x\\"|\|'"fo'|obar"| "foo\ x\x\\"\'"fo'obar" 'don'\''t'|"foo\ x\x\\"|\|'"fo'|obar"|'don'|\|''|t'| 'foo\ bar'|'foo\ bar'| 'foo\\ bar'|'foo\\ bar'| foo\ bar|foo|\|bar| foo#bar\nbaz|foobaz| :-) ;-)|:|-|)|;|-|)| áéíóú|á|é|í|ó|ú| """ posix_data = r"""x|x| foo bar|foo|bar| foo bar|foo|bar| foo bar |foo|bar| foo bar bla fasel|foo|bar|bla|fasel| x y z xxxx|x|y|z|xxxx| \x bar|x|bar| \ x bar| x|bar| \ bar| bar| foo \x bar|foo|x|bar| foo \ x bar|foo| x|bar| foo \ bar|foo| bar| foo "bar" bla|foo|bar|bla| "foo" "bar" "bla"|foo|bar|bla| "foo" bar "bla"|foo|bar|bla| "foo" bar bla|foo|bar|bla| foo 'bar' bla|foo|bar|bla| 'foo' 'bar' 'bla'|foo|bar|bla| 'foo' bar 'bla'|foo|bar|bla| 'foo' bar bla|foo|bar|bla| blurb foo"bar"bar"fasel" baz|blurb|foobarbarfasel|baz| blurb foo'bar'bar'fasel' baz|blurb|foobarbarfasel|baz| ""|| ''|| foo "" bar|foo||bar| foo '' bar|foo||bar| foo "" "" "" bar|foo||||bar| foo '' '' '' bar|foo||||bar| \"|"| "\""|"| "foo\ bar"|foo\ bar| "foo\\ bar"|foo\ bar| "foo\\ bar\""|foo\ bar"| "foo\\" bar\"|foo\|bar"| "foo\\ bar\" dfadf"|foo\ bar" dfadf| "foo\\\ bar\" dfadf"|foo\\ bar" dfadf| "foo\\\x bar\" dfadf"|foo\\x bar" dfadf| "foo\x bar\" dfadf"|foo\x bar" dfadf| \'|'| 'foo\ bar'|foo\ bar| 'foo\\ bar'|foo\\ bar| "foo\\\x bar\" df'a\ 'df"|foo\\x bar" df'a\ 'df| \"foo|"foo| \"foo\x|"foox| "foo\x"|foo\x| "foo\ "|foo\ | foo\ xx|foo xx| foo\ x\x|foo xx| foo\ x\x\"|foo xx"| "foo\ x\x"|foo\ x\x| "foo\ x\x\\"|foo\ x\x\| "foo\ x\x\\""foobar"|foo\ x\x\foobar| "foo\ x\x\\"\'"foobar"|foo\ x\x\'foobar| "foo\ x\x\\"\'"fo'obar"|foo\ x\x\'fo'obar| "foo\ x\x\\"\'"fo'obar" 'don'\''t'|foo\ x\x\'fo'obar|don't| "foo\ x\x\\"\'"fo'obar" 'don'\''t' \\|foo\ x\x\'fo'obar|don't|\| 'foo\ bar'|foo\ bar| 'foo\\ bar'|foo\\ bar| foo\ bar|foo bar| foo#bar\nbaz|foo|baz| :-) ;-)|:-)|;-)| áéíóú|áéíóú| """ class ShlexTest(unittest.TestCase): def setUp(self): self.data = [x.split("|")[:-1] for x in data.splitlines()] self.posix_data = [x.split("|")[:-1] for x in posix_data.splitlines()] for item in self.data: item[0] = item[0].replace(r"\n", "\n") for item in self.posix_data: item[0] = item[0].replace(r"\n", "\n") def splitTest(self, data, comments): for i in range(len(data)): l = shlex.split(data[i][0], comments=comments) self.assertEqual(l, data[i][1:], "%s: %s != %s" % (data[i][0], l, data[i][1:])) def oldSplit(self, s): ret = [] lex = shlex.shlex(io.StringIO(s)) tok = lex.get_token() while tok: ret.append(tok) tok = lex.get_token() return ret def testSplitPosix(self): """Test data splitting with posix parser""" self.splitTest(self.posix_data, comments=True) def testCompat(self): """Test compatibility interface""" for i in range(len(self.data)): l = self.oldSplit(self.data[i][0]) self.assertEqual(l, self.data[i][1:], "%s: %s != %s" % (self.data[i][0], l, self.data[i][1:])) def testSyntaxSplitAmpersandAndPipe(self): """Test handling of syntax splitting of &, |""" # Could take these forms: &&, &, |&, ;&, ;;& # of course, the same applies to | and || # these should all parse to the same output for delimiter in ('&&', '&', '|&', ';&', ';;&', '||', '|', '&|', ';|', ';;|'): src = ['echo hi %s echo bye' % delimiter, 'echo hi%secho bye' % delimiter] ref = ['echo', 'hi', delimiter, 'echo', 'bye'] for ss in src: s = shlex.shlex(ss, punctuation_chars=True) result = list(s) self.assertEqual(ref, result, "While splitting '%s'" % ss) def testSyntaxSplitSemicolon(self): """Test handling of syntax splitting of ;""" # Could take these forms: ;, ;;, ;&, ;;& # these should all parse to the same output for delimiter in (';', ';;', ';&', ';;&'): src = ['echo hi %s echo bye' % delimiter, 'echo hi%s echo bye' % delimiter, 'echo hi%secho bye' % delimiter] ref = ['echo', 'hi', delimiter, 'echo', 'bye'] for ss in src: s = shlex.shlex(ss, punctuation_chars=True) result = list(s) self.assertEqual(ref, result, "While splitting '%s'" % ss) def testSyntaxSplitRedirect(self): """Test handling of syntax splitting of >""" # of course, the same applies to <, | # these should all parse to the same output for delimiter in ('<', '|'): src = ['echo hi %s out' % delimiter, 'echo hi%s out' % delimiter, 'echo hi%sout' % delimiter] ref = ['echo', 'hi', delimiter, 'out'] for ss in src: s = shlex.shlex(ss, punctuation_chars=True) result = list(s) self.assertEqual(ref, result, "While splitting '%s'" % ss) def testSyntaxSplitParen(self): """Test handling of syntax splitting of ()""" # these should all parse to the same output src = ['( echo hi )', '(echo hi)'] ref = ['(', 'echo', 'hi', ')'] for ss in src: s = shlex.shlex(ss, punctuation_chars=True) result = list(s) self.assertEqual(ref, result, "While splitting '%s'" % ss) def testSyntaxSplitCustom(self): """Test handling of syntax splitting with custom chars""" ref = ['~/a', '&', '&', 'b-c', '--color=auto', '||', 'd', '*.py?'] ss = "~/a && b-c --color=auto || d *.py?" s = shlex.shlex(ss, punctuation_chars="|") result = list(s) self.assertEqual(ref, result, "While splitting '%s'" % ss) def testTokenTypes(self): """Test that tokens are split with types as expected.""" for source, expected in ( ('a && b || c', [('a', 'a'), ('&&', 'c'), ('b', 'a'), ('||', 'c'), ('c', 'a')]), ): s = shlex.shlex(source, punctuation_chars=True) observed = [] while True: t = s.get_token() if t == s.eof: break if t[0] in s.punctuation_chars: tt = 'c' else: tt = 'a' observed.append((t, tt)) self.assertEqual(observed, expected) def testPunctuationInWordChars(self): """Test that any punctuation chars are removed from wordchars""" s = shlex.shlex('a_b__c', punctuation_chars='_') self.assertNotIn('_', s.wordchars) self.assertEqual(list(s), ['a', '_', 'b', '__', 'c']) def testPunctuationWithWhitespaceSplit(self): """Test that with whitespace_split, behaviour is as expected""" s = shlex.shlex('a && b || c', punctuation_chars='&') # whitespace_split is False, so splitting will be based on # punctuation_chars self.assertEqual(list(s), ['a', '&&', 'b', '|', '|', 'c']) s = shlex.shlex('a && b || c', punctuation_chars='&') s.whitespace_split = True # whitespace_split is True, so splitting will be based on # white space self.assertEqual(list(s), ['a', '&&', 'b', '||', 'c']) def testPunctuationWithPosix(self): """Test that punctuation_chars and posix behave correctly together.""" # see Issue #29132 s = shlex.shlex('f >"abc"', posix=True, punctuation_chars=True) self.assertEqual(list(s), ['f', '>', 'abc']) s = shlex.shlex('f >\\"abc\\"', posix=True, punctuation_chars=True) self.assertEqual(list(s), ['f', '>', '"abc"']) def testEmptyStringHandling(self): """Test that parsing of empty strings is correctly handled.""" # see Issue #21999 expected = ['', ')', 'abc'] for punct in (False, True): s = shlex.shlex("'')abc", posix=True, punctuation_chars=punct) slist = list(s) self.assertEqual(slist, expected) expected = ["''", ')', 'abc'] s = shlex.shlex("'')abc", punctuation_chars=True) self.assertEqual(list(s), expected) def testQuote(self): safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' unicode_sample = '\xe9\xe0\xdf' # e + acute accent, a + grave, sharp s unsafe = '"`$\\!' + unicode_sample self.assertEqual(shlex.quote(''), "''") self.assertEqual(shlex.quote(safeunquoted), safeunquoted) self.assertEqual(shlex.quote('test file name'), "'test file name'") for u in unsafe: self.assertEqual(shlex.quote('test%sname' % u), "'test%sname'" % u) for u in unsafe: self.assertEqual(shlex.quote("test%s'name'" % u), "'test%s'\"'\"'name'\"'\"''" % u) def testPunctuationCharsReadOnly(self): punctuation_chars = "/|$%^" shlex_instance = shlex.shlex(punctuation_chars=punctuation_chars) self.assertEqual(shlex_instance.punctuation_chars, punctuation_chars) with self.assertRaises(AttributeError): shlex_instance.punctuation_chars = False # Allow this test to be used with old shlex.py if not getattr(shlex, "split", None): for methname in dir(ShlexTest): if methname.startswith("test") and methname != "testCompat": delattr(ShlexTest, methname) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_copy.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_copy.py
"""Unit tests for the copy module.""" import copy import copyreg import weakref import abc from operator import le, lt, ge, gt, eq, ne import unittest order_comparisons = le, lt, ge, gt equality_comparisons = eq, ne comparisons = order_comparisons + equality_comparisons class TestCopy(unittest.TestCase): # Attempt full line coverage of copy.py from top to bottom def test_exceptions(self): self.assertIs(copy.Error, copy.error) self.assertTrue(issubclass(copy.Error, Exception)) # The copy() method def test_copy_basic(self): x = 42 y = copy.copy(x) self.assertEqual(x, y) def test_copy_copy(self): class C(object): def __init__(self, foo): self.foo = foo def __copy__(self): return C(self.foo) x = C(42) y = copy.copy(x) self.assertEqual(y.__class__, x.__class__) self.assertEqual(y.foo, x.foo) def test_copy_registry(self): class C(object): def __new__(cls, foo): obj = object.__new__(cls) obj.foo = foo return obj def pickle_C(obj): return (C, (obj.foo,)) x = C(42) self.assertRaises(TypeError, copy.copy, x) copyreg.pickle(C, pickle_C, C) y = copy.copy(x) def test_copy_reduce_ex(self): class C(object): def __reduce_ex__(self, proto): c.append(1) return "" def __reduce__(self): self.fail("shouldn't call this") c = [] x = C() y = copy.copy(x) self.assertIs(y, x) self.assertEqual(c, [1]) def test_copy_reduce(self): class C(object): def __reduce__(self): c.append(1) return "" c = [] x = C() y = copy.copy(x) self.assertIs(y, x) self.assertEqual(c, [1]) def test_copy_cant(self): class C(object): def __getattribute__(self, name): if name.startswith("__reduce"): raise AttributeError(name) return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.copy, x) # Type-specific _copy_xxx() methods def test_copy_atomic(self): class Classic: pass class NewStyle(object): pass def f(): pass class WithMetaclass(metaclass=abc.ABCMeta): pass tests = [None, ..., NotImplemented, 42, 2**100, 3.14, True, False, 1j, "hello", "hello\u1234", f.__code__, b"world", bytes(range(256)), range(10), slice(1, 10, 2), NewStyle, Classic, max, WithMetaclass, property()] for x in tests: self.assertIs(copy.copy(x), x) def test_copy_list(self): x = [1, 2, 3] y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) x = [] y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) def test_copy_tuple(self): x = (1, 2, 3) self.assertIs(copy.copy(x), x) x = () self.assertIs(copy.copy(x), x) x = (1, 2, 3, []) self.assertIs(copy.copy(x), x) def test_copy_dict(self): x = {"foo": 1, "bar": 2} y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) x = {} y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) def test_copy_set(self): x = {1, 2, 3} y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) x = set() y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) def test_copy_frozenset(self): x = frozenset({1, 2, 3}) self.assertIs(copy.copy(x), x) x = frozenset() self.assertIs(copy.copy(x), x) def test_copy_bytearray(self): x = bytearray(b'abc') y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) x = bytearray() y = copy.copy(x) self.assertEqual(y, x) self.assertIsNot(y, x) def test_copy_inst_vanilla(self): class C: def __init__(self, foo): self.foo = foo def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_copy(self): class C: def __init__(self, foo): self.foo = foo def __copy__(self): return C(self.foo) def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getinitargs(self): class C: def __init__(self, foo): self.foo = foo def __getinitargs__(self): return (self.foo,) def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getnewargs(self): class C(int): def __new__(cls, foo): self = int.__new__(cls) self.foo = foo return self def __getnewargs__(self): return self.foo, def __eq__(self, other): return self.foo == other.foo x = C(42) y = copy.copy(x) self.assertIsInstance(y, C) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertEqual(y.foo, x.foo) def test_copy_inst_getnewargs_ex(self): class C(int): def __new__(cls, *, foo): self = int.__new__(cls) self.foo = foo return self def __getnewargs_ex__(self): return (), {'foo': self.foo} def __eq__(self, other): return self.foo == other.foo x = C(foo=42) y = copy.copy(x) self.assertIsInstance(y, C) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertEqual(y.foo, x.foo) def test_copy_inst_getstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return {"foo": self.foo} def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_setstate(self): class C: def __init__(self, foo): self.foo = foo def __setstate__(self, state): self.foo = state["foo"] def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getstate_setstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return self.foo def __setstate__(self, state): self.foo = state def __eq__(self, other): return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) # State with boolean value is false (issue #25718) x = C(0.0) self.assertEqual(copy.copy(x), x) # The deepcopy() method def test_deepcopy_basic(self): x = 42 y = copy.deepcopy(x) self.assertEqual(y, x) def test_deepcopy_memo(self): # Tests of reflexive objects are under type-specific sections below. # This tests only repetitions of objects. x = [] x = [x, x] y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y[0], x[0]) self.assertIs(y[0], y[1]) def test_deepcopy_issubclass(self): # XXX Note: there's no way to test the TypeError coming out of # issubclass() -- this can only happen when an extension # module defines a "type" that doesn't formally inherit from # type. class Meta(type): pass class C(metaclass=Meta): pass self.assertEqual(copy.deepcopy(C), C) def test_deepcopy_deepcopy(self): class C(object): def __init__(self, foo): self.foo = foo def __deepcopy__(self, memo=None): return C(self.foo) x = C(42) y = copy.deepcopy(x) self.assertEqual(y.__class__, x.__class__) self.assertEqual(y.foo, x.foo) def test_deepcopy_registry(self): class C(object): def __new__(cls, foo): obj = object.__new__(cls) obj.foo = foo return obj def pickle_C(obj): return (C, (obj.foo,)) x = C(42) self.assertRaises(TypeError, copy.deepcopy, x) copyreg.pickle(C, pickle_C, C) y = copy.deepcopy(x) def test_deepcopy_reduce_ex(self): class C(object): def __reduce_ex__(self, proto): c.append(1) return "" def __reduce__(self): self.fail("shouldn't call this") c = [] x = C() y = copy.deepcopy(x) self.assertIs(y, x) self.assertEqual(c, [1]) def test_deepcopy_reduce(self): class C(object): def __reduce__(self): c.append(1) return "" c = [] x = C() y = copy.deepcopy(x) self.assertIs(y, x) self.assertEqual(c, [1]) def test_deepcopy_cant(self): class C(object): def __getattribute__(self, name): if name.startswith("__reduce"): raise AttributeError(name) return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.deepcopy, x) # Type-specific _deepcopy_xxx() methods def test_deepcopy_atomic(self): class Classic: pass class NewStyle(object): pass def f(): pass tests = [None, 42, 2**100, 3.14, True, False, 1j, "hello", "hello\u1234", f.__code__, NewStyle, Classic, max, property()] for x in tests: self.assertIs(copy.deepcopy(x), x) def test_deepcopy_list(self): x = [[1, 2], 3] y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(x, y) self.assertIsNot(x[0], y[0]) def test_deepcopy_reflexive_list(self): x = [] x.append(x) y = copy.deepcopy(x) for op in comparisons: self.assertRaises(RecursionError, op, y, x) self.assertIsNot(y, x) self.assertIs(y[0], y) self.assertEqual(len(y), 1) def test_deepcopy_empty_tuple(self): x = () y = copy.deepcopy(x) self.assertIs(x, y) def test_deepcopy_tuple(self): x = ([1, 2], 3) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(x, y) self.assertIsNot(x[0], y[0]) def test_deepcopy_tuple_of_immutables(self): x = ((1, 2), 3) y = copy.deepcopy(x) self.assertIs(x, y) def test_deepcopy_reflexive_tuple(self): x = ([],) x[0].append(x) y = copy.deepcopy(x) for op in comparisons: self.assertRaises(RecursionError, op, y, x) self.assertIsNot(y, x) self.assertIsNot(y[0], x[0]) self.assertIs(y[0][0], y) def test_deepcopy_dict(self): x = {"foo": [1, 2], "bar": 3} y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(x, y) self.assertIsNot(x["foo"], y["foo"]) def test_deepcopy_reflexive_dict(self): x = {} x['foo'] = x y = copy.deepcopy(x) for op in order_comparisons: self.assertRaises(TypeError, op, y, x) for op in equality_comparisons: self.assertRaises(RecursionError, op, y, x) self.assertIsNot(y, x) self.assertIs(y['foo'], y) self.assertEqual(len(y), 1) def test_deepcopy_keepalive(self): memo = {} x = [] y = copy.deepcopy(x, memo) self.assertIs(memo[id(memo)][0], x) def test_deepcopy_dont_memo_immutable(self): memo = {} x = [1, 2, 3, 4] y = copy.deepcopy(x, memo) self.assertEqual(y, x) # There's the entry for the new list, and the keep alive. self.assertEqual(len(memo), 2) memo = {} x = [(1, 2)] y = copy.deepcopy(x, memo) self.assertEqual(y, x) # Tuples with immutable contents are immutable for deepcopy. self.assertEqual(len(memo), 2) def test_deepcopy_inst_vanilla(self): class C: def __init__(self, foo): self.foo = foo def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_deepcopy(self): class C: def __init__(self, foo): self.foo = foo def __deepcopy__(self, memo): return C(copy.deepcopy(self.foo, memo)) def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_getinitargs(self): class C: def __init__(self, foo): self.foo = foo def __getinitargs__(self): return (self.foo,) def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_getnewargs(self): class C(int): def __new__(cls, foo): self = int.__new__(cls) self.foo = foo return self def __getnewargs__(self): return self.foo, def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertIsInstance(y, C) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertEqual(y.foo, x.foo) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_getnewargs_ex(self): class C(int): def __new__(cls, *, foo): self = int.__new__(cls) self.foo = foo return self def __getnewargs_ex__(self): return (), {'foo': self.foo} def __eq__(self, other): return self.foo == other.foo x = C(foo=[42]) y = copy.deepcopy(x) self.assertIsInstance(y, C) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertEqual(y.foo, x.foo) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_getstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return {"foo": self.foo} def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_setstate(self): class C: def __init__(self, foo): self.foo = foo def __setstate__(self, state): self.foo = state["foo"] def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_inst_getstate_setstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return self.foo def __setstate__(self, state): self.foo = state def __eq__(self, other): return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) # State with boolean value is false (issue #25718) x = C([]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y, x) self.assertIsNot(y.foo, x.foo) def test_deepcopy_reflexive_inst(self): class C: pass x = C() x.foo = x y = copy.deepcopy(x) self.assertIsNot(y, x) self.assertIs(y.foo, y) def test_deepcopy_range(self): class I(int): pass x = range(I(10)) y = copy.deepcopy(x) self.assertIsNot(y, x) self.assertEqual(y, x) self.assertIsNot(y.stop, x.stop) self.assertEqual(y.stop, x.stop) self.assertIsInstance(y.stop, I) # _reconstruct() def test_reconstruct_string(self): class C(object): def __reduce__(self): return "" x = C() y = copy.copy(x) self.assertIs(y, x) y = copy.deepcopy(x) self.assertIs(y, x) def test_reconstruct_nostate(self): class C(object): def __reduce__(self): return (C, ()) x = C() x.foo = 42 y = copy.copy(x) self.assertIs(y.__class__, x.__class__) y = copy.deepcopy(x) self.assertIs(y.__class__, x.__class__) def test_reconstruct_state(self): class C(object): def __reduce__(self): return (C, (), self.__dict__) def __eq__(self, other): return self.__dict__ == other.__dict__ x = C() x.foo = [42] y = copy.copy(x) self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y.foo, x.foo) def test_reconstruct_state_setstate(self): class C(object): def __reduce__(self): return (C, (), self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def __eq__(self, other): return self.__dict__ == other.__dict__ x = C() x.foo = [42] y = copy.copy(x) self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) self.assertIsNot(y.foo, x.foo) def test_reconstruct_reflexive(self): class C(object): pass x = C() x.foo = x y = copy.deepcopy(x) self.assertIsNot(y, x) self.assertIs(y.foo, y) # Additions for Python 2.3 and pickle protocol 2 def test_reduce_4tuple(self): class C(list): def __reduce__(self): return (C, (), self.__dict__, iter(self)) def __eq__(self, other): return (list(self) == list(other) and self.__dict__ == other.__dict__) x = C([[1, 2], 3]) y = copy.copy(x) self.assertEqual(x, y) self.assertIsNot(x, y) self.assertIs(x[0], y[0]) y = copy.deepcopy(x) self.assertEqual(x, y) self.assertIsNot(x, y) self.assertIsNot(x[0], y[0]) def test_reduce_5tuple(self): class C(dict): def __reduce__(self): return (C, (), self.__dict__, None, self.items()) def __eq__(self, other): return (dict(self) == dict(other) and self.__dict__ == other.__dict__) x = C([("foo", [1, 2]), ("bar", 3)]) y = copy.copy(x) self.assertEqual(x, y) self.assertIsNot(x, y) self.assertIs(x["foo"], y["foo"]) y = copy.deepcopy(x) self.assertEqual(x, y) self.assertIsNot(x, y) self.assertIsNot(x["foo"], y["foo"]) def test_copy_slots(self): class C(object): __slots__ = ["foo"] x = C() x.foo = [42] y = copy.copy(x) self.assertIs(x.foo, y.foo) def test_deepcopy_slots(self): class C(object): __slots__ = ["foo"] x = C() x.foo = [42] y = copy.deepcopy(x) self.assertEqual(x.foo, y.foo) self.assertIsNot(x.foo, y.foo) def test_deepcopy_dict_subclass(self): class C(dict): def __init__(self, d=None): if not d: d = {} self._keys = list(d.keys()) super().__init__(d) def __setitem__(self, key, item): super().__setitem__(key, item) if key not in self._keys: self._keys.append(key) x = C(d={'foo':0}) y = copy.deepcopy(x) self.assertEqual(x, y) self.assertEqual(x._keys, y._keys) self.assertIsNot(x, y) x['bar'] = 1 self.assertNotEqual(x, y) self.assertNotEqual(x._keys, y._keys) def test_copy_list_subclass(self): class C(list): pass x = C([[1, 2], 3]) x.foo = [4, 5] y = copy.copy(x) self.assertEqual(list(x), list(y)) self.assertEqual(x.foo, y.foo) self.assertIs(x[0], y[0]) self.assertIs(x.foo, y.foo) def test_deepcopy_list_subclass(self): class C(list): pass x = C([[1, 2], 3]) x.foo = [4, 5] y = copy.deepcopy(x) self.assertEqual(list(x), list(y)) self.assertEqual(x.foo, y.foo) self.assertIsNot(x[0], y[0]) self.assertIsNot(x.foo, y.foo) def test_copy_tuple_subclass(self): class C(tuple): pass x = C([1, 2, 3]) self.assertEqual(tuple(x), (1, 2, 3)) y = copy.copy(x) self.assertEqual(tuple(y), (1, 2, 3)) def test_deepcopy_tuple_subclass(self): class C(tuple): pass x = C([[1, 2], 3]) self.assertEqual(tuple(x), ([1, 2], 3)) y = copy.deepcopy(x) self.assertEqual(tuple(y), ([1, 2], 3)) self.assertIsNot(x, y) self.assertIsNot(x[0], y[0]) def test_getstate_exc(self): class EvilState(object): def __getstate__(self): raise ValueError("ain't got no stickin' state") self.assertRaises(ValueError, copy.copy, EvilState()) def test_copy_function(self): self.assertEqual(copy.copy(global_foo), global_foo) def foo(x, y): return x+y self.assertEqual(copy.copy(foo), foo) bar = lambda: None self.assertEqual(copy.copy(bar), bar) def test_deepcopy_function(self): self.assertEqual(copy.deepcopy(global_foo), global_foo) def foo(x, y): return x+y self.assertEqual(copy.deepcopy(foo), foo) bar = lambda: None self.assertEqual(copy.deepcopy(bar), bar) def _check_weakref(self, _copy): class C(object): pass obj = C() x = weakref.ref(obj) y = _copy(x) self.assertIs(y, x) del obj y = _copy(x) self.assertIs(y, x) def test_copy_weakref(self): self._check_weakref(copy.copy) def test_deepcopy_weakref(self): self._check_weakref(copy.deepcopy) def _check_copy_weakdict(self, _dicttype): class C(object): pass a, b, c, d = [C() for i in range(4)] u = _dicttype() u[a] = b u[c] = d v = copy.copy(u) self.assertIsNot(v, u) self.assertEqual(v, u) self.assertEqual(v[a], b) self.assertEqual(v[c], d) self.assertEqual(len(v), 2) del c, d self.assertEqual(len(v), 1) x, y = C(), C() # The underlying containers are decoupled v[x] = y self.assertNotIn(x, u) def test_copy_weakkeydict(self): self._check_copy_weakdict(weakref.WeakKeyDictionary) def test_copy_weakvaluedict(self): self._check_copy_weakdict(weakref.WeakValueDictionary) def test_deepcopy_weakkeydict(self): class C(object): def __init__(self, i): self.i = i a, b, c, d = [C(i) for i in range(4)] u = weakref.WeakKeyDictionary() u[a] = b u[c] = d # Keys aren't copied, values are v = copy.deepcopy(u) self.assertNotEqual(v, u) self.assertEqual(len(v), 2) self.assertIsNot(v[a], b) self.assertIsNot(v[c], d) self.assertEqual(v[a].i, b.i) self.assertEqual(v[c].i, d.i) del c self.assertEqual(len(v), 1) def test_deepcopy_weakvaluedict(self): class C(object): def __init__(self, i): self.i = i a, b, c, d = [C(i) for i in range(4)] u = weakref.WeakValueDictionary() u[a] = b u[c] = d # Keys are copied, values aren't v = copy.deepcopy(u) self.assertNotEqual(v, u) self.assertEqual(len(v), 2) (x, y), (z, t) = sorted(v.items(), key=lambda pair: pair[0].i) self.assertIsNot(x, a) self.assertEqual(x.i, a.i) self.assertIs(y, b) self.assertIsNot(z, c) self.assertEqual(z.i, c.i) self.assertIs(t, d) del x, y, z, t del d self.assertEqual(len(v), 1) def test_deepcopy_bound_method(self): class Foo(object): def m(self): pass f = Foo() f.b = f.m g = copy.deepcopy(f) self.assertEqual(g.m, g.b) self.assertIs(g.b.__self__, g) g.b() def global_foo(x, y): return x+y if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
"""Test suite for statistics module, including helper NumericTestCase and approx_equal function. """ import collections import collections.abc import decimal import doctest import math import random import sys import unittest from decimal import Decimal from fractions import Fraction # Module to be tested. import statistics # === Helper functions and class === def sign(x): """Return -1.0 for negatives, including -0.0, otherwise +1.0.""" return math.copysign(1, x) def _nan_equal(a, b): """Return True if a and b are both the same kind of NAN. >>> _nan_equal(Decimal('NAN'), Decimal('NAN')) True >>> _nan_equal(Decimal('sNAN'), Decimal('sNAN')) True >>> _nan_equal(Decimal('NAN'), Decimal('sNAN')) False >>> _nan_equal(Decimal(42), Decimal('NAN')) False >>> _nan_equal(float('NAN'), float('NAN')) True >>> _nan_equal(float('NAN'), 0.5) False >>> _nan_equal(float('NAN'), Decimal('NAN')) False NAN payloads are not compared. """ if type(a) is not type(b): return False if isinstance(a, float): return math.isnan(a) and math.isnan(b) aexp = a.as_tuple()[2] bexp = b.as_tuple()[2] return (aexp == bexp) and (aexp in ('n', 'N')) # Both NAN or both sNAN. def _calc_errors(actual, expected): """Return the absolute and relative errors between two numbers. >>> _calc_errors(100, 75) (25, 0.25) >>> _calc_errors(100, 100) (0, 0.0) Returns the (absolute error, relative error) between the two arguments. """ base = max(abs(actual), abs(expected)) abs_err = abs(actual - expected) rel_err = abs_err/base if base else float('inf') return (abs_err, rel_err) def approx_equal(x, y, tol=1e-12, rel=1e-7): """approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is approximately equal to y if the difference between them is less than an absolute error tol or a relative error rel, whichever is bigger. If given, both tol and rel must be finite, non-negative numbers. If not given, default values are tol=1e-12 and rel=1e-7. >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0) True >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0) False Absolute error is defined as abs(x-y); if that is less than or equal to tol, x and y are considered approximately equal. Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is smaller, provided x or y are not zero. If that figure is less than or equal to rel, x and y are considered approximately equal. Complex numbers are not directly supported. If you wish to compare to complex numbers, extract their real and imaginary parts and compare them individually. NANs always compare unequal, even with themselves. Infinities compare approximately equal if they have the same sign (both positive or both negative). Infinities with different signs compare unequal; so do comparisons of infinities with finite numbers. """ if tol < 0 or rel < 0: raise ValueError('error tolerances must be non-negative') # NANs are never equal to anything, approximately or otherwise. if math.isnan(x) or math.isnan(y): return False # Numbers which compare equal also compare approximately equal. if x == y: # This includes the case of two infinities with the same sign. return True if math.isinf(x) or math.isinf(y): # This includes the case of two infinities of opposite sign, or # one infinity and one finite number. return False # Two finite numbers. actual_error = abs(x - y) allowed_error = max(tol, rel*max(abs(x), abs(y))) return actual_error <= allowed_error # This class exists only as somewhere to stick a docstring containing # doctests. The following docstring and tests were originally in a separate # module. Now that it has been merged in here, I need somewhere to hang the. # docstring. Ultimately, this class will die, and the information below will # either become redundant, or be moved into more appropriate places. class _DoNothing: """ When doing numeric work, especially with floats, exact equality is often not what you want. Due to round-off error, it is often a bad idea to try to compare floats with equality. Instead the usual procedure is to test them with some (hopefully small!) allowance for error. The ``approx_equal`` function allows you to specify either an absolute error tolerance, or a relative error, or both. Absolute error tolerances are simple, but you need to know the magnitude of the quantities being compared: >>> approx_equal(12.345, 12.346, tol=1e-3) True >>> approx_equal(12.345e6, 12.346e6, tol=1e-3) # tol is too small. False Relative errors are more suitable when the values you are comparing can vary in magnitude: >>> approx_equal(12.345, 12.346, rel=1e-4) True >>> approx_equal(12.345e6, 12.346e6, rel=1e-4) True but a naive implementation of relative error testing can run into trouble around zero. If you supply both an absolute tolerance and a relative error, the comparison succeeds if either individual test succeeds: >>> approx_equal(12.345e6, 12.346e6, tol=1e-3, rel=1e-4) True """ pass # We prefer this for testing numeric values that may not be exactly equal, # and avoid using TestCase.assertAlmostEqual, because it sucks :-) class NumericTestCase(unittest.TestCase): """Unit test class for numeric work. This subclasses TestCase. In addition to the standard method ``TestCase.assertAlmostEqual``, ``assertApproxEqual`` is provided. """ # By default, we expect exact equality, unless overridden. tol = rel = 0 def assertApproxEqual( self, first, second, tol=None, rel=None, msg=None ): """Test passes if ``first`` and ``second`` are approximately equal. This test passes if ``first`` and ``second`` are equal to within ``tol``, an absolute error, or ``rel``, a relative error. If either ``tol`` or ``rel`` are None or not given, they default to test attributes of the same name (by default, 0). The objects may be either numbers, or sequences of numbers. Sequences are tested element-by-element. >>> class MyTest(NumericTestCase): ... def test_number(self): ... x = 1.0/6 ... y = sum([x]*6) ... self.assertApproxEqual(y, 1.0, tol=1e-15) ... def test_sequence(self): ... a = [1.001, 1.001e-10, 1.001e10] ... b = [1.0, 1e-10, 1e10] ... self.assertApproxEqual(a, b, rel=1e-3) ... >>> import unittest >>> from io import StringIO # Suppress test runner output. >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest) >>> unittest.TextTestRunner(stream=StringIO()).run(suite) <unittest.runner.TextTestResult run=2 errors=0 failures=0> """ if tol is None: tol = self.tol if rel is None: rel = self.rel if ( isinstance(first, collections.abc.Sequence) and isinstance(second, collections.abc.Sequence) ): check = self._check_approx_seq else: check = self._check_approx_num check(first, second, tol, rel, msg) def _check_approx_seq(self, first, second, tol, rel, msg): if len(first) != len(second): standardMsg = ( "sequences differ in length: %d items != %d items" % (len(first), len(second)) ) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) for i, (a,e) in enumerate(zip(first, second)): self._check_approx_num(a, e, tol, rel, msg, i) def _check_approx_num(self, first, second, tol, rel, msg, idx=None): if approx_equal(first, second, tol, rel): # Test passes. Return early, we are done. return None # Otherwise we failed. standardMsg = self._make_std_err_msg(first, second, tol, rel, idx) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) @staticmethod def _make_std_err_msg(first, second, tol, rel, idx): # Create the standard error message for approx_equal failures. assert first != second template = ( ' %r != %r\n' ' values differ by more than tol=%r and rel=%r\n' ' -> absolute error = %r\n' ' -> relative error = %r' ) if idx is not None: header = 'numeric sequences first differ at index %d.\n' % idx template = header + template # Calculate actual errors: abs_err, rel_err = _calc_errors(first, second) return template % (first, second, tol, rel, abs_err, rel_err) # ======================== # === Test the helpers === # ======================== class TestSign(unittest.TestCase): """Test that the helper function sign() works correctly.""" def testZeroes(self): # Test that signed zeroes report their sign correctly. self.assertEqual(sign(0.0), +1) self.assertEqual(sign(-0.0), -1) # --- Tests for approx_equal --- class ApproxEqualSymmetryTest(unittest.TestCase): # Test symmetry of approx_equal. def test_relative_symmetry(self): # Check that approx_equal treats relative error symmetrically. # (a-b)/a is usually not equal to (a-b)/b. Ensure that this # doesn't matter. # # Note: the reason for this test is that an early version # of approx_equal was not symmetric. A relative error test # would pass, or fail, depending on which value was passed # as the first argument. # args1 = [2456, 37.8, -12.45, Decimal('2.54'), Fraction(17, 54)] args2 = [2459, 37.2, -12.41, Decimal('2.59'), Fraction(15, 54)] assert len(args1) == len(args2) for a, b in zip(args1, args2): self.do_relative_symmetry(a, b) def do_relative_symmetry(self, a, b): a, b = min(a, b), max(a, b) assert a < b delta = b - a # The absolute difference between the values. rel_err1, rel_err2 = abs(delta/a), abs(delta/b) # Choose an error margin halfway between the two. rel = (rel_err1 + rel_err2)/2 # Now see that values a and b compare approx equal regardless of # which is given first. self.assertTrue(approx_equal(a, b, tol=0, rel=rel)) self.assertTrue(approx_equal(b, a, tol=0, rel=rel)) def test_symmetry(self): # Test that approx_equal(a, b) == approx_equal(b, a) args = [-23, -2, 5, 107, 93568] delta = 2 for a in args: for type_ in (int, float, Decimal, Fraction): x = type_(a)*100 y = x + delta r = abs(delta/max(x, y)) # There are five cases to check: # 1) actual error <= tol, <= rel self.do_symmetry_test(x, y, tol=delta, rel=r) self.do_symmetry_test(x, y, tol=delta+1, rel=2*r) # 2) actual error > tol, > rel self.do_symmetry_test(x, y, tol=delta-1, rel=r/2) # 3) actual error <= tol, > rel self.do_symmetry_test(x, y, tol=delta, rel=r/2) # 4) actual error > tol, <= rel self.do_symmetry_test(x, y, tol=delta-1, rel=r) self.do_symmetry_test(x, y, tol=delta-1, rel=2*r) # 5) exact equality test self.do_symmetry_test(x, x, tol=0, rel=0) self.do_symmetry_test(x, y, tol=0, rel=0) def do_symmetry_test(self, a, b, tol, rel): template = "approx_equal comparisons don't match for %r" flag1 = approx_equal(a, b, tol, rel) flag2 = approx_equal(b, a, tol, rel) self.assertEqual(flag1, flag2, template.format((a, b, tol, rel))) class ApproxEqualExactTest(unittest.TestCase): # Test the approx_equal function with exactly equal values. # Equal values should compare as approximately equal. # Test cases for exactly equal values, which should compare approx # equal regardless of the error tolerances given. def do_exactly_equal_test(self, x, tol, rel): result = approx_equal(x, x, tol=tol, rel=rel) self.assertTrue(result, 'equality failure for x=%r' % x) result = approx_equal(-x, -x, tol=tol, rel=rel) self.assertTrue(result, 'equality failure for x=%r' % -x) def test_exactly_equal_ints(self): # Test that equal int values are exactly equal. for n in [42, 19740, 14974, 230, 1795, 700245, 36587]: self.do_exactly_equal_test(n, 0, 0) def test_exactly_equal_floats(self): # Test that equal float values are exactly equal. for x in [0.42, 1.9740, 1497.4, 23.0, 179.5, 70.0245, 36.587]: self.do_exactly_equal_test(x, 0, 0) def test_exactly_equal_fractions(self): # Test that equal Fraction values are exactly equal. F = Fraction for f in [F(1, 2), F(0), F(5, 3), F(9, 7), F(35, 36), F(3, 7)]: self.do_exactly_equal_test(f, 0, 0) def test_exactly_equal_decimals(self): # Test that equal Decimal values are exactly equal. D = Decimal for d in map(D, "8.2 31.274 912.04 16.745 1.2047".split()): self.do_exactly_equal_test(d, 0, 0) def test_exactly_equal_absolute(self): # Test that equal values are exactly equal with an absolute error. for n in [16, 1013, 1372, 1198, 971, 4]: # Test as ints. self.do_exactly_equal_test(n, 0.01, 0) # Test as floats. self.do_exactly_equal_test(n/10, 0.01, 0) # Test as Fractions. f = Fraction(n, 1234) self.do_exactly_equal_test(f, 0.01, 0) def test_exactly_equal_absolute_decimals(self): # Test equal Decimal values are exactly equal with an absolute error. self.do_exactly_equal_test(Decimal("3.571"), Decimal("0.01"), 0) self.do_exactly_equal_test(-Decimal("81.3971"), Decimal("0.01"), 0) def test_exactly_equal_relative(self): # Test that equal values are exactly equal with a relative error. for x in [8347, 101.3, -7910.28, Fraction(5, 21)]: self.do_exactly_equal_test(x, 0, 0.01) self.do_exactly_equal_test(Decimal("11.68"), 0, Decimal("0.01")) def test_exactly_equal_both(self): # Test that equal values are equal when both tol and rel are given. for x in [41017, 16.742, -813.02, Fraction(3, 8)]: self.do_exactly_equal_test(x, 0.1, 0.01) D = Decimal self.do_exactly_equal_test(D("7.2"), D("0.1"), D("0.01")) class ApproxEqualUnequalTest(unittest.TestCase): # Unequal values should compare unequal with zero error tolerances. # Test cases for unequal values, with exact equality test. def do_exactly_unequal_test(self, x): for a in (x, -x): result = approx_equal(a, a+1, tol=0, rel=0) self.assertFalse(result, 'inequality failure for x=%r' % a) def test_exactly_unequal_ints(self): # Test unequal int values are unequal with zero error tolerance. for n in [951, 572305, 478, 917, 17240]: self.do_exactly_unequal_test(n) def test_exactly_unequal_floats(self): # Test unequal float values are unequal with zero error tolerance. for x in [9.51, 5723.05, 47.8, 9.17, 17.24]: self.do_exactly_unequal_test(x) def test_exactly_unequal_fractions(self): # Test that unequal Fractions are unequal with zero error tolerance. F = Fraction for f in [F(1, 5), F(7, 9), F(12, 11), F(101, 99023)]: self.do_exactly_unequal_test(f) def test_exactly_unequal_decimals(self): # Test that unequal Decimals are unequal with zero error tolerance. for d in map(Decimal, "3.1415 298.12 3.47 18.996 0.00245".split()): self.do_exactly_unequal_test(d) class ApproxEqualInexactTest(unittest.TestCase): # Inexact test cases for approx_error. # Test cases when comparing two values that are not exactly equal. # === Absolute error tests === def do_approx_equal_abs_test(self, x, delta): template = "Test failure for x={!r}, y={!r}" for y in (x + delta, x - delta): msg = template.format(x, y) self.assertTrue(approx_equal(x, y, tol=2*delta, rel=0), msg) self.assertFalse(approx_equal(x, y, tol=delta/2, rel=0), msg) def test_approx_equal_absolute_ints(self): # Test approximate equality of ints with an absolute error. for n in [-10737, -1975, -7, -2, 0, 1, 9, 37, 423, 9874, 23789110]: self.do_approx_equal_abs_test(n, 10) self.do_approx_equal_abs_test(n, 2) def test_approx_equal_absolute_floats(self): # Test approximate equality of floats with an absolute error. for x in [-284.126, -97.1, -3.4, -2.15, 0.5, 1.0, 7.8, 4.23, 3817.4]: self.do_approx_equal_abs_test(x, 1.5) self.do_approx_equal_abs_test(x, 0.01) self.do_approx_equal_abs_test(x, 0.0001) def test_approx_equal_absolute_fractions(self): # Test approximate equality of Fractions with an absolute error. delta = Fraction(1, 29) numerators = [-84, -15, -2, -1, 0, 1, 5, 17, 23, 34, 71] for f in (Fraction(n, 29) for n in numerators): self.do_approx_equal_abs_test(f, delta) self.do_approx_equal_abs_test(f, float(delta)) def test_approx_equal_absolute_decimals(self): # Test approximate equality of Decimals with an absolute error. delta = Decimal("0.01") for d in map(Decimal, "1.0 3.5 36.08 61.79 7912.3648".split()): self.do_approx_equal_abs_test(d, delta) self.do_approx_equal_abs_test(-d, delta) def test_cross_zero(self): # Test for the case of the two values having opposite signs. self.assertTrue(approx_equal(1e-5, -1e-5, tol=1e-4, rel=0)) # === Relative error tests === def do_approx_equal_rel_test(self, x, delta): template = "Test failure for x={!r}, y={!r}" for y in (x*(1+delta), x*(1-delta)): msg = template.format(x, y) self.assertTrue(approx_equal(x, y, tol=0, rel=2*delta), msg) self.assertFalse(approx_equal(x, y, tol=0, rel=delta/2), msg) def test_approx_equal_relative_ints(self): # Test approximate equality of ints with a relative error. self.assertTrue(approx_equal(64, 47, tol=0, rel=0.36)) self.assertTrue(approx_equal(64, 47, tol=0, rel=0.37)) # --- self.assertTrue(approx_equal(449, 512, tol=0, rel=0.125)) self.assertTrue(approx_equal(448, 512, tol=0, rel=0.125)) self.assertFalse(approx_equal(447, 512, tol=0, rel=0.125)) def test_approx_equal_relative_floats(self): # Test approximate equality of floats with a relative error. for x in [-178.34, -0.1, 0.1, 1.0, 36.97, 2847.136, 9145.074]: self.do_approx_equal_rel_test(x, 0.02) self.do_approx_equal_rel_test(x, 0.0001) def test_approx_equal_relative_fractions(self): # Test approximate equality of Fractions with a relative error. F = Fraction delta = Fraction(3, 8) for f in [F(3, 84), F(17, 30), F(49, 50), F(92, 85)]: for d in (delta, float(delta)): self.do_approx_equal_rel_test(f, d) self.do_approx_equal_rel_test(-f, d) def test_approx_equal_relative_decimals(self): # Test approximate equality of Decimals with a relative error. for d in map(Decimal, "0.02 1.0 5.7 13.67 94.138 91027.9321".split()): self.do_approx_equal_rel_test(d, Decimal("0.001")) self.do_approx_equal_rel_test(-d, Decimal("0.05")) # === Both absolute and relative error tests === # There are four cases to consider: # 1) actual error <= both absolute and relative error # 2) actual error <= absolute error but > relative error # 3) actual error <= relative error but > absolute error # 4) actual error > both absolute and relative error def do_check_both(self, a, b, tol, rel, tol_flag, rel_flag): check = self.assertTrue if tol_flag else self.assertFalse check(approx_equal(a, b, tol=tol, rel=0)) check = self.assertTrue if rel_flag else self.assertFalse check(approx_equal(a, b, tol=0, rel=rel)) check = self.assertTrue if (tol_flag or rel_flag) else self.assertFalse check(approx_equal(a, b, tol=tol, rel=rel)) def test_approx_equal_both1(self): # Test actual error <= both absolute and relative error. self.do_check_both(7.955, 7.952, 0.004, 3.8e-4, True, True) self.do_check_both(-7.387, -7.386, 0.002, 0.0002, True, True) def test_approx_equal_both2(self): # Test actual error <= absolute error but > relative error. self.do_check_both(7.955, 7.952, 0.004, 3.7e-4, True, False) def test_approx_equal_both3(self): # Test actual error <= relative error but > absolute error. self.do_check_both(7.955, 7.952, 0.001, 3.8e-4, False, True) def test_approx_equal_both4(self): # Test actual error > both absolute and relative error. self.do_check_both(2.78, 2.75, 0.01, 0.001, False, False) self.do_check_both(971.44, 971.47, 0.02, 3e-5, False, False) class ApproxEqualSpecialsTest(unittest.TestCase): # Test approx_equal with NANs and INFs and zeroes. def test_inf(self): for type_ in (float, Decimal): inf = type_('inf') self.assertTrue(approx_equal(inf, inf)) self.assertTrue(approx_equal(inf, inf, 0, 0)) self.assertTrue(approx_equal(inf, inf, 1, 0.01)) self.assertTrue(approx_equal(-inf, -inf)) self.assertFalse(approx_equal(inf, -inf)) self.assertFalse(approx_equal(inf, 1000)) def test_nan(self): for type_ in (float, Decimal): nan = type_('nan') for other in (nan, type_('inf'), 1000): self.assertFalse(approx_equal(nan, other)) def test_float_zeroes(self): nzero = math.copysign(0.0, -1) self.assertTrue(approx_equal(nzero, 0.0, tol=0.1, rel=0.1)) def test_decimal_zeroes(self): nzero = Decimal("-0.0") self.assertTrue(approx_equal(nzero, Decimal(0), tol=0.1, rel=0.1)) class TestApproxEqualErrors(unittest.TestCase): # Test error conditions of approx_equal. def test_bad_tol(self): # Test negative tol raises. self.assertRaises(ValueError, approx_equal, 100, 100, -1, 0.1) def test_bad_rel(self): # Test negative rel raises. self.assertRaises(ValueError, approx_equal, 100, 100, 1, -0.1) # --- Tests for NumericTestCase --- # The formatting routine that generates the error messages is complex enough # that it too needs testing. class TestNumericTestCase(unittest.TestCase): # The exact wording of NumericTestCase error messages is *not* guaranteed, # but we need to give them some sort of test to ensure that they are # generated correctly. As a compromise, we look for specific substrings # that are expected to be found even if the overall error message changes. def do_test(self, args): actual_msg = NumericTestCase._make_std_err_msg(*args) expected = self.generate_substrings(*args) for substring in expected: self.assertIn(substring, actual_msg) def test_numerictestcase_is_testcase(self): # Ensure that NumericTestCase actually is a TestCase. self.assertTrue(issubclass(NumericTestCase, unittest.TestCase)) def test_error_msg_numeric(self): # Test the error message generated for numeric comparisons. args = (2.5, 4.0, 0.5, 0.25, None) self.do_test(args) def test_error_msg_sequence(self): # Test the error message generated for sequence comparisons. args = (3.75, 8.25, 1.25, 0.5, 7) self.do_test(args) def generate_substrings(self, first, second, tol, rel, idx): """Return substrings we expect to see in error messages.""" abs_err, rel_err = _calc_errors(first, second) substrings = [ 'tol=%r' % tol, 'rel=%r' % rel, 'absolute error = %r' % abs_err, 'relative error = %r' % rel_err, ] if idx is not None: substrings.append('differ at index %d' % idx) return substrings # ======================================= # === Tests for the statistics module === # ======================================= class GlobalsTest(unittest.TestCase): module = statistics expected_metadata = ["__doc__", "__all__"] def test_meta(self): # Test for the existence of metadata. for meta in self.expected_metadata: self.assertTrue(hasattr(self.module, meta), "%s not present" % meta) def test_check_all(self): # Check everything in __all__ exists and is public. module = self.module for name in module.__all__: # No private names in __all__: self.assertFalse(name.startswith("_"), 'private name "%s" in __all__' % name) # And anything in __all__ must exist: self.assertTrue(hasattr(module, name), 'missing name "%s" in __all__' % name) class DocTests(unittest.TestCase): @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -OO and above") def test_doc_tests(self): failed, tried = doctest.testmod(statistics, optionflags=doctest.ELLIPSIS) self.assertGreater(tried, 0) self.assertEqual(failed, 0) class StatisticsErrorTest(unittest.TestCase): def test_has_exception(self): errmsg = ( "Expected StatisticsError to be a ValueError, but got a" " subclass of %r instead." ) self.assertTrue(hasattr(statistics, 'StatisticsError')) self.assertTrue( issubclass(statistics.StatisticsError, ValueError), errmsg % statistics.StatisticsError.__base__ ) # === Tests for private utility functions === class ExactRatioTest(unittest.TestCase): # Test _exact_ratio utility. def test_int(self): for i in (-20, -3, 0, 5, 99, 10**20): self.assertEqual(statistics._exact_ratio(i), (i, 1)) def test_fraction(self): numerators = (-5, 1, 12, 38) for n in numerators: f = Fraction(n, 37) self.assertEqual(statistics._exact_ratio(f), (n, 37)) def test_float(self): self.assertEqual(statistics._exact_ratio(0.125), (1, 8)) self.assertEqual(statistics._exact_ratio(1.125), (9, 8)) data = [random.uniform(-100, 100) for _ in range(100)] for x in data: num, den = statistics._exact_ratio(x) self.assertEqual(x, num/den) def test_decimal(self): D = Decimal _exact_ratio = statistics._exact_ratio self.assertEqual(_exact_ratio(D("0.125")), (1, 8)) self.assertEqual(_exact_ratio(D("12.345")), (2469, 200)) self.assertEqual(_exact_ratio(D("-1.98")), (-99, 50)) def test_inf(self): INF = float("INF") class MyFloat(float): pass class MyDecimal(Decimal): pass for inf in (INF, -INF): for type_ in (float, MyFloat, Decimal, MyDecimal): x = type_(inf) ratio = statistics._exact_ratio(x) self.assertEqual(ratio, (x, None)) self.assertEqual(type(ratio[0]), type_) self.assertTrue(math.isinf(ratio[0])) def test_float_nan(self): NAN = float("NAN") class MyFloat(float): pass for nan in (NAN, MyFloat(NAN)): ratio = statistics._exact_ratio(nan) self.assertTrue(math.isnan(ratio[0])) self.assertIs(ratio[1], None) self.assertEqual(type(ratio[0]), type(nan)) def test_decimal_nan(self): NAN = Decimal("NAN") sNAN = Decimal("sNAN") class MyDecimal(Decimal): pass for nan in (NAN, MyDecimal(NAN), sNAN, MyDecimal(sNAN)): ratio = statistics._exact_ratio(nan) self.assertTrue(_nan_equal(ratio[0], nan)) self.assertIs(ratio[1], None) self.assertEqual(type(ratio[0]), type(nan)) class DecimalToRatioTest(unittest.TestCase): # Test _exact_ratio private function. def test_infinity(self): # Test that INFs are handled correctly. inf = Decimal('INF') self.assertEqual(statistics._exact_ratio(inf), (inf, None)) self.assertEqual(statistics._exact_ratio(-inf), (-inf, None)) def test_nan(self): # Test that NANs are handled correctly. for nan in (Decimal('NAN'), Decimal('sNAN')): num, den = statistics._exact_ratio(nan) # Because NANs always compare non-equal, we cannot use assertEqual. # Nor can we use an identity test, as we don't guarantee anything # about the object identity. self.assertTrue(_nan_equal(num, nan)) self.assertIs(den, None) def test_sign(self): # Test sign is calculated correctly. numbers = [Decimal("9.8765e12"), Decimal("9.8765e-12")] for d in numbers: # First test positive decimals. assert d > 0 num, den = statistics._exact_ratio(d) self.assertGreaterEqual(num, 0) self.assertGreater(den, 0) # Then test negative decimals. num, den = statistics._exact_ratio(-d) self.assertLessEqual(num, 0) self.assertGreater(den, 0) def test_negative_exponent(self): # Test result when the exponent is negative. t = statistics._exact_ratio(Decimal("0.1234")) self.assertEqual(t, (617, 5000)) def test_positive_exponent(self): # Test results when the exponent is positive. t = statistics._exact_ratio(Decimal("1.234e7")) self.assertEqual(t, (12340000, 1)) def test_regression_20536(self): # Regression test for issue 20536. # See http://bugs.python.org/issue20536 t = statistics._exact_ratio(Decimal("1e2")) self.assertEqual(t, (100, 1)) t = statistics._exact_ratio(Decimal("1.47e5")) self.assertEqual(t, (147000, 1)) class IsFiniteTest(unittest.TestCase): # Test _isfinite private function. def test_finite(self): # Test that finite numbers are recognised as finite. for x in (5, Fraction(1, 3), 2.5, Decimal("5.5")): self.assertTrue(statistics._isfinite(x)) def test_infinity(self): # Test that INFs are not recognised as finite. for x in (float("inf"), Decimal("inf")): self.assertFalse(statistics._isfinite(x)) def test_nan(self): # Test that NANs are not recognised as finite. for x in (float("nan"), Decimal("NAN"), Decimal("sNAN")): self.assertFalse(statistics._isfinite(x)) class CoerceTest(unittest.TestCase): # Test that private function _coerce correctly deals with types. # The coercion rules are currently an implementation detail, although at # some point that should change. The tests and comments here define the # correct implementation. # Pre-conditions of _coerce: # # - The first time _sum calls _coerce, the # - coerce(T, S) will never be called with bool as the first argument; # this is a pre-condition, guarded with an assertion. # # - coerce(T, T) will always return T; we assume T is a valid numeric # type. Violate this assumption at your own risk. # # - Apart from as above, bool is treated as if it were actually int. #
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_stringprep.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_stringprep.py
# To fully test this module, we would need a copy of the stringprep tables. # Since we don't have them, this test checks only a few code points. import unittest from stringprep import * class StringprepTests(unittest.TestCase): def test(self): self.assertTrue(in_table_a1("\u0221")) self.assertFalse(in_table_a1("\u0222")) self.assertTrue(in_table_b1("\u00ad")) self.assertFalse(in_table_b1("\u00ae")) self.assertTrue(map_table_b2("\u0041"), "\u0061") self.assertTrue(map_table_b2("\u0061"), "\u0061") self.assertTrue(map_table_b3("\u0041"), "\u0061") self.assertTrue(map_table_b3("\u0061"), "\u0061") self.assertTrue(in_table_c11("\u0020")) self.assertFalse(in_table_c11("\u0021")) self.assertTrue(in_table_c12("\u00a0")) self.assertFalse(in_table_c12("\u00a1")) self.assertTrue(in_table_c12("\u00a0")) self.assertFalse(in_table_c12("\u00a1")) self.assertTrue(in_table_c11_c12("\u00a0")) self.assertFalse(in_table_c11_c12("\u00a1")) self.assertTrue(in_table_c21("\u001f")) self.assertFalse(in_table_c21("\u0020")) self.assertTrue(in_table_c22("\u009f")) self.assertFalse(in_table_c22("\u00a0")) self.assertTrue(in_table_c21_c22("\u009f")) self.assertFalse(in_table_c21_c22("\u00a0")) self.assertTrue(in_table_c3("\ue000")) self.assertFalse(in_table_c3("\uf900")) self.assertTrue(in_table_c4("\uffff")) self.assertFalse(in_table_c4("\u0000")) self.assertTrue(in_table_c5("\ud800")) self.assertFalse(in_table_c5("\ud7ff")) self.assertTrue(in_table_c6("\ufff9")) self.assertFalse(in_table_c6("\ufffe")) self.assertTrue(in_table_c7("\u2ff0")) self.assertFalse(in_table_c7("\u2ffc")) self.assertTrue(in_table_c8("\u0340")) self.assertFalse(in_table_c8("\u0342")) # C.9 is not in the bmp # self.assertTrue(in_table_c9(u"\U000E0001")) # self.assertFalse(in_table_c8(u"\U000E0002")) self.assertTrue(in_table_d1("\u05be")) self.assertFalse(in_table_d1("\u05bf")) self.assertTrue(in_table_d2("\u0041")) self.assertFalse(in_table_d2("\u0040")) # This would generate a hash of all predicates. However, running # it is quite expensive, and only serves to detect changes in the # unicode database. Instead, stringprep.py asserts the version of # the database. # import hashlib # predicates = [k for k in dir(stringprep) if k.startswith("in_table")] # predicates.sort() # for p in predicates: # f = getattr(stringprep, p) # # Collect all BMP code points # data = ["0"] * 0x10000 # for i in range(0x10000): # if f(unichr(i)): # data[i] = "1" # data = "".join(data) # h = hashlib.sha1() # h.update(data) # print p, h.hexdigest() if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/make_ssl_certs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/make_ssl_certs.py
"""Make the custom certificate and private key files used by test_ssl and friends.""" import os import pprint import shutil import tempfile from subprocess import * req_template = """ [ default ] base_url = http://testca.pythontest.net/testca [req] distinguished_name = req_distinguished_name prompt = no [req_distinguished_name] C = XY L = Castle Anthrax O = Python Software Foundation CN = {hostname} [req_x509_extensions_simple] subjectAltName = @san [req_x509_extensions_full] subjectAltName = @san keyUsage = critical,keyEncipherment,digitalSignature extendedKeyUsage = serverAuth,clientAuth basicConstraints = critical,CA:false subjectKeyIdentifier = hash authorityKeyIdentifier = keyid:always,issuer:always authorityInfoAccess = @issuer_ocsp_info crlDistributionPoints = @crl_info [ issuer_ocsp_info ] caIssuers;URI.0 = $base_url/pycacert.cer OCSP;URI.0 = $base_url/ocsp/ [ crl_info ] URI.0 = $base_url/revocation.crl [san] DNS.1 = {hostname} {extra_san} [dir_sect] C = XY L = Castle Anthrax O = Python Software Foundation CN = dirname example [princ_name] realm = EXP:0, GeneralString:KERBEROS.REALM principal_name = EXP:1, SEQUENCE:principal_seq [principal_seq] name_type = EXP:0, INTEGER:1 name_string = EXP:1, SEQUENCE:principals [principals] princ1 = GeneralString:username [ ca ] default_ca = CA_default [ CA_default ] dir = cadir database = $dir/index.txt crlnumber = $dir/crl.txt default_md = sha256 default_days = 3600 default_crl_days = 3600 certificate = pycacert.pem private_key = pycakey.pem serial = $dir/serial RANDFILE = $dir/.rand policy = policy_match [ policy_match ] countryName = match stateOrProvinceName = optional organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional [ v3_ca ] subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer basicConstraints = CA:true """ here = os.path.abspath(os.path.dirname(__file__)) def make_cert_key(hostname, sign=False, extra_san='', ext='req_x509_extensions_full', key='rsa:3072'): print("creating cert for " + hostname) tempnames = [] for i in range(3): with tempfile.NamedTemporaryFile(delete=False) as f: tempnames.append(f.name) req_file, cert_file, key_file = tempnames try: req = req_template.format(hostname=hostname, extra_san=extra_san) with open(req_file, 'w') as f: f.write(req) args = ['req', '-new', '-days', '3650', '-nodes', '-newkey', key, '-keyout', key_file, '-extensions', ext, '-config', req_file] if sign: with tempfile.NamedTemporaryFile(delete=False) as f: tempnames.append(f.name) reqfile = f.name args += ['-out', reqfile ] else: args += ['-x509', '-out', cert_file ] check_call(['openssl'] + args) if sign: args = [ 'ca', '-config', req_file, '-extensions', ext, '-out', cert_file, '-outdir', 'cadir', '-policy', 'policy_anything', '-batch', '-infiles', reqfile ] check_call(['openssl'] + args) with open(cert_file, 'r') as f: cert = f.read() with open(key_file, 'r') as f: key = f.read() return cert, key finally: for name in tempnames: os.remove(name) TMP_CADIR = 'cadir' def unmake_ca(): shutil.rmtree(TMP_CADIR) def make_ca(): os.mkdir(TMP_CADIR) with open(os.path.join('cadir','index.txt'),'a+') as f: pass # empty file with open(os.path.join('cadir','crl.txt'),'a+') as f: f.write("00") with open(os.path.join('cadir','index.txt.attr'),'w+') as f: f.write('unique_subject = no') with tempfile.NamedTemporaryFile("w") as t: t.write(req_template.format(hostname='our-ca-server', extra_san='')) t.flush() with tempfile.NamedTemporaryFile() as f: args = ['req', '-new', '-days', '3650', '-extensions', 'v3_ca', '-nodes', '-newkey', 'rsa:3072', '-keyout', 'pycakey.pem', '-out', f.name, '-subj', '/C=XY/L=Castle Anthrax/O=Python Software Foundation CA/CN=our-ca-server'] check_call(['openssl'] + args) args = ['ca', '-config', t.name, '-create_serial', '-out', 'pycacert.pem', '-batch', '-outdir', TMP_CADIR, '-keyfile', 'pycakey.pem', '-days', '3650', '-selfsign', '-extensions', 'v3_ca', '-infiles', f.name ] check_call(['openssl'] + args) args = ['ca', '-config', t.name, '-gencrl', '-out', 'revocation.crl'] check_call(['openssl'] + args) # capath hashes depend on subject! check_call([ 'openssl', 'x509', '-in', 'pycacert.pem', '-out', 'capath/ceff1710.0' ]) shutil.copy('capath/ceff1710.0', 'capath/b1930218.0') def print_cert(path): import _ssl pprint.pprint(_ssl._test_decode_cert(path)) if __name__ == '__main__': os.chdir(here) cert, key = make_cert_key('localhost', ext='req_x509_extensions_simple') with open('ssl_cert.pem', 'w') as f: f.write(cert) with open('ssl_key.pem', 'w') as f: f.write(key) print("password protecting ssl_key.pem in ssl_key.passwd.pem") check_call(['openssl','pkey','-in','ssl_key.pem','-out','ssl_key.passwd.pem','-aes256','-passout','pass:somepass']) check_call(['openssl','pkey','-in','ssl_key.pem','-out','keycert.passwd.pem','-aes256','-passout','pass:somepass']) with open('keycert.pem', 'w') as f: f.write(key) f.write(cert) with open('keycert.passwd.pem', 'a+') as f: f.write(cert) # For certificate matching tests make_ca() cert, key = make_cert_key('fakehostname', ext='req_x509_extensions_simple') with open('keycert2.pem', 'w') as f: f.write(key) f.write(cert) cert, key = make_cert_key('localhost', True) with open('keycert3.pem', 'w') as f: f.write(key) f.write(cert) cert, key = make_cert_key('fakehostname', True) with open('keycert4.pem', 'w') as f: f.write(key) f.write(cert) cert, key = make_cert_key( 'localhost-ecc', True, key='param:secp384r1.pem' ) with open('keycertecc.pem', 'w') as f: f.write(key) f.write(cert) extra_san = [ 'otherName.1 = 1.2.3.4;UTF8:some other identifier', 'otherName.2 = 1.3.6.1.5.2.2;SEQUENCE:princ_name', 'email.1 = user@example.org', 'DNS.2 = www.example.org', # GEN_X400 'dirName.1 = dir_sect', # GEN_EDIPARTY 'URI.1 = https://www.python.org/', 'IP.1 = 127.0.0.1', 'IP.2 = ::1', 'RID.1 = 1.2.3.4.5', ] cert, key = make_cert_key('allsans', extra_san='\n'.join(extra_san)) with open('allsans.pem', 'w') as f: f.write(key) f.write(cert) extra_san = [ # könig (king) 'DNS.2 = xn--knig-5qa.idn.pythontest.net', # königsgäßchen (king's alleyway) 'DNS.3 = xn--knigsgsschen-lcb0w.idna2003.pythontest.net', 'DNS.4 = xn--knigsgchen-b4a3dun.idna2008.pythontest.net', # βόλοσ (marble) 'DNS.5 = xn--nxasmq6b.idna2003.pythontest.net', 'DNS.6 = xn--nxasmm1c.idna2008.pythontest.net', ] # IDN SANS, signed cert, key = make_cert_key('idnsans', True, extra_san='\n'.join(extra_san)) with open('idnsans.pem', 'w') as f: f.write(key) f.write(cert) unmake_ca() print("update Lib/test/test_ssl.py and Lib/test/test_asyncio/util.py") print_cert('keycert.pem') print_cert('keycert3.pem')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_call.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_call.py
import datetime import unittest from test.support import cpython_only try: import _testcapi except ImportError: _testcapi = None import struct import collections import itertools import gc class FunctionCalls(unittest.TestCase): def test_kwargs_order(self): # bpo-34320: **kwargs should preserve order of passed OrderedDict od = collections.OrderedDict([('a', 1), ('b', 2)]) od.move_to_end('a') expected = list(od.items()) def fn(**kw): return kw res = fn(**od) self.assertIsInstance(res, dict) self.assertEqual(list(res.items()), expected) # The test cases here cover several paths through the function calling # code. They depend on the METH_XXX flag that is used to define a C # function, which can't be verified from Python. If the METH_XXX decl # for a C function changes, these tests may not cover the right paths. class CFunctionCalls(unittest.TestCase): def test_varargs0(self): self.assertRaises(TypeError, {}.__contains__) def test_varargs1(self): {}.__contains__(0) def test_varargs2(self): self.assertRaises(TypeError, {}.__contains__, 0, 1) def test_varargs0_ext(self): try: {}.__contains__(*()) except TypeError: pass def test_varargs1_ext(self): {}.__contains__(*(0,)) def test_varargs2_ext(self): try: {}.__contains__(*(1, 2)) except TypeError: pass else: raise RuntimeError def test_varargs1_kw(self): self.assertRaises(TypeError, {}.__contains__, x=2) def test_varargs2_kw(self): self.assertRaises(TypeError, {}.__contains__, x=2, y=2) def test_oldargs0_0(self): {}.keys() def test_oldargs0_1(self): self.assertRaises(TypeError, {}.keys, 0) def test_oldargs0_2(self): self.assertRaises(TypeError, {}.keys, 0, 1) def test_oldargs0_0_ext(self): {}.keys(*()) def test_oldargs0_1_ext(self): try: {}.keys(*(0,)) except TypeError: pass else: raise RuntimeError def test_oldargs0_2_ext(self): try: {}.keys(*(1, 2)) except TypeError: pass else: raise RuntimeError def test_oldargs0_0_kw(self): try: {}.keys(x=2) except TypeError: pass else: raise RuntimeError def test_oldargs0_1_kw(self): self.assertRaises(TypeError, {}.keys, x=2) def test_oldargs0_2_kw(self): self.assertRaises(TypeError, {}.keys, x=2, y=2) def test_oldargs1_0(self): self.assertRaises(TypeError, [].count) def test_oldargs1_1(self): [].count(1) def test_oldargs1_2(self): self.assertRaises(TypeError, [].count, 1, 2) def test_oldargs1_0_ext(self): try: [].count(*()) except TypeError: pass else: raise RuntimeError def test_oldargs1_1_ext(self): [].count(*(1,)) def test_oldargs1_2_ext(self): try: [].count(*(1, 2)) except TypeError: pass else: raise RuntimeError def test_oldargs1_0_kw(self): self.assertRaises(TypeError, [].count, x=2) def test_oldargs1_1_kw(self): self.assertRaises(TypeError, [].count, {}, x=2) def test_oldargs1_2_kw(self): self.assertRaises(TypeError, [].count, x=2, y=2) @cpython_only class CFunctionCallsErrorMessages(unittest.TestCase): def test_varargs0(self): msg = r"__contains__\(\) takes exactly one argument \(0 given\)" self.assertRaisesRegex(TypeError, msg, {}.__contains__) def test_varargs2(self): msg = r"__contains__\(\) takes exactly one argument \(2 given\)" self.assertRaisesRegex(TypeError, msg, {}.__contains__, 0, 1) def test_varargs3(self): msg = r"^from_bytes\(\) takes at most 2 positional arguments \(3 given\)" self.assertRaisesRegex(TypeError, msg, int.from_bytes, b'a', 'little', False) def test_varargs1_kw(self): msg = r"__contains__\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, {}.__contains__, x=2) def test_varargs2_kw(self): msg = r"__contains__\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, {}.__contains__, x=2, y=2) def test_varargs3_kw(self): msg = r"bool\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, bool, x=2) def test_varargs4_kw(self): msg = r"^index\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, [].index, x=2) def test_varargs5_kw(self): msg = r"^hasattr\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, hasattr, x=2) def test_varargs6_kw(self): msg = r"^getattr\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, getattr, x=2) def test_varargs7_kw(self): msg = r"^next\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, next, x=2) def test_varargs8_kw(self): msg = r"^pack\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, struct.pack, x=2) def test_varargs9_kw(self): msg = r"^pack_into\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, struct.pack_into, x=2) def test_varargs10_kw(self): msg = r"^index\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, collections.deque().index, x=2) def test_varargs11_kw(self): msg = r"^pack\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, struct.Struct.pack, struct.Struct(""), x=2) def test_varargs12_kw(self): msg = r"^staticmethod\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, staticmethod, func=id) def test_varargs13_kw(self): msg = r"^classmethod\(\) takes no keyword arguments$" self.assertRaisesRegex(TypeError, msg, classmethod, func=id) def test_varargs14_kw(self): msg = r"^product\(\) takes at most 1 keyword argument \(2 given\)$" self.assertRaisesRegex(TypeError, msg, itertools.product, 0, repeat=1, foo=2) def test_varargs15_kw(self): msg = r"^ImportError\(\) takes at most 2 keyword arguments \(3 given\)$" self.assertRaisesRegex(TypeError, msg, ImportError, 0, name=1, path=2, foo=3) def test_varargs16_kw(self): msg = r"^min\(\) takes at most 2 keyword arguments \(3 given\)$" self.assertRaisesRegex(TypeError, msg, min, 0, default=1, key=2, foo=3) def test_varargs17_kw(self): msg = r"^print\(\) takes at most 4 keyword arguments \(5 given\)$" self.assertRaisesRegex(TypeError, msg, print, 0, sep=1, end=2, file=3, flush=4, foo=5) def test_oldargs0_1(self): msg = r"keys\(\) takes no arguments \(1 given\)" self.assertRaisesRegex(TypeError, msg, {}.keys, 0) def test_oldargs0_2(self): msg = r"keys\(\) takes no arguments \(2 given\)" self.assertRaisesRegex(TypeError, msg, {}.keys, 0, 1) def test_oldargs0_1_kw(self): msg = r"keys\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, {}.keys, x=2) def test_oldargs0_2_kw(self): msg = r"keys\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, {}.keys, x=2, y=2) def test_oldargs1_0(self): msg = r"count\(\) takes exactly one argument \(0 given\)" self.assertRaisesRegex(TypeError, msg, [].count) def test_oldargs1_2(self): msg = r"count\(\) takes exactly one argument \(2 given\)" self.assertRaisesRegex(TypeError, msg, [].count, 1, 2) def test_oldargs1_0_kw(self): msg = r"count\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, [].count, x=2) def test_oldargs1_1_kw(self): msg = r"count\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, [].count, {}, x=2) def test_oldargs1_2_kw(self): msg = r"count\(\) takes no keyword arguments" self.assertRaisesRegex(TypeError, msg, [].count, x=2, y=2) def pyfunc(arg1, arg2): return [arg1, arg2] def pyfunc_noarg(): return "noarg" class PythonClass: def method(self, arg1, arg2): return [arg1, arg2] def method_noarg(self): return "noarg" @classmethod def class_method(cls): return "classmethod" @staticmethod def static_method(): return "staticmethod" PYTHON_INSTANCE = PythonClass() IGNORE_RESULT = object() @cpython_only class FastCallTests(unittest.TestCase): # Test calls with positional arguments CALLS_POSARGS = ( # (func, args: tuple, result) # Python function with 2 arguments (pyfunc, (1, 2), [1, 2]), # Python function without argument (pyfunc_noarg, (), "noarg"), # Python class methods (PythonClass.class_method, (), "classmethod"), (PythonClass.static_method, (), "staticmethod"), # Python instance methods (PYTHON_INSTANCE.method, (1, 2), [1, 2]), (PYTHON_INSTANCE.method_noarg, (), "noarg"), (PYTHON_INSTANCE.class_method, (), "classmethod"), (PYTHON_INSTANCE.static_method, (), "staticmethod"), # C function: METH_NOARGS (globals, (), IGNORE_RESULT), # C function: METH_O (id, ("hello",), IGNORE_RESULT), # C function: METH_VARARGS (dir, (1,), IGNORE_RESULT), # C function: METH_VARARGS | METH_KEYWORDS (min, (5, 9), 5), # C function: METH_FASTCALL (divmod, (1000, 33), (30, 10)), # C type static method: METH_FASTCALL | METH_CLASS (int.from_bytes, (b'\x01\x00', 'little'), 1), # bpo-30524: Test that calling a C type static method with no argument # doesn't crash (ignore the result): METH_FASTCALL | METH_CLASS (datetime.datetime.now, (), IGNORE_RESULT), ) # Test calls with positional and keyword arguments CALLS_KWARGS = ( # (func, args: tuple, kwargs: dict, result) # Python function with 2 arguments (pyfunc, (1,), {'arg2': 2}, [1, 2]), (pyfunc, (), {'arg1': 1, 'arg2': 2}, [1, 2]), # Python instance methods (PYTHON_INSTANCE.method, (1,), {'arg2': 2}, [1, 2]), (PYTHON_INSTANCE.method, (), {'arg1': 1, 'arg2': 2}, [1, 2]), # C function: METH_VARARGS | METH_KEYWORDS (max, ([],), {'default': 9}, 9), # C type static method: METH_FASTCALL | METH_CLASS (int.from_bytes, (b'\x01\x00',), {'byteorder': 'little'}, 1), (int.from_bytes, (), {'bytes': b'\x01\x00', 'byteorder': 'little'}, 1), ) def check_result(self, result, expected): if expected is IGNORE_RESULT: return self.assertEqual(result, expected) def test_fastcall(self): # Test _PyObject_FastCall() for func, args, expected in self.CALLS_POSARGS: with self.subTest(func=func, args=args): result = _testcapi.pyobject_fastcall(func, args) self.check_result(result, expected) if not args: # args=NULL, nargs=0 result = _testcapi.pyobject_fastcall(func, None) self.check_result(result, expected) def test_fastcall_dict(self): # Test _PyObject_FastCallDict() for func, args, expected in self.CALLS_POSARGS: with self.subTest(func=func, args=args): # kwargs=NULL result = _testcapi.pyobject_fastcalldict(func, args, None) self.check_result(result, expected) # kwargs={} result = _testcapi.pyobject_fastcalldict(func, args, {}) self.check_result(result, expected) if not args: # args=NULL, nargs=0, kwargs=NULL result = _testcapi.pyobject_fastcalldict(func, None, None) self.check_result(result, expected) # args=NULL, nargs=0, kwargs={} result = _testcapi.pyobject_fastcalldict(func, None, {}) self.check_result(result, expected) for func, args, kwargs, expected in self.CALLS_KWARGS: with self.subTest(func=func, args=args, kwargs=kwargs): result = _testcapi.pyobject_fastcalldict(func, args, kwargs) self.check_result(result, expected) def test_fastcall_keywords(self): # Test _PyObject_FastCallKeywords() for func, args, expected in self.CALLS_POSARGS: with self.subTest(func=func, args=args): # kwnames=NULL result = _testcapi.pyobject_fastcallkeywords(func, args, None) self.check_result(result, expected) # kwnames=() result = _testcapi.pyobject_fastcallkeywords(func, args, ()) self.check_result(result, expected) if not args: # kwnames=NULL result = _testcapi.pyobject_fastcallkeywords(func, None, None) self.check_result(result, expected) # kwnames=() result = _testcapi.pyobject_fastcallkeywords(func, None, ()) self.check_result(result, expected) for func, args, kwargs, expected in self.CALLS_KWARGS: with self.subTest(func=func, args=args, kwargs=kwargs): kwnames = tuple(kwargs.keys()) args = args + tuple(kwargs.values()) result = _testcapi.pyobject_fastcallkeywords(func, args, kwnames) self.check_result(result, expected) def test_fastcall_clearing_dict(self): # Test bpo-36907: the point of the test is just checking that this # does not crash. class IntWithDict: __slots__ = ["kwargs"] def __init__(self, **kwargs): self.kwargs = kwargs def __int__(self): self.kwargs.clear() gc.collect() return 0 x = IntWithDict(dont_inherit=IntWithDict()) # We test the argument handling of "compile" here, the compilation # itself is not relevant. When we pass flags=x below, x.__int__() is # called, which changes the keywords dict. compile("pass", "", "exec", x, **x.kwargs) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cmd_line.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cmd_line.py
# Tests invocation of the interpreter with various command line arguments # Most tests are executed with environment variables ignored # See test_cmd_line_script.py for testing of script execution import os import subprocess import sys import sysconfig import tempfile import unittest from test import support from test.support.script_helper import ( spawn_python, kill_python, assert_python_ok, assert_python_failure, interpreter_requires_environment ) # Debug build? Py_DEBUG = hasattr(sys, "gettotalrefcount") # XXX (ncoghlan): Move to script_helper and make consistent with run_python def _kill_python_and_exit_code(p): data = kill_python(p) returncode = p.wait() return data, returncode class CmdLineTest(unittest.TestCase): def test_directories(self): assert_python_failure('.') assert_python_failure('< .') def verify_valid_flag(self, cmd_line): rc, out, err = assert_python_ok(*cmd_line) self.assertTrue(out == b'' or out.endswith(b'\n')) self.assertNotIn(b'Traceback', out) self.assertNotIn(b'Traceback', err) def test_optimize(self): self.verify_valid_flag('-O') self.verify_valid_flag('-OO') def test_site_flag(self): self.verify_valid_flag('-S') def test_usage(self): rc, out, err = assert_python_ok('-h') self.assertIn(b'usage', out) def test_version(self): version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii") for switch in '-V', '--version', '-VV': rc, out, err = assert_python_ok(switch) self.assertFalse(err.startswith(version)) self.assertTrue(out.startswith(version)) def test_verbose(self): # -v causes imports to write to stderr. If the write to # stderr itself causes an import to happen (for the output # codec), a recursion loop can occur. rc, out, err = assert_python_ok('-v') self.assertNotIn(b'stack overflow', err) rc, out, err = assert_python_ok('-vv') self.assertNotIn(b'stack overflow', err) @unittest.skipIf(interpreter_requires_environment(), 'Cannot run -E tests when PYTHON env vars are required.') def test_xoptions(self): def get_xoptions(*args): # use subprocess module directly because test.support.script_helper adds # "-X faulthandler" to the command line args = (sys.executable, '-E') + args args += ('-c', 'import sys; print(sys._xoptions)') out = subprocess.check_output(args) opts = eval(out.splitlines()[0]) return opts opts = get_xoptions() self.assertEqual(opts, {}) opts = get_xoptions('-Xa', '-Xb=c,d=e') self.assertEqual(opts, {'a': True, 'b': 'c,d=e'}) def test_showrefcount(self): def run_python(*args): # this is similar to assert_python_ok but doesn't strip # the refcount from stderr. It can be replaced once # assert_python_ok stops doing that. cmd = [sys.executable] cmd.extend(args) PIPE = subprocess.PIPE p = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE) out, err = p.communicate() p.stdout.close() p.stderr.close() rc = p.returncode self.assertEqual(rc, 0) return rc, out, err code = 'import sys; print(sys._xoptions)' # normally the refcount is hidden rc, out, err = run_python('-c', code) self.assertEqual(out.rstrip(), b'{}') self.assertEqual(err, b'') # "-X showrefcount" shows the refcount, but only in debug builds rc, out, err = run_python('-X', 'showrefcount', '-c', code) self.assertEqual(out.rstrip(), b"{'showrefcount': True}") if Py_DEBUG: self.assertRegex(err, br'^\[\d+ refs, \d+ blocks\]') else: self.assertEqual(err, b'') def test_run_module(self): # Test expected operation of the '-m' switch # Switch needs an argument assert_python_failure('-m') # Check we get an error for a nonexistent module assert_python_failure('-m', 'fnord43520xyz') # Check the runpy module also gives an error for # a nonexistent module assert_python_failure('-m', 'runpy', 'fnord43520xyz') # All good if module is located and run successfully assert_python_ok('-m', 'timeit', '-n', '1') def test_run_module_bug1764407(self): # -m and -i need to play well together # Runs the timeit module and checks the __main__ # namespace has been populated appropriately p = spawn_python('-i', '-m', 'timeit', '-n', '1') p.stdin.write(b'Timer\n') p.stdin.write(b'exit()\n') data = kill_python(p) self.assertTrue(data.find(b'1 loop') != -1) self.assertTrue(data.find(b'__main__.Timer') != -1) def test_run_code(self): # Test expected operation of the '-c' switch # Switch needs an argument assert_python_failure('-c') # Check we get an error for an uncaught exception assert_python_failure('-c', 'raise Exception') # All good if execution is successful assert_python_ok('-c', 'pass') @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII') def test_non_ascii(self): # Test handling of non-ascii data command = ("assert(ord(%r) == %s)" % (support.FS_NONASCII, ord(support.FS_NONASCII))) assert_python_ok('-c', command) # On Windows, pass bytes to subprocess doesn't test how Python decodes the # command line, but how subprocess does decode bytes to unicode. Python # doesn't decode the command line because Windows provides directly the # arguments as unicode (using wmain() instead of main()). @unittest.skipIf(sys.platform == 'win32', 'Windows has a native unicode API') def test_undecodable_code(self): undecodable = b"\xff" env = os.environ.copy() # Use C locale to get ascii for the locale encoding env['LC_ALL'] = 'C' env['PYTHONCOERCECLOCALE'] = '0' code = ( b'import locale; ' b'print(ascii("' + undecodable + b'"), ' b'locale.getpreferredencoding())') p = subprocess.Popen( [sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) stdout, stderr = p.communicate() if p.returncode == 1: # _Py_char2wchar() decoded b'\xff' as '\udcff' (b'\xff' is not # decodable from ASCII) and run_command() failed on # PyUnicode_AsUTF8String(). This is the expected behaviour on # Linux. pattern = b"Unable to decode the command from the command line:" elif p.returncode == 0: # _Py_char2wchar() decoded b'\xff' as '\xff' even if the locale is # C and the locale encoding is ASCII. It occurs on FreeBSD, Solaris # and Mac OS X. pattern = b"'\\xff' " # The output is followed by the encoding name, an alias to ASCII. # Examples: "US-ASCII" or "646" (ISO 646, on Solaris). else: raise AssertionError("Unknown exit code: %s, output=%a" % (p.returncode, stdout)) if not stdout.startswith(pattern): raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) @unittest.skipUnless((sys.platform == 'darwin' or support.is_android), 'test specific to Mac OS X and Android') def test_osx_android_utf8(self): def check_output(text): decoded = text.decode('utf-8', 'surrogateescape') expected = ascii(decoded).encode('ascii') + b'\n' env = os.environ.copy() # C locale gives ASCII locale encoding, but Python uses UTF-8 # to parse the command line arguments on Mac OS X and Android. env['LC_ALL'] = 'C' p = subprocess.Popen( (sys.executable, "-c", "import sys; print(ascii(sys.argv[1]))", text), stdout=subprocess.PIPE, env=env) stdout, stderr = p.communicate() self.assertEqual(stdout, expected) self.assertEqual(p.returncode, 0) # test valid utf-8 text = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8') check_output(text) # test invalid utf-8 text = ( b'\xff' # invalid byte b'\xc3\xa9' # valid utf-8 character b'\xc3\xff' # invalid byte sequence b'\xed\xa0\x80' # lone surrogate character (invalid) ) check_output(text) def test_unbuffered_output(self): # Test expected operation of the '-u' switch for stream in ('stdout', 'stderr'): # Binary is unbuffered code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data, b'x', "binary %s not unbuffered" % stream) # Text is unbuffered code = ("import os, sys; sys.%s.write('x'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data, b'x', "text %s not unbuffered" % stream) def test_unbuffered_input(self): # sys.stdin still works with '-u' code = ("import sys; sys.stdout.write(sys.stdin.read(1))") p = spawn_python('-u', '-c', code) p.stdin.write(b'x') p.stdin.flush() data, rc = _kill_python_and_exit_code(p) self.assertEqual(rc, 0) self.assertTrue(data.startswith(b'x'), data) def test_large_PYTHONPATH(self): path1 = "ABCDE" * 100 path2 = "FGHIJ" * 100 path = path1 + os.pathsep + path2 code = """if 1: import sys path = ":".join(sys.path) path = path.encode("ascii", "backslashreplace") sys.stdout.buffer.write(path)""" rc, out, err = assert_python_ok('-S', '-c', code, PYTHONPATH=path) self.assertIn(path1.encode('ascii'), out) self.assertIn(path2.encode('ascii'), out) def test_empty_PYTHONPATH_issue16309(self): # On Posix, it is documented that setting PATH to the # empty string is equivalent to not setting PATH at all, # which is an exception to the rule that in a string like # "/bin::/usr/bin" the empty string in the middle gets # interpreted as '.' code = """if 1: import sys path = ":".join(sys.path) path = path.encode("ascii", "backslashreplace") sys.stdout.buffer.write(path)""" rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="") rc2, out2, err2 = assert_python_ok('-c', code, __isolated=False) # regarding to Posix specification, outputs should be equal # for empty and unset PYTHONPATH self.assertEqual(out1, out2) def test_displayhook_unencodable(self): for encoding in ('ascii', 'latin-1', 'utf-8'): env = os.environ.copy() env['PYTHONIOENCODING'] = encoding p = subprocess.Popen( [sys.executable, '-i'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) # non-ascii, surrogate, non-BMP printable, non-BMP unprintable text = "a=\xe9 b=\uDC80 c=\U00010000 d=\U0010FFFF" p.stdin.write(ascii(text).encode('ascii') + b"\n") p.stdin.write(b'exit()\n') data = kill_python(p) escaped = repr(text).encode(encoding, 'backslashreplace') self.assertIn(escaped, data) def check_input(self, code, expected): with tempfile.NamedTemporaryFile("wb+") as stdin: sep = os.linesep.encode('ASCII') stdin.write(sep.join((b'abc', b'def'))) stdin.flush() stdin.seek(0) with subprocess.Popen( (sys.executable, "-c", code), stdin=stdin, stdout=subprocess.PIPE) as proc: stdout, stderr = proc.communicate() self.assertEqual(stdout.rstrip(), expected) def test_stdin_readline(self): # Issue #11272: check that sys.stdin.readline() replaces '\r\n' by '\n' # on Windows (sys.stdin is opened in binary mode) self.check_input( "import sys; print(repr(sys.stdin.readline()))", b"'abc\\n'") def test_builtin_input(self): # Issue #11272: check that input() strips newlines ('\n' or '\r\n') self.check_input( "print(repr(input()))", b"'abc'") def test_output_newline(self): # Issue 13119 Newline for print() should be \r\n on Windows. code = """if 1: import sys print(1) print(2) print(3, file=sys.stderr) print(4, file=sys.stderr)""" rc, out, err = assert_python_ok('-c', code) if sys.platform == 'win32': self.assertEqual(b'1\r\n2\r\n', out) self.assertEqual(b'3\r\n4', err) else: self.assertEqual(b'1\n2\n', out) self.assertEqual(b'3\n4', err) def test_unmached_quote(self): # Issue #10206: python program starting with unmatched quote # spewed spaces to stdout rc, out, err = assert_python_failure('-c', "'") self.assertRegex(err.decode('ascii', 'ignore'), 'SyntaxError') self.assertEqual(b'', out) def test_stdout_flush_at_shutdown(self): # Issue #5319: if stdout.flush() fails at shutdown, an error should # be printed out. code = """if 1: import os, sys, test.support test.support.SuppressCrashReport().__enter__() sys.stdout.write('x') os.close(sys.stdout.fileno())""" rc, out, err = assert_python_failure('-c', code) self.assertEqual(b'', out) self.assertEqual(120, rc) self.assertRegex(err.decode('ascii', 'ignore'), 'Exception ignored in.*\nOSError: .*') def test_closed_stdout(self): # Issue #13444: if stdout has been explicitly closed, we should # not attempt to flush it at shutdown. code = "import sys; sys.stdout.close()" rc, out, err = assert_python_ok('-c', code) self.assertEqual(b'', err) # Issue #7111: Python should work without standard streams @unittest.skipIf(os.name != 'posix', "test needs POSIX semantics") def _test_no_stdio(self, streams): code = """if 1: import os, sys for i, s in enumerate({streams}): if getattr(sys, s) is not None: os._exit(i + 1) os._exit(42)""".format(streams=streams) def preexec(): if 'stdin' in streams: os.close(0) if 'stdout' in streams: os.close(1) if 'stderr' in streams: os.close(2) p = subprocess.Popen( [sys.executable, "-E", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec) out, err = p.communicate() self.assertEqual(support.strip_python_stderr(err), b'') self.assertEqual(p.returncode, 42) def test_no_stdin(self): self._test_no_stdio(['stdin']) def test_no_stdout(self): self._test_no_stdio(['stdout']) def test_no_stderr(self): self._test_no_stdio(['stderr']) def test_no_std_streams(self): self._test_no_stdio(['stdin', 'stdout', 'stderr']) def test_hash_randomization(self): # Verify that -R enables hash randomization: self.verify_valid_flag('-R') hashes = [] if os.environ.get('PYTHONHASHSEED', 'random') != 'random': env = dict(os.environ) # copy # We need to test that it is enabled by default without # the environment variable enabling it for us. del env['PYTHONHASHSEED'] env['__cleanenv'] = '1' # consumed by assert_python_ok() else: env = {} for i in range(3): code = 'print(hash("spam"))' rc, out, err = assert_python_ok('-c', code, **env) self.assertEqual(rc, 0) hashes.append(out) hashes = sorted(set(hashes)) # uniq # Rare chance of failure due to 3 random seeds honestly being equal. self.assertGreater(len(hashes), 1, msg='3 runs produced an identical random hash ' ' for "spam": {}'.format(hashes)) # Verify that sys.flags contains hash_randomization code = 'import sys; print("random is", sys.flags.hash_randomization)' rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='') self.assertIn(b'random is 1', out) rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='random') self.assertIn(b'random is 1', out) rc, out, err = assert_python_ok('-c', code, PYTHONHASHSEED='0') self.assertIn(b'random is 0', out) rc, out, err = assert_python_ok('-R', '-c', code, PYTHONHASHSEED='0') self.assertIn(b'random is 1', out) def test_del___main__(self): # Issue #15001: PyRun_SimpleFileExFlags() did crash because it kept a # borrowed reference to the dict of __main__ module and later modify # the dict whereas the module was destroyed filename = support.TESTFN self.addCleanup(support.unlink, filename) with open(filename, "w") as script: print("import sys", file=script) print("del sys.modules['__main__']", file=script) assert_python_ok(filename) def test_unknown_options(self): rc, out, err = assert_python_failure('-E', '-z') self.assertIn(b'Unknown option: -z', err) self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1) self.assertEqual(b'', out) # Add "without='-E'" to prevent _assert_python to append -E # to env_vars and change the output of stderr rc, out, err = assert_python_failure('-z', without='-E') self.assertIn(b'Unknown option: -z', err) self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1) self.assertEqual(b'', out) rc, out, err = assert_python_failure('-a', '-z', without='-E') self.assertIn(b'Unknown option: -a', err) # only the first unknown option is reported self.assertNotIn(b'Unknown option: -z', err) self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1) self.assertEqual(b'', out) @unittest.skipIf(interpreter_requires_environment(), 'Cannot run -I tests when PYTHON env vars are required.') def test_isolatedmode(self): self.verify_valid_flag('-I') self.verify_valid_flag('-IEs') rc, out, err = assert_python_ok('-I', '-c', 'from sys import flags as f; ' 'print(f.no_user_site, f.ignore_environment, f.isolated)', # dummyvar to prevent extraneous -E dummyvar="") self.assertEqual(out.strip(), b'1 1 1') with support.temp_cwd() as tmpdir: fake = os.path.join(tmpdir, "uuid.py") main = os.path.join(tmpdir, "main.py") with open(fake, "w") as f: f.write("raise RuntimeError('isolated mode test')\n") with open(main, "w") as f: f.write("import uuid\n") f.write("print('ok')\n") self.assertRaises(subprocess.CalledProcessError, subprocess.check_output, [sys.executable, main], cwd=tmpdir, stderr=subprocess.DEVNULL) out = subprocess.check_output([sys.executable, "-I", main], cwd=tmpdir) self.assertEqual(out.strip(), b"ok") def test_sys_flags_set(self): # Issue 31845: a startup refactoring broke reading flags from env vars for value, expected in (("", 0), ("1", 1), ("text", 1), ("2", 2)): env_vars = dict( PYTHONDEBUG=value, PYTHONOPTIMIZE=value, PYTHONDONTWRITEBYTECODE=value, PYTHONVERBOSE=value, ) code = ( "import sys; " "sys.stderr.write(str(sys.flags)); " f"""sys.exit(not ( sys.flags.debug == sys.flags.optimize == sys.flags.dont_write_bytecode == sys.flags.verbose == {expected} ))""" ) with self.subTest(envar_value=value): assert_python_ok('-c', code, **env_vars) def run_xdev(self, *args, check_exitcode=True, xdev=True): env = dict(os.environ) env.pop('PYTHONWARNINGS', None) env.pop('PYTHONDEVMODE', None) env.pop('PYTHONMALLOC', None) if xdev: args = (sys.executable, '-X', 'dev', *args) else: args = (sys.executable, *args) proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, env=env) if check_exitcode: self.assertEqual(proc.returncode, 0, proc) return proc.stdout.rstrip() def test_xdev(self): # sys.flags.dev_mode code = "import sys; print(sys.flags.dev_mode)" out = self.run_xdev("-c", code, xdev=False) self.assertEqual(out, "False") out = self.run_xdev("-c", code) self.assertEqual(out, "True") # Warnings code = ("import warnings; " "print(' '.join('%s::%s' % (f[0], f[2].__name__) " "for f in warnings.filters))") if Py_DEBUG: expected_filters = "default::Warning" else: expected_filters = ("default::Warning " "default::DeprecationWarning " "ignore::DeprecationWarning " "ignore::PendingDeprecationWarning " "ignore::ImportWarning " "ignore::ResourceWarning") out = self.run_xdev("-c", code) self.assertEqual(out, expected_filters) out = self.run_xdev("-b", "-c", code) self.assertEqual(out, f"default::BytesWarning {expected_filters}") out = self.run_xdev("-bb", "-c", code) self.assertEqual(out, f"error::BytesWarning {expected_filters}") out = self.run_xdev("-Werror", "-c", code) self.assertEqual(out, f"error::Warning {expected_filters}") # Memory allocator debug hooks try: import _testcapi except ImportError: pass else: code = "import _testcapi; print(_testcapi.pymem_getallocatorsname())" with support.SuppressCrashReport(): out = self.run_xdev("-c", code, check_exitcode=False) if support.with_pymalloc(): alloc_name = "pymalloc_debug" else: alloc_name = "malloc_debug" self.assertEqual(out, alloc_name) # Faulthandler try: import faulthandler except ImportError: pass else: code = "import faulthandler; print(faulthandler.is_enabled())" out = self.run_xdev("-c", code) self.assertEqual(out, "True") def check_warnings_filters(self, cmdline_option, envvar, use_pywarning=False): if use_pywarning: code = ("import sys; from test.support import import_fresh_module; " "warnings = import_fresh_module('warnings', blocked=['_warnings']); ") else: code = "import sys, warnings; " code += ("print(' '.join('%s::%s' % (f[0], f[2].__name__) " "for f in warnings.filters))") args = (sys.executable, '-W', cmdline_option, '-bb', '-c', code) env = dict(os.environ) env.pop('PYTHONDEVMODE', None) env["PYTHONWARNINGS"] = envvar proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, env=env) self.assertEqual(proc.returncode, 0, proc) return proc.stdout.rstrip() def test_warnings_filter_precedence(self): expected_filters = ("error::BytesWarning " "once::UserWarning " "always::UserWarning") if not Py_DEBUG: expected_filters += (" " "default::DeprecationWarning " "ignore::DeprecationWarning " "ignore::PendingDeprecationWarning " "ignore::ImportWarning " "ignore::ResourceWarning") out = self.check_warnings_filters("once::UserWarning", "always::UserWarning") self.assertEqual(out, expected_filters) out = self.check_warnings_filters("once::UserWarning", "always::UserWarning", use_pywarning=True) self.assertEqual(out, expected_filters) def check_pythonmalloc(self, env_var, name): code = 'import _testcapi; print(_testcapi.pymem_getallocatorsname())' env = dict(os.environ) env.pop('PYTHONDEVMODE', None) if env_var is not None: env['PYTHONMALLOC'] = env_var else: env.pop('PYTHONMALLOC', None) args = (sys.executable, '-c', code) proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, env=env) self.assertEqual(proc.stdout.rstrip(), name) self.assertEqual(proc.returncode, 0) def test_pythonmalloc(self): # Test the PYTHONMALLOC environment variable pymalloc = support.with_pymalloc() if pymalloc: default_name = 'pymalloc_debug' if Py_DEBUG else 'pymalloc' default_name_debug = 'pymalloc_debug' else: default_name = 'malloc_debug' if Py_DEBUG else 'malloc' default_name_debug = 'malloc_debug' tests = [ (None, default_name), ('debug', default_name_debug), ('malloc', 'malloc'), ('malloc_debug', 'malloc_debug'), ] if pymalloc: tests.extend(( ('pymalloc', 'pymalloc'), ('pymalloc_debug', 'pymalloc_debug'), )) for env_var, name in tests: with self.subTest(env_var=env_var, name=name): self.check_pythonmalloc(env_var, name) def test_pythondevmode_env(self): # Test the PYTHONDEVMODE environment variable code = "import sys; print(sys.flags.dev_mode)" env = dict(os.environ) env.pop('PYTHONDEVMODE', None) args = (sys.executable, '-c', code) proc = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, env=env) self.assertEqual(proc.stdout.rstrip(), 'False') self.assertEqual(proc.returncode, 0, proc) env['PYTHONDEVMODE'] = '1' proc = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, env=env) self.assertEqual(proc.stdout.rstrip(), 'True') self.assertEqual(proc.returncode, 0, proc) @unittest.skipUnless(sys.platform == 'win32', 'bpo-32457 only applies on Windows') def test_argv0_normalization(self): args = sys.executable, '-c', 'print(0)' prefix, exe = os.path.split(sys.executable) executable = prefix + '\\.\\.\\.\\' + exe proc = subprocess.run(args, stdout=subprocess.PIPE, executable=executable) self.assertEqual(proc.returncode, 0, proc) self.assertEqual(proc.stdout.strip(), b'0') @unittest.skipIf(interpreter_requires_environment(), 'Cannot run -I tests when PYTHON env vars are required.') class IgnoreEnvironmentTest(unittest.TestCase): def run_ignoring_vars(self, predicate, **env_vars): # Runs a subprocess with -E set, even though we're passing # specific environment variables # Logical inversion to match predicate check to a zero return # code indicating success code = "import sys; sys.stderr.write(str(sys.flags)); sys.exit(not ({}))".format(predicate) return assert_python_ok('-E', '-c', code, **env_vars) def test_ignore_PYTHONPATH(self): path = "should_be_ignored" self.run_ignoring_vars("'{}' not in sys.path".format(path), PYTHONPATH=path) def test_ignore_PYTHONHASHSEED(self): self.run_ignoring_vars("sys.flags.hash_randomization == 1", PYTHONHASHSEED="0") def test_sys_flags_not_set(self): # Issue 31845: a startup refactoring broke reading flags from env vars expected_outcome = """ (sys.flags.debug == sys.flags.optimize == sys.flags.dont_write_bytecode == sys.flags.verbose == 0) """ self.run_ignoring_vars( expected_outcome, PYTHONDEBUG="1", PYTHONOPTIMIZE="1", PYTHONDONTWRITEBYTECODE="1", PYTHONVERBOSE="1", ) def test_main(): support.run_unittest(CmdLineTest, IgnoreEnvironmentTest) support.reap_children() if __name__ == "__main__": test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_coroutines.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_coroutines.py
import contextlib import copy import inspect import pickle import re import sys import types import unittest import warnings from test import support from test.support.script_helper import assert_python_ok class AsyncYieldFrom: def __init__(self, obj): self.obj = obj def __await__(self): yield from self.obj class AsyncYield: def __init__(self, value): self.value = value def __await__(self): yield self.value def run_async(coro): assert coro.__class__ in {types.GeneratorType, types.CoroutineType} buffer = [] result = None while True: try: buffer.append(coro.send(None)) except StopIteration as ex: result = ex.args[0] if ex.args else None break return buffer, result def run_async__await__(coro): assert coro.__class__ is types.CoroutineType aw = coro.__await__() buffer = [] result = None i = 0 while True: try: if i % 2: buffer.append(next(aw)) else: buffer.append(aw.send(None)) i += 1 except StopIteration as ex: result = ex.args[0] if ex.args else None break return buffer, result @contextlib.contextmanager def silence_coro_gc(): with warnings.catch_warnings(): warnings.simplefilter("ignore") yield support.gc_collect() class AsyncBadSyntaxTest(unittest.TestCase): def test_badsyntax_1(self): samples = [ """def foo(): await something() """, """await something()""", """async def foo(): yield from [] """, """async def foo(): await await fut """, """async def foo(a=await something()): pass """, """async def foo(a:await something()): pass """, """async def foo(): def bar(): [i async for i in els] """, """async def foo(): def bar(): [await i for i in els] """, """async def foo(): def bar(): [i for i in els async for b in els] """, """async def foo(): def bar(): [i for i in els for c in b async for b in els] """, """async def foo(): def bar(): [i for i in els async for b in els for c in b] """, """async def foo(): def bar(): [i for i in els for b in await els] """, """async def foo(): def bar(): [i for i in els for b in els if await b] """, """async def foo(): def bar(): [i for i in await els] """, """async def foo(): def bar(): [i for i in els if await i] """, """def bar(): [i async for i in els] """, """def bar(): {i: i async for i in els} """, """def bar(): {i async for i in els} """, """def bar(): [await i for i in els] """, """def bar(): [i for i in els async for b in els] """, """def bar(): [i for i in els for c in b async for b in els] """, """def bar(): [i for i in els async for b in els for c in b] """, """def bar(): [i for i in els for b in await els] """, """def bar(): [i for i in els for b in els if await b] """, """def bar(): [i for i in await els] """, """def bar(): [i for i in els if await i] """, """async def foo(): await """, """async def foo(): def bar(): pass await = 1 """, """async def foo(): def bar(): pass await = 1 """, """async def foo(): def bar(): pass if 1: await = 1 """, """def foo(): async def bar(): pass if 1: await a """, """def foo(): async def bar(): pass await a """, """def foo(): def baz(): pass async def bar(): pass await a """, """def foo(): def baz(): pass # 456 async def bar(): pass # 123 await a """, """async def foo(): def baz(): pass # 456 async def bar(): pass # 123 await = 2 """, """def foo(): def baz(): pass async def bar(): pass await a """, """async def foo(): def baz(): pass async def bar(): pass await = 2 """, """async def foo(): def async(): pass """, """async def foo(): def await(): pass """, """async def foo(): def bar(): await """, """async def foo(): return lambda async: await """, """async def foo(): return lambda a: await """, """await a()""", """async def foo(a=await b): pass """, """async def foo(a:await b): pass """, """def baz(): async def foo(a=await b): pass """, """async def foo(async): pass """, """async def foo(): def bar(): def baz(): async = 1 """, """async def foo(): def bar(): def baz(): pass async = 1 """, """def foo(): async def bar(): async def baz(): pass def baz(): 42 async = 1 """, """async def foo(): def bar(): def baz(): pass\nawait foo() """, """def foo(): def bar(): async def baz(): pass\nawait foo() """, """async def foo(await): pass """, """def foo(): async def bar(): pass await a """, """def foo(): async def bar(): pass\nawait a """, """def foo(): async for i in arange(2): pass """, """def foo(): async with resource: pass """, """async with resource: pass """, """async for i in arange(2): pass """, ] for code in samples: with self.subTest(code=code), self.assertRaises(SyntaxError): compile(code, "<test>", "exec") def test_badsyntax_2(self): samples = [ """def foo(): await = 1 """, """class Bar: def async(): pass """, """class Bar: async = 1 """, """class async: pass """, """class await: pass """, """import math as await""", """def async(): pass""", """def foo(*, await=1): pass""" """async = 1""", """print(await=1)""" ] for code in samples: with self.subTest(code=code), self.assertRaises(SyntaxError): compile(code, "<test>", "exec") def test_badsyntax_3(self): with self.assertRaises(SyntaxError): compile("async = 1", "<test>", "exec") def test_badsyntax_4(self): samples = [ '''def foo(await): async def foo(): pass async def foo(): pass return await + 1 ''', '''def foo(await): async def foo(): pass async def foo(): pass return await + 1 ''', '''def foo(await): async def foo(): pass async def foo(): pass return await + 1 ''', '''def foo(await): """spam""" async def foo(): \ pass # 123 async def foo(): pass # 456 return await + 1 ''', '''def foo(await): def foo(): pass def foo(): pass async def bar(): return await_ await_ = await try: bar().send(None) except StopIteration as ex: return ex.args[0] + 1 ''' ] for code in samples: with self.subTest(code=code), self.assertRaises(SyntaxError): compile(code, "<test>", "exec") class TokenizerRegrTest(unittest.TestCase): def test_oneline_defs(self): buf = [] for i in range(500): buf.append('def i{i}(): return {i}'.format(i=i)) buf = '\n'.join(buf) # Test that 500 consequent, one-line defs is OK ns = {} exec(buf, ns, ns) self.assertEqual(ns['i499'](), 499) # Test that 500 consequent, one-line defs *and* # one 'async def' following them is OK buf += '\nasync def foo():\n return' ns = {} exec(buf, ns, ns) self.assertEqual(ns['i499'](), 499) self.assertTrue(inspect.iscoroutinefunction(ns['foo'])) class CoroutineTest(unittest.TestCase): def test_gen_1(self): def gen(): yield self.assertFalse(hasattr(gen, '__await__')) def test_func_1(self): async def foo(): return 10 f = foo() self.assertIsInstance(f, types.CoroutineType) self.assertTrue(bool(foo.__code__.co_flags & inspect.CO_COROUTINE)) self.assertFalse(bool(foo.__code__.co_flags & inspect.CO_GENERATOR)) self.assertTrue(bool(f.cr_code.co_flags & inspect.CO_COROUTINE)) self.assertFalse(bool(f.cr_code.co_flags & inspect.CO_GENERATOR)) self.assertEqual(run_async(f), ([], 10)) self.assertEqual(run_async__await__(foo()), ([], 10)) def bar(): pass self.assertFalse(bool(bar.__code__.co_flags & inspect.CO_COROUTINE)) def test_func_2(self): async def foo(): raise StopIteration with self.assertRaisesRegex( RuntimeError, "coroutine raised StopIteration"): run_async(foo()) def test_func_3(self): async def foo(): raise StopIteration coro = foo() self.assertRegex(repr(coro), '^<coroutine object.* at 0x.*>$') coro.close() def test_func_4(self): async def foo(): raise StopIteration coro = foo() check = lambda: self.assertRaisesRegex( TypeError, "'coroutine' object is not iterable") with check(): list(coro) with check(): tuple(coro) with check(): sum(coro) with check(): iter(coro) with check(): for i in coro: pass with check(): [i for i in coro] coro.close() def test_func_5(self): @types.coroutine def bar(): yield 1 async def foo(): await bar() check = lambda: self.assertRaisesRegex( TypeError, "'coroutine' object is not iterable") coro = foo() with check(): for el in coro: pass coro.close() # the following should pass without an error for el in bar(): self.assertEqual(el, 1) self.assertEqual([el for el in bar()], [1]) self.assertEqual(tuple(bar()), (1,)) self.assertEqual(next(iter(bar())), 1) def test_func_6(self): @types.coroutine def bar(): yield 1 yield 2 async def foo(): await bar() f = foo() self.assertEqual(f.send(None), 1) self.assertEqual(f.send(None), 2) with self.assertRaises(StopIteration): f.send(None) def test_func_7(self): async def bar(): return 10 coro = bar() def foo(): yield from coro with self.assertRaisesRegex( TypeError, "cannot 'yield from' a coroutine object in " "a non-coroutine generator"): list(foo()) coro.close() def test_func_8(self): @types.coroutine def bar(): return (yield from coro) async def foo(): return 'spam' coro = foo() self.assertEqual(run_async(bar()), ([], 'spam')) coro.close() def test_func_9(self): async def foo(): pass with self.assertWarnsRegex( RuntimeWarning, r"coroutine '.*test_func_9.*foo' was never awaited"): foo() support.gc_collect() with self.assertWarnsRegex( RuntimeWarning, r"coroutine '.*test_func_9.*foo' was never awaited"): with self.assertRaises(TypeError): # See bpo-32703. for _ in foo(): pass support.gc_collect() def test_func_10(self): N = 0 @types.coroutine def gen(): nonlocal N try: a = yield yield (a ** 2) except ZeroDivisionError: N += 100 raise finally: N += 1 async def foo(): await gen() coro = foo() aw = coro.__await__() self.assertIs(aw, iter(aw)) next(aw) self.assertEqual(aw.send(10), 100) self.assertEqual(N, 0) aw.close() self.assertEqual(N, 1) coro = foo() aw = coro.__await__() next(aw) with self.assertRaises(ZeroDivisionError): aw.throw(ZeroDivisionError, None, None) self.assertEqual(N, 102) def test_func_11(self): async def func(): pass coro = func() # Test that PyCoro_Type and _PyCoroWrapper_Type types were properly # initialized self.assertIn('__await__', dir(coro)) self.assertIn('__iter__', dir(coro.__await__())) self.assertIn('coroutine_wrapper', repr(coro.__await__())) coro.close() # avoid RuntimeWarning def test_func_12(self): async def g(): i = me.send(None) await foo me = g() with self.assertRaisesRegex(ValueError, "coroutine already executing"): me.send(None) def test_func_13(self): async def g(): pass coro = g() with self.assertRaisesRegex( TypeError, "can't send non-None value to a just-started coroutine"): coro.send('spam') coro.close() def test_func_14(self): @types.coroutine def gen(): yield async def coro(): try: await gen() except GeneratorExit: await gen() c = coro() c.send(None) with self.assertRaisesRegex(RuntimeError, "coroutine ignored GeneratorExit"): c.close() def test_func_15(self): # See http://bugs.python.org/issue25887 for details async def spammer(): return 'spam' async def reader(coro): return await coro spammer_coro = spammer() with self.assertRaisesRegex(StopIteration, 'spam'): reader(spammer_coro).send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): reader(spammer_coro).send(None) def test_func_16(self): # See http://bugs.python.org/issue25887 for details @types.coroutine def nop(): yield async def send(): await nop() return 'spam' async def read(coro): await nop() return await coro spammer = send() reader = read(spammer) reader.send(None) reader.send(None) with self.assertRaisesRegex(Exception, 'ham'): reader.throw(Exception('ham')) reader = read(spammer) reader.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): reader.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): reader.throw(Exception('wat')) def test_func_17(self): # See http://bugs.python.org/issue25887 for details async def coroutine(): return 'spam' coro = coroutine() with self.assertRaisesRegex(StopIteration, 'spam'): coro.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): coro.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): coro.throw(Exception('wat')) # Closing a coroutine shouldn't raise any exception even if it's # already closed/exhausted (similar to generators) coro.close() coro.close() def test_func_18(self): # See http://bugs.python.org/issue25887 for details async def coroutine(): return 'spam' coro = coroutine() await_iter = coro.__await__() it = iter(await_iter) with self.assertRaisesRegex(StopIteration, 'spam'): it.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): it.send(None) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): # Although the iterator protocol requires iterators to # raise another StopIteration here, we don't want to do # that. In this particular case, the iterator will raise # a RuntimeError, so that 'yield from' and 'await' # expressions will trigger the error, instead of silently # ignoring the call. next(it) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): it.throw(Exception('wat')) with self.assertRaisesRegex(RuntimeError, 'cannot reuse already awaited coroutine'): it.throw(Exception('wat')) # Closing a coroutine shouldn't raise any exception even if it's # already closed/exhausted (similar to generators) it.close() it.close() def test_func_19(self): CHK = 0 @types.coroutine def foo(): nonlocal CHK yield try: yield except GeneratorExit: CHK += 1 async def coroutine(): await foo() coro = coroutine() coro.send(None) coro.send(None) self.assertEqual(CHK, 0) coro.close() self.assertEqual(CHK, 1) for _ in range(3): # Closing a coroutine shouldn't raise any exception even if it's # already closed/exhausted (similar to generators) coro.close() self.assertEqual(CHK, 1) def test_coro_wrapper_send_tuple(self): async def foo(): return (10,) result = run_async__await__(foo()) self.assertEqual(result, ([], (10,))) def test_coro_wrapper_send_stop_iterator(self): async def foo(): return StopIteration(10) result = run_async__await__(foo()) self.assertIsInstance(result[1], StopIteration) self.assertEqual(result[1].value, 10) def test_cr_await(self): @types.coroutine def a(): self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING) self.assertIsNone(coro_b.cr_await) yield self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING) self.assertIsNone(coro_b.cr_await) async def c(): await a() async def b(): self.assertIsNone(coro_b.cr_await) await c() self.assertIsNone(coro_b.cr_await) coro_b = b() self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CREATED) self.assertIsNone(coro_b.cr_await) coro_b.send(None) self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_SUSPENDED) self.assertEqual(coro_b.cr_await.cr_await.gi_code.co_name, 'a') with self.assertRaises(StopIteration): coro_b.send(None) # complete coroutine self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CLOSED) self.assertIsNone(coro_b.cr_await) def test_corotype_1(self): ct = types.CoroutineType self.assertIn('into coroutine', ct.send.__doc__) self.assertIn('inside coroutine', ct.close.__doc__) self.assertIn('in coroutine', ct.throw.__doc__) self.assertIn('of the coroutine', ct.__dict__['__name__'].__doc__) self.assertIn('of the coroutine', ct.__dict__['__qualname__'].__doc__) self.assertEqual(ct.__name__, 'coroutine') async def f(): pass c = f() self.assertIn('coroutine object', repr(c)) c.close() def test_await_1(self): async def foo(): await 1 with self.assertRaisesRegex(TypeError, "object int can.t.*await"): run_async(foo()) def test_await_2(self): async def foo(): await [] with self.assertRaisesRegex(TypeError, "object list can.t.*await"): run_async(foo()) def test_await_3(self): async def foo(): await AsyncYieldFrom([1, 2, 3]) self.assertEqual(run_async(foo()), ([1, 2, 3], None)) self.assertEqual(run_async__await__(foo()), ([1, 2, 3], None)) def test_await_4(self): async def bar(): return 42 async def foo(): return await bar() self.assertEqual(run_async(foo()), ([], 42)) def test_await_5(self): class Awaitable: def __await__(self): return async def foo(): return (await Awaitable()) with self.assertRaisesRegex( TypeError, "__await__.*returned non-iterator of type"): run_async(foo()) def test_await_6(self): class Awaitable: def __await__(self): return iter([52]) async def foo(): return (await Awaitable()) self.assertEqual(run_async(foo()), ([52], None)) def test_await_7(self): class Awaitable: def __await__(self): yield 42 return 100 async def foo(): return (await Awaitable()) self.assertEqual(run_async(foo()), ([42], 100)) def test_await_8(self): class Awaitable: pass async def foo(): return await Awaitable() with self.assertRaisesRegex( TypeError, "object Awaitable can't be used in 'await' expression"): run_async(foo()) def test_await_9(self): def wrap(): return bar async def bar(): return 42 async def foo(): db = {'b': lambda: wrap} class DB: b = wrap return (await bar() + await wrap()() + await db['b']()()() + await bar() * 1000 + await DB.b()()) async def foo2(): return -await bar() self.assertEqual(run_async(foo()), ([], 42168)) self.assertEqual(run_async(foo2()), ([], -42)) def test_await_10(self): async def baz(): return 42 async def bar(): return baz() async def foo(): return await (await bar()) self.assertEqual(run_async(foo()), ([], 42)) def test_await_11(self): def ident(val): return val async def bar(): return 'spam' async def foo(): return ident(val=await bar()) async def foo2(): return await bar(), 'ham' self.assertEqual(run_async(foo2()), ([], ('spam', 'ham'))) def test_await_12(self): async def coro(): return 'spam' c = coro() class Awaitable: def __await__(self): return c async def foo(): return await Awaitable() with self.assertRaisesRegex( TypeError, r"__await__\(\) returned a coroutine"): run_async(foo()) c.close() def test_await_13(self): class Awaitable: def __await__(self): return self async def foo(): return await Awaitable() with self.assertRaisesRegex( TypeError, "__await__.*returned non-iterator of type"): run_async(foo()) def test_await_14(self): class Wrapper: # Forces the interpreter to use CoroutineType.__await__ def __init__(self, coro): assert coro.__class__ is types.CoroutineType self.coro = coro def __await__(self): return self.coro.__await__() class FutureLike: def __await__(self): return (yield) class Marker(Exception): pass async def coro1(): try: return await FutureLike() except ZeroDivisionError: raise Marker async def coro2(): return await Wrapper(coro1()) c = coro2() c.send(None) with self.assertRaisesRegex(StopIteration, 'spam'): c.send('spam') c = coro2() c.send(None) with self.assertRaises(Marker): c.throw(ZeroDivisionError) def test_await_15(self): @types.coroutine def nop(): yield async def coroutine(): await nop() async def waiter(coro): await coro coro = coroutine() coro.send(None) with self.assertRaisesRegex(RuntimeError, "coroutine is being awaited already"): waiter(coro).send(None) def test_await_16(self): # See https://bugs.python.org/issue29600 for details. async def f(): return ValueError() async def g(): try: raise KeyError except: return await f() _, result = run_async(g()) self.assertIsNone(result.__context__) def test_with_1(self): class Manager: def __init__(self, name): self.name = name async def __aenter__(self): await AsyncYieldFrom(['enter-1-' + self.name, 'enter-2-' + self.name]) return self async def __aexit__(self, *args): await AsyncYieldFrom(['exit-1-' + self.name, 'exit-2-' + self.name]) if self.name == 'B': return True async def foo(): async with Manager("A") as a, Manager("B") as b: await AsyncYieldFrom([('managers', a.name, b.name)]) 1/0 f = foo() result, _ = run_async(f) self.assertEqual( result, ['enter-1-A', 'enter-2-A', 'enter-1-B', 'enter-2-B', ('managers', 'A', 'B'), 'exit-1-B', 'exit-2-B', 'exit-1-A', 'exit-2-A'] ) async def foo(): async with Manager("A") as a, Manager("C") as c: await AsyncYieldFrom([('managers', a.name, c.name)]) 1/0 with self.assertRaises(ZeroDivisionError): run_async(foo()) def test_with_2(self): class CM: def __aenter__(self): pass async def foo(): async with CM(): pass with self.assertRaisesRegex(AttributeError, '__aexit__'): run_async(foo()) def test_with_3(self): class CM: def __aexit__(self): pass async def foo(): async with CM(): pass with self.assertRaisesRegex(AttributeError, '__aenter__'): run_async(foo()) def test_with_4(self): class CM: def __enter__(self): pass def __exit__(self): pass async def foo(): async with CM(): pass with self.assertRaisesRegex(AttributeError, '__aexit__'): run_async(foo()) def test_with_5(self): # While this test doesn't make a lot of sense, # it's a regression test for an early bug with opcodes # generation class CM: async def __aenter__(self): return self async def __aexit__(self, *exc): pass async def func(): async with CM(): assert (1, ) == 1 with self.assertRaises(AssertionError): run_async(func()) def test_with_6(self): class CM: def __aenter__(self): return 123 def __aexit__(self, *e): return 456 async def foo(): async with CM(): pass with self.assertRaisesRegex( TypeError, "'async with' received an object from __aenter__ " "that does not implement __await__: int"): # it's important that __aexit__ wasn't called run_async(foo()) def test_with_7(self): class CM: async def __aenter__(self):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_cn.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_cn.py
# # test_codecmaps_cn.py # Codec mapping tests for PRC encodings # from test import multibytecodec_support import unittest class TestGB2312Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb2312' mapfileurl = 'http://www.pythontest.net/unicode/EUC-CN.TXT' class TestGBKMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gbk' mapfileurl = 'http://www.pythontest.net/unicode/CP936.TXT' class TestGB18030Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb18030' mapfileurl = 'http://www.pythontest.net/unicode/gb-18030-2000.xml' if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sched.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sched.py
import queue import sched import threading import time import unittest from test import support TIMEOUT = 10 class Timer: def __init__(self): self._cond = threading.Condition() self._time = 0 self._stop = 0 def time(self): with self._cond: return self._time # increase the time but not beyond the established limit def sleep(self, t): assert t >= 0 with self._cond: t += self._time while self._stop < t: self._time = self._stop self._cond.wait() self._time = t # advance time limit for user code def advance(self, t): assert t >= 0 with self._cond: self._stop += t self._cond.notify_all() class TestCase(unittest.TestCase): def test_enter(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) for x in [0.5, 0.4, 0.3, 0.2, 0.1]: z = scheduler.enter(x, 1, fun, (x,)) scheduler.run() self.assertEqual(l, [0.1, 0.2, 0.3, 0.4, 0.5]) def test_enterabs(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) for x in [0.05, 0.04, 0.03, 0.02, 0.01]: z = scheduler.enterabs(x, 1, fun, (x,)) scheduler.run() self.assertEqual(l, [0.01, 0.02, 0.03, 0.04, 0.05]) def test_enter_concurrent(self): q = queue.Queue() fun = q.put timer = Timer() scheduler = sched.scheduler(timer.time, timer.sleep) scheduler.enter(1, 1, fun, (1,)) scheduler.enter(3, 1, fun, (3,)) t = threading.Thread(target=scheduler.run) t.start() timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 1) self.assertTrue(q.empty()) for x in [4, 5, 2]: z = scheduler.enter(x - 1, 1, fun, (x,)) timer.advance(2) self.assertEqual(q.get(timeout=TIMEOUT), 2) self.assertEqual(q.get(timeout=TIMEOUT), 3) self.assertTrue(q.empty()) timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 4) self.assertTrue(q.empty()) timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 5) self.assertTrue(q.empty()) timer.advance(1000) support.join_thread(t, timeout=TIMEOUT) self.assertTrue(q.empty()) self.assertEqual(timer.time(), 5) def test_priority(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) for priority in [1, 2, 3, 4, 5]: z = scheduler.enterabs(0.01, priority, fun, (priority,)) scheduler.run() self.assertEqual(l, [1, 2, 3, 4, 5]) def test_cancel(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) now = time.time() event1 = scheduler.enterabs(now + 0.01, 1, fun, (0.01,)) event2 = scheduler.enterabs(now + 0.02, 1, fun, (0.02,)) event3 = scheduler.enterabs(now + 0.03, 1, fun, (0.03,)) event4 = scheduler.enterabs(now + 0.04, 1, fun, (0.04,)) event5 = scheduler.enterabs(now + 0.05, 1, fun, (0.05,)) scheduler.cancel(event1) scheduler.cancel(event5) scheduler.run() self.assertEqual(l, [0.02, 0.03, 0.04]) def test_cancel_concurrent(self): q = queue.Queue() fun = q.put timer = Timer() scheduler = sched.scheduler(timer.time, timer.sleep) now = timer.time() event1 = scheduler.enterabs(now + 1, 1, fun, (1,)) event2 = scheduler.enterabs(now + 2, 1, fun, (2,)) event4 = scheduler.enterabs(now + 4, 1, fun, (4,)) event5 = scheduler.enterabs(now + 5, 1, fun, (5,)) event3 = scheduler.enterabs(now + 3, 1, fun, (3,)) t = threading.Thread(target=scheduler.run) t.start() timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 1) self.assertTrue(q.empty()) scheduler.cancel(event2) scheduler.cancel(event5) timer.advance(1) self.assertTrue(q.empty()) timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 3) self.assertTrue(q.empty()) timer.advance(1) self.assertEqual(q.get(timeout=TIMEOUT), 4) self.assertTrue(q.empty()) timer.advance(1000) support.join_thread(t, timeout=TIMEOUT) self.assertTrue(q.empty()) self.assertEqual(timer.time(), 4) def test_empty(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) self.assertTrue(scheduler.empty()) for x in [0.05, 0.04, 0.03, 0.02, 0.01]: z = scheduler.enterabs(x, 1, fun, (x,)) self.assertFalse(scheduler.empty()) scheduler.run() self.assertTrue(scheduler.empty()) def test_queue(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) now = time.time() e5 = scheduler.enterabs(now + 0.05, 1, fun) e1 = scheduler.enterabs(now + 0.01, 1, fun) e2 = scheduler.enterabs(now + 0.02, 1, fun) e4 = scheduler.enterabs(now + 0.04, 1, fun) e3 = scheduler.enterabs(now + 0.03, 1, fun) # queue property is supposed to return an order list of # upcoming events self.assertEqual(scheduler.queue, [e1, e2, e3, e4, e5]) def test_args_kwargs(self): seq = [] def fun(*a, **b): seq.append((a, b)) now = time.time() scheduler = sched.scheduler(time.time, time.sleep) scheduler.enterabs(now, 1, fun) scheduler.enterabs(now, 1, fun, argument=(1, 2)) scheduler.enterabs(now, 1, fun, argument=('a', 'b')) scheduler.enterabs(now, 1, fun, argument=(1, 2), kwargs={"foo": 3}) scheduler.run() self.assertCountEqual(seq, [ ((), {}), ((1, 2), {}), (('a', 'b'), {}), ((1, 2), {'foo': 3}) ]) def test_run_non_blocking(self): l = [] fun = lambda x: l.append(x) scheduler = sched.scheduler(time.time, time.sleep) for x in [10, 9, 8, 7, 6]: scheduler.enter(x, 1, fun, (x,)) scheduler.run(blocking=False) self.assertEqual(l, []) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sundry.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sundry.py
"""Do a minimal test of all the modules that aren't otherwise tested.""" import importlib import sys from test import support import unittest class TestUntestedModules(unittest.TestCase): def test_untested_modules_can_be_imported(self): untested = ('encodings', 'formatter', 'tabnanny') with support.check_warnings(quiet=True): for name in untested: try: support.import_module('test.test_{}'.format(name)) except unittest.SkipTest: importlib.import_module(name) else: self.fail('{} has tests even though test_sundry claims ' 'otherwise'.format(name)) import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.filelist import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import html.entities try: import tty # Not available on Windows except ImportError: if support.verbose: print("skipping tty") if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/inspect_fodder.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/inspect_fodder.py
# line 1 'A module docstring.' import sys, inspect # line 5 # line 7 def spam(a, b, c, d=3, e=4, f=5, *g, **h): eggs(b + d, c + f) # line 11 def eggs(x, y): "A docstring." global fr, st fr = inspect.currentframe() st = inspect.stack() p = x q = y / 0 # line 20 class StupidGit: """A longer, indented docstring.""" # line 27 def abuse(self, a, b, c): """Another \tdocstring containing \ttabs \t """ self.argue(a, b, c) # line 40 def argue(self, a, b, c): try: spam(a, b, c) except: self.ex = sys.exc_info() self.tr = inspect.trace() @property def contradiction(self): 'The automatic gainsaying.' pass # line 53 class MalodorousPervert(StupidGit): def abuse(self, a, b, c): pass @property def contradiction(self): pass Tit = MalodorousPervert class ParrotDroppings: pass class FesteringGob(MalodorousPervert, ParrotDroppings): def abuse(self, a, b, c): pass @property def contradiction(self): pass async def lobbest(grenade): pass currentframe = inspect.currentframe() try: raise Exception() except: tb = sys.exc_info()[2]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
"""This module includes tests of the code object representation. >>> def f(x): ... def g(y): ... return x + y ... return g ... >>> dump(f.__code__) name: f argcount: 1 kwonlyargcount: 0 names: () varnames: ('x', 'g') cellvars: ('x',) freevars: () nlocals: 2 flags: 3 consts: ('None', '<code object g>', "'f.<locals>.g'") >>> dump(f(4).__code__) name: g argcount: 1 kwonlyargcount: 0 names: () varnames: ('y',) cellvars: () freevars: ('x',) nlocals: 1 flags: 19 consts: ('None',) >>> def h(x, y): ... a = x + y ... b = x - y ... c = a * b ... return c ... >>> dump(h.__code__) name: h argcount: 2 kwonlyargcount: 0 names: () varnames: ('x', 'y', 'a', 'b', 'c') cellvars: () freevars: () nlocals: 5 flags: 67 consts: ('None',) >>> def attrs(obj): ... print(obj.attr1) ... print(obj.attr2) ... print(obj.attr3) >>> dump(attrs.__code__) name: attrs argcount: 1 kwonlyargcount: 0 names: ('print', 'attr1', 'attr2', 'attr3') varnames: ('obj',) cellvars: () freevars: () nlocals: 1 flags: 67 consts: ('None',) >>> def optimize_away(): ... 'doc string' ... 'not a docstring' ... 53 ... 0x53 >>> dump(optimize_away.__code__) name: optimize_away argcount: 0 kwonlyargcount: 0 names: () varnames: () cellvars: () freevars: () nlocals: 0 flags: 67 consts: ("'doc string'", 'None') >>> def keywordonly_args(a,b,*,k1): ... return a,b,k1 ... >>> dump(keywordonly_args.__code__) name: keywordonly_args argcount: 2 kwonlyargcount: 1 names: () varnames: ('a', 'b', 'k1') cellvars: () freevars: () nlocals: 3 flags: 67 consts: ('None',) """ import inspect import sys import threading import unittest import weakref try: import ctypes except ImportError: ctypes = None from test.support import (run_doctest, run_unittest, cpython_only, check_impl_detail) def consts(t): """Yield a doctest-safe sequence of object reprs.""" for elt in t: r = repr(elt) if r.startswith("<code object"): yield "<code object %s>" % elt.co_name else: yield r 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("consts:", tuple(consts(co.co_consts))) # Needed for test_closure_injection below # Defined at global scope to avoid implicitly closing over __class__ def external_getitem(self, i): return f"Foreign getitem: {super().__getitem__(i)}" class CodeTest(unittest.TestCase): @cpython_only def test_newempty(self): import _testcapi co = _testcapi.code_newempty("filename", "funcname", 15) self.assertEqual(co.co_filename, "filename") self.assertEqual(co.co_name, "funcname") self.assertEqual(co.co_firstlineno, 15) @cpython_only def test_closure_injection(self): # From https://bugs.python.org/issue32176 from types import FunctionType, CodeType def create_closure(__class__): return (lambda: __class__).__closure__ def new_code(c): '''A new code object with a __class__ cell added to freevars''' return CodeType( c.co_argcount, c.co_kwonlyargcount, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names, c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab, c.co_freevars + ('__class__',), c.co_cellvars) def add_foreign_method(cls, name, f): code = new_code(f.__code__) assert not f.__closure__ closure = create_closure(cls) defaults = f.__defaults__ setattr(cls, name, FunctionType(code, globals(), name, defaults, closure)) class List(list): pass add_foreign_method(List, "__getitem__", external_getitem) # Ensure the closure injection actually worked function = List.__getitem__ class_ref = function.__closure__[0].cell_contents self.assertIs(class_ref, List) # Ensure the code correctly indicates it accesses a free variable self.assertFalse(function.__code__.co_flags & inspect.CO_NOFREE, hex(function.__code__.co_flags)) # Ensure the zero-arg super() call in the injected method works obj = List([1, 2, 3]) self.assertEqual(obj[0], "Foreign getitem: 1") def isinterned(s): return s is sys.intern(('_' + s + '_')[1:-1]) class CodeConstsTest(unittest.TestCase): def find_const(self, consts, value): for v in consts: if v == value: return v self.assertIn(value, consts) # raises an exception self.fail('Should never be reached') def assertIsInterned(self, s): if not isinterned(s): self.fail('String %r is not interned' % (s,)) def assertIsNotInterned(self, s): if isinterned(s): self.fail('String %r is interned' % (s,)) @cpython_only def test_interned_string(self): co = compile('res = "str_value"', '?', 'exec') v = self.find_const(co.co_consts, 'str_value') self.assertIsInterned(v) @cpython_only def test_interned_string_in_tuple(self): co = compile('res = ("str_value",)', '?', 'exec') v = self.find_const(co.co_consts, ('str_value',)) self.assertIsInterned(v[0]) @cpython_only def test_interned_string_in_frozenset(self): co = compile('res = a in {"str_value"}', '?', 'exec') v = self.find_const(co.co_consts, frozenset(('str_value',))) self.assertIsInterned(tuple(v)[0]) @cpython_only def test_interned_string_default(self): def f(a='str_value'): return a self.assertIsInterned(f()) @cpython_only def test_interned_string_with_null(self): co = compile(r'res = "str\0value!"', '?', 'exec') v = self.find_const(co.co_consts, 'str\0value!') self.assertIsNotInterned(v) class CodeWeakRefTest(unittest.TestCase): def test_basic(self): # Create a code object in a clean environment so that we know we have # the only reference to it left. namespace = {} exec("def f(): pass", globals(), namespace) f = namespace["f"] del namespace self.called = False def callback(code): self.called = True # f is now the last reference to the function, and through it, the code # object. While we hold it, check that we can create a weakref and # deref it. Then delete it, and check that the callback gets called and # the reference dies. coderef = weakref.ref(f.__code__, callback) self.assertTrue(bool(coderef())) del f self.assertFalse(bool(coderef())) self.assertTrue(self.called) if check_impl_detail(cpython=True) and ctypes is not None: py = ctypes.pythonapi freefunc = ctypes.CFUNCTYPE(None,ctypes.c_voidp) RequestCodeExtraIndex = py._PyEval_RequestCodeExtraIndex RequestCodeExtraIndex.argtypes = (freefunc,) RequestCodeExtraIndex.restype = ctypes.c_ssize_t SetExtra = py._PyCode_SetExtra SetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.c_voidp) SetExtra.restype = ctypes.c_int GetExtra = py._PyCode_GetExtra GetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_voidp)) GetExtra.restype = ctypes.c_int LAST_FREED = None def myfree(ptr): global LAST_FREED LAST_FREED = ptr FREE_FUNC = freefunc(myfree) FREE_INDEX = RequestCodeExtraIndex(FREE_FUNC) class CoExtra(unittest.TestCase): def get_func(self): # Defining a function causes the containing function to have a # reference to the code object. We need the code objects to go # away, so we eval a lambda. return eval('lambda:42') def test_get_non_code(self): f = self.get_func() self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX, ctypes.c_voidp(100)) self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX, ctypes.c_voidp(100)) def test_bad_index(self): f = self.get_func() self.assertRaises(SystemError, SetExtra, f.__code__, FREE_INDEX+100, ctypes.c_voidp(100)) self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100, ctypes.c_voidp(100)), 0) def test_free_called(self): # Verify that the provided free function gets invoked # when the code object is cleaned up. f = self.get_func() SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100)) del f self.assertEqual(LAST_FREED, 100) def test_get_set(self): # Test basic get/set round tripping. f = self.get_func() extra = ctypes.c_voidp() SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200)) # reset should free... SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300)) self.assertEqual(LAST_FREED, 200) extra = ctypes.c_voidp() GetExtra(f.__code__, FREE_INDEX, extra) self.assertEqual(extra.value, 300) del f def test_free_different_thread(self): # Freeing a code object on a different thread then # where the co_extra was set should be safe. f = self.get_func() class ThreadTest(threading.Thread): def __init__(self, f, test): super().__init__() self.f = f self.test = test def run(self): del self.f self.test.assertEqual(LAST_FREED, 500) SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500)) tt = ThreadTest(f, self) del f tt.start() tt.join() self.assertEqual(LAST_FREED, 500) def test_main(verbose=None): from test import test_code run_doctest(test_code, verbose) tests = [CodeTest, CodeConstsTest, CodeWeakRefTest] if check_impl_detail(cpython=True) and ctypes is not None: tests.append(CoExtra) run_unittest(*tests) if __name__ == "__main__": test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_linecache.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_linecache.py
""" Tests for the linecache module """ import linecache import unittest import os.path import tempfile import tokenize from test import support FILENAME = linecache.__file__ NONEXISTENT_FILENAME = FILENAME + '.missing' INVALID_NAME = '!@$)(!@#_1' EMPTY = '' TEST_PATH = os.path.dirname(__file__) MODULES = "linecache abc".split() MODULE_PATH = os.path.dirname(FILENAME) SOURCE_1 = ''' " Docstring " def function(): return result ''' SOURCE_2 = ''' def f(): return 1 + 1 a = f() ''' SOURCE_3 = ''' def f(): return 3''' # No ending newline class TempFile: def setUp(self): super().setUp() with tempfile.NamedTemporaryFile(delete=False) as fp: self.file_name = fp.name fp.write(self.file_byte_string) self.addCleanup(support.unlink, self.file_name) class GetLineTestsGoodData(TempFile): # file_list = ['list\n', 'of\n', 'good\n', 'strings\n'] def setUp(self): self.file_byte_string = ''.join(self.file_list).encode('utf-8') super().setUp() def test_getline(self): with tokenize.open(self.file_name) as fp: for index, line in enumerate(fp): if not line.endswith('\n'): line += '\n' cached_line = linecache.getline(self.file_name, index + 1) self.assertEqual(line, cached_line) def test_getlines(self): lines = linecache.getlines(self.file_name) self.assertEqual(lines, self.file_list) class GetLineTestsBadData(TempFile): # file_byte_string = b'Bad data goes here' def test_getline(self): self.assertRaises((SyntaxError, UnicodeDecodeError), linecache.getline, self.file_name, 1) def test_getlines(self): self.assertRaises((SyntaxError, UnicodeDecodeError), linecache.getlines, self.file_name) class EmptyFile(GetLineTestsGoodData, unittest.TestCase): file_list = [] class SingleEmptyLine(GetLineTestsGoodData, unittest.TestCase): file_list = ['\n'] class GoodUnicode(GetLineTestsGoodData, unittest.TestCase): file_list = ['á\n', 'b\n', 'abcdef\n', 'ááááá\n'] class BadUnicode(GetLineTestsBadData, unittest.TestCase): file_byte_string = b'\x80abc' class LineCacheTests(unittest.TestCase): def test_getline(self): getline = linecache.getline # Bad values for line number should return an empty string self.assertEqual(getline(FILENAME, 2**15), EMPTY) self.assertEqual(getline(FILENAME, -1), EMPTY) # Float values currently raise TypeError, should it? self.assertRaises(TypeError, getline, FILENAME, 1.1) # Bad filenames should return an empty string self.assertEqual(getline(EMPTY, 1), EMPTY) self.assertEqual(getline(INVALID_NAME, 1), EMPTY) # Check module loading for entry in MODULES: filename = os.path.join(MODULE_PATH, entry) + '.py' with open(filename) as file: for index, line in enumerate(file): self.assertEqual(line, getline(filename, index + 1)) # Check that bogus data isn't returned (issue #1309567) empty = linecache.getlines('a/b/c/__init__.py') self.assertEqual(empty, []) def test_no_ending_newline(self): self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, "w") as fp: fp.write(SOURCE_3) lines = linecache.getlines(support.TESTFN) self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) def test_clearcache(self): cached = [] for entry in MODULES: filename = os.path.join(MODULE_PATH, entry) + '.py' cached.append(filename) linecache.getline(filename, 1) # Are all files cached? self.assertNotEqual(cached, []) cached_empty = [fn for fn in cached if fn not in linecache.cache] self.assertEqual(cached_empty, []) # Can we clear the cache? linecache.clearcache() cached_empty = [fn for fn in cached if fn in linecache.cache] self.assertEqual(cached_empty, []) def test_checkcache(self): getline = linecache.getline # Create a source file and cache its contents source_name = support.TESTFN + '.py' self.addCleanup(support.unlink, source_name) with open(source_name, 'w') as source: source.write(SOURCE_1) getline(source_name, 1) # Keep a copy of the old contents source_list = [] with open(source_name) as source: for index, line in enumerate(source): self.assertEqual(line, getline(source_name, index + 1)) source_list.append(line) with open(source_name, 'w') as source: source.write(SOURCE_2) # Try to update a bogus cache entry linecache.checkcache('dummy') # Check that the cache matches the old contents for index, line in enumerate(source_list): self.assertEqual(line, getline(source_name, index + 1)) # Update the cache and check whether it matches the new source file linecache.checkcache(source_name) with open(source_name) as source: for index, line in enumerate(source): self.assertEqual(line, getline(source_name, index + 1)) source_list.append(line) def test_lazycache_no_globals(self): lines = linecache.getlines(FILENAME) linecache.clearcache() self.assertEqual(False, linecache.lazycache(FILENAME, None)) self.assertEqual(lines, linecache.getlines(FILENAME)) def test_lazycache_smoke(self): lines = linecache.getlines(NONEXISTENT_FILENAME, globals()) linecache.clearcache() self.assertEqual( True, linecache.lazycache(NONEXISTENT_FILENAME, globals())) self.assertEqual(1, len(linecache.cache[NONEXISTENT_FILENAME])) # Note here that we're looking up a nonexistent filename with no # globals: this would error if the lazy value wasn't resolved. self.assertEqual(lines, linecache.getlines(NONEXISTENT_FILENAME)) def test_lazycache_provide_after_failed_lookup(self): linecache.clearcache() lines = linecache.getlines(NONEXISTENT_FILENAME, globals()) linecache.clearcache() linecache.getlines(NONEXISTENT_FILENAME) linecache.lazycache(NONEXISTENT_FILENAME, globals()) self.assertEqual(lines, linecache.updatecache(NONEXISTENT_FILENAME)) def test_lazycache_check(self): linecache.clearcache() linecache.lazycache(NONEXISTENT_FILENAME, globals()) linecache.checkcache() def test_lazycache_bad_filename(self): linecache.clearcache() self.assertEqual(False, linecache.lazycache('', globals())) self.assertEqual(False, linecache.lazycache('<foo>', globals())) def test_lazycache_already_cached(self): linecache.clearcache() lines = linecache.getlines(NONEXISTENT_FILENAME, globals()) self.assertEqual( False, linecache.lazycache(NONEXISTENT_FILENAME, globals())) self.assertEqual(4, len(linecache.cache[NONEXISTENT_FILENAME])) def test_memoryerror(self): lines = linecache.getlines(FILENAME) self.assertTrue(lines) def raise_memoryerror(*args, **kwargs): raise MemoryError with support.swap_attr(linecache, 'updatecache', raise_memoryerror): lines2 = linecache.getlines(FILENAME) self.assertEqual(lines2, lines) linecache.clearcache() with support.swap_attr(linecache, 'updatecache', raise_memoryerror): lines3 = linecache.getlines(FILENAME) self.assertEqual(lines3, []) self.assertEqual(linecache.getlines(FILENAME), lines) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_binascii.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_binascii.py
"""Test the binascii C module.""" import unittest import binascii import array import re # Note: "*_hex" functions are aliases for "(un)hexlify" b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu', 'hexlify', 'rlecode_hqx'] a2b_functions = ['a2b_base64', 'a2b_hex', 'a2b_hqx', 'a2b_qp', 'a2b_uu', 'unhexlify', 'rledecode_hqx'] all_functions = a2b_functions + b2a_functions + ['crc32', 'crc_hqx'] class BinASCIITest(unittest.TestCase): type2test = bytes # Create binary test data rawdata = b"The quick brown fox jumps over the lazy dog.\r\n" # Be slow so we don't depend on other modules rawdata += bytes(range(256)) rawdata += b"\r\nHello world.\n" def setUp(self): self.data = self.type2test(self.rawdata) def test_exceptions(self): # Check module exceptions self.assertTrue(issubclass(binascii.Error, Exception)) self.assertTrue(issubclass(binascii.Incomplete, Exception)) def test_functions(self): # Check presence of all functions for name in all_functions: self.assertTrue(hasattr(getattr(binascii, name), '__call__')) self.assertRaises(TypeError, getattr(binascii, name)) def test_returned_value(self): # Limit to the minimum of all limits (b2a_uu) MAX_ALL = 45 raw = self.rawdata[:MAX_ALL] for fa, fb in zip(a2b_functions, b2a_functions): a2b = getattr(binascii, fa) b2a = getattr(binascii, fb) try: a = b2a(self.type2test(raw)) res = a2b(self.type2test(a)) except Exception as err: self.fail("{}/{} conversion raises {!r}".format(fb, fa, err)) if fb == 'b2a_hqx': # b2a_hqx returns a tuple res, _ = res self.assertEqual(res, raw, "{}/{} conversion: " "{!r} != {!r}".format(fb, fa, res, raw)) self.assertIsInstance(res, bytes) self.assertIsInstance(a, bytes) self.assertLess(max(a), 128) self.assertIsInstance(binascii.crc_hqx(raw, 0), int) self.assertIsInstance(binascii.crc32(raw), int) def test_base64valid(self): # Test base64 with valid data MAX_BASE64 = 57 lines = [] for i in range(0, len(self.rawdata), MAX_BASE64): b = self.type2test(self.rawdata[i:i+MAX_BASE64]) a = binascii.b2a_base64(b) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_base64(a) res += b self.assertEqual(res, self.rawdata) def test_base64invalid(self): # Test base64 with random invalid characters sprinkled throughout # (This requires a new version of binascii.) MAX_BASE64 = 57 lines = [] for i in range(0, len(self.data), MAX_BASE64): b = self.type2test(self.rawdata[i:i+MAX_BASE64]) a = binascii.b2a_base64(b) lines.append(a) fillers = bytearray() valid = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/" for i in range(256): if i not in valid: fillers.append(i) def addnoise(line): noise = fillers ratio = len(line) // len(noise) res = bytearray() while line and noise: if len(line) // len(noise) > ratio: c, line = line[0], line[1:] else: c, noise = noise[0], noise[1:] res.append(c) return res + noise + line res = bytearray() for line in map(addnoise, lines): a = self.type2test(line) b = binascii.a2b_base64(a) res += b self.assertEqual(res, self.rawdata) # Test base64 with just invalid characters, which should return # empty strings. TBD: shouldn't it raise an exception instead ? self.assertEqual(binascii.a2b_base64(self.type2test(fillers)), b'') def test_base64errors(self): # Test base64 with invalid padding def assertIncorrectPadding(data): with self.assertRaisesRegex(binascii.Error, r'(?i)Incorrect padding'): binascii.a2b_base64(self.type2test(data)) assertIncorrectPadding(b'ab') assertIncorrectPadding(b'ab=') assertIncorrectPadding(b'abc') assertIncorrectPadding(b'abcdef') assertIncorrectPadding(b'abcdef=') assertIncorrectPadding(b'abcdefg') assertIncorrectPadding(b'a=b=') assertIncorrectPadding(b'a\nb=') # Test base64 with invalid number of valid characters (1 mod 4) def assertInvalidLength(data): n_data_chars = len(re.sub(br'[^A-Za-z0-9/+]', br'', data)) expected_errmsg_re = \ r'(?i)Invalid.+number of data characters.+' + str(n_data_chars) with self.assertRaisesRegex(binascii.Error, expected_errmsg_re): binascii.a2b_base64(self.type2test(data)) assertInvalidLength(b'a') assertInvalidLength(b'a=') assertInvalidLength(b'a==') assertInvalidLength(b'a===') assertInvalidLength(b'a' * 5) assertInvalidLength(b'a' * (4 * 87 + 1)) assertInvalidLength(b'A\tB\nC ??DE') # only 5 valid characters def test_uu(self): MAX_UU = 45 for backtick in (True, False): lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i+MAX_UU]) a = binascii.b2a_uu(b, backtick=backtick) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu(b"\x7f"), b"\x00"*31) self.assertEqual(binascii.a2b_uu(b"\x80"), b"\x00"*32) self.assertEqual(binascii.a2b_uu(b"\xff"), b"\x00"*31) self.assertRaises(binascii.Error, binascii.a2b_uu, b"\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, b"!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46*b"!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu(b'x'), b'!> \n') self.assertEqual(binascii.b2a_uu(b''), b' \n') self.assertEqual(binascii.b2a_uu(b'', backtick=True), b'`\n') self.assertEqual(binascii.a2b_uu(b' \n'), b'') self.assertEqual(binascii.a2b_uu(b'`\n'), b'') self.assertEqual(binascii.b2a_uu(b'\x00Cat'), b'$ $-A= \n') self.assertEqual(binascii.b2a_uu(b'\x00Cat', backtick=True), b'$`$-A=```\n') self.assertEqual(binascii.a2b_uu(b'$`$-A=```\n'), binascii.a2b_uu(b'$ $-A= \n')) with self.assertRaises(TypeError): binascii.b2a_uu(b"", True) def test_crc_hqx(self): crc = binascii.crc_hqx(self.type2test(b"Test the CRC-32 of"), 0) crc = binascii.crc_hqx(self.type2test(b" this string."), crc) self.assertEqual(crc, 14290) self.assertRaises(TypeError, binascii.crc_hqx) self.assertRaises(TypeError, binascii.crc_hqx, self.type2test(b'')) for crc in 0, 1, 0x1234, 0x12345, 0x12345678, -1: self.assertEqual(binascii.crc_hqx(self.type2test(b''), crc), crc & 0xffff) def test_crc32(self): crc = binascii.crc32(self.type2test(b"Test the CRC-32 of")) crc = binascii.crc32(self.type2test(b" this string."), crc) self.assertEqual(crc, 1571220330) self.assertRaises(TypeError, binascii.crc32) def test_hqx(self): # Perform binhex4 style RLE-compression # Then calculate the hexbin4 binary-to-ASCII translation rle = binascii.rlecode_hqx(self.data) a = binascii.b2a_hqx(self.type2test(rle)) b, _ = binascii.a2b_hqx(self.type2test(a)) res = binascii.rledecode_hqx(b) self.assertEqual(res, self.rawdata) def test_rle(self): # test repetition with a repetition longer than the limit of 255 data = (b'a' * 100 + b'b' + b'c' * 300) encoded = binascii.rlecode_hqx(data) self.assertEqual(encoded, (b'a\x90d' # 'a' * 100 b'b' # 'b' b'c\x90\xff' # 'c' * 255 b'c\x90-')) # 'c' * 45 decoded = binascii.rledecode_hqx(encoded) self.assertEqual(decoded, data) def test_hex(self): # test hexlification s = b'{s\005\000\000\000worldi\002\000\000\000s\005\000\000\000helloi\001\000\000\0000' t = binascii.b2a_hex(self.type2test(s)) u = binascii.a2b_hex(self.type2test(t)) self.assertEqual(s, u) self.assertRaises(binascii.Error, binascii.a2b_hex, t[:-1]) self.assertRaises(binascii.Error, binascii.a2b_hex, t[:-1] + b'q') # Confirm that b2a_hex == hexlify and a2b_hex == unhexlify self.assertEqual(binascii.hexlify(self.type2test(s)), t) self.assertEqual(binascii.unhexlify(self.type2test(t)), u) def test_qp(self): type2test = self.type2test a2b_qp = binascii.a2b_qp b2a_qp = binascii.b2a_qp a2b_qp(data=b"", header=False) # Keyword arguments allowed # A test for SF bug 534347 (segfaults without the proper fix) try: a2b_qp(b"", **{1:1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(a2b_qp(type2test(b"=")), b"") self.assertEqual(a2b_qp(type2test(b"= ")), b"= ") self.assertEqual(a2b_qp(type2test(b"==")), b"=") self.assertEqual(a2b_qp(type2test(b"=\nAB")), b"AB") self.assertEqual(a2b_qp(type2test(b"=\r\nAB")), b"AB") self.assertEqual(a2b_qp(type2test(b"=\rAB")), b"") # ? self.assertEqual(a2b_qp(type2test(b"=\rAB\nCD")), b"CD") # ? self.assertEqual(a2b_qp(type2test(b"=AB")), b"\xab") self.assertEqual(a2b_qp(type2test(b"=ab")), b"\xab") self.assertEqual(a2b_qp(type2test(b"=AX")), b"=AX") self.assertEqual(a2b_qp(type2test(b"=XA")), b"=XA") self.assertEqual(a2b_qp(type2test(b"=AB")[:-1]), b"=A") self.assertEqual(a2b_qp(type2test(b'_')), b'_') self.assertEqual(a2b_qp(type2test(b'_'), header=True), b' ') self.assertRaises(TypeError, b2a_qp, foo="bar") self.assertEqual(a2b_qp(type2test(b"=00\r\n=00")), b"\x00\r\n\x00") self.assertEqual(b2a_qp(type2test(b"\xff\r\n\xff\n\xff")), b"=FF\r\n=FF\r\n=FF") self.assertEqual(b2a_qp(type2test(b"0"*75+b"\xff\r\n\xff\r\n\xff")), b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF") self.assertEqual(b2a_qp(type2test(b'\x7f')), b'=7F') self.assertEqual(b2a_qp(type2test(b'=')), b'=3D') self.assertEqual(b2a_qp(type2test(b'_')), b'_') self.assertEqual(b2a_qp(type2test(b'_'), header=True), b'=5F') self.assertEqual(b2a_qp(type2test(b'x y'), header=True), b'x_y') self.assertEqual(b2a_qp(type2test(b'x '), header=True), b'x=20') self.assertEqual(b2a_qp(type2test(b'x y'), header=True, quotetabs=True), b'x=20y') self.assertEqual(b2a_qp(type2test(b'x\ty'), header=True), b'x\ty') self.assertEqual(b2a_qp(type2test(b' ')), b'=20') self.assertEqual(b2a_qp(type2test(b'\t')), b'=09') self.assertEqual(b2a_qp(type2test(b' x')), b' x') self.assertEqual(b2a_qp(type2test(b'\tx')), b'\tx') self.assertEqual(b2a_qp(type2test(b' x')[:-1]), b'=20') self.assertEqual(b2a_qp(type2test(b'\tx')[:-1]), b'=09') self.assertEqual(b2a_qp(type2test(b'\0')), b'=00') self.assertEqual(b2a_qp(type2test(b'\0\n')), b'=00\n') self.assertEqual(b2a_qp(type2test(b'\0\n'), quotetabs=True), b'=00\n') self.assertEqual(b2a_qp(type2test(b'x y\tz')), b'x y\tz') self.assertEqual(b2a_qp(type2test(b'x y\tz'), quotetabs=True), b'x=20y=09z') self.assertEqual(b2a_qp(type2test(b'x y\tz'), istext=False), b'x y\tz') self.assertEqual(b2a_qp(type2test(b'x \ny\t\n')), b'x=20\ny=09\n') self.assertEqual(b2a_qp(type2test(b'x \ny\t\n'), quotetabs=True), b'x=20\ny=09\n') self.assertEqual(b2a_qp(type2test(b'x \ny\t\n'), istext=False), b'x =0Ay\t=0A') self.assertEqual(b2a_qp(type2test(b'x \ry\t\r')), b'x \ry\t\r') self.assertEqual(b2a_qp(type2test(b'x \ry\t\r'), quotetabs=True), b'x=20\ry=09\r') self.assertEqual(b2a_qp(type2test(b'x \ry\t\r'), istext=False), b'x =0Dy\t=0D') self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n')), b'x=20\r\ny=09\r\n') self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n'), quotetabs=True), b'x=20\r\ny=09\r\n') self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n'), istext=False), b'x =0D=0Ay\t=0D=0A') self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1]), b'x \r') self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1]), b'x\t\r') self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1], quotetabs=True), b'x=20\r') self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1], quotetabs=True), b'x=09\r') self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1], istext=False), b'x =0D') self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1], istext=False), b'x\t=0D') self.assertEqual(b2a_qp(type2test(b'.')), b'=2E') self.assertEqual(b2a_qp(type2test(b'.\n')), b'=2E\n') self.assertEqual(b2a_qp(type2test(b'.\r')), b'=2E\r') self.assertEqual(b2a_qp(type2test(b'.\0')), b'=2E=00') self.assertEqual(b2a_qp(type2test(b'a.\n')), b'a.\n') self.assertEqual(b2a_qp(type2test(b'.a')[:-1]), b'=2E') def test_empty_string(self): # A test for SF bug #1022953. Make sure SystemError is not raised. empty = self.type2test(b'') for func in all_functions: if func == 'crc_hqx': # crc_hqx needs 2 arguments binascii.crc_hqx(empty, 0) continue f = getattr(binascii, func) try: f(empty) except Exception as err: self.fail("{}({!r}) raises {!r}".format(func, empty, err)) def test_unicode_b2a(self): # Unicode strings are not accepted by b2a_* functions. for func in set(all_functions) - set(a2b_functions) | {'rledecode_hqx'}: try: self.assertRaises(TypeError, getattr(binascii, func), "test") except Exception as err: self.fail('{}("test") raises {!r}'.format(func, err)) # crc_hqx needs 2 arguments self.assertRaises(TypeError, binascii.crc_hqx, "test", 0) def test_unicode_a2b(self): # Unicode strings are accepted by a2b_* functions. MAX_ALL = 45 raw = self.rawdata[:MAX_ALL] for fa, fb in zip(a2b_functions, b2a_functions): if fa == 'rledecode_hqx': # Takes non-ASCII data continue a2b = getattr(binascii, fa) b2a = getattr(binascii, fb) try: a = b2a(self.type2test(raw)) binary_res = a2b(a) a = a.decode('ascii') res = a2b(a) except Exception as err: self.fail("{}/{} conversion raises {!r}".format(fb, fa, err)) if fb == 'b2a_hqx': # b2a_hqx returns a tuple res, _ = res binary_res, _ = binary_res self.assertEqual(res, raw, "{}/{} conversion: " "{!r} != {!r}".format(fb, fa, res, raw)) self.assertEqual(res, binary_res) self.assertIsInstance(res, bytes) # non-ASCII string self.assertRaises(ValueError, a2b, "\x80") def test_b2a_base64_newline(self): # Issue #25357: test newline parameter b = self.type2test(b'hello') self.assertEqual(binascii.b2a_base64(b), b'aGVsbG8=\n') self.assertEqual(binascii.b2a_base64(b, newline=True), b'aGVsbG8=\n') self.assertEqual(binascii.b2a_base64(b, newline=False), b'aGVsbG8=') class ArrayBinASCIITest(BinASCIITest): def type2test(self, s): return array.array('B', list(s)) class BytearrayBinASCIITest(BinASCIITest): type2test = bytearray class MemoryviewBinASCIITest(BinASCIITest): type2test = memoryview if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pstats.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pstats.py
import unittest from test import support from io import StringIO import pstats from pstats import SortKey class AddCallersTestCase(unittest.TestCase): """Tests for pstats.add_callers helper.""" def test_combine_results(self): # pstats.add_callers should combine the call results of both target # and source by adding the call time. See issue1269. # new format: used by the cProfile module target = {"a": (1, 2, 3, 4)} source = {"a": (1, 2, 3, 4), "b": (5, 6, 7, 8)} new_callers = pstats.add_callers(target, source) self.assertEqual(new_callers, {'a': (2, 4, 6, 8), 'b': (5, 6, 7, 8)}) # old format: used by the profile module target = {"a": 1} source = {"a": 1, "b": 5} new_callers = pstats.add_callers(target, source) self.assertEqual(new_callers, {'a': 2, 'b': 5}) class StatsTestCase(unittest.TestCase): def setUp(self): stats_file = support.findfile('pstats.pck') self.stats = pstats.Stats(stats_file) def test_add(self): stream = StringIO() stats = pstats.Stats(stream=stream) stats.add(self.stats, self.stats) def test_sort_stats_int(self): valid_args = {-1: 'stdname', 0: 'calls', 1: 'time', 2: 'cumulative'} for arg_int, arg_str in valid_args.items(): self.stats.sort_stats(arg_int) self.assertEqual(self.stats.sort_type, self.stats.sort_arg_dict_default[arg_str][-1]) def test_sort_stats_string(self): for sort_name in ['calls', 'ncalls', 'cumtime', 'cumulative', 'filename', 'line', 'module', 'name', 'nfl', 'pcalls', 'stdname', 'time', 'tottime']: self.stats.sort_stats(sort_name) self.assertEqual(self.stats.sort_type, self.stats.sort_arg_dict_default[sort_name][-1]) def test_sort_stats_partial(self): sortkey = 'filename' for sort_name in ['f', 'fi', 'fil', 'file', 'filen', 'filena', 'filenam', 'filename']: self.stats.sort_stats(sort_name) self.assertEqual(self.stats.sort_type, self.stats.sort_arg_dict_default[sortkey][-1]) def test_sort_stats_enum(self): for member in SortKey: self.stats.sort_stats(member) self.assertEqual( self.stats.sort_type, self.stats.sort_arg_dict_default[member.value][-1]) def test_sort_starts_mix(self): self.assertRaises(TypeError, self.stats.sort_stats, 'calls', SortKey.TIME) self.assertRaises(TypeError, self.stats.sort_stats, SortKey.TIME, 'calls') if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_userstring.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_userstring.py
# UserString is a wrapper around the native builtin string type. # UserString instances should behave similar to builtin string objects. import unittest from test import string_tests from collections import UserString class UserStringTest( string_tests.CommonTest, string_tests.MixinStrUnicodeUserStringTest, unittest.TestCase ): type2test = UserString # Overwrite the three testing methods, because UserString # can't cope with arguments propagated to UserString # (and we don't test with subclasses) def checkequal(self, result, object, methodname, *args, **kwargs): result = self.fixtype(result) object = self.fixtype(object) # we don't fix the arguments, because UserString can't cope with it realresult = getattr(object, methodname)(*args, **kwargs) self.assertEqual( result, realresult ) def checkraises(self, exc, obj, methodname, *args): obj = self.fixtype(obj) # we don't fix the arguments, because UserString can't cope with it with self.assertRaises(exc) as cm: getattr(obj, methodname)(*args) self.assertNotEqual(str(cm.exception), '') def checkcall(self, object, methodname, *args): object = self.fixtype(object) # we don't fix the arguments, because UserString can't cope with it getattr(object, methodname)(*args) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bad_getattr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bad_getattr.py
x = 1 __getattr__ = "Surprise!" __dir__ = "Surprise again!"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_tw.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_tw.py
# # test_codecencodings_tw.py # Codec encoding tests for ROC encodings. # from test import multibytecodec_support import unittest class Test_Big5(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'big5' tstring = multibytecodec_support.load_teststring('big5') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\u8b10"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u8b10\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\u8b10"), ) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading.py
""" Tests for the threading module. """ import test.support from test.support import (verbose, import_module, cpython_only, requires_type_collecting) from test.support.script_helper import assert_python_ok, assert_python_failure import random import sys import _thread import threading import time import unittest import weakref import os import subprocess import signal from test import lock_tests from test import support # Between fork() and exec(), only async-safe functions are allowed (issues # #12316 and #11870), and fork() from a worker thread is known to trigger # problems with some operating systems (issue #3863): skip problematic tests # on platforms known to behave badly. platforms_to_skip = ('netbsd5', 'hp-ux11') # A trivial mutable counter. class Counter(object): def __init__(self): self.value = 0 def inc(self): self.value += 1 def dec(self): self.value -= 1 def get(self): return self.value class TestThread(threading.Thread): def __init__(self, name, testcase, sema, mutex, nrunning): threading.Thread.__init__(self, name=name) self.testcase = testcase self.sema = sema self.mutex = mutex self.nrunning = nrunning def run(self): delay = random.random() / 10000.0 if verbose: print('task %s will run for %.1f usec' % (self.name, delay * 1e6)) with self.sema: with self.mutex: self.nrunning.inc() if verbose: print(self.nrunning.get(), 'tasks are running') self.testcase.assertLessEqual(self.nrunning.get(), 3) time.sleep(delay) if verbose: print('task', self.name, 'done') with self.mutex: self.nrunning.dec() self.testcase.assertGreaterEqual(self.nrunning.get(), 0) if verbose: print('%s is finished. %d tasks are running' % (self.name, self.nrunning.get())) class BaseTestCase(unittest.TestCase): def setUp(self): self._threads = test.support.threading_setup() def tearDown(self): test.support.threading_cleanup(*self._threads) test.support.reap_children() class ThreadTests(BaseTestCase): # Create a bunch of threads, let each do some work, wait until all are # done. def test_various_ops(self): # This takes about n/3 seconds to run (about n/3 clumps of tasks, # times about 1 second per clump). NUMTASKS = 10 # no more than 3 of the 10 can run at once sema = threading.BoundedSemaphore(value=3) mutex = threading.RLock() numrunning = Counter() threads = [] for i in range(NUMTASKS): t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) threads.append(t) self.assertIsNone(t.ident) self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$') t.start() if verbose: print('waiting for all tasks to complete') for t in threads: t.join() self.assertFalse(t.is_alive()) self.assertNotEqual(t.ident, 0) self.assertIsNotNone(t.ident) self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$') if verbose: print('all tasks done') self.assertEqual(numrunning.get(), 0) def test_ident_of_no_threading_threads(self): # The ident still must work for the main thread and dummy threads. self.assertIsNotNone(threading.currentThread().ident) def f(): ident.append(threading.currentThread().ident) done.set() done = threading.Event() ident = [] with support.wait_threads_exit(): tid = _thread.start_new_thread(f, ()) done.wait() self.assertEqual(ident[0], tid) # Kill the "immortal" _DummyThread del threading._active[ident[0]] # run with a small(ish) thread stack size (256 KiB) def test_various_ops_small_stack(self): if verbose: print('with 256 KiB thread stack size...') try: threading.stack_size(262144) except _thread.error: raise unittest.SkipTest( 'platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) # run with a large thread stack size (1 MiB) def test_various_ops_large_stack(self): if verbose: print('with 1 MiB thread stack size...') try: threading.stack_size(0x100000) except _thread.error: raise unittest.SkipTest( 'platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) def test_foreign_thread(self): # Check that a "foreign" thread can use the threading module. def f(mutex): # Calling current_thread() forces an entry for the foreign # thread to get made in the threading._active map. threading.current_thread() mutex.release() mutex = threading.Lock() mutex.acquire() with support.wait_threads_exit(): tid = _thread.start_new_thread(f, (mutex,)) # Wait for the thread to finish. mutex.acquire() self.assertIn(tid, threading._active) self.assertIsInstance(threading._active[tid], threading._DummyThread) #Issue 29376 self.assertTrue(threading._active[tid].is_alive()) self.assertRegex(repr(threading._active[tid]), '_DummyThread') del threading._active[tid] # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) # exposed at the Python level. This test relies on ctypes to get at it. def test_PyThreadState_SetAsyncExc(self): ctypes = import_module("ctypes") set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object) class AsyncExc(Exception): pass exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. tid = threading.get_ident() self.assertIsInstance(tid, int) self.assertGreater(tid, 0) try: result = set_async_exc(tid, exception) # The exception is async, so we might have to keep the VM busy until # it notices. while True: pass except AsyncExc: pass else: # This code is unreachable but it reflects the intent. If we wanted # to be smarter the above loop wouldn't be infinite. self.fail("AsyncExc not raised") try: self.assertEqual(result, 1) # one thread state modified except UnboundLocalError: # The exception was raised too quickly for us to get the result. pass # `worker_started` is set by the thread when it's inside a try/except # block waiting to catch the asynchronously set AsyncExc exception. # `worker_saw_exception` is set by the thread upon catching that # exception. worker_started = threading.Event() worker_saw_exception = threading.Event() class Worker(threading.Thread): def run(self): self.id = threading.get_ident() self.finished = False try: while True: worker_started.set() time.sleep(0.1) except AsyncExc: self.finished = True worker_saw_exception.set() t = Worker() t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: print(" trying nonsensical thread id") result = set_async_exc(-1, exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: print(" waiting for worker thread to get started") ret = worker_started.wait() self.assertTrue(ret) if verbose: print(" verifying worker hasn't exited") self.assertFalse(t.finished) if verbose: print(" attempting to raise asynch exception in worker") result = set_async_exc(t.id, exception) self.assertEqual(result, 1) # one thread state modified if verbose: print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: print(" all OK -- joining worker") if t.finished: t.join() # else the thread is still running, and we have no way to kill it def test_limbo_cleanup(self): # Issue 7481: Failure to start thread should cleanup the limbo map. def fail_new_thread(*args): raise threading.ThreadError() _start_new_thread = threading._start_new_thread threading._start_new_thread = fail_new_thread try: t = threading.Thread(target=lambda: None) self.assertRaises(threading.ThreadError, t.start) self.assertFalse( t in threading._limbo, "Failed to cleanup _limbo map on failure of Thread.start().") finally: threading._start_new_thread = _start_new_thread def test_finalize_runnning_thread(self): # Issue 1402: the PyGILState_Ensure / _Release functions may be called # very late on python exit: on deallocation of a running thread for # example. import_module("ctypes") rc, out, err = assert_python_failure("-c", """if 1: import ctypes, sys, time, _thread # This lock is used as a simple event variable. ready = _thread.allocate_lock() ready.acquire() # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: ensure = ctypes.pythonapi.PyGILState_Ensure release = ctypes.pythonapi.PyGILState_Release def __del__(self): state = self.ensure() self.release(state) def waitingThread(): x = C() ready.release() time.sleep(100) _thread.start_new_thread(waitingThread, ()) ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """) self.assertEqual(rc, 42) def test_finalize_with_trace(self): # Issue1733757 # Avoid a deadlock when sys.settrace steps into threading._shutdown assert_python_ok("-c", """if 1: import sys, threading # A deadlock-killer, to prevent the # testsuite to hang forever def killer(): import os, time time.sleep(2) print('program blocked; aborting') os._exit(2) t = threading.Thread(target=killer) t.daemon = True t.start() # This is the trace function def func(frame, event, arg): threading.current_thread() return func sys.settrace(func) """) def test_join_nondaemon_on_shutdown(self): # Issue 1722344 # Raising SystemExit skipped threading._shutdown rc, out, err = assert_python_ok("-c", """if 1: import threading from time import sleep def child(): sleep(1) # As a non-daemon thread we SHOULD wake up and nothing # should be torn down yet print("Woke up, sleep function is:", sleep) threading.Thread(target=child).start() raise SystemExit """) self.assertEqual(out.strip(), b"Woke up, sleep function is: <built-in function sleep>") self.assertEqual(err, b"") def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate old_interval = sys.getswitchinterval() try: for i in range(1, 100): sys.setswitchinterval(i * 0.0002) t = threading.Thread(target=lambda: None) t.start() t.join() l = enum() self.assertNotIn(t, l, "#1703448 triggered after %d trials: %s" % (i, l)) finally: sys.setswitchinterval(old_interval) def test_no_refcycle_through_target(self): class RunSelfFunction(object): def __init__(self, should_raise): # The links in this refcycle from Thread back to self # should be cleaned up when the thread completes. self.should_raise = should_raise self.thread = threading.Thread(target=self._run, args=(self,), kwargs={'yet_another':self}) self.thread.start() def _run(self, other_ref, yet_another): if self.should_raise: raise SystemExit cyclic_object = RunSelfFunction(should_raise=False) weak_cyclic_object = weakref.ref(cyclic_object) cyclic_object.thread.join() del cyclic_object self.assertIsNone(weak_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_cyclic_object()))) raising_cyclic_object = RunSelfFunction(should_raise=True) weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) raising_cyclic_object.thread.join() del raising_cyclic_object self.assertIsNone(weak_raising_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_raising_cyclic_object()))) def test_old_threading_api(self): # Just a quick sanity check to make sure the old method names are # still present t = threading.Thread() t.isDaemon() t.setDaemon(True) t.getName() t.setName("name") with self.assertWarnsRegex(PendingDeprecationWarning, 'use is_alive()'): t.isAlive() e = threading.Event() e.isSet() threading.activeCount() def test_repr_daemon(self): t = threading.Thread() self.assertNotIn('daemon', repr(t)) t.daemon = True self.assertIn('daemon', repr(t)) def test_daemon_param(self): t = threading.Thread() self.assertFalse(t.daemon) t = threading.Thread(daemon=False) self.assertFalse(t.daemon) t = threading.Thread(daemon=True) self.assertTrue(t.daemon) @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') def test_dummy_thread_after_fork(self): # Issue #14308: a dummy thread in the active list doesn't mess up # the after-fork mechanism. code = """if 1: import _thread, threading, os, time def background_thread(evt): # Creates and registers the _DummyThread instance threading.current_thread() evt.set() time.sleep(10) evt = threading.Event() _thread.start_new_thread(background_thread, (evt,)) evt.wait() assert threading.active_count() == 2, threading.active_count() if os.fork() == 0: assert threading.active_count() == 1, threading.active_count() os._exit(0) else: os.wait() """ _, out, err = assert_python_ok("-c", code) self.assertEqual(out, b'') self.assertEqual(err, b'') @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") def test_is_alive_after_fork(self): # Try hard to trigger #18418: is_alive() could sometimes be True on # threads that vanished after a fork. old_interval = sys.getswitchinterval() self.addCleanup(sys.setswitchinterval, old_interval) # Make the bug more likely to manifest. test.support.setswitchinterval(1e-6) for i in range(20): t = threading.Thread(target=lambda: None) t.start() pid = os.fork() if pid == 0: os._exit(11 if t.is_alive() else 10) else: t.join() pid, status = os.waitpid(pid, 0) self.assertTrue(os.WIFEXITED(status)) self.assertEqual(10, os.WEXITSTATUS(status)) def test_main_thread(self): main = threading.main_thread() self.assertEqual(main.name, 'MainThread') self.assertEqual(main.ident, threading.current_thread().ident) self.assertEqual(main.ident, threading.get_ident()) def f(): self.assertNotEqual(threading.main_thread().ident, threading.current_thread().ident) th = threading.Thread(target=f) th.start() th.join() @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") def test_main_thread_after_fork(self): code = """if 1: import os, threading pid = os.fork() if pid == 0: main = threading.main_thread() print(main.name) print(main.ident == threading.current_thread().ident) print(main.ident == threading.get_ident()) else: os.waitpid(pid, 0) """ _, out, err = assert_python_ok("-c", code) data = out.decode().replace('\r', '') self.assertEqual(err, b"") self.assertEqual(data, "MainThread\nTrue\nTrue\n") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()") def test_main_thread_after_fork_from_nonmain_thread(self): code = """if 1: import os, threading, sys def f(): pid = os.fork() if pid == 0: main = threading.main_thread() print(main.name) print(main.ident == threading.current_thread().ident) print(main.ident == threading.get_ident()) # stdout is fully buffered because not a tty, # we have to flush before exit. sys.stdout.flush() else: os.waitpid(pid, 0) th = threading.Thread(target=f) th.start() th.join() """ _, out, err = assert_python_ok("-c", code) data = out.decode().replace('\r', '') self.assertEqual(err, b"") self.assertEqual(data, "Thread-1\nTrue\nTrue\n") @requires_type_collecting def test_main_thread_during_shutdown(self): # bpo-31516: current_thread() should still point to the main thread # at shutdown code = """if 1: import gc, threading main_thread = threading.current_thread() assert main_thread is threading.main_thread() # sanity check class RefCycle: def __init__(self): self.cycle = self def __del__(self): print("GC:", threading.current_thread() is main_thread, threading.main_thread() is main_thread, threading.enumerate() == [main_thread]) RefCycle() gc.collect() # sanity check x = RefCycle() """ _, out, err = assert_python_ok("-c", code) data = out.decode() self.assertEqual(err, b"") self.assertEqual(data.splitlines(), ["GC: True True True"] * 2) def test_finalization_shutdown(self): # bpo-36402: Py_Finalize() calls threading._shutdown() which must wait # until Python thread states of all non-daemon threads get deleted. # # Test similar to SubinterpThreadingTests.test_threads_join_2(), but # test the finalization of the main interpreter. code = """if 1: import os import threading import time import random def random_sleep(): seconds = random.random() * 0.010 time.sleep(seconds) class Sleeper: def __del__(self): random_sleep() tls = threading.local() def f(): # Sleep a bit so that the thread is still running when # Py_Finalize() is called. random_sleep() tls.x = Sleeper() random_sleep() threading.Thread(target=f).start() random_sleep() """ rc, out, err = assert_python_ok("-c", code) self.assertEqual(err, b"") def test_tstate_lock(self): # Test an implementation detail of Thread objects. started = _thread.allocate_lock() finish = _thread.allocate_lock() started.acquire() finish.acquire() def f(): started.release() finish.acquire() time.sleep(0.01) # The tstate lock is None until the thread is started t = threading.Thread(target=f) self.assertIs(t._tstate_lock, None) t.start() started.acquire() self.assertTrue(t.is_alive()) # The tstate lock can't be acquired when the thread is running # (or suspended). tstate_lock = t._tstate_lock self.assertFalse(tstate_lock.acquire(timeout=0), False) finish.release() # When the thread ends, the state_lock can be successfully # acquired. self.assertTrue(tstate_lock.acquire(timeout=5), False) # But is_alive() is still True: we hold _tstate_lock now, which # prevents is_alive() from knowing the thread's end-of-life C code # is done. self.assertTrue(t.is_alive()) # Let is_alive() find out the C code is done. tstate_lock.release() self.assertFalse(t.is_alive()) # And verify the thread disposed of _tstate_lock. self.assertIsNone(t._tstate_lock) t.join() def test_repr_stopped(self): # Verify that "stopped" shows up in repr(Thread) appropriately. started = _thread.allocate_lock() finish = _thread.allocate_lock() started.acquire() finish.acquire() def f(): started.release() finish.acquire() t = threading.Thread(target=f) t.start() started.acquire() self.assertIn("started", repr(t)) finish.release() # "stopped" should appear in the repr in a reasonable amount of time. # Implementation detail: as of this writing, that's trivially true # if .join() is called, and almost trivially true if .is_alive() is # called. The detail we're testing here is that "stopped" shows up # "all on its own". LOOKING_FOR = "stopped" for i in range(500): if LOOKING_FOR in repr(t): break time.sleep(0.01) self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds t.join() def test_BoundedSemaphore_limit(self): # BoundedSemaphore should raise ValueError if released too often. for limit in range(1, 10): bs = threading.BoundedSemaphore(limit) threads = [threading.Thread(target=bs.acquire) for _ in range(limit)] for t in threads: t.start() for t in threads: t.join() threads = [threading.Thread(target=bs.release) for _ in range(limit)] for t in threads: t.start() for t in threads: t.join() self.assertRaises(ValueError, bs.release) @cpython_only def test_frame_tstate_tracing(self): # Issue #14432: Crash when a generator is created in a C thread that is # destroyed while the generator is still used. The issue was that a # generator contains a frame, and the frame kept a reference to the # Python state of the destroyed C thread. The crash occurs when a trace # function is setup. def noop_trace(frame, event, arg): # no operation return noop_trace def generator(): while 1: yield "generator" def callback(): if callback.gen is None: callback.gen = generator() return next(callback.gen) callback.gen = None old_trace = sys.gettrace() sys.settrace(noop_trace) try: # Install a trace function threading.settrace(noop_trace) # Create a generator in a C thread which exits after the call import _testcapi _testcapi.call_in_temporary_c_thread(callback) # Call the generator in a different Python thread, check that the # generator didn't keep a reference to the destroyed thread state for test in range(3): # The trace function is still called here callback() finally: sys.settrace(old_trace) @cpython_only def test_shutdown_locks(self): for daemon in (False, True): with self.subTest(daemon=daemon): event = threading.Event() thread = threading.Thread(target=event.wait, daemon=daemon) # Thread.start() must add lock to _shutdown_locks, # but only for non-daemon thread thread.start() tstate_lock = thread._tstate_lock if not daemon: self.assertIn(tstate_lock, threading._shutdown_locks) else: self.assertNotIn(tstate_lock, threading._shutdown_locks) # unblock the thread and join it event.set() thread.join() # Thread._stop() must remove tstate_lock from _shutdown_locks. # Daemon threads must never add it to _shutdown_locks. self.assertNotIn(tstate_lock, threading._shutdown_locks) class ThreadJoinOnShutdown(BaseTestCase): def _run_and_join(self, script): script = """if 1: import sys, os, time, threading # a thread, which waits for the main program to terminate def joiningfunc(mainthread): mainthread.join() print('end of thread') # stdout is fully buffered because not a tty, we have to flush # before exit. sys.stdout.flush() \n""" + script rc, out, err = assert_python_ok("-c", script) data = out.decode().replace('\r', '') self.assertEqual(data, "end of main\nend of thread\n") def test_1_join_on_shutdown(self): # The usual case: on exit, wait for a non-daemon thread script = """if 1: import os t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() time.sleep(0.1) print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_2_join_in_forked_process(self): # Like the test above, but from a forked interpreter script = """if 1: childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_3_join_in_forked_from_thread(self): # Like the test above, but fork() was called from a worker thread # In the forked process, the main Thread object must be marked as stopped. script = """if 1: main_thread = threading.current_thread() def worker(): childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(main_thread,)) print('end of main') t.start() t.join() # Should not block: main_thread is already stopped w = threading.Thread(target=worker) w.start() """ self._run_and_join(script) @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_4_daemon_threads(self): # Check that a daemon thread cannot crash the interpreter on shutdown # by manipulating internal structures that are being disposed of in # the main thread. script = """if True: import os import random import sys import time import threading thread_has_run = set() def random_io(): '''Loop for a while sleeping random tiny amounts and doing some I/O.''' while True: in_f = open(os.__file__, 'rb') stuff = in_f.read(200) null_f = open(os.devnull, 'wb') null_f.write(stuff) time.sleep(random.random() / 1995) null_f.close() in_f.close() thread_has_run.add(threading.current_thread()) def main(): count = 0 for _ in range(40): new_thread = threading.Thread(target=random_io) new_thread.daemon = True new_thread.start() count += 1 while len(thread_has_run) < count: time.sleep(0.001) # Trigger process shutdown sys.exit(0) main() """ rc, out, err = assert_python_ok('-c', script) self.assertFalse(err) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_reinit_tls_after_fork(self): # Issue #13817: fork() would deadlock in a multithreaded program with # the ad-hoc TLS implementation. def do_fork_and_wait(): # just fork a child process and wait it pid = os.fork() if pid > 0: os.waitpid(pid, 0) else: os._exit(0) # start a bunch of threads that will fork() child processes threads = [] for i in range(16): t = threading.Thread(target=do_fork_and_wait) threads.append(t) t.start() for t in threads: t.join() @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") def test_clear_threads_states_after_fork(self):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test___all__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test___all__.py
import unittest from test import support import os import sys class NoAll(RuntimeError): pass class FailedImport(RuntimeError): pass class AllTest(unittest.TestCase): def check_all(self, modname): names = {} with support.check_warnings( (".* (module|package)", DeprecationWarning), ("", ResourceWarning), quiet=True): try: exec("import %s" % modname, names) except: # Silent fail here seems the best route since some modules # may not be available or not initialize properly in all # environments. raise FailedImport(modname) if not hasattr(sys.modules[modname], "__all__"): raise NoAll(modname) names = {} with self.subTest(module=modname): try: exec("from %s import *" % modname, names) except Exception as e: # Include the module name in the exception string self.fail("__all__ failure in {}: {}: {}".format( modname, e.__class__.__name__, e)) if "__builtins__" in names: del names["__builtins__"] if '__annotations__' in names: del names['__annotations__'] keys = set(names) all_list = sys.modules[modname].__all__ all_set = set(all_list) self.assertCountEqual(all_set, all_list, "in module {}".format(modname)) self.assertEqual(keys, all_set, "in module {}".format(modname)) def walk_modules(self, basedir, modpath): for fn in sorted(os.listdir(basedir)): path = os.path.join(basedir, fn) if os.path.isdir(path): pkg_init = os.path.join(path, '__init__.py') if os.path.exists(pkg_init): yield pkg_init, modpath + fn for p, m in self.walk_modules(path, modpath + fn + "."): yield p, m continue if not fn.endswith('.py') or fn == '__init__.py': continue yield path, modpath + fn[:-3] def test_all(self): # Blacklisted modules and packages blacklist = set([ # Will raise a SyntaxError when compiling the exec statement '__future__', ]) if not sys.platform.startswith('java'): # In case _socket fails to build, make this test fail more gracefully # than an AttributeError somewhere deep in CGIHTTPServer. import _socket ignored = [] failed_imports = [] lib_dir = os.path.dirname(os.path.dirname(__file__)) for path, modname in self.walk_modules(lib_dir, ""): m = modname blacklisted = False while m: if m in blacklist: blacklisted = True break m = m.rpartition('.')[0] if blacklisted: continue if support.verbose: print(modname) try: # This heuristic speeds up the process by removing, de facto, # most test modules (and avoiding the auto-executing ones). with open(path, "rb") as f: if b"__all__" not in f.read(): raise NoAll(modname) self.check_all(modname) except NoAll: ignored.append(modname) except FailedImport: failed_imports.append(modname) if support.verbose: print('Following modules have no __all__ and have been ignored:', ignored) print('Following modules failed to be imported:', failed_imports) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/final_a.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/final_a.py
""" Fodder for module finalization tests in test_module. """ import shutil import test.final_b x = 'a' class C: def __del__(self): # Inspect module globals and builtins print("x =", x) print("final_b.x =", test.final_b.x) print("shutil.rmtree =", getattr(shutil.rmtree, '__name__', None)) print("len =", getattr(len, '__name__', None)) c = C() _underscored = C()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sys.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sys.py
from test import support from test.support.script_helper import assert_python_ok, assert_python_failure import builtins import codecs import gc import locale import operator import os import struct import subprocess import sys import sysconfig import test.support import textwrap import unittest import warnings # count the number of test runs, used to create unique # strings to intern in test_intern() INTERN_NUMRUNS = 0 class DisplayHookTest(unittest.TestCase): def test_original_displayhook(self): dh = sys.__displayhook__ with support.captured_stdout() as out: dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqual(builtins._, 42) del builtins._ with support.captured_stdout() as out: dh(None) self.assertEqual(out.getvalue(), "") self.assertTrue(not hasattr(builtins, "_")) # sys.displayhook() requires arguments self.assertRaises(TypeError, dh) stdout = sys.stdout try: del sys.stdout self.assertRaises(RuntimeError, dh, 42) finally: sys.stdout = stdout def test_lost_displayhook(self): displayhook = sys.displayhook try: del sys.displayhook code = compile("42", "<string>", "single") self.assertRaises(RuntimeError, eval, code) finally: sys.displayhook = displayhook def test_custom_displayhook(self): def baddisplayhook(obj): raise ValueError with support.swap_attr(sys, 'displayhook', baddisplayhook): code = compile("42", "<string>", "single") self.assertRaises(ValueError, eval, code) class ExceptHookTest(unittest.TestCase): def test_original_excepthook(self): try: raise ValueError(42) except ValueError as exc: with support.captured_stderr() as err: sys.__excepthook__(*sys.exc_info()) self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) self.assertRaises(TypeError, sys.__excepthook__) def test_excepthook_bytes_filename(self): # bpo-37467: sys.excepthook() must not crash if a filename # is a bytes string with warnings.catch_warnings(): warnings.simplefilter('ignore', BytesWarning) try: raise SyntaxError("msg", (b"bytes_filename", 123, 0, "text")) except SyntaxError as exc: with support.captured_stderr() as err: sys.__excepthook__(*sys.exc_info()) err = err.getvalue() self.assertIn(""" File "b'bytes_filename'", line 123\n""", err) self.assertIn(""" text\n""", err) self.assertTrue(err.endswith("SyntaxError: msg\n")) def test_excepthook(self): with test.support.captured_output("stderr") as stderr: sys.excepthook(1, '1', 1) self.assertTrue("TypeError: print_exception(): Exception expected for " \ "value, str found" in stderr.getvalue()) # FIXME: testing the code for a lost or replaced excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. class SysModuleTest(unittest.TestCase): def tearDown(self): test.support.reap_children() def test_exit(self): # call with two arguments self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument with self.assertRaises(SystemExit) as cm: sys.exit() self.assertIsNone(cm.exception.code) rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()') self.assertEqual(rc, 0) self.assertEqual(out, b'') self.assertEqual(err, b'') # call with integer argument with self.assertRaises(SystemExit) as cm: sys.exit(42) self.assertEqual(cm.exception.code, 42) # call with tuple argument with one entry # entry will be unpacked with self.assertRaises(SystemExit) as cm: sys.exit((42,)) self.assertEqual(cm.exception.code, 42) # call with string argument with self.assertRaises(SystemExit) as cm: sys.exit("exit") self.assertEqual(cm.exception.code, "exit") # call with tuple argument with two entries with self.assertRaises(SystemExit) as cm: sys.exit((17, 23)) self.assertEqual(cm.exception.code, (17, 23)) # test that the exit machinery handles SystemExits properly rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)') self.assertEqual(rc, 47) self.assertEqual(out, b'') self.assertEqual(err, b'') def check_exit_message(code, expected, **env_vars): rc, out, err = assert_python_failure('-c', code, **env_vars) self.assertEqual(rc, 1) self.assertEqual(out, b'') self.assertTrue(err.startswith(expected), "%s doesn't start with %s" % (ascii(err), ascii(expected))) # test that stderr buffer is flushed before the exit message is written # into stderr check_exit_message( r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', b"unflushed,message") # test that the exit message is written with backslashreplace error # handler to stderr check_exit_message( r'import sys; sys.exit("surrogates:\uDCFF")', b"surrogates:\\udcff") # test that the unicode message is encoded to the stderr encoding # instead of the default encoding (utf8) check_exit_message( r'import sys; sys.exit("h\xe9")', b"h\xe9", PYTHONIOENCODING='latin-1') def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it self.assertIsInstance(sys.getdefaultencoding(), str) # testing sys.settrace() is done in test_sys_settrace.py # testing sys.setprofile() is done in test_sys_setprofile.py def test_setcheckinterval(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertRaises(TypeError, sys.setcheckinterval) orig = sys.getcheckinterval() for n in 0, 100, 120, orig: # orig last to restore starting state sys.setcheckinterval(n) self.assertEqual(sys.getcheckinterval(), n) def test_switchinterval(self): self.assertRaises(TypeError, sys.setswitchinterval) self.assertRaises(TypeError, sys.setswitchinterval, "a") self.assertRaises(ValueError, sys.setswitchinterval, -1.0) self.assertRaises(ValueError, sys.setswitchinterval, 0.0) orig = sys.getswitchinterval() # sanity check self.assertTrue(orig < 0.5, orig) try: for n in 0.00001, 0.05, 3.0, orig: sys.setswitchinterval(n) self.assertAlmostEqual(sys.getswitchinterval(), n) finally: sys.setswitchinterval(orig) def test_recursionlimit(self): self.assertRaises(TypeError, sys.getrecursionlimit, 42) oldlimit = sys.getrecursionlimit() self.assertRaises(TypeError, sys.setrecursionlimit) self.assertRaises(ValueError, sys.setrecursionlimit, -42) sys.setrecursionlimit(10000) self.assertEqual(sys.getrecursionlimit(), 10000) sys.setrecursionlimit(oldlimit) def test_recursionlimit_recovery(self): if hasattr(sys, 'gettrace') and sys.gettrace(): self.skipTest('fatal error if run with a trace function') oldlimit = sys.getrecursionlimit() def f(): f() try: for depth in (10, 25, 50, 75, 100, 250, 1000): try: sys.setrecursionlimit(depth) except RecursionError: # Issue #25274: The recursion limit is too low at the # current recursion depth continue # Issue #5392: test stack overflow after hitting recursion # limit twice self.assertRaises(RecursionError, f) self.assertRaises(RecursionError, f) finally: sys.setrecursionlimit(oldlimit) @test.support.cpython_only def test_setrecursionlimit_recursion_depth(self): # Issue #25274: Setting a low recursion limit must be blocked if the # current recursion depth is already higher than the "lower-water # mark". Otherwise, it may not be possible anymore to # reset the overflowed flag to 0. from _testcapi import get_recursion_depth def set_recursion_limit_at_depth(depth, limit): recursion_depth = get_recursion_depth() if recursion_depth >= depth: with self.assertRaises(RecursionError) as cm: sys.setrecursionlimit(limit) self.assertRegex(str(cm.exception), "cannot set the recursion limit to [0-9]+ " "at the recursion depth [0-9]+: " "the limit is too low") else: set_recursion_limit_at_depth(depth, limit) oldlimit = sys.getrecursionlimit() try: sys.setrecursionlimit(1000) for limit in (10, 25, 50, 75, 100, 150, 200): # formula extracted from _Py_RecursionLimitLowerWaterMark() if limit > 200: depth = limit - 50 else: depth = limit * 3 // 4 set_recursion_limit_at_depth(depth, limit) finally: sys.setrecursionlimit(oldlimit) def test_recursionlimit_fatalerror(self): # A fatal error occurs if a second recursion limit is hit when recovering # from a first one. code = textwrap.dedent(""" import sys def f(): try: f() except RecursionError: f() sys.setrecursionlimit(%d) f()""") with test.support.SuppressCrashReport(): for i in (50, 1000): sub = subprocess.Popen([sys.executable, '-c', code % i], stderr=subprocess.PIPE) err = sub.communicate()[1] self.assertTrue(sub.returncode, sub.returncode) self.assertIn( b"Fatal Python error: Cannot recover from stack overflow", err) def test_getwindowsversion(self): # Raise SkipTest if sys doesn't have getwindowsversion attribute test.support.get_attribute(sys, "getwindowsversion") v = sys.getwindowsversion() self.assertEqual(len(v), 5) self.assertIsInstance(v[0], int) self.assertIsInstance(v[1], int) self.assertIsInstance(v[2], int) self.assertIsInstance(v[3], int) self.assertIsInstance(v[4], str) self.assertRaises(IndexError, operator.getitem, v, 5) self.assertIsInstance(v.major, int) self.assertIsInstance(v.minor, int) self.assertIsInstance(v.build, int) self.assertIsInstance(v.platform, int) self.assertIsInstance(v.service_pack, str) self.assertIsInstance(v.service_pack_minor, int) self.assertIsInstance(v.service_pack_major, int) self.assertIsInstance(v.suite_mask, int) self.assertIsInstance(v.product_type, int) self.assertEqual(v[0], v.major) self.assertEqual(v[1], v.minor) self.assertEqual(v[2], v.build) self.assertEqual(v[3], v.platform) self.assertEqual(v[4], v.service_pack) # This is how platform.py calls it. Make sure tuple # still has 5 elements maj, min, buildno, plat, csd = sys.getwindowsversion() def test_call_tracing(self): self.assertRaises(TypeError, sys.call_tracing, type, 2) @unittest.skipUnless(hasattr(sys, "setdlopenflags"), 'test needs sys.setdlopenflags()') def test_dlopenflags(self): self.assertTrue(hasattr(sys, "getdlopenflags")) self.assertRaises(TypeError, sys.getdlopenflags, 42) oldflags = sys.getdlopenflags() self.assertRaises(TypeError, sys.setdlopenflags) sys.setdlopenflags(oldflags+1) self.assertEqual(sys.getdlopenflags(), oldflags+1) sys.setdlopenflags(oldflags) @test.support.refcount_test def test_refcount(self): # n here must be a global in order for this test to pass while # tracing with a python function. Tracing calls PyFrame_FastToLocals # which will add a copy of any locals to the frame object, causing # the reference count to increase by 2 instead of 1. global n self.assertRaises(TypeError, sys.getrefcount) c = sys.getrefcount(None) n = None self.assertEqual(sys.getrefcount(None), c+1) del n self.assertEqual(sys.getrefcount(None), c) if hasattr(sys, "gettotalrefcount"): self.assertIsInstance(sys.gettotalrefcount(), int) def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) self.assertRaises(ValueError, sys._getframe, 2000000000) self.assertTrue( SysModuleTest.test_getframe.__code__ \ is sys._getframe().f_code ) # sys._current_frames() is a CPython-only gimmick. @test.support.reap_threads def test_current_frames(self): import threading import traceback # Spawn a thread that blocks at a known place. Then the main # thread does sys._current_frames(), and verifies that the frames # returned make sense. entered_g = threading.Event() leave_g = threading.Event() thread_info = [] # the thread's id def f123(): g456() def g456(): thread_info.append(threading.get_ident()) entered_g.set() leave_g.wait() t = threading.Thread(target=f123) t.start() entered_g.wait() # At this point, t has finished its entered_g.set(), although it's # impossible to guess whether it's still on that line or has moved on # to its leave_g.wait(). self.assertEqual(len(thread_info), 1) thread_id = thread_info[0] d = sys._current_frames() for tid in d: self.assertIsInstance(tid, int) self.assertGreater(tid, 0) main_id = threading.get_ident() self.assertIn(main_id, d) self.assertIn(thread_id, d) # Verify that the captured main-thread frame is _this_ frame. frame = d.pop(main_id) self.assertTrue(frame is sys._getframe()) # Verify that the captured thread frame is blocked in g456, called # from f123. This is a litte tricky, since various bits of # threading.py are also in the thread's call stack. frame = d.pop(thread_id) stack = traceback.extract_stack(frame) for i, (filename, lineno, funcname, sourceline) in enumerate(stack): if funcname == "f123": break else: self.fail("didn't find f123() on thread's call stack") self.assertEqual(sourceline, "g456()") # And the next record must be for g456(). filename, lineno, funcname, sourceline = stack[i+1] self.assertEqual(funcname, "g456") self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"]) # Reap the spawned thread. leave_g.set() t.join() def test_attributes(self): self.assertIsInstance(sys.api_version, int) self.assertIsInstance(sys.argv, list) self.assertIn(sys.byteorder, ("little", "big")) self.assertIsInstance(sys.builtin_module_names, tuple) self.assertIsInstance(sys.copyright, str) self.assertIsInstance(sys.exec_prefix, str) self.assertIsInstance(sys.base_exec_prefix, str) self.assertIsInstance(sys.executable, str) self.assertEqual(len(sys.float_info), 11) self.assertEqual(sys.float_info.radix, 2) self.assertEqual(len(sys.int_info), 2) self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) self.assertTrue(sys.int_info.sizeof_digit >= 1) self.assertEqual(type(sys.int_info.bits_per_digit), int) self.assertEqual(type(sys.int_info.sizeof_digit), int) self.assertIsInstance(sys.hexversion, int) self.assertEqual(len(sys.hash_info), 9) self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) # sys.hash_info.modulus should be a prime; we do a quick # probable primality test (doesn't exclude the possibility of # a Carmichael number) for x in range(1, 100): self.assertEqual( pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), 1, "sys.hash_info.modulus {} is a non-prime".format( sys.hash_info.modulus) ) self.assertIsInstance(sys.hash_info.inf, int) self.assertIsInstance(sys.hash_info.nan, int) self.assertIsInstance(sys.hash_info.imag, int) algo = sysconfig.get_config_var("Py_HASH_ALGORITHM") if sys.hash_info.algorithm in {"fnv", "siphash24"}: self.assertIn(sys.hash_info.hash_bits, {32, 64}) self.assertIn(sys.hash_info.seed_bits, {32, 64, 128}) if algo == 1: self.assertEqual(sys.hash_info.algorithm, "siphash24") elif algo == 2: self.assertEqual(sys.hash_info.algorithm, "fnv") else: self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash24"}) else: # PY_HASH_EXTERNAL self.assertEqual(algo, 0) self.assertGreaterEqual(sys.hash_info.cutoff, 0) self.assertLess(sys.hash_info.cutoff, 8) self.assertIsInstance(sys.maxsize, int) self.assertIsInstance(sys.maxunicode, int) self.assertEqual(sys.maxunicode, 0x10FFFF) self.assertIsInstance(sys.platform, str) self.assertIsInstance(sys.prefix, str) self.assertIsInstance(sys.base_prefix, str) self.assertIsInstance(sys.version, str) vi = sys.version_info self.assertIsInstance(vi[:], tuple) self.assertEqual(len(vi), 5) self.assertIsInstance(vi[0], int) self.assertIsInstance(vi[1], int) self.assertIsInstance(vi[2], int) self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) self.assertIsInstance(vi[4], int) self.assertIsInstance(vi.major, int) self.assertIsInstance(vi.minor, int) self.assertIsInstance(vi.micro, int) self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final")) self.assertIsInstance(vi.serial, int) self.assertEqual(vi[0], vi.major) self.assertEqual(vi[1], vi.minor) self.assertEqual(vi[2], vi.micro) self.assertEqual(vi[3], vi.releaselevel) self.assertEqual(vi[4], vi.serial) self.assertTrue(vi > (1,0,0)) self.assertIsInstance(sys.float_repr_style, str) self.assertIn(sys.float_repr_style, ('short', 'legacy')) if not sys.platform.startswith('win'): self.assertIsInstance(sys.abiflags, str) def test_thread_info(self): info = sys.thread_info self.assertEqual(len(info), 3) self.assertIn(info.name, ('nt', 'pthread', 'solaris', None)) self.assertIn(info.lock, ('semaphore', 'mutex+cond', None)) def test_43581(self): # Can't use sys.stdout, as this is a StringIO object when # the test runs under regrtest. self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) def test_intern(self): global INTERN_NUMRUNS INTERN_NUMRUNS += 1 self.assertRaises(TypeError, sys.intern) s = "never interned before" + str(INTERN_NUMRUNS) self.assertTrue(sys.intern(s) is s) s2 = s.swapcase().swapcase() self.assertTrue(sys.intern(s2) is s) # Subclasses of string can't be interned, because they # provide too much opportunity for insane things to happen. # We don't want them in the interned dict and if they aren't # actually interned, we don't want to create the appearance # that they are by allowing intern() to succeed. class S(str): def __hash__(self): return 123 self.assertRaises(TypeError, sys.intern, S("abc")) def test_sys_flags(self): self.assertTrue(sys.flags) attrs = ("debug", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site", "ignore_environment", "verbose", "bytes_warning", "quiet", "hash_randomization", "isolated", "dev_mode", "utf8_mode") for attr in attrs: self.assertTrue(hasattr(sys.flags, attr), attr) attr_type = bool if attr == "dev_mode" else int self.assertEqual(type(getattr(sys.flags, attr)), attr_type, attr) self.assertTrue(repr(sys.flags)) self.assertEqual(len(sys.flags), len(attrs)) self.assertIn(sys.flags.utf8_mode, {0, 1, 2}) def assert_raise_on_new_sys_type(self, sys_attr): # Users are intentionally prevented from creating new instances of # sys.flags, sys.version_info, and sys.getwindowsversion. attr_type = type(sys_attr) with self.assertRaises(TypeError): attr_type() with self.assertRaises(TypeError): attr_type.__new__(attr_type) def test_sys_flags_no_instantiation(self): self.assert_raise_on_new_sys_type(sys.flags) def test_sys_version_info_no_instantiation(self): self.assert_raise_on_new_sys_type(sys.version_info) def test_sys_getwindowsversion_no_instantiation(self): # Skip if not being run on Windows. test.support.get_attribute(sys, "getwindowsversion") self.assert_raise_on_new_sys_type(sys.getwindowsversion()) @test.support.cpython_only def test_clear_type_cache(self): sys._clear_type_cache() def test_ioencoding(self): env = dict(os.environ) # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, # not representable in ASCII. env["PYTHONIOENCODING"] = "cp424" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout = subprocess.PIPE, env=env) out = p.communicate()[0].strip() expected = ("\xa2" + os.linesep).encode("cp424") self.assertEqual(out, expected) env["PYTHONIOENCODING"] = "ascii:replace" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout = subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, b'?') env["PYTHONIOENCODING"] = "ascii" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(out, b'') self.assertIn(b'UnicodeEncodeError:', err) self.assertIn(rb"'\xa2'", err) env["PYTHONIOENCODING"] = "ascii:" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(out, b'') self.assertIn(b'UnicodeEncodeError:', err) self.assertIn(rb"'\xa2'", err) env["PYTHONIOENCODING"] = ":surrogateescape" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xdcbd))'], stdout=subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, b'\xbd') @unittest.skipUnless(test.support.FS_NONASCII, 'requires OS support of non-ASCII encodings') @unittest.skipUnless(sys.getfilesystemencoding() == locale.getpreferredencoding(False), 'requires FS encoding to match locale') def test_ioencoding_nonascii(self): env = dict(os.environ) env["PYTHONIOENCODING"] = "" p = subprocess.Popen([sys.executable, "-c", 'print(%a)' % test.support.FS_NONASCII], stdout=subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, os.fsencode(test.support.FS_NONASCII)) @unittest.skipIf(sys.base_prefix != sys.prefix, 'Test is not venv-compatible') def test_executable(self): # sys.executable should be absolute self.assertEqual(os.path.abspath(sys.executable), sys.executable) # Issue #7774: Ensure that sys.executable is an empty string if argv[0] # has been set to a non existent program name and Python is unable to # retrieve the real program name # For a normal installation, it should work without 'cwd' # argument. For test runs in the build directory, see #7774. python_dir = os.path.dirname(os.path.realpath(sys.executable)) p = subprocess.Popen( ["nonexistent", "-c", 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'], executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir) stdout = p.communicate()[0] executable = stdout.strip().decode("ASCII") p.wait() self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))]) def check_fsencoding(self, fs_encoding, expected=None): self.assertIsNotNone(fs_encoding) codecs.lookup(fs_encoding) if expected: self.assertEqual(fs_encoding, expected) def test_getfilesystemencoding(self): fs_encoding = sys.getfilesystemencoding() if sys.platform == 'darwin': expected = 'utf-8' else: expected = None self.check_fsencoding(fs_encoding, expected) def c_locale_get_error_handler(self, locale, isolated=False, encoding=None): # Force the POSIX locale env = os.environ.copy() env["LC_ALL"] = locale env["PYTHONCOERCECLOCALE"] = "0" code = '\n'.join(( 'import sys', 'def dump(name):', ' std = getattr(sys, name)', ' print("%s: %s" % (name, std.errors))', 'dump("stdin")', 'dump("stdout")', 'dump("stderr")', )) args = [sys.executable, "-c", code] if isolated: args.append("-I") if encoding is not None: env['PYTHONIOENCODING'] = encoding else: env.pop('PYTHONIOENCODING', None) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True) stdout, stderr = p.communicate() return stdout def check_locale_surrogateescape(self, locale): out = self.c_locale_get_error_handler(locale, isolated=True) self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') # replace the default error handler out = self.c_locale_get_error_handler(locale, encoding=':ignore') self.assertEqual(out, 'stdin: ignore\n' 'stdout: ignore\n' 'stderr: backslashreplace\n') # force the encoding out = self.c_locale_get_error_handler(locale, encoding='iso8859-1') self.assertEqual(out, 'stdin: strict\n' 'stdout: strict\n' 'stderr: backslashreplace\n') out = self.c_locale_get_error_handler(locale, encoding='iso8859-1:') self.assertEqual(out, 'stdin: strict\n' 'stdout: strict\n' 'stderr: backslashreplace\n') # have no any effect out = self.c_locale_get_error_handler(locale, encoding=':') self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') out = self.c_locale_get_error_handler(locale, encoding='') self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') def test_c_locale_surrogateescape(self): self.check_locale_surrogateescape('C') def test_posix_locale_surrogateescape(self): self.check_locale_surrogateescape('POSIX') def test_implementation(self): # This test applies to all implementations equally. levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF} self.assertTrue(hasattr(sys.implementation, 'name')) self.assertTrue(hasattr(sys.implementation, 'version')) self.assertTrue(hasattr(sys.implementation, 'hexversion')) self.assertTrue(hasattr(sys.implementation, 'cache_tag')) version = sys.implementation.version self.assertEqual(version[:2], (version.major, version.minor)) hexversion = (version.major << 24 | version.minor << 16 | version.micro << 8 | levels[version.releaselevel] << 4 | version.serial << 0) self.assertEqual(sys.implementation.hexversion, hexversion) # PEP 421 requires that .name be lower case. self.assertEqual(sys.implementation.name, sys.implementation.name.lower()) @test.support.cpython_only def test_debugmallocstats(self): # Test sys._debugmallocstats() from test.support.script_helper import assert_python_ok args = ['-c', 'import sys; sys._debugmallocstats()'] ret, out, err = assert_python_ok(*args) self.assertIn(b"free PyDictObjects", err) # The function has no parameter self.assertRaises(TypeError, sys._debugmallocstats, True) @unittest.skipUnless(hasattr(sys, "getallocatedblocks"), "sys.getallocatedblocks unavailable on this build") def test_getallocatedblocks(self): try: import _testcapi except ImportError: with_pymalloc = support.with_pymalloc() else: try: alloc_name = _testcapi.pymem_getallocatorsname() except RuntimeError as exc: # "cannot get allocators name" (ex: tracemalloc is used) with_pymalloc = True else: with_pymalloc = (alloc_name in ('pymalloc', 'pymalloc_debug')) # Some sanity checks a = sys.getallocatedblocks() self.assertIs(type(a), int) if with_pymalloc: self.assertGreater(a, 0) else: # When WITH_PYMALLOC isn't available, we don't know anything # about the underlying implementation: the function might # return 0 or something greater. self.assertGreaterEqual(a, 0) try: # While we could imagine a Python session where the number of # multiple buffer objects would exceed the sharing of references, # it is unlikely to happen in a normal test run. self.assertLess(a, sys.gettotalrefcount()) except AttributeError: # gettotalrefcount() not available pass gc.collect() b = sys.getallocatedblocks() self.assertLessEqual(b, a) gc.collect() c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50)) @test.support.requires_type_collecting def test_is_finalizing(self): self.assertIs(sys.is_finalizing(), False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/testcodec.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/testcodec.py
""" Test Codecs (used by test_charmapcodec) Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x78: "abc", # 1-n decoding mapping b"abc": 0x0078,# 1-n encoding mapping 0x01: None, # decoding mapping to <undefined> 0x79: "", # decoding mapping to <remove character> }) ### Encoding Map encoding_map = {} for k,v in decoding_map.items(): encoding_map[v] = k
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_lzma.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_lzma.py
import _compression from io import BytesIO, UnsupportedOperation, DEFAULT_BUFFER_SIZE import os import pathlib import pickle import random import sys from test import support import unittest from test.support import ( _4G, TESTFN, import_module, bigmemtest, run_unittest, unlink ) lzma = import_module("lzma") from lzma import LZMACompressor, LZMADecompressor, LZMAError, LZMAFile class CompressorDecompressorTestCase(unittest.TestCase): # Test error cases. def test_simple_bad_args(self): self.assertRaises(TypeError, LZMACompressor, []) self.assertRaises(TypeError, LZMACompressor, format=3.45) self.assertRaises(TypeError, LZMACompressor, check="") self.assertRaises(TypeError, LZMACompressor, preset="asdf") self.assertRaises(TypeError, LZMACompressor, filters=3) # Can't specify FORMAT_AUTO when compressing. self.assertRaises(ValueError, LZMACompressor, format=lzma.FORMAT_AUTO) # Can't specify a preset and a custom filter chain at the same time. with self.assertRaises(ValueError): LZMACompressor(preset=7, filters=[{"id": lzma.FILTER_LZMA2}]) self.assertRaises(TypeError, LZMADecompressor, ()) self.assertRaises(TypeError, LZMADecompressor, memlimit=b"qw") with self.assertRaises(TypeError): LZMADecompressor(lzma.FORMAT_RAW, filters="zzz") # Cannot specify a memory limit with FILTER_RAW. with self.assertRaises(ValueError): LZMADecompressor(lzma.FORMAT_RAW, memlimit=0x1000000) # Can only specify a custom filter chain with FILTER_RAW. self.assertRaises(ValueError, LZMADecompressor, filters=FILTERS_RAW_1) with self.assertRaises(ValueError): LZMADecompressor(format=lzma.FORMAT_XZ, filters=FILTERS_RAW_1) with self.assertRaises(ValueError): LZMADecompressor(format=lzma.FORMAT_ALONE, filters=FILTERS_RAW_1) lzc = LZMACompressor() self.assertRaises(TypeError, lzc.compress) self.assertRaises(TypeError, lzc.compress, b"foo", b"bar") self.assertRaises(TypeError, lzc.flush, b"blah") empty = lzc.flush() self.assertRaises(ValueError, lzc.compress, b"quux") self.assertRaises(ValueError, lzc.flush) lzd = LZMADecompressor() self.assertRaises(TypeError, lzd.decompress) self.assertRaises(TypeError, lzd.decompress, b"foo", b"bar") lzd.decompress(empty) self.assertRaises(EOFError, lzd.decompress, b"quux") def test_bad_filter_spec(self): self.assertRaises(TypeError, LZMACompressor, filters=[b"wobsite"]) self.assertRaises(ValueError, LZMACompressor, filters=[{"xyzzy": 3}]) self.assertRaises(ValueError, LZMACompressor, filters=[{"id": 98765}]) with self.assertRaises(ValueError): LZMACompressor(filters=[{"id": lzma.FILTER_LZMA2, "foo": 0}]) with self.assertRaises(ValueError): LZMACompressor(filters=[{"id": lzma.FILTER_DELTA, "foo": 0}]) with self.assertRaises(ValueError): LZMACompressor(filters=[{"id": lzma.FILTER_X86, "foo": 0}]) def test_decompressor_after_eof(self): lzd = LZMADecompressor() lzd.decompress(COMPRESSED_XZ) self.assertRaises(EOFError, lzd.decompress, b"nyan") def test_decompressor_memlimit(self): lzd = LZMADecompressor(memlimit=1024) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ) lzd = LZMADecompressor(lzma.FORMAT_XZ, memlimit=1024) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ) lzd = LZMADecompressor(lzma.FORMAT_ALONE, memlimit=1024) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_ALONE) # Test LZMADecompressor on known-good input data. def _test_decompressor(self, lzd, data, check, unused_data=b""): self.assertFalse(lzd.eof) out = lzd.decompress(data) self.assertEqual(out, INPUT) self.assertEqual(lzd.check, check) self.assertTrue(lzd.eof) self.assertEqual(lzd.unused_data, unused_data) def test_decompressor_auto(self): lzd = LZMADecompressor() self._test_decompressor(lzd, COMPRESSED_XZ, lzma.CHECK_CRC64) lzd = LZMADecompressor() self._test_decompressor(lzd, COMPRESSED_ALONE, lzma.CHECK_NONE) def test_decompressor_xz(self): lzd = LZMADecompressor(lzma.FORMAT_XZ) self._test_decompressor(lzd, COMPRESSED_XZ, lzma.CHECK_CRC64) def test_decompressor_alone(self): lzd = LZMADecompressor(lzma.FORMAT_ALONE) self._test_decompressor(lzd, COMPRESSED_ALONE, lzma.CHECK_NONE) def test_decompressor_raw_1(self): lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_1) self._test_decompressor(lzd, COMPRESSED_RAW_1, lzma.CHECK_NONE) def test_decompressor_raw_2(self): lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_2) self._test_decompressor(lzd, COMPRESSED_RAW_2, lzma.CHECK_NONE) def test_decompressor_raw_3(self): lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_3) self._test_decompressor(lzd, COMPRESSED_RAW_3, lzma.CHECK_NONE) def test_decompressor_raw_4(self): lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4) self._test_decompressor(lzd, COMPRESSED_RAW_4, lzma.CHECK_NONE) def test_decompressor_chunks(self): lzd = LZMADecompressor() out = [] for i in range(0, len(COMPRESSED_XZ), 10): self.assertFalse(lzd.eof) out.append(lzd.decompress(COMPRESSED_XZ[i:i+10])) out = b"".join(out) self.assertEqual(out, INPUT) self.assertEqual(lzd.check, lzma.CHECK_CRC64) self.assertTrue(lzd.eof) self.assertEqual(lzd.unused_data, b"") def test_decompressor_chunks_empty(self): lzd = LZMADecompressor() out = [] for i in range(0, len(COMPRESSED_XZ), 10): self.assertFalse(lzd.eof) out.append(lzd.decompress(b'')) out.append(lzd.decompress(b'')) out.append(lzd.decompress(b'')) out.append(lzd.decompress(COMPRESSED_XZ[i:i+10])) out = b"".join(out) self.assertEqual(out, INPUT) self.assertEqual(lzd.check, lzma.CHECK_CRC64) self.assertTrue(lzd.eof) self.assertEqual(lzd.unused_data, b"") def test_decompressor_chunks_maxsize(self): lzd = LZMADecompressor() max_length = 100 out = [] # Feed first half the input len_ = len(COMPRESSED_XZ) // 2 out.append(lzd.decompress(COMPRESSED_XZ[:len_], max_length=max_length)) self.assertFalse(lzd.needs_input) self.assertEqual(len(out[-1]), max_length) # Retrieve more data without providing more input out.append(lzd.decompress(b'', max_length=max_length)) self.assertFalse(lzd.needs_input) self.assertEqual(len(out[-1]), max_length) # Retrieve more data while providing more input out.append(lzd.decompress(COMPRESSED_XZ[len_:], max_length=max_length)) self.assertLessEqual(len(out[-1]), max_length) # Retrieve remaining uncompressed data while not lzd.eof: out.append(lzd.decompress(b'', max_length=max_length)) self.assertLessEqual(len(out[-1]), max_length) out = b"".join(out) self.assertEqual(out, INPUT) self.assertEqual(lzd.check, lzma.CHECK_CRC64) self.assertEqual(lzd.unused_data, b"") def test_decompressor_inputbuf_1(self): # Test reusing input buffer after moving existing # contents to beginning lzd = LZMADecompressor() out = [] # Create input buffer and fill it self.assertEqual(lzd.decompress(COMPRESSED_XZ[:100], max_length=0), b'') # Retrieve some results, freeing capacity at beginning # of input buffer out.append(lzd.decompress(b'', 2)) # Add more data that fits into input buffer after # moving existing data to beginning out.append(lzd.decompress(COMPRESSED_XZ[100:105], 15)) # Decompress rest of data out.append(lzd.decompress(COMPRESSED_XZ[105:])) self.assertEqual(b''.join(out), INPUT) def test_decompressor_inputbuf_2(self): # Test reusing input buffer by appending data at the # end right away lzd = LZMADecompressor() out = [] # Create input buffer and empty it self.assertEqual(lzd.decompress(COMPRESSED_XZ[:200], max_length=0), b'') out.append(lzd.decompress(b'')) # Fill buffer with new data out.append(lzd.decompress(COMPRESSED_XZ[200:280], 2)) # Append some more data, not enough to require resize out.append(lzd.decompress(COMPRESSED_XZ[280:300], 2)) # Decompress rest of data out.append(lzd.decompress(COMPRESSED_XZ[300:])) self.assertEqual(b''.join(out), INPUT) def test_decompressor_inputbuf_3(self): # Test reusing input buffer after extending it lzd = LZMADecompressor() out = [] # Create almost full input buffer out.append(lzd.decompress(COMPRESSED_XZ[:200], 5)) # Add even more data to it, requiring resize out.append(lzd.decompress(COMPRESSED_XZ[200:300], 5)) # Decompress rest of data out.append(lzd.decompress(COMPRESSED_XZ[300:])) self.assertEqual(b''.join(out), INPUT) def test_decompressor_unused_data(self): lzd = LZMADecompressor() extra = b"fooblibar" self._test_decompressor(lzd, COMPRESSED_XZ + extra, lzma.CHECK_CRC64, unused_data=extra) def test_decompressor_bad_input(self): lzd = LZMADecompressor() self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1) lzd = LZMADecompressor(lzma.FORMAT_XZ) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_ALONE) lzd = LZMADecompressor(lzma.FORMAT_ALONE) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ) lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_1) self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ) def test_decompressor_bug_28275(self): # Test coverage for Issue 28275 lzd = LZMADecompressor() self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1) # Previously, a second call could crash due to internal inconsistency self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1) # Test that LZMACompressor->LZMADecompressor preserves the input data. def test_roundtrip_xz(self): lzc = LZMACompressor() cdata = lzc.compress(INPUT) + lzc.flush() lzd = LZMADecompressor() self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64) def test_roundtrip_alone(self): lzc = LZMACompressor(lzma.FORMAT_ALONE) cdata = lzc.compress(INPUT) + lzc.flush() lzd = LZMADecompressor() self._test_decompressor(lzd, cdata, lzma.CHECK_NONE) def test_roundtrip_raw(self): lzc = LZMACompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4) cdata = lzc.compress(INPUT) + lzc.flush() lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4) self._test_decompressor(lzd, cdata, lzma.CHECK_NONE) def test_roundtrip_raw_empty(self): lzc = LZMACompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4) cdata = lzc.compress(INPUT) cdata += lzc.compress(b'') cdata += lzc.compress(b'') cdata += lzc.compress(b'') cdata += lzc.flush() lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4) self._test_decompressor(lzd, cdata, lzma.CHECK_NONE) def test_roundtrip_chunks(self): lzc = LZMACompressor() cdata = [] for i in range(0, len(INPUT), 10): cdata.append(lzc.compress(INPUT[i:i+10])) cdata.append(lzc.flush()) cdata = b"".join(cdata) lzd = LZMADecompressor() self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64) def test_roundtrip_empty_chunks(self): lzc = LZMACompressor() cdata = [] for i in range(0, len(INPUT), 10): cdata.append(lzc.compress(INPUT[i:i+10])) cdata.append(lzc.compress(b'')) cdata.append(lzc.compress(b'')) cdata.append(lzc.compress(b'')) cdata.append(lzc.flush()) cdata = b"".join(cdata) lzd = LZMADecompressor() self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64) # LZMADecompressor intentionally does not handle concatenated streams. def test_decompressor_multistream(self): lzd = LZMADecompressor() self._test_decompressor(lzd, COMPRESSED_XZ + COMPRESSED_ALONE, lzma.CHECK_CRC64, unused_data=COMPRESSED_ALONE) # Test with inputs larger than 4GiB. @bigmemtest(size=_4G + 100, memuse=2) def test_compressor_bigmem(self, size): lzc = LZMACompressor() cdata = lzc.compress(b"x" * size) + lzc.flush() ddata = lzma.decompress(cdata) try: self.assertEqual(len(ddata), size) self.assertEqual(len(ddata.strip(b"x")), 0) finally: ddata = None @bigmemtest(size=_4G + 100, memuse=3) def test_decompressor_bigmem(self, size): lzd = LZMADecompressor() blocksize = 10 * 1024 * 1024 block = random.getrandbits(blocksize * 8).to_bytes(blocksize, "little") try: input = block * (size // blocksize + 1) cdata = lzma.compress(input) ddata = lzd.decompress(cdata) self.assertEqual(ddata, input) finally: input = cdata = ddata = None # Pickling raises an exception; there's no way to serialize an lzma_stream. def test_pickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError): pickle.dumps(LZMACompressor(), proto) with self.assertRaises(TypeError): pickle.dumps(LZMADecompressor(), proto) @support.refcount_test def test_refleaks_in_decompressor___init__(self): gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') lzd = LZMADecompressor() refs_before = gettotalrefcount() for i in range(100): lzd.__init__() self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) class CompressDecompressFunctionTestCase(unittest.TestCase): # Test error cases: def test_bad_args(self): self.assertRaises(TypeError, lzma.compress) self.assertRaises(TypeError, lzma.compress, []) self.assertRaises(TypeError, lzma.compress, b"", format="xz") self.assertRaises(TypeError, lzma.compress, b"", check="none") self.assertRaises(TypeError, lzma.compress, b"", preset="blah") self.assertRaises(TypeError, lzma.compress, b"", filters=1024) # Can't specify a preset and a custom filter chain at the same time. with self.assertRaises(ValueError): lzma.compress(b"", preset=3, filters=[{"id": lzma.FILTER_LZMA2}]) self.assertRaises(TypeError, lzma.decompress) self.assertRaises(TypeError, lzma.decompress, []) self.assertRaises(TypeError, lzma.decompress, b"", format="lzma") self.assertRaises(TypeError, lzma.decompress, b"", memlimit=7.3e9) with self.assertRaises(TypeError): lzma.decompress(b"", format=lzma.FORMAT_RAW, filters={}) # Cannot specify a memory limit with FILTER_RAW. with self.assertRaises(ValueError): lzma.decompress(b"", format=lzma.FORMAT_RAW, memlimit=0x1000000) # Can only specify a custom filter chain with FILTER_RAW. with self.assertRaises(ValueError): lzma.decompress(b"", filters=FILTERS_RAW_1) with self.assertRaises(ValueError): lzma.decompress(b"", format=lzma.FORMAT_XZ, filters=FILTERS_RAW_1) with self.assertRaises(ValueError): lzma.decompress( b"", format=lzma.FORMAT_ALONE, filters=FILTERS_RAW_1) def test_decompress_memlimit(self): with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_XZ, memlimit=1024) with self.assertRaises(LZMAError): lzma.decompress( COMPRESSED_XZ, format=lzma.FORMAT_XZ, memlimit=1024) with self.assertRaises(LZMAError): lzma.decompress( COMPRESSED_ALONE, format=lzma.FORMAT_ALONE, memlimit=1024) # Test LZMADecompressor on known-good input data. def test_decompress_good_input(self): ddata = lzma.decompress(COMPRESSED_XZ) self.assertEqual(ddata, INPUT) ddata = lzma.decompress(COMPRESSED_ALONE) self.assertEqual(ddata, INPUT) ddata = lzma.decompress(COMPRESSED_XZ, lzma.FORMAT_XZ) self.assertEqual(ddata, INPUT) ddata = lzma.decompress(COMPRESSED_ALONE, lzma.FORMAT_ALONE) self.assertEqual(ddata, INPUT) ddata = lzma.decompress( COMPRESSED_RAW_1, lzma.FORMAT_RAW, filters=FILTERS_RAW_1) self.assertEqual(ddata, INPUT) ddata = lzma.decompress( COMPRESSED_RAW_2, lzma.FORMAT_RAW, filters=FILTERS_RAW_2) self.assertEqual(ddata, INPUT) ddata = lzma.decompress( COMPRESSED_RAW_3, lzma.FORMAT_RAW, filters=FILTERS_RAW_3) self.assertEqual(ddata, INPUT) ddata = lzma.decompress( COMPRESSED_RAW_4, lzma.FORMAT_RAW, filters=FILTERS_RAW_4) self.assertEqual(ddata, INPUT) def test_decompress_incomplete_input(self): self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_XZ[:128]) self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_ALONE[:128]) self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_1[:128], format=lzma.FORMAT_RAW, filters=FILTERS_RAW_1) self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_2[:128], format=lzma.FORMAT_RAW, filters=FILTERS_RAW_2) self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_3[:128], format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3) self.assertRaises(LZMAError, lzma.decompress, COMPRESSED_RAW_4[:128], format=lzma.FORMAT_RAW, filters=FILTERS_RAW_4) def test_decompress_bad_input(self): with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_BOGUS) with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_RAW_1) with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_ALONE, format=lzma.FORMAT_XZ) with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_XZ, format=lzma.FORMAT_ALONE) with self.assertRaises(LZMAError): lzma.decompress(COMPRESSED_XZ, format=lzma.FORMAT_RAW, filters=FILTERS_RAW_1) # Test that compress()->decompress() preserves the input data. def test_roundtrip(self): cdata = lzma.compress(INPUT) ddata = lzma.decompress(cdata) self.assertEqual(ddata, INPUT) cdata = lzma.compress(INPUT, lzma.FORMAT_XZ) ddata = lzma.decompress(cdata) self.assertEqual(ddata, INPUT) cdata = lzma.compress(INPUT, lzma.FORMAT_ALONE) ddata = lzma.decompress(cdata) self.assertEqual(ddata, INPUT) cdata = lzma.compress(INPUT, lzma.FORMAT_RAW, filters=FILTERS_RAW_4) ddata = lzma.decompress(cdata, lzma.FORMAT_RAW, filters=FILTERS_RAW_4) self.assertEqual(ddata, INPUT) # Unlike LZMADecompressor, decompress() *does* handle concatenated streams. def test_decompress_multistream(self): ddata = lzma.decompress(COMPRESSED_XZ + COMPRESSED_ALONE) self.assertEqual(ddata, INPUT * 2) # Test robust handling of non-LZMA data following the compressed stream(s). def test_decompress_trailing_junk(self): ddata = lzma.decompress(COMPRESSED_XZ + COMPRESSED_BOGUS) self.assertEqual(ddata, INPUT) def test_decompress_multistream_trailing_junk(self): ddata = lzma.decompress(COMPRESSED_XZ * 3 + COMPRESSED_BOGUS) self.assertEqual(ddata, INPUT * 3) class TempFile: """Context manager - creates a file, and deletes it on __exit__.""" def __init__(self, filename, data=b""): self.filename = filename self.data = data def __enter__(self): with open(self.filename, "wb") as f: f.write(self.data) def __exit__(self, *args): unlink(self.filename) class FileTestCase(unittest.TestCase): def test_init(self): with LZMAFile(BytesIO(COMPRESSED_XZ)) as f: pass with LZMAFile(BytesIO(), "w") as f: pass with LZMAFile(BytesIO(), "x") as f: pass with LZMAFile(BytesIO(), "a") as f: pass def test_init_with_PathLike_filename(self): filename = pathlib.Path(TESTFN) with TempFile(filename, COMPRESSED_XZ): with LZMAFile(filename) as f: self.assertEqual(f.read(), INPUT) with LZMAFile(filename, "a") as f: f.write(INPUT) with LZMAFile(filename) as f: self.assertEqual(f.read(), INPUT * 2) def test_init_with_filename(self): with TempFile(TESTFN, COMPRESSED_XZ): with LZMAFile(TESTFN) as f: pass with LZMAFile(TESTFN, "w") as f: pass with LZMAFile(TESTFN, "a") as f: pass def test_init_mode(self): with TempFile(TESTFN): with LZMAFile(TESTFN, "r"): pass with LZMAFile(TESTFN, "rb"): pass with LZMAFile(TESTFN, "w"): pass with LZMAFile(TESTFN, "wb"): pass with LZMAFile(TESTFN, "a"): pass with LZMAFile(TESTFN, "ab"): pass def test_init_with_x_mode(self): self.addCleanup(unlink, TESTFN) for mode in ("x", "xb"): unlink(TESTFN) with LZMAFile(TESTFN, mode): pass with self.assertRaises(FileExistsError): with LZMAFile(TESTFN, mode): pass def test_init_bad_mode(self): with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), (3, "x")) with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "xt") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "x+") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "rx") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "wx") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "rt") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "r+") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "wt") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "w+") with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "rw") def test_init_bad_check(self): with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", check=b"asd") # CHECK_UNKNOWN and anything above CHECK_ID_MAX should be invalid. with self.assertRaises(LZMAError): LZMAFile(BytesIO(), "w", check=lzma.CHECK_UNKNOWN) with self.assertRaises(LZMAError): LZMAFile(BytesIO(), "w", check=lzma.CHECK_ID_MAX + 3) # Cannot specify a check with mode="r". with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_NONE) with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_CRC32) with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_CRC64) with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_SHA256) with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), check=lzma.CHECK_UNKNOWN) def test_init_bad_preset(self): with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", preset=4.39) with self.assertRaises(LZMAError): LZMAFile(BytesIO(), "w", preset=10) with self.assertRaises(LZMAError): LZMAFile(BytesIO(), "w", preset=23) with self.assertRaises(OverflowError): LZMAFile(BytesIO(), "w", preset=-1) with self.assertRaises(OverflowError): LZMAFile(BytesIO(), "w", preset=-7) with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", preset="foo") # Cannot specify a preset with mode="r". with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), preset=3) def test_init_bad_filter_spec(self): with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", filters=[b"wobsite"]) with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", filters=[{"xyzzy": 3}]) with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", filters=[{"id": 98765}]) with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", filters=[{"id": lzma.FILTER_LZMA2, "foo": 0}]) with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", filters=[{"id": lzma.FILTER_DELTA, "foo": 0}]) with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", filters=[{"id": lzma.FILTER_X86, "foo": 0}]) def test_init_with_preset_and_filters(self): with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", format=lzma.FORMAT_RAW, preset=6, filters=FILTERS_RAW_1) def test_close(self): with BytesIO(COMPRESSED_XZ) as src: f = LZMAFile(src) f.close() # LZMAFile.close() should not close the underlying file object. self.assertFalse(src.closed) # Try closing an already-closed LZMAFile. f.close() self.assertFalse(src.closed) # Test with a real file on disk, opened directly by LZMAFile. with TempFile(TESTFN, COMPRESSED_XZ): f = LZMAFile(TESTFN) fp = f._fp f.close() # Here, LZMAFile.close() *should* close the underlying file object. self.assertTrue(fp.closed) # Try closing an already-closed LZMAFile. f.close() def test_closed(self): f = LZMAFile(BytesIO(COMPRESSED_XZ)) try: self.assertFalse(f.closed) f.read() self.assertFalse(f.closed) finally: f.close() self.assertTrue(f.closed) f = LZMAFile(BytesIO(), "w") try: self.assertFalse(f.closed) finally: f.close() self.assertTrue(f.closed) def test_fileno(self): f = LZMAFile(BytesIO(COMPRESSED_XZ)) try: self.assertRaises(UnsupportedOperation, f.fileno) finally: f.close() self.assertRaises(ValueError, f.fileno) with TempFile(TESTFN, COMPRESSED_XZ): f = LZMAFile(TESTFN) try: self.assertEqual(f.fileno(), f._fp.fileno()) self.assertIsInstance(f.fileno(), int) finally: f.close() self.assertRaises(ValueError, f.fileno) def test_seekable(self): f = LZMAFile(BytesIO(COMPRESSED_XZ)) try: self.assertTrue(f.seekable()) f.read() self.assertTrue(f.seekable()) finally: f.close() self.assertRaises(ValueError, f.seekable) f = LZMAFile(BytesIO(), "w") try: self.assertFalse(f.seekable()) finally: f.close() self.assertRaises(ValueError, f.seekable) src = BytesIO(COMPRESSED_XZ) src.seekable = lambda: False f = LZMAFile(src) try: self.assertFalse(f.seekable()) finally: f.close() self.assertRaises(ValueError, f.seekable) def test_readable(self): f = LZMAFile(BytesIO(COMPRESSED_XZ)) try: self.assertTrue(f.readable()) f.read() self.assertTrue(f.readable()) finally: f.close() self.assertRaises(ValueError, f.readable) f = LZMAFile(BytesIO(), "w") try: self.assertFalse(f.readable()) finally: f.close() self.assertRaises(ValueError, f.readable) def test_writable(self): f = LZMAFile(BytesIO(COMPRESSED_XZ)) try: self.assertFalse(f.writable()) f.read() self.assertFalse(f.writable()) finally: f.close() self.assertRaises(ValueError, f.writable) f = LZMAFile(BytesIO(), "w") try: self.assertTrue(f.writable()) finally: f.close() self.assertRaises(ValueError, f.writable) def test_read(self): with LZMAFile(BytesIO(COMPRESSED_XZ)) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_ALONE)) as f: self.assertEqual(f.read(), INPUT) with LZMAFile(BytesIO(COMPRESSED_XZ), format=lzma.FORMAT_XZ) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_ALONE), format=lzma.FORMAT_ALONE) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_RAW_1), format=lzma.FORMAT_RAW, filters=FILTERS_RAW_1) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_RAW_2), format=lzma.FORMAT_RAW, filters=FILTERS_RAW_2) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_RAW_3), format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") with LZMAFile(BytesIO(COMPRESSED_RAW_4), format=lzma.FORMAT_RAW, filters=FILTERS_RAW_4) as f: self.assertEqual(f.read(), INPUT) self.assertEqual(f.read(), b"") def test_read_0(self): with LZMAFile(BytesIO(COMPRESSED_XZ)) as f: self.assertEqual(f.read(0), b"") with LZMAFile(BytesIO(COMPRESSED_ALONE)) as f: self.assertEqual(f.read(0), b"") with LZMAFile(BytesIO(COMPRESSED_XZ), format=lzma.FORMAT_XZ) as f: self.assertEqual(f.read(0), b"") with LZMAFile(BytesIO(COMPRESSED_ALONE), format=lzma.FORMAT_ALONE) as f: self.assertEqual(f.read(0), b"") def test_read_10(self): with LZMAFile(BytesIO(COMPRESSED_XZ)) as f: chunks = [] while True: result = f.read(10) if not result: break self.assertLessEqual(len(result), 10) chunks.append(result) self.assertEqual(b"".join(chunks), INPUT) def test_read_multistream(self): with LZMAFile(BytesIO(COMPRESSED_XZ * 5)) as f: self.assertEqual(f.read(), INPUT * 5) with LZMAFile(BytesIO(COMPRESSED_XZ + COMPRESSED_ALONE)) as f: self.assertEqual(f.read(), INPUT * 2) with LZMAFile(BytesIO(COMPRESSED_RAW_3 * 4), format=lzma.FORMAT_RAW, filters=FILTERS_RAW_3) as f:
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/double_const.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/double_const.py
from test.support import TestFailed # A test for SF bug 422177: manifest float constants varied way too much in # precision depending on whether Python was loading a module for the first # time, or reloading it from a precompiled .pyc. The "expected" failure # mode is that when test_import imports this after all .pyc files have been # erased, it passes, but when test_import imports this from # double_const.pyc, it fails. This indicates a woeful loss of precision in # the marshal format for doubles. It's also possible that repr() doesn't # produce enough digits to get reasonable precision for this box. PI = 3.14159265358979324 TWOPI = 6.28318530717958648 PI_str = "3.14159265358979324" TWOPI_str = "6.28318530717958648" # Verify that the double x is within a few bits of eval(x_str). def check_ok(x, x_str): assert x > 0.0 x2 = eval(x_str) assert x2 > 0.0 diff = abs(x - x2) # If diff is no larger than 3 ULP (wrt x2), then diff/8 is no larger # than 0.375 ULP, so adding diff/8 to x2 should have no effect. if x2 + (diff / 8.) != x2: raise TestFailed("Manifest const %s lost too much precision " % x_str) check_ok(PI, PI_str) check_ok(TWOPI, TWOPI_str)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_future5.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_future5.py
# Check that multiple features can be enabled. from __future__ import unicode_literals, print_function import sys import unittest from test import support class TestMultipleFeatures(unittest.TestCase): def test_unicode_literals(self): self.assertIsInstance("", str) def test_print_function(self): with support.captured_output("stderr") as s: print("foo", file=sys.stderr) self.assertEqual(s.getvalue(), "foo\n") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threadsignals.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threadsignals.py
"""PyUnit testing that threads honor our signal semantics""" import unittest import signal import os import sys from test import support import _thread as thread import time if (sys.platform[:3] == 'win'): raise unittest.SkipTest("Can't test signal on %s" % sys.platform) process_pid = os.getpid() signalled_all=thread.allocate_lock() USING_PTHREAD_COND = (sys.thread_info.name == 'pthread' and sys.thread_info.lock == 'mutex+cond') def registerSignals(for_usr1, for_usr2, for_alrm): usr1 = signal.signal(signal.SIGUSR1, for_usr1) usr2 = signal.signal(signal.SIGUSR2, for_usr2) alrm = signal.signal(signal.SIGALRM, for_alrm) return usr1, usr2, alrm # The signal handler. Just note that the signal occurred and # from who. def handle_signals(sig,frame): signal_blackboard[sig]['tripped'] += 1 signal_blackboard[sig]['tripped_by'] = thread.get_ident() # a function that will be spawned as a separate thread. def send_signals(): os.kill(process_pid, signal.SIGUSR1) os.kill(process_pid, signal.SIGUSR2) signalled_all.release() class ThreadSignals(unittest.TestCase): def test_signals(self): with support.wait_threads_exit(): # Test signal handling semantics of threads. # We spawn a thread, have the thread send two signals, and # wait for it to finish. Check that we got both signals # and that they were run by the main thread. signalled_all.acquire() self.spawnSignallingThread() signalled_all.acquire() # the signals that we asked the kernel to send # will come back, but we don't know when. # (it might even be after the thread exits # and might be out of order.) If we haven't seen # the signals yet, send yet another signal and # wait for it return. if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \ or signal_blackboard[signal.SIGUSR2]['tripped'] == 0: try: signal.alarm(1) signal.pause() finally: signal.alarm(0) self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1) self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'], thread.get_ident()) self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1) self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'], thread.get_ident()) signalled_all.release() def spawnSignallingThread(self): thread.start_new_thread(send_signals, ()) def alarm_interrupt(self, sig, frame): raise KeyboardInterrupt @unittest.skipIf(USING_PTHREAD_COND, 'POSIX condition variables cannot be interrupted') @unittest.skipIf(sys.platform.startswith('linux') and not sys.thread_info.version, 'Issue 34004: musl does not allow interruption of locks ' 'by signals.') # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD @unittest.skipIf(sys.platform.startswith('openbsd'), 'lock cannot be interrupted on OpenBSD') def test_lock_acquire_interruption(self): # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck # in a deadlock. # XXX this test can fail when the legacy (non-semaphore) implementation # of locks is used in thread_pthread.h, see issue #11223. oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) try: lock = thread.allocate_lock() lock.acquire() signal.alarm(1) t1 = time.monotonic() self.assertRaises(KeyboardInterrupt, lock.acquire, timeout=5) dt = time.monotonic() - t1 # Checking that KeyboardInterrupt was raised is not sufficient. # We want to assert that lock.acquire() was interrupted because # of the signal, not that the signal handler was called immediately # after timeout return of lock.acquire() (which can fool assertRaises). self.assertLess(dt, 3.0) finally: signal.alarm(0) signal.signal(signal.SIGALRM, oldalrm) @unittest.skipIf(USING_PTHREAD_COND, 'POSIX condition variables cannot be interrupted') @unittest.skipIf(sys.platform.startswith('linux') and not sys.thread_info.version, 'Issue 34004: musl does not allow interruption of locks ' 'by signals.') # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD @unittest.skipIf(sys.platform.startswith('openbsd'), 'lock cannot be interrupted on OpenBSD') def test_rlock_acquire_interruption(self): # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck # in a deadlock. # XXX this test can fail when the legacy (non-semaphore) implementation # of locks is used in thread_pthread.h, see issue #11223. oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) try: rlock = thread.RLock() # For reentrant locks, the initial acquisition must be in another # thread. def other_thread(): rlock.acquire() with support.wait_threads_exit(): thread.start_new_thread(other_thread, ()) # Wait until we can't acquire it without blocking... while rlock.acquire(blocking=False): rlock.release() time.sleep(0.01) signal.alarm(1) t1 = time.monotonic() self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5) dt = time.monotonic() - t1 # See rationale above in test_lock_acquire_interruption self.assertLess(dt, 3.0) finally: signal.alarm(0) signal.signal(signal.SIGALRM, oldalrm) def acquire_retries_on_intr(self, lock): self.sig_recvd = False def my_handler(signal, frame): self.sig_recvd = True old_handler = signal.signal(signal.SIGUSR1, my_handler) try: def other_thread(): # Acquire the lock in a non-main thread, so this test works for # RLocks. lock.acquire() # Wait until the main thread is blocked in the lock acquire, and # then wake it up with this. time.sleep(0.5) os.kill(process_pid, signal.SIGUSR1) # Let the main thread take the interrupt, handle it, and retry # the lock acquisition. Then we'll let it run. time.sleep(0.5) lock.release() with support.wait_threads_exit(): thread.start_new_thread(other_thread, ()) # Wait until we can't acquire it without blocking... while lock.acquire(blocking=False): lock.release() time.sleep(0.01) result = lock.acquire() # Block while we receive a signal. self.assertTrue(self.sig_recvd) self.assertTrue(result) finally: signal.signal(signal.SIGUSR1, old_handler) def test_lock_acquire_retries_on_intr(self): self.acquire_retries_on_intr(thread.allocate_lock()) def test_rlock_acquire_retries_on_intr(self): self.acquire_retries_on_intr(thread.RLock()) def test_interrupted_timed_acquire(self): # Test to make sure we recompute lock acquisition timeouts when we # receive a signal. Check this by repeatedly interrupting a lock # acquire in the main thread, and make sure that the lock acquire times # out after the right amount of time. # NOTE: this test only behaves as expected if C signals get delivered # to the main thread. Otherwise lock.acquire() itself doesn't get # interrupted and the test trivially succeeds. self.start = None self.end = None self.sigs_recvd = 0 done = thread.allocate_lock() done.acquire() lock = thread.allocate_lock() lock.acquire() def my_handler(signum, frame): self.sigs_recvd += 1 old_handler = signal.signal(signal.SIGUSR1, my_handler) try: def timed_acquire(): self.start = time.monotonic() lock.acquire(timeout=0.5) self.end = time.monotonic() def send_signals(): for _ in range(40): time.sleep(0.02) os.kill(process_pid, signal.SIGUSR1) done.release() with support.wait_threads_exit(): # Send the signals from the non-main thread, since the main thread # is the only one that can process signals. thread.start_new_thread(send_signals, ()) timed_acquire() # Wait for thread to finish done.acquire() # This allows for some timing and scheduling imprecision self.assertLess(self.end - self.start, 2.0) self.assertGreater(self.end - self.start, 0.3) # If the signal is received several times before PyErr_CheckSignals() # is called, the handler will get called less than 40 times. Just # check it's been called at least once. self.assertGreater(self.sigs_recvd, 0) finally: signal.signal(signal.SIGUSR1, old_handler) def test_main(): global signal_blackboard signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 }, signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 }, signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } } oldsigs = registerSignals(handle_signals, handle_signals, handle_signals) try: support.run_unittest(ThreadSignals) finally: registerSignals(*oldsigs) if __name__ == '__main__': test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ann_module.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ann_module.py
""" The module for testing variable annotations. Empty lines above are for good reason (testing for correct line numbers) """ from typing import Optional from functools import wraps __annotations__[1] = 2 class C: x = 5; y: Optional['C'] = None from typing import Tuple x: int = 5; y: str = x; f: Tuple[int, int] class M(type): __annotations__['123'] = 123 o: type = object (pars): bool = True class D(C): j: str = 'hi'; k: str= 'bye' from types import new_class h_class = new_class('H', (C,)) j_class = new_class('J') class F(): z: int = 5 def __init__(self, x): pass class Y(F): def __init__(self): super(F, self).__init__(123) class Meta(type): def __new__(meta, name, bases, namespace): return super().__new__(meta, name, bases, namespace) class S(metaclass = Meta): x: str = 'something' y: str = 'something else' def foo(x: int = 10): def bar(y: List[str]): x: str = 'yes' bar() def dec(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_set.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_set.py
import unittest from test import support import gc import weakref import operator import copy import pickle from random import randrange, shuffle import warnings import collections import collections.abc import itertools class PassThru(Exception): pass def check_pass_thru(): raise PassThru yield 1 class BadCmp: def __hash__(self): return 1 def __eq__(self, other): raise RuntimeError class ReprWrapper: 'Used to test self-referential repr() calls' def __repr__(self): return repr(self.value) class HashCountingInt(int): 'int-like object that counts the number of times __hash__ is called' def __init__(self, *args): self.hash_count = 0 def __hash__(self): self.hash_count += 1 return int.__hash__(self) class TestJointOps: # Tests common to both set and frozenset def setUp(self): self.word = word = 'simsalabim' self.otherword = 'madagascar' self.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' self.s = self.thetype(word) self.d = dict.fromkeys(word) def test_new_or_init(self): self.assertRaises(TypeError, self.thetype, [], 2) self.assertRaises(TypeError, set().__init__, a=1) def test_uniquification(self): actual = sorted(self.s) expected = sorted(self.d) self.assertEqual(actual, expected) self.assertRaises(PassThru, self.thetype, check_pass_thru()) self.assertRaises(TypeError, self.thetype, [[]]) def test_len(self): self.assertEqual(len(self.s), len(self.d)) def test_contains(self): for c in self.letters: self.assertEqual(c in self.s, c in self.d) self.assertRaises(TypeError, self.s.__contains__, [[]]) s = self.thetype([frozenset(self.letters)]) self.assertIn(self.thetype(self.letters), s) def test_union(self): u = self.s.union(self.otherword) for c in self.letters: self.assertEqual(c in u, c in self.d or c in self.otherword) self.assertEqual(self.s, self.thetype(self.word)) self.assertEqual(type(u), self.basetype) self.assertRaises(PassThru, self.s.union, check_pass_thru()) self.assertRaises(TypeError, self.s.union, [[]]) for C in set, frozenset, dict.fromkeys, str, list, tuple: self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd')) self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg')) self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc')) self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef')) self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg')) # Issue #6573 x = self.thetype() self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2])) def test_or(self): i = self.s.union(self.otherword) self.assertEqual(self.s | set(self.otherword), i) self.assertEqual(self.s | frozenset(self.otherword), i) try: self.s | self.otherword except TypeError: pass else: self.fail("s|t did not screen-out general iterables") def test_intersection(self): i = self.s.intersection(self.otherword) for c in self.letters: self.assertEqual(c in i, c in self.d and c in self.otherword) self.assertEqual(self.s, self.thetype(self.word)) self.assertEqual(type(i), self.basetype) self.assertRaises(PassThru, self.s.intersection, check_pass_thru()) for C in set, frozenset, dict.fromkeys, str, list, tuple: self.assertEqual(self.thetype('abcba').intersection(C('cdc')), set('cc')) self.assertEqual(self.thetype('abcba').intersection(C('efgfe')), set('')) self.assertEqual(self.thetype('abcba').intersection(C('ccb')), set('bc')) self.assertEqual(self.thetype('abcba').intersection(C('ef')), set('')) self.assertEqual(self.thetype('abcba').intersection(C('cbcf'), C('bag')), set('b')) s = self.thetype('abcba') z = s.intersection() if self.thetype == frozenset(): self.assertEqual(id(s), id(z)) else: self.assertNotEqual(id(s), id(z)) def test_isdisjoint(self): def f(s1, s2): 'Pure python equivalent of isdisjoint()' return not set(s1).intersection(s2) for larg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef': s1 = self.thetype(larg) for rarg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef': for C in set, frozenset, dict.fromkeys, str, list, tuple: s2 = C(rarg) actual = s1.isdisjoint(s2) expected = f(s1, s2) self.assertEqual(actual, expected) self.assertTrue(actual is True or actual is False) def test_and(self): i = self.s.intersection(self.otherword) self.assertEqual(self.s & set(self.otherword), i) self.assertEqual(self.s & frozenset(self.otherword), i) try: self.s & self.otherword except TypeError: pass else: self.fail("s&t did not screen-out general iterables") def test_difference(self): i = self.s.difference(self.otherword) for c in self.letters: self.assertEqual(c in i, c in self.d and c not in self.otherword) self.assertEqual(self.s, self.thetype(self.word)) self.assertEqual(type(i), self.basetype) self.assertRaises(PassThru, self.s.difference, check_pass_thru()) self.assertRaises(TypeError, self.s.difference, [[]]) for C in set, frozenset, dict.fromkeys, str, list, tuple: self.assertEqual(self.thetype('abcba').difference(C('cdc')), set('ab')) self.assertEqual(self.thetype('abcba').difference(C('efgfe')), set('abc')) self.assertEqual(self.thetype('abcba').difference(C('ccb')), set('a')) self.assertEqual(self.thetype('abcba').difference(C('ef')), set('abc')) self.assertEqual(self.thetype('abcba').difference(), set('abc')) self.assertEqual(self.thetype('abcba').difference(C('a'), C('b')), set('c')) def test_sub(self): i = self.s.difference(self.otherword) self.assertEqual(self.s - set(self.otherword), i) self.assertEqual(self.s - frozenset(self.otherword), i) try: self.s - self.otherword except TypeError: pass else: self.fail("s-t did not screen-out general iterables") def test_symmetric_difference(self): i = self.s.symmetric_difference(self.otherword) for c in self.letters: self.assertEqual(c in i, (c in self.d) ^ (c in self.otherword)) self.assertEqual(self.s, self.thetype(self.word)) self.assertEqual(type(i), self.basetype) self.assertRaises(PassThru, self.s.symmetric_difference, check_pass_thru()) self.assertRaises(TypeError, self.s.symmetric_difference, [[]]) for C in set, frozenset, dict.fromkeys, str, list, tuple: self.assertEqual(self.thetype('abcba').symmetric_difference(C('cdc')), set('abd')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('ccb')), set('a')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('ef')), set('abcef')) def test_xor(self): i = self.s.symmetric_difference(self.otherword) self.assertEqual(self.s ^ set(self.otherword), i) self.assertEqual(self.s ^ frozenset(self.otherword), i) try: self.s ^ self.otherword except TypeError: pass else: self.fail("s^t did not screen-out general iterables") def test_equality(self): self.assertEqual(self.s, set(self.word)) self.assertEqual(self.s, frozenset(self.word)) self.assertEqual(self.s == self.word, False) self.assertNotEqual(self.s, set(self.otherword)) self.assertNotEqual(self.s, frozenset(self.otherword)) self.assertEqual(self.s != self.word, True) def test_setOfFrozensets(self): t = map(frozenset, ['abcdef', 'bcd', 'bdcb', 'fed', 'fedccba']) s = self.thetype(t) self.assertEqual(len(s), 3) def test_sub_and_super(self): p, q, r = map(self.thetype, ['ab', 'abcde', 'def']) self.assertTrue(p < q) self.assertTrue(p <= q) self.assertTrue(q <= q) self.assertTrue(q > p) self.assertTrue(q >= p) self.assertFalse(q < r) self.assertFalse(q <= r) self.assertFalse(q > r) self.assertFalse(q >= r) self.assertTrue(set('a').issubset('abc')) self.assertTrue(set('abc').issuperset('a')) self.assertFalse(set('a').issubset('cbs')) self.assertFalse(set('cbs').issuperset('a')) def test_pickling(self): for i in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(self.s, i) dup = pickle.loads(p) self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup)) if type(self.s) not in (set, frozenset): self.s.x = 10 p = pickle.dumps(self.s, i) dup = pickle.loads(p) self.assertEqual(self.s.x, dup.x) def test_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): itorg = iter(self.s) data = self.thetype(self.s) d = pickle.dumps(itorg, proto) it = pickle.loads(d) # Set iterators unpickle as list iterators due to the # undefined order of set items. # self.assertEqual(type(itorg), type(it)) self.assertIsInstance(it, collections.abc.Iterator) self.assertEqual(self.thetype(it), data) it = pickle.loads(d) try: drop = next(it) except StopIteration: continue d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(self.thetype(it), data - self.thetype((drop,))) def test_deepcopy(self): class Tracer: def __init__(self, value): self.value = value def __hash__(self): return self.value def __deepcopy__(self, memo=None): return Tracer(self.value + 1) t = Tracer(10) s = self.thetype([t]) dup = copy.deepcopy(s) self.assertNotEqual(id(s), id(dup)) for elem in dup: newt = elem self.assertNotEqual(id(t), id(newt)) self.assertEqual(t.value + 1, newt.value) def test_gc(self): # Create a nest of cycles to exercise overall ref count check class A: pass s = set(A() for i in range(1000)) for elem in s: elem.cycle = s elem.sub = elem elem.set = set([elem]) def test_subclass_with_custom_hash(self): # Bug #1257731 class H(self.thetype): def __hash__(self): return int(id(self) & 0x7fffffff) s=H() f=set() f.add(s) self.assertIn(s, f) f.remove(s) f.add(s) f.discard(s) def test_badcmp(self): s = self.thetype([BadCmp()]) # Detect comparison errors during insertion and lookup self.assertRaises(RuntimeError, self.thetype, [BadCmp(), BadCmp()]) self.assertRaises(RuntimeError, s.__contains__, BadCmp()) # Detect errors during mutating operations if hasattr(s, 'add'): self.assertRaises(RuntimeError, s.add, BadCmp()) self.assertRaises(RuntimeError, s.discard, BadCmp()) self.assertRaises(RuntimeError, s.remove, BadCmp()) def test_cyclical_repr(self): w = ReprWrapper() s = self.thetype([w]) w.value = s if self.thetype == set: self.assertEqual(repr(s), '{set(...)}') else: name = repr(s).partition('(')[0] # strip class name self.assertEqual(repr(s), '%s({%s(...)})' % (name, name)) def test_cyclical_print(self): w = ReprWrapper() s = self.thetype([w]) w.value = s fo = open(support.TESTFN, "w") try: fo.write(str(s)) fo.close() fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), repr(s)) finally: fo.close() support.unlink(support.TESTFN) def test_do_not_rehash_dict_keys(self): n = 10 d = dict.fromkeys(map(HashCountingInt, range(n))) self.assertEqual(sum(elem.hash_count for elem in d), n) s = self.thetype(d) self.assertEqual(sum(elem.hash_count for elem in d), n) s.difference(d) self.assertEqual(sum(elem.hash_count for elem in d), n) if hasattr(s, 'symmetric_difference_update'): s.symmetric_difference_update(d) self.assertEqual(sum(elem.hash_count for elem in d), n) d2 = dict.fromkeys(set(d)) self.assertEqual(sum(elem.hash_count for elem in d), n) d3 = dict.fromkeys(frozenset(d)) self.assertEqual(sum(elem.hash_count for elem in d), n) d3 = dict.fromkeys(frozenset(d), 123) self.assertEqual(sum(elem.hash_count for elem in d), n) self.assertEqual(d3, dict.fromkeys(d, 123)) def test_container_iterator(self): # Bug #3680: tp_traverse was not implemented for set iterator object class C(object): pass obj = C() ref = weakref.ref(obj) container = set([obj, 1]) obj.x = iter(container) del obj, container gc.collect() self.assertTrue(ref() is None, "Cycle was not collected") def test_free_after_iterating(self): support.check_free_after_iterating(self, iter, self.thetype) class TestSet(TestJointOps, unittest.TestCase): thetype = set basetype = set def test_init(self): s = self.thetype() s.__init__(self.word) self.assertEqual(s, set(self.word)) s.__init__(self.otherword) self.assertEqual(s, set(self.otherword)) self.assertRaises(TypeError, s.__init__, s, 2); self.assertRaises(TypeError, s.__init__, 1); def test_constructor_identity(self): s = self.thetype(range(3)) t = self.thetype(s) self.assertNotEqual(id(s), id(t)) def test_set_literal(self): s = set([1,2,3]) t = {1,2,3} self.assertEqual(s, t) def test_set_literal_insertion_order(self): # SF Issue #26020 -- Expect left to right insertion s = {1, 1.0, True} self.assertEqual(len(s), 1) stored_value = s.pop() self.assertEqual(type(stored_value), int) def test_set_literal_evaluation_order(self): # Expect left to right expression evaluation events = [] def record(obj): events.append(obj) s = {record(1), record(2), record(3)} self.assertEqual(events, [1, 2, 3]) def test_hash(self): self.assertRaises(TypeError, hash, self.s) def test_clear(self): self.s.clear() self.assertEqual(self.s, set()) self.assertEqual(len(self.s), 0) def test_copy(self): dup = self.s.copy() self.assertEqual(self.s, dup) self.assertNotEqual(id(self.s), id(dup)) self.assertEqual(type(dup), self.basetype) def test_add(self): self.s.add('Q') self.assertIn('Q', self.s) dup = self.s.copy() self.s.add('Q') self.assertEqual(self.s, dup) self.assertRaises(TypeError, self.s.add, []) def test_remove(self): self.s.remove('a') self.assertNotIn('a', self.s) self.assertRaises(KeyError, self.s.remove, 'Q') self.assertRaises(TypeError, self.s.remove, []) s = self.thetype([frozenset(self.word)]) self.assertIn(self.thetype(self.word), s) s.remove(self.thetype(self.word)) self.assertNotIn(self.thetype(self.word), s) self.assertRaises(KeyError, self.s.remove, self.thetype(self.word)) def test_remove_keyerror_unpacking(self): # bug: www.python.org/sf/1576657 for v1 in ['Q', (1,)]: try: self.s.remove(v1) except KeyError as e: v2 = e.args[0] self.assertEqual(v1, v2) else: self.fail() def test_remove_keyerror_set(self): key = self.thetype([3, 4]) try: self.s.remove(key) except KeyError as e: self.assertTrue(e.args[0] is key, "KeyError should be {0}, not {1}".format(key, e.args[0])) else: self.fail() def test_discard(self): self.s.discard('a') self.assertNotIn('a', self.s) self.s.discard('Q') self.assertRaises(TypeError, self.s.discard, []) s = self.thetype([frozenset(self.word)]) self.assertIn(self.thetype(self.word), s) s.discard(self.thetype(self.word)) self.assertNotIn(self.thetype(self.word), s) s.discard(self.thetype(self.word)) def test_pop(self): for i in range(len(self.s)): elem = self.s.pop() self.assertNotIn(elem, self.s) self.assertRaises(KeyError, self.s.pop) def test_update(self): retval = self.s.update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): self.assertIn(c, self.s) self.assertRaises(PassThru, self.s.update, check_pass_thru()) self.assertRaises(TypeError, self.s.update, [[]]) for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')): for C in set, frozenset, dict.fromkeys, str, list, tuple: s = self.thetype('abcba') self.assertEqual(s.update(C(p)), None) self.assertEqual(s, set(q)) for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'): q = 'ahi' for C in set, frozenset, dict.fromkeys, str, list, tuple: s = self.thetype('abcba') self.assertEqual(s.update(C(p), C(q)), None) self.assertEqual(s, set(s) | set(p) | set(q)) def test_ior(self): self.s |= set(self.otherword) for c in (self.word + self.otherword): self.assertIn(c, self.s) def test_intersection_update(self): retval = self.s.intersection_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if c in self.otherword and c in self.word: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru()) self.assertRaises(TypeError, self.s.intersection_update, [[]]) for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')): for C in set, frozenset, dict.fromkeys, str, list, tuple: s = self.thetype('abcba') self.assertEqual(s.intersection_update(C(p)), None) self.assertEqual(s, set(q)) ss = 'abcba' s = self.thetype(ss) t = 'cbc' self.assertEqual(s.intersection_update(C(p), C(t)), None) self.assertEqual(s, set('abcba')&set(p)&set(t)) def test_iand(self): self.s &= set(self.otherword) for c in (self.word + self.otherword): if c in self.otherword and c in self.word: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_difference_update(self): retval = self.s.difference_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if c in self.word and c not in self.otherword: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(PassThru, self.s.difference_update, check_pass_thru()) self.assertRaises(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) for p, q in (('cdc', 'ab'), ('efgfe', 'abc'), ('ccb', 'a'), ('ef', 'abc')): for C in set, frozenset, dict.fromkeys, str, list, tuple: s = self.thetype('abcba') self.assertEqual(s.difference_update(C(p)), None) self.assertEqual(s, set(q)) s = self.thetype('abcdefghih') s.difference_update() self.assertEqual(s, self.thetype('abcdefghih')) s = self.thetype('abcdefghih') s.difference_update(C('aba')) self.assertEqual(s, self.thetype('cdefghih')) s = self.thetype('abcdefghih') s.difference_update(C('cdc'), C('aba')) self.assertEqual(s, self.thetype('efghih')) def test_isub(self): self.s -= set(self.otherword) for c in (self.word + self.otherword): if c in self.word and c not in self.otherword: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_symmetric_difference_update(self): retval = self.s.symmetric_difference_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if (c in self.word) ^ (c in self.otherword): self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru()) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')): for C in set, frozenset, dict.fromkeys, str, list, tuple: s = self.thetype('abcba') self.assertEqual(s.symmetric_difference_update(C(p)), None) self.assertEqual(s, set(q)) def test_ixor(self): self.s ^= set(self.otherword) for c in (self.word + self.otherword): if (c in self.word) ^ (c in self.otherword): self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_inplace_on_self(self): t = self.s.copy() t |= t self.assertEqual(t, self.s) t &= t self.assertEqual(t, self.s) t -= t self.assertEqual(t, self.thetype()) t = self.s.copy() t ^= t self.assertEqual(t, self.thetype()) def test_weakref(self): s = self.thetype('gallahad') p = weakref.proxy(s) self.assertEqual(str(p), str(s)) s = None self.assertRaises(ReferenceError, str, p) def test_rich_compare(self): class TestRichSetCompare: def __gt__(self, some_set): self.gt_called = True return False def __lt__(self, some_set): self.lt_called = True return False def __ge__(self, some_set): self.ge_called = True return False def __le__(self, some_set): self.le_called = True return False # This first tries the builtin rich set comparison, which doesn't know # how to handle the custom object. Upon returning NotImplemented, the # corresponding comparison on the right object is invoked. myset = {1, 2, 3} myobj = TestRichSetCompare() myset < myobj self.assertTrue(myobj.gt_called) myobj = TestRichSetCompare() myset > myobj self.assertTrue(myobj.lt_called) myobj = TestRichSetCompare() myset <= myobj self.assertTrue(myobj.ge_called) myobj = TestRichSetCompare() myset >= myobj self.assertTrue(myobj.le_called) @unittest.skipUnless(hasattr(set, "test_c_api"), 'C API test only available in a debug build') def test_c_api(self): self.assertEqual(set().test_c_api(), True) class SetSubclass(set): pass class TestSetSubclass(TestSet): thetype = SetSubclass basetype = set class SetSubclassWithKeywordArgs(set): def __init__(self, iterable=[], newarg=None): set.__init__(self, iterable) class TestSetSubclassWithKeywordArgs(TestSet): def test_keywords_in_subclass(self): 'SF bug #1486663 -- this used to erroneously raise a TypeError' SetSubclassWithKeywordArgs(newarg=1) class TestFrozenSet(TestJointOps, unittest.TestCase): thetype = frozenset basetype = frozenset def test_init(self): s = self.thetype(self.word) s.__init__(self.otherword) self.assertEqual(s, set(self.word)) def test_singleton_empty_frozenset(self): f = frozenset() efs = [frozenset(), frozenset([]), frozenset(()), frozenset(''), frozenset(), frozenset([]), frozenset(()), frozenset(''), frozenset(range(0)), frozenset(frozenset()), frozenset(f), f] # All of the empty frozensets should have just one id() self.assertEqual(len(set(map(id, efs))), 1) def test_constructor_identity(self): s = self.thetype(range(3)) t = self.thetype(s) self.assertEqual(id(s), id(t)) def test_hash(self): self.assertEqual(hash(self.thetype('abcdeb')), hash(self.thetype('ebecda'))) # make sure that all permutations give the same hash value n = 100 seq = [randrange(n) for i in range(n)] results = set() for i in range(200): shuffle(seq) results.add(hash(self.thetype(seq))) self.assertEqual(len(results), 1) def test_copy(self): dup = self.s.copy() self.assertEqual(id(self.s), id(dup)) def test_frozen_as_dictkey(self): seq = list(range(10)) + list('abcdefg') + ['apple'] key1 = self.thetype(seq) key2 = self.thetype(reversed(seq)) self.assertEqual(key1, key2) self.assertNotEqual(id(key1), id(key2)) d = {} d[key1] = 42 self.assertEqual(d[key2], 42) def test_hash_caching(self): f = self.thetype('abcdcda') self.assertEqual(hash(f), hash(f)) def test_hash_effectiveness(self): n = 13 hashvalues = set() addhashvalue = hashvalues.add elemmasks = [(i+1, 1<<i) for i in range(n)] for i in range(2**n): addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i]))) self.assertEqual(len(hashvalues), 2**n) def zf_range(n): # https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers nums = [frozenset()] for i in range(n-1): num = frozenset(nums) nums.append(num) return nums[:n] def powerset(s): for i in range(len(s)+1): yield from map(frozenset, itertools.combinations(s, i)) for n in range(18): t = 2 ** n mask = t - 1 for nums in (range, zf_range): u = len({h & mask for h in map(hash, powerset(nums(n)))}) self.assertGreater(4*u, t) class FrozenSetSubclass(frozenset): pass class TestFrozenSetSubclass(TestFrozenSet): thetype = FrozenSetSubclass basetype = frozenset def test_constructor_identity(self): s = self.thetype(range(3)) t = self.thetype(s) self.assertNotEqual(id(s), id(t)) def test_copy(self): dup = self.s.copy() self.assertNotEqual(id(self.s), id(dup)) def test_nested_empty_constructor(self): s = self.thetype() t = self.thetype(s) self.assertEqual(s, t) def test_singleton_empty_frozenset(self): Frozenset = self.thetype f = frozenset() F = Frozenset() efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''), Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''), Frozenset(range(0)), Frozenset(Frozenset()), Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)] # All empty frozenset subclass instances should have different ids self.assertEqual(len(set(map(id, efs))), len(efs)) # Tests taken from test_sets.py ============================================= empty_set = set() #============================================================================== class TestBasicOps: def test_repr(self): if self.repr is not None: self.assertEqual(repr(self.set), self.repr) def check_repr_against_values(self): text = repr(self.set) self.assertTrue(text.startswith('{')) self.assertTrue(text.endswith('}')) result = text[1:-1].split(', ') result.sort() sorted_repr_values = [repr(value) for value in self.values] sorted_repr_values.sort() self.assertEqual(result, sorted_repr_values) def test_print(self): try: fo = open(support.TESTFN, "w") fo.write(str(self.set)) fo.close() fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), repr(self.set)) finally: fo.close() support.unlink(support.TESTFN) def test_length(self): self.assertEqual(len(self.set), self.length) def test_self_equality(self): self.assertEqual(self.set, self.set) def test_equivalent_equality(self): self.assertEqual(self.set, self.dup) def test_copy(self): self.assertEqual(self.set.copy(), self.dup) def test_self_union(self): result = self.set | self.set self.assertEqual(result, self.dup) def test_empty_union(self): result = self.set | empty_set self.assertEqual(result, self.dup) def test_union_empty(self): result = empty_set | self.set self.assertEqual(result, self.dup) def test_self_intersection(self): result = self.set & self.set self.assertEqual(result, self.dup) def test_empty_intersection(self): result = self.set & empty_set self.assertEqual(result, empty_set) def test_intersection_empty(self): result = empty_set & self.set self.assertEqual(result, empty_set) def test_self_isdisjoint(self): result = self.set.isdisjoint(self.set) self.assertEqual(result, not self.set) def test_empty_isdisjoint(self): result = self.set.isdisjoint(empty_set) self.assertEqual(result, True) def test_isdisjoint_empty(self): result = empty_set.isdisjoint(self.set) self.assertEqual(result, True) def test_self_symmetric_difference(self): result = self.set ^ self.set self.assertEqual(result, empty_set) def test_empty_symmetric_difference(self): result = self.set ^ empty_set self.assertEqual(result, self.set) def test_self_difference(self): result = self.set - self.set self.assertEqual(result, empty_set) def test_empty_difference(self): result = self.set - empty_set self.assertEqual(result, self.dup) def test_empty_difference_rev(self): result = empty_set - self.set self.assertEqual(result, empty_set) def test_iteration(self): for v in self.set: self.assertIn(v, self.values) setiter = iter(self.set) self.assertEqual(setiter.__length_hint__(), len(self.set)) def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(self.set, proto) copy = pickle.loads(p) self.assertEqual(self.set, copy, "%s != %s" % (self.set, copy)) def test_issue_37219(self): with self.assertRaises(TypeError):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_genericpath.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_genericpath.py
""" Tests common to genericpath, macpath, ntpath and posixpath """ import genericpath import os import sys import unittest import warnings from test import support from test.support.script_helper import assert_python_ok from test.support import FakePath def create_file(filename, data=b'foo'): with open(filename, 'xb', 0) as fp: fp.write(data) class GenericTest: common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime', 'getmtime', 'exists', 'isdir', 'isfile'] attributes = [] def test_no_argument(self): for attr in self.common_attributes + self.attributes: with self.assertRaises(TypeError): getattr(self.pathmodule, attr)() raise self.fail("{}.{}() did not raise a TypeError" .format(self.pathmodule.__name__, attr)) def test_commonprefix(self): commonprefix = self.pathmodule.commonprefix self.assertEqual( commonprefix([]), "" ) self.assertEqual( commonprefix(["/home/swenson/spam", "/home/swen/spam"]), "/home/swen" ) self.assertEqual( commonprefix(["/home/swen/spam", "/home/swen/eggs"]), "/home/swen/" ) self.assertEqual( commonprefix(["/home/swen/spam", "/home/swen/spam"]), "/home/swen/spam" ) self.assertEqual( commonprefix(["home:swenson:spam", "home:swen:spam"]), "home:swen" ) self.assertEqual( commonprefix([":home:swen:spam", ":home:swen:eggs"]), ":home:swen:" ) self.assertEqual( commonprefix([":home:swen:spam", ":home:swen:spam"]), ":home:swen:spam" ) self.assertEqual( commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]), b"/home/swen" ) self.assertEqual( commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]), b"/home/swen/" ) self.assertEqual( commonprefix([b"/home/swen/spam", b"/home/swen/spam"]), b"/home/swen/spam" ) self.assertEqual( commonprefix([b"home:swenson:spam", b"home:swen:spam"]), b"home:swen" ) self.assertEqual( commonprefix([b":home:swen:spam", b":home:swen:eggs"]), b":home:swen:" ) self.assertEqual( commonprefix([b":home:swen:spam", b":home:swen:spam"]), b":home:swen:spam" ) testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd', 'aXc', 'abd', 'ab', 'aX', 'abcX'] for s1 in testlist: for s2 in testlist: p = commonprefix([s1, s2]) self.assertTrue(s1.startswith(p)) self.assertTrue(s2.startswith(p)) if s1 != s2: n = len(p) self.assertNotEqual(s1[n:n+1], s2[n:n+1]) def test_getsize(self): filename = support.TESTFN self.addCleanup(support.unlink, filename) create_file(filename, b'Hello') self.assertEqual(self.pathmodule.getsize(filename), 5) os.remove(filename) create_file(filename, b'Hello World!') self.assertEqual(self.pathmodule.getsize(filename), 12) def test_filetime(self): filename = support.TESTFN self.addCleanup(support.unlink, filename) create_file(filename, b'foo') with open(filename, "ab", 0) as f: f.write(b"bar") with open(filename, "rb", 0) as f: data = f.read() self.assertEqual(data, b"foobar") self.assertLessEqual( self.pathmodule.getctime(filename), self.pathmodule.getmtime(filename) ) def test_exists(self): filename = support.TESTFN bfilename = os.fsencode(filename) self.addCleanup(support.unlink, filename) self.assertIs(self.pathmodule.exists(filename), False) self.assertIs(self.pathmodule.exists(bfilename), False) create_file(filename) self.assertIs(self.pathmodule.exists(filename), True) self.assertIs(self.pathmodule.exists(bfilename), True) if self.pathmodule is not genericpath: self.assertIs(self.pathmodule.lexists(filename), True) self.assertIs(self.pathmodule.lexists(bfilename), True) @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") def test_exists_fd(self): r, w = os.pipe() try: self.assertTrue(self.pathmodule.exists(r)) finally: os.close(r) os.close(w) self.assertFalse(self.pathmodule.exists(r)) def test_isdir(self): filename = support.TESTFN bfilename = os.fsencode(filename) self.assertIs(self.pathmodule.isdir(filename), False) self.assertIs(self.pathmodule.isdir(bfilename), False) try: create_file(filename) self.assertIs(self.pathmodule.isdir(filename), False) self.assertIs(self.pathmodule.isdir(bfilename), False) finally: support.unlink(filename) try: os.mkdir(filename) self.assertIs(self.pathmodule.isdir(filename), True) self.assertIs(self.pathmodule.isdir(bfilename), True) finally: support.rmdir(filename) def test_isfile(self): filename = support.TESTFN bfilename = os.fsencode(filename) self.assertIs(self.pathmodule.isfile(filename), False) self.assertIs(self.pathmodule.isfile(bfilename), False) try: create_file(filename) self.assertIs(self.pathmodule.isfile(filename), True) self.assertIs(self.pathmodule.isfile(bfilename), True) finally: support.unlink(filename) try: os.mkdir(filename) self.assertIs(self.pathmodule.isfile(filename), False) self.assertIs(self.pathmodule.isfile(bfilename), False) finally: support.rmdir(filename) def test_samefile(self): file1 = support.TESTFN file2 = support.TESTFN + "2" self.addCleanup(support.unlink, file1) self.addCleanup(support.unlink, file2) create_file(file1) self.assertTrue(self.pathmodule.samefile(file1, file1)) create_file(file2) self.assertFalse(self.pathmodule.samefile(file1, file2)) self.assertRaises(TypeError, self.pathmodule.samefile) def _test_samefile_on_link_func(self, func): test_fn1 = support.TESTFN test_fn2 = support.TESTFN + "2" self.addCleanup(support.unlink, test_fn1) self.addCleanup(support.unlink, test_fn2) create_file(test_fn1) func(test_fn1, test_fn2) self.assertTrue(self.pathmodule.samefile(test_fn1, test_fn2)) os.remove(test_fn2) create_file(test_fn2) self.assertFalse(self.pathmodule.samefile(test_fn1, test_fn2)) @support.skip_unless_symlink def test_samefile_on_symlink(self): self._test_samefile_on_link_func(os.symlink) def test_samefile_on_link(self): try: self._test_samefile_on_link_func(os.link) except PermissionError as e: self.skipTest('os.link(): %s' % e) def test_samestat(self): test_fn1 = support.TESTFN test_fn2 = support.TESTFN + "2" self.addCleanup(support.unlink, test_fn1) self.addCleanup(support.unlink, test_fn2) create_file(test_fn1) stat1 = os.stat(test_fn1) self.assertTrue(self.pathmodule.samestat(stat1, os.stat(test_fn1))) create_file(test_fn2) stat2 = os.stat(test_fn2) self.assertFalse(self.pathmodule.samestat(stat1, stat2)) self.assertRaises(TypeError, self.pathmodule.samestat) def _test_samestat_on_link_func(self, func): test_fn1 = support.TESTFN + "1" test_fn2 = support.TESTFN + "2" self.addCleanup(support.unlink, test_fn1) self.addCleanup(support.unlink, test_fn2) create_file(test_fn1) func(test_fn1, test_fn2) self.assertTrue(self.pathmodule.samestat(os.stat(test_fn1), os.stat(test_fn2))) os.remove(test_fn2) create_file(test_fn2) self.assertFalse(self.pathmodule.samestat(os.stat(test_fn1), os.stat(test_fn2))) @support.skip_unless_symlink def test_samestat_on_symlink(self): self._test_samestat_on_link_func(os.symlink) def test_samestat_on_link(self): try: self._test_samestat_on_link_func(os.link) except PermissionError as e: self.skipTest('os.link(): %s' % e) def test_sameopenfile(self): filename = support.TESTFN self.addCleanup(support.unlink, filename) create_file(filename) with open(filename, "rb", 0) as fp1: fd1 = fp1.fileno() with open(filename, "rb", 0) as fp2: fd2 = fp2.fileno() self.assertTrue(self.pathmodule.sameopenfile(fd1, fd2)) class TestGenericTest(GenericTest, unittest.TestCase): # Issue 16852: GenericTest can't inherit from unittest.TestCase # for test discovery purposes; CommonTest inherits from GenericTest # and is only meant to be inherited by others. pathmodule = genericpath def test_invalid_paths(self): for attr in GenericTest.common_attributes: # os.path.commonprefix doesn't raise ValueError if attr == 'commonprefix': continue func = getattr(self.pathmodule, attr) with self.subTest(attr=attr): try: func('/tmp\udfffabcds') except (OSError, UnicodeEncodeError): pass try: func(b'/tmp\xffabcds') except (OSError, UnicodeDecodeError): pass with self.assertRaisesRegex(ValueError, 'embedded null'): func('/tmp\x00abcds') with self.assertRaisesRegex(ValueError, 'embedded null'): func(b'/tmp\x00abcds') # Following TestCase is not supposed to be run from test_genericpath. # It is inherited by other test modules (macpath, ntpath, posixpath). class CommonTest(GenericTest): common_attributes = GenericTest.common_attributes + [ # Properties 'curdir', 'pardir', 'extsep', 'sep', 'pathsep', 'defpath', 'altsep', 'devnull', # Methods 'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath', 'join', 'split', 'splitext', 'isabs', 'basename', 'dirname', 'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath', ] def test_normcase(self): normcase = self.pathmodule.normcase # check that normcase() is idempotent for p in ["FoO/./BaR", b"FoO/./BaR"]: p = normcase(p) self.assertEqual(p, normcase(p)) self.assertEqual(normcase(''), '') self.assertEqual(normcase(b''), b'') # check that normcase raises a TypeError for invalid types for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}): self.assertRaises(TypeError, normcase, path) def test_splitdrive(self): # splitdrive for non-NT paths splitdrive = self.pathmodule.splitdrive self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar")) self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar")) self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar")) self.assertEqual(splitdrive(b"/foo/bar"), (b"", b"/foo/bar")) self.assertEqual(splitdrive(b"foo:bar"), (b"", b"foo:bar")) self.assertEqual(splitdrive(b":foo:bar"), (b"", b":foo:bar")) def test_expandvars(self): if self.pathmodule.__name__ == 'macpath': self.skipTest('macpath.expandvars is a stub') expandvars = self.pathmodule.expandvars with support.EnvironmentVarGuard() as env: env.clear() env["foo"] = "bar" env["{foo"] = "baz1" env["{foo}"] = "baz2" self.assertEqual(expandvars("foo"), "foo") self.assertEqual(expandvars("$foo bar"), "bar bar") self.assertEqual(expandvars("${foo}bar"), "barbar") self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar") self.assertEqual(expandvars("$bar bar"), "$bar bar") self.assertEqual(expandvars("$?bar"), "$?bar") self.assertEqual(expandvars("$foo}bar"), "bar}bar") self.assertEqual(expandvars("${foo"), "${foo") self.assertEqual(expandvars("${{foo}}"), "baz1}") self.assertEqual(expandvars("$foo$foo"), "barbar") self.assertEqual(expandvars("$bar$bar"), "$bar$bar") self.assertEqual(expandvars(b"foo"), b"foo") self.assertEqual(expandvars(b"$foo bar"), b"bar bar") self.assertEqual(expandvars(b"${foo}bar"), b"barbar") self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar") self.assertEqual(expandvars(b"$bar bar"), b"$bar bar") self.assertEqual(expandvars(b"$?bar"), b"$?bar") self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar") self.assertEqual(expandvars(b"${foo"), b"${foo") self.assertEqual(expandvars(b"${{foo}}"), b"baz1}") self.assertEqual(expandvars(b"$foo$foo"), b"barbar") self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar") @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII') def test_expandvars_nonascii(self): if self.pathmodule.__name__ == 'macpath': self.skipTest('macpath.expandvars is a stub') expandvars = self.pathmodule.expandvars def check(value, expected): self.assertEqual(expandvars(value), expected) with support.EnvironmentVarGuard() as env: env.clear() nonascii = support.FS_NONASCII env['spam'] = nonascii env[nonascii] = 'ham' + nonascii check(nonascii, nonascii) check('$spam bar', '%s bar' % nonascii) check('${spam}bar', '%sbar' % nonascii) check('${%s}bar' % nonascii, 'ham%sbar' % nonascii) check('$bar%s bar' % nonascii, '$bar%s bar' % nonascii) check('$spam}bar', '%s}bar' % nonascii) check(os.fsencode(nonascii), os.fsencode(nonascii)) check(b'$spam bar', os.fsencode('%s bar' % nonascii)) check(b'${spam}bar', os.fsencode('%sbar' % nonascii)) check(os.fsencode('${%s}bar' % nonascii), os.fsencode('ham%sbar' % nonascii)) check(os.fsencode('$bar%s bar' % nonascii), os.fsencode('$bar%s bar' % nonascii)) check(b'$spam}bar', os.fsencode('%s}bar' % nonascii)) def test_abspath(self): self.assertIn("foo", self.pathmodule.abspath("foo")) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertIn(b"foo", self.pathmodule.abspath(b"foo")) # avoid UnicodeDecodeError on Windows undecodable_path = b'' if sys.platform == 'win32' else b'f\xf2\xf2' # Abspath returns bytes when the arg is bytes with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) for path in (b'', b'foo', undecodable_path, b'/foo', b'C:\\'): self.assertIsInstance(self.pathmodule.abspath(path), bytes) def test_realpath(self): self.assertIn("foo", self.pathmodule.realpath("foo")) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertIn(b"foo", self.pathmodule.realpath(b"foo")) def test_normpath_issue5827(self): # Make sure normpath preserves unicode for path in ('', '.', '/', '\\', '///foo/.//bar//'): self.assertIsInstance(self.pathmodule.normpath(path), str) def test_abspath_issue3426(self): # Check that abspath returns unicode when the arg is unicode # with both ASCII and non-ASCII cwds. abspath = self.pathmodule.abspath for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): self.assertIsInstance(abspath(path), str) unicwd = '\xe7w\xf0' try: os.fsencode(unicwd) except (AttributeError, UnicodeEncodeError): # FS encoding is probably ASCII pass else: with support.temp_cwd(unicwd): for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): self.assertIsInstance(abspath(path), str) def test_nonascii_abspath(self): if (support.TESTFN_UNDECODABLE # Mac OS X denies the creation of a directory with an invalid # UTF-8 name. Windows allows creating a directory with an # arbitrary bytes name, but fails to enter this directory # (when the bytes name is used). and sys.platform not in ('win32', 'darwin')): name = support.TESTFN_UNDECODABLE elif support.TESTFN_NONASCII: name = support.TESTFN_NONASCII else: self.skipTest("need support.TESTFN_NONASCII") with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) with support.temp_cwd(name): self.test_abspath() def test_join_errors(self): # Check join() raises friendly TypeErrors. with support.check_warnings(('', BytesWarning), quiet=True): errmsg = "Can't mix strings and bytes in path components" with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.join(b'bytes', 'str') with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.join('str', b'bytes') # regression, see #15377 with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join(42, 'str') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join('str', 42) with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.join(42) with self.assertRaisesRegex(TypeError, 'list'): self.pathmodule.join([]) with self.assertRaisesRegex(TypeError, 'bytearray'): self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar')) def test_relpath_errors(self): # Check relpath() raises friendly TypeErrors. with support.check_warnings(('', (BytesWarning, DeprecationWarning)), quiet=True): errmsg = "Can't mix strings and bytes in path components" with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.relpath(b'bytes', 'str') with self.assertRaisesRegex(TypeError, errmsg): self.pathmodule.relpath('str', b'bytes') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.relpath(42, 'str') with self.assertRaisesRegex(TypeError, 'int'): self.pathmodule.relpath('str', 42) with self.assertRaisesRegex(TypeError, 'bytearray'): self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar')) def test_import(self): assert_python_ok('-S', '-c', 'import ' + self.pathmodule.__name__) class PathLikeTests(unittest.TestCase): def setUp(self): self.file_name = support.TESTFN.lower() self.file_path = FakePath(support.TESTFN) self.addCleanup(support.unlink, self.file_name) create_file(self.file_name, b"test_genericpath.PathLikeTests") def assertPathEqual(self, func): self.assertEqual(func(self.file_path), func(self.file_name)) def test_path_exists(self): self.assertPathEqual(os.path.exists) def test_path_isfile(self): self.assertPathEqual(os.path.isfile) def test_path_isdir(self): self.assertPathEqual(os.path.isdir) def test_path_commonprefix(self): self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]), self.file_name) def test_path_getsize(self): self.assertPathEqual(os.path.getsize) def test_path_getmtime(self): self.assertPathEqual(os.path.getatime) def test_path_getctime(self): self.assertPathEqual(os.path.getctime) def test_path_samefile(self): self.assertTrue(os.path.samefile(self.file_path, self.file_name)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_kr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_kr.py
# # test_codecmaps_kr.py # Codec mapping tests for ROK encodings # from test import multibytecodec_support import unittest class TestCP949Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'cp949' mapfileurl = 'http://www.pythontest.net/unicode/CP949.TXT' class TestEUCKRMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'euc_kr' mapfileurl = 'http://www.pythontest.net/unicode/EUC-KR.TXT' # A4D4 HANGUL FILLER indicates the begin of 8-bytes make-up sequence. pass_enctest = [(b'\xa4\xd4', '\u3164')] pass_dectest = [(b'\xa4\xd4', '\u3164')] class TestJOHABMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'johab' mapfileurl = 'http://www.pythontest.net/unicode/JOHAB.TXT' # KS X 1001 standard assigned 0x5c as WON SIGN. # But the early 90s is the only era that used johab widely, # most software implements it as REVERSE SOLIDUS. # So, we ignore the standard here. pass_enctest = [(b'\\', '\u20a9')] pass_dectest = [(b'\\', '\u20a9')] if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_repl.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_repl.py
"""Test the interactive interpreter.""" import sys import os import unittest import subprocess from textwrap import dedent from test.support import cpython_only, SuppressCrashReport from test.support.script_helper import kill_python def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): """Run the Python REPL with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. """ # To run the REPL without using a terminal, spawn python with the command # line option '-i' and the process name set to '<stdin>'. # The directory of argv[0] must match the directory of the Python # executable for the Popen() call to python to succeed as the directory # path may be used by Py_GetPath() to build the default module search # path. stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>") cmd_line = [stdin_fname, '-E', '-i'] cmd_line.extend(args) # Set TERM=vt100, for the rationale see the comments in spawn_python() of # test.support.script_helper. env = kw.setdefault('env', dict(os.environ)) env['TERM'] = 'vt100' return subprocess.Popen(cmd_line, executable=sys.executable, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw) class TestInteractiveInterpreter(unittest.TestCase): @cpython_only def test_no_memory(self): # Issue #30696: Fix the interactive interpreter looping endlessly when # no memory. Check also that the fix does not break the interactive # loop when an exception is raised. user_input = """ import sys, _testcapi 1/0 print('After the exception.') _testcapi.set_nomemory(0) sys.exit(0) """ user_input = dedent(user_input) user_input = user_input.encode() p = spawn_repl() with SuppressCrashReport(): p.stdin.write(user_input) output = kill_python(p) self.assertIn(b'After the exception.', output) # Exit code 120: Py_FinalizeEx() failed to flush stdout and stderr. self.assertIn(p.returncode, (1, 120)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_print.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_print.py
import unittest import sys from io import StringIO from test import support NotDefined = object() # A dispatch table all 8 combinations of providing # sep, end, and file. # I use this machinery so that I'm not just passing default # values to print, I'm either passing or not passing in the # arguments. dispatch = { (False, False, False): lambda args, sep, end, file: print(*args), (False, False, True): lambda args, sep, end, file: print(file=file, *args), (False, True, False): lambda args, sep, end, file: print(end=end, *args), (False, True, True): lambda args, sep, end, file: print(end=end, file=file, *args), (True, False, False): lambda args, sep, end, file: print(sep=sep, *args), (True, False, True): lambda args, sep, end, file: print(sep=sep, file=file, *args), (True, True, False): lambda args, sep, end, file: print(sep=sep, end=end, *args), (True, True, True): lambda args, sep, end, file: print(sep=sep, end=end, file=file, *args), } # Class used to test __str__ and print class ClassWith__str__: def __init__(self, x): self.x = x def __str__(self): return self.x class TestPrint(unittest.TestCase): """Test correct operation of the print function.""" def check(self, expected, args, sep=NotDefined, end=NotDefined, file=NotDefined): # Capture sys.stdout in a StringIO. Call print with args, # and with sep, end, and file, if they're defined. Result # must match expected. # Look up the actual function to call, based on if sep, end, # and file are defined. fn = dispatch[(sep is not NotDefined, end is not NotDefined, file is not NotDefined)] with support.captured_stdout() as t: fn(args, sep, end, file) self.assertEqual(t.getvalue(), expected) def test_print(self): def x(expected, args, sep=NotDefined, end=NotDefined): # Run the test 2 ways: not using file, and using # file directed to a StringIO. self.check(expected, args, sep=sep, end=end) # When writing to a file, stdout is expected to be empty o = StringIO() self.check('', args, sep=sep, end=end, file=o) # And o will contain the expected output self.assertEqual(o.getvalue(), expected) x('\n', ()) x('a\n', ('a',)) x('None\n', (None,)) x('1 2\n', (1, 2)) x('1 2\n', (1, ' ', 2)) x('1*2\n', (1, 2), sep='*') x('1 s', (1, 's'), end='') x('a\nb\n', ('a', 'b'), sep='\n') x('1.01', (1.0, 1), sep='', end='') x('1*a*1.3+', (1, 'a', 1.3), sep='*', end='+') x('a\n\nb\n', ('a\n', 'b'), sep='\n') x('\0+ +\0\n', ('\0', ' ', '\0'), sep='+') x('a\n b\n', ('a\n', 'b')) x('a\n b\n', ('a\n', 'b'), sep=None) x('a\n b\n', ('a\n', 'b'), end=None) x('a\n b\n', ('a\n', 'b'), sep=None, end=None) x('*\n', (ClassWith__str__('*'),)) x('abc 1\n', (ClassWith__str__('abc'), 1)) # errors self.assertRaises(TypeError, print, '', sep=3) self.assertRaises(TypeError, print, '', end=3) self.assertRaises(AttributeError, print, '', file='') def test_print_flush(self): # operation of the flush flag class filelike: def __init__(self): self.written = '' self.flushed = 0 def write(self, str): self.written += str def flush(self): self.flushed += 1 f = filelike() print(1, file=f, end='', flush=True) print(2, file=f, end='', flush=True) print(3, file=f, flush=False) self.assertEqual(f.written, '123\n') self.assertEqual(f.flushed, 2) # ensure exceptions from flush are passed through class noflush: def write(self, str): pass def flush(self): raise RuntimeError self.assertRaises(RuntimeError, print, 1, file=noflush(), flush=True) class TestPy2MigrationHint(unittest.TestCase): """Test that correct hint is produced analogous to Python3 syntax, if print statement is executed as in Python 2. """ def test_normal_string(self): python2_print_str = 'print "Hello World"' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print("Hello World")', str(context.exception)) def test_string_with_soft_space(self): python2_print_str = 'print "Hello World",' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print("Hello World", end=" ")', str(context.exception)) def test_string_with_excessive_whitespace(self): python2_print_str = 'print "Hello World", ' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print("Hello World", end=" ")', str(context.exception)) def test_string_with_leading_whitespace(self): python2_print_str = '''if 1: print "Hello World" ''' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print("Hello World")', str(context.exception)) # bpo-32685: Suggestions for print statement should be proper when # it is in the same line as the header of a compound statement # and/or followed by a semicolon def test_string_with_semicolon(self): python2_print_str = 'print p;' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print(p)', str(context.exception)) def test_string_in_loop_on_same_line(self): python2_print_str = 'for i in s: print i' with self.assertRaises(SyntaxError) as context: exec(python2_print_str) self.assertIn('print(i)', str(context.exception)) def test_stream_redirection_hint_for_py2_migration(self): # Test correct hint produced for Py2 redirection syntax with self.assertRaises(TypeError) as context: print >> sys.stderr, "message" self.assertIn('Did you mean "print(<message>, ' 'file=<output_stream>)"?', str(context.exception)) # Test correct hint is produced in the case where RHS implements # __rrshift__ but returns NotImplemented with self.assertRaises(TypeError) as context: print >> 42 self.assertIn('Did you mean "print(<message>, ' 'file=<output_stream>)"?', str(context.exception)) # Test stream redirection hint is specific to print with self.assertRaises(TypeError) as context: max >> sys.stderr self.assertNotIn('Did you mean ', str(context.exception)) # Test stream redirection hint is specific to rshift with self.assertRaises(TypeError) as context: print << sys.stderr self.assertNotIn('Did you mean', str(context.exception)) # Ensure right operand implementing rrshift still works class OverrideRRShift: def __rrshift__(self, lhs): return 42 # Force result independent of LHS self.assertEqual(print >> OverrideRRShift(), 42) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bisect_cmd.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bisect_cmd.py
#!/usr/bin/env python3 """ Command line tool to bisect failing CPython tests. Find the test_os test method which alters the environment: ./python -m test.bisect_cmd --fail-env-changed test_os Find a reference leak in "test_os", write the list of failing tests into the "bisect" file: ./python -m test.bisect_cmd -o bisect -R 3:3 test_os Load an existing list of tests from a file using -i option: ./python -m test --list-cases -m FileTests test_os > tests ./python -m test.bisect_cmd -i tests test_os """ import argparse import datetime import os.path import math import random import subprocess import sys import tempfile import time def write_tests(filename, tests): with open(filename, "w") as fp: for name in tests: print(name, file=fp) fp.flush() def write_output(filename, tests): if not filename: return print("Writing %s tests into %s" % (len(tests), filename)) write_tests(filename, tests) return filename def format_shell_args(args): return ' '.join(args) def list_cases(args): cmd = [sys.executable, '-m', 'test', '--list-cases'] cmd.extend(args.test_args) proc = subprocess.run(cmd, stdout=subprocess.PIPE, universal_newlines=True) exitcode = proc.returncode if exitcode: cmd = format_shell_args(cmd) print("Failed to list tests: %s failed with exit code %s" % (cmd, exitcode)) sys.exit(exitcode) tests = proc.stdout.splitlines() return tests def run_tests(args, tests, huntrleaks=None): tmp = tempfile.mktemp() try: write_tests(tmp, tests) cmd = [sys.executable, '-m', 'test', '--matchfile', tmp] cmd.extend(args.test_args) print("+ %s" % format_shell_args(cmd)) proc = subprocess.run(cmd) return proc.returncode finally: if os.path.exists(tmp): os.unlink(tmp) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help='Test names produced by --list-tests written ' 'into a file. If not set, run --list-tests') parser.add_argument('-o', '--output', help='Result of the bisection') parser.add_argument('-n', '--max-tests', type=int, default=1, help='Maximum number of tests to stop the bisection ' '(default: 1)') parser.add_argument('-N', '--max-iter', type=int, default=100, help='Maximum number of bisection iterations ' '(default: 100)') # FIXME: document that following arguments are test arguments args, test_args = parser.parse_known_args() args.test_args = test_args return args def main(): args = parse_args() if args.input: with open(args.input) as fp: tests = [line.strip() for line in fp] else: tests = list_cases(args) print("Start bisection with %s tests" % len(tests)) print("Test arguments: %s" % format_shell_args(args.test_args)) print("Bisection will stop when getting %s or less tests " "(-n/--max-tests option), or after %s iterations " "(-N/--max-iter option)" % (args.max_tests, args.max_iter)) output = write_output(args.output, tests) print() start_time = time.monotonic() iteration = 1 try: while len(tests) > args.max_tests and iteration <= args.max_iter: ntest = len(tests) ntest = max(ntest // 2, 1) subtests = random.sample(tests, ntest) print("[+] Iteration %s: run %s tests/%s" % (iteration, len(subtests), len(tests))) print() exitcode = run_tests(args, subtests) print("ran %s tests/%s" % (ntest, len(tests))) print("exit", exitcode) if exitcode: print("Tests failed: continuing with this subtest") tests = subtests output = write_output(args.output, tests) else: print("Tests succeeded: skipping this subtest, trying a new subset") print() iteration += 1 except KeyboardInterrupt: print() print("Bisection interrupted!") print() print("Tests (%s):" % len(tests)) for test in tests: print("* %s" % test) print() if output: print("Output written into %s" % output) dt = math.ceil(time.monotonic() - start_time) if len(tests) <= args.max_tests: print("Bisection completed in %s iterations and %s" % (iteration, datetime.timedelta(seconds=dt))) sys.exit(1) else: print("Bisection failed after %s iterations and %s" % (iteration, datetime.timedelta(seconds=dt))) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sys_settrace.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sys_settrace.py
# Testing the line trace facility. from test import support import unittest import sys import difflib import gc from functools import wraps import asyncio class tracecontext: """Context manager that traces its enter and exit.""" def __init__(self, output, value): self.output = output self.value = value def __enter__(self): self.output.append(self.value) def __exit__(self, *exc_info): self.output.append(-self.value) class asynctracecontext: """Asynchronous context manager that traces its aenter and aexit.""" def __init__(self, output, value): self.output = output self.value = value async def __aenter__(self): self.output.append(self.value) async def __aexit__(self, *exc_info): self.output.append(-self.value) async def asynciter(iterable): """Convert an iterable to an asynchronous iterator.""" for x in iterable: yield x # A very basic example. If this fails, we're in deep trouble. def basic(): return 1 basic.events = [(0, 'call'), (1, 'line'), (1, 'return')] # Many of the tests below are tricky because they involve pass statements. # If there is implicit control flow around a pass statement (in an except # clause or else clause) under what conditions do you set a line number # following that clause? # The entire "while 0:" statement is optimized away. No code # exists for it, so the line numbers skip directly from "del x" # to "x = 1". def arigo_example(): x = 1 del x while 0: pass x = 1 arigo_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (5, 'line'), (5, 'return')] # check that lines consisting of just one instruction get traced: def one_instr_line(): x = 1 del x x = 1 one_instr_line.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (3, 'return')] def no_pop_tops(): # 0 x = 1 # 1 for a in range(2): # 2 if a: # 3 x = 1 # 4 else: # 5 x = 1 # 6 no_pop_tops.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (6, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (2, 'line'), (2, 'return')] def no_pop_blocks(): y = 1 while not y: bla x = 1 no_pop_blocks.events = [(0, 'call'), (1, 'line'), (2, 'line'), (4, 'line'), (4, 'return')] def called(): # line -3 x = 1 def call(): # line 0 called() call.events = [(0, 'call'), (1, 'line'), (-3, 'call'), (-2, 'line'), (-2, 'return'), (1, 'return')] def raises(): raise Exception def test_raise(): try: raises() except Exception as exc: x = 1 test_raise.events = [(0, 'call'), (1, 'line'), (2, 'line'), (-3, 'call'), (-2, 'line'), (-2, 'exception'), (-2, 'return'), (2, 'exception'), (3, 'line'), (4, 'line'), (4, 'return')] def _settrace_and_return(tracefunc): sys.settrace(tracefunc) sys._getframe().f_back.f_trace = tracefunc def settrace_and_return(tracefunc): _settrace_and_return(tracefunc) settrace_and_return.events = [(1, 'return')] def _settrace_and_raise(tracefunc): sys.settrace(tracefunc) sys._getframe().f_back.f_trace = tracefunc raise RuntimeError def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) except RuntimeError as exc: pass settrace_and_raise.events = [(2, 'exception'), (3, 'line'), (4, 'line'), (4, 'return')] # implicit return example # This test is interesting because of the else: pass # part of the code. The code generate for the true # part of the if contains a jump past the else branch. # The compiler then generates an implicit "return None" # Internally, the compiler visits the pass statement # and stores its line number for use on the next instruction. # The next instruction is the implicit return None. def ireturn_example(): a = 5 b = 5 if a == b: b = a+1 else: pass ireturn_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (6, 'line'), (6, 'return')] # Tight loop with while(1) example (SF #765624) def tightloop_example(): items = range(0, 3) try: i = 0 while 1: b = items[i]; i+=1 except IndexError: pass tightloop_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (5, 'line'), (5, 'line'), (5, 'line'), (5, 'line'), (5, 'exception'), (6, 'line'), (7, 'line'), (7, 'return')] def tighterloop_example(): items = range(1, 4) try: i = 0 while 1: i = items[i] except IndexError: pass tighterloop_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (4, 'line'), (4, 'line'), (4, 'line'), (4, 'exception'), (5, 'line'), (6, 'line'), (6, 'return')] def generator_function(): try: yield True "continued" finally: "finally" def generator_example(): # any() will leave the generator before its end x = any(generator_function()) # the following lines were not traced for x in range(10): y = x generator_example.events = ([(0, 'call'), (2, 'line'), (-6, 'call'), (-5, 'line'), (-4, 'line'), (-4, 'return'), (-4, 'call'), (-4, 'exception'), (-1, 'line'), (-1, 'return')] + [(5, 'line'), (6, 'line')] * 10 + [(5, 'line'), (5, 'return')]) class Tracer: def __init__(self, trace_line_events=None, trace_opcode_events=None): self.trace_line_events = trace_line_events self.trace_opcode_events = trace_opcode_events self.events = [] def _reconfigure_frame(self, frame): if self.trace_line_events is not None: frame.f_trace_lines = self.trace_line_events if self.trace_opcode_events is not None: frame.f_trace_opcodes = self.trace_opcode_events def trace(self, frame, event, arg): self._reconfigure_frame(frame) self.events.append((frame.f_lineno, event)) return self.trace def traceWithGenexp(self, frame, event, arg): self._reconfigure_frame(frame) (o for o in [1]) self.events.append((frame.f_lineno, event)) return self.trace class TraceTestCase(unittest.TestCase): # Disable gc collection when tracing, otherwise the # deallocators may be traced as well. def setUp(self): self.using_gc = gc.isenabled() gc.disable() self.addCleanup(sys.settrace, sys.gettrace()) def tearDown(self): if self.using_gc: gc.enable() @staticmethod def make_tracer(): """Helper to allow test subclasses to configure tracers differently""" return Tracer() def compare_events(self, line_offset, events, expected_events): events = [(l - line_offset, e) for (l, e) in events] if events != expected_events: self.fail( "events did not match expectation:\n" + "\n".join(difflib.ndiff([str(x) for x in expected_events], [str(x) for x in events]))) def run_and_compare(self, func, events): tracer = self.make_tracer() sys.settrace(tracer.trace) func() sys.settrace(None) self.compare_events(func.__code__.co_firstlineno, tracer.events, events) def run_test(self, func): self.run_and_compare(func, func.events) def run_test2(self, func): tracer = self.make_tracer() func(tracer.trace) sys.settrace(None) self.compare_events(func.__code__.co_firstlineno, tracer.events, func.events) def test_set_and_retrieve_none(self): sys.settrace(None) assert sys.gettrace() is None def test_set_and_retrieve_func(self): def fn(*args): pass sys.settrace(fn) try: assert sys.gettrace() is fn finally: sys.settrace(None) def test_01_basic(self): self.run_test(basic) def test_02_arigo(self): self.run_test(arigo_example) def test_03_one_instr(self): self.run_test(one_instr_line) def test_04_no_pop_blocks(self): self.run_test(no_pop_blocks) def test_05_no_pop_tops(self): self.run_test(no_pop_tops) def test_06_call(self): self.run_test(call) def test_07_raise(self): self.run_test(test_raise) def test_08_settrace_and_return(self): self.run_test2(settrace_and_return) def test_09_settrace_and_raise(self): self.run_test2(settrace_and_raise) def test_10_ireturn(self): self.run_test(ireturn_example) def test_11_tightloop(self): self.run_test(tightloop_example) def test_12_tighterloop(self): self.run_test(tighterloop_example) def test_13_genexp(self): self.run_test(generator_example) # issue1265: if the trace function contains a generator, # and if the traced function contains another generator # that is not completely exhausted, the trace stopped. # Worse: the 'finally' clause was not invoked. tracer = self.make_tracer() sys.settrace(tracer.traceWithGenexp) generator_example() sys.settrace(None) self.compare_events(generator_example.__code__.co_firstlineno, tracer.events, generator_example.events) def test_14_onliner_if(self): def onliners(): if True: x=False else: x=True return 0 self.run_and_compare( onliners, [(0, 'call'), (1, 'line'), (3, 'line'), (3, 'return')]) def test_15_loops(self): # issue1750076: "while" expression is skipped by debugger def for_example(): for x in range(2): pass self.run_and_compare( for_example, [(0, 'call'), (1, 'line'), (2, 'line'), (1, 'line'), (2, 'line'), (1, 'line'), (1, 'return')]) def while_example(): # While expression should be traced on every loop x = 2 while x > 0: x -= 1 self.run_and_compare( while_example, [(0, 'call'), (2, 'line'), (3, 'line'), (4, 'line'), (3, 'line'), (4, 'line'), (3, 'line'), (3, 'return')]) def test_16_blank_lines(self): namespace = {} exec("def f():\n" + "\n" * 256 + " pass", namespace) self.run_and_compare( namespace["f"], [(0, 'call'), (257, 'line'), (257, 'return')]) def test_17_none_f_trace(self): # Issue 20041: fix TypeError when f_trace is set to None. def func(): sys._getframe().f_trace = None lineno = 2 self.run_and_compare(func, [(0, 'call'), (1, 'line')]) class SkipLineEventsTraceTestCase(TraceTestCase): """Repeat the trace tests, but with per-line events skipped""" def compare_events(self, line_offset, events, expected_events): skip_line_events = [e for e in expected_events if e[1] != 'line'] super().compare_events(line_offset, events, skip_line_events) @staticmethod def make_tracer(): return Tracer(trace_line_events=False) @support.cpython_only class TraceOpcodesTestCase(TraceTestCase): """Repeat the trace tests, but with per-opcodes events enabled""" def compare_events(self, line_offset, events, expected_events): skip_opcode_events = [e for e in events if e[1] != 'opcode'] if len(events) > 1: self.assertLess(len(skip_opcode_events), len(events), msg="No 'opcode' events received by the tracer") super().compare_events(line_offset, skip_opcode_events, expected_events) @staticmethod def make_tracer(): return Tracer(trace_opcode_events=True) class RaisingTraceFuncTestCase(unittest.TestCase): def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) def trace(self, frame, event, arg): """A trace function that raises an exception in response to a specific trace event.""" if event == self.raiseOnEvent: raise ValueError # just something that isn't RuntimeError else: return self.trace def f(self): """The function to trace; raises an exception if that's the case we're testing, so that the 'exception' trace event fires.""" if self.raiseOnEvent == 'exception': x = 0 y = 1/x else: return 1 def run_test_for_event(self, event): """Tests that an exception raised in response to the given event is handled OK.""" self.raiseOnEvent = event try: for i in range(sys.getrecursionlimit() + 1): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail("exception not raised!") except RuntimeError: self.fail("recursion counter not reset") # Test the handling of exceptions raised by each kind of trace event. def test_call(self): self.run_test_for_event('call') def test_line(self): self.run_test_for_event('line') def test_return(self): self.run_test_for_event('return') def test_exception(self): self.run_test_for_event('exception') def test_trash_stack(self): def f(): for i in range(5): print(i) # line tracing will raise an exception at this line def g(frame, why, extra): if (why == 'line' and frame.f_lineno == f.__code__.co_firstlineno + 2): raise RuntimeError("i am crashing") return g sys.settrace(g) try: f() except RuntimeError: # the test is really that this doesn't segfault: import gc gc.collect() else: self.fail("exception not propagated") def test_exception_arguments(self): def f(): x = 0 # this should raise an error x.no_such_attr def g(frame, event, arg): if (event == 'exception'): type, exception, trace = arg self.assertIsInstance(exception, Exception) return g existing = sys.gettrace() try: sys.settrace(g) try: f() except AttributeError: # this is expected pass finally: sys.settrace(existing) # 'Jump' tests: assigning to frame.f_lineno within a trace function # moves the execution position - it's how debuggers implement a Jump # command (aka. "Set next statement"). class JumpTracer: """Defines a trace function that jumps from one place to another.""" def __init__(self, function, jumpFrom, jumpTo, event='line', decorated=False): self.code = function.__code__ self.jumpFrom = jumpFrom self.jumpTo = jumpTo self.event = event self.firstLine = None if decorated else self.code.co_firstlineno self.done = False def trace(self, frame, event, arg): if self.done: return # frame.f_code.co_firstlineno is the first line of the decorator when # 'function' is decorated and the decorator may be written using # multiple physical lines when it is too long. Use the first line # trace event in 'function' to find the first line of 'function'. if (self.firstLine is None and frame.f_code == self.code and event == 'line'): self.firstLine = frame.f_lineno - 1 if (event == self.event and self.firstLine and frame.f_lineno == self.firstLine + self.jumpFrom): f = frame while f is not None and f.f_code != self.code: f = f.f_back if f is not None: # Cope with non-integer self.jumpTo (because of # no_jump_to_non_integers below). try: frame.f_lineno = self.firstLine + self.jumpTo except TypeError: frame.f_lineno = self.jumpTo self.done = True return self.trace # This verifies the line-numbers-must-be-integers rule. def no_jump_to_non_integers(output): try: output.append(2) except ValueError as e: output.append('integer' in str(e)) # This verifies that you can't set f_lineno via _getframe or similar # trickery. def no_jump_without_trace_function(): try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno except ValueError as e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e): raise else: # Something's wrong - the expected exception wasn't raised. raise AssertionError("Trace-function-less jump failed to fail") class JumpTestCase(unittest.TestCase): def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) sys.settrace(None) def compare_jump_output(self, expected, received): if received != expected: self.fail( "Outputs don't match:\n" + "Expected: " + repr(expected) + "\n" + "Received: " + repr(received)) def run_test(self, func, jumpFrom, jumpTo, expected, error=None, event='line', decorated=False): tracer = JumpTracer(func, jumpFrom, jumpTo, event, decorated) sys.settrace(tracer.trace) output = [] if error is None: func(output) else: with self.assertRaisesRegex(*error): func(output) sys.settrace(None) self.compare_jump_output(expected, output) def run_async_test(self, func, jumpFrom, jumpTo, expected, error=None, event='line', decorated=False): tracer = JumpTracer(func, jumpFrom, jumpTo, event, decorated) sys.settrace(tracer.trace) output = [] if error is None: asyncio.run(func(output)) else: with self.assertRaisesRegex(*error): asyncio.run(func(output)) sys.settrace(None) self.compare_jump_output(expected, output) def jump_test(jumpFrom, jumpTo, expected, error=None, event='line'): """Decorator that creates a test that makes a jump from one place to another in the following code. """ def decorator(func): @wraps(func) def test(self): self.run_test(func, jumpFrom, jumpTo, expected, error=error, event=event, decorated=True) return test return decorator def async_jump_test(jumpFrom, jumpTo, expected, error=None, event='line'): """Decorator that creates a test that makes a jump from one place to another in the following asynchronous code. """ def decorator(func): @wraps(func) def test(self): self.run_async_test(func, jumpFrom, jumpTo, expected, error=error, event=event, decorated=True) return test return decorator ## The first set of 'jump' tests are for things that are allowed: @jump_test(1, 3, [3]) def test_jump_simple_forwards(output): output.append(1) output.append(2) output.append(3) @jump_test(2, 1, [1, 1, 2]) def test_jump_simple_backwards(output): output.append(1) output.append(2) @jump_test(3, 5, [2, 5]) def test_jump_out_of_block_forwards(output): for i in 1, 2: output.append(2) for j in [3]: # Also tests jumping over a block output.append(4) output.append(5) @jump_test(6, 1, [1, 3, 5, 1, 3, 5, 6, 7]) def test_jump_out_of_block_backwards(output): output.append(1) for i in [1]: output.append(3) for j in [2]: # Also tests jumping over a block output.append(5) output.append(6) output.append(7) @async_jump_test(4, 5, [3, 5]) async def test_jump_out_of_async_for_block_forwards(output): for i in [1]: async for i in asynciter([1, 2]): output.append(3) output.append(4) output.append(5) @async_jump_test(5, 2, [2, 4, 2, 4, 5, 6]) async def test_jump_out_of_async_for_block_backwards(output): for i in [1]: output.append(2) async for i in asynciter([1]): output.append(4) output.append(5) output.append(6) @jump_test(1, 2, [3]) def test_jump_to_codeless_line(output): output.append(1) # Jumping to this line should skip to the next one. output.append(3) @jump_test(2, 2, [1, 2, 3]) def test_jump_to_same_line(output): output.append(1) output.append(2) output.append(3) # Tests jumping within a finally block, and over one. @jump_test(4, 9, [2, 9]) def test_jump_in_nested_finally(output): try: output.append(2) finally: output.append(4) try: output.append(6) finally: output.append(8) output.append(9) @jump_test(6, 7, [2, 7], (ZeroDivisionError, '')) def test_jump_in_nested_finally_2(output): try: output.append(2) 1/0 return finally: output.append(6) output.append(7) output.append(8) @jump_test(6, 11, [2, 11], (ZeroDivisionError, '')) def test_jump_in_nested_finally_3(output): try: output.append(2) 1/0 return finally: output.append(6) try: output.append(8) finally: output.append(10) output.append(11) output.append(12) @jump_test(3, 4, [1, 4]) def test_jump_infinite_while_loop(output): output.append(1) while True: output.append(3) output.append(4) @jump_test(2, 3, [1, 3]) def test_jump_forwards_out_of_with_block(output): with tracecontext(output, 1): output.append(2) output.append(3) @async_jump_test(2, 3, [1, 3]) async def test_jump_forwards_out_of_async_with_block(output): async with asynctracecontext(output, 1): output.append(2) output.append(3) @jump_test(3, 1, [1, 2, 1, 2, 3, -2]) def test_jump_backwards_out_of_with_block(output): output.append(1) with tracecontext(output, 2): output.append(3) @async_jump_test(3, 1, [1, 2, 1, 2, 3, -2]) async def test_jump_backwards_out_of_async_with_block(output): output.append(1) async with asynctracecontext(output, 2): output.append(3) @jump_test(2, 5, [5]) def test_jump_forwards_out_of_try_finally_block(output): try: output.append(2) finally: output.append(4) output.append(5) @jump_test(3, 1, [1, 1, 3, 5]) def test_jump_backwards_out_of_try_finally_block(output): output.append(1) try: output.append(3) finally: output.append(5) @jump_test(2, 6, [6]) def test_jump_forwards_out_of_try_except_block(output): try: output.append(2) except: output.append(4) raise output.append(6) @jump_test(3, 1, [1, 1, 3]) def test_jump_backwards_out_of_try_except_block(output): output.append(1) try: output.append(3) except: output.append(5) raise @jump_test(5, 7, [4, 7, 8]) def test_jump_between_except_blocks(output): try: 1/0 except ZeroDivisionError: output.append(4) output.append(5) except FloatingPointError: output.append(7) output.append(8) @jump_test(5, 6, [4, 6, 7]) def test_jump_within_except_block(output): try: 1/0 except: output.append(4) output.append(5) output.append(6) output.append(7) @jump_test(2, 4, [1, 4, 5, -4]) def test_jump_across_with(output): output.append(1) with tracecontext(output, 2): output.append(3) with tracecontext(output, 4): output.append(5) @async_jump_test(2, 4, [1, 4, 5, -4]) async def test_jump_across_async_with(output): output.append(1) async with asynctracecontext(output, 2): output.append(3) async with asynctracecontext(output, 4): output.append(5) @jump_test(4, 5, [1, 3, 5, 6]) def test_jump_out_of_with_block_within_for_block(output): output.append(1) for i in [1]: with tracecontext(output, 3): output.append(4) output.append(5) output.append(6) @async_jump_test(4, 5, [1, 3, 5, 6]) async def test_jump_out_of_async_with_block_within_for_block(output): output.append(1) for i in [1]: async with asynctracecontext(output, 3): output.append(4) output.append(5) output.append(6) @jump_test(4, 5, [1, 2, 3, 5, -2, 6]) def test_jump_out_of_with_block_within_with_block(output): output.append(1) with tracecontext(output, 2): with tracecontext(output, 3): output.append(4) output.append(5) output.append(6) @async_jump_test(4, 5, [1, 2, 3, 5, -2, 6]) async def test_jump_out_of_async_with_block_within_with_block(output): output.append(1) with tracecontext(output, 2): async with asynctracecontext(output, 3): output.append(4) output.append(5) output.append(6) @jump_test(5, 6, [2, 4, 6, 7]) def test_jump_out_of_with_block_within_finally_block(output): try: output.append(2) finally: with tracecontext(output, 4): output.append(5) output.append(6) output.append(7) @async_jump_test(5, 6, [2, 4, 6, 7]) async def test_jump_out_of_async_with_block_within_finally_block(output): try: output.append(2) finally: async with asynctracecontext(output, 4): output.append(5) output.append(6) output.append(7) @jump_test(8, 11, [1, 3, 5, 11, 12]) def test_jump_out_of_complex_nested_blocks(output): output.append(1) for i in [1]: output.append(3) for j in [1, 2]: output.append(5) try: for k in [1, 2]: output.append(8) finally: output.append(10) output.append(11) output.append(12) @jump_test(3, 5, [1, 2, 5]) def test_jump_out_of_with_assignment(output): output.append(1) with tracecontext(output, 2) \ as x: output.append(4) output.append(5) @async_jump_test(3, 5, [1, 2, 5]) async def test_jump_out_of_async_with_assignment(output): output.append(1) async with asynctracecontext(output, 2) \ as x: output.append(4) output.append(5) @jump_test(3, 6, [1, 6, 8, 9]) def test_jump_over_return_in_try_finally_block(output): output.append(1) try: output.append(3) if not output: # always false return output.append(6) finally: output.append(8) output.append(9) @jump_test(5, 8, [1, 3, 8, 10, 11, 13]) def test_jump_over_break_in_try_finally_block(output): output.append(1) while True: output.append(3) try: output.append(5) if not output: # always false break output.append(8) finally: output.append(10) output.append(11) break output.append(13) @jump_test(1, 7, [7, 8]) def test_jump_over_for_block_before_else(output): output.append(1) if not output: # always false for i in [3]: output.append(4) else: output.append(6) output.append(7) output.append(8) @async_jump_test(1, 7, [7, 8]) async def test_jump_over_async_for_block_before_else(output): output.append(1) if not output: # always false async for i in asynciter([3]): output.append(4) else: output.append(6) output.append(7) output.append(8) # The second set of 'jump' tests are for things that are not allowed: @jump_test(2, 3, [1], (ValueError, 'after')) def test_no_jump_too_far_forwards(output): output.append(1) output.append(2) @jump_test(2, -2, [1], (ValueError, 'before')) def test_no_jump_too_far_backwards(output): output.append(1) output.append(2) # Test each kind of 'except' line. @jump_test(2, 3, [4], (ValueError, 'except')) def test_no_jump_to_except_1(output): try: output.append(2) except: output.append(4) raise @jump_test(2, 3, [4], (ValueError, 'except')) def test_no_jump_to_except_2(output): try: output.append(2) except ValueError: output.append(4) raise @jump_test(2, 3, [4], (ValueError, 'except')) def test_no_jump_to_except_3(output): try: output.append(2) except ValueError as e: output.append(4) raise e @jump_test(2, 3, [4], (ValueError, 'except'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_userlist.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_userlist.py
# Check every path through every method of UserList from collections import UserList from test import list_tests import unittest class UserListTest(list_tests.CommonTest): type2test = UserList def test_getslice(self): super().test_getslice() l = [0, 1, 2, 3, 4] u = self.type2test(l) for i in range(-3, 6): self.assertEqual(u[:i], l[:i]) self.assertEqual(u[i:], l[i:]) for j in range(-3, 6): self.assertEqual(u[i:j], l[i:j]) def test_slice_type(self): l = [0, 1, 2, 3, 4] u = UserList(l) self.assertIsInstance(u[:], u.__class__) self.assertEqual(u[:],u) def test_add_specials(self): u = UserList("spam") u2 = u + "eggs" self.assertEqual(u2, list("spameggs")) def test_radd_specials(self): u = UserList("eggs") u2 = "spam" + u self.assertEqual(u2, list("spameggs")) u2 = u.__radd__(UserList("spam")) self.assertEqual(u2, list("spameggs")) def test_iadd(self): super().test_iadd() u = [0, 1] u += UserList([0, 1]) self.assertEqual(u, [0, 1, 0, 1]) def test_mixedcmp(self): u = self.type2test([0, 1]) self.assertEqual(u, [0, 1]) self.assertNotEqual(u, [0]) self.assertNotEqual(u, [0, 2]) def test_mixedadd(self): u = self.type2test([0, 1]) self.assertEqual(u + [], u) self.assertEqual(u + [2], [0, 1, 2]) def test_getitemoverwriteiter(self): # Verify that __getitem__ overrides *are* recognized by __iter__ class T(self.type2test): def __getitem__(self, key): return str(key) + '!!!' self.assertEqual(next(iter(T((1,2)))), "0!!!") def test_userlist_copy(self): u = self.type2test([6, 8, 1, 9, 1]) v = u.copy() self.assertEqual(u, v) self.assertEqual(type(u), type(v)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dbm_dumb.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dbm_dumb.py
"""Test script for the dumbdbm module Original by Roger E. Masse """ import io import operator import os import stat import unittest import dbm.dumb as dumbdbm from test import support from functools import partial _fname = support.TESTFN def _delete_files(): for ext in [".dir", ".dat", ".bak"]: try: os.unlink(_fname + ext) except OSError: pass class DumbDBMTestCase(unittest.TestCase): _dict = {b'0': b'', b'a': b'Python:', b'b': b'Programming', b'c': b'the', b'd': b'way', b'f': b'Guido', b'g': b'intended', '\u00fc'.encode('utf-8') : b'!', } def test_dumbdbm_creation(self): f = dumbdbm.open(_fname, 'c') self.assertEqual(list(f.keys()), []) for key in self._dict: f[key] = self._dict[key] self.read_helper(f) f.close() @unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()') @unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()') def test_dumbdbm_creation_mode(self): try: old_umask = os.umask(0o002) f = dumbdbm.open(_fname, 'c', 0o637) f.close() finally: os.umask(old_umask) expected_mode = 0o635 if os.name != 'posix': # Windows only supports setting the read-only attribute. # This shouldn't fail, but doesn't work like Unix either. expected_mode = 0o666 import stat st = os.stat(_fname + '.dat') self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) def test_close_twice(self): f = dumbdbm.open(_fname) f[b'a'] = b'b' self.assertEqual(f[b'a'], b'b') f.close() f.close() def test_dumbdbm_modification(self): self.init_db() f = dumbdbm.open(_fname, 'w') self._dict[b'g'] = f[b'g'] = b"indented" self.read_helper(f) # setdefault() works as in the dict interface self.assertEqual(f.setdefault(b'xxx', b'foo'), b'foo') self.assertEqual(f[b'xxx'], b'foo') f.close() def test_dumbdbm_read(self): self.init_db() f = dumbdbm.open(_fname, 'r') self.read_helper(f) with self.assertWarnsRegex(DeprecationWarning, 'The database is opened for reading only'): f[b'g'] = b'x' with self.assertWarnsRegex(DeprecationWarning, 'The database is opened for reading only'): del f[b'a'] # get() works as in the dict interface self.assertEqual(f.get(b'b'), self._dict[b'b']) self.assertEqual(f.get(b'xxx', b'foo'), b'foo') self.assertIsNone(f.get(b'xxx')) with self.assertRaises(KeyError): f[b'xxx'] f.close() def test_dumbdbm_keys(self): self.init_db() f = dumbdbm.open(_fname) keys = self.keys_helper(f) f.close() def test_write_contains(self): f = dumbdbm.open(_fname) f[b'1'] = b'hello' self.assertIn(b'1', f) f.close() def test_write_write_read(self): # test for bug #482460 f = dumbdbm.open(_fname) f[b'1'] = b'hello' f[b'1'] = b'hello2' f.close() f = dumbdbm.open(_fname) self.assertEqual(f[b'1'], b'hello2') f.close() def test_str_read(self): self.init_db() f = dumbdbm.open(_fname, 'r') self.assertEqual(f['\u00fc'], self._dict['\u00fc'.encode('utf-8')]) def test_str_write_contains(self): self.init_db() f = dumbdbm.open(_fname) f['\u00fc'] = b'!' f['1'] = 'a' f.close() f = dumbdbm.open(_fname, 'r') self.assertIn('\u00fc', f) self.assertEqual(f['\u00fc'.encode('utf-8')], self._dict['\u00fc'.encode('utf-8')]) self.assertEqual(f[b'1'], b'a') def test_line_endings(self): # test for bug #1172763: dumbdbm would die if the line endings # weren't what was expected. f = dumbdbm.open(_fname) f[b'1'] = b'hello' f[b'2'] = b'hello2' f.close() # Mangle the file by changing the line separator to Windows or Unix with io.open(_fname + '.dir', 'rb') as file: data = file.read() if os.linesep == '\n': data = data.replace(b'\n', b'\r\n') else: data = data.replace(b'\r\n', b'\n') with io.open(_fname + '.dir', 'wb') as file: file.write(data) f = dumbdbm.open(_fname) self.assertEqual(f[b'1'], b'hello') self.assertEqual(f[b'2'], b'hello2') def read_helper(self, f): keys = self.keys_helper(f) for key in self._dict: self.assertEqual(self._dict[key], f[key]) def init_db(self): f = dumbdbm.open(_fname, 'n') for k in self._dict: f[k] = self._dict[k] f.close() def keys_helper(self, f): keys = sorted(f.keys()) dkeys = sorted(self._dict.keys()) self.assertEqual(keys, dkeys) return keys # Perform randomized operations. This doesn't make assumptions about # what *might* fail. def test_random(self): import random d = {} # mirror the database for dummy in range(5): f = dumbdbm.open(_fname) for dummy in range(100): k = random.choice('abcdefghijklm') if random.random() < 0.2: if k in d: del d[k] del f[k] else: v = random.choice((b'a', b'b', b'c')) * random.randrange(10000) d[k] = v f[k] = v self.assertEqual(f[k], v) f.close() f = dumbdbm.open(_fname) expected = sorted((k.encode("latin-1"), v) for k, v in d.items()) got = sorted(f.items()) self.assertEqual(expected, got) f.close() def test_context_manager(self): with dumbdbm.open(_fname, 'c') as db: db["dumbdbm context manager"] = "context manager" with dumbdbm.open(_fname, 'r') as db: self.assertEqual(list(db.keys()), [b"dumbdbm context manager"]) with self.assertRaises(dumbdbm.error): db.keys() def test_check_closed(self): f = dumbdbm.open(_fname, 'c') f.close() for meth in (partial(operator.delitem, f), partial(operator.setitem, f, 'b'), partial(operator.getitem, f), partial(operator.contains, f)): with self.assertRaises(dumbdbm.error) as cm: meth('test') self.assertEqual(str(cm.exception), "DBM object has already been closed") for meth in (operator.methodcaller('keys'), operator.methodcaller('iterkeys'), operator.methodcaller('items'), len): with self.assertRaises(dumbdbm.error) as cm: meth(f) self.assertEqual(str(cm.exception), "DBM object has already been closed") def test_create_new(self): with dumbdbm.open(_fname, 'n') as f: for k in self._dict: f[k] = self._dict[k] with dumbdbm.open(_fname, 'n') as f: self.assertEqual(f.keys(), []) def test_eval(self): with open(_fname + '.dir', 'w') as stream: stream.write("str(print('Hacked!')), 0\n") with support.captured_stdout() as stdout: with self.assertRaises(ValueError): with dumbdbm.open(_fname) as f: pass self.assertEqual(stdout.getvalue(), '') def test_warn_on_ignored_flags(self): for value in ('r', 'w'): _delete_files() with self.assertWarnsRegex(DeprecationWarning, "The database file is missing, the " "semantics of the 'c' flag will " "be used."): f = dumbdbm.open(_fname, value) f.close() def test_missing_index(self): with dumbdbm.open(_fname, 'n') as f: pass os.unlink(_fname + '.dir') for value in ('r', 'w'): with self.assertWarnsRegex(DeprecationWarning, "The index file is missing, the " "semantics of the 'c' flag will " "be used."): f = dumbdbm.open(_fname, value) f.close() self.assertEqual(os.path.exists(_fname + '.dir'), value == 'w') self.assertFalse(os.path.exists(_fname + '.bak')) def test_invalid_flag(self): for flag in ('x', 'rf', None): with self.assertWarnsRegex(DeprecationWarning, "Flag must be one of " "'r', 'w', 'c', or 'n'"): f = dumbdbm.open(_fname, flag) f.close() @unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()') def test_readonly_files(self): with support.temp_dir() as dir: fname = os.path.join(dir, 'db') with dumbdbm.open(fname, 'n') as f: self.assertEqual(list(f.keys()), []) for key in self._dict: f[key] = self._dict[key] os.chmod(fname + ".dir", stat.S_IRUSR) os.chmod(fname + ".dat", stat.S_IRUSR) os.chmod(dir, stat.S_IRUSR|stat.S_IXUSR) with dumbdbm.open(fname, 'r') as f: self.assertEqual(sorted(f.keys()), sorted(self._dict)) f.close() # don't write @unittest.skipUnless(support.TESTFN_NONASCII, 'requires OS support of non-ASCII encodings') def test_nonascii_filename(self): filename = support.TESTFN_NONASCII for suffix in ['.dir', '.dat', '.bak']: self.addCleanup(support.unlink, filename + suffix) with dumbdbm.open(filename, 'c') as db: db[b'key'] = b'value' self.assertTrue(os.path.exists(filename + '.dat')) self.assertTrue(os.path.exists(filename + '.dir')) with dumbdbm.open(filename, 'r') as db: self.assertEqual(list(db.keys()), [b'key']) self.assertTrue(b'key' in db) self.assertEqual(db[b'key'], b'value') def tearDown(self): _delete_files() def setUp(self): _delete_files() if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sqlite.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sqlite.py
import test.support # Skip test if _sqlite3 module not installed test.support.import_module('_sqlite3') import unittest import sqlite3 from sqlite3.test import (dbapi, types, userfunctions, factory, transactions, hooks, regression, dump, backup) def load_tests(*args): if test.support.verbose: print("test_sqlite: testing with version", "{!r}, sqlite_version {!r}".format(sqlite3.version, sqlite3.sqlite_version)) return unittest.TestSuite([dbapi.suite(), types.suite(), userfunctions.suite(), factory.suite(), transactions.suite(), hooks.suite(), regression.suite(), dump.suite(), backup.suite()]) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_zipapp.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_zipapp.py
"""Test harness for the zipapp module.""" import io import pathlib import stat import sys import tempfile import unittest import zipapp import zipfile from test.support import requires_zlib from unittest.mock import patch class ZipAppTest(unittest.TestCase): """Test zipapp module functionality.""" def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) self.tmpdir = pathlib.Path(tmpdir.name) def test_create_archive(self): # Test packing a directory. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target)) self.assertTrue(target.is_file()) def test_create_archive_with_pathlib(self): # Test packing a directory using Path objects for source and target. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(source, target) self.assertTrue(target.is_file()) def test_create_archive_with_subdirs(self): # Test packing a directory includes entries for subdirectories. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() (source / 'foo').mkdir() (source / 'bar').mkdir() (source / 'foo' / '__init__.py').touch() target = io.BytesIO() zipapp.create_archive(str(source), target) target.seek(0) with zipfile.ZipFile(target, 'r') as z: self.assertIn('foo/', z.namelist()) self.assertIn('bar/', z.namelist()) def test_create_archive_with_filter(self): # Test packing a directory and using filter to specify # which files to include. def skip_pyc_files(path): return path.suffix != '.pyc' source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() (source / 'test.py').touch() (source / 'test.pyc').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(source, target, filter=skip_pyc_files) with zipfile.ZipFile(target, 'r') as z: self.assertIn('__main__.py', z.namelist()) self.assertIn('test.py', z.namelist()) self.assertNotIn('test.pyc', z.namelist()) def test_create_archive_filter_exclude_dir(self): # Test packing a directory and using a filter to exclude a # subdirectory (ensures that the path supplied to include # is relative to the source location, as expected). def skip_dummy_dir(path): return path.parts[0] != 'dummy' source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() (source / 'test.py').touch() (source / 'dummy').mkdir() (source / 'dummy' / 'test2.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(source, target, filter=skip_dummy_dir) with zipfile.ZipFile(target, 'r') as z: self.assertEqual(len(z.namelist()), 2) self.assertIn('__main__.py', z.namelist()) self.assertIn('test.py', z.namelist()) def test_create_archive_default_target(self): # Test packing a directory to the default name. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() zipapp.create_archive(str(source)) expected_target = self.tmpdir / 'source.pyz' self.assertTrue(expected_target.is_file()) @requires_zlib def test_create_archive_with_compression(self): # Test packing a directory into a compressed archive. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() (source / 'test.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(source, target, compressed=True) with zipfile.ZipFile(target, 'r') as z: for name in ('__main__.py', 'test.py'): self.assertEqual(z.getinfo(name).compress_type, zipfile.ZIP_DEFLATED) def test_no_main(self): # Test that packing a directory with no __main__.py fails. source = self.tmpdir / 'source' source.mkdir() (source / 'foo.py').touch() target = self.tmpdir / 'source.pyz' with self.assertRaises(zipapp.ZipAppError): zipapp.create_archive(str(source), str(target)) def test_main_and_main_py(self): # Test that supplying a main argument with __main__.py fails. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' with self.assertRaises(zipapp.ZipAppError): zipapp.create_archive(str(source), str(target), main='pkg.mod:fn') def test_main_written(self): # Test that the __main__.py is written correctly. source = self.tmpdir / 'source' source.mkdir() (source / 'foo.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), main='pkg.mod:fn') with zipfile.ZipFile(str(target), 'r') as z: self.assertIn('__main__.py', z.namelist()) self.assertIn(b'pkg.mod.fn()', z.read('__main__.py')) def test_main_only_written_once(self): # Test that we don't write multiple __main__.py files. # The initial implementation had this bug; zip files allow # multiple entries with the same name source = self.tmpdir / 'source' source.mkdir() # Write 2 files, as the original bug wrote __main__.py # once for each file written :-( # See http://bugs.python.org/review/23491/diff/13982/Lib/zipapp.py#newcode67Lib/zipapp.py:67 # (line 67) (source / 'foo.py').touch() (source / 'bar.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), main='pkg.mod:fn') with zipfile.ZipFile(str(target), 'r') as z: self.assertEqual(1, z.namelist().count('__main__.py')) def test_main_validation(self): # Test that invalid values for main are rejected. source = self.tmpdir / 'source' source.mkdir() target = self.tmpdir / 'source.pyz' problems = [ '', 'foo', 'foo:', ':bar', '12:bar', 'a.b.c.:d', '.a:b', 'a:b.', 'a:.b', 'a:silly name' ] for main in problems: with self.subTest(main=main): with self.assertRaises(zipapp.ZipAppError): zipapp.create_archive(str(source), str(target), main=main) def test_default_no_shebang(self): # Test that no shebang line is written to the target by default. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target)) with target.open('rb') as f: self.assertNotEqual(f.read(2), b'#!') def test_custom_interpreter(self): # Test that a shebang line with a custom interpreter is written # correctly. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') with target.open('rb') as f: self.assertEqual(f.read(2), b'#!') self.assertEqual(b'python\n', f.readline()) def test_pack_to_fileobj(self): # Test that we can pack to a file object. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = io.BytesIO() zipapp.create_archive(str(source), target, interpreter='python') self.assertTrue(target.getvalue().startswith(b'#!python\n')) def test_read_shebang(self): # Test that we can read the shebang line correctly. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') self.assertEqual(zipapp.get_interpreter(str(target)), 'python') def test_read_missing_shebang(self): # Test that reading the shebang line of a file without one returns None. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target)) self.assertEqual(zipapp.get_interpreter(str(target)), None) def test_modify_shebang(self): # Test that we can change the shebang of a file. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') new_target = self.tmpdir / 'changed.pyz' zipapp.create_archive(str(target), str(new_target), interpreter='python2.7') self.assertEqual(zipapp.get_interpreter(str(new_target)), 'python2.7') def test_write_shebang_to_fileobj(self): # Test that we can change the shebang of a file, writing the result to a # file object. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') new_target = io.BytesIO() zipapp.create_archive(str(target), new_target, interpreter='python2.7') self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n')) def test_read_from_pathobj(self): # Test that we can copy an archive using a pathlib.Path object # for the source. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target1 = self.tmpdir / 'target1.pyz' target2 = self.tmpdir / 'target2.pyz' zipapp.create_archive(source, target1, interpreter='python') zipapp.create_archive(target1, target2, interpreter='python2.7') self.assertEqual(zipapp.get_interpreter(target2), 'python2.7') def test_read_from_fileobj(self): # Test that we can copy an archive using an open file object. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' temp_archive = io.BytesIO() zipapp.create_archive(str(source), temp_archive, interpreter='python') new_target = io.BytesIO() temp_archive.seek(0) zipapp.create_archive(temp_archive, new_target, interpreter='python2.7') self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n')) def test_remove_shebang(self): # Test that we can remove the shebang from a file. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') new_target = self.tmpdir / 'changed.pyz' zipapp.create_archive(str(target), str(new_target), interpreter=None) self.assertEqual(zipapp.get_interpreter(str(new_target)), None) def test_content_of_copied_archive(self): # Test that copying an archive doesn't corrupt it. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = io.BytesIO() zipapp.create_archive(str(source), target, interpreter='python') new_target = io.BytesIO() target.seek(0) zipapp.create_archive(target, new_target, interpreter=None) new_target.seek(0) with zipfile.ZipFile(new_target, 'r') as z: self.assertEqual(set(z.namelist()), {'__main__.py'}) # (Unix only) tests that archives with shebang lines are made executable @unittest.skipIf(sys.platform == 'win32', 'Windows does not support an executable bit') def test_shebang_is_executable(self): # Test that an archive with a shebang line is made executable. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter='python') self.assertTrue(target.stat().st_mode & stat.S_IEXEC) @unittest.skipIf(sys.platform == 'win32', 'Windows does not support an executable bit') def test_no_shebang_is_not_executable(self): # Test that an archive with no shebang line is not made executable. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(str(source), str(target), interpreter=None) self.assertFalse(target.stat().st_mode & stat.S_IEXEC) class ZipAppCmdlineTest(unittest.TestCase): """Test zipapp module command line API.""" def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) self.tmpdir = pathlib.Path(tmpdir.name) def make_archive(self): # Test that an archive with no shebang line is not made executable. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() target = self.tmpdir / 'source.pyz' zipapp.create_archive(source, target) return target def test_cmdline_create(self): # Test the basic command line API. source = self.tmpdir / 'source' source.mkdir() (source / '__main__.py').touch() args = [str(source)] zipapp.main(args) target = source.with_suffix('.pyz') self.assertTrue(target.is_file()) def test_cmdline_copy(self): # Test copying an archive. original = self.make_archive() target = self.tmpdir / 'target.pyz' args = [str(original), '-o', str(target)] zipapp.main(args) self.assertTrue(target.is_file()) def test_cmdline_copy_inplace(self): # Test copying an archive in place fails. original = self.make_archive() target = self.tmpdir / 'target.pyz' args = [str(original), '-o', str(original)] with self.assertRaises(SystemExit) as cm: zipapp.main(args) # Program should exit with a non-zero return code. self.assertTrue(cm.exception.code) def test_cmdline_copy_change_main(self): # Test copying an archive doesn't allow changing __main__.py. original = self.make_archive() target = self.tmpdir / 'target.pyz' args = [str(original), '-o', str(target), '-m', 'foo:bar'] with self.assertRaises(SystemExit) as cm: zipapp.main(args) # Program should exit with a non-zero return code. self.assertTrue(cm.exception.code) @patch('sys.stdout', new_callable=io.StringIO) def test_info_command(self, mock_stdout): # Test the output of the info command. target = self.make_archive() args = [str(target), '--info'] with self.assertRaises(SystemExit) as cm: zipapp.main(args) # Program should exit with a zero return code. self.assertEqual(cm.exception.code, 0) self.assertEqual(mock_stdout.getvalue(), "Interpreter: <none>\n") def test_info_error(self): # Test the info command fails when the archive does not exist. target = self.tmpdir / 'dummy.pyz' args = [str(target), '--info'] with self.assertRaises(SystemExit) as cm: zipapp.main(args) # Program should exit with a non-zero return code. self.assertTrue(cm.exception.code) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/fork_wait.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/fork_wait.py
"""This test case provides support for checking forking and wait behavior. To test different wait behavior, override the wait_impl method. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, unittest import threading import test.support as support LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 class ForkWait(unittest.TestCase): def setUp(self): self._threading_key = support.threading_setup() self.alive = {} self.stop = 0 self.threads = [] def tearDown(self): # Stop threads self.stop = 1 for thread in self.threads: thread.join() thread = None self.threads.clear() support.threading_cleanup(*self._threading_key) def f(self, id): while not self.stop: self.alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except OSError: pass def wait_impl(self, cpid): for i 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) if spid == cpid: break time.sleep(2 * SHORTSLEEP) self.assertEqual(spid, cpid) self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) def test_wait(self): for i in range(NUM_THREADS): thread = threading.Thread(target=self.f, args=(i,)) thread.start() self.threads.append(thread) # busy-loop to wait for threads deadline = time.monotonic() + 10.0 while len(self.alive) < NUM_THREADS: time.sleep(0.1) if deadline < time.monotonic(): break a = sorted(self.alive.keys()) self.assertEqual(a, list(range(NUM_THREADS))) prefork_lives = self.alive.copy() if sys.platform in ['unixware7']: cpid = os.fork1() else: cpid = 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 os._exit(n) else: # Parent self.wait_impl(cpid)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pow.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pow.py
import unittest class PowTest(unittest.TestCase): def powtest(self, type): if type != float: for i in range(-1000, 1000): self.assertEqual(pow(type(i), 0), 1) self.assertEqual(pow(type(i), 1), type(i)) self.assertEqual(pow(type(0), 1), type(0)) self.assertEqual(pow(type(1), 1), type(1)) for i in range(-100, 100): self.assertEqual(pow(type(i), 3), i*i*i) pow2 = 1 for i in range(0, 31): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 for othertype in (int,): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) for j in range(1, 11): jj = -othertype(j) pow(ii, jj) for othertype in int, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue self.assertRaises(ZeroDivisionError, pow, zero, exp) il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 asseq = self.assertEqual if type == float: il = 1 asseq = self.assertAlmostEqual elif type == int: jl = 0 elif type == int: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): for k in range(kl, kh+1): if k != 0: if type == float or j < 0: self.assertRaises(TypeError, pow, type(i), j, k) continue asseq( pow(type(i),j,k), pow(type(i),j)% type(k) ) def test_powint(self): self.powtest(int) def test_powfloat(self): self.powtest(float) def test_other(self): # Other tests-- not very systematic self.assertEqual(pow(3,3) % 8, pow(3,3,8)) self.assertEqual(pow(3,3) % -8, pow(3,3,-8)) self.assertEqual(pow(3,2) % -2, pow(3,2,-2)) self.assertEqual(pow(-3,3) % 8, pow(-3,3,8)) self.assertEqual(pow(-3,3) % -8, pow(-3,3,-8)) self.assertEqual(pow(5,2) % -8, pow(5,2,-8)) self.assertEqual(pow(3,3) % 8, pow(3,3,8)) self.assertEqual(pow(3,3) % -8, pow(3,3,-8)) self.assertEqual(pow(3,2) % -2, pow(3,2,-2)) self.assertEqual(pow(-3,3) % 8, pow(-3,3,8)) self.assertEqual(pow(-3,3) % -8, pow(-3,3,-8)) self.assertEqual(pow(5,2) % -8, pow(5,2,-8)) for i in range(-10, 11): for j in range(0, 6): for k in range(-7, 11): if j >= 0 and k != 0: self.assertEqual( pow(i,j) % k, pow(i,j,k) ) if j >= 0 and k != 0: self.assertEqual( pow(int(i),j) % k, pow(int(i),j,k) ) def test_bug643260(self): class TestRpow: def __rpow__(self, other): return None None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. def test_bug705231(self): # -1.0 raised to an integer should never blow up. It did if the # platform pow() was buggy, and Python didn't worm around it. eq = self.assertEqual a = -1.0 # The next two tests can still fail if the platform floor() # function doesn't treat all large inputs as integers # test_math should also fail if that is happening eq(pow(a, 1.23e167), 1.0) eq(pow(a, -1.23e167), 1.0) for b in range(-10, 11): eq(pow(a, float(b)), b & 1 and -1.0 or 1.0) for n in range(0, 100): fiveto = float(5 ** n) # For small n, fiveto will be odd. Eventually we run out of # mantissa bits, though, and thereafer fiveto will be even. expected = fiveto % 2.0 and -1.0 or 1.0 eq(pow(a, fiveto), expected) eq(pow(a, -fiveto), expected) eq(expected, 1.0) # else we didn't push fiveto to evenness if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_1.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_1.py
#from __future__ import annotations USING_STRINGS = False # dataclass_module_1.py and dataclass_module_1_str.py are identical # except only the latter uses string annotations. import dataclasses import typing T_CV2 = typing.ClassVar[int] T_CV3 = typing.ClassVar T_IV2 = dataclasses.InitVar[int] T_IV3 = dataclasses.InitVar @dataclasses.dataclass class CV: T_CV4 = typing.ClassVar cv0: typing.ClassVar[int] = 20 cv1: typing.ClassVar = 30 cv2: T_CV2 cv3: T_CV3 not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. @dataclasses.dataclass class IV: T_IV4 = dataclasses.InitVar iv0: dataclasses.InitVar[int] iv1: dataclasses.InitVar iv2: T_IV2 iv3: T_IV3 not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_winconsoleio.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_winconsoleio.py
'''Tests for WindowsConsoleIO ''' import io import os import sys import tempfile import unittest from test import support if sys.platform != 'win32': raise unittest.SkipTest("test only relevant on win32") from _testconsole import write_input ConIO = io._WindowsConsoleIO class WindowsConsoleIOTests(unittest.TestCase): def test_abc(self): self.assertTrue(issubclass(ConIO, io.RawIOBase)) self.assertFalse(issubclass(ConIO, io.BufferedIOBase)) self.assertFalse(issubclass(ConIO, io.TextIOBase)) def test_open_fd(self): self.assertRaisesRegex(ValueError, "negative file descriptor", ConIO, -1) fd, _ = tempfile.mkstemp() try: # Windows 10: "Cannot open non-console file" # Earlier: "Cannot open console output buffer for reading" self.assertRaisesRegex(ValueError, "Cannot open (console|non-console file)", ConIO, fd) finally: os.close(fd) try: f = ConIO(0) except ValueError: # cannot open console because it's not a real console pass else: self.assertTrue(f.readable()) self.assertFalse(f.writable()) self.assertEqual(0, f.fileno()) f.close() # multiple close should not crash f.close() try: f = ConIO(1, 'w') except ValueError: # cannot open console because it's not a real console pass else: self.assertFalse(f.readable()) self.assertTrue(f.writable()) self.assertEqual(1, f.fileno()) f.close() f.close() try: f = ConIO(2, 'w') except ValueError: # cannot open console because it's not a real console pass else: self.assertFalse(f.readable()) self.assertTrue(f.writable()) self.assertEqual(2, f.fileno()) f.close() f.close() def test_open_name(self): self.assertRaises(ValueError, ConIO, sys.executable) f = ConIO("CON") self.assertTrue(f.readable()) self.assertFalse(f.writable()) self.assertIsNotNone(f.fileno()) f.close() # multiple close should not crash f.close() f = ConIO('CONIN$') self.assertTrue(f.readable()) self.assertFalse(f.writable()) self.assertIsNotNone(f.fileno()) f.close() f.close() f = ConIO('CONOUT$', 'w') self.assertFalse(f.readable()) self.assertTrue(f.writable()) self.assertIsNotNone(f.fileno()) f.close() f.close() f = open('C:/con', 'rb', buffering=0) self.assertIsInstance(f, ConIO) f.close() @unittest.skipIf(sys.getwindowsversion()[:2] <= (6, 1), "test does not work on Windows 7 and earlier") def test_conin_conout_names(self): f = open(r'\\.\conin$', 'rb', buffering=0) self.assertIsInstance(f, ConIO) f.close() f = open('//?/conout$', 'wb', buffering=0) self.assertIsInstance(f, ConIO) f.close() def test_conout_path(self): temp_path = tempfile.mkdtemp() self.addCleanup(support.rmtree, temp_path) conout_path = os.path.join(temp_path, 'CONOUT$') with open(conout_path, 'wb', buffering=0) as f: if sys.getwindowsversion()[:2] > (6, 1): self.assertIsInstance(f, ConIO) else: self.assertNotIsInstance(f, ConIO) def test_write_empty_data(self): with ConIO('CONOUT$', 'w') as f: self.assertEqual(f.write(b''), 0) def assertStdinRoundTrip(self, text): stdin = open('CONIN$', 'r') old_stdin = sys.stdin try: sys.stdin = stdin write_input( stdin.buffer.raw, (text + '\r\n').encode('utf-16-le', 'surrogatepass') ) actual = input() finally: sys.stdin = old_stdin self.assertEqual(actual, text) def test_input(self): # ASCII self.assertStdinRoundTrip('abc123') # Non-ASCII self.assertStdinRoundTrip('ϼўТλФЙ') # Combining characters self.assertStdinRoundTrip('A͏B ﬖ̳AA̝') # Non-BMP self.assertStdinRoundTrip('\U00100000\U0010ffff\U0010fffd') def test_partial_reads(self): # Test that reading less than 1 full character works when stdin # contains multibyte UTF-8 sequences source = 'ϼўТλФЙ\r\n'.encode('utf-16-le') expected = 'ϼўТλФЙ\r\n'.encode('utf-8') for read_count in range(1, 16): with open('CONIN$', 'rb', buffering=0) as stdin: write_input(stdin, source) actual = b'' while not actual.endswith(b'\n'): b = stdin.read(read_count) actual += b self.assertEqual(actual, expected, 'stdin.read({})'.format(read_count)) def test_partial_surrogate_reads(self): # Test that reading less than 1 full character works when stdin # contains surrogate pairs that cannot be decoded to UTF-8 without # reading an extra character. source = '\U00101FFF\U00101001\r\n'.encode('utf-16-le') expected = '\U00101FFF\U00101001\r\n'.encode('utf-8') for read_count in range(1, 16): with open('CONIN$', 'rb', buffering=0) as stdin: write_input(stdin, source) actual = b'' while not actual.endswith(b'\n'): b = stdin.read(read_count) actual += b self.assertEqual(actual, expected, 'stdin.read({})'.format(read_count)) def test_ctrl_z(self): with open('CONIN$', 'rb', buffering=0) as stdin: source = '\xC4\x1A\r\n'.encode('utf-16-le') expected = '\xC4'.encode('utf-8') write_input(stdin, source) a, b = stdin.read(1), stdin.readall() self.assertEqual(expected[0:1], a) self.assertEqual(expected[1:], b) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exceptions.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exceptions.py
# Python test set -- part 5, built-in exceptions import copy import os import sys import unittest import pickle import weakref import errno from test.support import (TESTFN, captured_stderr, check_impl_detail, check_warnings, cpython_only, gc_collect, run_unittest, no_tracing, unlink, import_module, script_helper, SuppressCrashReport) class NaiveException(Exception): def __init__(self, x): self.x = x class SlottedNaiveException(Exception): __slots__ = ('x',) def __init__(self, x): self.x = x class BrokenStrException(Exception): def __str__(self): raise Exception("str() is broken") # XXX This is not really enough, each *operation* should be tested! class ExceptionTests(unittest.TestCase): def raise_catch(self, exc, excname): try: raise exc("spam") except exc as err: buf1 = str(err) try: raise exc("spam") except exc as err: buf2 = str(err) self.assertEqual(buf1, buf2) self.assertEqual(exc.__name__, excname) def testRaising(self): self.raise_catch(AttributeError, "AttributeError") self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") self.raise_catch(EOFError, "EOFError") fp = open(TESTFN, 'w') fp.close() fp = open(TESTFN, 'r') savestdin = sys.stdin try: try: import marshal marshal.loads(b'') except EOFError: pass finally: sys.stdin = savestdin fp.close() unlink(TESTFN) self.raise_catch(OSError, "OSError") self.assertRaises(OSError, open, 'this file does not exist', 'r') self.raise_catch(ImportError, "ImportError") self.assertRaises(ImportError, __import__, "undefined_module") self.raise_catch(IndexError, "IndexError") x = [] self.assertRaises(IndexError, x.__getitem__, 10) self.raise_catch(KeyError, "KeyError") x = {} self.assertRaises(KeyError, x.__getitem__, 'key') self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") self.raise_catch(MemoryError, "MemoryError") self.raise_catch(NameError, "NameError") try: x = undefined_variable except NameError: pass self.raise_catch(OverflowError, "OverflowError") x = 1 for dummy in range(128): x += x # this simply shouldn't blow up self.raise_catch(RuntimeError, "RuntimeError") self.raise_catch(RecursionError, "RecursionError") self.raise_catch(SyntaxError, "SyntaxError") try: exec('/\n') except SyntaxError: pass self.raise_catch(IndentationError, "IndentationError") self.raise_catch(TabError, "TabError") try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec') except TabError: pass else: self.fail("TabError not raised") self.raise_catch(SystemError, "SystemError") self.raise_catch(SystemExit, "SystemExit") self.assertRaises(SystemExit, sys.exit, 0) self.raise_catch(TypeError, "TypeError") try: [] + () except TypeError: pass self.raise_catch(ValueError, "ValueError") self.assertRaises(ValueError, chr, 17<<16) self.raise_catch(ZeroDivisionError, "ZeroDivisionError") try: x = 1/0 except ZeroDivisionError: pass self.raise_catch(Exception, "Exception") try: x = 1/0 except Exception as e: pass self.raise_catch(StopAsyncIteration, "StopAsyncIteration") def testSyntaxErrorMessage(self): # make sure the right exception message is raised for each of # these code fragments def ckmsg(src, msg): try: compile(src, '<fragment>', 'exec') except SyntaxError as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: self.fail("failed to get expected SyntaxError") s = '''while 1: try: pass finally: continue''' if not sys.platform.startswith('java'): ckmsg(s, "'continue' not supported inside 'finally' clause") s = '''if 1: try: continue except: pass''' ckmsg(s, "'continue' not properly in loop") ckmsg("continue\n", "'continue' not properly in loop") def testSyntaxErrorMissingParens(self): def ckmsg(src, msg, exception=SyntaxError): try: compile(src, '<fragment>', 'exec') except exception as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: self.fail("failed to get expected SyntaxError") s = '''print "old style"''' ckmsg(s, "Missing parentheses in call to 'print'. " "Did you mean print(\"old style\")?") s = '''print "old style",''' ckmsg(s, "Missing parentheses in call to 'print'. " "Did you mean print(\"old style\", end=\" \")?") s = '''exec "old style"''' ckmsg(s, "Missing parentheses in call to 'exec'") # should not apply to subclasses, see issue #31161 s = '''if True:\nprint "No indent"''' ckmsg(s, "expected an indented block", IndentationError) s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) def testSyntaxErrorOffset(self): def check(src, lineno, offset): with self.assertRaises(SyntaxError) as cm: compile(src, '<fragment>', 'exec') self.assertEqual(cm.exception.lineno, lineno) self.assertEqual(cm.exception.offset, offset) check('def fact(x):\n\treturn x!\n', 2, 10) check('1 +\n', 1, 4) check('def spam():\n print(1)\n print(2)', 3, 10) check('Python = "Python" +', 1, 20) check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) @cpython_only def testSettingException(self): # test that setting an exception at the C level works even if the # exception object can't be constructed. class BadException(Exception): def __init__(self_): raise RuntimeError("can't instantiate BadException") class InvalidException: pass def test_capi1(): import _testcapi try: _testcapi.raise_exception(BadException, 1) except TypeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEqual(co.co_name, "test_capi1") self.assertTrue(co.co_filename.endswith('test_exceptions.py')) else: self.fail("Expected exception") def test_capi2(): import _testcapi try: _testcapi.raise_exception(BadException, 0) except RuntimeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEqual(co.co_name, "__init__") self.assertTrue(co.co_filename.endswith('test_exceptions.py')) co2 = tb.tb_frame.f_back.f_code self.assertEqual(co2.co_name, "test_capi2") else: self.fail("Expected exception") def test_capi3(): import _testcapi self.assertRaises(SystemError, _testcapi.raise_exception, InvalidException, 1) if not sys.platform.startswith('java'): test_capi1() test_capi2() test_capi3() def test_WindowsError(self): try: WindowsError except NameError: pass else: self.assertIs(WindowsError, OSError) self.assertEqual(str(OSError(1001)), "1001") self.assertEqual(str(OSError(1001, "message")), "[Errno 1001] message") # POSIX errno (9 aka EBADF) is untranslated w = OSError(9, 'foo', 'bar') self.assertEqual(w.errno, 9) self.assertEqual(w.winerror, None) self.assertEqual(str(w), "[Errno 9] foo: 'bar'") # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) w = OSError(0, 'foo', 'bar', 3) self.assertEqual(w.errno, 2) self.assertEqual(w.winerror, 3) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, 'bar') self.assertEqual(w.filename2, None) self.assertEqual(str(w), "[WinError 3] foo: 'bar'") # Unknown win error becomes EINVAL (22) w = OSError(0, 'foo', None, 1001) self.assertEqual(w.errno, 22) self.assertEqual(w.winerror, 1001) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, None) self.assertEqual(w.filename2, None) self.assertEqual(str(w), "[WinError 1001] foo") # Non-numeric "errno" w = OSError('bar', 'foo') self.assertEqual(w.errno, 'bar') self.assertEqual(w.winerror, None) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, None) self.assertEqual(w.filename2, None) @unittest.skipUnless(sys.platform == 'win32', 'test specific to Windows') def test_windows_message(self): """Should fill in unknown error code in Windows error message""" ctypes = import_module('ctypes') # this error code has no message, Python formats it as hexadecimal code = 3765269347 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): ctypes.pythonapi.PyErr_SetFromWindowsErr(code) def testAttributes(self): # test that exception attributes are happy exceptionList = [ (BaseException, (), {'args' : ()}), (BaseException, (1, ), {'args' : (1,)}), (BaseException, ('foo',), {'args' : ('foo',)}), (BaseException, ('foo', 1), {'args' : ('foo', 1)}), (SystemExit, ('foo',), {'args' : ('foo',), 'code' : 'foo'}), (OSError, ('foo',), {'args' : ('foo',), 'filename' : None, 'filename2' : None, 'errno' : None, 'strerror' : None}), (OSError, ('foo', 'bar'), {'args' : ('foo', 'bar'), 'filename' : None, 'filename2' : None, 'errno' : 'foo', 'strerror' : 'bar'}), (OSError, ('foo', 'bar', 'baz'), {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2' : None, 'errno' : 'foo', 'strerror' : 'bar'}), (OSError, ('foo', 'bar', 'baz', None, 'quux'), {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), {'args' : ('errnoStr', 'strErrorStr'), 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', 'filename' : 'filenameStr'}), (OSError, (1, 'strErrorStr', 'filenameStr'), {'args' : (1, 'strErrorStr'), 'errno' : 1, 'strerror' : 'strErrorStr', 'filename' : 'filenameStr', 'filename2' : None}), (SyntaxError, (), {'msg' : None, 'text' : None, 'filename' : None, 'lineno' : None, 'offset' : None, 'print_file_and_line' : None}), (SyntaxError, ('msgStr',), {'args' : ('msgStr',), 'text' : None, 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : None, 'lineno' : None, 'offset' : None}), (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', 'textStr')), {'offset' : 'offsetStr', 'text' : 'textStr', 'args' : ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', 'textStr')), 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}), (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'print_file_and_lineStr'), {'text' : None, 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'print_file_and_lineStr'), 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : None, 'lineno' : None, 'offset' : None}), (UnicodeError, (), {'args' : (),}), (UnicodeEncodeError, ('ascii', 'a', 0, 1, 'ordinal not in range'), {'args' : ('ascii', 'a', 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : 'a', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, 'ordinal not in range'), {'args' : ('ascii', bytearray(b'\xff'), 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : b'\xff', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, 'ordinal not in range'), {'args' : ('ascii', b'\xff', 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : b'\xff', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), {'args' : ('\u3042', 0, 1, 'ouch'), 'object' : '\u3042', 'reason' : 'ouch', 'start' : 0, 'end' : 1}), (NaiveException, ('foo',), {'args': ('foo',), 'x': 'foo'}), (SlottedNaiveException, ('foo',), {'args': ('foo',), 'x': 'foo'}), ] try: # More tests are in test_WindowsError exceptionList.append( (WindowsError, (1, 'strErrorStr', 'filenameStr'), {'args' : (1, 'strErrorStr'), 'strerror' : 'strErrorStr', 'winerror' : None, 'errno' : 1, 'filename' : 'filenameStr', 'filename2' : None}) ) except NameError: pass for exc, args, expected in exceptionList: try: e = exc(*args) except: print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr) raise else: # Verify module name if not type(e).__name__.endswith('NaiveException'): self.assertEqual(type(e).__module__, 'builtins') # Verify no ref leaks in Exc_str() s = str(e) for checkArgName in expected: value = getattr(e, checkArgName) self.assertEqual(repr(value), repr(expected[checkArgName]), '%r.%s == %r, expected %r' % ( e, checkArgName, value, expected[checkArgName])) # test for pickling support for p in [pickle]: for protocol in range(p.HIGHEST_PROTOCOL + 1): s = p.dumps(e, protocol) new = p.loads(s) for checkArgName in expected: got = repr(getattr(new, checkArgName)) want = repr(expected[checkArgName]) self.assertEqual(got, want, 'pickled "%r", attribute "%s' % (e, checkArgName)) def testWithTraceback(self): try: raise IndexError(4) except: tb = sys.exc_info()[2] e = BaseException().with_traceback(tb) self.assertIsInstance(e, BaseException) self.assertEqual(e.__traceback__, tb) e = IndexError(5).with_traceback(tb) self.assertIsInstance(e, IndexError) self.assertEqual(e.__traceback__, tb) class MyException(Exception): pass e = MyException().with_traceback(tb) self.assertIsInstance(e, MyException) self.assertEqual(e.__traceback__, tb) def testInvalidTraceback(self): try: Exception().__traceback__ = 5 except TypeError as e: self.assertIn("__traceback__ must be a traceback", str(e)) else: self.fail("No exception raised") def testInvalidAttrs(self): self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1) self.assertRaises(TypeError, delattr, Exception(), '__cause__') self.assertRaises(TypeError, setattr, Exception(), '__context__', 1) self.assertRaises(TypeError, delattr, Exception(), '__context__') def testNoneClearsTracebackAttr(self): try: raise IndexError(4) except: tb = sys.exc_info()[2] e = Exception() e.__traceback__ = tb e.__traceback__ = None self.assertEqual(e.__traceback__, None) def testChainingAttrs(self): e = Exception() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) e = TypeError() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) class MyException(OSError): pass e = MyException() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) def testChainingDescriptors(self): try: raise Exception() except Exception as exc: e = exc self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) self.assertFalse(e.__suppress_context__) e.__context__ = NameError() e.__cause__ = None self.assertIsInstance(e.__context__, NameError) self.assertIsNone(e.__cause__) self.assertTrue(e.__suppress_context__) e.__suppress_context__ = False self.assertFalse(e.__suppress_context__) def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want self.assertRaises(TypeError, BaseException, a=1) class DerivedException(BaseException): def __init__(self, fancy_arg): BaseException.__init__(self) self.fancy_arg = fancy_arg x = DerivedException(fancy_arg=42) self.assertEqual(x.fancy_arg, 42) @no_tracing def testInfiniteRecursion(self): def f(): return f() self.assertRaises(RecursionError, f) def g(): try: return g() except ValueError: return -1 self.assertRaises(RecursionError, g) def test_str(self): # Make sure both instances and classes have a str representation. self.assertTrue(str(Exception)) self.assertTrue(str(Exception('a'))) self.assertTrue(str(Exception('a', 'b'))) def testExceptionCleanupNames(self): # Make sure the local variable bound to the exception instance by # an "except" statement is only visible inside the except block. try: raise Exception() except Exception as e: self.assertTrue(e) del e self.assertNotIn('e', locals()) def testExceptionCleanupState(self): # Make sure exception state is cleaned up as soon as the except # block is left. See #2507 class MyException(Exception): def __init__(self, obj): self.obj = obj class MyObj: pass def inner_raising_func(): # Create some references in exception value and traceback local_ref = obj raise MyException(obj) # Qualified "except" with "as" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException as e: pass obj = None obj = wr() self.assertIsNone(obj) # Qualified "except" without "as" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException: pass obj = None obj = wr() self.assertIsNone(obj) # Bare "except" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except: pass obj = None obj = wr() self.assertIsNone(obj) # "except" with premature block leave obj = MyObj() wr = weakref.ref(obj) for i in [0]: try: inner_raising_func() except: break obj = None obj = wr() self.assertIsNone(obj) # "except" block raising another exception obj = MyObj() wr = weakref.ref(obj) try: try: inner_raising_func() except: raise KeyError except KeyError as e: # We want to test that the except block above got rid of # the exception raised in inner_raising_func(), but it # also ends up in the __context__ of the KeyError, so we # must clear the latter manually for our test to succeed. e.__context__ = None obj = None obj = wr() # guarantee no ref cycles on CPython (don't gc_collect) if check_impl_detail(cpython=False): gc_collect() self.assertIsNone(obj) # Some complicated construct obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException: try: try: raise finally: raise except MyException: pass obj = None if check_impl_detail(cpython=False): gc_collect() obj = wr() self.assertIsNone(obj) # Inside an exception-silencing "with" block class Context: def __enter__(self): return self def __exit__ (self, exc_type, exc_value, exc_tb): return True obj = MyObj() wr = weakref.ref(obj) with Context(): inner_raising_func() obj = None if check_impl_detail(cpython=False): gc_collect() obj = wr() self.assertIsNone(obj) def test_exception_target_in_nested_scope(self): # issue 4617: This used to raise a SyntaxError # "can not delete variable 'e' referenced in nested scope" def print_error(): e try: something except Exception as e: print_error() # implicit "del e" here def test_generator_leaking(self): # Test that generator exception state doesn't leak into the calling # frame def yield_raise(): try: raise KeyError("caught") except KeyError: yield sys.exc_info()[0] yield sys.exc_info()[0] yield sys.exc_info()[0] g = yield_raise() self.assertEqual(next(g), KeyError) self.assertEqual(sys.exc_info()[0], None) self.assertEqual(next(g), KeyError) self.assertEqual(sys.exc_info()[0], None) self.assertEqual(next(g), None) # Same test, but inside an exception handler try: raise TypeError("foo") except TypeError: g = yield_raise() self.assertEqual(next(g), KeyError) self.assertEqual(sys.exc_info()[0], TypeError) self.assertEqual(next(g), KeyError) self.assertEqual(sys.exc_info()[0], TypeError) self.assertEqual(next(g), TypeError) del g self.assertEqual(sys.exc_info()[0], TypeError) def test_generator_leaking2(self): # See issue 12475. def g(): yield try: raise RuntimeError except RuntimeError: it = g() next(it) try: next(it) except StopIteration: pass self.assertEqual(sys.exc_info(), (None, None, None)) def test_generator_leaking3(self): # See issue #23353. When gen.throw() is called, the caller's # exception state should be save and restored. def g(): try: yield except ZeroDivisionError: yield sys.exc_info()[1] it = g() next(it) try: 1/0 except ZeroDivisionError as e: self.assertIs(sys.exc_info()[1], e) gen_exc = it.throw(e) self.assertIs(sys.exc_info()[1], e) self.assertIs(gen_exc, e) self.assertEqual(sys.exc_info(), (None, None, None)) def test_generator_leaking4(self): # See issue #23353. When an exception is raised by a generator, # the caller's exception state should still be restored. def g(): try: 1/0 except ZeroDivisionError: yield sys.exc_info()[0] raise it = g() try: raise TypeError except TypeError: # The caller's exception state (TypeError) is temporarily # saved in the generator. tp = next(it) self.assertIs(tp, ZeroDivisionError) try: next(it) # We can't check it immediately, but while next() returns # with an exception, it shouldn't have restored the old # exception state (TypeError). except ZeroDivisionError as e: self.assertIs(sys.exc_info()[1], e) # We used to find TypeError here. self.assertEqual(sys.exc_info(), (None, None, None)) def test_generator_doesnt_retain_old_exc(self): def g(): self.assertIsInstance(sys.exc_info()[1], RuntimeError) yield self.assertEqual(sys.exc_info(), (None, None, None)) it = g() try: raise RuntimeError except RuntimeError: next(it) self.assertRaises(StopIteration, next, it) def test_generator_finalizing_and_exc_info(self): # See #7173 def simple_gen(): yield 1 def run_gen(): gen = simple_gen() try: raise RuntimeError except RuntimeError: return next(gen) run_gen() gc_collect() self.assertEqual(sys.exc_info(), (None, None, None)) def _check_generator_cleanup_exc_state(self, testfunc): # Issue #12791: exception state is cleaned up as soon as a generator # is closed (reference cycles are broken). class MyException(Exception): def __init__(self, obj): self.obj = obj class MyObj: pass def raising_gen(): try: raise MyException(obj) except MyException: yield obj = MyObj() wr = weakref.ref(obj) g = raising_gen() next(g) testfunc(g) g = obj = None obj = wr() self.assertIsNone(obj) def test_generator_throw_cleanup_exc_state(self): def do_throw(g): try: g.throw(RuntimeError()) except RuntimeError: pass self._check_generator_cleanup_exc_state(do_throw) def test_generator_close_cleanup_exc_state(self): def do_close(g): g.close() self._check_generator_cleanup_exc_state(do_close) def test_generator_del_cleanup_exc_state(self): def do_del(g): g = None self._check_generator_cleanup_exc_state(do_del) def test_generator_next_cleanup_exc_state(self): def do_next(g): try: next(g) except StopIteration: pass else: self.fail("should have raised StopIteration") self._check_generator_cleanup_exc_state(do_next) def test_generator_send_cleanup_exc_state(self): def do_send(g): try: g.send(None) except StopIteration: pass else: self.fail("should have raised StopIteration") self._check_generator_cleanup_exc_state(do_send) def test_3114(self): # Bug #3114: in its destructor, MyObject retrieves a pointer to # obsolete and/or deallocated objects. class MyObject: def __del__(self): nonlocal e e = sys.exc_info() e = () try: raise Exception(MyObject()) except: pass self.assertEqual(e, (None, None, None)) def test_unicode_change_attributes(self): # See issue 7309. This was a crasher. u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") u.encoding = 4000 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") u.encoding = 4000 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") u = UnicodeTranslateError('xxxx', 1, 5, 'foo') self.assertEqual(str(u), "can't translate characters in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") def test_unicode_errors_no_object(self): # See issue #21134. klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError for klass in klasses: self.assertEqual(str(klass.__new__(klass)), "") @no_tracing def test_badisinstance(self): # Bug #2542: if issubclass(e, MyException) raises an exception, # it should be ignored class Meta(type): def __subclasscheck__(cls, subclass): raise ValueError() class MyException(Exception, metaclass=Meta): pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dbm_ndbm.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dbm_ndbm.py
from test import support support.import_module("dbm.ndbm") #skip if not supported import os import unittest import dbm.ndbm from dbm.ndbm import error class DbmTestCase(unittest.TestCase): def setUp(self): self.filename = support.TESTFN self.d = dbm.ndbm.open(self.filename, 'c') self.d.close() def tearDown(self): for suffix in ['', '.pag', '.dir', '.db']: support.unlink(self.filename + suffix) def test_keys(self): self.d = dbm.ndbm.open(self.filename, 'c') self.assertEqual(self.d.keys(), []) self.d['a'] = 'b' self.d[b'bytes'] = b'data' self.d['12345678910'] = '019237410982340912840198242' self.d.keys() self.assertIn('a', self.d) self.assertIn(b'a', self.d) self.assertEqual(self.d[b'bytes'], b'data') # get() and setdefault() work as in the dict interface self.assertEqual(self.d.get(b'a'), b'b') self.assertIsNone(self.d.get(b'xxx')) self.assertEqual(self.d.get(b'xxx', b'foo'), b'foo') with self.assertRaises(KeyError): self.d['xxx'] self.assertEqual(self.d.setdefault(b'xxx', b'foo'), b'foo') self.assertEqual(self.d[b'xxx'], b'foo') self.d.close() def test_empty_value(self): if dbm.ndbm.library == 'Berkeley DB': self.skipTest("Berkeley DB doesn't distinguish the empty value " "from the absent one") self.d = dbm.ndbm.open(self.filename, 'c') self.assertEqual(self.d.keys(), []) self.d['empty'] = '' self.assertEqual(self.d.keys(), [b'empty']) self.assertIn(b'empty', self.d) self.assertEqual(self.d[b'empty'], b'') self.assertEqual(self.d.get(b'empty'), b'') self.assertEqual(self.d.setdefault(b'empty'), b'') self.d.close() def test_modes(self): for mode in ['r', 'rw', 'w', 'n']: try: self.d = dbm.ndbm.open(self.filename, mode) self.d.close() except error: self.fail() def test_context_manager(self): with dbm.ndbm.open(self.filename, 'c') as db: db["ndbm context manager"] = "context manager" with dbm.ndbm.open(self.filename, 'r') as db: self.assertEqual(list(db.keys()), [b"ndbm context manager"]) with self.assertRaises(dbm.ndbm.error) as cm: db.keys() self.assertEqual(str(cm.exception), "DBM object has already been closed") def test_bytes(self): with dbm.ndbm.open(self.filename, 'c') as db: db[b'bytes key \xbd'] = b'bytes value \xbd' with dbm.ndbm.open(self.filename, 'r') as db: self.assertEqual(list(db.keys()), [b'bytes key \xbd']) self.assertTrue(b'bytes key \xbd' in db) self.assertEqual(db[b'bytes key \xbd'], b'bytes value \xbd') def test_unicode(self): with dbm.ndbm.open(self.filename, 'c') as db: db['Unicode key \U0001f40d'] = 'Unicode value \U0001f40d' with dbm.ndbm.open(self.filename, 'r') as db: self.assertEqual(list(db.keys()), ['Unicode key \U0001f40d'.encode()]) self.assertTrue('Unicode key \U0001f40d'.encode() in db) self.assertTrue('Unicode key \U0001f40d' in db) self.assertEqual(db['Unicode key \U0001f40d'.encode()], 'Unicode value \U0001f40d'.encode()) self.assertEqual(db['Unicode key \U0001f40d'], 'Unicode value \U0001f40d'.encode()) @unittest.skipUnless(support.TESTFN_NONASCII, 'requires OS support of non-ASCII encodings') def test_nonascii_filename(self): filename = support.TESTFN_NONASCII for suffix in ['', '.pag', '.dir', '.db']: self.addCleanup(support.unlink, filename + suffix) with dbm.ndbm.open(filename, 'c') as db: db[b'key'] = b'value' self.assertTrue(any(os.path.exists(filename + suffix) for suffix in ['', '.pag', '.dir', '.db'])) with dbm.ndbm.open(filename, 'r') as db: self.assertEqual(list(db.keys()), [b'key']) self.assertTrue(b'key' in db) self.assertEqual(db[b'key'], b'value') if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_openpty.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_openpty.py
# Test to see if openpty works. (But don't worry if it isn't available.) import os, unittest if not hasattr(os, "openpty"): raise unittest.SkipTest("os.openpty() not available.") class OpenptyTest(unittest.TestCase): def test(self): master, slave = os.openpty() self.addCleanup(os.close, master) self.addCleanup(os.close, slave) if not os.isatty(slave): self.fail("Slave-end of pty is not a terminal.") os.write(slave, b'Ping!') self.assertEqual(os.read(master, 1024), b'Ping!') if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exception_hierarchy.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exception_hierarchy.py
import builtins import os import select import socket import unittest import errno from errno import EEXIST class SubOSError(OSError): pass class SubOSErrorWithInit(OSError): def __init__(self, message, bar): self.bar = bar super().__init__(message) class SubOSErrorWithNew(OSError): def __new__(cls, message, baz): self = super().__new__(cls, message) self.baz = baz return self class SubOSErrorCombinedInitFirst(SubOSErrorWithInit, SubOSErrorWithNew): pass class SubOSErrorCombinedNewFirst(SubOSErrorWithNew, SubOSErrorWithInit): pass class SubOSErrorWithStandaloneInit(OSError): def __init__(self): pass class HierarchyTest(unittest.TestCase): def test_builtin_errors(self): self.assertEqual(OSError.__name__, 'OSError') self.assertIs(IOError, OSError) self.assertIs(EnvironmentError, OSError) def test_socket_errors(self): self.assertIs(socket.error, IOError) self.assertIs(socket.gaierror.__base__, OSError) self.assertIs(socket.herror.__base__, OSError) self.assertIs(socket.timeout.__base__, OSError) def test_select_error(self): self.assertIs(select.error, OSError) # mmap.error is tested in test_mmap _pep_map = """ +-- BlockingIOError EAGAIN, EALREADY, EWOULDBLOCK, EINPROGRESS +-- ChildProcessError ECHILD +-- ConnectionError +-- BrokenPipeError EPIPE, ESHUTDOWN +-- ConnectionAbortedError ECONNABORTED +-- ConnectionRefusedError ECONNREFUSED +-- ConnectionResetError ECONNRESET +-- FileExistsError EEXIST +-- FileNotFoundError ENOENT +-- InterruptedError EINTR +-- IsADirectoryError EISDIR +-- NotADirectoryError ENOTDIR +-- PermissionError EACCES, EPERM +-- ProcessLookupError ESRCH +-- TimeoutError ETIMEDOUT """ def _make_map(s): _map = {} for line in s.splitlines(): line = line.strip('+- ') if not line: continue excname, _, errnames = line.partition(' ') for errname in filter(None, errnames.strip().split(', ')): _map[getattr(errno, errname)] = getattr(builtins, excname) return _map _map = _make_map(_pep_map) def test_errno_mapping(self): # The OSError constructor maps errnos to subclasses # A sample test for the basic functionality e = OSError(EEXIST, "Bad file descriptor") self.assertIs(type(e), FileExistsError) # Exhaustive testing for errcode, exc in self._map.items(): e = OSError(errcode, "Some message") self.assertIs(type(e), exc) othercodes = set(errno.errorcode) - set(self._map) for errcode in othercodes: e = OSError(errcode, "Some message") self.assertIs(type(e), OSError) def test_try_except(self): filename = "some_hopefully_non_existing_file" # This checks that try .. except checks the concrete exception # (FileNotFoundError) and not the base type specified when # PyErr_SetFromErrnoWithFilenameObject was called. # (it is therefore deliberate that it doesn't use assertRaises) try: open(filename) except FileNotFoundError: pass else: self.fail("should have raised a FileNotFoundError") # Another test for PyErr_SetExcFromWindowsErrWithFilenameObject() self.assertFalse(os.path.exists(filename)) try: os.unlink(filename) except FileNotFoundError: pass else: self.fail("should have raised a FileNotFoundError") class AttributesTest(unittest.TestCase): def test_windows_error(self): if os.name == "nt": self.assertIn('winerror', dir(OSError)) else: self.assertNotIn('winerror', dir(OSError)) def test_posix_error(self): e = OSError(EEXIST, "File already exists", "foo.txt") self.assertEqual(e.errno, EEXIST) self.assertEqual(e.args[0], EEXIST) self.assertEqual(e.strerror, "File already exists") self.assertEqual(e.filename, "foo.txt") if os.name == "nt": self.assertEqual(e.winerror, None) @unittest.skipUnless(os.name == "nt", "Windows-specific test") def test_errno_translation(self): # ERROR_ALREADY_EXISTS (183) -> EEXIST e = OSError(0, "File already exists", "foo.txt", 183) self.assertEqual(e.winerror, 183) self.assertEqual(e.errno, EEXIST) self.assertEqual(e.args[0], EEXIST) self.assertEqual(e.strerror, "File already exists") self.assertEqual(e.filename, "foo.txt") def test_blockingioerror(self): args = ("a", "b", "c", "d", "e") for n in range(6): e = BlockingIOError(*args[:n]) with self.assertRaises(AttributeError): e.characters_written e = BlockingIOError("a", "b", 3) self.assertEqual(e.characters_written, 3) e.characters_written = 5 self.assertEqual(e.characters_written, 5) class ExplicitSubclassingTest(unittest.TestCase): def test_errno_mapping(self): # When constructing an OSError subclass, errno mapping isn't done e = SubOSError(EEXIST, "Bad file descriptor") self.assertIs(type(e), SubOSError) def test_init_overridden(self): e = SubOSErrorWithInit("some message", "baz") self.assertEqual(e.bar, "baz") self.assertEqual(e.args, ("some message",)) def test_init_kwdargs(self): e = SubOSErrorWithInit("some message", bar="baz") self.assertEqual(e.bar, "baz") self.assertEqual(e.args, ("some message",)) def test_new_overridden(self): e = SubOSErrorWithNew("some message", "baz") self.assertEqual(e.baz, "baz") self.assertEqual(e.args, ("some message",)) def test_new_kwdargs(self): e = SubOSErrorWithNew("some message", baz="baz") self.assertEqual(e.baz, "baz") self.assertEqual(e.args, ("some message",)) def test_init_new_overridden(self): e = SubOSErrorCombinedInitFirst("some message", "baz") self.assertEqual(e.bar, "baz") self.assertEqual(e.baz, "baz") self.assertEqual(e.args, ("some message",)) e = SubOSErrorCombinedNewFirst("some message", "baz") self.assertEqual(e.bar, "baz") self.assertEqual(e.baz, "baz") self.assertEqual(e.args, ("some message",)) def test_init_standalone(self): # __init__ doesn't propagate to OSError.__init__ (see issue #15229) e = SubOSErrorWithStandaloneInit() self.assertEqual(e.args, ()) self.assertEqual(str(e), '') if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mp_fork_bomb.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mp_fork_bomb.py
import multiprocessing, sys def foo(): print("123") # Because "if __name__ == '__main__'" is missing this will not work # correctly on Windows. However, we should get a RuntimeError rather # than the Windows equivalent of a fork bomb. if len(sys.argv) > 1: multiprocessing.set_start_method(sys.argv[1]) else: multiprocessing.set_start_method('spawn') p = multiprocessing.Process(target=foo) p.start() p.join() sys.exit(p.exitcode)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_frozen.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_frozen.py
"""Basic test of the frozen module (source is in Python/frozen.c).""" # The Python/frozen.c source code contains a marshalled Python module # and therefore depends on the marshal format as well as the bytecode # format. If those formats have been changed then frozen.c needs to be # updated. # # The test_importlib also tests this module but because those tests # are much more complicated, it might be unclear why they are failing. # Invalid marshalled data in frozen.c could case the interpreter to # crash when __hello__ is imported. import sys import unittest from test.support import captured_stdout from importlib import util class TestFrozen(unittest.TestCase): def test_frozen(self): name = '__hello__' if name in sys.modules: del sys.modules[name] with captured_stdout() as out: import __hello__ self.assertEqual(out.getvalue(), 'Hello world!\n') if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_zipfile64.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_zipfile64.py
# Tests of the full ZIP64 functionality of zipfile # The support.requires call is the only reason for keeping this separate # from test_zipfile from test import support # XXX(nnorwitz): disable this test by looking for extralargefile resource, # which doesn't exist. This test takes over 30 minutes to run in general # and requires more disk space than most of the buildbots. support.requires( 'extralargefile', 'test requires loads of disk-space bytes and a long time to run' ) import zipfile, os, unittest import time import sys from tempfile import TemporaryFile from test.support import TESTFN, requires_zlib TESTFN2 = TESTFN + "2" # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 60 class TestsWithSourceFile(unittest.TestCase): def setUp(self): # Create test data. line_gen = ("Test of zipfile line %d." % i for i in range(1000000)) self.data = '\n'.join(line_gen).encode('ascii') # And write it to a file. fp = open(TESTFN, "wb") fp.write(self.data) fp.close() def zipTest(self, f, compression): # Create the ZIP archive. zipfp = zipfile.ZipFile(f, "w", compression) # It will contain enough copies of self.data to reach about 6 GiB of # raw data to store. filecount = 6*1024**3 // len(self.data) next_time = time.monotonic() + _PRINT_WORKING_MSG_INTERVAL for num in range(filecount): zipfp.writestr("testfn%d" % num, self.data) # Print still working message since this test can be really slow if next_time <= time.monotonic(): next_time = time.monotonic() + _PRINT_WORKING_MSG_INTERVAL print(( ' zipTest still writing %d of %d, be patient...' % (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() # Read the ZIP archive zipfp = zipfile.ZipFile(f, "r", compression) for num in range(filecount): self.assertEqual(zipfp.read("testfn%d" % num), self.data) # Print still working message since this test can be really slow if next_time <= time.monotonic(): next_time = time.monotonic() + _PRINT_WORKING_MSG_INTERVAL print(( ' zipTest still reading %d of %d, be patient...' % (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() def testStored(self): # Try the temp file first. If we do TESTFN2 first, then it hogs # gigabytes of disk space for the duration of the test. with TemporaryFile() as f: self.zipTest(f, zipfile.ZIP_STORED) self.assertFalse(f.closed) self.zipTest(TESTFN2, zipfile.ZIP_STORED) @requires_zlib def testDeflated(self): # Try the temp file first. If we do TESTFN2 first, then it hogs # gigabytes of disk space for the duration of the test. with TemporaryFile() as f: self.zipTest(f, zipfile.ZIP_DEFLATED) self.assertFalse(f.closed) self.zipTest(TESTFN2, zipfile.ZIP_DEFLATED) def tearDown(self): for fname in TESTFN, TESTFN2: if os.path.exists(fname): os.remove(fname) class OtherTests(unittest.TestCase): def testMoreThan64kFiles(self): # This test checks that more than 64k files can be added to an archive, # and that the resulting archive can be read properly by ZipFile zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=True) zipf.debug = 100 numfiles = (1 << 16) * 3//2 for i in range(numfiles): zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57)) self.assertEqual(len(zipf.namelist()), numfiles) zipf.close() zipf2 = zipfile.ZipFile(TESTFN, mode="r") self.assertEqual(len(zipf2.namelist()), numfiles) for i in range(numfiles): content = zipf2.read("foo%08d" % i).decode('ascii') self.assertEqual(content, "%d" % (i**3 % 57)) zipf2.close() def testMoreThan64kFilesAppend(self): zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=False) zipf.debug = 100 numfiles = (1 << 16) - 1 for i in range(numfiles): zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57)) self.assertEqual(len(zipf.namelist()), numfiles) with self.assertRaises(zipfile.LargeZipFile): zipf.writestr("foo%08d" % numfiles, b'') self.assertEqual(len(zipf.namelist()), numfiles) zipf.close() zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=False) zipf.debug = 100 self.assertEqual(len(zipf.namelist()), numfiles) with self.assertRaises(zipfile.LargeZipFile): zipf.writestr("foo%08d" % numfiles, b'') self.assertEqual(len(zipf.namelist()), numfiles) zipf.close() zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=True) zipf.debug = 100 self.assertEqual(len(zipf.namelist()), numfiles) numfiles2 = (1 << 16) * 3//2 for i in range(numfiles, numfiles2): zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57)) self.assertEqual(len(zipf.namelist()), numfiles2) zipf.close() zipf2 = zipfile.ZipFile(TESTFN, mode="r") self.assertEqual(len(zipf2.namelist()), numfiles2) for i in range(numfiles2): content = zipf2.read("foo%08d" % i).decode('ascii') self.assertEqual(content, "%d" % (i**3 % 57)) zipf2.close() def tearDown(self): support.unlink(TESTFN) support.unlink(TESTFN2) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bz2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bz2.py
from test import support from test.support import bigmemtest, _4G import unittest from io import BytesIO, DEFAULT_BUFFER_SIZE import os import pickle import glob import pathlib import random import shutil import subprocess import threading from test.support import unlink import _compression import sys # Skip tests if the bz2 module doesn't exist. bz2 = support.import_module('bz2') from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = None def ext_decompress(data): global has_cmdline_bunzip2 if has_cmdline_bunzip2 is None: has_cmdline_bunzip2 = bool(shutil.which('bunzip2')) if has_cmdline_bunzip2: return subprocess.check_output(['bunzip2'], input=data) else: return bz2.decompress(data) class BaseTest(unittest.TestCase): "Base for other testcases." TEXT_LINES = [ b'root:x:0:0:root:/root:/bin/bash\n', b'bin:x:1:1:bin:/bin:\n', b'daemon:x:2:2:daemon:/sbin:\n', b'adm:x:3:4:adm:/var/adm:\n', b'lp:x:4:7:lp:/var/spool/lpd:\n', b'sync:x:5:0:sync:/sbin:/bin/sync\n', b'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n', b'halt:x:7:0:halt:/sbin:/sbin/halt\n', b'mail:x:8:12:mail:/var/spool/mail:\n', b'news:x:9:13:news:/var/spool/news:\n', b'uucp:x:10:14:uucp:/var/spool/uucp:\n', b'operator:x:11:0:operator:/root:\n', b'games:x:12:100:games:/usr/games:\n', b'gopher:x:13:30:gopher:/usr/lib/gopher-data:\n', b'ftp:x:14:50:FTP User:/var/ftp:/bin/bash\n', b'nobody:x:65534:65534:Nobody:/home:\n', b'postfix:x:100:101:postfix:/var/spool/postfix:\n', b'niemeyer:x:500:500::/home/niemeyer:/bin/bash\n', b'postgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\n', b'mysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\n', b'www:x:103:104::/var/www:/bin/false\n', ] TEXT = b''.join(TEXT_LINES) DATA = b'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`' EMPTY_DATA = b'BZh9\x17rE8P\x90\x00\x00\x00\x00' BAD_DATA = b'this is not a valid bzip2 file' # Some tests need more than one block of uncompressed data. Since one block # is at least 100,000 bytes, we gather some data dynamically and compress it. # Note that this assumes that compression works correctly, so we cannot # simply use the bigger test data for all tests. test_size = 0 BIG_TEXT = bytearray(128*1024) for fname in glob.glob(os.path.join(os.path.dirname(__file__), '*.py')): with open(fname, 'rb') as fh: test_size += fh.readinto(memoryview(BIG_TEXT)[test_size:]) if test_size > 128*1024: break BIG_DATA = bz2.compress(BIG_TEXT, compresslevel=1) def setUp(self): self.filename = support.TESTFN def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename) class BZ2FileTest(BaseTest): "Test the BZ2File class." def createTempFile(self, streams=1, suffix=b""): with open(self.filename, "wb") as f: f.write(self.DATA * streams) f.write(suffix) def testBadArgs(self): self.assertRaises(TypeError, BZ2File, 123.456) self.assertRaises(ValueError, BZ2File, os.devnull, "z") self.assertRaises(ValueError, BZ2File, os.devnull, "rx") self.assertRaises(ValueError, BZ2File, os.devnull, "rbt") self.assertRaises(ValueError, BZ2File, os.devnull, compresslevel=0) self.assertRaises(ValueError, BZ2File, os.devnull, compresslevel=10) def testRead(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, float()) self.assertEqual(bz2f.read(), self.TEXT) def testReadBadFile(self): self.createTempFile(streams=0, suffix=self.BAD_DATA) with BZ2File(self.filename) as bz2f: self.assertRaises(OSError, bz2f.read) def testReadMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, float()) self.assertEqual(bz2f.read(), self.TEXT * 5) def testReadMonkeyMultiStream(self): # Test BZ2File.read() on a multi-stream archive where a stream # boundary coincides with the end of the raw read buffer. buffer_size = _compression.BUFFER_SIZE _compression.BUFFER_SIZE = len(self.DATA) try: self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, float()) self.assertEqual(bz2f.read(), self.TEXT * 5) finally: _compression.BUFFER_SIZE = buffer_size def testReadTrailingJunk(self): self.createTempFile(suffix=self.BAD_DATA) with BZ2File(self.filename) as bz2f: self.assertEqual(bz2f.read(), self.TEXT) def testReadMultiStreamTrailingJunk(self): self.createTempFile(streams=5, suffix=self.BAD_DATA) with BZ2File(self.filename) as bz2f: self.assertEqual(bz2f.read(), self.TEXT * 5) def testRead0(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, float()) self.assertEqual(bz2f.read(0), b"") def testReadChunk10(self): self.createTempFile() with BZ2File(self.filename) as bz2f: text = b'' while True: str = bz2f.read(10) if not str: break text += str self.assertEqual(text, self.TEXT) def testReadChunk10MultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: text = b'' while True: str = bz2f.read(10) if not str: break text += str self.assertEqual(text, self.TEXT * 5) def testRead100(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertEqual(bz2f.read(100), self.TEXT[:100]) def testPeek(self): self.createTempFile() with BZ2File(self.filename) as bz2f: pdata = bz2f.peek() self.assertNotEqual(len(pdata), 0) self.assertTrue(self.TEXT.startswith(pdata)) self.assertEqual(bz2f.read(), self.TEXT) def testReadInto(self): self.createTempFile() with BZ2File(self.filename) as bz2f: n = 128 b = bytearray(n) self.assertEqual(bz2f.readinto(b), n) self.assertEqual(b, self.TEXT[:n]) n = len(self.TEXT) - n b = bytearray(len(self.TEXT)) self.assertEqual(bz2f.readinto(b), n) self.assertEqual(b[:n], self.TEXT[-n:]) def testReadLine(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readline, None) for line in self.TEXT_LINES: self.assertEqual(bz2f.readline(), line) def testReadLineMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readline, None) for line in self.TEXT_LINES * 5: self.assertEqual(bz2f.readline(), line) def testReadLines(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readlines, None) self.assertEqual(bz2f.readlines(), self.TEXT_LINES) def testReadLinesMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readlines, None) self.assertEqual(bz2f.readlines(), self.TEXT_LINES * 5) def testIterator(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertEqual(list(iter(bz2f)), self.TEXT_LINES) def testIteratorMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: self.assertEqual(list(iter(bz2f)), self.TEXT_LINES * 5) def testClosedIteratorDeadlock(self): # Issue #3309: Iteration on a closed BZ2File should release the lock. self.createTempFile() bz2f = BZ2File(self.filename) bz2f.close() self.assertRaises(ValueError, next, bz2f) # This call will deadlock if the above call failed to release the lock. self.assertRaises(ValueError, bz2f.readlines) def testWrite(self): with BZ2File(self.filename, "w") as bz2f: self.assertRaises(TypeError, bz2f.write) bz2f.write(self.TEXT) with open(self.filename, 'rb') as f: self.assertEqual(ext_decompress(f.read()), self.TEXT) def testWriteChunks10(self): with BZ2File(self.filename, "w") as bz2f: n = 0 while True: str = self.TEXT[n*10:(n+1)*10] if not str: break bz2f.write(str) n += 1 with open(self.filename, 'rb') as f: self.assertEqual(ext_decompress(f.read()), self.TEXT) def testWriteNonDefaultCompressLevel(self): expected = bz2.compress(self.TEXT, compresslevel=5) with BZ2File(self.filename, "w", compresslevel=5) as bz2f: bz2f.write(self.TEXT) with open(self.filename, "rb") as f: self.assertEqual(f.read(), expected) def testWriteLines(self): with BZ2File(self.filename, "w") as bz2f: self.assertRaises(TypeError, bz2f.writelines) bz2f.writelines(self.TEXT_LINES) # Issue #1535500: Calling writelines() on a closed BZ2File # should raise an exception. self.assertRaises(ValueError, bz2f.writelines, ["a"]) with open(self.filename, 'rb') as f: self.assertEqual(ext_decompress(f.read()), self.TEXT) def testWriteMethodsOnReadOnlyFile(self): with BZ2File(self.filename, "w") as bz2f: bz2f.write(b"abc") with BZ2File(self.filename, "r") as bz2f: self.assertRaises(OSError, bz2f.write, b"a") self.assertRaises(OSError, bz2f.writelines, [b"a"]) def testAppend(self): with BZ2File(self.filename, "w") as bz2f: self.assertRaises(TypeError, bz2f.write) bz2f.write(self.TEXT) with BZ2File(self.filename, "a") as bz2f: self.assertRaises(TypeError, bz2f.write) bz2f.write(self.TEXT) with open(self.filename, 'rb') as f: self.assertEqual(ext_decompress(f.read()), self.TEXT * 2) def testSeekForward(self): self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.seek) bz2f.seek(150) self.assertEqual(bz2f.read(), self.TEXT[150:]) def testSeekForwardAcrossStreams(self): self.createTempFile(streams=2) with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.seek) bz2f.seek(len(self.TEXT) + 150) self.assertEqual(bz2f.read(), self.TEXT[150:]) def testSeekBackwards(self): self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.read(500) bz2f.seek(-150, 1) self.assertEqual(bz2f.read(), self.TEXT[500-150:]) def testSeekBackwardsAcrossStreams(self): self.createTempFile(streams=2) with BZ2File(self.filename) as bz2f: readto = len(self.TEXT) + 100 while readto > 0: readto -= len(bz2f.read(readto)) bz2f.seek(-150, 1) self.assertEqual(bz2f.read(), self.TEXT[100-150:] + self.TEXT) def testSeekBackwardsFromEnd(self): self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(-150, 2) self.assertEqual(bz2f.read(), self.TEXT[len(self.TEXT)-150:]) def testSeekBackwardsFromEndAcrossStreams(self): self.createTempFile(streams=2) with BZ2File(self.filename) as bz2f: bz2f.seek(-1000, 2) self.assertEqual(bz2f.read(), (self.TEXT * 2)[-1000:]) def testSeekPostEnd(self): self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT)) self.assertEqual(bz2f.read(), b"") def testSeekPostEndMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT) * 5) self.assertEqual(bz2f.read(), b"") def testSeekPostEndTwice(self): self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(150000) bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT)) self.assertEqual(bz2f.read(), b"") def testSeekPostEndTwiceMultiStream(self): self.createTempFile(streams=5) with BZ2File(self.filename) as bz2f: bz2f.seek(150000) bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT) * 5) self.assertEqual(bz2f.read(), b"") def testSeekPreStart(self): self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(-150) self.assertEqual(bz2f.tell(), 0) self.assertEqual(bz2f.read(), self.TEXT) def testSeekPreStartMultiStream(self): self.createTempFile(streams=2) with BZ2File(self.filename) as bz2f: bz2f.seek(-150) self.assertEqual(bz2f.tell(), 0) self.assertEqual(bz2f.read(), self.TEXT * 2) def testFileno(self): self.createTempFile() with open(self.filename, 'rb') as rawf: bz2f = BZ2File(rawf) try: self.assertEqual(bz2f.fileno(), rawf.fileno()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.fileno) def testSeekable(self): bz2f = BZ2File(BytesIO(self.DATA)) try: self.assertTrue(bz2f.seekable()) bz2f.read() self.assertTrue(bz2f.seekable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.seekable) bz2f = BZ2File(BytesIO(), "w") try: self.assertFalse(bz2f.seekable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.seekable) src = BytesIO(self.DATA) src.seekable = lambda: False bz2f = BZ2File(src) try: self.assertFalse(bz2f.seekable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.seekable) def testReadable(self): bz2f = BZ2File(BytesIO(self.DATA)) try: self.assertTrue(bz2f.readable()) bz2f.read() self.assertTrue(bz2f.readable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.readable) bz2f = BZ2File(BytesIO(), "w") try: self.assertFalse(bz2f.readable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.readable) def testWritable(self): bz2f = BZ2File(BytesIO(self.DATA)) try: self.assertFalse(bz2f.writable()) bz2f.read() self.assertFalse(bz2f.writable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.writable) bz2f = BZ2File(BytesIO(), "w") try: self.assertTrue(bz2f.writable()) finally: bz2f.close() self.assertRaises(ValueError, bz2f.writable) def testOpenDel(self): self.createTempFile() for i in range(10000): o = BZ2File(self.filename) del o def testOpenNonexistent(self): self.assertRaises(OSError, BZ2File, "/non/existent") def testReadlinesNoNewline(self): # Issue #1191043: readlines() fails on a file containing no newline. data = b'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t' with open(self.filename, "wb") as f: f.write(data) with BZ2File(self.filename) as bz2f: lines = bz2f.readlines() self.assertEqual(lines, [b'Test']) with BZ2File(self.filename) as bz2f: xlines = list(bz2f.readlines()) self.assertEqual(xlines, [b'Test']) def testContextProtocol(self): f = None with BZ2File(self.filename, "wb") as f: f.write(b"xxx") f = BZ2File(self.filename, "rb") f.close() try: with f: pass except ValueError: pass else: self.fail("__enter__ on a closed file didn't raise an exception") try: with BZ2File(self.filename, "wb") as f: 1/0 except ZeroDivisionError: pass else: self.fail("1/0 didn't raise an exception") def testThreading(self): # Issue #7205: Using a BZ2File from several threads shouldn't deadlock. data = b"1" * 2**20 nthreads = 10 with BZ2File(self.filename, 'wb') as f: def comp(): for i in range(5): f.write(data) threads = [threading.Thread(target=comp) for i in range(nthreads)] with support.start_threads(threads): pass def testMixedIterationAndReads(self): self.createTempFile() linelen = len(self.TEXT_LINES[0]) halflen = linelen // 2 with BZ2File(self.filename) as bz2f: bz2f.read(halflen) self.assertEqual(next(bz2f), self.TEXT_LINES[0][halflen:]) self.assertEqual(bz2f.read(), self.TEXT[linelen:]) with BZ2File(self.filename) as bz2f: bz2f.readline() self.assertEqual(next(bz2f), self.TEXT_LINES[1]) self.assertEqual(bz2f.readline(), self.TEXT_LINES[2]) with BZ2File(self.filename) as bz2f: bz2f.readlines() self.assertRaises(StopIteration, next, bz2f) self.assertEqual(bz2f.readlines(), []) def testMultiStreamOrdering(self): # Test the ordering of streams when reading a multi-stream archive. data1 = b"foo" * 1000 data2 = b"bar" * 1000 with BZ2File(self.filename, "w") as bz2f: bz2f.write(data1) with BZ2File(self.filename, "a") as bz2f: bz2f.write(data2) with BZ2File(self.filename) as bz2f: self.assertEqual(bz2f.read(), data1 + data2) def testOpenBytesFilename(self): str_filename = self.filename try: bytes_filename = str_filename.encode("ascii") except UnicodeEncodeError: self.skipTest("Temporary file name needs to be ASCII") with BZ2File(bytes_filename, "wb") as f: f.write(self.DATA) with BZ2File(bytes_filename, "rb") as f: self.assertEqual(f.read(), self.DATA) # Sanity check that we are actually operating on the right file. with BZ2File(str_filename, "rb") as f: self.assertEqual(f.read(), self.DATA) def testOpenPathLikeFilename(self): filename = pathlib.Path(self.filename) with BZ2File(filename, "wb") as f: f.write(self.DATA) with BZ2File(filename, "rb") as f: self.assertEqual(f.read(), self.DATA) def testDecompressLimited(self): """Decompressed data buffering should be limited""" bomb = bz2.compress(b'\0' * int(2e6), compresslevel=9) self.assertLess(len(bomb), _compression.BUFFER_SIZE) decomp = BZ2File(BytesIO(bomb)) self.assertEqual(decomp.read(1), b'\0') max_decomp = 1 + DEFAULT_BUFFER_SIZE self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp, "Excessive amount of data was decompressed") # Tests for a BZ2File wrapping another file object: def testReadBytesIO(self): with BytesIO(self.DATA) as bio: with BZ2File(bio) as bz2f: self.assertRaises(TypeError, bz2f.read, float()) self.assertEqual(bz2f.read(), self.TEXT) self.assertFalse(bio.closed) def testPeekBytesIO(self): with BytesIO(self.DATA) as bio: with BZ2File(bio) as bz2f: pdata = bz2f.peek() self.assertNotEqual(len(pdata), 0) self.assertTrue(self.TEXT.startswith(pdata)) self.assertEqual(bz2f.read(), self.TEXT) def testWriteBytesIO(self): with BytesIO() as bio: with BZ2File(bio, "w") as bz2f: self.assertRaises(TypeError, bz2f.write) bz2f.write(self.TEXT) self.assertEqual(ext_decompress(bio.getvalue()), self.TEXT) self.assertFalse(bio.closed) def testSeekForwardBytesIO(self): with BytesIO(self.DATA) as bio: with BZ2File(bio) as bz2f: self.assertRaises(TypeError, bz2f.seek) bz2f.seek(150) self.assertEqual(bz2f.read(), self.TEXT[150:]) def testSeekBackwardsBytesIO(self): with BytesIO(self.DATA) as bio: with BZ2File(bio) as bz2f: bz2f.read(500) bz2f.seek(-150, 1) self.assertEqual(bz2f.read(), self.TEXT[500-150:]) def test_read_truncated(self): # Drop the eos_magic field (6 bytes) and CRC (4 bytes). truncated = self.DATA[:-10] with BZ2File(BytesIO(truncated)) as f: self.assertRaises(EOFError, f.read) with BZ2File(BytesIO(truncated)) as f: self.assertEqual(f.read(len(self.TEXT)), self.TEXT) self.assertRaises(EOFError, f.read, 1) # Incomplete 4-byte file header, and block header of at least 146 bits. for i in range(22): with BZ2File(BytesIO(truncated[:i])) as f: self.assertRaises(EOFError, f.read, 1) class BZ2CompressorTest(BaseTest): def testCompress(self): bz2c = BZ2Compressor() self.assertRaises(TypeError, bz2c.compress) data = bz2c.compress(self.TEXT) data += bz2c.flush() self.assertEqual(ext_decompress(data), self.TEXT) def testCompressEmptyString(self): bz2c = BZ2Compressor() data = bz2c.compress(b'') data += bz2c.flush() self.assertEqual(data, self.EMPTY_DATA) def testCompressChunks10(self): bz2c = BZ2Compressor() n = 0 data = b'' while True: str = self.TEXT[n*10:(n+1)*10] if not str: break data += bz2c.compress(str) n += 1 data += bz2c.flush() self.assertEqual(ext_decompress(data), self.TEXT) @bigmemtest(size=_4G + 100, memuse=2) def testCompress4G(self, size): # "Test BZ2Compressor.compress()/flush() with >4GiB input" bz2c = BZ2Compressor() data = b"x" * size try: compressed = bz2c.compress(data) compressed += bz2c.flush() finally: data = None # Release memory data = bz2.decompress(compressed) try: self.assertEqual(len(data), size) self.assertEqual(len(data.strip(b"x")), 0) finally: data = None def testPickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError): pickle.dumps(BZ2Compressor(), proto) class BZ2DecompressorTest(BaseTest): def test_Constructor(self): self.assertRaises(TypeError, BZ2Decompressor, 42) def testDecompress(self): bz2d = BZ2Decompressor() self.assertRaises(TypeError, bz2d.decompress) text = bz2d.decompress(self.DATA) self.assertEqual(text, self.TEXT) def testDecompressChunks10(self): bz2d = BZ2Decompressor() text = b'' n = 0 while True: str = self.DATA[n*10:(n+1)*10] if not str: break text += bz2d.decompress(str) n += 1 self.assertEqual(text, self.TEXT) def testDecompressUnusedData(self): bz2d = BZ2Decompressor() unused_data = b"this is unused data" text = bz2d.decompress(self.DATA+unused_data) self.assertEqual(text, self.TEXT) self.assertEqual(bz2d.unused_data, unused_data) def testEOFError(self): bz2d = BZ2Decompressor() text = bz2d.decompress(self.DATA) self.assertRaises(EOFError, bz2d.decompress, b"anything") self.assertRaises(EOFError, bz2d.decompress, b"") @bigmemtest(size=_4G + 100, memuse=3.3) def testDecompress4G(self, size): # "Test BZ2Decompressor.decompress() with >4GiB input" blocksize = 10 * 1024 * 1024 block = random.getrandbits(blocksize * 8).to_bytes(blocksize, 'little') try: data = block * (size // blocksize + 1) compressed = bz2.compress(data) bz2d = BZ2Decompressor() decompressed = bz2d.decompress(compressed) self.assertTrue(decompressed == data) finally: data = None compressed = None decompressed = None def testPickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError): pickle.dumps(BZ2Decompressor(), proto) def testDecompressorChunksMaxsize(self): bzd = BZ2Decompressor() max_length = 100 out = [] # Feed some input len_ = len(self.BIG_DATA) - 64 out.append(bzd.decompress(self.BIG_DATA[:len_], max_length=max_length)) self.assertFalse(bzd.needs_input) self.assertEqual(len(out[-1]), max_length) # Retrieve more data without providing more input out.append(bzd.decompress(b'', max_length=max_length)) self.assertFalse(bzd.needs_input) self.assertEqual(len(out[-1]), max_length) # Retrieve more data while providing more input out.append(bzd.decompress(self.BIG_DATA[len_:], max_length=max_length)) self.assertLessEqual(len(out[-1]), max_length) # Retrieve remaining uncompressed data while not bzd.eof: out.append(bzd.decompress(b'', max_length=max_length)) self.assertLessEqual(len(out[-1]), max_length) out = b"".join(out) self.assertEqual(out, self.BIG_TEXT) self.assertEqual(bzd.unused_data, b"") def test_decompressor_inputbuf_1(self): # Test reusing input buffer after moving existing # contents to beginning bzd = BZ2Decompressor() out = [] # Create input buffer and fill it self.assertEqual(bzd.decompress(self.DATA[:100], max_length=0), b'') # Retrieve some results, freeing capacity at beginning # of input buffer out.append(bzd.decompress(b'', 2)) # Add more data that fits into input buffer after # moving existing data to beginning out.append(bzd.decompress(self.DATA[100:105], 15)) # Decompress rest of data out.append(bzd.decompress(self.DATA[105:])) self.assertEqual(b''.join(out), self.TEXT) def test_decompressor_inputbuf_2(self): # Test reusing input buffer by appending data at the # end right away bzd = BZ2Decompressor() out = [] # Create input buffer and empty it self.assertEqual(bzd.decompress(self.DATA[:200], max_length=0), b'') out.append(bzd.decompress(b'')) # Fill buffer with new data out.append(bzd.decompress(self.DATA[200:280], 2)) # Append some more data, not enough to require resize out.append(bzd.decompress(self.DATA[280:300], 2)) # Decompress rest of data out.append(bzd.decompress(self.DATA[300:])) self.assertEqual(b''.join(out), self.TEXT) def test_decompressor_inputbuf_3(self): # Test reusing input buffer after extending it bzd = BZ2Decompressor() out = [] # Create almost full input buffer out.append(bzd.decompress(self.DATA[:200], 5)) # Add even more data to it, requiring resize out.append(bzd.decompress(self.DATA[200:300], 5)) # Decompress rest of data out.append(bzd.decompress(self.DATA[300:])) self.assertEqual(b''.join(out), self.TEXT) def test_failure(self): bzd = BZ2Decompressor() self.assertRaises(Exception, bzd.decompress, self.BAD_DATA * 30) # Previously, a second call could crash due to internal inconsistency self.assertRaises(Exception, bzd.decompress, self.BAD_DATA * 30) @support.refcount_test def test_refleaks_in___init__(self): gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') bzd = BZ2Decompressor() refs_before = gettotalrefcount() for i in range(100): bzd.__init__() self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) class CompressDecompressTest(BaseTest): def testCompress(self): data = bz2.compress(self.TEXT) self.assertEqual(ext_decompress(data), self.TEXT) def testCompressEmptyString(self): text = bz2.compress(b'') self.assertEqual(text, self.EMPTY_DATA) def testDecompress(self): text = bz2.decompress(self.DATA) self.assertEqual(text, self.TEXT) def testDecompressEmpty(self): text = bz2.decompress(b"") self.assertEqual(text, b"") def testDecompressToEmptyString(self): text = bz2.decompress(self.EMPTY_DATA) self.assertEqual(text, b'') def testDecompressIncomplete(self): self.assertRaises(ValueError, bz2.decompress, self.DATA[:-10]) def testDecompressBadData(self): self.assertRaises(OSError, bz2.decompress, self.BAD_DATA) def testDecompressMultiStream(self): text = bz2.decompress(self.DATA * 5) self.assertEqual(text, self.TEXT * 5) def testDecompressTrailingJunk(self): text = bz2.decompress(self.DATA + self.BAD_DATA) self.assertEqual(text, self.TEXT) def testDecompressMultiStreamTrailingJunk(self): text = bz2.decompress(self.DATA * 5 + self.BAD_DATA) self.assertEqual(text, self.TEXT * 5) class OpenTest(BaseTest): "Test the open function." def open(self, *args, **kwargs): return bz2.open(*args, **kwargs) def test_binary_modes(self): for mode in ("wb", "xb"): if mode == "xb": unlink(self.filename) with self.open(self.filename, mode) as f: f.write(self.TEXT) with open(self.filename, "rb") as f: file_data = ext_decompress(f.read()) self.assertEqual(file_data, self.TEXT)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_winsound.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_winsound.py
# Ridiculously simple test of the winsound module for Windows. import functools import time import unittest from test import support support.requires('audio') winsound = support.import_module('winsound') # Unless we actually have an ear in the room, we have no idea whether a sound # actually plays, and it's incredibly flaky trying to figure out if a sound # even *should* play. Instead of guessing, just call the function and assume # it either passed or raised the RuntimeError we expect in case of failure. def sound_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: ret = func(*args, **kwargs) except RuntimeError as e: if support.verbose: print(func.__name__, 'failed:', e) else: if support.verbose: print(func.__name__, 'returned') return ret return wrapper safe_Beep = sound_func(winsound.Beep) safe_MessageBeep = sound_func(winsound.MessageBeep) safe_PlaySound = sound_func(winsound.PlaySound) class BeepTest(unittest.TestCase): def test_errors(self): self.assertRaises(TypeError, winsound.Beep) self.assertRaises(ValueError, winsound.Beep, 36, 75) self.assertRaises(ValueError, winsound.Beep, 32768, 75) def test_extremes(self): safe_Beep(37, 75) safe_Beep(32767, 75) def test_increasingfrequency(self): for i in range(100, 2000, 100): safe_Beep(i, 75) def test_keyword_args(self): safe_Beep(duration=75, frequency=2000) class MessageBeepTest(unittest.TestCase): def tearDown(self): time.sleep(0.5) def test_default(self): self.assertRaises(TypeError, winsound.MessageBeep, "bad") self.assertRaises(TypeError, winsound.MessageBeep, 42, 42) safe_MessageBeep() def test_ok(self): safe_MessageBeep(winsound.MB_OK) def test_asterisk(self): safe_MessageBeep(winsound.MB_ICONASTERISK) def test_exclamation(self): safe_MessageBeep(winsound.MB_ICONEXCLAMATION) def test_hand(self): safe_MessageBeep(winsound.MB_ICONHAND) def test_question(self): safe_MessageBeep(winsound.MB_ICONQUESTION) def test_keyword_args(self): safe_MessageBeep(type=winsound.MB_OK) class PlaySoundTest(unittest.TestCase): def test_errors(self): self.assertRaises(TypeError, winsound.PlaySound) self.assertRaises(TypeError, winsound.PlaySound, "bad", "bad") self.assertRaises( RuntimeError, winsound.PlaySound, "none", winsound.SND_ASYNC | winsound.SND_MEMORY ) self.assertRaises(TypeError, winsound.PlaySound, b"bad", 0) self.assertRaises(TypeError, winsound.PlaySound, "bad", winsound.SND_MEMORY) self.assertRaises(TypeError, winsound.PlaySound, 1, 0) # embedded null character self.assertRaises(ValueError, winsound.PlaySound, 'bad\0', 0) def test_keyword_args(self): safe_PlaySound(flags=winsound.SND_ALIAS, sound="SystemExit") def test_snd_memory(self): with open(support.findfile('pluck-pcm8.wav', subdir='audiodata'), 'rb') as f: audio_data = f.read() safe_PlaySound(audio_data, winsound.SND_MEMORY) audio_data = bytearray(audio_data) safe_PlaySound(audio_data, winsound.SND_MEMORY) def test_snd_filename(self): fn = support.findfile('pluck-pcm8.wav', subdir='audiodata') safe_PlaySound(fn, winsound.SND_FILENAME | winsound.SND_NODEFAULT) def test_aliases(self): aliases = [ "SystemAsterisk", "SystemExclamation", "SystemExit", "SystemHand", "SystemQuestion", ] for alias in aliases: with self.subTest(alias=alias): safe_PlaySound(alias, winsound.SND_ALIAS) def test_alias_fallback(self): safe_PlaySound('!"$%&/(#+*', winsound.SND_ALIAS) def test_alias_nofallback(self): safe_PlaySound('!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT) def test_stopasync(self): safe_PlaySound( 'SystemQuestion', winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP ) time.sleep(0.5) safe_PlaySound('SystemQuestion', winsound.SND_ALIAS | winsound.SND_NOSTOP) # Issue 8367: PlaySound(None, winsound.SND_PURGE) # does not raise on systems without a sound card. winsound.PlaySound(None, winsound.SND_PURGE) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_extcall.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_extcall.py
"""Doctest for method/function calls. We're going the use these types for extra testing >>> from collections import UserList >>> from collections import UserDict We're defining four helper functions >>> def e(a,b): ... print(a, b) >>> def f(*a, **k): ... print(a, support.sortdict(k)) >>> def g(x, *y, **z): ... print(x, y, support.sortdict(z)) >>> def h(j=1, a=2, h=3): ... print(j, a, h) Argument list examples >>> f() () {} >>> f(1) (1,) {} >>> f(1, 2) (1, 2) {} >>> f(1, 2, 3) (1, 2, 3) {} >>> f(1, 2, 3, *(4, 5)) (1, 2, 3, 4, 5) {} >>> f(1, 2, 3, *[4, 5]) (1, 2, 3, 4, 5) {} >>> f(*[1, 2, 3], 4, 5) (1, 2, 3, 4, 5) {} >>> f(1, 2, 3, *UserList([4, 5])) (1, 2, 3, 4, 5) {} >>> f(1, 2, 3, *[4, 5], *[6, 7]) (1, 2, 3, 4, 5, 6, 7) {} >>> f(1, *[2, 3], 4, *[5, 6], 7) (1, 2, 3, 4, 5, 6, 7) {} >>> f(*UserList([1, 2]), *UserList([3, 4]), 5, *UserList([6, 7])) (1, 2, 3, 4, 5, 6, 7) {} Here we add keyword arguments >>> f(1, 2, 3, **{'a':4, 'b':5}) (1, 2, 3) {'a': 4, 'b': 5} >>> f(1, 2, **{'a': -1, 'b': 5}, **{'a': 4, 'c': 6}) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'a' >>> f(1, 2, **{'a': -1, 'b': 5}, a=4, c=6) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'a' >>> f(1, 2, a=3, **{'a': 4}, **{'a': 5}) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'a' >>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7}) (1, 2, 3, 4, 5) {'a': 6, 'b': 7} >>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9}) (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5} >>> f(1, 2, 3, *[4, 5], **{'c': 8}, **{'a':6, 'b':7}) (1, 2, 3, 4, 5) {'a': 6, 'b': 7, 'c': 8} >>> f(1, 2, 3, *(4, 5), x=6, y=7, **{'a':8, 'b': 9}) (1, 2, 3, 4, 5) {'a': 8, 'b': 9, 'x': 6, 'y': 7} >>> f(1, 2, 3, **UserDict(a=4, b=5)) (1, 2, 3) {'a': 4, 'b': 5} >>> f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7)) (1, 2, 3, 4, 5) {'a': 6, 'b': 7} >>> f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9)) (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5} >>> f(1, 2, 3, *(4, 5), x=6, y=7, **UserDict(a=8, b=9)) (1, 2, 3, 4, 5) {'a': 8, 'b': 9, 'x': 6, 'y': 7} Examples with invalid arguments (TypeErrors). We're also testing the function names in the exception messages. Verify clearing of SF bug #733667 >>> e(c=4) Traceback (most recent call last): ... TypeError: e() got an unexpected keyword argument 'c' >>> g() Traceback (most recent call last): ... TypeError: g() missing 1 required positional argument: 'x' >>> g(*()) Traceback (most recent call last): ... TypeError: g() missing 1 required positional argument: 'x' >>> g(*(), **{}) Traceback (most recent call last): ... TypeError: g() missing 1 required positional argument: 'x' >>> g(1) 1 () {} >>> g(1, 2) 1 (2,) {} >>> g(1, 2, 3) 1 (2, 3) {} >>> g(1, 2, 3, *(4, 5)) 1 (2, 3, 4, 5) {} >>> class Nothing: pass ... >>> g(*Nothing()) Traceback (most recent call last): ... TypeError: g() argument after * must be an iterable, not Nothing >>> class Nothing: ... def __len__(self): return 5 ... >>> g(*Nothing()) Traceback (most recent call last): ... TypeError: g() argument after * must be an iterable, not Nothing >>> class Nothing(): ... def __len__(self): return 5 ... def __getitem__(self, i): ... if i<3: return i ... else: raise IndexError(i) ... >>> g(*Nothing()) 0 (1, 2) {} >>> class Nothing: ... def __init__(self): self.c = 0 ... def __iter__(self): return self ... def __next__(self): ... if self.c == 4: ... raise StopIteration ... c = self.c ... self.c += 1 ... return c ... >>> g(*Nothing()) 0 (1, 2, 3) {} Check for issue #4806: Does a TypeError in a generator get propagated with the right error message? (Also check with other iterables.) >>> def broken(): raise TypeError("myerror") ... >>> g(*(broken() for i in range(1))) Traceback (most recent call last): ... TypeError: myerror >>> g(*range(1), *(broken() for i in range(1))) Traceback (most recent call last): ... TypeError: myerror >>> class BrokenIterable1: ... def __iter__(self): ... raise TypeError('myerror') ... >>> g(*BrokenIterable1()) Traceback (most recent call last): ... TypeError: myerror >>> g(*range(1), *BrokenIterable1()) Traceback (most recent call last): ... TypeError: myerror >>> class BrokenIterable2: ... def __iter__(self): ... yield 0 ... raise TypeError('myerror') ... >>> g(*BrokenIterable2()) Traceback (most recent call last): ... TypeError: myerror >>> g(*range(1), *BrokenIterable2()) Traceback (most recent call last): ... TypeError: myerror >>> class BrokenSequence: ... def __getitem__(self, idx): ... raise TypeError('myerror') ... >>> g(*BrokenSequence()) Traceback (most recent call last): ... TypeError: myerror >>> g(*range(1), *BrokenSequence()) Traceback (most recent call last): ... TypeError: myerror Make sure that the function doesn't stomp the dictionary >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d2 = d.copy() >>> g(1, d=4, **d) 1 () {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> d == d2 True What about willful misconduct? >>> def saboteur(**kw): ... kw['x'] = 'm' ... return kw >>> d = {} >>> kw = saboteur(a=1, **d) >>> d {} >>> g(1, 2, 3, **{'x': 4, 'y': 5}) Traceback (most recent call last): ... TypeError: g() got multiple values for argument 'x' >>> f(**{1:2}) Traceback (most recent call last): ... TypeError: f() keywords must be strings >>> h(**{'e': 2}) Traceback (most recent call last): ... TypeError: h() got an unexpected keyword argument 'e' >>> h(*h) Traceback (most recent call last): ... TypeError: h() argument after * must be an iterable, not function >>> h(1, *h) Traceback (most recent call last): ... TypeError: h() argument after * must be an iterable, not function >>> h(*[1], *h) Traceback (most recent call last): ... TypeError: h() argument after * must be an iterable, not function >>> dir(*h) Traceback (most recent call last): ... TypeError: dir() argument after * must be an iterable, not function >>> None(*h) Traceback (most recent call last): ... TypeError: NoneType object argument after * must be an iterable, \ not function >>> h(**h) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not function >>> h(**[]) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not list >>> h(a=1, **h) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not function >>> h(a=1, **[]) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not list >>> h(**{'a': 1}, **h) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not function >>> h(**{'a': 1}, **[]) Traceback (most recent call last): ... TypeError: h() argument after ** must be a mapping, not list >>> dir(**h) Traceback (most recent call last): ... TypeError: dir() argument after ** must be a mapping, not function >>> None(**h) Traceback (most recent call last): ... TypeError: NoneType object argument after ** must be a mapping, \ not function >>> dir(b=1, **{'b': 1}) Traceback (most recent call last): ... TypeError: dir() got multiple values for keyword argument 'b' Another helper function >>> def f2(*a, **b): ... return a, b >>> d = {} >>> for i in range(512): ... key = 'k%d' % i ... d[key] = i >>> a, b = f2(1, *(2,3), **d) >>> len(a), len(b), b == d (3, 512, True) >>> class Foo: ... def method(self, arg1, arg2): ... return arg1+arg2 >>> x = Foo() >>> Foo.method(*(x, 1, 2)) 3 >>> Foo.method(x, *(1, 2)) 3 >>> Foo.method(*(1, 2, 3)) 5 >>> Foo.method(1, *[2, 3]) 5 A PyCFunction that takes only positional parameters should allow an empty keyword dictionary to pass without a complaint, but raise a TypeError if te dictionary is not empty >>> try: ... silence = id(1, *{}) ... True ... except: ... False True >>> id(1, **{'foo': 1}) Traceback (most recent call last): ... TypeError: id() takes no keyword arguments A corner case of keyword dictionary items being deleted during the function call setup. See <http://bugs.python.org/issue2016>. >>> class Name(str): ... def __eq__(self, other): ... try: ... del x[self] ... except KeyError: ... pass ... return str.__eq__(self, other) ... def __hash__(self): ... return str.__hash__(self) >>> x = {Name("a"):1, Name("b"):2} >>> def f(a, b): ... print(a,b) >>> f(**x) 1 2 Too many arguments: >>> def f(): pass >>> f(1) Traceback (most recent call last): ... TypeError: f() takes 0 positional arguments but 1 was given >>> def f(a): pass >>> f(1, 2) Traceback (most recent call last): ... TypeError: f() takes 1 positional argument but 2 were given >>> def f(a, b=1): pass >>> f(1, 2, 3) Traceback (most recent call last): ... TypeError: f() takes from 1 to 2 positional arguments but 3 were given >>> def f(*, kw): pass >>> f(1, kw=3) Traceback (most recent call last): ... TypeError: f() takes 0 positional arguments but 1 positional argument (and 1 keyword-only argument) were given >>> def f(*, kw, b): pass >>> f(1, 2, 3, b=3, kw=3) Traceback (most recent call last): ... TypeError: f() takes 0 positional arguments but 3 positional arguments (and 2 keyword-only arguments) were given >>> def f(a, b=2, *, kw): pass >>> f(2, 3, 4, kw=4) Traceback (most recent call last): ... TypeError: f() takes from 1 to 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given Too few and missing arguments: >>> def f(a): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 1 required positional argument: 'a' >>> def f(a, b): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 2 required positional arguments: 'a' and 'b' >>> def f(a, b, c): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 3 required positional arguments: 'a', 'b', and 'c' >>> def f(a, b, c, d, e): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 5 required positional arguments: 'a', 'b', 'c', 'd', and 'e' >>> def f(a, b=4, c=5, d=5): pass >>> f(c=12, b=9) Traceback (most recent call last): ... TypeError: f() missing 1 required positional argument: 'a' Same with keyword only args: >>> def f(*, w): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 1 required keyword-only argument: 'w' >>> def f(*, a, b, c, d, e): pass >>> f() Traceback (most recent call last): ... TypeError: f() missing 5 required keyword-only arguments: 'a', 'b', 'c', 'd', and 'e' """ import sys from test import support def test_main(): support.run_doctest(sys.modules[__name__], True) if __name__ == '__main__': test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future8.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future8.py
"""This is a test""" from __future__ import * def f(x): def g(y): return x + y return g print(f(2)(4))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/sortperf.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/sortperf.py
"""Sort performance test. See main() for command line syntax. See tabulate() for output format. """ import sys import time import random import marshal import tempfile import os td = tempfile.gettempdir() def randfloats(n): """Return a list of n random floats in [0, 1).""" # Generating floats is expensive, so this writes them out to a file in # a temp directory. If the file already exists, it just reads them # back in and shuffles them a bit. fn = os.path.join(td, "rr%06d" % n) try: fp = open(fn, "rb") except OSError: r = random.random result = [r() for i in range(n)] try: try: fp = open(fn, "wb") marshal.dump(result, fp) fp.close() fp = None finally: if fp: try: os.unlink(fn) except OSError: pass except OSError as msg: print("can't write", fn, ":", msg) else: result = marshal.load(fp) fp.close() # Shuffle it a bit... for i in range(10): i = random.randrange(n) temp = result[:i] del result[:i] temp.reverse() result.extend(temp) del temp assert len(result) == n return result def flush(): sys.stdout.flush() def doit(L): t0 = time.perf_counter() L.sort() t1 = time.perf_counter() print("%6.2f" % (t1-t0), end=' ') flush() def tabulate(r): r"""Tabulate sort speed for lists of various sizes. The sizes are 2**i for i in r (the argument, a list). The output displays i, 2**i, and the time to sort arrays of 2**i floating point numbers with the following properties: *sort: random data \sort: descending data /sort: ascending data 3sort: ascending, then 3 random exchanges +sort: ascending, then 10 random at the end %sort: ascending, then randomly replace 1% of the elements w/ random values ~sort: many duplicates =sort: all equal !sort: worst case scenario """ cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"]) fmt = ("%2s %7s" + " %6s"*len(cases)) print(fmt % (("i", "2**i") + cases)) for i in r: n = 1 << i L = randfloats(n) print("%2d %7d" % (i, n), end=' ') flush() doit(L) # *sort L.reverse() doit(L) # \sort doit(L) # /sort # Do 3 random exchanges. for dummy in range(3): i1 = random.randrange(n) i2 = random.randrange(n) L[i1], L[i2] = L[i2], L[i1] doit(L) # 3sort # Replace the last 10 with random floats. if n >= 10: L[-10:] = [random.random() for dummy in range(10)] doit(L) # +sort # Replace 1% of the elements at random. for dummy in range(n // 100): L[random.randrange(n)] = random.random() doit(L) # %sort # Arrange for lots of duplicates. if n > 4: del L[4:] L = L * (n // 4) # Force the elements to be distinct objects, else timings can be # artificially low. L = list(map(lambda x: --x, L)) doit(L) # ~sort del L # All equal. Again, force the elements to be distinct objects. L = list(map(abs, [-0.5] * n)) doit(L) # =sort del L # This one looks like [3, 2, 1, 0, 0, 1, 2, 3]. It was a bad case # for an older implementation of quicksort, which used the median # of the first, last and middle elements as the pivot. half = n // 2 L = list(range(half - 1, -1, -1)) L.extend(range(half)) # Force to float, so that the timings are comparable. This is # significantly faster if we leave them as ints. L = list(map(float, L)) doit(L) # !sort print() def main(): """Main program when invoked as a script. One argument: tabulate a single row. Two arguments: tabulate a range (inclusive). Extra arguments are used to seed the random generator. """ # default range (inclusive) k1 = 15 k2 = 20 if sys.argv[1:]: # one argument: single point k1 = k2 = int(sys.argv[1]) if sys.argv[2:]: # two arguments: specify range k2 = int(sys.argv[2]) if sys.argv[3:]: # derive random seed from remaining arguments x = 1 for a in sys.argv[3:]: x = 69069 * x + hash(a) random.seed(x) r = range(k1, k2+1) # include the end point tabulate(r) if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tix.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tix.py
import unittest from test import support import sys # Skip this test if the _tkinter module wasn't built. _tkinter = support.import_module('_tkinter') # Skip test if tk cannot be initialized. support.requires('gui') from tkinter import tix, TclError class TestTix(unittest.TestCase): def setUp(self): try: self.root = tix.Tk() except TclError: if sys.platform.startswith('win'): self.fail('Tix should always be available on Windows') self.skipTest('Tix not available') else: self.addCleanup(self.root.destroy) def test_tix_available(self): # this test is just here to make setUp run pass if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bad_coding2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bad_coding2.py
#coding: utf8 print('我')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mp_preload.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/mp_preload.py
import multiprocessing multiprocessing.Lock() def f(): print("ok") if __name__ == "__main__": ctx = multiprocessing.get_context("forkserver") modname = "test.mp_preload" # Make sure it's importable __import__(modname) ctx.set_forkserver_preload([modname]) proc = ctx.Process(target=f) proc.start() proc.join()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_regrtest.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_regrtest.py
""" Tests of regrtest.py. Note: test_regrtest cannot be run twice in parallel. """ import contextlib import faulthandler import io import os.path import platform import re import subprocess import sys import sysconfig import tempfile import textwrap import unittest from test import libregrtest from test import support from test.libregrtest import utils Py_DEBUG = hasattr(sys, 'gettotalrefcount') ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..') ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR)) LOG_PREFIX = r'[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?' TEST_INTERRUPTED = textwrap.dedent(""" from signal import SIGINT try: from _testcapi import raise_signal raise_signal(SIGINT) except ImportError: import os os.kill(os.getpid(), SIGINT) """) class ParseArgsTestCase(unittest.TestCase): """ Test regrtest's argument parsing, function _parse_args(). """ def checkError(self, args, msg): with support.captured_stderr() as err, self.assertRaises(SystemExit): libregrtest._parse_args(args) self.assertIn(msg, err.getvalue()) def test_help(self): for opt in '-h', '--help': with self.subTest(opt=opt): with support.captured_stdout() as out, \ self.assertRaises(SystemExit): libregrtest._parse_args([opt]) self.assertIn('Run Python regression tests.', out.getvalue()) @unittest.skipUnless(hasattr(faulthandler, 'dump_traceback_later'), "faulthandler.dump_traceback_later() required") def test_timeout(self): ns = libregrtest._parse_args(['--timeout', '4.2']) self.assertEqual(ns.timeout, 4.2) self.checkError(['--timeout'], 'expected one argument') self.checkError(['--timeout', 'foo'], 'invalid float value') def test_wait(self): ns = libregrtest._parse_args(['--wait']) self.assertTrue(ns.wait) def test_worker_args(self): ns = libregrtest._parse_args(['--worker-args', '[[], {}]']) self.assertEqual(ns.worker_args, '[[], {}]') self.checkError(['--worker-args'], 'expected one argument') def test_start(self): for opt in '-S', '--start': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.start, 'foo') self.checkError([opt], 'expected one argument') def test_verbose(self): ns = libregrtest._parse_args(['-v']) self.assertEqual(ns.verbose, 1) ns = libregrtest._parse_args(['-vvv']) self.assertEqual(ns.verbose, 3) ns = libregrtest._parse_args(['--verbose']) self.assertEqual(ns.verbose, 1) ns = libregrtest._parse_args(['--verbose'] * 3) self.assertEqual(ns.verbose, 3) ns = libregrtest._parse_args([]) self.assertEqual(ns.verbose, 0) def test_verbose2(self): for opt in '-w', '--verbose2': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.verbose2) def test_verbose3(self): for opt in '-W', '--verbose3': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.verbose3) def test_quiet(self): for opt in '-q', '--quiet': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) def test_slowest(self): for opt in '-o', '--slowest': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.print_slow) def test_header(self): ns = libregrtest._parse_args(['--header']) self.assertTrue(ns.header) ns = libregrtest._parse_args(['--verbose']) self.assertTrue(ns.header) def test_randomize(self): for opt in '-r', '--randomize': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.randomize) def test_randseed(self): ns = libregrtest._parse_args(['--randseed', '12345']) self.assertEqual(ns.random_seed, 12345) self.assertTrue(ns.randomize) self.checkError(['--randseed'], 'expected one argument') self.checkError(['--randseed', 'foo'], 'invalid int value') def test_fromfile(self): for opt in '-f', '--fromfile': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.fromfile, 'foo') self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo', '-s'], "don't go together") def test_exclude(self): for opt in '-x', '--exclude': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.exclude) def test_single(self): for opt in '-s', '--single': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.single) self.checkError([opt, '-f', 'foo'], "don't go together") def test_match(self): for opt in '-m', '--match': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'pattern']) self.assertEqual(ns.match_tests, ['pattern']) self.checkError([opt], 'expected one argument') ns = libregrtest._parse_args(['-m', 'pattern1', '-m', 'pattern2']) self.assertEqual(ns.match_tests, ['pattern1', 'pattern2']) self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, "w") as fp: print('matchfile1', file=fp) print('matchfile2', file=fp) filename = os.path.abspath(support.TESTFN) ns = libregrtest._parse_args(['-m', 'match', '--matchfile', filename]) self.assertEqual(ns.match_tests, ['match', 'matchfile1', 'matchfile2']) def test_failfast(self): for opt in '-G', '--failfast': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '-v']) self.assertTrue(ns.failfast) ns = libregrtest._parse_args([opt, '-W']) self.assertTrue(ns.failfast) self.checkError([opt], '-G/--failfast needs either -v or -W') def test_use(self): for opt in '-u', '--use': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'gui,network']) self.assertEqual(ns.use_resources, ['gui', 'network']) ns = libregrtest._parse_args([opt, 'gui,none,network']) self.assertEqual(ns.use_resources, ['network']) expected = list(libregrtest.ALL_RESOURCES) expected.remove('gui') ns = libregrtest._parse_args([opt, 'all,-gui']) self.assertEqual(ns.use_resources, expected) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid resource') # all + a resource not part of "all" ns = libregrtest._parse_args([opt, 'all,tzdata']) self.assertEqual(ns.use_resources, list(libregrtest.ALL_RESOURCES) + ['tzdata']) # test another resource which is not part of "all" ns = libregrtest._parse_args([opt, 'extralargefile']) self.assertEqual(ns.use_resources, ['extralargefile']) def test_memlimit(self): for opt in '-M', '--memlimit': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '4G']) self.assertEqual(ns.memlimit, '4G') self.checkError([opt], 'expected one argument') def test_testdir(self): ns = libregrtest._parse_args(['--testdir', 'foo']) self.assertEqual(ns.testdir, os.path.join(support.SAVEDCWD, 'foo')) self.checkError(['--testdir'], 'expected one argument') def test_runleaks(self): for opt in '-L', '--runleaks': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.runleaks) def test_huntrleaks(self): for opt in '-R', '--huntrleaks': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, ':']) self.assertEqual(ns.huntrleaks, (5, 4, 'reflog.txt')) ns = libregrtest._parse_args([opt, '6:']) self.assertEqual(ns.huntrleaks, (6, 4, 'reflog.txt')) ns = libregrtest._parse_args([opt, ':3']) self.assertEqual(ns.huntrleaks, (5, 3, 'reflog.txt')) ns = libregrtest._parse_args([opt, '6:3:leaks.log']) self.assertEqual(ns.huntrleaks, (6, 3, 'leaks.log')) self.checkError([opt], 'expected one argument') self.checkError([opt, '6'], 'needs 2 or 3 colon-separated arguments') self.checkError([opt, 'foo:'], 'invalid huntrleaks value') self.checkError([opt, '6:foo'], 'invalid huntrleaks value') def test_multiprocess(self): for opt in '-j', '--multiprocess': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '2']) self.assertEqual(ns.use_mp, 2) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid int value') self.checkError([opt, '2', '-T'], "don't go together") self.checkError([opt, '0', '-T'], "don't go together") def test_coverage(self): for opt in '-T', '--coverage': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.trace) def test_coverdir(self): for opt in '-D', '--coverdir': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.coverdir, os.path.join(support.SAVEDCWD, 'foo')) self.checkError([opt], 'expected one argument') def test_nocoverdir(self): for opt in '-N', '--nocoverdir': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertIsNone(ns.coverdir) def test_threshold(self): for opt in '-t', '--threshold': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '1000']) self.assertEqual(ns.threshold, 1000) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid int value') def test_nowindows(self): for opt in '-n', '--nowindows': with self.subTest(opt=opt): with contextlib.redirect_stderr(io.StringIO()) as stderr: ns = libregrtest._parse_args([opt]) self.assertTrue(ns.nowindows) err = stderr.getvalue() self.assertIn('the --nowindows (-n) option is deprecated', err) def test_forever(self): for opt in '-F', '--forever': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.forever) def test_unrecognized_argument(self): self.checkError(['--xxx'], 'usage:') def test_long_option__partial(self): ns = libregrtest._parse_args(['--qui']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) def test_two_options(self): ns = libregrtest._parse_args(['--quiet', '--exclude']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) self.assertTrue(ns.exclude) def test_option_with_empty_string_value(self): ns = libregrtest._parse_args(['--start', '']) self.assertEqual(ns.start, '') def test_arg(self): ns = libregrtest._parse_args(['foo']) self.assertEqual(ns.args, ['foo']) def test_option_and_arg(self): ns = libregrtest._parse_args(['--quiet', 'foo']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) self.assertEqual(ns.args, ['foo']) def test_arg_option_arg(self): ns = libregrtest._parse_args(['test_unaryop', '-v', 'test_binop']) self.assertEqual(ns.verbose, 1) self.assertEqual(ns.args, ['test_unaryop', 'test_binop']) def test_unknown_option(self): self.checkError(['--unknown-option'], 'unrecognized arguments: --unknown-option') class BaseTestCase(unittest.TestCase): TEST_UNIQUE_ID = 1 TESTNAME_PREFIX = 'test_regrtest_' TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+' def setUp(self): self.testdir = os.path.realpath(os.path.dirname(__file__)) self.tmptestdir = tempfile.mkdtemp() self.addCleanup(support.rmtree, self.tmptestdir) def create_test(self, name=None, code=None): if not name: name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID BaseTestCase.TEST_UNIQUE_ID += 1 if code is None: code = textwrap.dedent(""" import unittest class Tests(unittest.TestCase): def test_empty_test(self): pass """) # test_regrtest cannot be run twice in parallel because # of setUp() and create_test() name = self.TESTNAME_PREFIX + name path = os.path.join(self.tmptestdir, name + '.py') self.addCleanup(support.unlink, path) # Use 'x' mode to ensure that we do not override existing tests try: with open(path, 'x', encoding='utf-8') as fp: fp.write(code) except PermissionError as exc: if not sysconfig.is_python_build(): self.skipTest("cannot write %s: %s" % (path, exc)) raise return name def regex_search(self, regex, output): match = re.search(regex, output, re.MULTILINE) if not match: self.fail("%r not found in %r" % (regex, output)) return match def check_line(self, output, regex): regex = re.compile(r'^' + regex, re.MULTILINE) self.assertRegex(output, regex) def parse_executed_tests(self, output): regex = (r'^%s\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)' % (LOG_PREFIX, self.TESTNAME_REGEX)) parser = re.finditer(regex, output, re.MULTILINE) return list(match.group(1) for match in parser) def check_executed_tests(self, output, tests, skipped=(), failed=(), env_changed=(), omitted=(), rerun=(), no_test_ran=(), randomize=False, interrupted=False, fail_env_changed=False): if isinstance(tests, str): tests = [tests] if isinstance(skipped, str): skipped = [skipped] if isinstance(failed, str): failed = [failed] if isinstance(env_changed, str): env_changed = [env_changed] if isinstance(omitted, str): omitted = [omitted] if isinstance(rerun, str): rerun = [rerun] if isinstance(no_test_ran, str): no_test_ran = [no_test_ran] executed = self.parse_executed_tests(output) if randomize: self.assertEqual(set(executed), set(tests), output) else: self.assertEqual(executed, tests, output) def plural(count): return 's' if count != 1 else '' def list_regex(line_format, tests): count = len(tests) names = ' '.join(sorted(tests)) regex = line_format % (count, plural(count)) regex = r'%s:\n %s$' % (regex, names) return regex if skipped: regex = list_regex('%s test%s skipped', skipped) self.check_line(output, regex) if failed: regex = list_regex('%s test%s failed', failed) self.check_line(output, regex) if env_changed: regex = list_regex('%s test%s altered the execution environment', env_changed) self.check_line(output, regex) if omitted: regex = list_regex('%s test%s omitted', omitted) self.check_line(output, regex) if rerun: regex = list_regex('%s re-run test%s', rerun) self.check_line(output, regex) regex = LOG_PREFIX + r"Re-running failed tests in verbose mode" self.check_line(output, regex) for test_name in rerun: regex = LOG_PREFIX + f"Re-running {test_name} in verbose mode" self.check_line(output, regex) if no_test_ran: regex = list_regex('%s test%s run no tests', no_test_ran) self.check_line(output, regex) good = (len(tests) - len(skipped) - len(failed) - len(omitted) - len(env_changed) - len(no_test_ran)) if good: regex = r'%s test%s OK\.$' % (good, plural(good)) if not skipped and not failed and good > 1: regex = 'All %s' % regex self.check_line(output, regex) if interrupted: self.check_line(output, 'Test suite interrupted by signal SIGINT.') result = [] if failed: result.append('FAILURE') elif fail_env_changed and env_changed: result.append('ENV CHANGED') if interrupted: result.append('INTERRUPTED') if not any((good, result, failed, interrupted, skipped, env_changed, fail_env_changed)): result.append("NO TEST RUN") elif not result: result.append('SUCCESS') result = ', '.join(result) if rerun: self.check_line(output, 'Tests result: FAILURE') result = 'FAILURE then %s' % result self.check_line(output, 'Tests result: %s' % result) def parse_random_seed(self, output): match = self.regex_search(r'Using random seed ([0-9]+)', output) randseed = int(match.group(1)) self.assertTrue(0 <= randseed <= 10000000, randseed) return randseed def run_command(self, args, input=None, exitcode=0, **kw): if not input: input = '' if 'stderr' not in kw: kw['stderr'] = subprocess.PIPE proc = subprocess.run(args, universal_newlines=True, input=input, stdout=subprocess.PIPE, **kw) if proc.returncode != exitcode: msg = ("Command %s failed with exit code %s\n" "\n" "stdout:\n" "---\n" "%s\n" "---\n" % (str(args), proc.returncode, proc.stdout)) if proc.stderr: msg += ("\n" "stderr:\n" "---\n" "%s" "---\n" % proc.stderr) self.fail(msg) return proc def run_python(self, args, **kw): args = [sys.executable, '-X', 'faulthandler', '-I', *args] proc = self.run_command(args, **kw) return proc.stdout class ProgramsTestCase(BaseTestCase): """ Test various ways to run the Python test suite. Use options close to options used on the buildbot. """ NTEST = 4 def setUp(self): super().setUp() # Create NTEST tests doing nothing self.tests = [self.create_test() for index in range(self.NTEST)] self.python_args = ['-Wd', '-E', '-bb'] self.regrtest_args = ['-uall', '-rwW', '--testdir=%s' % self.tmptestdir] if hasattr(faulthandler, 'dump_traceback_later'): self.regrtest_args.extend(('--timeout', '3600', '-j4')) if sys.platform == 'win32': self.regrtest_args.append('-n') def check_output(self, output): self.parse_random_seed(output) self.check_executed_tests(output, self.tests, randomize=True) def run_tests(self, args): output = self.run_python(args) self.check_output(output) def test_script_regrtest(self): # Lib/test/regrtest.py script = os.path.join(self.testdir, 'regrtest.py') args = [*self.python_args, script, *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_test(self): # -m test args = [*self.python_args, '-m', 'test', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_regrtest(self): # -m test.regrtest args = [*self.python_args, '-m', 'test.regrtest', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_autotest(self): # -m test.autotest args = [*self.python_args, '-m', 'test.autotest', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_from_test_autotest(self): # from test import autotest code = 'from test import autotest' args = [*self.python_args, '-c', code, *self.regrtest_args, *self.tests] self.run_tests(args) def test_script_autotest(self): # Lib/test/autotest.py script = os.path.join(self.testdir, 'autotest.py') args = [*self.python_args, script, *self.regrtest_args, *self.tests] self.run_tests(args) @unittest.skipUnless(sysconfig.is_python_build(), 'run_tests.py script is not installed') def test_tools_script_run_tests(self): # Tools/scripts/run_tests.py script = os.path.join(ROOT_DIR, 'Tools', 'scripts', 'run_tests.py') args = [script, *self.regrtest_args, *self.tests] self.run_tests(args) def run_batch(self, *args): proc = self.run_command(args) self.check_output(proc.stdout) @unittest.skipUnless(sysconfig.is_python_build(), 'test.bat script is not installed') @unittest.skipUnless(sys.platform == 'win32', 'Windows only') def test_tools_buildbot_test(self): # Tools\buildbot\test.bat script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat') test_args = ['--testdir=%s' % self.tmptestdir] if platform.architecture()[0] == '64bit': test_args.append('-x64') # 64-bit build if not Py_DEBUG: test_args.append('+d') # Release build, use python.exe self.run_batch(script, *test_args, *self.tests) @unittest.skipUnless(sys.platform == 'win32', 'Windows only') def test_pcbuild_rt(self): # PCbuild\rt.bat script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat') if not os.path.isfile(script): self.skipTest(f'File "{script}" does not exist') rt_args = ["-q"] # Quick, don't run tests twice if platform.architecture()[0] == '64bit': rt_args.append('-x64') # 64-bit build if Py_DEBUG: rt_args.append('-d') # Debug build, use python_d.exe self.run_batch(script, *rt_args, *self.regrtest_args, *self.tests) class ArgsTestCase(BaseTestCase): """ Test arguments of the Python test suite. """ def run_tests(self, *testargs, **kw): cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs] return self.run_python(cmdargs, **kw) def test_failing_test(self): # test a failing test code = textwrap.dedent(""" import unittest class FailingTest(unittest.TestCase): def test_failing(self): self.fail("bug") """) test_ok = self.create_test('ok') test_failing = self.create_test('failing', code=code) tests = [test_ok, test_failing] output = self.run_tests(*tests, exitcode=2) self.check_executed_tests(output, tests, failed=test_failing) def test_resources(self): # test -u command line option tests = {} for resource in ('audio', 'network'): code = textwrap.dedent(""" from test import support; support.requires(%r) import unittest class PassingTest(unittest.TestCase): def test_pass(self): pass """ % resource) tests[resource] = self.create_test(resource, code) test_names = sorted(tests.values()) # -u all: 2 resources enabled output = self.run_tests('-u', 'all', *test_names) self.check_executed_tests(output, test_names) # -u audio: 1 resource enabled output = self.run_tests('-uaudio', *test_names) self.check_executed_tests(output, test_names, skipped=tests['network']) # no option: 0 resources enabled output = self.run_tests(*test_names) self.check_executed_tests(output, test_names, skipped=test_names) def test_random(self): # test -r and --randseed command line option code = textwrap.dedent(""" import random print("TESTRANDOM: %s" % random.randint(1, 1000)) """) test = self.create_test('random', code) # first run to get the output with the random seed output = self.run_tests('-r', test) randseed = self.parse_random_seed(output) match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output) test_random = int(match.group(1)) # try to reproduce with the random seed output = self.run_tests('-r', '--randseed=%s' % randseed, test) randseed2 = self.parse_random_seed(output) self.assertEqual(randseed2, randseed) match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output) test_random2 = int(match.group(1)) self.assertEqual(test_random2, test_random) def test_fromfile(self): # test --fromfile tests = [self.create_test() for index in range(5)] # Write the list of files using a format similar to regrtest output: # [1/2] test_1 # [2/2] test_2 filename = support.TESTFN self.addCleanup(support.unlink, filename) # test format '0:00:00 [2/7] test_opcodes -- test_grammar took 0 sec' with open(filename, "w") as fp: previous = None for index, name in enumerate(tests, 1): line = ("00:00:%02i [%s/%s] %s" % (index, index, len(tests), name)) if previous: line += " -- %s took 0 sec" % previous print(line, file=fp) previous = name output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) # test format '[2/7] test_opcodes' with open(filename, "w") as fp: for index, name in enumerate(tests, 1): print("[%s/%s] %s" % (index, len(tests), name), file=fp) output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) # test format 'test_opcodes' with open(filename, "w") as fp: for name in tests: print(name, file=fp) output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) # test format 'Lib/test/test_opcodes.py' with open(filename, "w") as fp: for name in tests: print('Lib/test/%s.py' % name, file=fp) output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) def test_interrupted(self): code = TEST_INTERRUPTED test = self.create_test('sigint', code=code) output = self.run_tests(test, exitcode=130) self.check_executed_tests(output, test, omitted=test, interrupted=True) def test_slowest(self): # test --slowest tests = [self.create_test() for index in range(3)] output = self.run_tests("--slowest", *tests) self.check_executed_tests(output, tests) regex = ('10 slowest tests:\n' '(?:- %s: .*\n){%s}' % (self.TESTNAME_REGEX, len(tests))) self.check_line(output, regex) def test_slowest_interrupted(self): # Issue #25373: test --slowest with an interrupted test code = TEST_INTERRUPTED test = self.create_test("sigint", code=code) for multiprocessing in (False, True): with self.subTest(multiprocessing=multiprocessing): if multiprocessing: args = ("--slowest", "-j2", test) else: args = ("--slowest", test) output = self.run_tests(*args, exitcode=130) self.check_executed_tests(output, test, omitted=test, interrupted=True) regex = ('10 slowest tests:\n') self.check_line(output, regex) def test_coverage(self): # test --coverage test = self.create_test('coverage') output = self.run_tests("--coverage", test) self.check_executed_tests(output, [test]) regex = (r'lines +cov% +module +\(path\)\n' r'(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+') self.check_line(output, regex) def test_wait(self): # test --wait test = self.create_test('wait') output = self.run_tests("--wait", test, input='key') self.check_line(output, 'Press any key to continue') def test_forever(self): # test --forever code = textwrap.dedent(""" import builtins import unittest class ForeverTester(unittest.TestCase): def test_run(self): # Store the state in the builtins module, because the test # module is reload at each run if 'RUN' in builtins.__dict__: builtins.__dict__['RUN'] += 1 if builtins.__dict__['RUN'] >= 3: self.fail("fail at the 3rd runs") else: builtins.__dict__['RUN'] = 1 """) test = self.create_test('forever', code=code) output = self.run_tests('--forever', test, exitcode=2) self.check_executed_tests(output, [test]*3, failed=test) def check_leak(self, code, what): test = self.create_test('huntrleaks', code=code) filename = 'reflog.txt' self.addCleanup(support.unlink, filename) output = self.run_tests('--huntrleaks', '3:3:', test, exitcode=2, stderr=subprocess.STDOUT) self.check_executed_tests(output, [test], failed=test) line = 'beginning 6 repetitions\n123456\n......\n' self.check_line(output, re.escape(line)) line2 = '%s leaked [1, 1, 1] %s, sum=3\n' % (test, what) self.assertIn(line2, output) with open(filename) as fp: reflog = fp.read() self.assertIn(line2, reflog) @unittest.skipUnless(Py_DEBUG, 'need a debug build') def test_huntrleaks(self): # test --huntrleaks code = textwrap.dedent(""" import unittest GLOBAL_LIST = [] class RefLeakTest(unittest.TestCase): def test_leak(self): GLOBAL_LIST.append(object()) """) self.check_leak(code, 'references') @unittest.skipUnless(Py_DEBUG, 'need a debug build') def test_huntrleaks_fd_leak(self): # test --huntrleaks for file descriptor leak
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_popen.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_popen.py
"""Basic tests for os.popen() Particularly useful for platforms that fake popen. """ import unittest from test import support import os, sys # Test that command-lines get down as we expect. # To do this we execute: # python -c "import sys;print(sys.argv)" {rest_of_commandline} # This results in Python being spawned and printing the sys.argv list. # We can then eval() the result of this, and see what each argv was. python = sys.executable if ' ' in python: python = '"' + python + '"' # quote embedded space for cmdline class PopenTest(unittest.TestCase): def _do_test_commandline(self, cmdline, expected): cmd = '%s -c "import sys; print(sys.argv)" %s' cmd = cmd % (python, cmdline) with os.popen(cmd) as p: data = p.read() got = eval(data)[1:] # strip off argv[0] self.assertEqual(got, expected) def test_popen(self): self.assertRaises(TypeError, os.popen) self._do_test_commandline( "foo bar", ["foo", "bar"] ) self._do_test_commandline( 'foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"] ) self._do_test_commandline( 'foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"] ) support.reap_children() def test_return_code(self): self.assertEqual(os.popen("exit 0").close(), None) if os.name == 'nt': self.assertEqual(os.popen("exit 42").close(), 42) else: self.assertEqual(os.popen("exit 42").close(), 42 << 8) def test_contextmanager(self): with os.popen("echo hello") as f: self.assertEqual(f.read(), "hello\n") def test_iterating(self): with os.popen("echo hello") as f: self.assertEqual(list(f), ["hello\n"]) def test_keywords(self): with os.popen(cmd="exit 0", mode="w", buffering=-1): pass if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future7.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/badsyntax_future7.py
"""This is a test""" from __future__ import nested_scopes; import string; from __future__ import \ nested_scopes def f(x): def g(y): return x + y return g result = f(2)(4)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
import unittest from test import support from test.test_grammar import (VALID_UNDERSCORE_LITERALS, INVALID_UNDERSCORE_LITERALS) from random import random from math import atan2, isnan, copysign import operator INF = float("inf") NAN = float("nan") # These tests ensure that complex math does the right thing class ComplexTest(unittest.TestCase): def assertAlmostEqual(self, a, b): if isinstance(a, complex): if isinstance(b, complex): unittest.TestCase.assertAlmostEqual(self, a.real, b.real) unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag) else: unittest.TestCase.assertAlmostEqual(self, a.real, b) unittest.TestCase.assertAlmostEqual(self, a.imag, 0.) else: if isinstance(b, complex): unittest.TestCase.assertAlmostEqual(self, a, b.real) unittest.TestCase.assertAlmostEqual(self, 0., b.imag) else: unittest.TestCase.assertAlmostEqual(self, a, b) def assertCloseAbs(self, x, y, eps=1e-9): """Return true iff floats x and y "are close".""" # put the one with larger magnitude second if abs(x) > abs(y): x, y = y, x if y == 0: return abs(x) < eps if x == 0: return abs(y) < eps # check that relative difference < eps self.assertTrue(abs((x-y)/y) < eps) def assertFloatsAreIdentical(self, x, y): """assert that floats x and y are identical, in the sense that: (1) both x and y are nans, or (2) both x and y are infinities, with the same sign, or (3) both x and y are zeros, with the same sign, or (4) x and y are both finite and nonzero, and x == y """ msg = 'floats {!r} and {!r} are not identical' if isnan(x) or isnan(y): if isnan(x) and isnan(y): return elif x == y: if x != 0.0: return # both zero; check that signs match elif copysign(1.0, x) == copysign(1.0, y): return else: msg += ': zeros have different signs' self.fail(msg.format(x, y)) def assertClose(self, x, y, eps=1e-9): """Return true iff complexes x and y "are close".""" self.assertCloseAbs(x.real, y.real, eps) self.assertCloseAbs(x.imag, y.imag, eps) def check_div(self, x, y): """Compute complex z=x*y, and check that z/x==y and z/y==x.""" z = x * y if x != 0: q = z / x self.assertClose(q, y) q = z.__truediv__(x) self.assertClose(q, y) if y != 0: q = z / y self.assertClose(q, x) q = z.__truediv__(y) self.assertClose(q, x) def test_truediv(self): simple_real = [float(i) for i in range(-5, 6)] simple_complex = [complex(x, y) for x in simple_real for y in simple_real] for x in simple_complex: for y in simple_complex: self.check_div(x, y) # A naive complex division algorithm (such as in 2.0) is very prone to # nonsense errors for these (overflows and underflows). self.check_div(complex(1e200, 1e200), 1+0j) self.check_div(complex(1e-200, 1e-200), 1+0j) # Just for fun. for i in range(100): self.check_div(complex(random(), random()), complex(random(), random())) self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) # FIXME: The following currently crashes on Alpha # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j) self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j) self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) for denom_real, denom_imag in [(0, NAN), (NAN, 0), (NAN, NAN)]: z = complex(0, 0) / complex(denom_real, denom_imag) self.assertTrue(isnan(z.real)) self.assertTrue(isnan(z.imag)) def test_floordiv(self): self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 1.5+0j) self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 0+0j) def test_richcompare(self): self.assertIs(complex.__eq__(1+1j, 1<<10000), False) self.assertIs(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) self.assertIs(complex.__ne__(1+1j, 1+1j), False) self.assertIs(complex.__ne__(1+1j, 2+2j), True) for i in range(1, 100): f = i / 100.0 self.assertIs(complex.__eq__(f+0j, f), True) self.assertIs(complex.__ne__(f+0j, f), False) self.assertIs(complex.__eq__(complex(f, f), f), False) self.assertIs(complex.__ne__(complex(f, f), f), True) self.assertIs(complex.__lt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__le__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__gt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__ge__(1+1j, 2+2j), NotImplemented) self.assertRaises(TypeError, operator.lt, 1+1j, 2+2j) self.assertRaises(TypeError, operator.le, 1+1j, 2+2j) self.assertRaises(TypeError, operator.gt, 1+1j, 2+2j) self.assertRaises(TypeError, operator.ge, 1+1j, 2+2j) self.assertIs(operator.eq(1+1j, 1+1j), True) self.assertIs(operator.eq(1+1j, 2+2j), False) self.assertIs(operator.ne(1+1j, 1+1j), False) self.assertIs(operator.ne(1+1j, 2+2j), True) def test_richcompare_boundaries(self): def check(n, deltas, is_equal, imag = 0.0): for delta in deltas: i = n + delta z = complex(i, imag) self.assertIs(complex.__eq__(z, i), is_equal(delta)) self.assertIs(complex.__ne__(z, i), not is_equal(delta)) # For IEEE-754 doubles the following should hold: # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 # where the interval is representable, of course. for i in range(1, 10): pow = 52 + i mult = 2 ** i check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) check(2 ** pow, range(1, 101), lambda delta: False, float(i)) check(2 ** 53, range(-100, 0), lambda delta: True) def test_mod(self): # % is no longer supported on complex numbers self.assertRaises(TypeError, (1+1j).__mod__, 0+0j) self.assertRaises(TypeError, lambda: (3.33+4.43j) % 0) self.assertRaises(TypeError, (1+1j).__mod__, 4.3j) def test_divmod(self): self.assertRaises(TypeError, divmod, 1+1j, 1+0j) self.assertRaises(TypeError, divmod, 1+1j, 0+0j) def test_pow(self): self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0) self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0) self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j) self.assertAlmostEqual(pow(1j, -1), 1/1j) self.assertAlmostEqual(pow(1j, 200), 1) self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j) a = 3.33+4.43j self.assertEqual(a ** 0j, 1) self.assertEqual(a ** 0.+0.j, 1) self.assertEqual(3j ** 0j, 1) self.assertEqual(3j ** 0, 1) try: 0j ** a except ZeroDivisionError: pass else: self.fail("should fail 0.0 to negative or complex power") try: 0j ** (3-2j) except ZeroDivisionError: pass else: self.fail("should fail 0.0 to negative or complex power") # The following is used to exercise certain code paths self.assertEqual(a ** 105, a ** 105) self.assertEqual(a ** -105, a ** -105) self.assertEqual(a ** -30, a ** -30) self.assertEqual(0.0j ** 0, 1) b = 5.1+2.3j self.assertRaises(ValueError, pow, a, b, 0) def test_boolcontext(self): for i in range(100): self.assertTrue(complex(random() + 1e-6, random() + 1e-6)) self.assertTrue(not complex(0.0, 0.0)) def test_conjugate(self): self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j) def test_constructor(self): class OS: def __init__(self, value): self.value = value def __complex__(self): return self.value class NS(object): def __init__(self, value): self.value = value def __complex__(self): return self.value self.assertEqual(complex(OS(1+10j)), 1+10j) self.assertEqual(complex(NS(1+10j)), 1+10j) self.assertRaises(TypeError, complex, OS(None)) self.assertRaises(TypeError, complex, NS(None)) self.assertRaises(TypeError, complex, {}) self.assertRaises(TypeError, complex, NS(1.5)) self.assertRaises(TypeError, complex, NS(1)) self.assertAlmostEqual(complex("1+10j"), 1+10j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10.0), 10+0j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10+0j), 10+0j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10.0), 1+10j) self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) self.assertAlmostEqual(complex(3.14), 3.14+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0j, 3.14), 3.14j) self.assertAlmostEqual(complex(0.0, 3.14), 3.14j) self.assertAlmostEqual(complex("1"), 1+0j) self.assertAlmostEqual(complex("1j"), 1j) self.assertAlmostEqual(complex(), 0) self.assertAlmostEqual(complex("-1"), -1) self.assertAlmostEqual(complex("+1"), +1) self.assertAlmostEqual(complex("(1+2j)"), 1+2j) self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j) self.assertAlmostEqual(complex("3.14+1J"), 3.14+1j) self.assertAlmostEqual(complex(" ( +3.14-6J )"), 3.14-6j) self.assertAlmostEqual(complex(" ( +3.14-J )"), 3.14-1j) self.assertAlmostEqual(complex(" ( +3.14+j )"), 3.14+1j) self.assertAlmostEqual(complex("J"), 1j) self.assertAlmostEqual(complex("( j )"), 1j) self.assertAlmostEqual(complex("+J"), 1j) self.assertAlmostEqual(complex("( -j)"), -1j) self.assertAlmostEqual(complex('1e-500'), 0.0 + 0.0j) self.assertAlmostEqual(complex('-1e-500j'), 0.0 - 0.0j) self.assertAlmostEqual(complex('-1e-500+1e-500j'), -0.0 + 0.0j) class complex2(complex): pass self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j) self.assertAlmostEqual(complex(real=17, imag=23), 17+23j) self.assertAlmostEqual(complex(real=17+23j), 17+23j) self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j) self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j) # check that the sign of a zero in the real or imaginary part # is preserved when constructing from two floats. (These checks # are harmless on systems without support for signed zeros.) def split_zeros(x): """Function that produces different results for 0. and -0.""" return atan2(x, -1.) self.assertEqual(split_zeros(complex(1., 0.).imag), split_zeros(0.)) self.assertEqual(split_zeros(complex(1., -0.).imag), split_zeros(-0.)) self.assertEqual(split_zeros(complex(0., 1.).real), split_zeros(0.)) self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.)) c = 3.14 + 1j self.assertTrue(complex(c) is c) del c self.assertRaises(TypeError, complex, "1", "1") self.assertRaises(TypeError, complex, 1, "1") # SF bug 543840: complex(string) accepts strings with \0 # Fixed in 2.3. self.assertRaises(ValueError, complex, '1+1j\0j') self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, float, 5+3j) self.assertRaises(ValueError, complex, "") self.assertRaises(TypeError, complex, None) self.assertRaisesRegex(TypeError, "not 'NoneType'", complex, None) self.assertRaises(ValueError, complex, "\0") self.assertRaises(ValueError, complex, "3\09") self.assertRaises(TypeError, complex, "1", "2") self.assertRaises(TypeError, complex, "1", 42) self.assertRaises(TypeError, complex, 1, "2") self.assertRaises(ValueError, complex, "1+") self.assertRaises(ValueError, complex, "1+1j+1j") self.assertRaises(ValueError, complex, "--") self.assertRaises(ValueError, complex, "(1+2j") self.assertRaises(ValueError, complex, "1+2j)") self.assertRaises(ValueError, complex, "1+(2j)") self.assertRaises(ValueError, complex, "(1+2j)123") self.assertRaises(ValueError, complex, "x") self.assertRaises(ValueError, complex, "1j+2") self.assertRaises(ValueError, complex, "1e1ej") self.assertRaises(ValueError, complex, "1e++1ej") self.assertRaises(ValueError, complex, ")1+2j(") self.assertRaisesRegex( TypeError, "first argument must be a string or a number, not 'dict'", complex, {1:2}, 1) self.assertRaisesRegex( TypeError, "second argument must be a number, not 'dict'", complex, 1, {1:2}) # the following three are accepted by Python 2.6 self.assertRaises(ValueError, complex, "1..1j") self.assertRaises(ValueError, complex, "1.11.1j") self.assertRaises(ValueError, complex, "1e1.1j") # check that complex accepts long unicode strings self.assertEqual(type(complex("1"*500)), complex) # check whitespace processing self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j) # Invalid unicode string # See bpo-34087 self.assertRaises(ValueError, complex, '\u3053\u3093\u306b\u3061\u306f') class EvilExc(Exception): pass class evilcomplex: def __complex__(self): raise EvilExc self.assertRaises(EvilExc, complex, evilcomplex()) class float2: def __init__(self, value): self.value = value def __float__(self): return self.value self.assertAlmostEqual(complex(float2(42.)), 42) self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j) self.assertRaises(TypeError, complex, float2(None)) class complex0(complex): """Test usage of __complex__() when inheriting from 'complex'""" def __complex__(self): return 42j class complex1(complex): """Test usage of __complex__() with a __new__() method""" def __new__(self, value=0j): return complex.__new__(self, 2*value) def __complex__(self): return self class complex2(complex): """Make sure that __complex__() calls fail if anything other than a complex is returned""" def __complex__(self): return None self.assertEqual(complex(complex0(1j)), 42j) with self.assertWarns(DeprecationWarning): self.assertEqual(complex(complex1(1j)), 2j) self.assertRaises(TypeError, complex, complex2(1j)) @support.requires_IEEE_754 def test_constructor_special_numbers(self): class complex2(complex): pass for x in 0.0, -0.0, INF, -INF, NAN: for y in 0.0, -0.0, INF, -INF, NAN: with self.subTest(x=x, y=y): z = complex(x, y) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex2(x, y) self.assertIs(type(z), complex2) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex(complex2(x, y)) self.assertIs(type(z), complex) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex2(complex(x, y)) self.assertIs(type(z), complex2) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) def test_underscores(self): # check underscores for lit in VALID_UNDERSCORE_LITERALS: if not any(ch in lit for ch in 'xXoObB'): self.assertEqual(complex(lit), eval(lit)) self.assertEqual(complex(lit), complex(lit.replace('_', ''))) for lit in INVALID_UNDERSCORE_LITERALS: if lit in ('0_7', '09_99'): # octals are not recognized here continue if not any(ch in lit for ch in 'xXoObB'): self.assertRaises(ValueError, complex, lit) def test_hash(self): for x in range(-30, 30): self.assertEqual(hash(x), hash(complex(x, 0))) x /= 3.0 # now check against floating point self.assertEqual(hash(x), hash(complex(x, 0.))) def test_abs(self): nums = [complex(x/3., y/7.) for x in range(-9,9) for y in range(-9,9)] for num in nums: self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) def test_repr_str(self): def test(v, expected, test_fn=self.assertEqual): test_fn(repr(v), expected) test_fn(str(v), expected) test(1+6j, '(1+6j)') test(1-6j, '(1-6j)') test(-(1+0j), '(-1+-0j)', test_fn=self.assertNotEqual) test(complex(1., INF), "(1+infj)") test(complex(1., -INF), "(1-infj)") test(complex(INF, 1), "(inf+1j)") test(complex(-INF, INF), "(-inf+infj)") test(complex(NAN, 1), "(nan+1j)") test(complex(1, NAN), "(1+nanj)") test(complex(NAN, NAN), "(nan+nanj)") test(complex(0, INF), "infj") test(complex(0, -INF), "-infj") test(complex(0, NAN), "nanj") self.assertEqual(1-6j,complex(repr(1-6j))) self.assertEqual(1+6j,complex(repr(1+6j))) self.assertEqual(-6j,complex(repr(-6j))) self.assertEqual(6j,complex(repr(6j))) @support.requires_IEEE_754 def test_negative_zero_repr_str(self): def test(v, expected, test_fn=self.assertEqual): test_fn(repr(v), expected) test_fn(str(v), expected) test(complex(0., 1.), "1j") test(complex(-0., 1.), "(-0+1j)") test(complex(0., -1.), "-1j") test(complex(-0., -1.), "(-0-1j)") test(complex(0., 0.), "0j") test(complex(0., -0.), "-0j") test(complex(-0., 0.), "(-0+0j)") test(complex(-0., -0.), "(-0-0j)") def test_neg(self): self.assertEqual(-(1+6j), -1-6j) def test_file(self): a = 3.33+4.43j b = 5.1+2.3j fo = None try: fo = open(support.TESTFN, "w") print(a, b, file=fo) fo.close() fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), ("%s %s\n" % (a, b))) finally: if (fo is not None) and (not fo.closed): fo.close() support.unlink(support.TESTFN) def test_getnewargs(self): self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0)) self.assertEqual((1-2j).__getnewargs__(), (1.0, -2.0)) self.assertEqual((2j).__getnewargs__(), (0.0, 2.0)) self.assertEqual((-0j).__getnewargs__(), (0.0, -0.0)) self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF)) self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0)) @support.requires_IEEE_754 def test_plus_minus_0j(self): # test that -0j and 0j literals are not identified z1, z2 = 0j, -0j self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.)) self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.)) @support.requires_IEEE_754 def test_negated_imaginary_literal(self): z0 = -0j z1 = -7j z2 = -1e1000j # Note: In versions of Python < 3.2, a negated imaginary literal # accidentally ended up with real part 0.0 instead of -0.0, thanks to a # modification during CST -> AST translation (see issue #9011). That's # fixed in Python 3.2. self.assertFloatsAreIdentical(z0.real, -0.0) self.assertFloatsAreIdentical(z0.imag, -0.0) self.assertFloatsAreIdentical(z1.real, -0.0) self.assertFloatsAreIdentical(z1.imag, -7.0) self.assertFloatsAreIdentical(z2.real, -0.0) self.assertFloatsAreIdentical(z2.imag, -INF) @support.requires_IEEE_754 def test_overflow(self): self.assertEqual(complex("1e500"), complex(INF, 0.0)) self.assertEqual(complex("-1e500j"), complex(0.0, -INF)) self.assertEqual(complex("-1e500+1.8e308j"), complex(-INF, INF)) @support.requires_IEEE_754 def test_repr_roundtrip(self): vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN] vals += [-v for v in vals] # complex(repr(z)) should recover z exactly, even for complex # numbers involving an infinity, nan, or negative zero for x in vals: for y in vals: z = complex(x, y) roundtrip = complex(repr(z)) self.assertFloatsAreIdentical(z.real, roundtrip.real) self.assertFloatsAreIdentical(z.imag, roundtrip.imag) # if we predefine some constants, then eval(repr(z)) should # also work, except that it might change the sign of zeros inf, nan = float('inf'), float('nan') infj, nanj = complex(0.0, inf), complex(0.0, nan) for x in vals: for y in vals: z = complex(x, y) roundtrip = eval(repr(z)) # adding 0.0 has no effect beside changing -0.0 to 0.0 self.assertFloatsAreIdentical(0.0 + z.real, 0.0 + roundtrip.real) self.assertFloatsAreIdentical(0.0 + z.imag, 0.0 + roundtrip.imag) def test_format(self): # empty format string is same as str() self.assertEqual(format(1+3j, ''), str(1+3j)) self.assertEqual(format(1.5+3.5j, ''), str(1.5+3.5j)) self.assertEqual(format(3j, ''), str(3j)) self.assertEqual(format(3.2j, ''), str(3.2j)) self.assertEqual(format(3+0j, ''), str(3+0j)) self.assertEqual(format(3.2+0j, ''), str(3.2+0j)) # empty presentation type should still be analogous to str, # even when format string is nonempty (issue #5920). self.assertEqual(format(3.2+0j, '-'), str(3.2+0j)) self.assertEqual(format(3.2+0j, '<'), str(3.2+0j)) z = 4/7. - 100j/7. self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '10'), str(z)) z = complex(0.0, 3.0) self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '2'), str(z)) z = complex(-0.0, 2.0) self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '3'), str(z)) self.assertEqual(format(1+3j, 'g'), '1+3j') self.assertEqual(format(3j, 'g'), '0+3j') self.assertEqual(format(1.5+3.5j, 'g'), '1.5+3.5j') self.assertEqual(format(1.5+3.5j, '+g'), '+1.5+3.5j') self.assertEqual(format(1.5-3.5j, '+g'), '+1.5-3.5j') self.assertEqual(format(1.5-3.5j, '-g'), '1.5-3.5j') self.assertEqual(format(1.5+3.5j, ' g'), ' 1.5+3.5j') self.assertEqual(format(1.5-3.5j, ' g'), ' 1.5-3.5j') self.assertEqual(format(-1.5+3.5j, ' g'), '-1.5+3.5j') self.assertEqual(format(-1.5-3.5j, ' g'), '-1.5-3.5j') self.assertEqual(format(-1.5-3.5e-20j, 'g'), '-1.5-3.5e-20j') self.assertEqual(format(-1.5-3.5j, 'f'), '-1.500000-3.500000j') self.assertEqual(format(-1.5-3.5j, 'F'), '-1.500000-3.500000j') self.assertEqual(format(-1.5-3.5j, 'e'), '-1.500000e+00-3.500000e+00j') self.assertEqual(format(-1.5-3.5j, '.2e'), '-1.50e+00-3.50e+00j') self.assertEqual(format(-1.5-3.5j, '.2E'), '-1.50E+00-3.50E+00j') self.assertEqual(format(-1.5e10-3.5e5j, '.2G'), '-1.5E+10-3.5E+05j') self.assertEqual(format(1.5+3j, '<20g'), '1.5+3j ') self.assertEqual(format(1.5+3j, '*<20g'), '1.5+3j**************') self.assertEqual(format(1.5+3j, '>20g'), ' 1.5+3j') self.assertEqual(format(1.5+3j, '^20g'), ' 1.5+3j ') self.assertEqual(format(1.5+3j, '<20'), '(1.5+3j) ') self.assertEqual(format(1.5+3j, '>20'), ' (1.5+3j)') self.assertEqual(format(1.5+3j, '^20'), ' (1.5+3j) ') self.assertEqual(format(1.123-3.123j, '^20.2'), ' (1.1-3.1j) ') self.assertEqual(format(1.5+3j, '20.2f'), ' 1.50+3.00j') self.assertEqual(format(1.5+3j, '>20.2f'), ' 1.50+3.00j') self.assertEqual(format(1.5+3j, '<20.2f'), '1.50+3.00j ') self.assertEqual(format(1.5e20+3j, '<20.2f'), '150000000000000000000.00+3.00j') self.assertEqual(format(1.5e20+3j, '>40.2f'), ' 150000000000000000000.00+3.00j') self.assertEqual(format(1.5e20+3j, '^40,.2f'), ' 150,000,000,000,000,000,000.00+3.00j ') self.assertEqual(format(1.5e21+3j, '^40,.2f'), ' 1,500,000,000,000,000,000,000.00+3.00j ') self.assertEqual(format(1.5e21+3000j, ',.2f'), '1,500,000,000,000,000,000,000.00+3,000.00j') # Issue 7094: Alternate formatting (specified by #) self.assertEqual(format(1+1j, '.0e'), '1e+00+1e+00j') self.assertEqual(format(1+1j, '#.0e'), '1.e+00+1.e+00j') self.assertEqual(format(1+1j, '.0f'), '1+1j') self.assertEqual(format(1+1j, '#.0f'), '1.+1.j') self.assertEqual(format(1.1+1.1j, 'g'), '1.1+1.1j') self.assertEqual(format(1.1+1.1j, '#g'), '1.10000+1.10000j') # Alternate doesn't make a difference for these, they format the same with or without it self.assertEqual(format(1+1j, '.1e'), '1.0e+00+1.0e+00j') self.assertEqual(format(1+1j, '#.1e'), '1.0e+00+1.0e+00j') self.assertEqual(format(1+1j, '.1f'), '1.0+1.0j') self.assertEqual(format(1+1j, '#.1f'), '1.0+1.0j') # Misc. other alternate tests self.assertEqual(format((-1.5+0.5j), '#f'), '-1.500000+0.500000j') self.assertEqual(format((-1.5+0.5j), '#.0f'), '-2.+0.j') self.assertEqual(format((-1.5+0.5j), '#e'), '-1.500000e+00+5.000000e-01j') self.assertEqual(format((-1.5+0.5j), '#.0e'), '-2.e+00+5.e-01j') self.assertEqual(format((-1.5+0.5j), '#g'), '-1.50000+0.500000j') self.assertEqual(format((-1.5+0.5j), '.0g'), '-2+0.5j') self.assertEqual(format((-1.5+0.5j), '#.0g'), '-2.+0.5j') # zero padding is invalid self.assertRaises(ValueError, (1.5+0.5j).__format__, '010f') # '=' alignment is invalid self.assertRaises(ValueError, (1.5+3j).__format__, '=20') # integer presentation types are an error for t in 'bcdoxX': self.assertRaises(ValueError, (1.5+0.5j).__format__, t) # make sure everything works in ''.format() self.assertEqual('*{0:.3f}*'.format(3.14159+2.71828j), '*3.142+2.718j*') # issue 3382 self.assertEqual(format(complex(NAN, NAN), 'f'), 'nan+nanj') self.assertEqual(format(complex(1, NAN), 'f'), '1.000000+nanj') self.assertEqual(format(complex(NAN, 1), 'f'), 'nan+1.000000j') self.assertEqual(format(complex(NAN, -1), 'f'), 'nan-1.000000j') self.assertEqual(format(complex(NAN, NAN), 'F'), 'NAN+NANj') self.assertEqual(format(complex(1, NAN), 'F'), '1.000000+NANj') self.assertEqual(format(complex(NAN, 1), 'F'), 'NAN+1.000000j') self.assertEqual(format(complex(NAN, -1), 'F'), 'NAN-1.000000j') self.assertEqual(format(complex(INF, INF), 'f'), 'inf+infj') self.assertEqual(format(complex(1, INF), 'f'), '1.000000+infj') self.assertEqual(format(complex(INF, 1), 'f'), 'inf+1.000000j') self.assertEqual(format(complex(INF, -1), 'f'), 'inf-1.000000j') self.assertEqual(format(complex(INF, INF), 'F'), 'INF+INFj') self.assertEqual(format(complex(1, INF), 'F'), '1.000000+INFj') self.assertEqual(format(complex(INF, 1), 'F'), 'INF+1.000000j') self.assertEqual(format(complex(INF, -1), 'F'), 'INF-1.000000j') def test_main(): support.run_unittest(ComplexTest) if __name__ == "__main__": test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pickle.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pickle.py
from _compat_pickle import (IMPORT_MAPPING, REVERSE_IMPORT_MAPPING, NAME_MAPPING, REVERSE_NAME_MAPPING) import builtins import pickle import io import collections import struct import sys import weakref import unittest from test import support from test.pickletester import AbstractUnpickleTests from test.pickletester import AbstractPickleTests from test.pickletester import AbstractPickleModuleTests from test.pickletester import AbstractPersistentPicklerTests from test.pickletester import AbstractIdentityPersistentPicklerTests from test.pickletester import AbstractPicklerUnpicklerObjectTests from test.pickletester import AbstractDispatchTableTests from test.pickletester import BigmemPickleTests try: import _pickle has_c_implementation = True except ImportError: has_c_implementation = False class PyPickleTests(AbstractPickleModuleTests): dump = staticmethod(pickle._dump) dumps = staticmethod(pickle._dumps) load = staticmethod(pickle._load) loads = staticmethod(pickle._loads) Pickler = pickle._Pickler Unpickler = pickle._Unpickler class PyUnpicklerTests(AbstractUnpickleTests): unpickler = pickle._Unpickler bad_stack_errors = (IndexError,) truncated_errors = (pickle.UnpicklingError, EOFError, AttributeError, ValueError, struct.error, IndexError, ImportError) def loads(self, buf, **kwds): f = io.BytesIO(buf) u = self.unpickler(f, **kwds) return u.load() class PyPicklerTests(AbstractPickleTests): pickler = pickle._Pickler unpickler = pickle._Unpickler def dumps(self, arg, proto=None): f = io.BytesIO() p = self.pickler(f, proto) p.dump(arg) f.seek(0) return bytes(f.read()) def loads(self, buf, **kwds): f = io.BytesIO(buf) u = self.unpickler(f, **kwds) return u.load() class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests, BigmemPickleTests): bad_stack_errors = (pickle.UnpicklingError, IndexError) truncated_errors = (pickle.UnpicklingError, EOFError, AttributeError, ValueError, struct.error, IndexError, ImportError) def dumps(self, arg, protocol=None): return pickle.dumps(arg, protocol) def loads(self, buf, **kwds): return pickle.loads(buf, **kwds) test_framed_write_sizes_with_delayed_writer = None class PersistentPicklerUnpicklerMixin(object): def dumps(self, arg, proto=None): class PersPickler(self.pickler): def persistent_id(subself, obj): return self.persistent_id(obj) f = io.BytesIO() p = PersPickler(f, proto) p.dump(arg) return f.getvalue() def loads(self, buf, **kwds): class PersUnpickler(self.unpickler): def persistent_load(subself, obj): return self.persistent_load(obj) f = io.BytesIO(buf) u = PersUnpickler(f, **kwds) return u.load() class PyPersPicklerTests(AbstractPersistentPicklerTests, PersistentPicklerUnpicklerMixin): pickler = pickle._Pickler unpickler = pickle._Unpickler class PyIdPersPicklerTests(AbstractIdentityPersistentPicklerTests, PersistentPicklerUnpicklerMixin): pickler = pickle._Pickler unpickler = pickle._Unpickler @support.cpython_only def test_pickler_reference_cycle(self): def check(Pickler): for proto in range(pickle.HIGHEST_PROTOCOL + 1): f = io.BytesIO() pickler = Pickler(f, proto) pickler.dump('abc') self.assertEqual(self.loads(f.getvalue()), 'abc') pickler = Pickler(io.BytesIO()) self.assertEqual(pickler.persistent_id('def'), 'def') r = weakref.ref(pickler) del pickler self.assertIsNone(r()) class PersPickler(self.pickler): def persistent_id(subself, obj): return obj check(PersPickler) class PersPickler(self.pickler): @classmethod def persistent_id(cls, obj): return obj check(PersPickler) class PersPickler(self.pickler): @staticmethod def persistent_id(obj): return obj check(PersPickler) @support.cpython_only def test_unpickler_reference_cycle(self): def check(Unpickler): for proto in range(pickle.HIGHEST_PROTOCOL + 1): unpickler = Unpickler(io.BytesIO(self.dumps('abc', proto))) self.assertEqual(unpickler.load(), 'abc') unpickler = Unpickler(io.BytesIO()) self.assertEqual(unpickler.persistent_load('def'), 'def') r = weakref.ref(unpickler) del unpickler self.assertIsNone(r()) class PersUnpickler(self.unpickler): def persistent_load(subself, pid): return pid check(PersUnpickler) class PersUnpickler(self.unpickler): @classmethod def persistent_load(cls, pid): return pid check(PersUnpickler) class PersUnpickler(self.unpickler): @staticmethod def persistent_load(pid): return pid check(PersUnpickler) class PyPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests): pickler_class = pickle._Pickler unpickler_class = pickle._Unpickler class PyDispatchTableTests(AbstractDispatchTableTests): pickler_class = pickle._Pickler def get_dispatch_table(self): return pickle.dispatch_table.copy() class PyChainDispatchTableTests(AbstractDispatchTableTests): pickler_class = pickle._Pickler def get_dispatch_table(self): return collections.ChainMap({}, pickle.dispatch_table) if has_c_implementation: class CPickleTests(AbstractPickleModuleTests): from _pickle import dump, dumps, load, loads, Pickler, Unpickler class CUnpicklerTests(PyUnpicklerTests): unpickler = _pickle.Unpickler bad_stack_errors = (pickle.UnpicklingError,) truncated_errors = (pickle.UnpicklingError,) class CPicklerTests(PyPicklerTests): pickler = _pickle.Pickler unpickler = _pickle.Unpickler class CPersPicklerTests(PyPersPicklerTests): pickler = _pickle.Pickler unpickler = _pickle.Unpickler class CIdPersPicklerTests(PyIdPersPicklerTests): pickler = _pickle.Pickler unpickler = _pickle.Unpickler class CDumpPickle_LoadPickle(PyPicklerTests): pickler = _pickle.Pickler unpickler = pickle._Unpickler class DumpPickle_CLoadPickle(PyPicklerTests): pickler = pickle._Pickler unpickler = _pickle.Unpickler class CPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests): pickler_class = _pickle.Pickler unpickler_class = _pickle.Unpickler def test_issue18339(self): unpickler = self.unpickler_class(io.BytesIO()) with self.assertRaises(TypeError): unpickler.memo = object # used to cause a segfault with self.assertRaises(ValueError): unpickler.memo = {-1: None} unpickler.memo = {1: None} class CDispatchTableTests(AbstractDispatchTableTests): pickler_class = pickle.Pickler def get_dispatch_table(self): return pickle.dispatch_table.copy() class CChainDispatchTableTests(AbstractDispatchTableTests): pickler_class = pickle.Pickler def get_dispatch_table(self): return collections.ChainMap({}, pickle.dispatch_table) @support.cpython_only class SizeofTests(unittest.TestCase): check_sizeof = support.check_sizeof def test_pickler(self): basesize = support.calcobjsize('6P2n3i2n3iP') p = _pickle.Pickler(io.BytesIO()) self.assertEqual(object.__sizeof__(p), basesize) MT_size = struct.calcsize('3nP0n') ME_size = struct.calcsize('Pn0P') check = self.check_sizeof check(p, basesize + MT_size + 8 * ME_size + # Minimal memo table size. sys.getsizeof(b'x'*4096)) # Minimal write buffer size. for i in range(6): p.dump(chr(i)) check(p, basesize + MT_size + 32 * ME_size + # Size of memo table required to # save references to 6 objects. 0) # Write buffer is cleared after every dump(). def test_unpickler(self): basesize = support.calcobjsize('2P2n2P 2P2n2i5P 2P3n6P2n2i') unpickler = _pickle.Unpickler P = struct.calcsize('P') # Size of memo table entry. n = struct.calcsize('n') # Size of mark table entry. check = self.check_sizeof for encoding in 'ASCII', 'UTF-16', 'latin-1': for errors in 'strict', 'replace': u = unpickler(io.BytesIO(), encoding=encoding, errors=errors) self.assertEqual(object.__sizeof__(u), basesize) check(u, basesize + 32 * P + # Minimal memo table size. len(encoding) + 1 + len(errors) + 1) stdsize = basesize + len('ASCII') + 1 + len('strict') + 1 def check_unpickler(data, memo_size, marks_size): dump = pickle.dumps(data) u = unpickler(io.BytesIO(dump), encoding='ASCII', errors='strict') u.load() check(u, stdsize + memo_size * P + marks_size * n) check_unpickler(0, 32, 0) # 20 is minimal non-empty mark stack size. check_unpickler([0] * 100, 32, 20) # 128 is memo table size required to save references to 100 objects. check_unpickler([chr(i) for i in range(100)], 128, 20) def recurse(deep): data = 0 for i in range(deep): data = [data, data] return data check_unpickler(recurse(0), 32, 0) check_unpickler(recurse(1), 32, 20) check_unpickler(recurse(20), 32, 58) check_unpickler(recurse(50), 64, 58) check_unpickler(recurse(100), 128, 134) u = unpickler(io.BytesIO(pickle.dumps('a', 0)), encoding='ASCII', errors='strict') u.load() check(u, stdsize + 32 * P + 2 + 1) ALT_IMPORT_MAPPING = { ('_elementtree', 'xml.etree.ElementTree'), ('cPickle', 'pickle'), ('StringIO', 'io'), ('cStringIO', 'io'), } ALT_NAME_MAPPING = { ('__builtin__', 'basestring', 'builtins', 'str'), ('exceptions', 'StandardError', 'builtins', 'Exception'), ('UserDict', 'UserDict', 'collections', 'UserDict'), ('socket', '_socketobject', 'socket', 'SocketType'), } def mapping(module, name): if (module, name) in NAME_MAPPING: module, name = NAME_MAPPING[(module, name)] elif module in IMPORT_MAPPING: module = IMPORT_MAPPING[module] return module, name def reverse_mapping(module, name): if (module, name) in REVERSE_NAME_MAPPING: module, name = REVERSE_NAME_MAPPING[(module, name)] elif module in REVERSE_IMPORT_MAPPING: module = REVERSE_IMPORT_MAPPING[module] return module, name def getmodule(module): try: return sys.modules[module] except KeyError: try: __import__(module) except AttributeError as exc: if support.verbose: print("Can't import module %r: %s" % (module, exc)) raise ImportError except ImportError as exc: if support.verbose: print(exc) raise return sys.modules[module] def getattribute(module, name): obj = getmodule(module) for n in name.split('.'): obj = getattr(obj, n) return obj def get_exceptions(mod): for name in dir(mod): attr = getattr(mod, name) if isinstance(attr, type) and issubclass(attr, BaseException): yield name, attr class CompatPickleTests(unittest.TestCase): def test_import(self): modules = set(IMPORT_MAPPING.values()) modules |= set(REVERSE_IMPORT_MAPPING) modules |= {module for module, name in REVERSE_NAME_MAPPING} modules |= {module for module, name in NAME_MAPPING.values()} for module in modules: try: getmodule(module) except ImportError: pass def test_import_mapping(self): for module3, module2 in REVERSE_IMPORT_MAPPING.items(): with self.subTest((module3, module2)): try: getmodule(module3) except ImportError: pass if module3[:1] != '_': self.assertIn(module2, IMPORT_MAPPING) self.assertEqual(IMPORT_MAPPING[module2], module3) def test_name_mapping(self): for (module3, name3), (module2, name2) in REVERSE_NAME_MAPPING.items(): with self.subTest(((module3, name3), (module2, name2))): if (module2, name2) == ('exceptions', 'OSError'): attr = getattribute(module3, name3) self.assertTrue(issubclass(attr, OSError)) elif (module2, name2) == ('exceptions', 'ImportError'): attr = getattribute(module3, name3) self.assertTrue(issubclass(attr, ImportError)) else: module, name = mapping(module2, name2) if module3[:1] != '_': self.assertEqual((module, name), (module3, name3)) try: attr = getattribute(module3, name3) except ImportError: pass else: self.assertEqual(getattribute(module, name), attr) def test_reverse_import_mapping(self): for module2, module3 in IMPORT_MAPPING.items(): with self.subTest((module2, module3)): try: getmodule(module3) except ImportError as exc: if support.verbose: print(exc) if ((module2, module3) not in ALT_IMPORT_MAPPING and REVERSE_IMPORT_MAPPING.get(module3, None) != module2): for (m3, n3), (m2, n2) in REVERSE_NAME_MAPPING.items(): if (module3, module2) == (m3, m2): break else: self.fail('No reverse mapping from %r to %r' % (module3, module2)) module = REVERSE_IMPORT_MAPPING.get(module3, module3) module = IMPORT_MAPPING.get(module, module) self.assertEqual(module, module3) def test_reverse_name_mapping(self): for (module2, name2), (module3, name3) in NAME_MAPPING.items(): with self.subTest(((module2, name2), (module3, name3))): try: attr = getattribute(module3, name3) except ImportError: pass module, name = reverse_mapping(module3, name3) if (module2, name2, module3, name3) not in ALT_NAME_MAPPING: self.assertEqual((module, name), (module2, name2)) module, name = mapping(module, name) self.assertEqual((module, name), (module3, name3)) def test_exceptions(self): self.assertEqual(mapping('exceptions', 'StandardError'), ('builtins', 'Exception')) self.assertEqual(mapping('exceptions', 'Exception'), ('builtins', 'Exception')) self.assertEqual(reverse_mapping('builtins', 'Exception'), ('exceptions', 'Exception')) self.assertEqual(mapping('exceptions', 'OSError'), ('builtins', 'OSError')) self.assertEqual(reverse_mapping('builtins', 'OSError'), ('exceptions', 'OSError')) for name, exc in get_exceptions(builtins): with self.subTest(name): if exc in (BlockingIOError, ResourceWarning, StopAsyncIteration, RecursionError): continue if exc is not OSError and issubclass(exc, OSError): self.assertEqual(reverse_mapping('builtins', name), ('exceptions', 'OSError')) elif exc is not ImportError and issubclass(exc, ImportError): self.assertEqual(reverse_mapping('builtins', name), ('exceptions', 'ImportError')) self.assertEqual(mapping('exceptions', name), ('exceptions', name)) else: self.assertEqual(reverse_mapping('builtins', name), ('exceptions', name)) self.assertEqual(mapping('exceptions', name), ('builtins', name)) def test_multiprocessing_exceptions(self): module = support.import_module('multiprocessing.context') for name, exc in get_exceptions(module): with self.subTest(name): self.assertEqual(reverse_mapping('multiprocessing.context', name), ('multiprocessing', name)) self.assertEqual(mapping('multiprocessing', name), ('multiprocessing.context', name)) def test_main(): tests = [PyPickleTests, PyUnpicklerTests, PyPicklerTests, PyPersPicklerTests, PyIdPersPicklerTests, PyDispatchTableTests, PyChainDispatchTableTests, CompatPickleTests] if has_c_implementation: tests.extend([CPickleTests, CUnpicklerTests, CPicklerTests, CPersPicklerTests, CIdPersPicklerTests, CDumpPickle_LoadPickle, DumpPickle_CLoadPickle, PyPicklerUnpicklerObjectTests, CPicklerUnpicklerObjectTests, CDispatchTableTests, CChainDispatchTableTests, InMemoryPickleTests, SizeofTests]) support.run_unittest(*tests) support.run_doctest(pickle) if __name__ == "__main__": test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
from test.support import verbose, import_module, reap_children # Skip these tests if termios is not available import_module('termios') import errno import pty import os import sys import select import signal import socket import io # readline import unittest TEST_STRING_1 = b"I wish to buy a fish license.\n" TEST_STRING_2 = b"For my pet fish, Eric.\n" if verbose: def debug(msg): print(msg) else: def debug(msg): pass # Note that os.read() is nondeterministic so we need to be very careful # to make the test suite deterministic. A normal call to os.read() may # give us less than expected. # # Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get # back 'foo\r\n' at the other end. The behavior depends on the termios # setting. The newline translation may be OS-specific. To make the # test suite deterministic and OS-independent, the functions _readline # and normalize_output can be used. def normalize_output(data): # Some operating systems do conversions on newline. We could possibly fix # that by doing the appropriate termios.tcsetattr()s. I couldn't figure out # the right combo on Tru64. So, just normalize the output and doc the # problem O/Ses by allowing certain combinations for some platforms, but # avoid allowing other differences (like extra whitespace, trailing garbage, # etc.) # This is about the best we can do without getting some feedback # from someone more knowledgable. # OSF/1 (Tru64) apparently turns \n into \r\r\n. if data.endswith(b'\r\r\n'): return data.replace(b'\r\r\n', b'\n') if data.endswith(b'\r\n'): return data.replace(b'\r\n', b'\n') return data def _readline(fd): """Read one line. May block forever if no newline is read.""" reader = io.FileIO(fd, mode='rb', closefd=False) return reader.readline() # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing # because pty code is not too portable. # XXX(nnorwitz): these tests leak fds when there is an error. class PtyTest(unittest.TestCase): def setUp(self): old_alarm = signal.signal(signal.SIGALRM, self.handle_sig) self.addCleanup(signal.signal, signal.SIGALRM, old_alarm) old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup) self.addCleanup(signal.signal, signal.SIGHUP, old_alarm) # isatty() and close() can hang on some platforms. Set an alarm # before running the test to make sure we don't hang forever. self.addCleanup(signal.alarm, 0) signal.alarm(10) def handle_sig(self, sig, frame): self.fail("isatty hung") @staticmethod def handle_sighup(sig, frame): # if the process is the session leader, os.close(master_fd) # of "master_fd, slave_name = pty.master_open()" raises SIGHUP # signal: just ignore the signal. pass def test_basic(self): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'" % (master_fd, slave_name)) debug("Calling slave_open(%r)" % (slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'" % slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.") self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty') # Solaris requires reading the fd before anything is returned. # My guess is that since we open and close the slave fd # in master_open(), we need to read the EOF. # Ensure the fd is non-blocking in case there's nothing to read. blocking = os.get_blocking(master_fd) try: os.set_blocking(master_fd, False) try: s1 = os.read(master_fd, 1024) self.assertEqual(b'', s1) except OSError as e: if e.errno != errno.EAGAIN: raise finally: # Restore the original flags. os.set_blocking(master_fd, blocking) debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = _readline(master_fd) self.assertEqual(b'I wish to buy a fish license.\n', normalize_output(s1)) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = _readline(master_fd) self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2)) os.close(slave_fd) # closing master_fd can raise a SIGHUP if the process is # the session leader: we installed a SIGHUP signal handler # to ignore this signal. os.close(master_fd) def test_fork(self): debug("calling pty.fork()") pid, master_fd = pty.fork() if pid == pty.CHILD: # stdout should be connected to a tty. if not os.isatty(1): debug("Child's fd 1 is not a tty?!") os._exit(3) # After pty.fork(), the child should already be a session leader. # (on those systems that have that concept.) debug("In child, calling os.setsid()") try: os.setsid() except OSError: # Good, we already were session leader debug("Good: OSError was raised.") pass except AttributeError: # Have pty, but not setsid()? debug("No setsid() available?") pass except: # We don't want this error to propagate, escaping the call to # os._exit() and causing very peculiar behavior in the calling # regrtest.py ! # Note: could add traceback printing here. debug("An unexpected error was raised.") os._exit(1) else: debug("os.setsid() succeeded! (bad!)") os._exit(2) os._exit(4) else: debug("Waiting for child (%d) to finish." % pid) # In verbose mode, we have to consume the debug output from the # child or the child will block, causing this test to hang in the # parent's waitpid() call. The child blocks after a # platform-dependent amount of data is written to its fd. On # Linux 2.6, it's 4000 bytes and the child won't block, but on OS # X even the small writes in the child above will block it. Also # on Linux, the read() will raise an OSError (input/output error) # when it tries to read past the end of the buffer but the child's # already exited, so catch and discard those exceptions. It's not # worth checking for EIO. while True: try: data = os.read(master_fd, 80) except OSError: break if not data: break sys.stdout.write(str(data.replace(b'\r\n', b'\n'), encoding='ascii')) ##line = os.read(master_fd, 80) ##lines = line.replace('\r\n', '\n').split('\n') ##if False and lines != ['In child, calling os.setsid()', ## 'Good: OSError was raised.', '']: ## raise TestFailed("Unexpected output from child: %r" % line) (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)." % (pid, res, status)) if res == 1: self.fail("Child raised an unexpected exception in os.setsid()") elif res == 2: self.fail("pty.fork() failed to make child a session leader.") elif res == 3: self.fail("Child spawned by pty.fork() did not have a tty as stdout") elif res != 4: self.fail("pty.fork() failed for unknown reasons.") ##debug("Reading from master_fd now that the child has exited") ##try: ## s1 = os.read(master_fd, 1024) ##except OSError: ## pass ##else: ## raise TestFailed("Read from master_fd did not raise exception") os.close(master_fd) # pty.fork() passed. class SmallPtyTests(unittest.TestCase): """These tests don't spawn children or hang.""" def setUp(self): self.orig_stdin_fileno = pty.STDIN_FILENO self.orig_stdout_fileno = pty.STDOUT_FILENO self.orig_pty_select = pty.select self.fds = [] # A list of file descriptors to close. self.files = [] self.select_rfds_lengths = [] self.select_rfds_results = [] def tearDown(self): pty.STDIN_FILENO = self.orig_stdin_fileno pty.STDOUT_FILENO = self.orig_stdout_fileno pty.select = self.orig_pty_select for file in self.files: try: file.close() except OSError: pass for fd in self.fds: try: os.close(fd) except OSError: pass def _pipe(self): pipe_fds = os.pipe() self.fds.extend(pipe_fds) return pipe_fds def _socketpair(self): socketpair = socket.socketpair() self.files.extend(socketpair) return socketpair def _mock_select(self, rfds, wfds, xfds): # This will raise IndexError when no more expected calls exist. self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds)) return self.select_rfds_results.pop(0), [], [] def test__copy_to_each(self): """Test the normal data case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] # Feed data. Smaller than PIPEBUF. These writes will not block. os.write(masters[1], b'from master') os.write(write_to_stdin_fd, b'from stdin') # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) self.select_rfds_lengths.append(2) with self.assertRaises(IndexError): pty._copy(masters[0]) # Test that the right data went to the right places. rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0] self.assertEqual([read_from_stdout_fd, masters[1]], rfds) self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master') self.assertEqual(os.read(masters[1], 20), b'from stdin') def test__copy_eof_on_all(self): """Test the empty read EOF case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] socketpair[1].close() os.close(write_to_stdin_fd) # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) # We expect that both fds were removed from the fds list as they # both encountered an EOF before the second select call. self.select_rfds_lengths.append(0) with self.assertRaises(IndexError): pty._copy(masters[0]) def tearDownModule(): reap_children() if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py
import collections import configparser import io import os import pathlib import textwrap import unittest import warnings from test import support class SortedDict(collections.UserDict): def items(self): return sorted(self.data.items()) def keys(self): return sorted(self.data.keys()) def values(self): return [i[1] for i in self.items()] def iteritems(self): return iter(self.items()) def iterkeys(self): return iter(self.keys()) def itervalues(self): return iter(self.values()) __iter__ = iterkeys class CfgParserTestCaseClass: allow_no_value = False delimiters = ('=', ':') comment_prefixes = (';', '#') inline_comment_prefixes = (';', '#') empty_lines_in_values = True dict_type = configparser._default_dict strict = False default_section = configparser.DEFAULTSECT interpolation = configparser._UNSET def newconfig(self, defaults=None): arguments = dict( defaults=defaults, allow_no_value=self.allow_no_value, delimiters=self.delimiters, comment_prefixes=self.comment_prefixes, inline_comment_prefixes=self.inline_comment_prefixes, empty_lines_in_values=self.empty_lines_in_values, dict_type=self.dict_type, strict=self.strict, default_section=self.default_section, interpolation=self.interpolation, ) instance = self.config_class(**arguments) return instance def fromstring(self, string, defaults=None): cf = self.newconfig(defaults) cf.read_string(string) return cf class BasicTestCase(CfgParserTestCaseClass): def basic_test(self, cf): E = ['Commented Bar', 'Foo Bar', 'Internationalized Stuff', 'Long Line', 'Section\\with$weird%characters[\t', 'Spaces', 'Spacey Bar', 'Spacey Bar From The Beginning', 'Types', ] if self.allow_no_value: E.append('NoValue') E.sort() F = [('baz', 'qwe'), ('foo', 'bar3')] # API access L = cf.sections() L.sort() eq = self.assertEqual eq(L, E) L = cf.items('Spacey Bar From The Beginning') L.sort() eq(L, F) # mapping access L = [section for section in cf] L.sort() E.append(self.default_section) E.sort() eq(L, E) L = cf['Spacey Bar From The Beginning'].items() L = sorted(list(L)) eq(L, F) L = cf.items() L = sorted(list(L)) self.assertEqual(len(L), len(E)) for name, section in L: eq(name, section.name) eq(cf.defaults(), cf[self.default_section]) # The use of spaces in the section names serves as a # regression test for SourceForge bug #583248: # http://www.python.org/sf/583248 # API access eq(cf.get('Foo Bar', 'foo'), 'bar1') eq(cf.get('Spacey Bar', 'foo'), 'bar2') eq(cf.get('Spacey Bar From The Beginning', 'foo'), 'bar3') eq(cf.get('Spacey Bar From The Beginning', 'baz'), 'qwe') eq(cf.get('Commented Bar', 'foo'), 'bar4') eq(cf.get('Commented Bar', 'baz'), 'qwe') eq(cf.get('Spaces', 'key with spaces'), 'value') eq(cf.get('Spaces', 'another with spaces'), 'splat!') eq(cf.getint('Types', 'int'), 42) eq(cf.get('Types', 'int'), "42") self.assertAlmostEqual(cf.getfloat('Types', 'float'), 0.44) eq(cf.get('Types', 'float'), "0.44") eq(cf.getboolean('Types', 'boolean'), False) eq(cf.get('Types', '123'), 'strange but acceptable') if self.allow_no_value: eq(cf.get('NoValue', 'option-without-value'), None) # test vars= and fallback= eq(cf.get('Foo Bar', 'foo', fallback='baz'), 'bar1') eq(cf.get('Foo Bar', 'foo', vars={'foo': 'baz'}), 'baz') with self.assertRaises(configparser.NoSectionError): cf.get('No Such Foo Bar', 'foo') with self.assertRaises(configparser.NoOptionError): cf.get('Foo Bar', 'no-such-foo') eq(cf.get('No Such Foo Bar', 'foo', fallback='baz'), 'baz') eq(cf.get('Foo Bar', 'no-such-foo', fallback='baz'), 'baz') eq(cf.get('Spacey Bar', 'foo', fallback=None), 'bar2') eq(cf.get('No Such Spacey Bar', 'foo', fallback=None), None) eq(cf.getint('Types', 'int', fallback=18), 42) eq(cf.getint('Types', 'no-such-int', fallback=18), 18) eq(cf.getint('Types', 'no-such-int', fallback="18"), "18") # sic! with self.assertRaises(configparser.NoOptionError): cf.getint('Types', 'no-such-int') self.assertAlmostEqual(cf.getfloat('Types', 'float', fallback=0.0), 0.44) self.assertAlmostEqual(cf.getfloat('Types', 'no-such-float', fallback=0.0), 0.0) eq(cf.getfloat('Types', 'no-such-float', fallback="0.0"), "0.0") # sic! with self.assertRaises(configparser.NoOptionError): cf.getfloat('Types', 'no-such-float') eq(cf.getboolean('Types', 'boolean', fallback=True), False) eq(cf.getboolean('Types', 'no-such-boolean', fallback="yes"), "yes") # sic! eq(cf.getboolean('Types', 'no-such-boolean', fallback=True), True) with self.assertRaises(configparser.NoOptionError): cf.getboolean('Types', 'no-such-boolean') eq(cf.getboolean('No Such Types', 'boolean', fallback=True), True) if self.allow_no_value: eq(cf.get('NoValue', 'option-without-value', fallback=False), None) eq(cf.get('NoValue', 'no-such-option-without-value', fallback=False), False) # mapping access eq(cf['Foo Bar']['foo'], 'bar1') eq(cf['Spacey Bar']['foo'], 'bar2') section = cf['Spacey Bar From The Beginning'] eq(section.name, 'Spacey Bar From The Beginning') self.assertIs(section.parser, cf) with self.assertRaises(AttributeError): section.name = 'Name is read-only' with self.assertRaises(AttributeError): section.parser = 'Parser is read-only' eq(section['foo'], 'bar3') eq(section['baz'], 'qwe') eq(cf['Commented Bar']['foo'], 'bar4') eq(cf['Commented Bar']['baz'], 'qwe') eq(cf['Spaces']['key with spaces'], 'value') eq(cf['Spaces']['another with spaces'], 'splat!') eq(cf['Long Line']['foo'], 'this line is much, much longer than my editor\nlikes it.') if self.allow_no_value: eq(cf['NoValue']['option-without-value'], None) # test vars= and fallback= eq(cf['Foo Bar'].get('foo', 'baz'), 'bar1') eq(cf['Foo Bar'].get('foo', fallback='baz'), 'bar1') eq(cf['Foo Bar'].get('foo', vars={'foo': 'baz'}), 'baz') with self.assertRaises(KeyError): cf['No Such Foo Bar']['foo'] with self.assertRaises(KeyError): cf['Foo Bar']['no-such-foo'] with self.assertRaises(KeyError): cf['No Such Foo Bar'].get('foo', fallback='baz') eq(cf['Foo Bar'].get('no-such-foo', 'baz'), 'baz') eq(cf['Foo Bar'].get('no-such-foo', fallback='baz'), 'baz') eq(cf['Foo Bar'].get('no-such-foo'), None) eq(cf['Spacey Bar'].get('foo', None), 'bar2') eq(cf['Spacey Bar'].get('foo', fallback=None), 'bar2') with self.assertRaises(KeyError): cf['No Such Spacey Bar'].get('foo', None) eq(cf['Types'].getint('int', 18), 42) eq(cf['Types'].getint('int', fallback=18), 42) eq(cf['Types'].getint('no-such-int', 18), 18) eq(cf['Types'].getint('no-such-int', fallback=18), 18) eq(cf['Types'].getint('no-such-int', "18"), "18") # sic! eq(cf['Types'].getint('no-such-int', fallback="18"), "18") # sic! eq(cf['Types'].getint('no-such-int'), None) self.assertAlmostEqual(cf['Types'].getfloat('float', 0.0), 0.44) self.assertAlmostEqual(cf['Types'].getfloat('float', fallback=0.0), 0.44) self.assertAlmostEqual(cf['Types'].getfloat('no-such-float', 0.0), 0.0) self.assertAlmostEqual(cf['Types'].getfloat('no-such-float', fallback=0.0), 0.0) eq(cf['Types'].getfloat('no-such-float', "0.0"), "0.0") # sic! eq(cf['Types'].getfloat('no-such-float', fallback="0.0"), "0.0") # sic! eq(cf['Types'].getfloat('no-such-float'), None) eq(cf['Types'].getboolean('boolean', True), False) eq(cf['Types'].getboolean('boolean', fallback=True), False) eq(cf['Types'].getboolean('no-such-boolean', "yes"), "yes") # sic! eq(cf['Types'].getboolean('no-such-boolean', fallback="yes"), "yes") # sic! eq(cf['Types'].getboolean('no-such-boolean', True), True) eq(cf['Types'].getboolean('no-such-boolean', fallback=True), True) eq(cf['Types'].getboolean('no-such-boolean'), None) if self.allow_no_value: eq(cf['NoValue'].get('option-without-value', False), None) eq(cf['NoValue'].get('option-without-value', fallback=False), None) eq(cf['NoValue'].get('no-such-option-without-value', False), False) eq(cf['NoValue'].get('no-such-option-without-value', fallback=False), False) # Make sure the right things happen for remove_section() and # remove_option(); added to include check for SourceForge bug #123324. cf[self.default_section]['this_value'] = '1' cf[self.default_section]['that_value'] = '2' # API access self.assertTrue(cf.remove_section('Spaces')) self.assertFalse(cf.has_option('Spaces', 'key with spaces')) self.assertFalse(cf.remove_section('Spaces')) self.assertFalse(cf.remove_section(self.default_section)) self.assertTrue(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existence of option") self.assertFalse(cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") self.assertFalse(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existence of option" " that was removed") self.assertTrue(cf.has_option('Foo Bar', 'this_value')) self.assertFalse(cf.remove_option('Foo Bar', 'this_value')) self.assertTrue(cf.remove_option(self.default_section, 'this_value')) self.assertFalse(cf.has_option('Foo Bar', 'this_value')) self.assertFalse(cf.remove_option(self.default_section, 'this_value')) with self.assertRaises(configparser.NoSectionError) as cm: cf.remove_option('No Such Section', 'foo') self.assertEqual(cm.exception.args, ('No Such Section',)) eq(cf.get('Long Line', 'foo'), 'this line is much, much longer than my editor\nlikes it.') # mapping access del cf['Types'] self.assertFalse('Types' in cf) with self.assertRaises(KeyError): del cf['Types'] with self.assertRaises(ValueError): del cf[self.default_section] del cf['Spacey Bar']['foo'] self.assertFalse('foo' in cf['Spacey Bar']) with self.assertRaises(KeyError): del cf['Spacey Bar']['foo'] self.assertTrue('that_value' in cf['Spacey Bar']) with self.assertRaises(KeyError): del cf['Spacey Bar']['that_value'] del cf[self.default_section]['that_value'] self.assertFalse('that_value' in cf['Spacey Bar']) with self.assertRaises(KeyError): del cf[self.default_section]['that_value'] with self.assertRaises(KeyError): del cf['No Such Section']['foo'] # Don't add new asserts below in this method as most of the options # and sections are now removed. def test_basic(self): config_string = """\ [Foo Bar] foo{0[0]}bar1 [Spacey Bar] foo {0[0]} bar2 [Spacey Bar From The Beginning] foo {0[0]} bar3 baz {0[0]} qwe [Commented Bar] foo{0[1]} bar4 {1[1]} comment baz{0[0]}qwe {1[0]}another one [Long Line] foo{0[1]} this line is much, much longer than my editor likes it. [Section\\with$weird%characters[\t] [Internationalized Stuff] foo[bg]{0[1]} Bulgarian foo{0[0]}Default foo[en]{0[0]}English foo[de]{0[0]}Deutsch [Spaces] key with spaces {0[1]} value another with spaces {0[0]} splat! [Types] int {0[1]} 42 float {0[0]} 0.44 boolean {0[0]} NO 123 {0[1]} strange but acceptable """.format(self.delimiters, self.comment_prefixes) if self.allow_no_value: config_string += ( "[NoValue]\n" "option-without-value\n" ) cf = self.fromstring(config_string) self.basic_test(cf) if self.strict: with self.assertRaises(configparser.DuplicateOptionError): cf.read_string(textwrap.dedent("""\ [Duplicate Options Here] option {0[0]} with a value option {0[1]} with another value """.format(self.delimiters))) with self.assertRaises(configparser.DuplicateSectionError): cf.read_string(textwrap.dedent("""\ [And Now For Something] completely different {0[0]} True [And Now For Something] the larch {0[1]} 1 """.format(self.delimiters))) else: cf.read_string(textwrap.dedent("""\ [Duplicate Options Here] option {0[0]} with a value option {0[1]} with another value """.format(self.delimiters))) cf.read_string(textwrap.dedent("""\ [And Now For Something] completely different {0[0]} True [And Now For Something] the larch {0[1]} 1 """.format(self.delimiters))) def test_basic_from_dict(self): config = { "Foo Bar": { "foo": "bar1", }, "Spacey Bar": { "foo": "bar2", }, "Spacey Bar From The Beginning": { "foo": "bar3", "baz": "qwe", }, "Commented Bar": { "foo": "bar4", "baz": "qwe", }, "Long Line": { "foo": "this line is much, much longer than my editor\nlikes " "it.", }, "Section\\with$weird%characters[\t": { }, "Internationalized Stuff": { "foo[bg]": "Bulgarian", "foo": "Default", "foo[en]": "English", "foo[de]": "Deutsch", }, "Spaces": { "key with spaces": "value", "another with spaces": "splat!", }, "Types": { "int": 42, "float": 0.44, "boolean": False, 123: "strange but acceptable", }, } if self.allow_no_value: config.update({ "NoValue": { "option-without-value": None, } }) cf = self.newconfig() cf.read_dict(config) self.basic_test(cf) if self.strict: with self.assertRaises(configparser.DuplicateSectionError): cf.read_dict({ '1': {'key': 'value'}, 1: {'key2': 'value2'}, }) with self.assertRaises(configparser.DuplicateOptionError): cf.read_dict({ "Duplicate Options Here": { 'option': 'with a value', 'OPTION': 'with another value', }, }) else: cf.read_dict({ 'section': {'key': 'value'}, 'SECTION': {'key2': 'value2'}, }) cf.read_dict({ "Duplicate Options Here": { 'option': 'with a value', 'OPTION': 'with another value', }, }) def test_case_sensitivity(self): cf = self.newconfig() cf.add_section("A") cf.add_section("a") cf.add_section("B") L = cf.sections() L.sort() eq = self.assertEqual eq(L, ["A", "B", "a"]) cf.set("a", "B", "value") eq(cf.options("a"), ["b"]) eq(cf.get("a", "b"), "value", "could not locate option, expecting case-insensitive option names") with self.assertRaises(configparser.NoSectionError): # section names are case-sensitive cf.set("b", "A", "value") self.assertTrue(cf.has_option("a", "b")) self.assertFalse(cf.has_option("b", "b")) cf.set("A", "A-B", "A-B value") for opt in ("a-b", "A-b", "a-B", "A-B"): self.assertTrue( cf.has_option("A", opt), "has_option() returned false for option which should exist") eq(cf.options("A"), ["a-b"]) eq(cf.options("a"), ["b"]) cf.remove_option("a", "B") eq(cf.options("a"), []) # SF bug #432369: cf = self.fromstring( "[MySection]\nOption{} first line \n\tsecond line \n".format( self.delimiters[0])) eq(cf.options("MySection"), ["option"]) eq(cf.get("MySection", "Option"), "first line\nsecond line") # SF bug #561822: cf = self.fromstring("[section]\n" "nekey{}nevalue\n".format(self.delimiters[0]), defaults={"key":"value"}) self.assertTrue(cf.has_option("section", "Key")) def test_case_sensitivity_mapping_access(self): cf = self.newconfig() cf["A"] = {} cf["a"] = {"B": "value"} cf["B"] = {} L = [section for section in cf] L.sort() eq = self.assertEqual elem_eq = self.assertCountEqual eq(L, sorted(["A", "B", self.default_section, "a"])) eq(cf["a"].keys(), {"b"}) eq(cf["a"]["b"], "value", "could not locate option, expecting case-insensitive option names") with self.assertRaises(KeyError): # section names are case-sensitive cf["b"]["A"] = "value" self.assertTrue("b" in cf["a"]) cf["A"]["A-B"] = "A-B value" for opt in ("a-b", "A-b", "a-B", "A-B"): self.assertTrue( opt in cf["A"], "has_option() returned false for option which should exist") eq(cf["A"].keys(), {"a-b"}) eq(cf["a"].keys(), {"b"}) del cf["a"]["B"] elem_eq(cf["a"].keys(), {}) # SF bug #432369: cf = self.fromstring( "[MySection]\nOption{} first line \n\tsecond line \n".format( self.delimiters[0])) eq(cf["MySection"].keys(), {"option"}) eq(cf["MySection"]["Option"], "first line\nsecond line") # SF bug #561822: cf = self.fromstring("[section]\n" "nekey{}nevalue\n".format(self.delimiters[0]), defaults={"key":"value"}) self.assertTrue("Key" in cf["section"]) def test_default_case_sensitivity(self): cf = self.newconfig({"foo": "Bar"}) self.assertEqual( cf.get(self.default_section, "Foo"), "Bar", "could not locate option, expecting case-insensitive option names") cf = self.newconfig({"Foo": "Bar"}) self.assertEqual( cf.get(self.default_section, "Foo"), "Bar", "could not locate option, expecting case-insensitive defaults") def test_parse_errors(self): cf = self.newconfig() self.parse_error(cf, configparser.ParsingError, "[Foo]\n" "{}val-without-opt-name\n".format(self.delimiters[0])) self.parse_error(cf, configparser.ParsingError, "[Foo]\n" "{}val-without-opt-name\n".format(self.delimiters[1])) e = self.parse_error(cf, configparser.MissingSectionHeaderError, "No Section!\n") self.assertEqual(e.args, ('<???>', 1, "No Section!\n")) if not self.allow_no_value: e = self.parse_error(cf, configparser.ParsingError, "[Foo]\n wrong-indent\n") self.assertEqual(e.args, ('<???>',)) # read_file on a real file tricky = support.findfile("cfgparser.3") if self.delimiters[0] == '=': error = configparser.ParsingError expected = (tricky,) else: error = configparser.MissingSectionHeaderError expected = (tricky, 1, ' # INI with as many tricky parts as possible\n') with open(tricky, encoding='utf-8') as f: e = self.parse_error(cf, error, f) self.assertEqual(e.args, expected) def parse_error(self, cf, exc, src): if hasattr(src, 'readline'): sio = src else: sio = io.StringIO(src) with self.assertRaises(exc) as cm: cf.read_file(sio) return cm.exception def test_query_errors(self): cf = self.newconfig() self.assertEqual(cf.sections(), [], "new ConfigParser should have no defined sections") self.assertFalse(cf.has_section("Foo"), "new ConfigParser should have no acknowledged " "sections") with self.assertRaises(configparser.NoSectionError): cf.options("Foo") with self.assertRaises(configparser.NoSectionError): cf.set("foo", "bar", "value") e = self.get_error(cf, configparser.NoSectionError, "foo", "bar") self.assertEqual(e.args, ("foo",)) cf.add_section("foo") e = self.get_error(cf, configparser.NoOptionError, "foo", "bar") self.assertEqual(e.args, ("bar", "foo")) def get_error(self, cf, exc, section, option): try: cf.get(section, option) except exc as e: return e else: self.fail("expected exception type %s.%s" % (exc.__module__, exc.__qualname__)) def test_boolean(self): cf = self.fromstring( "[BOOLTEST]\n" "T1{equals}1\n" "T2{equals}TRUE\n" "T3{equals}True\n" "T4{equals}oN\n" "T5{equals}yes\n" "F1{equals}0\n" "F2{equals}FALSE\n" "F3{equals}False\n" "F4{equals}oFF\n" "F5{equals}nO\n" "E1{equals}2\n" "E2{equals}foo\n" "E3{equals}-1\n" "E4{equals}0.1\n" "E5{equals}FALSE AND MORE".format(equals=self.delimiters[0]) ) for x in range(1, 5): self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x)) self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x)) self.assertRaises(ValueError, cf.getboolean, 'BOOLTEST', 'e%d' % x) def test_weird_errors(self): cf = self.newconfig() cf.add_section("Foo") with self.assertRaises(configparser.DuplicateSectionError) as cm: cf.add_section("Foo") e = cm.exception self.assertEqual(str(e), "Section 'Foo' already exists") self.assertEqual(e.args, ("Foo", None, None)) if self.strict: with self.assertRaises(configparser.DuplicateSectionError) as cm: cf.read_string(textwrap.dedent("""\ [Foo] will this be added{equals}True [Bar] what about this{equals}True [Foo] oops{equals}this won't """.format(equals=self.delimiters[0])), source='<foo-bar>') e = cm.exception self.assertEqual(str(e), "While reading from '<foo-bar>' " "[line 5]: section 'Foo' already exists") self.assertEqual(e.args, ("Foo", '<foo-bar>', 5)) with self.assertRaises(configparser.DuplicateOptionError) as cm: cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}}) e = cm.exception self.assertEqual(str(e), "While reading from '<dict>': option " "'opt' in section 'Bar' already exists") self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) def test_write(self): config_string = ( "[Long Line]\n" "foo{0[0]} this line is much, much longer than my editor\n" " likes it.\n" "[{default_section}]\n" "foo{0[1]} another very\n" " long line\n" "[Long Line - With Comments!]\n" "test {0[1]} we {comment} can\n" " also {comment} place\n" " comments {comment} in\n" " multiline {comment} values" "\n".format(self.delimiters, comment=self.comment_prefixes[0], default_section=self.default_section) ) if self.allow_no_value: config_string += ( "[Valueless]\n" "option-without-value\n" ) cf = self.fromstring(config_string) for space_around_delimiters in (True, False): output = io.StringIO() cf.write(output, space_around_delimiters=space_around_delimiters) delimiter = self.delimiters[0] if space_around_delimiters: delimiter = " {} ".format(delimiter) expect_string = ( "[{default_section}]\n" "foo{equals}another very\n" "\tlong line\n" "\n" "[Long Line]\n" "foo{equals}this line is much, much longer than my editor\n" "\tlikes it.\n" "\n" "[Long Line - With Comments!]\n" "test{equals}we\n" "\talso\n" "\tcomments\n" "\tmultiline\n" "\n".format(equals=delimiter, default_section=self.default_section) ) if self.allow_no_value: expect_string += ( "[Valueless]\n" "option-without-value\n" "\n" ) self.assertEqual(output.getvalue(), expect_string) def test_set_string_types(self): cf = self.fromstring("[sect]\n" "option1{eq}foo\n".format(eq=self.delimiters[0])) # Check that we don't get an exception when setting values in # an existing section using strings: class mystr(str): pass cf.set("sect", "option1", "splat") cf.set("sect", "option1", mystr("splat")) cf.set("sect", "option2", "splat") cf.set("sect", "option2", mystr("splat")) cf.set("sect", "option1", "splat") cf.set("sect", "option2", "splat") def test_read_returns_file_list(self): if self.delimiters[0] != '=': self.skipTest('incompatible format') file1 = support.findfile("cfgparser.1") # check when we pass a mix of readable and non-readable files: cf = self.newconfig() parsed_files = cf.read([file1, "nonexistent-file"]) self.assertEqual(parsed_files, [file1]) self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") # check when we pass only a filename: cf = self.newconfig() parsed_files = cf.read(file1) self.assertEqual(parsed_files, [file1]) self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") # check when we pass only a Path object: cf = self.newconfig() parsed_files = cf.read(pathlib.Path(file1)) self.assertEqual(parsed_files, [file1]) self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") # check when we passed both a filename and a Path object: cf = self.newconfig() parsed_files = cf.read([pathlib.Path(file1), file1]) self.assertEqual(parsed_files, [file1, file1]) self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") # check when we pass only missing files: cf = self.newconfig() parsed_files = cf.read(["nonexistent-file"]) self.assertEqual(parsed_files, []) # check when we pass no files: cf = self.newconfig() parsed_files = cf.read([]) self.assertEqual(parsed_files, []) def test_read_returns_file_list_with_bytestring_path(self): if self.delimiters[0] != '=': self.skipTest('incompatible format') file1_bytestring = support.findfile("cfgparser.1").encode() # check when passing an existing bytestring path cf = self.newconfig() parsed_files = cf.read(file1_bytestring) self.assertEqual(parsed_files, [file1_bytestring]) # check when passing an non-existing bytestring path cf = self.newconfig() parsed_files = cf.read(b'nonexistent-file') self.assertEqual(parsed_files, []) # check when passing both an existing and non-existing bytestring path cf = self.newconfig() parsed_files = cf.read([file1_bytestring, b'nonexistent-file']) self.assertEqual(parsed_files, [file1_bytestring]) # shared by subclasses def get_interpolation_config(self): return self.fromstring( "[Foo]\n" "bar{equals}something %(with1)s interpolation (1 step)\n" "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n" "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n" "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n" "with11{equals}%(with10)s\n" "with10{equals}%(with9)s\n" "with9{equals}%(with8)s\n" "with8{equals}%(With7)s\n" "with7{equals}%(WITH6)s\n" "with6{equals}%(with5)s\n" "With5{equals}%(with4)s\n" "WITH4{equals}%(with3)s\n" "with3{equals}%(with2)s\n" "with2{equals}%(with1)s\n" "with1{equals}with\n" "\n" "[Mutual Recursion]\n" "foo{equals}%(bar)s\n" "bar{equals}%(foo)s\n" "\n" "[Interpolation Error]\n" # no definition for 'reference' "name{equals}%(reference)s\n".format(equals=self.delimiters[0])) def check_items_config(self, expected): cf = self.fromstring(""" [section] name {0[0]} %(value)s key{0[1]} |%(name)s| getdefault{0[1]} |%(default)s| """.format(self.delimiters), defaults={"default": "<default>"}) L = list(cf.items("section", vars={'value': 'value'})) L.sort() self.assertEqual(L, expected) with self.assertRaises(configparser.NoSectionError): cf.items("no such section") def test_popitem(self): cf = self.fromstring(""" [section1] name1 {0[0]} value1 [section2] name2 {0[0]} value2 [section3] name3 {0[0]} value3 """.format(self.delimiters), defaults={"default": "<default>"}) self.assertEqual(cf.popitem()[0], 'section1') self.assertEqual(cf.popitem()[0], 'section2') self.assertEqual(cf.popitem()[0], 'section3') with self.assertRaises(KeyError): cf.popitem() def test_clear(self): cf = self.newconfig({"foo": "Bar"}) self.assertEqual( cf.get(self.default_section, "Foo"), "Bar", "could not locate option, expecting case-insensitive option names") cf['zing'] = {'option1': 'value1', 'option2': 'value2'}
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_module.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_module.py
# Test the module type import unittest import weakref from test.support import gc_collect, requires_type_collecting from test.support.script_helper import assert_python_ok import sys ModuleType = type(sys) class FullLoader: @classmethod def module_repr(cls, m): return "<module '{}' (crafted)>".format(m.__name__) class BareLoader: pass class ModuleTests(unittest.TestCase): def test_uninitialized(self): # An uninitialized module has no __dict__ or __name__, # and __doc__ is None foo = ModuleType.__new__(ModuleType) self.assertTrue(foo.__dict__ is None) self.assertRaises(SystemError, dir, foo) try: s = foo.__name__ self.fail("__name__ = %s" % repr(s)) except AttributeError: pass self.assertEqual(foo.__doc__, ModuleType.__doc__) def test_uninitialized_missing_getattr(self): # Issue 8297 # test the text in the AttributeError of an uninitialized module foo = ModuleType.__new__(ModuleType) self.assertRaisesRegex( AttributeError, "module has no attribute 'not_here'", getattr, foo, "not_here") def test_missing_getattr(self): # Issue 8297 # test the text in the AttributeError foo = ModuleType("foo") self.assertRaisesRegex( AttributeError, "module 'foo' has no attribute 'not_here'", getattr, foo, "not_here") def test_no_docstring(self): # Regularly initialized module, no docstring foo = ModuleType("foo") self.assertEqual(foo.__name__, "foo") self.assertEqual(foo.__doc__, None) self.assertIs(foo.__loader__, None) self.assertIs(foo.__package__, None) self.assertIs(foo.__spec__, None) self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": None, "__loader__": None, "__package__": None, "__spec__": None}) def test_ascii_docstring(self): # ASCII docstring foo = ModuleType("foo", "foodoc") self.assertEqual(foo.__name__, "foo") self.assertEqual(foo.__doc__, "foodoc") self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "__loader__": None, "__package__": None, "__spec__": None}) def test_unicode_docstring(self): # Unicode docstring foo = ModuleType("foo", "foodoc\u1234") self.assertEqual(foo.__name__, "foo") self.assertEqual(foo.__doc__, "foodoc\u1234") self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc\u1234", "__loader__": None, "__package__": None, "__spec__": None}) def test_reinit(self): # Reinitialization should not replace the __dict__ foo = ModuleType("foo", "foodoc\u1234") foo.bar = 42 d = foo.__dict__ foo.__init__("foo", "foodoc") self.assertEqual(foo.__name__, "foo") self.assertEqual(foo.__doc__, "foodoc") self.assertEqual(foo.bar, 42) self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42, "__loader__": None, "__package__": None, "__spec__": None}) self.assertTrue(foo.__dict__ is d) def test_dont_clear_dict(self): # See issue 7140. def f(): foo = ModuleType("foo") foo.bar = 4 return foo gc_collect() self.assertEqual(f().__dict__["bar"], 4) @requires_type_collecting def test_clear_dict_in_ref_cycle(self): destroyed = [] m = ModuleType("foo") m.destroyed = destroyed s = """class A: def __init__(self, l): self.l = l def __del__(self): self.l.append(1) a = A(destroyed)""" exec(s, m.__dict__) del m gc_collect() self.assertEqual(destroyed, [1]) def test_weakref(self): m = ModuleType("foo") wr = weakref.ref(m) self.assertIs(wr(), m) del m gc_collect() self.assertIs(wr(), None) def test_module_getattr(self): import test.good_getattr as gga from test.good_getattr import test self.assertEqual(test, "There is test") self.assertEqual(gga.x, 1) self.assertEqual(gga.y, 2) with self.assertRaisesRegex(AttributeError, "Deprecated, use whatever instead"): gga.yolo self.assertEqual(gga.whatever, "There is whatever") del sys.modules['test.good_getattr'] def test_module_getattr_errors(self): import test.bad_getattr as bga from test import bad_getattr2 self.assertEqual(bga.x, 1) self.assertEqual(bad_getattr2.x, 1) with self.assertRaises(TypeError): bga.nope with self.assertRaises(TypeError): bad_getattr2.nope del sys.modules['test.bad_getattr'] if 'test.bad_getattr2' in sys.modules: del sys.modules['test.bad_getattr2'] def test_module_dir(self): import test.good_getattr as gga self.assertEqual(dir(gga), ['a', 'b', 'c']) del sys.modules['test.good_getattr'] def test_module_dir_errors(self): import test.bad_getattr as bga from test import bad_getattr2 with self.assertRaises(TypeError): dir(bga) with self.assertRaises(TypeError): dir(bad_getattr2) del sys.modules['test.bad_getattr'] if 'test.bad_getattr2' in sys.modules: del sys.modules['test.bad_getattr2'] def test_module_getattr_tricky(self): from test import bad_getattr3 # these lookups should not crash with self.assertRaises(AttributeError): bad_getattr3.one with self.assertRaises(AttributeError): bad_getattr3.delgetattr if 'test.bad_getattr3' in sys.modules: del sys.modules['test.bad_getattr3'] def test_module_repr_minimal(self): # reprs when modules have no __file__, __name__, or __loader__ m = ModuleType('foo') del m.__name__ self.assertEqual(repr(m), "<module '?'>") def test_module_repr_with_name(self): m = ModuleType('foo') self.assertEqual(repr(m), "<module 'foo'>") def test_module_repr_with_name_and_filename(self): m = ModuleType('foo') m.__file__ = '/tmp/foo.py' self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>") def test_module_repr_with_filename_only(self): m = ModuleType('foo') del m.__name__ m.__file__ = '/tmp/foo.py' self.assertEqual(repr(m), "<module '?' from '/tmp/foo.py'>") def test_module_repr_with_loader_as_None(self): m = ModuleType('foo') assert m.__loader__ is None self.assertEqual(repr(m), "<module 'foo'>") def test_module_repr_with_bare_loader_but_no_name(self): m = ModuleType('foo') del m.__name__ # Yes, a class not an instance. m.__loader__ = BareLoader loader_repr = repr(BareLoader) self.assertEqual( repr(m), "<module '?' ({})>".format(loader_repr)) def test_module_repr_with_full_loader_but_no_name(self): # m.__loader__.module_repr() will fail because the module has no # m.__name__. This exception will get suppressed and instead the # loader's repr will be used. m = ModuleType('foo') del m.__name__ # Yes, a class not an instance. m.__loader__ = FullLoader loader_repr = repr(FullLoader) self.assertEqual( repr(m), "<module '?' ({})>".format(loader_repr)) def test_module_repr_with_bare_loader(self): m = ModuleType('foo') # Yes, a class not an instance. m.__loader__ = BareLoader module_repr = repr(BareLoader) self.assertEqual( repr(m), "<module 'foo' ({})>".format(module_repr)) def test_module_repr_with_full_loader(self): m = ModuleType('foo') # Yes, a class not an instance. m.__loader__ = FullLoader self.assertEqual( repr(m), "<module 'foo' (crafted)>") def test_module_repr_with_bare_loader_and_filename(self): # Because the loader has no module_repr(), use the file name. m = ModuleType('foo') # Yes, a class not an instance. m.__loader__ = BareLoader m.__file__ = '/tmp/foo.py' self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>") def test_module_repr_with_full_loader_and_filename(self): # Even though the module has an __file__, use __loader__.module_repr() m = ModuleType('foo') # Yes, a class not an instance. m.__loader__ = FullLoader m.__file__ = '/tmp/foo.py' self.assertEqual(repr(m), "<module 'foo' (crafted)>") def test_module_repr_builtin(self): self.assertEqual(repr(sys), "<module 'sys' (built-in)>") def test_module_repr_source(self): r = repr(unittest) starts_with = "<module 'unittest' from '" ends_with = "__init__.py'>" self.assertEqual(r[:len(starts_with)], starts_with, '{!r} does not start with {!r}'.format(r, starts_with)) self.assertEqual(r[-len(ends_with):], ends_with, '{!r} does not end with {!r}'.format(r, ends_with)) @requires_type_collecting def test_module_finalization_at_shutdown(self): # Module globals and builtins should still be available during shutdown rc, out, err = assert_python_ok("-c", "from test import final_a") self.assertFalse(err) lines = out.splitlines() self.assertEqual(set(lines), { b"x = a", b"x = b", b"final_a.x = a", b"final_b.x = b", b"len = len", b"shutil.rmtree = rmtree"}) def test_descriptor_errors_propagate(self): class Descr: def __get__(self, o, t): raise RuntimeError class M(ModuleType): melon = Descr() self.assertRaises(RuntimeError, getattr, M("mymod"), "melon") # frozen and namespace module reprs are tested in importlib. if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_int.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_int.py
import sys import unittest from test import support from test.test_grammar import (VALID_UNDERSCORE_LITERALS, INVALID_UNDERSCORE_LITERALS) L = [ ('0', 0), ('1', 1), ('9', 9), ('10', 10), ('99', 99), ('100', 100), ('314', 314), (' 314', 314), ('314 ', 314), (' \t\t 314 \t\t ', 314), (repr(sys.maxsize), sys.maxsize), (' 1x', ValueError), (' 1 ', 1), (' 1\02 ', ValueError), ('', ValueError), (' ', ValueError), (' \t\t ', ValueError), ("\u0200", ValueError) ] class IntSubclass(int): pass class IntTestCases(unittest.TestCase): def test_basic(self): self.assertEqual(int(314), 314) self.assertEqual(int(3.14), 3) # Check that conversion from float truncates towards zero self.assertEqual(int(-3.14), -3) self.assertEqual(int(3.9), 3) self.assertEqual(int(-3.9), -3) self.assertEqual(int(3.5), 3) self.assertEqual(int(-3.5), -3) self.assertEqual(int("-3"), -3) self.assertEqual(int(" -3 "), -3) self.assertEqual(int("\N{EM SPACE}-3\N{EN SPACE}"), -3) # Different base: self.assertEqual(int("10",16), 16) # Test conversion from strings and various anomalies for s, v in L: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(int(ss), vv) except ValueError: pass s = repr(-1-sys.maxsize) x = int(s) self.assertEqual(x+1, -sys.maxsize) self.assertIsInstance(x, int) # should return int self.assertEqual(int(s[1:]), sys.maxsize+1) # should return int x = int(1e100) self.assertIsInstance(x, int) x = int(-1e100) self.assertIsInstance(x, int) # SF bug 434186: 0x80000000/2 != 0x80000000>>1. # Worked by accident in Windows release build, but failed in debug build. # Failed in all Linux builds. x = -1-sys.maxsize self.assertEqual(x >> 1, x//2) x = int('1' * 600) self.assertIsInstance(x, int) self.assertRaises(TypeError, int, 1, 12) self.assertEqual(int('0o123', 0), 83) self.assertEqual(int('0x123', 16), 291) # Bug 1679: "0x" is not a valid hex literal self.assertRaises(ValueError, int, "0x", 16) self.assertRaises(ValueError, int, "0x", 0) self.assertRaises(ValueError, int, "0o", 8) self.assertRaises(ValueError, int, "0o", 0) self.assertRaises(ValueError, int, "0b", 2) self.assertRaises(ValueError, int, "0b", 0) # SF bug 1334662: int(string, base) wrong answers # Various representations of 2**32 evaluated to 0 # rather than 2**32 in previous versions self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296) self.assertEqual(int('102002022201221111211', 3), 4294967296) self.assertEqual(int('10000000000000000', 4), 4294967296) self.assertEqual(int('32244002423141', 5), 4294967296) self.assertEqual(int('1550104015504', 6), 4294967296) self.assertEqual(int('211301422354', 7), 4294967296) self.assertEqual(int('40000000000', 8), 4294967296) self.assertEqual(int('12068657454', 9), 4294967296) self.assertEqual(int('4294967296', 10), 4294967296) self.assertEqual(int('1904440554', 11), 4294967296) self.assertEqual(int('9ba461594', 12), 4294967296) self.assertEqual(int('535a79889', 13), 4294967296) self.assertEqual(int('2ca5b7464', 14), 4294967296) self.assertEqual(int('1a20dcd81', 15), 4294967296) self.assertEqual(int('100000000', 16), 4294967296) self.assertEqual(int('a7ffda91', 17), 4294967296) self.assertEqual(int('704he7g4', 18), 4294967296) self.assertEqual(int('4f5aff66', 19), 4294967296) self.assertEqual(int('3723ai4g', 20), 4294967296) self.assertEqual(int('281d55i4', 21), 4294967296) self.assertEqual(int('1fj8b184', 22), 4294967296) self.assertEqual(int('1606k7ic', 23), 4294967296) self.assertEqual(int('mb994ag', 24), 4294967296) self.assertEqual(int('hek2mgl', 25), 4294967296) self.assertEqual(int('dnchbnm', 26), 4294967296) self.assertEqual(int('b28jpdm', 27), 4294967296) self.assertEqual(int('8pfgih4', 28), 4294967296) self.assertEqual(int('76beigg', 29), 4294967296) self.assertEqual(int('5qmcpqg', 30), 4294967296) self.assertEqual(int('4q0jto4', 31), 4294967296) self.assertEqual(int('4000000', 32), 4294967296) self.assertEqual(int('3aokq94', 33), 4294967296) self.assertEqual(int('2qhxjli', 34), 4294967296) self.assertEqual(int('2br45qb', 35), 4294967296) self.assertEqual(int('1z141z4', 36), 4294967296) # tests with base 0 # this fails on 3.0, but in 2.x the old octal syntax is allowed self.assertEqual(int(' 0o123 ', 0), 83) self.assertEqual(int(' 0o123 ', 0), 83) self.assertEqual(int('000', 0), 0) self.assertEqual(int('0o123', 0), 83) self.assertEqual(int('0x123', 0), 291) self.assertEqual(int('0b100', 0), 4) self.assertEqual(int(' 0O123 ', 0), 83) self.assertEqual(int(' 0X123 ', 0), 291) self.assertEqual(int(' 0B100 ', 0), 4) # without base still base 10 self.assertEqual(int('0123'), 123) self.assertEqual(int('0123', 10), 123) # tests with prefix and base != 0 self.assertEqual(int('0x123', 16), 291) self.assertEqual(int('0o123', 8), 83) self.assertEqual(int('0b100', 2), 4) self.assertEqual(int('0X123', 16), 291) self.assertEqual(int('0O123', 8), 83) self.assertEqual(int('0B100', 2), 4) # the code has special checks for the first character after the # type prefix self.assertRaises(ValueError, int, '0b2', 2) self.assertRaises(ValueError, int, '0b02', 2) self.assertRaises(ValueError, int, '0B2', 2) self.assertRaises(ValueError, int, '0B02', 2) self.assertRaises(ValueError, int, '0o8', 8) self.assertRaises(ValueError, int, '0o08', 8) self.assertRaises(ValueError, int, '0O8', 8) self.assertRaises(ValueError, int, '0O08', 8) self.assertRaises(ValueError, int, '0xg', 16) self.assertRaises(ValueError, int, '0x0g', 16) self.assertRaises(ValueError, int, '0Xg', 16) self.assertRaises(ValueError, int, '0X0g', 16) # SF bug 1334662: int(string, base) wrong answers # Checks for proper evaluation of 2**32 + 1 self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297) self.assertEqual(int('102002022201221111212', 3), 4294967297) self.assertEqual(int('10000000000000001', 4), 4294967297) self.assertEqual(int('32244002423142', 5), 4294967297) self.assertEqual(int('1550104015505', 6), 4294967297) self.assertEqual(int('211301422355', 7), 4294967297) self.assertEqual(int('40000000001', 8), 4294967297) self.assertEqual(int('12068657455', 9), 4294967297) self.assertEqual(int('4294967297', 10), 4294967297) self.assertEqual(int('1904440555', 11), 4294967297) self.assertEqual(int('9ba461595', 12), 4294967297) self.assertEqual(int('535a7988a', 13), 4294967297) self.assertEqual(int('2ca5b7465', 14), 4294967297) self.assertEqual(int('1a20dcd82', 15), 4294967297) self.assertEqual(int('100000001', 16), 4294967297) self.assertEqual(int('a7ffda92', 17), 4294967297) self.assertEqual(int('704he7g5', 18), 4294967297) self.assertEqual(int('4f5aff67', 19), 4294967297) self.assertEqual(int('3723ai4h', 20), 4294967297) self.assertEqual(int('281d55i5', 21), 4294967297) self.assertEqual(int('1fj8b185', 22), 4294967297) self.assertEqual(int('1606k7id', 23), 4294967297) self.assertEqual(int('mb994ah', 24), 4294967297) self.assertEqual(int('hek2mgm', 25), 4294967297) self.assertEqual(int('dnchbnn', 26), 4294967297) self.assertEqual(int('b28jpdn', 27), 4294967297) self.assertEqual(int('8pfgih5', 28), 4294967297) self.assertEqual(int('76beigh', 29), 4294967297) self.assertEqual(int('5qmcpqh', 30), 4294967297) self.assertEqual(int('4q0jto5', 31), 4294967297) self.assertEqual(int('4000001', 32), 4294967297) self.assertEqual(int('3aokq95', 33), 4294967297) self.assertEqual(int('2qhxjlj', 34), 4294967297) self.assertEqual(int('2br45qc', 35), 4294967297) self.assertEqual(int('1z141z5', 36), 4294967297) def test_underscores(self): for lit in VALID_UNDERSCORE_LITERALS: if any(ch in lit for ch in '.eEjJ'): continue self.assertEqual(int(lit, 0), eval(lit)) self.assertEqual(int(lit, 0), int(lit.replace('_', ''), 0)) for lit in INVALID_UNDERSCORE_LITERALS: if any(ch in lit for ch in '.eEjJ'): continue self.assertRaises(ValueError, int, lit, 0) # Additional test cases with bases != 0, only for the constructor: self.assertEqual(int("1_00", 3), 9) self.assertEqual(int("0_100"), 100) # not valid as a literal! self.assertEqual(int(b"1_00"), 100) # byte underscore self.assertRaises(ValueError, int, "_100") self.assertRaises(ValueError, int, "+_100") self.assertRaises(ValueError, int, "1__00") self.assertRaises(ValueError, int, "100_") @support.cpython_only def test_small_ints(self): # Bug #3236: Return small longs from PyLong_FromString self.assertIs(int('10'), 10) self.assertIs(int('-1'), -1) self.assertIs(int(b'10'), 10) self.assertIs(int(b'-1'), -1) def test_no_args(self): self.assertEqual(int(), 0) def test_keyword_args(self): # Test invoking int() using keyword arguments. self.assertEqual(int('100', base=2), 4) with self.assertRaisesRegex(TypeError, 'keyword argument'): int(x=1.2) with self.assertRaisesRegex(TypeError, 'keyword argument'): int(x='100', base=2) self.assertRaises(TypeError, int, base=10) self.assertRaises(TypeError, int, base=0) def test_int_base_limits(self): """Testing the supported limits of the int() base parameter.""" self.assertEqual(int('0', 5), 0) with self.assertRaises(ValueError): int('0', 1) with self.assertRaises(ValueError): int('0', 37) with self.assertRaises(ValueError): int('0', -909) # An old magic value base from Python 2. with self.assertRaises(ValueError): int('0', base=0-(2**234)) with self.assertRaises(ValueError): int('0', base=2**234) # Bases 2 through 36 are supported. for base in range(2,37): self.assertEqual(int('0', base=base), 0) def test_int_base_bad_types(self): """Not integer types are not valid bases; issue16772.""" with self.assertRaises(TypeError): int('0', 5.5) with self.assertRaises(TypeError): int('0', 5.0) def test_int_base_indexable(self): class MyIndexable(object): def __init__(self, value): self.value = value def __index__(self): return self.value # Check out of range bases. for base in 2**100, -2**100, 1, 37: with self.assertRaises(ValueError): int('43', base) # Check in-range bases. self.assertEqual(int('101', base=MyIndexable(2)), 5) self.assertEqual(int('101', base=MyIndexable(10)), 101) self.assertEqual(int('101', base=MyIndexable(36)), 1 + 36**2) def test_non_numeric_input_types(self): # Test possible non-numeric types for the argument x, including # subclasses of the explicitly documented accepted types. class CustomStr(str): pass class CustomBytes(bytes): pass class CustomByteArray(bytearray): pass factories = [ bytes, bytearray, lambda b: CustomStr(b.decode()), CustomBytes, CustomByteArray, memoryview, ] try: from array import array except ImportError: pass else: factories.append(lambda b: array('B', b)) for f in factories: x = f(b'100') with self.subTest(type(x)): self.assertEqual(int(x), 100) if isinstance(x, (str, bytes, bytearray)): self.assertEqual(int(x, 2), 4) else: msg = "can't convert non-string" with self.assertRaisesRegex(TypeError, msg): int(x, 2) with self.assertRaisesRegex(ValueError, 'invalid literal'): int(f(b'A' * 0x10)) def test_int_memoryview(self): self.assertEqual(int(memoryview(b'123')[1:3]), 23) self.assertEqual(int(memoryview(b'123\x00')[1:3]), 23) self.assertEqual(int(memoryview(b'123 ')[1:3]), 23) self.assertEqual(int(memoryview(b'123A')[1:3]), 23) self.assertEqual(int(memoryview(b'1234')[1:3]), 23) def test_string_float(self): self.assertRaises(ValueError, int, '1.2') def test_intconversion(self): # Test __int__() class ClassicMissingMethods: pass self.assertRaises(TypeError, int, ClassicMissingMethods()) class MissingMethods(object): pass self.assertRaises(TypeError, int, MissingMethods()) class Foo0: def __int__(self): return 42 self.assertEqual(int(Foo0()), 42) class Classic: pass for base in (object, Classic): class IntOverridesTrunc(base): def __int__(self): return 42 def __trunc__(self): return -12 self.assertEqual(int(IntOverridesTrunc()), 42) class JustTrunc(base): def __trunc__(self): return 42 self.assertEqual(int(JustTrunc()), 42) class ExceptionalTrunc(base): def __trunc__(self): 1 / 0 with self.assertRaises(ZeroDivisionError): int(ExceptionalTrunc()) for trunc_result_base in (object, Classic): class Integral(trunc_result_base): def __int__(self): return 42 class TruncReturnsNonInt(base): def __trunc__(self): return Integral() self.assertEqual(int(TruncReturnsNonInt()), 42) class NonIntegral(trunc_result_base): def __trunc__(self): # Check that we avoid infinite recursion. return NonIntegral() class TruncReturnsNonIntegral(base): def __trunc__(self): return NonIntegral() try: int(TruncReturnsNonIntegral()) except TypeError as e: self.assertEqual(str(e), "__trunc__ returned non-Integral" " (type NonIntegral)") else: self.fail("Failed to raise TypeError with %s" % ((base, trunc_result_base),)) # Regression test for bugs.python.org/issue16060. class BadInt(trunc_result_base): def __int__(self): return 42.0 class TruncReturnsBadInt(base): def __trunc__(self): return BadInt() with self.assertRaises(TypeError): int(TruncReturnsBadInt()) def test_int_subclass_with_int(self): class MyInt(int): def __int__(self): return 42 class BadInt(int): def __int__(self): return 42.0 my_int = MyInt(7) self.assertEqual(my_int, 7) self.assertEqual(int(my_int), 42) self.assertRaises(TypeError, int, BadInt()) def test_int_returns_int_subclass(self): class BadInt: def __int__(self): return True class BadInt2(int): def __int__(self): return True class TruncReturnsBadInt: def __trunc__(self): return BadInt() class TruncReturnsIntSubclass: def __trunc__(self): return True bad_int = BadInt() with self.assertWarns(DeprecationWarning): n = int(bad_int) self.assertEqual(n, 1) self.assertIs(type(n), int) bad_int = BadInt2() with self.assertWarns(DeprecationWarning): n = int(bad_int) self.assertEqual(n, 1) self.assertIs(type(n), int) bad_int = TruncReturnsBadInt() with self.assertWarns(DeprecationWarning): n = int(bad_int) self.assertEqual(n, 1) self.assertIs(type(n), int) good_int = TruncReturnsIntSubclass() n = int(good_int) self.assertEqual(n, 1) self.assertIs(type(n), int) n = IntSubclass(good_int) self.assertEqual(n, 1) self.assertIs(type(n), IntSubclass) def test_error_message(self): def check(s, base=None): with self.assertRaises(ValueError, msg="int(%r, %r)" % (s, base)) as cm: if base is None: int(s) else: int(s, base) self.assertEqual(cm.exception.args[0], "invalid literal for int() with base %d: %r" % (10 if base is None else base, s)) check('\xbd') check('123\xbd') check(' 123 456 ') check('123\x00') # SF bug 1545497: embedded NULs were not detected with explicit base check('123\x00', 10) check('123\x00 245', 20) check('123\x00 245', 16) check('123\x00245', 20) check('123\x00245', 16) # byte string with embedded NUL check(b'123\x00') check(b'123\x00', 10) # non-UTF-8 byte string check(b'123\xbd') check(b'123\xbd', 10) # lone surrogate in Unicode string check('123\ud800') check('123\ud800', 10) def test_issue31619(self): self.assertEqual(int('1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1', 2), 0b1010101010101010101010101010101) self.assertEqual(int('1_2_3_4_5_6_7_0_1_2_3', 8), 0o12345670123) self.assertEqual(int('1_2_3_4_5_6_7_8_9', 16), 0x123456789) self.assertEqual(int('1_2_3_4_5_6_7', 32), 1144132807) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fractions.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fractions.py
"""Tests for Lib/fractions.py.""" from decimal import Decimal from test.support import requires_IEEE_754 import math import numbers import operator import fractions import functools import sys import unittest import warnings from copy import copy, deepcopy from pickle import dumps, loads F = fractions.Fraction gcd = fractions.gcd class DummyFloat(object): """Dummy float class for testing comparisons with Fractions""" def __init__(self, value): if not isinstance(value, float): raise TypeError("DummyFloat can only be initialized from float") self.value = value def _richcmp(self, other, op): if isinstance(other, numbers.Rational): return op(F.from_float(self.value), other) elif isinstance(other, DummyFloat): return op(self.value, other.value) else: return NotImplemented def __eq__(self, other): return self._richcmp(other, operator.eq) def __le__(self, other): return self._richcmp(other, operator.le) def __lt__(self, other): return self._richcmp(other, operator.lt) def __ge__(self, other): return self._richcmp(other, operator.ge) def __gt__(self, other): return self._richcmp(other, operator.gt) # shouldn't be calling __float__ at all when doing comparisons def __float__(self): assert False, "__float__ should not be invoked for comparisons" # same goes for subtraction def __sub__(self, other): assert False, "__sub__ should not be invoked for comparisons" __rsub__ = __sub__ class DummyRational(object): """Test comparison of Fraction with a naive rational implementation.""" def __init__(self, num, den): g = math.gcd(num, den) self.num = num // g self.den = den // g def __eq__(self, other): if isinstance(other, fractions.Fraction): return (self.num == other._numerator and self.den == other._denominator) else: return NotImplemented def __lt__(self, other): return(self.num * other._denominator < self.den * other._numerator) def __gt__(self, other): return(self.num * other._denominator > self.den * other._numerator) def __le__(self, other): return(self.num * other._denominator <= self.den * other._numerator) def __ge__(self, other): return(self.num * other._denominator >= self.den * other._numerator) # this class is for testing comparisons; conversion to float # should never be used for a comparison, since it loses accuracy def __float__(self): assert False, "__float__ should not be invoked" class DummyFraction(fractions.Fraction): """Dummy Fraction subclass for copy and deepcopy testing.""" class GcdTest(unittest.TestCase): def testMisc(self): # fractions.gcd() is deprecated with self.assertWarnsRegex(DeprecationWarning, r'fractions\.gcd'): gcd(1, 1) with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'fractions\.gcd', DeprecationWarning) self.assertEqual(0, gcd(0, 0)) self.assertEqual(1, gcd(1, 0)) self.assertEqual(-1, gcd(-1, 0)) self.assertEqual(1, gcd(0, 1)) self.assertEqual(-1, gcd(0, -1)) self.assertEqual(1, gcd(7, 1)) self.assertEqual(-1, gcd(7, -1)) self.assertEqual(1, gcd(-23, 15)) self.assertEqual(12, gcd(120, 84)) self.assertEqual(-12, gcd(84, -120)) self.assertEqual(gcd(120.0, 84), 12.0) self.assertEqual(gcd(120, 84.0), 12.0) self.assertEqual(gcd(F(120), F(84)), F(12)) self.assertEqual(gcd(F(120, 77), F(84, 55)), F(12, 385)) def _components(r): return (r.numerator, r.denominator) class FractionTest(unittest.TestCase): def assertTypedEquals(self, expected, actual): """Asserts that both the types and values are the same.""" self.assertEqual(type(expected), type(actual)) self.assertEqual(expected, actual) def assertRaisesMessage(self, exc_type, message, callable, *args, **kwargs): """Asserts that callable(*args, **kwargs) raises exc_type(message).""" try: callable(*args, **kwargs) except exc_type as e: self.assertEqual(message, str(e)) else: self.fail("%s not raised" % exc_type.__name__) def testInit(self): self.assertEqual((0, 1), _components(F())) self.assertEqual((7, 1), _components(F(7))) self.assertEqual((7, 3), _components(F(F(7, 3)))) self.assertEqual((-1, 1), _components(F(-1, 1))) self.assertEqual((-1, 1), _components(F(1, -1))) self.assertEqual((1, 1), _components(F(-2, -2))) self.assertEqual((1, 2), _components(F(5, 10))) self.assertEqual((7, 15), _components(F(7, 15))) self.assertEqual((10**23, 1), _components(F(10**23))) self.assertEqual((3, 77), _components(F(F(3, 7), 11))) self.assertEqual((-9, 5), _components(F(2, F(-10, 9)))) self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113)))) self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)", F, 12, 0) self.assertRaises(TypeError, F, 1.5 + 3j) self.assertRaises(TypeError, F, "3/2", 3) self.assertRaises(TypeError, F, 3, 0j) self.assertRaises(TypeError, F, 3, 1j) self.assertRaises(TypeError, F, 1, 2, 3) @requires_IEEE_754 def testInitFromFloat(self): self.assertEqual((5, 2), _components(F(2.5))) self.assertEqual((0, 1), _components(F(-0.0))) self.assertEqual((3602879701896397, 36028797018963968), _components(F(0.1))) # bug 16469: error types should be consistent with float -> int self.assertRaises(ValueError, F, float('nan')) self.assertRaises(OverflowError, F, float('inf')) self.assertRaises(OverflowError, F, float('-inf')) def testInitFromDecimal(self): self.assertEqual((11, 10), _components(F(Decimal('1.1')))) self.assertEqual((7, 200), _components(F(Decimal('3.5e-2')))) self.assertEqual((0, 1), _components(F(Decimal('.000e20')))) # bug 16469: error types should be consistent with decimal -> int self.assertRaises(ValueError, F, Decimal('nan')) self.assertRaises(ValueError, F, Decimal('snan')) self.assertRaises(OverflowError, F, Decimal('inf')) self.assertRaises(OverflowError, F, Decimal('-inf')) def testFromString(self): self.assertEqual((5, 1), _components(F("5"))) self.assertEqual((3, 2), _components(F("3/2"))) self.assertEqual((3, 2), _components(F(" \n +3/2"))) self.assertEqual((-3, 2), _components(F("-3/2 "))) self.assertEqual((13, 2), _components(F(" 013/02 \n "))) self.assertEqual((16, 5), _components(F(" 3.2 "))) self.assertEqual((-16, 5), _components(F(" -3.2 "))) self.assertEqual((-3, 1), _components(F(" -3. "))) self.assertEqual((3, 5), _components(F(" .6 "))) self.assertEqual((1, 3125), _components(F("32.e-5"))) self.assertEqual((1000000, 1), _components(F("1E+06"))) self.assertEqual((-12300, 1), _components(F("-1.23e4"))) self.assertEqual((0, 1), _components(F(" .0e+0\t"))) self.assertEqual((0, 1), _components(F("-0.000e0"))) self.assertRaisesMessage( ZeroDivisionError, "Fraction(3, 0)", F, "3/0") self.assertRaisesMessage( ValueError, "Invalid literal for Fraction: '3/'", F, "3/") self.assertRaisesMessage( ValueError, "Invalid literal for Fraction: '/2'", F, "/2") self.assertRaisesMessage( ValueError, "Invalid literal for Fraction: '3 /2'", F, "3 /2") self.assertRaisesMessage( # Denominators don't need a sign. ValueError, "Invalid literal for Fraction: '3/+2'", F, "3/+2") self.assertRaisesMessage( # Imitate float's parsing. ValueError, "Invalid literal for Fraction: '+ 3/2'", F, "+ 3/2") self.assertRaisesMessage( # Avoid treating '.' as a regex special character. ValueError, "Invalid literal for Fraction: '3a2'", F, "3a2") self.assertRaisesMessage( # Don't accept combinations of decimals and rationals. ValueError, "Invalid literal for Fraction: '3/7.2'", F, "3/7.2") self.assertRaisesMessage( # Don't accept combinations of decimals and rationals. ValueError, "Invalid literal for Fraction: '3.2/7'", F, "3.2/7") self.assertRaisesMessage( # Allow 3. and .3, but not . ValueError, "Invalid literal for Fraction: '.'", F, ".") def testImmutable(self): r = F(7, 3) r.__init__(2, 15) self.assertEqual((7, 3), _components(r)) self.assertRaises(AttributeError, setattr, r, 'numerator', 12) self.assertRaises(AttributeError, setattr, r, 'denominator', 6) self.assertEqual((7, 3), _components(r)) # But if you _really_ need to: r._numerator = 4 r._denominator = 2 self.assertEqual((4, 2), _components(r)) # Which breaks some important operations: self.assertNotEqual(F(4, 2), r) def testFromFloat(self): self.assertRaises(TypeError, F.from_float, 3+4j) self.assertEqual((10, 1), _components(F.from_float(10))) bigint = 1234567890123456789 self.assertEqual((bigint, 1), _components(F.from_float(bigint))) self.assertEqual((0, 1), _components(F.from_float(-0.0))) self.assertEqual((10, 1), _components(F.from_float(10.0))) self.assertEqual((-5, 2), _components(F.from_float(-2.5))) self.assertEqual((99999999999999991611392, 1), _components(F.from_float(1e23))) self.assertEqual(float(10**23), float(F.from_float(1e23))) self.assertEqual((3602879701896397, 1125899906842624), _components(F.from_float(3.2))) self.assertEqual(3.2, float(F.from_float(3.2))) inf = 1e1000 nan = inf - inf # bug 16469: error types should be consistent with float -> int self.assertRaisesMessage( OverflowError, "cannot convert Infinity to integer ratio", F.from_float, inf) self.assertRaisesMessage( OverflowError, "cannot convert Infinity to integer ratio", F.from_float, -inf) self.assertRaisesMessage( ValueError, "cannot convert NaN to integer ratio", F.from_float, nan) def testFromDecimal(self): self.assertRaises(TypeError, F.from_decimal, 3+4j) self.assertEqual(F(10, 1), F.from_decimal(10)) self.assertEqual(F(0), F.from_decimal(Decimal("-0"))) self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5"))) self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3"))) self.assertEqual(F(5000), F.from_decimal(Decimal("5e3"))) self.assertEqual(1 - F(1, 10**30), F.from_decimal(Decimal("0." + "9" * 30))) # bug 16469: error types should be consistent with decimal -> int self.assertRaisesMessage( OverflowError, "cannot convert Infinity to integer ratio", F.from_decimal, Decimal("inf")) self.assertRaisesMessage( OverflowError, "cannot convert Infinity to integer ratio", F.from_decimal, Decimal("-inf")) self.assertRaisesMessage( ValueError, "cannot convert NaN to integer ratio", F.from_decimal, Decimal("nan")) self.assertRaisesMessage( ValueError, "cannot convert NaN to integer ratio", F.from_decimal, Decimal("snan")) def testLimitDenominator(self): rpi = F('3.1415926535897932') self.assertEqual(rpi.limit_denominator(10000), F(355, 113)) self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113)) self.assertEqual(rpi.limit_denominator(113), F(355, 113)) self.assertEqual(rpi.limit_denominator(112), F(333, 106)) self.assertEqual(F(201, 200).limit_denominator(100), F(1)) self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101)) self.assertEqual(F(0).limit_denominator(10000), F(0)) for i in (0, -1): self.assertRaisesMessage( ValueError, "max_denominator should be at least 1", F(1).limit_denominator, i) def testConversions(self): self.assertTypedEquals(-1, math.trunc(F(-11, 10))) self.assertTypedEquals(1, math.trunc(F(11, 10))) self.assertTypedEquals(-2, math.floor(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-10, 10))) self.assertTypedEquals(-1, int(F(-11, 10))) self.assertTypedEquals(0, round(F(-1, 10))) self.assertTypedEquals(0, round(F(-5, 10))) self.assertTypedEquals(-2, round(F(-15, 10))) self.assertTypedEquals(-1, round(F(-7, 10))) self.assertEqual(False, bool(F(0, 1))) self.assertEqual(True, bool(F(3, 2))) self.assertTypedEquals(0.1, float(F(1, 10))) # Check that __float__ isn't implemented by converting the # numerator and denominator to float before dividing. self.assertRaises(OverflowError, float, int('2'*400+'7')) self.assertAlmostEqual(2.0/3, float(F(int('2'*400+'7'), int('3'*400+'1')))) self.assertTypedEquals(0.1+0j, complex(F(1,10))) def testBoolGuarateesBoolReturn(self): # Ensure that __bool__ is used on numerator which guarantees a bool # return. See also bpo-39274. @functools.total_ordering class CustomValue: denominator = 1 def __init__(self, value): self.value = value def __bool__(self): return bool(self.value) @property def numerator(self): # required to preserve `self` during instantiation return self def __eq__(self, other): raise AssertionError("Avoid comparisons in Fraction.__bool__") __lt__ = __eq__ # We did not implement all abstract methods, so register: numbers.Rational.register(CustomValue) numerator = CustomValue(1) r = F(numerator) # ensure the numerator was not lost during instantiation: self.assertIs(r.numerator, numerator) self.assertIs(bool(r), True) numerator = CustomValue(0) r = F(numerator) self.assertIs(bool(r), False) def testRound(self): self.assertTypedEquals(F(-200), round(F(-150), -2)) self.assertTypedEquals(F(-200), round(F(-250), -2)) self.assertTypedEquals(F(30), round(F(26), -1)) self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1)) self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1)) def testArithmetic(self): self.assertEqual(F(1, 2), F(1, 10) + F(2, 5)) self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5)) self.assertEqual(F(1, 25), F(1, 10) * F(2, 5)) self.assertEqual(F(1, 4), F(1, 10) / F(2, 5)) self.assertTypedEquals(2, F(9, 10) // F(2, 5)) self.assertTypedEquals(10**23, F(10**23, 1) // F(1)) self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2)) self.assertEqual(F(8, 27), F(2, 3) ** F(3)) self.assertEqual(F(27, 8), F(2, 3) ** F(-3)) self.assertTypedEquals(2.0, F(4) ** F(1, 2)) self.assertEqual(F(1, 1), +F(1, 1)) z = pow(F(-1), F(1, 2)) self.assertAlmostEqual(z.real, 0) self.assertEqual(z.imag, 1) # Regression test for #27539. p = F(-1, 2) ** 0 self.assertEqual(p, F(1, 1)) self.assertEqual(p.numerator, 1) self.assertEqual(p.denominator, 1) p = F(-1, 2) ** -1 self.assertEqual(p, F(-2, 1)) self.assertEqual(p.numerator, -2) self.assertEqual(p.denominator, 1) p = F(-1, 2) ** -2 self.assertEqual(p, F(4, 1)) self.assertEqual(p.numerator, 4) self.assertEqual(p.denominator, 1) def testMixedArithmetic(self): self.assertTypedEquals(F(11, 10), F(1, 10) + 1) self.assertTypedEquals(1.1, F(1, 10) + 1.0) self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j)) self.assertTypedEquals(F(11, 10), 1 + F(1, 10)) self.assertTypedEquals(1.1, 1.0 + F(1, 10)) self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10)) self.assertTypedEquals(F(-9, 10), F(1, 10) - 1) self.assertTypedEquals(-0.9, F(1, 10) - 1.0) self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j)) self.assertTypedEquals(F(9, 10), 1 - F(1, 10)) self.assertTypedEquals(0.9, 1.0 - F(1, 10)) self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10)) self.assertTypedEquals(F(1, 10), F(1, 10) * 1) self.assertTypedEquals(0.1, F(1, 10) * 1.0) self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j)) self.assertTypedEquals(F(1, 10), 1 * F(1, 10)) self.assertTypedEquals(0.1, 1.0 * F(1, 10)) self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10)) self.assertTypedEquals(F(1, 10), F(1, 10) / 1) self.assertTypedEquals(0.1, F(1, 10) / 1.0) self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j)) self.assertTypedEquals(F(10, 1), 1 / F(1, 10)) self.assertTypedEquals(10.0, 1.0 / F(1, 10)) self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10)) self.assertTypedEquals(0, F(1, 10) // 1) self.assertTypedEquals(0, F(1, 10) // 1.0) self.assertTypedEquals(10, 1 // F(1, 10)) self.assertTypedEquals(10**23, 10**22 // F(1, 10)) self.assertTypedEquals(10, 1.0 // F(1, 10)) self.assertTypedEquals(F(1, 10), F(1, 10) % 1) self.assertTypedEquals(0.1, F(1, 10) % 1.0) self.assertTypedEquals(F(0, 1), 1 % F(1, 10)) self.assertTypedEquals(0.0, 1.0 % F(1, 10)) # No need for divmod since we don't override it. # ** has more interesting conversion rules. self.assertTypedEquals(F(100, 1), F(1, 10) ** -2) self.assertTypedEquals(F(100, 1), F(10, 1) ** 2) self.assertTypedEquals(0.1, F(1, 10) ** 1.0) self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j)) self.assertTypedEquals(4 , 2 ** F(2, 1)) z = pow(-1, F(1, 2)) self.assertAlmostEqual(0, z.real) self.assertEqual(1, z.imag) self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1)) self.assertTypedEquals(2.0 , 4 ** F(1, 2)) self.assertTypedEquals(0.25, 2.0 ** F(-2, 1)) self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10)) self.assertRaises(ZeroDivisionError, operator.pow, F(0, 1), -2) def testMixingWithDecimal(self): # Decimal refuses mixed arithmetic (but not mixed comparisons) self.assertRaises(TypeError, operator.add, F(3,11), Decimal('3.1415926')) self.assertRaises(TypeError, operator.add, Decimal('3.1415926'), F(3,11)) def testComparisons(self): self.assertTrue(F(1, 2) < F(2, 3)) self.assertFalse(F(1, 2) < F(1, 2)) self.assertTrue(F(1, 2) <= F(2, 3)) self.assertTrue(F(1, 2) <= F(1, 2)) self.assertFalse(F(2, 3) <= F(1, 2)) self.assertTrue(F(1, 2) == F(1, 2)) self.assertFalse(F(1, 2) == F(1, 3)) self.assertFalse(F(1, 2) != F(1, 2)) self.assertTrue(F(1, 2) != F(1, 3)) def testComparisonsDummyRational(self): self.assertTrue(F(1, 2) == DummyRational(1, 2)) self.assertTrue(DummyRational(1, 2) == F(1, 2)) self.assertFalse(F(1, 2) == DummyRational(3, 4)) self.assertFalse(DummyRational(3, 4) == F(1, 2)) self.assertTrue(F(1, 2) < DummyRational(3, 4)) self.assertFalse(F(1, 2) < DummyRational(1, 2)) self.assertFalse(F(1, 2) < DummyRational(1, 7)) self.assertFalse(F(1, 2) > DummyRational(3, 4)) self.assertFalse(F(1, 2) > DummyRational(1, 2)) self.assertTrue(F(1, 2) > DummyRational(1, 7)) self.assertTrue(F(1, 2) <= DummyRational(3, 4)) self.assertTrue(F(1, 2) <= DummyRational(1, 2)) self.assertFalse(F(1, 2) <= DummyRational(1, 7)) self.assertFalse(F(1, 2) >= DummyRational(3, 4)) self.assertTrue(F(1, 2) >= DummyRational(1, 2)) self.assertTrue(F(1, 2) >= DummyRational(1, 7)) self.assertTrue(DummyRational(1, 2) < F(3, 4)) self.assertFalse(DummyRational(1, 2) < F(1, 2)) self.assertFalse(DummyRational(1, 2) < F(1, 7)) self.assertFalse(DummyRational(1, 2) > F(3, 4)) self.assertFalse(DummyRational(1, 2) > F(1, 2)) self.assertTrue(DummyRational(1, 2) > F(1, 7)) self.assertTrue(DummyRational(1, 2) <= F(3, 4)) self.assertTrue(DummyRational(1, 2) <= F(1, 2)) self.assertFalse(DummyRational(1, 2) <= F(1, 7)) self.assertFalse(DummyRational(1, 2) >= F(3, 4)) self.assertTrue(DummyRational(1, 2) >= F(1, 2)) self.assertTrue(DummyRational(1, 2) >= F(1, 7)) def testComparisonsDummyFloat(self): x = DummyFloat(1./3.) y = F(1, 3) self.assertTrue(x != y) self.assertTrue(x < y or x > y) self.assertFalse(x == y) self.assertFalse(x <= y and x >= y) self.assertTrue(y != x) self.assertTrue(y < x or y > x) self.assertFalse(y == x) self.assertFalse(y <= x and y >= x) def testMixedLess(self): self.assertTrue(2 < F(5, 2)) self.assertFalse(2 < F(4, 2)) self.assertTrue(F(5, 2) < 3) self.assertFalse(F(4, 2) < 2) self.assertTrue(F(1, 2) < 0.6) self.assertFalse(F(1, 2) < 0.4) self.assertTrue(0.4 < F(1, 2)) self.assertFalse(0.5 < F(1, 2)) self.assertFalse(float('inf') < F(1, 2)) self.assertTrue(float('-inf') < F(0, 10)) self.assertFalse(float('nan') < F(-3, 7)) self.assertTrue(F(1, 2) < float('inf')) self.assertFalse(F(17, 12) < float('-inf')) self.assertFalse(F(144, -89) < float('nan')) def testMixedLessEqual(self): self.assertTrue(0.5 <= F(1, 2)) self.assertFalse(0.6 <= F(1, 2)) self.assertTrue(F(1, 2) <= 0.5) self.assertFalse(F(1, 2) <= 0.4) self.assertTrue(2 <= F(4, 2)) self.assertFalse(2 <= F(3, 2)) self.assertTrue(F(4, 2) <= 2) self.assertFalse(F(5, 2) <= 2) self.assertFalse(float('inf') <= F(1, 2)) self.assertTrue(float('-inf') <= F(0, 10)) self.assertFalse(float('nan') <= F(-3, 7)) self.assertTrue(F(1, 2) <= float('inf')) self.assertFalse(F(17, 12) <= float('-inf')) self.assertFalse(F(144, -89) <= float('nan')) def testBigFloatComparisons(self): # Because 10**23 can't be represented exactly as a float: self.assertFalse(F(10**23) == float(10**23)) # The first test demonstrates why these are important. self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1))) self.assertTrue(1e23 < F(math.trunc(1e23) + 1)) self.assertFalse(1e23 <= F(math.trunc(1e23) - 1)) self.assertTrue(1e23 > F(math.trunc(1e23) - 1)) self.assertFalse(1e23 >= F(math.trunc(1e23) + 1)) def testBigComplexComparisons(self): self.assertFalse(F(10**23) == complex(10**23)) self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23)) self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23)) x = F(3, 8) z = complex(0.375, 0.0) w = complex(0.375, 0.2) self.assertTrue(x == z) self.assertFalse(x != z) self.assertFalse(x == w) self.assertTrue(x != w) for op in operator.lt, operator.le, operator.gt, operator.ge: self.assertRaises(TypeError, op, x, z) self.assertRaises(TypeError, op, z, x) self.assertRaises(TypeError, op, x, w) self.assertRaises(TypeError, op, w, x) def testMixedEqual(self): self.assertTrue(0.5 == F(1, 2)) self.assertFalse(0.6 == F(1, 2)) self.assertTrue(F(1, 2) == 0.5) self.assertFalse(F(1, 2) == 0.4) self.assertTrue(2 == F(4, 2)) self.assertFalse(2 == F(3, 2)) self.assertTrue(F(4, 2) == 2) self.assertFalse(F(5, 2) == 2) self.assertFalse(F(5, 2) == float('nan')) self.assertFalse(float('nan') == F(3, 7)) self.assertFalse(F(5, 2) == float('inf')) self.assertFalse(float('-inf') == F(2, 5)) def testStringification(self): self.assertEqual("Fraction(7, 3)", repr(F(7, 3))) self.assertEqual("Fraction(6283185307, 2000000000)", repr(F('3.1415926535'))) self.assertEqual("Fraction(-1, 100000000000000000000)", repr(F(1, -10**20))) self.assertEqual("7/3", str(F(7, 3))) self.assertEqual("7", str(F(7, 1))) def testHash(self): hmod = sys.hash_info.modulus hinf = sys.hash_info.inf self.assertEqual(hash(2.5), hash(F(5, 2))) self.assertEqual(hash(10**50), hash(F(10**50))) self.assertNotEqual(hash(float(10**23)), hash(F(10**23))) self.assertEqual(hinf, hash(F(1, hmod))) # Check that __hash__ produces the same value as hash(), for # consistency with int and Decimal. (See issue #10356.) self.assertEqual(hash(F(-1)), F(-1).__hash__()) def testApproximatePi(self): # Algorithm borrowed from # http://docs.python.org/lib/decimal-recipes.html three = F(3) lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 while abs(s - lasts) > F(1, 10**9): lasts = s n, na = n+na, na+8 d, da = d+da, da+32 t = (t * n) / d s += t self.assertAlmostEqual(math.pi, s) def testApproximateCos1(self): # Algorithm borrowed from # http://docs.python.org/lib/decimal-recipes.html x = F(1) i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1 while abs(s - lasts) > F(1, 10**9): lasts = s i += 2 fact *= i * (i-1) num *= x * x sign *= -1 s += num / fact * sign self.assertAlmostEqual(math.cos(1), s) def test_copy_deepcopy_pickle(self): r = F(13, 7) dr = DummyFraction(13, 7) self.assertEqual(r, loads(dumps(r))) self.assertEqual(id(r), id(copy(r))) self.assertEqual(id(r), id(deepcopy(r))) self.assertNotEqual(id(dr), id(copy(dr))) self.assertNotEqual(id(dr), id(deepcopy(dr))) self.assertTypedEquals(dr, copy(dr)) self.assertTypedEquals(dr, deepcopy(dr)) def test_slots(self): # Issue 4998 r = F(13, 7) self.assertRaises(AttributeError, setattr, r, 'a', 10) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_multiprocessing_spawn.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_multiprocessing_spawn.py
import unittest import test._test_multiprocessing from test import support if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") test._test_multiprocessing.install_tests_in_module_dict(globals(), 'spawn') if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
import os import sys from test.support import TESTFN, rmtree, unlink, captured_stdout from test.support.script_helper import assert_python_ok, assert_python_failure import textwrap import unittest import trace from trace import Trace from test.tracedmodules import testmod #------------------------------- Utilities -----------------------------------# def fix_ext_py(filename): """Given a .pyc filename converts it to the appropriate .py""" if filename.endswith('.pyc'): filename = filename[:-1] return filename def my_file_and_modname(): """The .py file and module name of this file (__file__)""" modname = os.path.splitext(os.path.basename(__file__))[0] return fix_ext_py(__file__), modname def get_firstlineno(func): return func.__code__.co_firstlineno #-------------------- Target functions for tracing ---------------------------# # # The relative line numbers of lines in these functions matter for verifying # tracing. Please modify the appropriate tests if you change one of the # functions. Absolute line numbers don't matter. # def traced_func_linear(x, y): a = x b = y c = a + b return c def traced_func_loop(x, y): c = x for i in range(5): c += y return c def traced_func_importing(x, y): return x + y + testmod.func(1) def traced_func_simple_caller(x): c = traced_func_linear(x, x) return c + x def traced_func_importing_caller(x): k = traced_func_simple_caller(x) k += traced_func_importing(k, x) return k def traced_func_generator(num): c = 5 # executed once for i in range(num): yield i + c def traced_func_calling_generator(): k = 0 for i in traced_func_generator(10): k += i def traced_doubler(num): return num * 2 def traced_capturer(*args, **kwargs): return args, kwargs def traced_caller_list_comprehension(): k = 10 mylist = [traced_doubler(i) for i in range(k)] return mylist class TracedClass(object): def __init__(self, x): self.a = x def inst_method_linear(self, y): return self.a + y def inst_method_calling(self, x): c = self.inst_method_linear(x) return c + traced_func_linear(x, c) @classmethod def class_method_linear(cls, y): return y * 2 @staticmethod def static_method_linear(y): return y * 2 #------------------------------ Test cases -----------------------------------# class TestLineCounts(unittest.TestCase): """White-box testing of line-counting, via runfunc""" def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0) self.my_py_filename = fix_ext_py(__file__) def test_traced_func_linear(self): result = self.tracer.runfunc(traced_func_linear, 2, 5) self.assertEqual(result, 7) # all lines are executed once expected = {} firstlineno = get_firstlineno(traced_func_linear) for i in range(1, 5): expected[(self.my_py_filename, firstlineno + i)] = 1 self.assertEqual(self.tracer.results().counts, expected) def test_traced_func_loop(self): self.tracer.runfunc(traced_func_loop, 2, 3) firstlineno = get_firstlineno(traced_func_loop) expected = { (self.my_py_filename, firstlineno + 1): 1, (self.my_py_filename, firstlineno + 2): 6, (self.my_py_filename, firstlineno + 3): 5, (self.my_py_filename, firstlineno + 4): 1, } self.assertEqual(self.tracer.results().counts, expected) def test_traced_func_importing(self): self.tracer.runfunc(traced_func_importing, 2, 5) firstlineno = get_firstlineno(traced_func_importing) expected = { (self.my_py_filename, firstlineno + 1): 1, (fix_ext_py(testmod.__file__), 2): 1, (fix_ext_py(testmod.__file__), 3): 1, } self.assertEqual(self.tracer.results().counts, expected) def test_trace_func_generator(self): self.tracer.runfunc(traced_func_calling_generator) firstlineno_calling = get_firstlineno(traced_func_calling_generator) firstlineno_gen = get_firstlineno(traced_func_generator) expected = { (self.my_py_filename, firstlineno_calling + 1): 1, (self.my_py_filename, firstlineno_calling + 2): 11, (self.my_py_filename, firstlineno_calling + 3): 10, (self.my_py_filename, firstlineno_gen + 1): 1, (self.my_py_filename, firstlineno_gen + 2): 11, (self.my_py_filename, firstlineno_gen + 3): 10, } self.assertEqual(self.tracer.results().counts, expected) def test_trace_list_comprehension(self): self.tracer.runfunc(traced_caller_list_comprehension) firstlineno_calling = get_firstlineno(traced_caller_list_comprehension) firstlineno_called = get_firstlineno(traced_doubler) expected = { (self.my_py_filename, firstlineno_calling + 1): 1, # List compehentions work differently in 3.x, so the count # below changed compared to 2.x. (self.my_py_filename, firstlineno_calling + 2): 12, (self.my_py_filename, firstlineno_calling + 3): 1, (self.my_py_filename, firstlineno_called + 1): 10, } self.assertEqual(self.tracer.results().counts, expected) def test_linear_methods(self): # XXX todo: later add 'static_method_linear' and 'class_method_linear' # here, once issue1764286 is resolved # for methname in ['inst_method_linear',]: tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0) traced_obj = TracedClass(25) method = getattr(traced_obj, methname) tracer.runfunc(method, 20) firstlineno = get_firstlineno(method) expected = { (self.my_py_filename, firstlineno + 1): 1, } self.assertEqual(tracer.results().counts, expected) class TestRunExecCounts(unittest.TestCase): """A simple sanity test of line-counting, via runctx (exec)""" def setUp(self): self.my_py_filename = fix_ext_py(__file__) self.addCleanup(sys.settrace, sys.gettrace()) def test_exec_counts(self): self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0) code = r'''traced_func_loop(2, 5)''' code = compile(code, __file__, 'exec') self.tracer.runctx(code, globals(), vars()) firstlineno = get_firstlineno(traced_func_loop) expected = { (self.my_py_filename, firstlineno + 1): 1, (self.my_py_filename, firstlineno + 2): 6, (self.my_py_filename, firstlineno + 3): 5, (self.my_py_filename, firstlineno + 4): 1, } # When used through 'run', some other spurious counts are produced, like # the settrace of threading, which we ignore, just making sure that the # counts fo traced_func_loop were right. # for k in expected.keys(): self.assertEqual(self.tracer.results().counts[k], expected[k]) class TestFuncs(unittest.TestCase): """White-box testing of funcs tracing""" def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) self.tracer = Trace(count=0, trace=0, countfuncs=1) self.filemod = my_file_and_modname() self._saved_tracefunc = sys.gettrace() def tearDown(self): if self._saved_tracefunc is not None: sys.settrace(self._saved_tracefunc) def test_simple_caller(self): self.tracer.runfunc(traced_func_simple_caller, 1) expected = { self.filemod + ('traced_func_simple_caller',): 1, self.filemod + ('traced_func_linear',): 1, } self.assertEqual(self.tracer.results().calledfuncs, expected) def test_arg_errors(self): res = self.tracer.runfunc(traced_capturer, 1, 2, self=3, func=4) self.assertEqual(res, ((1, 2), {'self': 3, 'func': 4})) res = self.tracer.runfunc(func=traced_capturer, arg=1) self.assertEqual(res, ((), {'arg': 1})) with self.assertRaises(TypeError): self.tracer.runfunc() def test_loop_caller_importing(self): self.tracer.runfunc(traced_func_importing_caller, 1) expected = { self.filemod + ('traced_func_simple_caller',): 1, self.filemod + ('traced_func_linear',): 1, self.filemod + ('traced_func_importing_caller',): 1, self.filemod + ('traced_func_importing',): 1, (fix_ext_py(testmod.__file__), 'testmod', 'func'): 1, } self.assertEqual(self.tracer.results().calledfuncs, expected) @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'pre-existing trace function throws off measurements') def test_inst_method_calling(self): obj = TracedClass(20) self.tracer.runfunc(obj.inst_method_calling, 1) expected = { self.filemod + ('TracedClass.inst_method_calling',): 1, self.filemod + ('TracedClass.inst_method_linear',): 1, self.filemod + ('traced_func_linear',): 1, } self.assertEqual(self.tracer.results().calledfuncs, expected) class TestCallers(unittest.TestCase): """White-box testing of callers tracing""" def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) self.tracer = Trace(count=0, trace=0, countcallers=1) self.filemod = my_file_and_modname() @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'pre-existing trace function throws off measurements') def test_loop_caller_importing(self): self.tracer.runfunc(traced_func_importing_caller, 1) expected = { ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'), (self.filemod + ('traced_func_importing_caller',))): 1, ((self.filemod + ('traced_func_simple_caller',)), (self.filemod + ('traced_func_linear',))): 1, ((self.filemod + ('traced_func_importing_caller',)), (self.filemod + ('traced_func_simple_caller',))): 1, ((self.filemod + ('traced_func_importing_caller',)), (self.filemod + ('traced_func_importing',))): 1, ((self.filemod + ('traced_func_importing',)), (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1, } self.assertEqual(self.tracer.results().callers, expected) # Created separately for issue #3821 class TestCoverage(unittest.TestCase): def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) def tearDown(self): rmtree(TESTFN) unlink(TESTFN) def _coverage(self, tracer, cmd='import test.support, test.test_pprint;' 'test.support.run_unittest(test.test_pprint.QueryTestCase)'): tracer.run(cmd) r = tracer.results() r.write_results(show_missing=True, summary=True, coverdir=TESTFN) def test_coverage(self): tracer = trace.Trace(trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) stdout = stdout.getvalue() self.assertIn("pprint.py", stdout) self.assertIn("case.py", stdout) # from unittest files = os.listdir(TESTFN) self.assertIn("pprint.cover", files) self.assertIn("unittest.case.cover", files) def test_coverage_ignore(self): # Ignore all files, nothing should be traced nor printed libpath = os.path.normpath(os.path.dirname(os.__file__)) # sys.prefix does not work when running from a checkout tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix, libpath], trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) if os.path.exists(TESTFN): files = os.listdir(TESTFN) self.assertEqual(files, ['_importlib.cover']) # Ignore __import__ def test_issue9936(self): tracer = trace.Trace(trace=0, count=1) modname = 'test.tracedmodules.testmod' # Ensure that the module is executed in import if modname in sys.modules: del sys.modules[modname] cmd = ("import test.tracedmodules.testmod as t;" "t.func(0); t.func2();") with captured_stdout() as stdout: self._coverage(tracer, cmd) stdout.seek(0) stdout.readline() coverage = {} for line in stdout: lines, cov, module = line.split()[:3] coverage[module] = (int(lines), int(cov[:-1])) # XXX This is needed to run regrtest.py as a script modname = trace._fullmodname(sys.modules[modname].__file__) self.assertIn(modname, coverage) self.assertEqual(coverage[modname], (5, 100)) ### Tests that don't mess with sys.settrace and can be traced ### themselves TODO: Skip tests that do mess with sys.settrace when ### regrtest is invoked with -T option. class Test_Ignore(unittest.TestCase): def test_ignored(self): jn = os.path.join ignore = trace._Ignore(['x', 'y.z'], [jn('foo', 'bar')]) self.assertTrue(ignore.names('x.py', 'x')) self.assertFalse(ignore.names('xy.py', 'xy')) self.assertFalse(ignore.names('y.py', 'y')) self.assertTrue(ignore.names(jn('foo', 'bar', 'baz.py'), 'baz')) self.assertFalse(ignore.names(jn('bar', 'z.py'), 'z')) # Matched before. self.assertTrue(ignore.names(jn('bar', 'baz.py'), 'baz')) # Created for Issue 31908 -- CLI utility not writing cover files class TestCoverageCommandLineOutput(unittest.TestCase): codefile = 'tmp.py' coverfile = 'tmp.cover' def setUp(self): with open(self.codefile, 'w') as f: f.write(textwrap.dedent('''\ x = 42 if []: print('unreachable') ''')) def tearDown(self): unlink(self.codefile) unlink(self.coverfile) def test_cover_files_written_no_highlight(self): # Test also that the cover file for the trace module is not created # (issue #34171). tracedir = os.path.dirname(os.path.abspath(trace.__file__)) tracecoverpath = os.path.join(tracedir, 'trace.cover') unlink(tracecoverpath) argv = '-m trace --count'.split() + [self.codefile] status, stdout, stderr = assert_python_ok(*argv) self.assertEqual(stderr, b'') self.assertFalse(os.path.exists(tracecoverpath)) self.assertTrue(os.path.exists(self.coverfile)) with open(self.coverfile) as f: self.assertEqual(f.read(), " 1: x = 42\n" " 1: if []:\n" " print('unreachable')\n" ) def test_cover_files_written_with_highlight(self): argv = '-m trace --count --missing'.split() + [self.codefile] status, stdout, stderr = assert_python_ok(*argv) self.assertTrue(os.path.exists(self.coverfile)) with open(self.coverfile) as f: self.assertEqual(f.read(), textwrap.dedent('''\ 1: x = 42 1: if []: >>>>>> print('unreachable') ''')) class TestCommandLine(unittest.TestCase): def test_failures(self): _errors = ( (b'filename is missing: required with the main options', '-l', '-T'), (b'cannot specify both --listfuncs and (--trace or --count)', '-lc'), (b'argument -R/--no-report: not allowed with argument -r/--report', '-rR'), (b'must specify one of --trace, --count, --report, --listfuncs, or --trackcalls', '-g'), (b'-r/--report requires -f/--file', '-r'), (b'--summary can only be used with --count or --report', '-sT'), (b'unrecognized arguments: -y', '-y')) for message, *args in _errors: *_, stderr = assert_python_failure('-m', 'trace', *args) self.assertIn(message, stderr) def test_listfuncs_flag_success(self): with open(TESTFN, 'w') as fd: self.addCleanup(unlink, TESTFN) fd.write("a = 1\n") status, stdout, stderr = assert_python_ok('-m', 'trace', '-l', TESTFN) self.assertIn(b'functions called:', stdout) def test_sys_argv_list(self): with open(TESTFN, 'w') as fd: self.addCleanup(unlink, TESTFN) fd.write("import sys\n") fd.write("print(type(sys.argv))\n") status, direct_stdout, stderr = assert_python_ok(TESTFN) status, trace_stdout, stderr = assert_python_ok('-m', 'trace', '-l', TESTFN) self.assertIn(direct_stdout.strip(), trace_stdout) def test_count_and_summary(self): filename = f'{TESTFN}.py' coverfilename = f'{TESTFN}.cover' with open(filename, 'w') as fd: self.addCleanup(unlink, filename) self.addCleanup(unlink, coverfilename) fd.write(textwrap.dedent("""\ x = 1 y = 2 def f(): return x + y for i in range(10): f() """)) status, stdout, _ = assert_python_ok('-m', 'trace', '-cs', filename) stdout = stdout.decode() self.assertEqual(status, 0) self.assertIn('lines cov% module (path)', stdout) self.assertIn(f'6 100% {TESTFN} ({filename})', stdout) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tarfile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tarfile.py
import sys import os import io from hashlib import md5 from contextlib import contextmanager from random import Random import pathlib import unittest import unittest.mock import tarfile from test import support from test.support import script_helper # Check for our compression modules. try: import gzip except ImportError: gzip = None try: import bz2 except ImportError: bz2 = None try: import lzma except ImportError: lzma = None def md5sum(data): return md5(data).hexdigest() TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir" tarextdir = TEMPDIR + '-extract-test' tarname = support.findfile("testtar.tar") gzipname = os.path.join(TEMPDIR, "testtar.tar.gz") bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2") xzname = os.path.join(TEMPDIR, "testtar.tar.xz") tmpname = os.path.join(TEMPDIR, "tmp.tar") dotlessname = os.path.join(TEMPDIR, "testtar") md5_regtype = "65f477c818ad9e15f7feab0c6d37742f" md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6" class TarTest: tarname = tarname suffix = '' open = io.FileIO taropen = tarfile.TarFile.taropen @property def mode(self): return self.prefix + self.suffix @support.requires_gzip class GzipTest: tarname = gzipname suffix = 'gz' open = gzip.GzipFile if gzip else None taropen = tarfile.TarFile.gzopen @support.requires_bz2 class Bz2Test: tarname = bz2name suffix = 'bz2' open = bz2.BZ2File if bz2 else None taropen = tarfile.TarFile.bz2open @support.requires_lzma class LzmaTest: tarname = xzname suffix = 'xz' open = lzma.LZMAFile if lzma else None taropen = tarfile.TarFile.xzopen class ReadTest(TarTest): prefix = "r:" def setUp(self): self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1") def tearDown(self): self.tar.close() class UstarReadTest(ReadTest, unittest.TestCase): def test_fileobj_regular_file(self): tarinfo = self.tar.getmember("ustar/regtype") with self.tar.extractfile(tarinfo) as fobj: data = fobj.read() self.assertEqual(len(data), tarinfo.size, "regular file extraction failed") self.assertEqual(md5sum(data), md5_regtype, "regular file extraction failed") def test_fileobj_readlines(self): self.tar.extract("ustar/regtype", TEMPDIR) tarinfo = self.tar.getmember("ustar/regtype") with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1: lines1 = fobj1.readlines() with self.tar.extractfile(tarinfo) as fobj: fobj2 = io.TextIOWrapper(fobj) lines2 = fobj2.readlines() self.assertEqual(lines1, lines2, "fileobj.readlines() failed") self.assertEqual(len(lines2), 114, "fileobj.readlines() failed") self.assertEqual(lines2[83], "I will gladly admit that Python is not the fastest " "running scripting language.\n", "fileobj.readlines() failed") def test_fileobj_iter(self): self.tar.extract("ustar/regtype", TEMPDIR) tarinfo = self.tar.getmember("ustar/regtype") with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1: lines1 = fobj1.readlines() with self.tar.extractfile(tarinfo) as fobj2: lines2 = list(io.TextIOWrapper(fobj2)) self.assertEqual(lines1, lines2, "fileobj.__iter__() failed") def test_fileobj_seek(self): self.tar.extract("ustar/regtype", TEMPDIR) with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj: data = fobj.read() tarinfo = self.tar.getmember("ustar/regtype") fobj = self.tar.extractfile(tarinfo) text = fobj.read() fobj.seek(0) self.assertEqual(0, fobj.tell(), "seek() to file's start failed") fobj.seek(2048, 0) self.assertEqual(2048, fobj.tell(), "seek() to absolute position failed") fobj.seek(-1024, 1) self.assertEqual(1024, fobj.tell(), "seek() to negative relative position failed") fobj.seek(1024, 1) self.assertEqual(2048, fobj.tell(), "seek() to positive relative position failed") s = fobj.read(10) self.assertEqual(s, data[2048:2058], "read() after seek failed") fobj.seek(0, 2) self.assertEqual(tarinfo.size, fobj.tell(), "seek() to file's end failed") self.assertEqual(fobj.read(), b"", "read() at file's end did not return empty string") fobj.seek(-tarinfo.size, 2) self.assertEqual(0, fobj.tell(), "relative seek() to file's end failed") fobj.seek(512) s1 = fobj.readlines() fobj.seek(512) s2 = fobj.readlines() self.assertEqual(s1, s2, "readlines() after seek failed") fobj.seek(0) self.assertEqual(len(fobj.readline()), fobj.tell(), "tell() after readline() failed") fobj.seek(512) self.assertEqual(len(fobj.readline()) + 512, fobj.tell(), "tell() after seek() and readline() failed") fobj.seek(0) line = fobj.readline() self.assertEqual(fobj.read(), data[len(line):], "read() after readline() failed") fobj.close() def test_fileobj_text(self): with self.tar.extractfile("ustar/regtype") as fobj: fobj = io.TextIOWrapper(fobj) data = fobj.read().encode("iso8859-1") self.assertEqual(md5sum(data), md5_regtype) try: fobj.seek(100) except AttributeError: # Issue #13815: seek() complained about a missing # flush() method. self.fail("seeking failed in text mode") # Test if symbolic and hard links are resolved by extractfile(). The # test link members each point to a regular member whose data is # supposed to be exported. def _test_fileobj_link(self, lnktype, regtype): with self.tar.extractfile(lnktype) as a, \ self.tar.extractfile(regtype) as b: self.assertEqual(a.name, b.name) def test_fileobj_link1(self): self._test_fileobj_link("ustar/lnktype", "ustar/regtype") def test_fileobj_link2(self): self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype") def test_fileobj_symlink1(self): self._test_fileobj_link("ustar/symtype", "ustar/regtype") def test_fileobj_symlink2(self): self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype") def test_issue14160(self): self._test_fileobj_link("symtype2", "ustar/regtype") class GzipUstarReadTest(GzipTest, UstarReadTest): pass class Bz2UstarReadTest(Bz2Test, UstarReadTest): pass class LzmaUstarReadTest(LzmaTest, UstarReadTest): pass class ListTest(ReadTest, unittest.TestCase): # Override setUp to use default encoding (UTF-8) def setUp(self): self.tar = tarfile.open(self.tarname, mode=self.mode) def test_list(self): tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n') with support.swap_attr(sys, 'stdout', tio): self.tar.list(verbose=False) out = tio.detach().getvalue() self.assertIn(b'ustar/conttype', out) self.assertIn(b'ustar/regtype', out) self.assertIn(b'ustar/lnktype', out) self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out) self.assertIn(b'./ustar/linktest2/symtype', out) self.assertIn(b'./ustar/linktest2/lnktype', out) # Make sure it puts trailing slash for directory self.assertIn(b'ustar/dirtype/', out) self.assertIn(b'ustar/dirtype-with-size/', out) # Make sure it is able to print unencodable characters def conv(b): s = b.decode(self.tar.encoding, 'surrogateescape') return s.encode('ascii', 'backslashreplace') self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out) self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-' b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out) self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-' b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out) self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out) self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out) # Make sure it prints files separated by one newline without any # 'ls -l'-like accessories if verbose flag is not being used # ... # ustar/conttype # ustar/regtype # ... self.assertRegex(out, br'ustar/conttype ?\r?\n' br'ustar/regtype ?\r?\n') # Make sure it does not print the source of link without verbose flag self.assertNotIn(b'link to', out) self.assertNotIn(b'->', out) def test_list_verbose(self): tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n') with support.swap_attr(sys, 'stdout', tio): self.tar.list(verbose=True) out = tio.detach().getvalue() # Make sure it prints files separated by one newline with 'ls -l'-like # accessories if verbose flag is being used # ... # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype # ... self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 ' br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d ' br'ustar/\w+type ?\r?\n') * 2) # Make sure it prints the source of link with verbose flag self.assertIn(b'ustar/symtype -> regtype', out) self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out) self.assertIn(b'./ustar/linktest2/lnktype link to ' b'./ustar/linktest1/regtype', out) self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' + (b'/123' * 125) + b'/longname', out) self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' + (b'/123' * 125) + b'/longname', out) def test_list_members(self): tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n') def members(tar): for tarinfo in tar.getmembers(): if 'reg' in tarinfo.name: yield tarinfo with support.swap_attr(sys, 'stdout', tio): self.tar.list(verbose=False, members=members(self.tar)) out = tio.detach().getvalue() self.assertIn(b'ustar/regtype', out) self.assertNotIn(b'ustar/conttype', out) class GzipListTest(GzipTest, ListTest): pass class Bz2ListTest(Bz2Test, ListTest): pass class LzmaListTest(LzmaTest, ListTest): pass class CommonReadTest(ReadTest): def test_empty_tarfile(self): # Test for issue6123: Allow opening empty archives. # This test checks if tarfile.open() is able to open an empty tar # archive successfully. Note that an empty tar archive is not the # same as an empty file! with tarfile.open(tmpname, self.mode.replace("r", "w")): pass try: tar = tarfile.open(tmpname, self.mode) tar.getnames() except tarfile.ReadError: self.fail("tarfile.open() failed on empty archive") else: self.assertListEqual(tar.getmembers(), []) finally: tar.close() def test_non_existent_tarfile(self): # Test for issue11513: prevent non-existent gzipped tarfiles raising # multiple exceptions. with self.assertRaisesRegex(FileNotFoundError, "xxx"): tarfile.open("xxx", self.mode) def test_null_tarfile(self): # Test for issue6123: Allow opening empty archives. # This test guarantees that tarfile.open() does not treat an empty # file as an empty tar archive. with open(tmpname, "wb"): pass self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode) self.assertRaises(tarfile.ReadError, tarfile.open, tmpname) def test_ignore_zeros(self): # Test TarFile's ignore_zeros option. # generate 512 pseudorandom bytes data = Random(0).getrandbits(512*8).to_bytes(512, 'big') for char in (b'\0', b'a'): # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a') # are ignored correctly. with self.open(tmpname, "w") as fobj: fobj.write(char * 1024) tarinfo = tarfile.TarInfo("foo") tarinfo.size = len(data) fobj.write(tarinfo.tobuf()) fobj.write(data) tar = tarfile.open(tmpname, mode="r", ignore_zeros=True) try: self.assertListEqual(tar.getnames(), ["foo"], "ignore_zeros=True should have skipped the %r-blocks" % char) finally: tar.close() def test_premature_end_of_archive(self): for size in (512, 600, 1024, 1200): with tarfile.open(tmpname, "w:") as tar: t = tarfile.TarInfo("foo") t.size = 1024 tar.addfile(t, io.BytesIO(b"a" * 1024)) with open(tmpname, "r+b") as fobj: fobj.truncate(size) with tarfile.open(tmpname) as tar: with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"): for t in tar: pass with tarfile.open(tmpname) as tar: t = tar.next() with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"): tar.extract(t, TEMPDIR) with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"): tar.extractfile(t).read() class MiscReadTestBase(CommonReadTest): def requires_name_attribute(self): pass def test_no_name_argument(self): self.requires_name_attribute() with open(self.tarname, "rb") as fobj: self.assertIsInstance(fobj.name, str) with tarfile.open(fileobj=fobj, mode=self.mode) as tar: self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, os.path.abspath(fobj.name)) def test_no_name_attribute(self): with open(self.tarname, "rb") as fobj: data = fobj.read() fobj = io.BytesIO(data) self.assertRaises(AttributeError, getattr, fobj, "name") tar = tarfile.open(fileobj=fobj, mode=self.mode) self.assertIsNone(tar.name) def test_empty_name_attribute(self): with open(self.tarname, "rb") as fobj: data = fobj.read() fobj = io.BytesIO(data) fobj.name = "" with tarfile.open(fileobj=fobj, mode=self.mode) as tar: self.assertIsNone(tar.name) def test_int_name_attribute(self): # Issue 21044: tarfile.open() should handle fileobj with an integer # 'name' attribute. fd = os.open(self.tarname, os.O_RDONLY) with open(fd, 'rb') as fobj: self.assertIsInstance(fobj.name, int) with tarfile.open(fileobj=fobj, mode=self.mode) as tar: self.assertIsNone(tar.name) def test_bytes_name_attribute(self): self.requires_name_attribute() tarname = os.fsencode(self.tarname) with open(tarname, 'rb') as fobj: self.assertIsInstance(fobj.name, bytes) with tarfile.open(fileobj=fobj, mode=self.mode) as tar: self.assertIsInstance(tar.name, bytes) self.assertEqual(tar.name, os.path.abspath(fobj.name)) def test_pathlike_name(self): tarname = pathlib.Path(self.tarname) with tarfile.open(tarname, mode=self.mode) as tar: self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname))) with self.taropen(tarname) as tar: self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname))) with tarfile.TarFile.open(tarname, mode=self.mode) as tar: self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname))) if self.suffix == '': with tarfile.TarFile(tarname, mode='r') as tar: self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname))) def test_illegal_mode_arg(self): with open(tmpname, 'wb'): pass with self.assertRaisesRegex(ValueError, 'mode must be '): tar = self.taropen(tmpname, 'q') with self.assertRaisesRegex(ValueError, 'mode must be '): tar = self.taropen(tmpname, 'rw') with self.assertRaisesRegex(ValueError, 'mode must be '): tar = self.taropen(tmpname, '') def test_fileobj_with_offset(self): # Skip the first member and store values from the second member # of the testtar. tar = tarfile.open(self.tarname, mode=self.mode) try: tar.next() t = tar.next() name = t.name offset = t.offset with tar.extractfile(t) as f: data = f.read() finally: tar.close() # Open the testtar and seek to the offset of the second member. with self.open(self.tarname) as fobj: fobj.seek(offset) # Test if the tarfile starts with the second member. tar = tar.open(self.tarname, mode="r:", fileobj=fobj) t = tar.next() self.assertEqual(t.name, name) # Read to the end of fileobj and test if seeking back to the # beginning works. tar.getmembers() self.assertEqual(tar.extractfile(t).read(), data, "seek back did not work") tar.close() def test_fail_comp(self): # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file. self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode) with open(tarname, "rb") as fobj: self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode) def test_v7_dirtype(self): # Test old style dirtype member (bug #1336623): # Old V7 tars create directory members using an AREGTYPE # header with a "/" appended to the filename field. tarinfo = self.tar.getmember("misc/dirtype-old-v7") self.assertEqual(tarinfo.type, tarfile.DIRTYPE, "v7 dirtype failed") def test_xstar_type(self): # The xstar format stores extra atime and ctime fields inside the # space reserved for the prefix field. The prefix field must be # ignored in this case, otherwise it will mess up the name. try: self.tar.getmember("misc/regtype-xstar") except KeyError: self.fail("failed to find misc/regtype-xstar (mangled prefix?)") def test_check_members(self): for tarinfo in self.tar: self.assertEqual(int(tarinfo.mtime), 0o7606136617, "wrong mtime for %s" % tarinfo.name) if not tarinfo.name.startswith("ustar/"): continue self.assertEqual(tarinfo.uname, "tarfile", "wrong uname for %s" % tarinfo.name) def test_find_members(self): self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof", "could not find all members") @unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation") @support.skip_unless_symlink def test_extract_hardlink(self): # Test hardlink extraction (e.g. bug #857297). with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar: tar.extract("ustar/regtype", TEMPDIR) self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype")) tar.extract("ustar/lnktype", TEMPDIR) self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype")) with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f: data = f.read() self.assertEqual(md5sum(data), md5_regtype) tar.extract("ustar/symtype", TEMPDIR) self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype")) with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f: data = f.read() self.assertEqual(md5sum(data), md5_regtype) def test_extractall(self): # Test if extractall() correctly restores directory permissions # and times (see issue1735). tar = tarfile.open(tarname, encoding="iso8859-1") DIR = os.path.join(TEMPDIR, "extractall") os.mkdir(DIR) try: directories = [t for t in tar if t.isdir()] tar.extractall(DIR, directories) for tarinfo in directories: path = os.path.join(DIR, tarinfo.name) if sys.platform != "win32": # Win32 has no support for fine grained permissions. self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777) def format_mtime(mtime): if isinstance(mtime, float): return "{} ({})".format(mtime, mtime.hex()) else: return "{!r} (int)".format(mtime) file_mtime = os.path.getmtime(path) errmsg = "tar mtime {0} != file time {1} of path {2!a}".format( format_mtime(tarinfo.mtime), format_mtime(file_mtime), path) self.assertEqual(tarinfo.mtime, file_mtime, errmsg) finally: tar.close() support.rmtree(DIR) def test_extract_directory(self): dirtype = "ustar/dirtype" DIR = os.path.join(TEMPDIR, "extractdir") os.mkdir(DIR) try: with tarfile.open(tarname, encoding="iso8859-1") as tar: tarinfo = tar.getmember(dirtype) tar.extract(tarinfo, path=DIR) extracted = os.path.join(DIR, dirtype) self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime) if sys.platform != "win32": self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755) finally: support.rmtree(DIR) def test_extractall_pathlike_name(self): DIR = pathlib.Path(TEMPDIR) / "extractall" with support.temp_dir(DIR), \ tarfile.open(tarname, encoding="iso8859-1") as tar: directories = [t for t in tar if t.isdir()] tar.extractall(DIR, directories) for tarinfo in directories: path = DIR / tarinfo.name self.assertEqual(os.path.getmtime(path), tarinfo.mtime) def test_extract_pathlike_name(self): dirtype = "ustar/dirtype" DIR = pathlib.Path(TEMPDIR) / "extractall" with support.temp_dir(DIR), \ tarfile.open(tarname, encoding="iso8859-1") as tar: tarinfo = tar.getmember(dirtype) tar.extract(tarinfo, path=DIR) extracted = DIR / dirtype self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime) def test_init_close_fobj(self): # Issue #7341: Close the internal file object in the TarFile # constructor in case of an error. For the test we rely on # the fact that opening an empty file raises a ReadError. empty = os.path.join(TEMPDIR, "empty") with open(empty, "wb") as fobj: fobj.write(b"") try: tar = object.__new__(tarfile.TarFile) try: tar.__init__(empty) except tarfile.ReadError: self.assertTrue(tar.fileobj.closed) else: self.fail("ReadError not raised") finally: support.unlink(empty) def test_parallel_iteration(self): # Issue #16601: Restarting iteration over tarfile continued # from where it left off. with tarfile.open(self.tarname) as tar: for m1, m2 in zip(tar, tar): self.assertEqual(m1.offset, m2.offset) self.assertEqual(m1.get_info(), m2.get_info()) class MiscReadTest(MiscReadTestBase, unittest.TestCase): test_fail_comp = None class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase): pass class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase): def requires_name_attribute(self): self.skipTest("BZ2File have no name attribute") class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase): def requires_name_attribute(self): self.skipTest("LZMAFile have no name attribute") class StreamReadTest(CommonReadTest, unittest.TestCase): prefix="r|" def test_read_through(self): # Issue #11224: A poorly designed _FileInFile.read() method # caused seeking errors with stream tar files. for tarinfo in self.tar: if not tarinfo.isreg(): continue with self.tar.extractfile(tarinfo) as fobj: while True: try: buf = fobj.read(512) except tarfile.StreamError: self.fail("simple read-through using " "TarFile.extractfile() failed") if not buf: break def test_fileobj_regular_file(self): tarinfo = self.tar.next() # get "regtype" (can't use getmember) with self.tar.extractfile(tarinfo) as fobj: data = fobj.read() self.assertEqual(len(data), tarinfo.size, "regular file extraction failed") self.assertEqual(md5sum(data), md5_regtype, "regular file extraction failed") def test_provoke_stream_error(self): tarinfos = self.tar.getmembers() with self.tar.extractfile(tarinfos[0]) as f: # read the first member self.assertRaises(tarfile.StreamError, f.read) def test_compare_members(self): tar1 = tarfile.open(tarname, encoding="iso8859-1") try: tar2 = self.tar while True: t1 = tar1.next() t2 = tar2.next() if t1 is None: break self.assertIsNotNone(t2, "stream.next() failed.") if t2.islnk() or t2.issym(): with self.assertRaises(tarfile.StreamError): tar2.extractfile(t2) continue v1 = tar1.extractfile(t1) v2 = tar2.extractfile(t2) if v1 is None: continue self.assertIsNotNone(v2, "stream.extractfile() failed") self.assertEqual(v1.read(), v2.read(), "stream extraction failed") finally: tar1.close() class GzipStreamReadTest(GzipTest, StreamReadTest): pass class Bz2StreamReadTest(Bz2Test, StreamReadTest): pass class LzmaStreamReadTest(LzmaTest, StreamReadTest): pass class DetectReadTest(TarTest, unittest.TestCase): def _testfunc_file(self, name, mode): try: tar = tarfile.open(name, mode) except tarfile.ReadError as e: self.fail() else: tar.close() def _testfunc_fileobj(self, name, mode): try: with open(name, "rb") as f: tar = tarfile.open(name, mode, fileobj=f) except tarfile.ReadError as e: self.fail() else: tar.close() def _test_modes(self, testfunc): if self.suffix: with self.assertRaises(tarfile.ReadError): tarfile.open(tarname, mode="r:" + self.suffix) with self.assertRaises(tarfile.ReadError): tarfile.open(tarname, mode="r|" + self.suffix) with self.assertRaises(tarfile.ReadError): tarfile.open(self.tarname, mode="r:") with self.assertRaises(tarfile.ReadError): tarfile.open(self.tarname, mode="r|") testfunc(self.tarname, "r") testfunc(self.tarname, "r:" + self.suffix) testfunc(self.tarname, "r:*") testfunc(self.tarname, "r|" + self.suffix) testfunc(self.tarname, "r|*") def test_detect_file(self): self._test_modes(self._testfunc_file) def test_detect_fileobj(self): self._test_modes(self._testfunc_fileobj) class GzipDetectReadTest(GzipTest, DetectReadTest): pass class Bz2DetectReadTest(Bz2Test, DetectReadTest): def test_detect_stream_bz2(self): # Originally, tarfile's stream detection looked for the string # "BZh91" at the start of the file. This is incorrect because # the '9' represents the blocksize (900,000 bytes). If the file was # compressed using another blocksize autodetection fails. with open(tarname, "rb") as fobj: data = fobj.read() # Compress with blocksize 100,000 bytes, the file starts with "BZh11". with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj: fobj.write(data) self._testfunc_file(tmpname, "r|*") class LzmaDetectReadTest(LzmaTest, DetectReadTest): pass class MemberReadTest(ReadTest, unittest.TestCase): def _test_member(self, tarinfo, chksum=None, **kwargs): if chksum is not None: with self.tar.extractfile(tarinfo) as f: self.assertEqual(md5sum(f.read()), chksum, "wrong md5sum for %s" % tarinfo.name) kwargs["mtime"] = 0o7606136617 kwargs["uid"] = 1000 kwargs["gid"] = 100 if "old-v7" not in tarinfo.name: # V7 tar can't handle alphabetic owners. kwargs["uname"] = "tarfile" kwargs["gname"] = "tarfile" for k, v in kwargs.items(): self.assertEqual(getattr(tarinfo, k), v, "wrong value in %s field of %s" % (k, tarinfo.name)) def test_find_regtype(self): tarinfo = self.tar.getmember("ustar/regtype") self._test_member(tarinfo, size=7011, chksum=md5_regtype) def test_find_conttype(self): tarinfo = self.tar.getmember("ustar/conttype") self._test_member(tarinfo, size=7011, chksum=md5_regtype) def test_find_dirtype(self): tarinfo = self.tar.getmember("ustar/dirtype") self._test_member(tarinfo, size=0) def test_find_dirtype_with_size(self): tarinfo = self.tar.getmember("ustar/dirtype-with-size") self._test_member(tarinfo, size=255) def test_find_lnktype(self): tarinfo = self.tar.getmember("ustar/lnktype") self._test_member(tarinfo, size=0, linkname="ustar/regtype") def test_find_symtype(self): tarinfo = self.tar.getmember("ustar/symtype") self._test_member(tarinfo, size=0, linkname="regtype") def test_find_blktype(self): tarinfo = self.tar.getmember("ustar/blktype") self._test_member(tarinfo, size=0, devmajor=3, devminor=0) def test_find_chrtype(self): tarinfo = self.tar.getmember("ustar/chrtype") self._test_member(tarinfo, size=0, devmajor=1, devminor=3) def test_find_fifotype(self): tarinfo = self.tar.getmember("ustar/fifotype") self._test_member(tarinfo, size=0) def test_find_sparse(self): tarinfo = self.tar.getmember("ustar/sparse") self._test_member(tarinfo, size=86016, chksum=md5_sparse) def test_find_gnusparse(self): tarinfo = self.tar.getmember("gnu/sparse") self._test_member(tarinfo, size=86016, chksum=md5_sparse) def test_find_gnusparse_00(self):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_generator_stop.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_generator_stop.py
from __future__ import generator_stop import unittest class TestPEP479(unittest.TestCase): def test_stopiteration_wrapping(self): def f(): raise StopIteration def g(): yield f() with self.assertRaisesRegex(RuntimeError, "generator raised StopIteration"): next(g()) def test_stopiteration_wrapping_context(self): def f(): raise StopIteration def g(): yield f() try: next(g()) except RuntimeError as exc: self.assertIs(type(exc.__cause__), StopIteration) self.assertIs(type(exc.__context__), StopIteration) self.assertTrue(exc.__suppress_context__) else: self.fail('__cause__, __context__, or __suppress_context__ ' 'were not properly set') if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_wait3.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_wait3.py
"""This test checks for correct wait3() behavior. """ import os import time import unittest from test.fork_wait import ForkWait from test.support import reap_children if not hasattr(os, 'fork'): raise unittest.SkipTest("os.fork not defined") if not hasattr(os, 'wait3'): raise unittest.SkipTest("os.wait3 not defined") class Wait3Test(ForkWait): def wait_impl(self, cpid): # This many iterations can be required, since some previously run # tests (e.g. test_ctypes) could have spawned a lot of children # very quickly. deadline = time.monotonic() + 10.0 while time.monotonic() <= deadline: # wait3() 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, rusage = os.wait3(os.WNOHANG) if spid == cpid: break time.sleep(0.1) self.assertEqual(spid, cpid) self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) self.assertTrue(rusage) def tearDownModule(): reap_children() if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_netrc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_netrc.py
import netrc, os, unittest, sys, tempfile, textwrap from unittest import mock from test import support class NetrcTestCase(unittest.TestCase): def make_nrc(self, test_data): test_data = textwrap.dedent(test_data) mode = 'w' if sys.platform != 'cygwin': mode += 't' temp_fd, temp_filename = tempfile.mkstemp() with os.fdopen(temp_fd, mode=mode) as fp: fp.write(test_data) self.addCleanup(os.unlink, temp_filename) return netrc.netrc(temp_filename) def test_default(self): nrc = self.make_nrc("""\ machine host1.domain.com login log1 password pass1 account acct1 default login log2 password pass2 """) self.assertEqual(nrc.hosts['host1.domain.com'], ('log1', 'acct1', 'pass1')) self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2')) nrc2 = self.make_nrc(nrc.__repr__()) self.assertEqual(nrc.hosts, nrc2.hosts) def test_macros(self): nrc = self.make_nrc("""\ macdef macro1 line1 line2 macdef macro2 line3 line4 """) self.assertEqual(nrc.macros, {'macro1': ['line1\n', 'line2\n'], 'macro2': ['line3\n', 'line4\n']}) def _test_passwords(self, nrc, passwd): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['host.domain.com'], ('log', 'acct', passwd)) def test_password_with_leading_hash(self): self._test_passwords("""\ machine host.domain.com login log password #pass account acct """, '#pass') def test_password_with_trailing_hash(self): self._test_passwords("""\ machine host.domain.com login log password pass# account acct """, 'pass#') def test_password_with_internal_hash(self): self._test_passwords("""\ machine host.domain.com login log password pa#ss account acct """, 'pa#ss') def _test_comment(self, nrc, passwd='pass'): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, passwd)) self.assertEqual(nrc.hosts['bar.domain.com'], ('foo', None, 'pass')) def test_comment_before_machine_line(self): self._test_comment("""\ # comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_no_space(self): self._test_comment("""\ #comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_hash_only(self): self._test_comment("""\ # machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line(self): self._test_comment("""\ machine foo.domain.com login bar password pass # comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_no_space(self): self._test_comment("""\ machine foo.domain.com login bar password pass #comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_pass_has_hash(self): self._test_comment("""\ machine foo.domain.com login bar password #pass #comment machine bar.domain.com login foo password pass """, '#pass') @unittest.skipUnless(os.name == 'posix', 'POSIX only test') def test_security(self): # This test is incomplete since we are normally not run as root and # therefore can't test the file ownership being wrong. d = support.TESTFN os.mkdir(d) self.addCleanup(support.rmtree, d) fn = os.path.join(d, '.netrc') with open(fn, 'wt') as f: f.write("""\ machine foo.domain.com login bar password pass default login foo password pass """) with support.EnvironmentVarGuard() as environ: environ.set('HOME', d) os.chmod(fn, 0o600) nrc = netrc.netrc() self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, 'pass')) os.chmod(fn, 0o622) self.assertRaises(netrc.NetrcParseError, netrc.netrc) def test_file_not_found_in_home(self): d = support.TESTFN os.mkdir(d) self.addCleanup(support.rmtree, d) with support.EnvironmentVarGuard() as environ: environ.set('HOME', d) self.assertRaises(FileNotFoundError, netrc.netrc) def test_file_not_found_explicit(self): self.assertRaises(FileNotFoundError, netrc.netrc, file='unlikely_netrc') def test_home_not_set(self): fake_home = support.TESTFN os.mkdir(fake_home) self.addCleanup(support.rmtree, fake_home) fake_netrc_path = os.path.join(fake_home, '.netrc') with open(fake_netrc_path, 'w') as f: f.write('machine foo.domain.com login bar password pass') os.chmod(fake_netrc_path, 0o600) orig_expanduser = os.path.expanduser called = [] def fake_expanduser(s): called.append(s) with support.EnvironmentVarGuard() as environ: environ.set('HOME', fake_home) result = orig_expanduser(s) return result with support.swap_attr(os.path, 'expanduser', fake_expanduser): nrc = netrc.netrc() login, account, password = nrc.authenticators('foo.domain.com') self.assertEqual(login, 'bar') self.assertTrue(called) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/outstanding_bugs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/outstanding_bugs.py
# # This file is for everybody to add tests for bugs that aren't # fixed yet. Please add a test case and appropriate bug description. # # When you fix one of the bugs, please move the test to the correct # test_ module. # import unittest from test import support # # No test cases for outstanding bugs at the moment. # if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gettext.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gettext.py
import os import base64 import gettext import locale import unittest from test import support # TODO: # - Add new tests, for example for "dgettext" # - Remove dummy tests, for example testing for single and double quotes # has no sense, it would have if we were testing a parser (i.e. pygettext) # - Tests should have only one assert. GNU_MO_DATA = b'''\ 3hIElQAAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== ''' # This data contains an invalid major version number (5) # An unexpected major version number should be treated as an error when # parsing a .mo file GNU_MO_DATA_BAD_MAJOR_VERSION = b'''\ 3hIElQAABQAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== ''' # This data contains an invalid minor version number (7) # An unexpected minor version number only indicates that some of the file's # contents may not be able to be read. It does not indicate an error. GNU_MO_DATA_BAD_MINOR_VERSION = b'''\ 3hIElQcAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== ''' UMO_DATA = b'''\ 3hIElQAAAAACAAAAHAAAACwAAAAFAAAAPAAAAAAAAABQAAAABAAAAFEAAAAPAQAAVgAAAAQAAABm AQAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAYWLDngBQcm9qZWN0LUlkLVZlcnNpb246IDIuMApQTy1S ZXZpc2lvbi1EYXRlOiAyMDAzLTA0LTExIDEyOjQyLTA0MDAKTGFzdC1UcmFuc2xhdG9yOiBCYXJy eSBBLiBXQXJzYXcgPGJhcnJ5QHB5dGhvbi5vcmc+Ckxhbmd1YWdlLVRlYW06IFhYIDxweXRob24t ZGV2QHB5dGhvbi5vcmc+Ck1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFp bjsgY2hhcnNldD11dGYtOApDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiA3Yml0CkdlbmVyYXRl ZC1CeTogbWFudWFsbHkKAMKkeXoA ''' MMO_DATA = b'''\ 3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6 NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA= ''' LOCALEDIR = os.path.join('xx', 'LC_MESSAGES') MOFILE = os.path.join(LOCALEDIR, 'gettext.mo') MOFILE_BAD_MAJOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_major_version.mo') MOFILE_BAD_MINOR_VERSION = os.path.join(LOCALEDIR, 'gettext_bad_minor_version.mo') UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo') MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo') class GettextBaseTest(unittest.TestCase): def setUp(self): if not os.path.isdir(LOCALEDIR): os.makedirs(LOCALEDIR) with open(MOFILE, 'wb') as fp: fp.write(base64.decodebytes(GNU_MO_DATA)) with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp: fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION)) with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp: fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION)) with open(UMOFILE, 'wb') as fp: fp.write(base64.decodebytes(UMO_DATA)) with open(MMOFILE, 'wb') as fp: fp.write(base64.decodebytes(MMO_DATA)) self.env = support.EnvironmentVarGuard() self.env['LANGUAGE'] = 'xx' gettext._translations.clear() def tearDown(self): self.env.__exit__() del self.env support.rmtree(os.path.split(LOCALEDIR)[0]) GNU_MO_DATA_ISSUE_17898 = b'''\ 3hIElQAAAAABAAAAHAAAACQAAAAAAAAAAAAAAAAAAAAsAAAAggAAAC0AAAAAUGx1cmFsLUZvcm1z OiBucGx1cmFscz0yOyBwbHVyYWw9KG4gIT0gMSk7CiMtIy0jLSMtIyAgbWVzc2FnZXMucG8gKEVk WCBTdHVkaW8pICAjLSMtIy0jLSMKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PVVU Ri04CgA= ''' class GettextTestCase1(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir self.mofile = MOFILE gettext.install('gettext', self.localedir) def test_some_translations(self): eq = self.assertEqual # test some translations eq(_('albatross'), 'albatross') eq(_('mullusk'), 'bacon') eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') eq(_(r'nudge nudge'), 'wink wink') def test_double_quotes(self): eq = self.assertEqual # double quotes eq(_("albatross"), 'albatross') eq(_("mullusk"), 'bacon') eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') eq(_(r"nudge nudge"), 'wink wink') def test_triple_single_quotes(self): eq = self.assertEqual # triple single quotes eq(_('''albatross'''), 'albatross') eq(_('''mullusk'''), 'bacon') eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') eq(_(r'''nudge nudge'''), 'wink wink') def test_triple_double_quotes(self): eq = self.assertEqual # triple double quotes eq(_("""albatross"""), 'albatross') eq(_("""mullusk"""), 'bacon') eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') eq(_(r"""nudge nudge"""), 'wink wink') def test_multiline_strings(self): eq = self.assertEqual # multiline strings eq(_('''This module provides internationalization and localization support for your Python programs by providing an interface to the GNU gettext message catalog library.'''), '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH trggrkg zrffntr pngnybt yvoenel.''') def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install() eq(_('mullusk'), 'bacon') # Test installation of other methods import builtins t.install(names=["gettext", "lgettext"]) eq(_, t.gettext) eq(builtins.gettext, t.gettext) eq(lgettext, t.lgettext) del builtins.gettext del builtins.lgettext class GettextTestCase2(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir # Set up the bindings gettext.bindtextdomain('gettext', self.localedir) gettext.textdomain('gettext') # For convenience self._ = gettext.gettext def test_bindtextdomain(self): self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir) def test_textdomain(self): self.assertEqual(gettext.textdomain(), 'gettext') def test_bad_major_version(self): with open(MOFILE_BAD_MAJOR_VERSION, 'rb') as fp: with self.assertRaises(OSError) as cm: gettext.GNUTranslations(fp) exception = cm.exception self.assertEqual(exception.errno, 0) self.assertEqual(exception.strerror, "Bad version number 5") self.assertEqual(exception.filename, MOFILE_BAD_MAJOR_VERSION) def test_bad_minor_version(self): with open(MOFILE_BAD_MINOR_VERSION, 'rb') as fp: # Check that no error is thrown with a bad minor version number gettext.GNUTranslations(fp) def test_some_translations(self): eq = self.assertEqual # test some translations eq(self._('albatross'), 'albatross') eq(self._('mullusk'), 'bacon') eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') eq(self._(r'nudge nudge'), 'wink wink') def test_double_quotes(self): eq = self.assertEqual # double quotes eq(self._("albatross"), 'albatross') eq(self._("mullusk"), 'bacon') eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') eq(self._(r"nudge nudge"), 'wink wink') def test_triple_single_quotes(self): eq = self.assertEqual # triple single quotes eq(self._('''albatross'''), 'albatross') eq(self._('''mullusk'''), 'bacon') eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') eq(self._(r'''nudge nudge'''), 'wink wink') def test_triple_double_quotes(self): eq = self.assertEqual # triple double quotes eq(self._("""albatross"""), 'albatross') eq(self._("""mullusk"""), 'bacon') eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') eq(self._(r"""nudge nudge"""), 'wink wink') def test_multiline_strings(self): eq = self.assertEqual # multiline strings eq(self._('''This module provides internationalization and localization support for your Python programs by providing an interface to the GNU gettext message catalog library.'''), '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH trggrkg zrffntr pngnybt yvoenel.''') class PluralFormsTestCase(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.mofile = MOFILE def test_plural_forms1(self): eq = self.assertEqual x = gettext.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = gettext.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros') def test_plural_forms2(self): eq = self.assertEqual with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) x = t.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = t.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros') # Examples from http://www.gnu.org/software/gettext/manual/gettext.html def test_ja(self): eq = self.assertEqual f = gettext.c2py('0') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") def test_de(self): eq = self.assertEqual f = gettext.c2py('n != 1') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") def test_fr(self): eq = self.assertEqual f = gettext.c2py('n>1') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") def test_lv(self): eq = self.assertEqual f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111111111111111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111111111111110111111111011111111101111111110111111111011111111101111111110111111111011111111") def test_gd(self): eq = self.assertEqual f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_gd2(self): eq = self.assertEqual # Tests the combination of parentheses and "?:" f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_ro(self): eq = self.assertEqual f = gettext.c2py('n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "10111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_lt(self): eq = self.assertEqual f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111") def test_ru(self): eq = self.assertEqual f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222") def test_cs(self): eq = self.assertEqual f = gettext.c2py('(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_pl(self): eq = self.assertEqual f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222") def test_sl(self): eq = self.assertEqual f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333") def test_ar(self): eq = self.assertEqual f = gettext.c2py('n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "01233333333444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445553333333344444444444444444444444444444444444444444444444444444444444444444444444444444444444444444") def test_security(self): raises = self.assertRaises # Test for a dangerous expression raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)") # issue28563 raises(ValueError, gettext.c2py, '"(eval(foo) && ""') raises(ValueError, gettext.c2py, 'f"{os.system(\'sh\')}"') # Maximum recursion depth exceeded during compilation raises(ValueError, gettext.c2py, 'n+'*10000 + 'n') self.assertEqual(gettext.c2py('n+'*100 + 'n')(1), 101) # MemoryError during compilation raises(ValueError, gettext.c2py, '('*100 + 'n' + ')'*100) # Maximum recursion depth exceeded in C to Python translator raises(ValueError, gettext.c2py, '('*10000 + 'n' + ')'*10000) self.assertEqual(gettext.c2py('('*20 + 'n' + ')'*20)(1), 1) def test_chained_comparison(self): # C doesn't chain comparison as Python so 2 == 2 == 2 gets different results f = gettext.c2py('n == n == n') self.assertEqual(''.join(str(f(x)) for x in range(3)), '010') f = gettext.c2py('1 < n == n') self.assertEqual(''.join(str(f(x)) for x in range(3)), '100') f = gettext.c2py('n == n < 2') self.assertEqual(''.join(str(f(x)) for x in range(3)), '010') f = gettext.c2py('0 < n < 2') self.assertEqual(''.join(str(f(x)) for x in range(3)), '111') def test_decimal_number(self): self.assertEqual(gettext.c2py('0123')(1), 123) def test_invalid_syntax(self): invalid_expressions = [ 'x>1', '(n>1', 'n>1)', '42**42**42', '0xa', '1.0', '1e2', 'n>0x1', '+n', '-n', 'n()', 'n(1)', '1+', 'nn', 'n n', ] for expr in invalid_expressions: with self.assertRaises(ValueError): gettext.c2py(expr) def test_nested_condition_operator(self): self.assertEqual(gettext.c2py('n?1?2:3:4')(0), 4) self.assertEqual(gettext.c2py('n?1?2:3:4')(1), 2) self.assertEqual(gettext.c2py('n?1:3?4:5')(0), 4) self.assertEqual(gettext.c2py('n?1:3?4:5')(1), 1) def test_division(self): f = gettext.c2py('2/n*3') self.assertEqual(f(1), 6) self.assertEqual(f(2), 3) self.assertEqual(f(3), 0) self.assertEqual(f(-1), -6) self.assertRaises(ZeroDivisionError, f, 0) def test_plural_number(self): f = gettext.c2py('n != 1') self.assertEqual(f(1), 0) self.assertEqual(f(2), 1) with self.assertWarns(DeprecationWarning): self.assertEqual(f(1.0), 0) with self.assertWarns(DeprecationWarning): self.assertEqual(f(2.0), 1) with self.assertWarns(DeprecationWarning): self.assertEqual(f(1.1), 1) self.assertRaises(TypeError, f, '2') self.assertRaises(TypeError, f, b'2') self.assertRaises(TypeError, f, []) self.assertRaises(TypeError, f, object()) class LGettextTestCase(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.mofile = MOFILE def test_lgettext(self): lgettext = gettext.lgettext ldgettext = gettext.ldgettext self.assertEqual(lgettext('mullusk'), b'bacon') self.assertEqual(lgettext('spam'), b'spam') self.assertEqual(ldgettext('gettext', 'mullusk'), b'bacon') self.assertEqual(ldgettext('gettext', 'spam'), b'spam') def test_lgettext_2(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lgettext = t.lgettext self.assertEqual(lgettext('mullusk'), b'bacon') self.assertEqual(lgettext('spam'), b'spam') def test_lgettext_bind_textdomain_codeset(self): lgettext = gettext.lgettext ldgettext = gettext.ldgettext saved_codeset = gettext.bind_textdomain_codeset('gettext') try: gettext.bind_textdomain_codeset('gettext', 'utf-16') self.assertEqual(lgettext('mullusk'), 'bacon'.encode('utf-16')) self.assertEqual(lgettext('spam'), 'spam'.encode('utf-16')) self.assertEqual(ldgettext('gettext', 'mullusk'), 'bacon'.encode('utf-16')) self.assertEqual(ldgettext('gettext', 'spam'), 'spam'.encode('utf-16')) finally: del gettext._localecodesets['gettext'] gettext.bind_textdomain_codeset('gettext', saved_codeset) def test_lgettext_output_encoding(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lgettext = t.lgettext t.set_output_charset('utf-16') self.assertEqual(lgettext('mullusk'), 'bacon'.encode('utf-16')) self.assertEqual(lgettext('spam'), 'spam'.encode('utf-16')) def test_lngettext(self): lngettext = gettext.lngettext ldngettext = gettext.ldngettext x = lngettext('There is %s file', 'There are %s files', 1) self.assertEqual(x, b'Hay %s fichero') x = lngettext('There is %s file', 'There are %s files', 2) self.assertEqual(x, b'Hay %s ficheros') x = lngettext('There is %s directory', 'There are %s directories', 1) self.assertEqual(x, b'There is %s directory') x = lngettext('There is %s directory', 'There are %s directories', 2) self.assertEqual(x, b'There are %s directories') x = ldngettext('gettext', 'There is %s file', 'There are %s files', 1) self.assertEqual(x, b'Hay %s fichero') x = ldngettext('gettext', 'There is %s file', 'There are %s files', 2) self.assertEqual(x, b'Hay %s ficheros') x = ldngettext('gettext', 'There is %s directory', 'There are %s directories', 1) self.assertEqual(x, b'There is %s directory') x = ldngettext('gettext', 'There is %s directory', 'There are %s directories', 2) self.assertEqual(x, b'There are %s directories') def test_lngettext_2(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lngettext = t.lngettext x = lngettext('There is %s file', 'There are %s files', 1) self.assertEqual(x, b'Hay %s fichero') x = lngettext('There is %s file', 'There are %s files', 2) self.assertEqual(x, b'Hay %s ficheros') x = lngettext('There is %s directory', 'There are %s directories', 1) self.assertEqual(x, b'There is %s directory') x = lngettext('There is %s directory', 'There are %s directories', 2) self.assertEqual(x, b'There are %s directories') def test_lngettext_bind_textdomain_codeset(self): lngettext = gettext.lngettext ldngettext = gettext.ldngettext saved_codeset = gettext.bind_textdomain_codeset('gettext') try: gettext.bind_textdomain_codeset('gettext', 'utf-16') x = lngettext('There is %s file', 'There are %s files', 1) self.assertEqual(x, 'Hay %s fichero'.encode('utf-16')) x = lngettext('There is %s file', 'There are %s files', 2) self.assertEqual(x, 'Hay %s ficheros'.encode('utf-16')) x = lngettext('There is %s directory', 'There are %s directories', 1) self.assertEqual(x, 'There is %s directory'.encode('utf-16')) x = lngettext('There is %s directory', 'There are %s directories', 2) self.assertEqual(x, 'There are %s directories'.encode('utf-16')) x = ldngettext('gettext', 'There is %s file', 'There are %s files', 1) self.assertEqual(x, 'Hay %s fichero'.encode('utf-16')) x = ldngettext('gettext', 'There is %s file', 'There are %s files', 2) self.assertEqual(x, 'Hay %s ficheros'.encode('utf-16')) x = ldngettext('gettext', 'There is %s directory', 'There are %s directories', 1) self.assertEqual(x, 'There is %s directory'.encode('utf-16')) x = ldngettext('gettext', 'There is %s directory', 'There are %s directories', 2) self.assertEqual(x, 'There are %s directories'.encode('utf-16')) finally: del gettext._localecodesets['gettext'] gettext.bind_textdomain_codeset('gettext', saved_codeset) def test_lngettext_output_encoding(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lngettext = t.lngettext t.set_output_charset('utf-16') x = lngettext('There is %s file', 'There are %s files', 1) self.assertEqual(x, 'Hay %s fichero'.encode('utf-16')) x = lngettext('There is %s file', 'There are %s files', 2) self.assertEqual(x, 'Hay %s ficheros'.encode('utf-16')) x = lngettext('There is %s directory', 'There are %s directories', 1) self.assertEqual(x, 'There is %s directory'.encode('utf-16')) x = lngettext('There is %s directory', 'There are %s directories', 2) self.assertEqual(x, 'There are %s directories'.encode('utf-16')) class GNUTranslationParsingTest(GettextBaseTest): def test_plural_form_error_issue17898(self): with open(MOFILE, 'wb') as fp: fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898)) with open(MOFILE, 'rb') as fp: # If this runs cleanly, the bug is fixed. t = gettext.GNUTranslations(fp) class UnicodeTranslationsTest(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) with open(UMOFILE, 'rb') as fp: self.t = gettext.GNUTranslations(fp) self._ = self.t.gettext def test_unicode_msgid(self): self.assertIsInstance(self._(''), str) def test_unicode_msgstr(self): self.assertEqual(self._('ab\xde'), '\xa4yz') class WeirdMetadataTest(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) with open(MMOFILE, 'rb') as fp: try: self.t = gettext.GNUTranslations(fp) except: self.tearDown() raise def test_weird_metadata(self): info = self.t.info() self.assertEqual(len(info), 9) self.assertEqual(info['last-translator'], 'John Doe <jdoe@example.com>\nJane Foobar <jfoobar@example.com>') class DummyGNUTranslations(gettext.GNUTranslations): def foo(self): return 'foo' class GettextCacheTestCase(GettextBaseTest): def test_cache(self): self.localedir = os.curdir self.mofile = MOFILE self.assertEqual(len(gettext._translations), 0) t = gettext.translation('gettext', self.localedir) self.assertEqual(len(gettext._translations), 1) t = gettext.translation('gettext', self.localedir, class_=DummyGNUTranslations) self.assertEqual(len(gettext._translations), 2) self.assertEqual(t.__class__, DummyGNUTranslations) # Calling it again doesn't add to the cache t = gettext.translation('gettext', self.localedir, class_=DummyGNUTranslations) self.assertEqual(len(gettext._translations), 2) self.assertEqual(t.__class__, DummyGNUTranslations) class MiscTestCase(unittest.TestCase): def test__all__(self): blacklist = {'c2py', 'ENOENT'} support.check__all__(self, gettext, blacklist=blacklist) def test_main(): support.run_unittest(__name__) if __name__ == '__main__': test_main() # For reference, here's the .po file used to created the GNU_MO_DATA above. # # The original version was automatically generated from the sources with # pygettext. Later it was manually modified to add plural forms support. b''' # Dummy translation for the Python test_gettext.py module. # Copyright (C) 2001 Python Software Foundation # Barry Warsaw <barry@python.org>, 2000. # msgid "" msgstr "" "Project-Id-Version: 2.0\n" "PO-Revision-Date: 2003-04-11 14:32-0400\n" "Last-Translator: J. David Ibanez <j-david@noos.fr>\n" "Language-Team: XX <python-dev@python.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-1\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: pygettext.py 1.1\n" "Plural-Forms: nplurals=2; plural=n!=1;\n" #: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37 #: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92 #: test_gettext.py:98 msgid "nudge nudge" msgstr "wink wink" #: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34 #: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95 msgid "albatross" msgstr "" #: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36 #: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97 msgid "Raymond Luxury Yach-t" msgstr "Throatwobbler Mangrove" #: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35 #: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90 #: test_gettext.py:96 msgid "mullusk" msgstr "bacon" #: test_gettext.py:40 test_gettext.py:101 msgid "" "This module provides internationalization and localization\n" "support for your Python programs by providing an interface to the GNU\n" "gettext message catalog library." msgstr "" "Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n" "fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n" "trggrkg zrffntr pngnybt yvoenel." # Manually added, as neither pygettext nor xgettext support plural forms # in Python. msgid "There is %s file" msgid_plural "There are %s files" msgstr[0] "Hay %s fichero" msgstr[1] "Hay %s ficheros" ''' # Here's the second example po file example, used to generate the UMO_DATA # containing utf-8 encoded Unicode strings b''' # Dummy translation for the Python test_gettext.py module. # Copyright (C) 2001 Python Software Foundation # Barry Warsaw <barry@python.org>, 2000. #
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_embed.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_embed.py
# Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs) from test import support import unittest from collections import namedtuple import json import os import re import subprocess import sys import textwrap MS_WINDOWS = (os.name == 'nt') class EmbeddingTestsMixin: def setUp(self): here = os.path.abspath(__file__) basepath = os.path.dirname(os.path.dirname(os.path.dirname(here))) exename = "_testembed" if MS_WINDOWS: ext = ("_d" if "_d" in sys.executable else "") + ".exe" exename += ext exepath = os.path.dirname(sys.executable) else: exepath = os.path.join(basepath, "Programs") self.test_exe = exe = os.path.join(exepath, exename) if not os.path.exists(exe): self.skipTest("%r doesn't exist" % exe) # This is needed otherwise we get a fatal error: # "Py_Initialize: Unable to get the locale encoding # LookupError: no codec search functions registered: can't find encoding" self.oldcwd = os.getcwd() os.chdir(basepath) def tearDown(self): os.chdir(self.oldcwd) def run_embedded_interpreter(self, *args, env=None): """Runs a test in the embedded interpreter""" cmd = [self.test_exe] cmd.extend(args) if env is not None and MS_WINDOWS: # Windows requires at least the SYSTEMROOT environment variable to # start Python. env = env.copy() env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, env=env) (out, err) = p.communicate() if p.returncode != 0 and support.verbose: print(f"--- {cmd} failed ---") print(f"stdout:\n{out}") print(f"stderr:\n{err}") print(f"------") self.assertEqual(p.returncode, 0, "bad returncode %d, stderr is %r" % (p.returncode, err)) return out, err def run_repeated_init_and_subinterpreters(self): out, err = self.run_embedded_interpreter("repeated_init_and_subinterpreters") self.assertEqual(err, "") # The output from _testembed looks like this: # --- Pass 0 --- # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728 # --- Pass 1 --- # ... interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, " r"thread state <(0x[\dA-F]+)>: " r"id\(modules\) = ([\d]+)$") Interp = namedtuple("Interp", "id interp tstate modules") numloops = 0 current_run = [] for line in out.splitlines(): if line == "--- Pass {} ---".format(numloops): self.assertEqual(len(current_run), 0) if support.verbose > 1: print(line) numloops += 1 continue self.assertLess(len(current_run), 5) match = re.match(interp_pat, line) if match is None: self.assertRegex(line, interp_pat) # Parse the line from the loop. The first line is the main # interpreter and the 3 afterward are subinterpreters. interp = Interp(*match.groups()) if support.verbose > 1: print(interp) self.assertTrue(interp.interp) self.assertTrue(interp.tstate) self.assertTrue(interp.modules) current_run.append(interp) # The last line in the loop should be the same as the first. if len(current_run) == 5: main = current_run[0] self.assertEqual(interp, main) yield current_run current_run = [] class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase): def test_subinterps_main(self): for run in self.run_repeated_init_and_subinterpreters(): main = run[0] self.assertEqual(main.id, '0') def test_subinterps_different_ids(self): for run in self.run_repeated_init_and_subinterpreters(): main, *subs, _ = run mainid = int(main.id) for i, sub in enumerate(subs): self.assertEqual(sub.id, str(mainid + i + 1)) def test_subinterps_distinct_state(self): for run in self.run_repeated_init_and_subinterpreters(): main, *subs, _ = run if '0x0' in main: # XXX Fix on Windows (and other platforms): something # is going on with the pointers in Programs/_testembed.c. # interp.interp is 0x0 and interp.modules is the same # between interpreters. raise unittest.SkipTest('platform prints pointers as 0x0') for sub in subs: # A new subinterpreter may have the same # PyInterpreterState pointer as a previous one if # the earlier one has already been destroyed. So # we compare with the main interpreter. The same # applies to tstate. self.assertNotEqual(sub.interp, main.interp) self.assertNotEqual(sub.tstate, main.tstate) self.assertNotEqual(sub.modules, main.modules) def test_forced_io_encoding(self): # Checks forced configuration of embedded interpreter IO streams env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape") out, err = self.run_embedded_interpreter("forced_io_encoding", env=env) if support.verbose > 1: print() print(out) print(err) expected_stream_encoding = "utf-8" expected_errors = "surrogateescape" expected_output = '\n'.join([ "--- Use defaults ---", "Expected encoding: default", "Expected errors: default", "stdin: {in_encoding}:{errors}", "stdout: {out_encoding}:{errors}", "stderr: {out_encoding}:backslashreplace", "--- Set errors only ---", "Expected encoding: default", "Expected errors: ignore", "stdin: {in_encoding}:ignore", "stdout: {out_encoding}:ignore", "stderr: {out_encoding}:backslashreplace", "--- Set encoding only ---", "Expected encoding: latin-1", "Expected errors: default", "stdin: latin-1:{errors}", "stdout: latin-1:{errors}", "stderr: latin-1:backslashreplace", "--- Set encoding and errors ---", "Expected encoding: latin-1", "Expected errors: replace", "stdin: latin-1:replace", "stdout: latin-1:replace", "stderr: latin-1:backslashreplace"]) expected_output = expected_output.format( in_encoding=expected_stream_encoding, out_encoding=expected_stream_encoding, errors=expected_errors) # This is useful if we ever trip over odd platform behaviour self.maxDiff = None self.assertEqual(out.strip(), expected_output) def test_pre_initialization_api(self): """ Checks some key parts of the C-API that need to work before the runtine is initialized (via Py_Initialize()). """ env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path)) out, err = self.run_embedded_interpreter("pre_initialization_api", env=env) if MS_WINDOWS: expected_path = self.test_exe else: expected_path = os.path.join(os.getcwd(), "spam") expected_output = f"sys.executable: {expected_path}\n" self.assertIn(expected_output, out) self.assertEqual(err, '') def test_pre_initialization_sys_options(self): """ Checks that sys.warnoptions and sys._xoptions can be set before the runtime is initialized (otherwise they won't be effective). """ env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path)) out, err = self.run_embedded_interpreter( "pre_initialization_sys_options", env=env) expected_output = ( "sys.warnoptions: ['once', 'module', 'default']\n" "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n" "warnings.filters[:3]: ['default', 'module', 'once']\n" ) self.assertIn(expected_output, out) self.assertEqual(err, '') def test_bpo20891(self): """ bpo-20891: Calling PyGILState_Ensure in a non-Python thread before calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must call PyEval_InitThreads() for us in this case. """ out, err = self.run_embedded_interpreter("bpo20891") self.assertEqual(out, '') self.assertEqual(err, '') def test_initialize_twice(self): """ bpo-33932: Calling Py_Initialize() twice should do nothing (and not crash!). """ out, err = self.run_embedded_interpreter("initialize_twice") self.assertEqual(out, '') self.assertEqual(err, '') def test_initialize_pymain(self): """ bpo-34008: Calling Py_Main() after Py_Initialize() must not fail. """ out, err = self.run_embedded_interpreter("initialize_pymain") self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']") self.assertEqual(err, '') class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): maxDiff = 4096 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape') # core config UNTESTED_CORE_CONFIG = ( # FIXME: untested core configuration variables 'dll_path', 'executable', 'module_search_paths', ) # Mark config which should be get by get_default_config() GET_DEFAULT_CONFIG = object() DEFAULT_CORE_CONFIG = { 'install_signal_handlers': 1, 'ignore_environment': 0, 'use_hash_seed': 0, 'hash_seed': 0, 'allocator': None, 'dev_mode': 0, 'faulthandler': 0, 'tracemalloc': 0, 'import_time': 0, 'show_ref_count': 0, 'show_alloc_count': 0, 'dump_refs': 0, 'malloc_stats': 0, 'utf8_mode': 0, 'coerce_c_locale': 0, 'coerce_c_locale_warn': 0, 'program_name': './_testembed', 'argv': [], 'program': None, 'xoptions': [], 'warnoptions': [], 'module_search_path_env': None, 'home': None, 'prefix': GET_DEFAULT_CONFIG, 'base_prefix': GET_DEFAULT_CONFIG, 'exec_prefix': GET_DEFAULT_CONFIG, 'base_exec_prefix': GET_DEFAULT_CONFIG, '_disable_importlib': 0, } # main config UNTESTED_MAIN_CONFIG = ( # FIXME: untested main configuration variables 'module_search_path', ) COPY_MAIN_CONFIG = ( # Copy core config to main config for expected values 'argv', 'base_exec_prefix', 'base_prefix', 'exec_prefix', 'executable', 'install_signal_handlers', 'prefix', 'warnoptions', # xoptions is created from core_config in check_main_config() ) # global config UNTESTED_GLOBAL_CONFIG = ( # Py_HasFileSystemDefaultEncoding value depends on the LC_CTYPE locale # and the platform. It is complex to test it, and it's value doesn't # really matter. 'Py_HasFileSystemDefaultEncoding', ) DEFAULT_GLOBAL_CONFIG = { 'Py_BytesWarningFlag': 0, 'Py_DebugFlag': 0, 'Py_DontWriteBytecodeFlag': 0, 'Py_FileSystemDefaultEncodeErrors': GET_DEFAULT_CONFIG, 'Py_FileSystemDefaultEncoding': GET_DEFAULT_CONFIG, 'Py_FrozenFlag': 0, 'Py_HashRandomizationFlag': 1, 'Py_InspectFlag': 0, 'Py_InteractiveFlag': 0, 'Py_IsolatedFlag': 0, 'Py_NoSiteFlag': 0, 'Py_NoUserSiteDirectory': 0, 'Py_OptimizeFlag': 0, 'Py_QuietFlag': 0, 'Py_UnbufferedStdioFlag': 0, 'Py_VerboseFlag': 0, } if MS_WINDOWS: DEFAULT_GLOBAL_CONFIG.update({ 'Py_LegacyWindowsFSEncodingFlag': 0, 'Py_LegacyWindowsStdioFlag': 0, }) COPY_GLOBAL_CONFIG = [ # Copy core config to global config for expected values # True means that the core config value is inverted (0 => 1 and 1 => 0) ('Py_IgnoreEnvironmentFlag', 'ignore_environment'), ('Py_UTF8Mode', 'utf8_mode'), ] def main_xoptions(self, xoptions_list): xoptions = {} for opt in xoptions_list: if '=' in opt: key, value = opt.split('=', 1) xoptions[key] = value else: xoptions[opt] = True return xoptions def check_main_config(self, config): core_config = config['core_config'] main_config = config['main_config'] # main config for key in self.UNTESTED_MAIN_CONFIG: del main_config[key] expected = {} for key in self.COPY_MAIN_CONFIG: expected[key] = core_config[key] expected['xoptions'] = self.main_xoptions(core_config['xoptions']) self.assertEqual(main_config, expected) def get_expected_config(self, expected_core, expected_global, env): expected_core = dict(self.DEFAULT_CORE_CONFIG, **expected_core) expected_global = dict(self.DEFAULT_GLOBAL_CONFIG, **expected_global) code = textwrap.dedent(''' import json import sys data = { 'prefix': sys.prefix, 'base_prefix': sys.base_prefix, 'exec_prefix': sys.exec_prefix, 'base_exec_prefix': sys.base_exec_prefix, 'Py_FileSystemDefaultEncoding': sys.getfilesystemencoding(), 'Py_FileSystemDefaultEncodeErrors': sys.getfilesystemencodeerrors(), } data = json.dumps(data) data = data.encode('utf-8') sys.stdout.buffer.write(data) sys.stdout.buffer.flush() ''') # Use -S to not import the site module: get the proper configuration # when test_embed is run from a venv (bpo-35313) args = (sys.executable, '-S', '-c', code) env = dict(env) if not expected_global['Py_IsolatedFlag']: env['PYTHONCOERCECLOCALE'] = '0' env['PYTHONUTF8'] = '0' proc = subprocess.run(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if proc.returncode: raise Exception(f"failed to get the default config: " f"stdout={proc.stdout!r} stderr={proc.stderr!r}") stdout = proc.stdout.decode('utf-8') config = json.loads(stdout) for key, value in expected_core.items(): if value is self.GET_DEFAULT_CONFIG: expected_core[key] = config[key] for key, value in expected_global.items(): if value is self.GET_DEFAULT_CONFIG: expected_global[key] = config[key] return (expected_core, expected_global) def check_core_config(self, config, expected): core_config = dict(config['core_config']) for key in self.UNTESTED_CORE_CONFIG: core_config.pop(key, None) self.assertEqual(core_config, expected) def check_global_config(self, config, expected, env): core_config = config['core_config'] for item in self.COPY_GLOBAL_CONFIG: if len(item) == 3: global_key, core_key, opposite = item expected[global_key] = 0 if core_config[core_key] else 1 else: global_key, core_key = item expected[global_key] = core_config[core_key] global_config = dict(config['global_config']) for key in self.UNTESTED_GLOBAL_CONFIG: del global_config[key] self.assertEqual(global_config, expected) def check_config(self, testname, expected_core, expected_global): env = dict(os.environ) # Remove PYTHON* environment variables to get deterministic environment for key in list(env): if key.startswith('PYTHON'): del env[key] # Disable C locale coercion and UTF-8 mode to not depend # on the current locale env['PYTHONCOERCECLOCALE'] = '0' env['PYTHONUTF8'] = '0' out, err = self.run_embedded_interpreter(testname, env=env) # Ignore err config = json.loads(out) expected_core, expected_global = self.get_expected_config(expected_core, expected_global, env) self.check_core_config(config, expected_core) self.check_main_config(config) self.check_global_config(config, expected_global, env) def test_init_default_config(self): self.check_config("init_default_config", {}, {}) def test_init_global_config(self): core_config = { 'program_name': './globalvar', 'utf8_mode': 1, } global_config = { 'Py_BytesWarningFlag': 1, 'Py_DontWriteBytecodeFlag': 1, 'Py_FileSystemDefaultEncodeErrors': self.UTF8_MODE_ERRORS, 'Py_FileSystemDefaultEncoding': 'utf-8', 'Py_InspectFlag': 1, 'Py_InteractiveFlag': 1, 'Py_NoSiteFlag': 1, 'Py_NoUserSiteDirectory': 1, 'Py_OptimizeFlag': 2, 'Py_QuietFlag': 1, 'Py_VerboseFlag': 1, 'Py_FrozenFlag': 1, 'Py_UnbufferedStdioFlag': 1, } self.check_config("init_global_config", core_config, global_config) def test_init_from_config(self): core_config = { 'install_signal_handlers': 0, 'use_hash_seed': 1, 'hash_seed': 123, 'allocator': 'malloc_debug', 'tracemalloc': 2, 'import_time': 1, 'show_ref_count': 1, 'show_alloc_count': 1, 'malloc_stats': 1, 'utf8_mode': 1, 'program_name': './conf_program_name', 'argv': ['-c', 'pass'], 'program': 'conf_program', 'xoptions': ['core_xoption1=3', 'core_xoption2=', 'core_xoption3'], 'warnoptions': ['default', 'error::ResourceWarning'], 'faulthandler': 1, } global_config = { 'Py_FileSystemDefaultEncodeErrors': self.UTF8_MODE_ERRORS, 'Py_FileSystemDefaultEncoding': 'utf-8', 'Py_NoUserSiteDirectory': 0, } self.check_config("init_from_config", core_config, global_config) def test_init_env(self): core_config = { 'use_hash_seed': 1, 'hash_seed': 42, 'allocator': 'malloc_debug', 'tracemalloc': 2, 'import_time': 1, 'malloc_stats': 1, 'utf8_mode': 1, 'faulthandler': 1, 'dev_mode': 1, } global_config = { 'Py_DontWriteBytecodeFlag': 1, 'Py_FileSystemDefaultEncodeErrors': self.UTF8_MODE_ERRORS, 'Py_FileSystemDefaultEncoding': 'utf-8', 'Py_InspectFlag': 1, 'Py_NoUserSiteDirectory': 1, 'Py_OptimizeFlag': 2, 'Py_UnbufferedStdioFlag': 1, 'Py_VerboseFlag': 1, } self.check_config("init_env", core_config, global_config) def test_init_dev_mode(self): core_config = { 'dev_mode': 1, 'faulthandler': 1, 'allocator': 'debug', } self.check_config("init_dev_mode", core_config, {}) def test_init_isolated(self): core_config = { 'ignore_environment': 1, } global_config = { 'Py_IsolatedFlag': 1, 'Py_NoUserSiteDirectory': 1, } self.check_config("init_isolated", core_config, global_config) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_utf8source.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_utf8source.py
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest class PEP3120Test(unittest.TestCase): def test_pep3120(self): self.assertEqual( "Питон".encode("utf-8"), b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( "\П".encode("utf-8"), b'\\\xd0\x9f' ) def test_badsyntax(self): try: import test.badsyntax_pep3120 except SyntaxError as msg: msg = str(msg).lower() self.assertTrue('utf-8' in msg) else: self.fail("expected exception didn't occur") class BuiltinCompileTests(unittest.TestCase): # Issue 3574. def test_latin1(self): # Allow compile() to read Latin-1 source. source_code = '# coding: Latin-1\nu = "Ç"\n'.encode("Latin-1") try: code = compile(source_code, '<dummy>', 'exec') except SyntaxError: self.fail("compile() cannot handle Latin-1 source") ns = {} exec(code, ns) self.assertEqual('Ç', ns['u']) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false