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/test_mimetypes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_mimetypes.py
import io import locale import mimetypes import pathlib import sys import unittest from test import support # Tell it we don't know about external files: mimetypes.knownfiles = [] mimetypes.inited = False mimetypes._default_mime_types() class MimeTypesTestCase(unittest.TestCase): def setUp(self): self.db = mimetypes.MimeTypes() def test_default_data(self): eq = self.assertEqual eq(self.db.guess_type("foo.html"), ("text/html", None)) eq(self.db.guess_type("foo.tgz"), ("application/x-tar", "gzip")) eq(self.db.guess_type("foo.tar.gz"), ("application/x-tar", "gzip")) eq(self.db.guess_type("foo.tar.Z"), ("application/x-tar", "compress")) eq(self.db.guess_type("foo.tar.bz2"), ("application/x-tar", "bzip2")) eq(self.db.guess_type("foo.tar.xz"), ("application/x-tar", "xz")) def test_data_urls(self): eq = self.assertEqual guess_type = self.db.guess_type eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None)) eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None)) eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None)) def test_file_parsing(self): eq = self.assertEqual sio = io.StringIO("x-application/x-unittest pyunit\n") self.db.readfp(sio) eq(self.db.guess_type("foo.pyunit"), ("x-application/x-unittest", None)) eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit") def test_non_standard_types(self): eq = self.assertEqual # First try strict eq(self.db.guess_type('foo.xul', strict=True), (None, None)) eq(self.db.guess_extension('image/jpg', strict=True), None) # And then non-strict eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None)) eq(self.db.guess_extension('image/jpg', strict=False), '.jpg') def test_filename_with_url_delimiters(self): # bpo-38449: URL delimiters cases should be handled also. # They would have different mime types if interpreted as URL as # compared to when interpreted as filename because of the semicolon. eq = self.assertEqual gzip_expected = ('application/x-tar', 'gzip') eq(self.db.guess_type(";1.tar.gz"), gzip_expected) eq(self.db.guess_type("?1.tar.gz"), gzip_expected) eq(self.db.guess_type("#1.tar.gz"), gzip_expected) eq(self.db.guess_type("#1#.tar.gz"), gzip_expected) eq(self.db.guess_type(";1#.tar.gz"), gzip_expected) eq(self.db.guess_type(";&1=123;?.tar.gz"), gzip_expected) eq(self.db.guess_type("?k1=v1&k2=v2.tar.gz"), gzip_expected) eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected) def test_guess_all_types(self): eq = self.assertEqual unless = self.assertTrue # First try strict. Use a set here for testing the results because if # test_urllib2 is run before test_mimetypes, global state is modified # such that the 'all' set will have more items in it. all = set(self.db.guess_all_extensions('text/plain', strict=True)) unless(all >= set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt'])) # And now non-strict all = self.db.guess_all_extensions('image/jpg', strict=False) all.sort() eq(all, ['.jpg']) # And now for no hits all = self.db.guess_all_extensions('image/jpg', strict=True) eq(all, []) def test_encoding(self): getpreferredencoding = locale.getpreferredencoding self.addCleanup(setattr, locale, 'getpreferredencoding', getpreferredencoding) locale.getpreferredencoding = lambda: 'ascii' filename = support.findfile("mime.types") mimes = mimetypes.MimeTypes([filename]) exts = mimes.guess_all_extensions('application/vnd.geocube+xml', strict=True) self.assertEqual(exts, ['.g3', '.g\xb3']) def test_init_reinitializes(self): # Issue 4936: make sure an init starts clean # First, put some poison into the types table mimetypes.add_type('foo/bar', '.foobar') self.assertEqual(mimetypes.guess_extension('foo/bar'), '.foobar') # Reinitialize mimetypes.init() # Poison should be gone. self.assertEqual(mimetypes.guess_extension('foo/bar'), None) def test_preferred_extension(self): def check_extensions(): self.assertEqual(mimetypes.guess_extension('application/octet-stream'), '.bin') self.assertEqual(mimetypes.guess_extension('application/postscript'), '.ps') self.assertEqual(mimetypes.guess_extension('application/vnd.apple.mpegurl'), '.m3u') self.assertEqual(mimetypes.guess_extension('application/vnd.ms-excel'), '.xls') self.assertEqual(mimetypes.guess_extension('application/vnd.ms-powerpoint'), '.ppt') self.assertEqual(mimetypes.guess_extension('application/x-texinfo'), '.texi') self.assertEqual(mimetypes.guess_extension('application/x-troff'), '.roff') self.assertEqual(mimetypes.guess_extension('application/xml'), '.xsl') self.assertEqual(mimetypes.guess_extension('audio/mpeg'), '.mp3') self.assertEqual(mimetypes.guess_extension('image/jpeg'), '.jpg') self.assertEqual(mimetypes.guess_extension('image/tiff'), '.tiff') self.assertEqual(mimetypes.guess_extension('message/rfc822'), '.eml') self.assertEqual(mimetypes.guess_extension('text/html'), '.html') self.assertEqual(mimetypes.guess_extension('text/plain'), '.txt') self.assertEqual(mimetypes.guess_extension('video/mpeg'), '.mpeg') self.assertEqual(mimetypes.guess_extension('video/quicktime'), '.mov') check_extensions() mimetypes.init() check_extensions() def test_init_stability(self): mimetypes.init() suffix_map = mimetypes.suffix_map encodings_map = mimetypes.encodings_map types_map = mimetypes.types_map common_types = mimetypes.common_types mimetypes.init() self.assertIsNot(suffix_map, mimetypes.suffix_map) self.assertIsNot(encodings_map, mimetypes.encodings_map) self.assertIsNot(types_map, mimetypes.types_map) self.assertIsNot(common_types, mimetypes.common_types) self.assertEqual(suffix_map, mimetypes.suffix_map) self.assertEqual(encodings_map, mimetypes.encodings_map) self.assertEqual(types_map, mimetypes.types_map) self.assertEqual(common_types, mimetypes.common_types) def test_path_like_ob(self): filename = "LICENSE.txt" filepath = pathlib.Path(filename) filepath_with_abs_dir = pathlib.Path('/dir/'+filename) filepath_relative = pathlib.Path('../dir/'+filename) path_dir = pathlib.Path('./') expected = self.db.guess_type(filename) self.assertEqual(self.db.guess_type(filepath), expected) self.assertEqual(self.db.guess_type( filepath_with_abs_dir), expected) self.assertEqual(self.db.guess_type(filepath_relative), expected) self.assertEqual(self.db.guess_type(path_dir), (None, None)) def test_keywords_args_api(self): self.assertEqual(self.db.guess_type( url="foo.html", strict=True), ("text/html", None)) self.assertEqual(self.db.guess_all_extensions( type='image/jpg', strict=True), []) self.assertEqual(self.db.guess_extension( type='image/jpg', strict=False), '.jpg') @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") class Win32MimeTypesTestCase(unittest.TestCase): def setUp(self): # ensure all entries actually come from the Windows registry self.original_types_map = mimetypes.types_map.copy() mimetypes.types_map.clear() mimetypes.init() self.db = mimetypes.MimeTypes() def tearDown(self): # restore default settings mimetypes.types_map.clear() mimetypes.types_map.update(self.original_types_map) def test_registry_parsing(self): # the original, minimum contents of the MIME database in the # Windows registry is undocumented AFAIK. # Use file types that should *always* exist: eq = self.assertEqual eq(self.db.guess_type("foo.txt"), ("text/plain", None)) eq(self.db.guess_type("image.jpg"), ("image/jpeg", None)) eq(self.db.guess_type("image.png"), ("image/png", None)) class MiscTestCase(unittest.TestCase): def test__all__(self): support.check__all__(self, mimetypes) 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_unicode_file.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_unicode_file.py
# Test some Unicode file name semantics # We don't test many operations on files other than # that their names can be used with Unicode characters. import os, glob, time, shutil import unicodedata import unittest from test.support import (run_unittest, rmtree, change_cwd, TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNENCODABLE, create_empty_file) if not os.path.supports_unicode_filenames: try: TESTFN_UNICODE.encode(TESTFN_ENCODING) except (UnicodeError, TypeError): # Either the file system encoding is None, or the file name # cannot be encoded in the file system encoding. raise unittest.SkipTest("No Unicode filesystem semantics on this platform.") def remove_if_exists(filename): if os.path.exists(filename): os.unlink(filename) class TestUnicodeFiles(unittest.TestCase): # The 'do_' functions are the actual tests. They generally assume the # file already exists etc. # Do all the tests we can given only a single filename. The file should # exist. def _do_single(self, filename): self.assertTrue(os.path.exists(filename)) self.assertTrue(os.path.isfile(filename)) self.assertTrue(os.access(filename, os.R_OK)) self.assertTrue(os.path.exists(os.path.abspath(filename))) self.assertTrue(os.path.isfile(os.path.abspath(filename))) self.assertTrue(os.access(os.path.abspath(filename), os.R_OK)) os.chmod(filename, 0o777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename self._do_copyish(filename, filename) # Filename should appear in glob output self.assertTrue( os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0])) # basename should appear in listdir. path, base = os.path.split(os.path.abspath(filename)) file_list = os.listdir(path) # Normalize the unicode strings, as round-tripping the name via the OS # may return a different (but equivalent) value. base = unicodedata.normalize("NFD", base) file_list = [unicodedata.normalize("NFD", f) for f in file_list] self.assertIn(base, file_list) # Tests that copy, move, etc one file to another. def _do_copyish(self, filename1, filename2): # Should be able to rename the file using either name. self.assertTrue(os.path.isfile(filename1)) # must exist. os.rename(filename1, filename2 + ".new") self.assertFalse(os.path.isfile(filename2)) self.assertTrue(os.path.isfile(filename1 + '.new')) os.rename(filename1 + ".new", filename2) self.assertFalse(os.path.isfile(filename1 + '.new')) self.assertTrue(os.path.isfile(filename2)) shutil.copy(filename1, filename2 + ".new") os.unlink(filename1 + ".new") # remove using equiv name. # And a couple of moves, one using each name. shutil.move(filename1, filename2 + ".new") self.assertFalse(os.path.exists(filename2)) self.assertTrue(os.path.exists(filename1 + '.new')) shutil.move(filename1 + ".new", filename2) self.assertFalse(os.path.exists(filename2 + '.new')) self.assertTrue(os.path.exists(filename1)) # Note - due to the implementation of shutil.move, # it tries a rename first. This only fails on Windows when on # different file systems - and this test can't ensure that. # So we test the shutil.copy2 function, which is the thing most # likely to fail. shutil.copy2(filename1, filename2 + ".new") self.assertTrue(os.path.isfile(filename1 + '.new')) os.unlink(filename1 + ".new") self.assertFalse(os.path.exists(filename2 + '.new')) def _do_directory(self, make_name, chdir_name): if os.path.isdir(make_name): rmtree(make_name) os.mkdir(make_name) try: with change_cwd(chdir_name): cwd_result = os.getcwd() name_result = make_name cwd_result = unicodedata.normalize("NFD", cwd_result) name_result = unicodedata.normalize("NFD", name_result) self.assertEqual(os.path.basename(cwd_result),name_result) finally: os.rmdir(make_name) # The '_test' functions 'entry points with params' - ie, what the # top-level 'test' functions would be if they could take params def _test_single(self, filename): remove_if_exists(filename) create_empty_file(filename) try: self._do_single(filename) finally: os.unlink(filename) self.assertTrue(not os.path.exists(filename)) # and again with os.open. f = os.open(filename, os.O_CREAT) os.close(f) try: self._do_single(filename) finally: os.unlink(filename) # The 'test' functions are unittest entry points, and simply call our # _test functions with each of the filename combinations we wish to test def test_single_files(self): self._test_single(TESTFN_UNICODE) if TESTFN_UNENCODABLE is not None: self._test_single(TESTFN_UNENCODABLE) def test_directories(self): # For all 'equivalent' combinations: # Make dir with encoded, chdir with unicode, checkdir with encoded # (or unicode/encoded/unicode, etc ext = ".dir" self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext) # Our directory name that can't use a non-unicode name. if TESTFN_UNENCODABLE is not None: self._do_directory(TESTFN_UNENCODABLE+ext, TESTFN_UNENCODABLE+ext) def test_main(): run_unittest(__name__) 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_dis.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dis.py
# Minimal tests for dis module from test.support import captured_stdout from test.bytecode_helper import BytecodeTestCase import unittest import sys import dis import io import re import types import contextlib def get_tb(): def _error(): try: 1 / 0 except Exception as e: tb = e.__traceback__ return tb tb = _error() while tb.tb_next: tb = tb.tb_next return tb TRACEBACK_CODE = get_tb().tb_frame.f_code class _C: def __init__(self, x): self.x = x == 1 @staticmethod def sm(x): x = x == 1 @classmethod def cm(cls, x): cls.x = x == 1 dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % (_C.__init__.__code__.co_firstlineno + 1,) dis_c_instance_method_bytes = """\ 0 LOAD_FAST 1 (1) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (0) 8 STORE_ATTR 0 (0) 10 LOAD_CONST 0 (0) 12 RETURN_VALUE """ dis_c_class_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (cls) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % (_C.cm.__code__.co_firstlineno + 2,) dis_c_static_method = """\ %3d 0 LOAD_FAST 0 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 STORE_FAST 0 (x) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE """ % (_C.sm.__code__.co_firstlineno + 2,) # Class disassembling info has an extra newline at end. dis_c = """\ Disassembly of %s: %s Disassembly of %s: %s Disassembly of %s: %s """ % (_C.__init__.__name__, dis_c_instance_method, _C.cm.__name__, dis_c_class_method, _C.sm.__name__, dis_c_static_method) def _f(a): print(a) return 1 dis_f = """\ %3d 0 LOAD_GLOBAL 0 (print) 2 LOAD_FAST 0 (a) 4 CALL_FUNCTION 1 6 POP_TOP %3d 8 LOAD_CONST 1 (1) 10 RETURN_VALUE """ % (_f.__code__.co_firstlineno + 1, _f.__code__.co_firstlineno + 2) dis_f_co_code = """\ 0 LOAD_GLOBAL 0 (0) 2 LOAD_FAST 0 (0) 4 CALL_FUNCTION 1 6 POP_TOP 8 LOAD_CONST 1 (1) 10 RETURN_VALUE """ def bug708901(): for res in range(1, 10): pass dis_bug708901 = """\ %3d 0 SETUP_LOOP 18 (to 20) 2 LOAD_GLOBAL 0 (range) 4 LOAD_CONST 1 (1) %3d 6 LOAD_CONST 2 (10) 8 CALL_FUNCTION 2 10 GET_ITER >> 12 FOR_ITER 4 (to 18) 14 STORE_FAST 0 (res) %3d 16 JUMP_ABSOLUTE 12 >> 18 POP_BLOCK >> 20 LOAD_CONST 0 (None) 22 RETURN_VALUE """ % (bug708901.__code__.co_firstlineno + 1, bug708901.__code__.co_firstlineno + 2, bug708901.__code__.co_firstlineno + 3) def bug1333982(x=[]): assert 0, ([s for s in x] + 1) pass dis_bug1333982 = """\ %3d 0 LOAD_CONST 1 (0) 2 POP_JUMP_IF_TRUE 26 4 LOAD_GLOBAL 0 (AssertionError) 6 LOAD_CONST 2 (<code object <listcomp> at 0x..., file "%s", line %d>) 8 LOAD_CONST 3 ('bug1333982.<locals>.<listcomp>') 10 MAKE_FUNCTION 0 12 LOAD_FAST 0 (x) 14 GET_ITER 16 CALL_FUNCTION 1 %3d 18 LOAD_CONST 4 (1) 20 BINARY_ADD 22 CALL_FUNCTION 1 24 RAISE_VARARGS 1 %3d >> 26 LOAD_CONST 0 (None) 28 RETURN_VALUE """ % (bug1333982.__code__.co_firstlineno + 1, __file__, bug1333982.__code__.co_firstlineno + 1, bug1333982.__code__.co_firstlineno + 2, bug1333982.__code__.co_firstlineno + 3) _BIG_LINENO_FORMAT = """\ %3d 0 LOAD_GLOBAL 0 (spam) 2 POP_TOP 4 LOAD_CONST 0 (None) 6 RETURN_VALUE """ _BIG_LINENO_FORMAT2 = """\ %4d 0 LOAD_GLOBAL 0 (spam) 2 POP_TOP 4 LOAD_CONST 0 (None) 6 RETURN_VALUE """ dis_module_expected_results = """\ Disassembly of f: 4 0 LOAD_CONST 0 (None) 2 RETURN_VALUE Disassembly of g: 5 0 LOAD_CONST 0 (None) 2 RETURN_VALUE """ expr_str = "x + 1" dis_expr_str = """\ 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (1) 4 BINARY_ADD 6 RETURN_VALUE """ simple_stmt_str = "x = x + 1" dis_simple_stmt_str = """\ 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (1) 4 BINARY_ADD 6 STORE_NAME 0 (x) 8 LOAD_CONST 1 (None) 10 RETURN_VALUE """ annot_stmt_str = """\ x: int = 1 y: fun(1) lst[fun(0)]: int = 1 """ # leading newline is for a reason (tests lineno) dis_annot_stmt_str = """\ 2 0 SETUP_ANNOTATIONS 2 LOAD_CONST 0 (1) 4 STORE_NAME 0 (x) 6 LOAD_NAME 1 (int) 8 LOAD_NAME 2 (__annotations__) 10 LOAD_CONST 1 ('x') 12 STORE_SUBSCR 3 14 LOAD_NAME 3 (fun) 16 LOAD_CONST 0 (1) 18 CALL_FUNCTION 1 20 LOAD_NAME 2 (__annotations__) 22 LOAD_CONST 2 ('y') 24 STORE_SUBSCR 4 26 LOAD_CONST 0 (1) 28 LOAD_NAME 4 (lst) 30 LOAD_NAME 3 (fun) 32 LOAD_CONST 3 (0) 34 CALL_FUNCTION 1 36 STORE_SUBSCR 38 LOAD_NAME 1 (int) 40 POP_TOP 42 LOAD_CONST 4 (None) 44 RETURN_VALUE """ compound_stmt_str = """\ x = 0 while 1: x += 1""" # Trailing newline has been deliberately omitted dis_compound_stmt_str = """\ 1 0 LOAD_CONST 0 (0) 2 STORE_NAME 0 (x) 2 4 SETUP_LOOP 12 (to 18) 3 >> 6 LOAD_NAME 0 (x) 8 LOAD_CONST 1 (1) 10 INPLACE_ADD 12 STORE_NAME 0 (x) 14 JUMP_ABSOLUTE 6 16 POP_BLOCK >> 18 LOAD_CONST 2 (None) 20 RETURN_VALUE """ dis_traceback = """\ %3d 0 SETUP_EXCEPT 12 (to 14) %3d 2 LOAD_CONST 1 (1) 4 LOAD_CONST 2 (0) --> 6 BINARY_TRUE_DIVIDE 8 POP_TOP 10 POP_BLOCK 12 JUMP_FORWARD 40 (to 54) %3d >> 14 DUP_TOP 16 LOAD_GLOBAL 0 (Exception) 18 COMPARE_OP 10 (exception match) 20 POP_JUMP_IF_FALSE 52 22 POP_TOP 24 STORE_FAST 0 (e) 26 POP_TOP 28 SETUP_FINALLY 10 (to 40) %3d 30 LOAD_FAST 0 (e) 32 LOAD_ATTR 1 (__traceback__) 34 STORE_FAST 1 (tb) 36 POP_BLOCK 38 LOAD_CONST 0 (None) >> 40 LOAD_CONST 0 (None) 42 STORE_FAST 0 (e) 44 DELETE_FAST 0 (e) 46 END_FINALLY 48 POP_EXCEPT 50 JUMP_FORWARD 2 (to 54) >> 52 END_FINALLY %3d >> 54 LOAD_FAST 1 (tb) 56 RETURN_VALUE """ % (TRACEBACK_CODE.co_firstlineno + 1, TRACEBACK_CODE.co_firstlineno + 2, TRACEBACK_CODE.co_firstlineno + 3, TRACEBACK_CODE.co_firstlineno + 4, TRACEBACK_CODE.co_firstlineno + 5) def _fstring(a, b, c, d): return f'{a} {b:4} {c!r} {d!r:4}' dis_fstring = """\ %3d 0 LOAD_FAST 0 (a) 2 FORMAT_VALUE 0 4 LOAD_CONST 1 (' ') 6 LOAD_FAST 1 (b) 8 LOAD_CONST 2 ('4') 10 FORMAT_VALUE 4 (with format) 12 LOAD_CONST 1 (' ') 14 LOAD_FAST 2 (c) 16 FORMAT_VALUE 2 (repr) 18 LOAD_CONST 1 (' ') 20 LOAD_FAST 3 (d) 22 LOAD_CONST 2 ('4') 24 FORMAT_VALUE 6 (repr, with format) 26 BUILD_STRING 7 28 RETURN_VALUE """ % (_fstring.__code__.co_firstlineno + 1,) def _g(x): yield x async def _ag(x): yield x async def _co(x): async for item in _ag(x): pass def _h(y): def foo(x): '''funcdoc''' return [x + z for z in y] return foo dis_nested_0 = """\ %3d 0 LOAD_CLOSURE 0 (y) 2 BUILD_TUPLE 1 4 LOAD_CONST 1 (<code object foo at 0x..., file "%s", line %d>) 6 LOAD_CONST 2 ('_h.<locals>.foo') 8 MAKE_FUNCTION 8 10 STORE_FAST 1 (foo) %3d 12 LOAD_FAST 1 (foo) 14 RETURN_VALUE """ % (_h.__code__.co_firstlineno + 1, __file__, _h.__code__.co_firstlineno + 1, _h.__code__.co_firstlineno + 4, ) dis_nested_1 = """%s Disassembly of <code object foo at 0x..., file "%s", line %d>: %3d 0 LOAD_CLOSURE 0 (x) 2 BUILD_TUPLE 1 4 LOAD_CONST 1 (<code object <listcomp> at 0x..., file "%s", line %d>) 6 LOAD_CONST 2 ('_h.<locals>.foo.<locals>.<listcomp>') 8 MAKE_FUNCTION 8 10 LOAD_DEREF 1 (y) 12 GET_ITER 14 CALL_FUNCTION 1 16 RETURN_VALUE """ % (dis_nested_0, __file__, _h.__code__.co_firstlineno + 1, _h.__code__.co_firstlineno + 3, __file__, _h.__code__.co_firstlineno + 3, ) dis_nested_2 = """%s Disassembly of <code object <listcomp> at 0x..., file "%s", line %d>: %3d 0 BUILD_LIST 0 2 LOAD_FAST 0 (.0) >> 4 FOR_ITER 12 (to 18) 6 STORE_FAST 1 (z) 8 LOAD_DEREF 0 (x) 10 LOAD_FAST 1 (z) 12 BINARY_ADD 14 LIST_APPEND 2 16 JUMP_ABSOLUTE 4 >> 18 RETURN_VALUE """ % (dis_nested_1, __file__, _h.__code__.co_firstlineno + 3, _h.__code__.co_firstlineno + 3, ) class DisTests(unittest.TestCase): maxDiff = None def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): # We want to test the default printing behaviour, not the file arg output = io.StringIO() with contextlib.redirect_stdout(output): if wrapper: dis.dis(func, **kwargs) else: dis.disassemble(func, lasti, **kwargs) return output.getvalue() def get_disassemble_as_string(self, func, lasti=-1): return self.get_disassembly(func, lasti, False) def strip_addresses(self, text): return re.sub(r'\b0x[0-9A-Fa-f]+\b', '0x...', text) def do_disassembly_test(self, func, expected): got = self.get_disassembly(func, depth=0) if got != expected: got = self.strip_addresses(got) self.assertEqual(got, expected) def test_opmap(self): self.assertEqual(dis.opmap["NOP"], 9) self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst) self.assertIn(dis.opmap["STORE_NAME"], dis.hasname) def test_opname(self): self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") def test_boundaries(self): self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG) self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT) def test_widths(self): for opcode, opname in enumerate(dis.opname): if opname in ('BUILD_MAP_UNPACK_WITH_CALL', 'BUILD_TUPLE_UNPACK_WITH_CALL'): continue with self.subTest(opname=opname): width = dis._OPNAME_WIDTH if opcode < dis.HAVE_ARGUMENT: width += 1 + dis._OPARG_WIDTH self.assertLessEqual(len(opname), width) def test_dis(self): self.do_disassembly_test(_f, dis_f) def test_bug_708901(self): self.do_disassembly_test(bug708901, dis_bug708901) def test_bug_1333982(self): # This one is checking bytecodes generated for an `assert` statement, # so fails if the tests are run with -O. Skip this test then. if not __debug__: self.skipTest('need asserts, run without -O') self.do_disassembly_test(bug1333982, dis_bug1333982) def test_big_linenos(self): def func(count): namespace = {} func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"]) exec(func, namespace) return namespace['foo'] # Test all small ranges for i in range(1, 300): expected = _BIG_LINENO_FORMAT % (i + 2) self.do_disassembly_test(func(i), expected) # Test some larger ranges too for i in range(300, 1000, 10): expected = _BIG_LINENO_FORMAT % (i + 2) self.do_disassembly_test(func(i), expected) for i in range(1000, 5000, 10): expected = _BIG_LINENO_FORMAT2 % (i + 2) self.do_disassembly_test(func(i), expected) from test import dis_module self.do_disassembly_test(dis_module, dis_module_expected_results) def test_big_offsets(self): def func(count): namespace = {} func = "def foo(x):\n " + ";".join(["x = x + 1"] * count) + "\n return x" exec(func, namespace) return namespace['foo'] def expected(count, w): s = ['''\ %*d LOAD_FAST 0 (x) %*d LOAD_CONST 1 (1) %*d BINARY_ADD %*d STORE_FAST 0 (x) ''' % (w, 8*i, w, 8*i + 2, w, 8*i + 4, w, 8*i + 6) for i in range(count)] s += ['''\ 3 %*d LOAD_FAST 0 (x) %*d RETURN_VALUE ''' % (w, 8*count, w, 8*count + 2)] s[0] = ' 2' + s[0][3:] return ''.join(s) for i in range(1, 5): self.do_disassembly_test(func(i), expected(i, 4)) self.do_disassembly_test(func(1249), expected(1249, 4)) self.do_disassembly_test(func(1250), expected(1250, 5)) def test_disassemble_str(self): self.do_disassembly_test(expr_str, dis_expr_str) self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str) self.do_disassembly_test(annot_stmt_str, dis_annot_stmt_str) self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str) def test_disassemble_bytes(self): self.do_disassembly_test(_f.__code__.co_code, dis_f_co_code) def test_disassemble_class(self): self.do_disassembly_test(_C, dis_c) def test_disassemble_instance_method(self): self.do_disassembly_test(_C(1).__init__, dis_c_instance_method) def test_disassemble_instance_method_bytes(self): method_bytecode = _C(1).__init__.__code__.co_code self.do_disassembly_test(method_bytecode, dis_c_instance_method_bytes) def test_disassemble_static_method(self): self.do_disassembly_test(_C.sm, dis_c_static_method) def test_disassemble_class_method(self): self.do_disassembly_test(_C.cm, dis_c_class_method) def test_disassemble_generator(self): gen_func_disas = self.get_disassembly(_g) # Generator function gen_disas = self.get_disassembly(_g(1)) # Generator iterator self.assertEqual(gen_disas, gen_func_disas) def test_disassemble_async_generator(self): agen_func_disas = self.get_disassembly(_ag) # Async generator function agen_disas = self.get_disassembly(_ag(1)) # Async generator iterator self.assertEqual(agen_disas, agen_func_disas) def test_disassemble_coroutine(self): coro_func_disas = self.get_disassembly(_co) # Coroutine function coro = _co(1) # Coroutine object coro.close() # Avoid a RuntimeWarning (never awaited) coro_disas = self.get_disassembly(coro) self.assertEqual(coro_disas, coro_func_disas) def test_disassemble_fstring(self): self.do_disassembly_test(_fstring, dis_fstring) def test_dis_none(self): try: del sys.last_traceback except AttributeError: pass self.assertRaises(RuntimeError, dis.dis, None) def test_dis_traceback(self): try: del sys.last_traceback except AttributeError: pass try: 1/0 except Exception as e: tb = e.__traceback__ sys.last_traceback = tb tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti) self.do_disassembly_test(None, tb_dis) def test_dis_object(self): self.assertRaises(TypeError, dis.dis, object()) def test_disassemble_recursive(self): def check(expected, **kwargs): dis = self.get_disassembly(_h, **kwargs) dis = self.strip_addresses(dis) self.assertEqual(dis, expected) check(dis_nested_0, depth=0) check(dis_nested_1, depth=1) check(dis_nested_2, depth=2) check(dis_nested_2, depth=3) check(dis_nested_2, depth=None) check(dis_nested_2) class DisWithFileTests(DisTests): # Run the tests again, using the file arg instead of print def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): output = io.StringIO() if wrapper: dis.dis(func, file=output, **kwargs) else: dis.disassemble(func, lasti, file=output, **kwargs) return output.getvalue() code_info_code_info = """\ Name: code_info Filename: (.*) Argument count: 1 Kw-only arguments: 0 Number of locals: 1 Stack size: 3 Flags: OPTIMIZED, NEWLOCALS, NOFREE Constants: 0: %r Names: 0: _format_code_info 1: _get_code_object Variable names: 0: x""" % (('Formatted details of methods, functions, or code.',) if sys.flags.optimize < 2 else (None,)) @staticmethod def tricky(x, y, z=True, *args, c, d, e=[], **kwds): def f(c=c): print(x, y, z, c, d, e, f) yield x, y, z, c, d, e, f code_info_tricky = """\ Name: tricky Filename: (.*) Argument count: 3 Kw-only arguments: 3 Number of locals: 8 Stack size: 7 Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR Constants: 0: None 1: <code object f at (.*), file "(.*)", line (.*)> 2: 'tricky.<locals>.f' Variable names: 0: x 1: y 2: z 3: c 4: d 5: e 6: args 7: kwds Cell variables: 0: [edfxyz] 1: [edfxyz] 2: [edfxyz] 3: [edfxyz] 4: [edfxyz] 5: [edfxyz]""" # NOTE: the order of the cell variables above depends on dictionary order! co_tricky_nested_f = tricky.__func__.__code__.co_consts[1] code_info_tricky_nested_f = """\ Name: f Filename: (.*) Argument count: 1 Kw-only arguments: 0 Number of locals: 1 Stack size: 8 Flags: OPTIMIZED, NEWLOCALS, NESTED Constants: 0: None Names: 0: print Variable names: 0: c Free variables: 0: [edfxyz] 1: [edfxyz] 2: [edfxyz] 3: [edfxyz] 4: [edfxyz] 5: [edfxyz]""" code_info_expr_str = """\ Name: <module> Filename: <disassembly> Argument count: 0 Kw-only arguments: 0 Number of locals: 0 Stack size: 2 Flags: NOFREE Constants: 0: 1 Names: 0: x""" code_info_simple_stmt_str = """\ Name: <module> Filename: <disassembly> Argument count: 0 Kw-only arguments: 0 Number of locals: 0 Stack size: 2 Flags: NOFREE Constants: 0: 1 1: None Names: 0: x""" code_info_compound_stmt_str = """\ Name: <module> Filename: <disassembly> Argument count: 0 Kw-only arguments: 0 Number of locals: 0 Stack size: 2 Flags: NOFREE Constants: 0: 0 1: 1 2: None Names: 0: x""" async def async_def(): await 1 async for a in b: pass async with c as d: pass code_info_async_def = """\ Name: async_def Filename: (.*) Argument count: 0 Kw-only arguments: 0 Number of locals: 2 Stack size: 10 Flags: OPTIMIZED, NEWLOCALS, NOFREE, COROUTINE Constants: 0: None 1: 1""" class CodeInfoTests(unittest.TestCase): test_pairs = [ (dis.code_info, code_info_code_info), (tricky, code_info_tricky), (co_tricky_nested_f, code_info_tricky_nested_f), (expr_str, code_info_expr_str), (simple_stmt_str, code_info_simple_stmt_str), (compound_stmt_str, code_info_compound_stmt_str), (async_def, code_info_async_def) ] def test_code_info(self): self.maxDiff = 1000 for x, expected in self.test_pairs: self.assertRegex(dis.code_info(x), expected) def test_show_code(self): self.maxDiff = 1000 for x, expected in self.test_pairs: with captured_stdout() as output: dis.show_code(x) self.assertRegex(output.getvalue(), expected+"\n") output = io.StringIO() dis.show_code(x, file=output) self.assertRegex(output.getvalue(), expected) def test_code_info_object(self): self.assertRaises(TypeError, dis.code_info, object()) def test_pretty_flags_no_flags(self): self.assertEqual(dis.pretty_flags(0), '0x0') # Fodder for instruction introspection tests # Editing any of these may require recalculating the expected output def outer(a=1, b=2): def f(c=3, d=4): def inner(e=5, f=6): print(a, b, c, d, e, f) print(a, b, c, d) return inner print(a, b, '', 1, [], {}, "Hello world!") return f def jumpy(): # This won't actually run (but that's OK, we only disassemble it) for i in range(10): print(i) if i < 4: continue if i > 6: break else: print("I can haz else clause?") while i: print(i) i -= 1 if i > 6: continue if i < 4: break else: print("Who let lolcatz into this test suite?") try: 1 / 0 except ZeroDivisionError: print("Here we go, here we go, here we go...") else: with i as dodgy: print("Never reach this") finally: print("OK, now we're done") # End fodder for opinfo generation tests expected_outer_line = 1 _line_offset = outer.__code__.co_firstlineno - 1 code_object_f = outer.__code__.co_consts[3] expected_f_line = code_object_f.co_firstlineno - _line_offset code_object_inner = code_object_f.co_consts[3] expected_inner_line = code_object_inner.co_firstlineno - _line_offset expected_jumpy_line = 1 # The following lines are useful to regenerate the expected results after # either the fodder is modified or the bytecode generation changes # After regeneration, update the references to code_object_f and # code_object_inner before rerunning the tests #_instructions = dis.get_instructions(outer, first_line=expected_outer_line) #print('expected_opinfo_outer = [\n ', #',\n '.join(map(str, _instructions)), ',\n]', sep='') #_instructions = dis.get_instructions(outer(), first_line=expected_f_line) #print('expected_opinfo_f = [\n ', #',\n '.join(map(str, _instructions)), ',\n]', sep='') #_instructions = dis.get_instructions(outer()(), first_line=expected_inner_line) #print('expected_opinfo_inner = [\n ', #',\n '.join(map(str, _instructions)), ',\n]', sep='') #_instructions = dis.get_instructions(jumpy, first_line=expected_jumpy_line) #print('expected_opinfo_jumpy = [\n ', #',\n '.join(map(str, _instructions)), ',\n]', sep='') Instruction = dis.Instruction expected_opinfo_outer = [ Instruction(opname='LOAD_CONST', opcode=100, arg=8, argval=(3, 4), argrepr='(3, 4)', offset=0, starts_line=2, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), Instruction(opname='BUILD_TUPLE', opcode=102, arg=2, argval=2, argrepr='', offset=6, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_f, argrepr=repr(code_object_f), offset=8, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f', argrepr="'outer.<locals>.f'", offset=10, starts_line=None, is_jump_target=False), Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='', offset=12, starts_line=None, is_jump_target=False), Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='f', argrepr='f', offset=14, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=16, starts_line=7, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=18, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=20, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval='', argrepr="''", offset=22, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=6, argval=1, argrepr='1', offset=24, starts_line=None, is_jump_target=False), Instruction(opname='BUILD_LIST', opcode=103, arg=0, argval=0, argrepr='', offset=26, starts_line=None, is_jump_target=False), Instruction(opname='BUILD_MAP', opcode=105, arg=0, argval=0, argrepr='', offset=28, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=7, argval='Hello world!', argrepr="'Hello world!'", offset=30, starts_line=None, is_jump_target=False), Instruction(opname='CALL_FUNCTION', opcode=131, arg=7, argval=7, argrepr='', offset=32, starts_line=None, is_jump_target=False), Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=34, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='f', argrepr='f', offset=36, starts_line=8, is_jump_target=False), Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=38, starts_line=None, is_jump_target=False), ] expected_opinfo_f = [ Instruction(opname='LOAD_CONST', opcode=100, arg=5, argval=(5, 6), argrepr='(5, 6)', offset=0, starts_line=3, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=2, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=3, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=0, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CLOSURE', opcode=135, arg=1, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), Instruction(opname='BUILD_TUPLE', opcode=102, arg=4, argval=4, argrepr='', offset=10, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=code_object_inner, argrepr=repr(code_object_inner), offset=12, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval='outer.<locals>.f.<locals>.inner', argrepr="'outer.<locals>.f.<locals>.inner'", offset=14, starts_line=None, is_jump_target=False), Instruction(opname='MAKE_FUNCTION', opcode=132, arg=9, argval=9, argrepr='', offset=16, starts_line=None, is_jump_target=False), Instruction(opname='STORE_FAST', opcode=125, arg=2, argval='inner', argrepr='inner', offset=18, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=20, starts_line=5, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='a', argrepr='a', offset=22, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='b', argrepr='b', offset=24, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='c', argrepr='c', offset=26, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='d', argrepr='d', offset=28, starts_line=None, is_jump_target=False), Instruction(opname='CALL_FUNCTION', opcode=131, arg=4, argval=4, argrepr='', offset=30, starts_line=None, is_jump_target=False), Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=32, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_FAST', opcode=124, arg=2, argval='inner', argrepr='inner', offset=34, starts_line=6, is_jump_target=False), Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=36, starts_line=None, is_jump_target=False), ] expected_opinfo_inner = [ Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=0, starts_line=4, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=2, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=1, argval='b', argrepr='b', offset=4, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=2, argval='c', argrepr='c', offset=6, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_DEREF', opcode=136, arg=3, argval='d', argrepr='d', offset=8, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='e', argrepr='e', offset=10, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='f', argrepr='f', offset=12, starts_line=None, is_jump_target=False), Instruction(opname='CALL_FUNCTION', opcode=131, arg=6, argval=6, argrepr='', offset=14, starts_line=None, is_jump_target=False), Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False), Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=18, starts_line=None, is_jump_target=False), Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=20, starts_line=None, is_jump_target=False), ] expected_opinfo_jumpy = [
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_reprlib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_reprlib.py
""" Test cases for the repr module Nick Mathewson """ import sys import os import shutil import importlib import importlib.util import unittest from test.support import create_empty_file, verbose from reprlib import repr as r # Don't shadow builtin repr from reprlib import Repr from reprlib import recursive_repr def nestedTuple(nesting): t = () for i in range(nesting): t = (t,) return t class ReprTests(unittest.TestCase): def test_string(self): eq = self.assertEqual eq(r("abc"), "'abc'") eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'") s = "a"*30+"b"*30 expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) eq(r("\"'"), repr("\"'")) s = "\""*30+"'"*100 expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) def test_tuple(self): eq = self.assertEqual eq(r((1,)), "(1,)") t3 = (1, 2, 3) eq(r(t3), "(1, 2, 3)") r2 = Repr() r2.maxtuple = 2 expected = repr(t3)[:-2] + "...)" eq(r2.repr(t3), expected) def test_container(self): from array import array from collections import deque eq = self.assertEqual # Tuples give up after 6 elements eq(r(()), "()") eq(r((1,)), "(1,)") eq(r((1, 2, 3)), "(1, 2, 3)") eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)") eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)") # Lists give up after 6 as well eq(r([]), "[]") eq(r([1]), "[1]") eq(r([1, 2, 3]), "[1, 2, 3]") eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]") eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]") # Sets give up after 6 as well eq(r(set([])), "set()") eq(r(set([1])), "{1}") eq(r(set([1, 2, 3])), "{1, 2, 3}") eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}") eq(r(set([1, 2, 3, 4, 5, 6, 7])), "{1, 2, 3, 4, 5, 6, ...}") # Frozensets give up after 6 as well eq(r(frozenset([])), "frozenset()") eq(r(frozenset([1])), "frozenset({1})") eq(r(frozenset([1, 2, 3])), "frozenset({1, 2, 3})") eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset({1, 2, 3, 4, 5, 6})") eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset({1, 2, 3, 4, 5, 6, ...})") # collections.deque after 6 eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])") # Dictionaries give up after 4. eq(r({}), "{}") d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4} eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}") d['arthur'] = 1 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}") # array.array after 5. eq(r(array('i')), "array('i')") eq(r(array('i', [1])), "array('i', [1])") eq(r(array('i', [1, 2])), "array('i', [1, 2])") eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])") eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])") eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])") eq(r(array('i', [1, 2, 3, 4, 5, 6])), "array('i', [1, 2, 3, 4, 5, ...])") def test_set_literal(self): eq = self.assertEqual eq(r({1}), "{1}") eq(r({1, 2, 3}), "{1, 2, 3}") eq(r({1, 2, 3, 4, 5, 6}), "{1, 2, 3, 4, 5, 6}") eq(r({1, 2, 3, 4, 5, 6, 7}), "{1, 2, 3, 4, 5, 6, ...}") def test_frozenset(self): eq = self.assertEqual eq(r(frozenset({1})), "frozenset({1})") eq(r(frozenset({1, 2, 3})), "frozenset({1, 2, 3})") eq(r(frozenset({1, 2, 3, 4, 5, 6})), "frozenset({1, 2, 3, 4, 5, 6})") eq(r(frozenset({1, 2, 3, 4, 5, 6, 7})), "frozenset({1, 2, 3, 4, 5, 6, ...})") def test_numbers(self): eq = self.assertEqual eq(r(123), repr(123)) eq(r(123), repr(123)) eq(r(1.0/3), repr(1.0/3)) n = 10**100 expected = repr(n)[:18] + "..." + repr(n)[-19:] eq(r(n), expected) def test_instance(self): eq = self.assertEqual i1 = ClassWithRepr("a") eq(r(i1), repr(i1)) i2 = ClassWithRepr("x"*1000) expected = repr(i2)[:13] + "..." + repr(i2)[-14:] eq(r(i2), expected) i3 = ClassWithFailingRepr() eq(r(i3), ("<ClassWithFailingRepr instance at %#x>"%id(i3))) s = r(ClassWithFailingRepr) self.assertTrue(s.startswith("<class ")) self.assertTrue(s.endswith(">")) self.assertIn(s.find("..."), [12, 13]) def test_lambda(self): r = repr(lambda x: x) self.assertTrue(r.startswith("<function ReprTests.test_lambda.<locals>.<lambda"), r) # XXX anonymous functions? see func_repr def test_builtin_function(self): eq = self.assertEqual # Functions eq(repr(hash), '<built-in function hash>') # Methods self.assertTrue(repr(''.split).startswith( '<built-in method split of str object at 0x')) def test_range(self): eq = self.assertEqual eq(repr(range(1)), 'range(0, 1)') eq(repr(range(1, 2)), 'range(1, 2)') eq(repr(range(1, 4, 3)), 'range(1, 4, 3)') def test_nesting(self): eq = self.assertEqual # everything is meant to give up after 6 levels. eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]") eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]") eq(r(nestedTuple(6)), "(((((((),),),),),),)") eq(r(nestedTuple(7)), "(((((((...),),),),),),)") eq(r({ nestedTuple(5) : nestedTuple(5) }), "{((((((),),),),),): ((((((),),),),),)}") eq(r({ nestedTuple(6) : nestedTuple(6) }), "{((((((...),),),),),): ((((((...),),),),),)}") eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]") eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]") def test_cell(self): def get_cell(): x = 42 def inner(): return x return inner x = get_cell().__closure__[0] self.assertRegex(repr(x), r'<cell at 0x[0-9A-Fa-f]+: ' r'int object at 0x[0-9A-Fa-f]+>') self.assertRegex(r(x), r'<cell at 0x.*\.\.\..*>') def test_descriptors(self): eq = self.assertEqual # method descriptors eq(repr(dict.items), "<method 'items' of 'dict' objects>") # XXX member descriptors # XXX attribute descriptors # XXX slot descriptors # static and class methods class C: def foo(cls): pass x = staticmethod(C.foo) self.assertTrue(repr(x).startswith('<staticmethod object at 0x')) x = classmethod(C.foo) self.assertTrue(repr(x).startswith('<classmethod object at 0x')) def test_unsortable(self): # Repr.repr() used to call sorted() on sets, frozensets and dicts # without taking into account that not all objects are comparable x = set([1j, 2j, 3j]) y = frozenset(x) z = {1j: 1, 2j: 2} r(x) r(y) r(z) def write_file(path, text): with open(path, 'w', encoding='ASCII') as fp: fp.write(text) class LongReprTest(unittest.TestCase): longname = 'areallylongpackageandmodulenametotestreprtruncation' def setUp(self): self.pkgname = os.path.join(self.longname) self.subpkgname = os.path.join(self.longname, self.longname) # Make the package and subpackage shutil.rmtree(self.pkgname, ignore_errors=True) os.mkdir(self.pkgname) create_empty_file(os.path.join(self.pkgname, '__init__.py')) shutil.rmtree(self.subpkgname, ignore_errors=True) os.mkdir(self.subpkgname) create_empty_file(os.path.join(self.subpkgname, '__init__.py')) # Remember where we are self.here = os.getcwd() sys.path.insert(0, self.here) # When regrtest is run with its -j option, this command alone is not # enough. importlib.invalidate_caches() def tearDown(self): actions = [] for dirpath, dirnames, filenames in os.walk(self.pkgname): for name in dirnames + filenames: actions.append(os.path.join(dirpath, name)) actions.append(self.pkgname) actions.sort() actions.reverse() for p in actions: if os.path.isdir(p): os.rmdir(p) else: os.remove(p) del sys.path[0] def _check_path_limitations(self, module_name): # base directory source_path_len = len(self.here) # a path separator + `longname` (twice) source_path_len += 2 * (len(self.longname) + 1) # a path separator + `module_name` + ".py" source_path_len += len(module_name) + 1 + len(".py") cached_path_len = (source_path_len + len(importlib.util.cache_from_source("x.py")) - len("x.py")) if os.name == 'nt' and cached_path_len >= 258: # Under Windows, the max path len is 260 including C's terminating # NUL character. # (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath) self.skipTest("test paths too long (%d characters) for Windows' 260 character limit" % cached_path_len) elif os.name == 'nt' and verbose: print("cached_path_len =", cached_path_len) def test_module(self): self.maxDiff = None self._check_path_limitations(self.pkgname) create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py')) importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation module = areallylongpackageandmodulenametotestreprtruncation self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__)) self.assertEqual(repr(sys), "<module 'sys' (built-in)>") def test_type(self): self._check_path_limitations('foo') eq = self.assertEqual write_file(os.path.join(self.subpkgname, 'foo.py'), '''\ class foo(object): pass ''') importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo eq(repr(foo.foo), "<class '%s.foo'>" % foo.__name__) @unittest.skip('need a suitable object') def test_object(self): # XXX Test the repr of a type with a really long tp_name but with no # tp_repr. WIBNI we had ::Inline? :) pass def test_class(self): self._check_path_limitations('bar') write_file(os.path.join(self.subpkgname, 'bar.py'), '''\ class bar: pass ''') importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar # Module name may be prefixed with "test.", depending on how run. self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__) def test_instance(self): self._check_path_limitations('baz') write_file(os.path.join(self.subpkgname, 'baz.py'), '''\ class baz: pass ''') importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() self.assertTrue(repr(ibaz).startswith( "<%s.baz object at 0x" % baz.__name__)) def test_method(self): self._check_path_limitations('qux') eq = self.assertEqual write_file(os.path.join(self.subpkgname, 'qux.py'), '''\ class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: def amethod(self): pass ''') importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux # Unbound methods first r = repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod) self.assertTrue(r.startswith('<function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod'), r) # Bound method next iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() r = repr(iqux.amethod) self.assertTrue(r.startswith( '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \ % (qux.__name__,) ), r) @unittest.skip('needs a built-in function with a really long name') def test_builtin_function(self): # XXX test built-in functions and methods with really long names pass class ClassWithRepr: def __init__(self, s): self.s = s def __repr__(self): return "ClassWithRepr(%r)" % self.s class ClassWithFailingRepr: def __repr__(self): raise Exception("This should be caught by Repr.repr_instance") class MyContainer: 'Helper class for TestRecursiveRepr' def __init__(self, values): self.values = list(values) def append(self, value): self.values.append(value) @recursive_repr() def __repr__(self): return '<' + ', '.join(map(str, self.values)) + '>' class MyContainer2(MyContainer): @recursive_repr('+++') def __repr__(self): return '<' + ', '.join(map(str, self.values)) + '>' class MyContainer3: def __repr__(self): 'Test document content' pass wrapped = __repr__ wrapper = recursive_repr()(wrapped) class TestRecursiveRepr(unittest.TestCase): def test_recursive_repr(self): m = MyContainer(list('abcde')) m.append(m) m.append('x') m.append(m) self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>') m = MyContainer2(list('abcde')) m.append(m) m.append('x') m.append(m) self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>') def test_assigned_attributes(self): from functools import WRAPPER_ASSIGNMENTS as assigned wrapped = MyContainer3.wrapped wrapper = MyContainer3.wrapper for name in assigned: self.assertIs(getattr(wrapper, name), getattr(wrapped, 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_xml_dom_minicompat.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_dom_minicompat.py
# Tests for xml.dom.minicompat import copy import pickle import unittest import xml.dom from xml.dom.minicompat import * class EmptyNodeListTestCase(unittest.TestCase): """Tests for the EmptyNodeList class.""" def test_emptynodelist_item(self): # Test item access on an EmptyNodeList. node_list = EmptyNodeList() self.assertIsNone(node_list.item(0)) self.assertIsNone(node_list.item(-1)) # invalid item with self.assertRaises(IndexError): node_list[0] with self.assertRaises(IndexError): node_list[-1] def test_emptynodelist_length(self): node_list = EmptyNodeList() # Reading self.assertEqual(node_list.length, 0) # Writing with self.assertRaises(xml.dom.NoModificationAllowedErr): node_list.length = 111 def test_emptynodelist___add__(self): node_list = EmptyNodeList() + NodeList() self.assertEqual(node_list, NodeList()) def test_emptynodelist___radd__(self): node_list = [1,2] + EmptyNodeList() self.assertEqual(node_list, [1,2]) class NodeListTestCase(unittest.TestCase): """Tests for the NodeList class.""" def test_nodelist_item(self): # Test items access on a NodeList. # First, use an empty NodeList. node_list = NodeList() self.assertIsNone(node_list.item(0)) self.assertIsNone(node_list.item(-1)) with self.assertRaises(IndexError): node_list[0] with self.assertRaises(IndexError): node_list[-1] # Now, use a NodeList with items. node_list.append(111) node_list.append(999) self.assertEqual(node_list.item(0), 111) self.assertIsNone(node_list.item(-1)) # invalid item self.assertEqual(node_list[0], 111) self.assertEqual(node_list[-1], 999) def test_nodelist_length(self): node_list = NodeList([1, 2]) # Reading self.assertEqual(node_list.length, 2) # Writing with self.assertRaises(xml.dom.NoModificationAllowedErr): node_list.length = 111 def test_nodelist___add__(self): node_list = NodeList([3, 4]) + [1, 2] self.assertEqual(node_list, NodeList([3, 4, 1, 2])) def test_nodelist___radd__(self): node_list = [1, 2] + NodeList([3, 4]) self.assertEqual(node_list, NodeList([1, 2, 3, 4])) def test_nodelist_pickle_roundtrip(self): # Test pickling and unpickling of a NodeList. for proto in range(pickle.HIGHEST_PROTOCOL + 1): # Empty NodeList. node_list = NodeList() pickled = pickle.dumps(node_list, proto) unpickled = pickle.loads(pickled) self.assertIsNot(unpickled, node_list) self.assertEqual(unpickled, node_list) # Non-empty NodeList. node_list.append(1) node_list.append(2) pickled = pickle.dumps(node_list, proto) unpickled = pickle.loads(pickled) self.assertIsNot(unpickled, node_list) self.assertEqual(unpickled, node_list) def test_nodelist_copy(self): # Empty NodeList. node_list = NodeList() copied = copy.copy(node_list) self.assertIsNot(copied, node_list) self.assertEqual(copied, node_list) # Non-empty NodeList. node_list.append([1]) node_list.append([2]) copied = copy.copy(node_list) self.assertIsNot(copied, node_list) self.assertEqual(copied, node_list) for x, y in zip(copied, node_list): self.assertIs(x, y) def test_nodelist_deepcopy(self): # Empty NodeList. node_list = NodeList() copied = copy.deepcopy(node_list) self.assertIsNot(copied, node_list) self.assertEqual(copied, node_list) # Non-empty NodeList. node_list.append([1]) node_list.append([2]) copied = copy.deepcopy(node_list) self.assertIsNot(copied, node_list) self.assertEqual(copied, node_list) for x, y in zip(copied, node_list): self.assertIsNot(x, y) self.assertEqual(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_poplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_poplib.py
"""Test script for poplib module.""" # Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL # a real test suite import poplib import asyncore import asynchat import socket import os import errno import threading from unittest import TestCase, skipUnless from test import support as test_support HOST = test_support.HOST PORT = 0 SUPPORTS_SSL = False if hasattr(poplib, 'POP3_SSL'): import ssl SUPPORTS_SSL = True 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") requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported') # the dummy data returned by server when LIST and RETR commands are issued LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n' RETR_RESP = b"""From: postmaster@python.org\ \r\nContent-Type: text/plain\r\n\ MIME-Version: 1.0\r\n\ Subject: Dummy\r\n\ \r\n\ line1\r\n\ line2\r\n\ line3\r\n\ .\r\n""" class DummyPOP3Handler(asynchat.async_chat): CAPAS = {'UIDL': [], 'IMPLEMENTATION': ['python-testlib-pop-server']} enable_UTF8 = False def __init__(self, conn): asynchat.async_chat.__init__(self, conn) self.set_terminator(b"\r\n") self.in_buffer = [] self.push('+OK dummy pop3 server ready. <timestamp>') self.tls_active = False self.tls_starting = False def collect_incoming_data(self, data): self.in_buffer.append(data) def found_terminator(self): line = b''.join(self.in_buffer) line = str(line, 'ISO-8859-1') self.in_buffer = [] cmd = line.split(' ')[0].lower() space = line.find(' ') if space != -1: arg = line[space + 1:] else: arg = "" if hasattr(self, 'cmd_' + cmd): method = getattr(self, 'cmd_' + cmd) method(arg) else: self.push('-ERR unrecognized POP3 command "%s".' %cmd) def handle_error(self): raise def push(self, data): asynchat.async_chat.push(self, data.encode("ISO-8859-1") + b'\r\n') def cmd_echo(self, arg): # sends back the received string (used by the test suite) self.push(arg) def cmd_user(self, arg): if arg != "guido": self.push("-ERR no such user") self.push('+OK password required') def cmd_pass(self, arg): if arg != "python": self.push("-ERR wrong password") self.push('+OK 10 messages') def cmd_stat(self, arg): self.push('+OK 10 100') def cmd_list(self, arg): if arg: self.push('+OK %s %s' % (arg, arg)) else: self.push('+OK') asynchat.async_chat.push(self, LIST_RESP) cmd_uidl = cmd_list def cmd_retr(self, arg): self.push('+OK %s bytes' %len(RETR_RESP)) asynchat.async_chat.push(self, RETR_RESP) cmd_top = cmd_retr def cmd_dele(self, arg): self.push('+OK message marked for deletion.') def cmd_noop(self, arg): self.push('+OK done nothing.') def cmd_rpop(self, arg): self.push('+OK done nothing.') def cmd_apop(self, arg): self.push('+OK done nothing.') def cmd_quit(self, arg): self.push('+OK closing.') self.close_when_done() def _get_capas(self): _capas = dict(self.CAPAS) if not self.tls_active and SUPPORTS_SSL: _capas['STLS'] = [] return _capas def cmd_capa(self, arg): self.push('+OK Capability list follows') if self._get_capas(): for cap, params in self._get_capas().items(): _ln = [cap] if params: _ln.extend(params) self.push(' '.join(_ln)) self.push('.') def cmd_utf8(self, arg): self.push('+OK I know RFC6856' if self.enable_UTF8 else '-ERR What is UTF8?!') if SUPPORTS_SSL: def cmd_stls(self, arg): if self.tls_active is False: self.push('+OK Begin TLS negotiation') context = ssl.SSLContext() context.load_cert_chain(CERTFILE) tls_sock = context.wrap_socket(self.socket, server_side=True, do_handshake_on_connect=False, suppress_ragged_eofs=False) self.del_channel() self.set_socket(tls_sock) self.tls_active = True self.tls_starting = True self.in_buffer = [] self._do_tls_handshake() else: self.push('-ERR Command not permitted when TLS active') def _do_tls_handshake(self): try: self.socket.do_handshake() except ssl.SSLError as err: if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): return elif err.args[0] == ssl.SSL_ERROR_EOF: return self.handle_close() # TODO: SSLError does not expose alert information elif ("SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] or "SSLV3_ALERT_CERTIFICATE_UNKNOWN" in err.args[1]): return self.handle_close() raise except OSError as err: if err.args[0] == errno.ECONNABORTED: return self.handle_close() else: self.tls_active = True self.tls_starting = False def handle_read(self): if self.tls_starting: self._do_tls_handshake() else: try: asynchat.async_chat.handle_read(self) except ssl.SSLEOFError: self.handle_close() class DummyPOP3Server(asyncore.dispatcher, threading.Thread): handler = DummyPOP3Handler def __init__(self, address, af=socket.AF_INET): threading.Thread.__init__(self) asyncore.dispatcher.__init__(self) self.daemon = True self.create_socket(af, socket.SOCK_STREAM) self.bind(address) self.listen(5) self.active = False self.active_lock = threading.Lock() self.host, self.port = self.socket.getsockname()[:2] self.handler_instance = None def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() try: while self.active and asyncore.socket_map: with self.active_lock: asyncore.loop(timeout=0.1, count=1) finally: asyncore.close_all(ignore_all=True) def stop(self): assert self.active self.active = False self.join() def handle_accepted(self, conn, addr): self.handler_instance = self.handler(conn) def handle_connect(self): self.close() handle_read = handle_connect def writable(self): return 0 def handle_error(self): raise class TestPOP3Class(TestCase): def assertOK(self, resp): self.assertTrue(resp.startswith(b"+OK")) def setUp(self): self.server = DummyPOP3Server((HOST, PORT)) self.server.start() self.client = poplib.POP3(self.server.host, self.server.port, timeout=3) def tearDown(self): self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None def test_getwelcome(self): self.assertEqual(self.client.getwelcome(), b'+OK dummy pop3 server ready. <timestamp>') def test_exceptions(self): self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo -err') def test_user(self): self.assertOK(self.client.user('guido')) self.assertRaises(poplib.error_proto, self.client.user, 'invalid') def test_pass_(self): self.assertOK(self.client.pass_('python')) self.assertRaises(poplib.error_proto, self.client.user, 'invalid') def test_stat(self): self.assertEqual(self.client.stat(), (10, 100)) def test_list(self): self.assertEqual(self.client.list()[1:], ([b'1 1', b'2 2', b'3 3', b'4 4', b'5 5'], 25)) self.assertTrue(self.client.list('1').endswith(b"OK 1 1")) def test_retr(self): expected = (b'+OK 116 bytes', [b'From: postmaster@python.org', b'Content-Type: text/plain', b'MIME-Version: 1.0', b'Subject: Dummy', b'', b'line1', b'line2', b'line3'], 113) foo = self.client.retr('foo') self.assertEqual(foo, expected) def test_too_long_lines(self): self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo +%s' % ((poplib._MAXLINE + 10) * 'a')) def test_dele(self): self.assertOK(self.client.dele('foo')) def test_noop(self): self.assertOK(self.client.noop()) def test_rpop(self): self.assertOK(self.client.rpop('foo')) def test_apop_normal(self): self.assertOK(self.client.apop('foo', 'dummypassword')) def test_apop_REDOS(self): # Replace welcome with very long evil welcome. # NB The upper bound on welcome length is currently 2048. # At this length, evil input makes each apop call take # on the order of milliseconds instead of microseconds. evil_welcome = b'+OK' + (b'<' * 1000000) with test_support.swap_attr(self.client, 'welcome', evil_welcome): # The evil welcome is invalid, so apop should throw. self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb') def test_top(self): expected = (b'+OK 116 bytes', [b'From: postmaster@python.org', b'Content-Type: text/plain', b'MIME-Version: 1.0', b'Subject: Dummy', b'', b'line1', b'line2', b'line3'], 113) self.assertEqual(self.client.top(1, 1), expected) def test_uidl(self): self.client.uidl() self.client.uidl('foo') def test_utf8_raises_if_unsupported(self): self.server.handler.enable_UTF8 = False self.assertRaises(poplib.error_proto, self.client.utf8) def test_utf8(self): self.server.handler.enable_UTF8 = True expected = b'+OK I know RFC6856' result = self.client.utf8() self.assertEqual(result, expected) def test_capa(self): capa = self.client.capa() self.assertTrue('IMPLEMENTATION' in capa.keys()) def test_quit(self): resp = self.client.quit() self.assertTrue(resp) self.assertIsNone(self.client.sock) self.assertIsNone(self.client.file) @requires_ssl def test_stls_capa(self): capa = self.client.capa() self.assertTrue('STLS' in capa.keys()) @requires_ssl def test_stls(self): expected = b'+OK Begin TLS negotiation' resp = self.client.stls() self.assertEqual(resp, expected) @requires_ssl def test_stls_context(self): expected = b'+OK Begin TLS negotiation' ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_verify_locations(CAFILE) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertEqual(ctx.check_hostname, True) with self.assertRaises(ssl.CertificateError): resp = self.client.stls(context=ctx) self.client = poplib.POP3("localhost", self.server.port, timeout=3) resp = self.client.stls(context=ctx) self.assertEqual(resp, expected) if SUPPORTS_SSL: from test.test_ftplib import SSLConnection class DummyPOP3_SSLHandler(SSLConnection, DummyPOP3Handler): def __init__(self, conn): asynchat.async_chat.__init__(self, conn) self.secure_connection() self.set_terminator(b"\r\n") self.in_buffer = [] self.push('+OK dummy pop3 server ready. <timestamp>') self.tls_active = True self.tls_starting = False @requires_ssl class TestPOP3_SSLClass(TestPOP3Class): # repeat previous tests by using poplib.POP3_SSL def setUp(self): self.server = DummyPOP3Server((HOST, PORT)) self.server.handler = DummyPOP3_SSLHandler self.server.start() self.client = poplib.POP3_SSL(self.server.host, self.server.port) def test__all__(self): self.assertIn('POP3_SSL', poplib.__all__) def test_context(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host, self.server.port, keyfile=CERTFILE, context=ctx) self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host, self.server.port, certfile=CERTFILE, context=ctx) self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host, self.server.port, keyfile=CERTFILE, certfile=CERTFILE, context=ctx) self.client.quit() self.client = poplib.POP3_SSL(self.server.host, self.server.port, context=ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.assertIs(self.client.sock.context, ctx) self.assertTrue(self.client.noop().startswith(b'+OK')) def test_stls(self): self.assertRaises(poplib.error_proto, self.client.stls) test_stls_context = test_stls def test_stls_capa(self): capa = self.client.capa() self.assertFalse('STLS' in capa.keys()) @requires_ssl class TestPOP3_TLSClass(TestPOP3Class): # repeat previous tests by using poplib.POP3.stls() def setUp(self): self.server = DummyPOP3Server((HOST, PORT)) self.server.start() self.client = poplib.POP3(self.server.host, self.server.port, timeout=3) self.client.stls() def tearDown(self): if self.client.file is not None and self.client.sock is not None: try: self.client.quit() except poplib.error_proto: # happens in the test_too_long_lines case; the overlong # response will be treated as response to QUIT and raise # this exception self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None def test_stls(self): self.assertRaises(poplib.error_proto, self.client.stls) test_stls_context = test_stls def test_stls_capa(self): capa = self.client.capa() self.assertFalse(b'STLS' in capa.keys()) class TestTimeouts(TestCase): def setUp(self): self.evt = threading.Event() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(60) # Safety net. Look issue 11812 self.port = test_support.bind_port(self.sock) self.thread = threading.Thread(target=self.server, args=(self.evt,self.sock)) self.thread.daemon = True self.thread.start() self.evt.wait() def tearDown(self): self.thread.join() # Explicitly clear the attribute to prevent dangling thread self.thread = None def server(self, evt, serv): serv.listen() evt.set() try: conn, addr = serv.accept() conn.send(b"+ Hola mundo\n") conn.close() except socket.timeout: pass finally: serv.close() def testTimeoutDefault(self): self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: pop = poplib.POP3(HOST, self.port) finally: socket.setdefaulttimeout(None) self.assertEqual(pop.sock.gettimeout(), 30) pop.close() def testTimeoutNone(self): self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: pop = poplib.POP3(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(None) self.assertIsNone(pop.sock.gettimeout()) pop.close() def testTimeoutValue(self): pop = poplib.POP3(HOST, self.port, timeout=30) self.assertEqual(pop.sock.gettimeout(), 30) pop.close() def test_main(): tests = [TestPOP3Class, TestTimeouts, TestPOP3_SSLClass, TestPOP3_TLSClass] thread_info = test_support.threading_setup() try: test_support.run_unittest(*tests) finally: test_support.threading_cleanup(*thread_info) 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_weakset.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakset.py
import unittest from weakref import WeakSet import string from collections import UserString as ustr import gc import contextlib class Foo: pass class RefCycle: def __init__(self): self.cycle = self class TestWeakSet(unittest.TestCase): def setUp(self): # need to keep references to them self.items = [ustr(c) for c in ('a', 'b', 'c')] self.items2 = [ustr(c) for c in ('x', 'y', 'z')] self.ab_items = [ustr(c) for c in 'ab'] self.abcde_items = [ustr(c) for c in 'abcde'] self.def_items = [ustr(c) for c in 'def'] self.ab_weakset = WeakSet(self.ab_items) self.abcde_weakset = WeakSet(self.abcde_items) self.def_weakset = WeakSet(self.def_items) self.letters = [ustr(c) for c in string.ascii_letters] self.s = WeakSet(self.items) self.d = dict.fromkeys(self.items) self.obj = ustr('F') self.fs = WeakSet([self.obj]) def test_methods(self): weaksetmethods = dir(WeakSet) for method in dir(set): if method == 'test_c_api' or method.startswith('_'): continue self.assertIn(method, weaksetmethods, "WeakSet missing method " + method) def test_new_or_init(self): self.assertRaises(TypeError, WeakSet, [], 2) def test_len(self): self.assertEqual(len(self.s), len(self.d)) self.assertEqual(len(self.fs), 1) del self.obj self.assertEqual(len(self.fs), 0) def test_contains(self): for c in self.letters: self.assertEqual(c in self.s, c in self.d) # 1 is not weakref'able, but that TypeError is caught by __contains__ self.assertNotIn(1, self.s) self.assertIn(self.obj, self.fs) del self.obj self.assertNotIn(ustr('F'), self.fs) def test_union(self): u = self.s.union(self.items2) for c in self.letters: self.assertEqual(c in u, c in self.d or c in self.items2) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(u), WeakSet) self.assertRaises(TypeError, self.s.union, [[]]) for C in set, frozenset, dict.fromkeys, list, tuple: x = WeakSet(self.items + self.items2) c = C(self.items2) self.assertEqual(self.s.union(c), x) del c self.assertEqual(len(u), len(self.items) + len(self.items2)) self.items2.pop() gc.collect() self.assertEqual(len(u), len(self.items) + len(self.items2)) def test_or(self): i = self.s.union(self.items2) self.assertEqual(self.s | set(self.items2), i) self.assertEqual(self.s | frozenset(self.items2), i) def test_intersection(self): s = WeakSet(self.letters) i = s.intersection(self.items2) for c in self.letters: self.assertEqual(c in i, c in self.items2 and c in self.letters) self.assertEqual(s, WeakSet(self.letters)) self.assertEqual(type(i), WeakSet) for C in set, frozenset, dict.fromkeys, list, tuple: x = WeakSet([]) self.assertEqual(i.intersection(C(self.items)), x) self.assertEqual(len(i), len(self.items2)) self.items2.pop() gc.collect() self.assertEqual(len(i), len(self.items2)) def test_isdisjoint(self): self.assertTrue(self.s.isdisjoint(WeakSet(self.items2))) self.assertTrue(not self.s.isdisjoint(WeakSet(self.letters))) def test_and(self): i = self.s.intersection(self.items2) self.assertEqual(self.s & set(self.items2), i) self.assertEqual(self.s & frozenset(self.items2), i) def test_difference(self): i = self.s.difference(self.items2) for c in self.letters: self.assertEqual(c in i, c in self.d and c not in self.items2) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(i), WeakSet) self.assertRaises(TypeError, self.s.difference, [[]]) def test_sub(self): i = self.s.difference(self.items2) self.assertEqual(self.s - set(self.items2), i) self.assertEqual(self.s - frozenset(self.items2), i) def test_symmetric_difference(self): i = self.s.symmetric_difference(self.items2) for c in self.letters: self.assertEqual(c in i, (c in self.d) ^ (c in self.items2)) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(i), WeakSet) self.assertRaises(TypeError, self.s.symmetric_difference, [[]]) self.assertEqual(len(i), len(self.items) + len(self.items2)) self.items2.pop() gc.collect() self.assertEqual(len(i), len(self.items) + len(self.items2)) def test_xor(self): i = self.s.symmetric_difference(self.items2) self.assertEqual(self.s ^ set(self.items2), i) self.assertEqual(self.s ^ frozenset(self.items2), i) def test_sub_and_super(self): self.assertTrue(self.ab_weakset <= self.abcde_weakset) self.assertTrue(self.abcde_weakset <= self.abcde_weakset) self.assertTrue(self.abcde_weakset >= self.ab_weakset) self.assertFalse(self.abcde_weakset <= self.def_weakset) self.assertFalse(self.abcde_weakset >= self.def_weakset) 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_lt(self): self.assertTrue(self.ab_weakset < self.abcde_weakset) self.assertFalse(self.abcde_weakset < self.def_weakset) self.assertFalse(self.ab_weakset < self.ab_weakset) self.assertFalse(WeakSet() < WeakSet()) def test_gt(self): self.assertTrue(self.abcde_weakset > self.ab_weakset) self.assertFalse(self.abcde_weakset > self.def_weakset) self.assertFalse(self.ab_weakset > self.ab_weakset) self.assertFalse(WeakSet() > WeakSet()) def test_gc(self): # Create a nest of cycles to exercise overall ref count check s = WeakSet(Foo() for i in range(1000)) for elem in s: elem.cycle = s elem.sub = elem elem.set = WeakSet([elem]) def test_subclass_with_custom_hash(self): # Bug #1257731 class H(WeakSet): 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_init(self): s = WeakSet() s.__init__(self.items) self.assertEqual(s, self.s) s.__init__(self.items2) self.assertEqual(s, WeakSet(self.items2)) self.assertRaises(TypeError, s.__init__, s, 2); self.assertRaises(TypeError, s.__init__, 1); def test_constructor_identity(self): s = WeakSet(self.items) t = WeakSet(s) self.assertNotEqual(id(s), id(t)) def test_hash(self): self.assertRaises(TypeError, hash, self.s) def test_clear(self): self.s.clear() self.assertEqual(self.s, WeakSet([])) 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)) def test_add(self): x = ustr('Q') self.s.add(x) self.assertIn(x, self.s) dup = self.s.copy() self.s.add(x) self.assertEqual(self.s, dup) self.assertRaises(TypeError, self.s.add, []) self.fs.add(Foo()) self.assertTrue(len(self.fs) == 1) self.fs.add(self.obj) self.assertTrue(len(self.fs) == 1) def test_remove(self): x = ustr('a') self.s.remove(x) self.assertNotIn(x, self.s) self.assertRaises(KeyError, self.s.remove, x) self.assertRaises(TypeError, self.s.remove, []) def test_discard(self): a, q = ustr('a'), ustr('Q') self.s.discard(a) self.assertNotIn(a, self.s) self.s.discard(q) self.assertRaises(TypeError, self.s.discard, []) 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.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): self.assertIn(c, self.s) self.assertRaises(TypeError, self.s.update, [[]]) def test_update_set(self): self.s.update(set(self.items2)) for c in (self.items + self.items2): self.assertIn(c, self.s) def test_ior(self): self.s |= set(self.items2) for c in (self.items + self.items2): self.assertIn(c, self.s) def test_intersection_update(self): retval = self.s.intersection_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items2 and c in self.items: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.intersection_update, [[]]) def test_iand(self): self.s &= set(self.items2) for c in (self.items + self.items2): if c in self.items2 and c in self.items: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_difference_update(self): retval = self.s.difference_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items and c not in self.items2: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) def test_isub(self): self.s -= set(self.items2) for c in (self.items + self.items2): if c in self.items and c not in self.items2: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_symmetric_difference_update(self): retval = self.s.symmetric_difference_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) def test_ixor(self): self.s ^= set(self.items2) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): 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, WeakSet()) t = self.s.copy() t ^= t self.assertEqual(t, WeakSet()) def test_eq(self): # issue 5964 self.assertTrue(self.s == self.s) self.assertTrue(self.s == WeakSet(self.items)) self.assertFalse(self.s == set(self.items)) self.assertFalse(self.s == list(self.items)) self.assertFalse(self.s == tuple(self.items)) self.assertFalse(self.s == WeakSet([Foo])) self.assertFalse(self.s == 1) def test_ne(self): self.assertTrue(self.s != set(self.items)) s1 = WeakSet() s2 = WeakSet() self.assertFalse(s1 != s2) def test_weak_destroy_while_iterating(self): # Issue #7105: iterators shouldn't crash when a key is implicitly removed # Create new items to be sure no-one else holds a reference items = [ustr(c) for c in ('a', 'b', 'c')] s = WeakSet(items) it = iter(s) next(it) # Trigger internal iteration # Destroy an item del items[-1] gc.collect() # just in case # We have removed either the first consumed items, or another one self.assertIn(len(list(it)), [len(items), len(items) - 1]) del it # The removal has been committed self.assertEqual(len(s), len(items)) def test_weak_destroy_and_mutate_while_iterating(self): # Issue #7105: iterators shouldn't crash when a key is implicitly removed items = [ustr(c) for c in string.ascii_letters] s = WeakSet(items) @contextlib.contextmanager def testcontext(): try: it = iter(s) # Start iterator yielded = ustr(str(next(it))) # Schedule an item for removal and recreate it u = ustr(str(items.pop())) if yielded == u: # The iterator still has a reference to the removed item, # advance it (issue #20006). next(it) gc.collect() # just in case yield u finally: it = None # should commit all removals with testcontext() as u: self.assertNotIn(u, s) with testcontext() as u: self.assertRaises(KeyError, s.remove, u) self.assertNotIn(u, s) with testcontext() as u: s.add(u) self.assertIn(u, s) t = s.copy() with testcontext() as u: s.update(t) self.assertEqual(len(s), len(t)) with testcontext() as u: s.clear() self.assertEqual(len(s), 0) def test_len_cycles(self): N = 20 items = [RefCycle() for i in range(N)] s = WeakSet(items) del items it = iter(s) try: next(it) except StopIteration: pass gc.collect() n1 = len(s) del it gc.collect() n2 = len(s) # one item may be kept alive inside the iterator self.assertIn(n1, (0, 1)) self.assertEqual(n2, 0) def test_len_race(self): # Extended sanity checks for len() in the face of cyclic collection self.addCleanup(gc.set_threshold, *gc.get_threshold()) for th in range(1, 100): N = 20 gc.collect(0) gc.set_threshold(th, th, th) items = [RefCycle() for i in range(N)] s = WeakSet(items) del items # All items will be collected at next garbage collection pass it = iter(s) try: next(it) except StopIteration: pass n1 = len(s) del it n2 = len(s) self.assertGreaterEqual(n1, 0) self.assertLessEqual(n1, N) self.assertGreaterEqual(n2, 0) self.assertLessEqual(n2, n1) 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_urllib2_localnet.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2_localnet.py
import base64 import os import email import urllib.parse import urllib.request import http.server import threading import unittest import hashlib from test import support try: import ssl except ImportError: ssl = None here = os.path.dirname(__file__) # Self-signed cert file for 'localhost' CERT_localhost = os.path.join(here, 'keycert.pem') # Self-signed cert file for 'fakehostname' CERT_fakehostname = os.path.join(here, 'keycert2.pem') # Loopback http server infrastructure class LoopbackHttpServer(http.server.HTTPServer): """HTTP server w/ a few modifications that make it useful for loopback testing purposes. """ def __init__(self, server_address, RequestHandlerClass): http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass) # Set the timeout of our listening socket really low so # that we can stop the server easily. self.socket.settimeout(0.1) def get_request(self): """HTTPServer method, overridden.""" request, client_address = self.socket.accept() # It's a loopback connection, so setting the timeout # really low shouldn't affect anything, but should make # deadlocks less likely to occur. request.settimeout(10.0) return (request, client_address) class LoopbackHttpServerThread(threading.Thread): """Stoppable thread that runs a loopback http server.""" def __init__(self, request_handler): threading.Thread.__init__(self) self._stop_server = False self.ready = threading.Event() request_handler.protocol_version = "HTTP/1.0" self.httpd = LoopbackHttpServer(("127.0.0.1", 0), request_handler) self.port = self.httpd.server_port def stop(self): """Stops the webserver if it's currently running.""" self._stop_server = True self.join() self.httpd.server_close() def run(self): self.ready.set() while not self._stop_server: self.httpd.handle_request() # Authentication infrastructure class DigestAuthHandler: """Handler for performing digest authentication.""" def __init__(self): self._request_num = 0 self._nonces = [] self._users = {} self._realm_name = "Test Realm" self._qop = "auth" def set_qop(self, qop): self._qop = qop def set_users(self, users): assert isinstance(users, dict) self._users = users def set_realm(self, realm): self._realm_name = realm def _generate_nonce(self): self._request_num += 1 nonce = hashlib.md5(str(self._request_num).encode("ascii")).hexdigest() self._nonces.append(nonce) return nonce def _create_auth_dict(self, auth_str): first_space_index = auth_str.find(" ") auth_str = auth_str[first_space_index+1:] parts = auth_str.split(",") auth_dict = {} for part in parts: name, value = part.split("=") name = name.strip() if value[0] == '"' and value[-1] == '"': value = value[1:-1] else: value = value.strip() auth_dict[name] = value return auth_dict def _validate_auth(self, auth_dict, password, method, uri): final_dict = {} final_dict.update(auth_dict) final_dict["password"] = password final_dict["method"] = method final_dict["uri"] = uri HA1_str = "%(username)s:%(realm)s:%(password)s" % final_dict HA1 = hashlib.md5(HA1_str.encode("ascii")).hexdigest() HA2_str = "%(method)s:%(uri)s" % final_dict HA2 = hashlib.md5(HA2_str.encode("ascii")).hexdigest() final_dict["HA1"] = HA1 final_dict["HA2"] = HA2 response_str = "%(HA1)s:%(nonce)s:%(nc)s:" \ "%(cnonce)s:%(qop)s:%(HA2)s" % final_dict response = hashlib.md5(response_str.encode("ascii")).hexdigest() return response == auth_dict["response"] def _return_auth_challenge(self, request_handler): request_handler.send_response(407, "Proxy Authentication Required") request_handler.send_header("Content-Type", "text/html") request_handler.send_header( 'Proxy-Authenticate', 'Digest realm="%s", ' 'qop="%s",' 'nonce="%s", ' % \ (self._realm_name, self._qop, self._generate_nonce())) # XXX: Not sure if we're supposed to add this next header or # not. #request_handler.send_header('Connection', 'close') request_handler.end_headers() request_handler.wfile.write(b"Proxy Authentication Required.") return False def handle_request(self, request_handler): """Performs digest authentication on the given HTTP request handler. Returns True if authentication was successful, False otherwise. If no users have been set, then digest auth is effectively disabled and this method will always return True. """ if len(self._users) == 0: return True if "Proxy-Authorization" not in request_handler.headers: return self._return_auth_challenge(request_handler) else: auth_dict = self._create_auth_dict( request_handler.headers["Proxy-Authorization"] ) if auth_dict["username"] in self._users: password = self._users[ auth_dict["username"] ] else: return self._return_auth_challenge(request_handler) if not auth_dict.get("nonce") in self._nonces: return self._return_auth_challenge(request_handler) else: self._nonces.remove(auth_dict["nonce"]) auth_validated = False # MSIE uses short_path in its validation, but Python's # urllib.request uses the full path, so we're going to see if # either of them works here. for path in [request_handler.path, request_handler.short_path]: if self._validate_auth(auth_dict, password, request_handler.command, path): auth_validated = True if not auth_validated: return self._return_auth_challenge(request_handler) return True class BasicAuthHandler(http.server.BaseHTTPRequestHandler): """Handler for performing basic authentication.""" # Server side values USER = 'testUser' PASSWD = 'testPass' REALM = 'Test' USER_PASSWD = "%s:%s" % (USER, PASSWD) ENCODED_AUTH = base64.b64encode(USER_PASSWD.encode('ascii')).decode('ascii') def __init__(self, *args, **kwargs): http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def log_message(self, format, *args): # Suppress console log message pass def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_AUTHHEAD(self): self.send_response(401) self.send_header("WWW-Authenticate", "Basic realm=\"%s\"" % self.REALM) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): if not self.headers.get("Authorization", ""): self.do_AUTHHEAD() self.wfile.write(b"No Auth header received") elif self.headers.get( "Authorization", "") == "Basic " + self.ENCODED_AUTH: self.send_response(200) self.end_headers() self.wfile.write(b"It works") else: # Request Unauthorized self.do_AUTHHEAD() # Proxy test infrastructure class FakeProxyHandler(http.server.BaseHTTPRequestHandler): """This is a 'fake proxy' that makes it look like the entire internet has gone down due to a sudden zombie invasion. It main utility is in providing us with authentication support for testing. """ def __init__(self, digest_auth_handler, *args, **kwargs): # This has to be set before calling our parent's __init__(), which will # try to call do_GET(). self.digest_auth_handler = digest_auth_handler http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def log_message(self, format, *args): # Uncomment the next line for debugging. # sys.stderr.write(format % args) pass def do_GET(self): (scm, netloc, path, params, query, fragment) = urllib.parse.urlparse( self.path, "http") self.short_path = path if self.digest_auth_handler.handle_request(self): self.send_response(200, "OK") self.send_header("Content-Type", "text/html") self.end_headers() self.wfile.write(bytes("You've reached %s!<BR>" % self.path, "ascii")) self.wfile.write(b"Our apologies, but our server is down due to " b"a sudden zombie invasion.") # Test cases class BasicAuthTests(unittest.TestCase): USER = "testUser" PASSWD = "testPass" INCORRECT_PASSWD = "Incorrect" REALM = "Test" def setUp(self): super(BasicAuthTests, self).setUp() # With Basic Authentication def http_server_with_basic_auth_handler(*args, **kwargs): return BasicAuthHandler(*args, **kwargs) self.server = LoopbackHttpServerThread(http_server_with_basic_auth_handler) self.addCleanup(self.stop_server) self.server_url = 'http://127.0.0.1:%s' % self.server.port self.server.start() self.server.ready.wait() def stop_server(self): self.server.stop() self.server = None def tearDown(self): super(BasicAuthTests, self).tearDown() def test_basic_auth_success(self): ah = urllib.request.HTTPBasicAuthHandler() ah.add_password(self.REALM, self.server_url, self.USER, self.PASSWD) urllib.request.install_opener(urllib.request.build_opener(ah)) try: self.assertTrue(urllib.request.urlopen(self.server_url)) except urllib.error.HTTPError: self.fail("Basic auth failed for the url: %s" % self.server_url) def test_basic_auth_httperror(self): ah = urllib.request.HTTPBasicAuthHandler() ah.add_password(self.REALM, self.server_url, self.USER, self.INCORRECT_PASSWD) urllib.request.install_opener(urllib.request.build_opener(ah)) self.assertRaises(urllib.error.HTTPError, urllib.request.urlopen, self.server_url) class ProxyAuthTests(unittest.TestCase): URL = "http://localhost" USER = "tester" PASSWD = "test123" REALM = "TestRealm" def setUp(self): super(ProxyAuthTests, self).setUp() # Ignore proxy bypass settings in the environment. def restore_environ(old_environ): os.environ.clear() os.environ.update(old_environ) self.addCleanup(restore_environ, os.environ.copy()) os.environ['NO_PROXY'] = '' os.environ['no_proxy'] = '' self.digest_auth_handler = DigestAuthHandler() self.digest_auth_handler.set_users({self.USER: self.PASSWD}) self.digest_auth_handler.set_realm(self.REALM) # With Digest Authentication. def create_fake_proxy_handler(*args, **kwargs): return FakeProxyHandler(self.digest_auth_handler, *args, **kwargs) self.server = LoopbackHttpServerThread(create_fake_proxy_handler) self.addCleanup(self.stop_server) self.server.start() self.server.ready.wait() proxy_url = "http://127.0.0.1:%d" % self.server.port handler = urllib.request.ProxyHandler({"http" : proxy_url}) self.proxy_digest_handler = urllib.request.ProxyDigestAuthHandler() self.opener = urllib.request.build_opener( handler, self.proxy_digest_handler) def stop_server(self): self.server.stop() self.server = None def test_proxy_with_bad_password_raises_httperror(self): self.proxy_digest_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD+"bad") self.digest_auth_handler.set_qop("auth") self.assertRaises(urllib.error.HTTPError, self.opener.open, self.URL) def test_proxy_with_no_password_raises_httperror(self): self.digest_auth_handler.set_qop("auth") self.assertRaises(urllib.error.HTTPError, self.opener.open, self.URL) def test_proxy_qop_auth_works(self): self.proxy_digest_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD) self.digest_auth_handler.set_qop("auth") result = self.opener.open(self.URL) while result.read(): pass result.close() def test_proxy_qop_auth_int_works_or_throws_urlerror(self): self.proxy_digest_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD) self.digest_auth_handler.set_qop("auth-int") try: result = self.opener.open(self.URL) except urllib.error.URLError: # It's okay if we don't support auth-int, but we certainly # shouldn't receive any kind of exception here other than # a URLError. result = None if result: while result.read(): pass result.close() def GetRequestHandler(responses): class FakeHTTPRequestHandler(http.server.BaseHTTPRequestHandler): server_version = "TestHTTP/" requests = [] headers_received = [] port = 80 def do_GET(self): body = self.send_head() while body: done = self.wfile.write(body) body = body[done:] def do_POST(self): content_length = self.headers["Content-Length"] post_data = self.rfile.read(int(content_length)) self.do_GET() self.requests.append(post_data) def send_head(self): FakeHTTPRequestHandler.headers_received = self.headers self.requests.append(self.path) response_code, headers, body = responses.pop(0) self.send_response(response_code) for (header, value) in headers: self.send_header(header, value % {'port':self.port}) if body: self.send_header("Content-type", "text/plain") self.end_headers() return body self.end_headers() def log_message(self, *args): pass return FakeHTTPRequestHandler class TestUrlopen(unittest.TestCase): """Tests urllib.request.urlopen using the network. These tests are not exhaustive. Assuming that testing using files does a good job overall of some of the basic interface features. There are no tests exercising the optional 'data' and 'proxies' arguments. No tests for transparent redirection have been written. """ def setUp(self): super(TestUrlopen, self).setUp() # Ignore proxies for localhost tests. def restore_environ(old_environ): os.environ.clear() os.environ.update(old_environ) self.addCleanup(restore_environ, os.environ.copy()) os.environ['NO_PROXY'] = '*' os.environ['no_proxy'] = '*' def urlopen(self, url, data=None, **kwargs): l = [] f = urllib.request.urlopen(url, data, **kwargs) try: # Exercise various methods l.extend(f.readlines(200)) l.append(f.readline()) l.append(f.read(1024)) l.append(f.read()) finally: f.close() return b"".join(l) def stop_server(self): self.server.stop() self.server = None def start_server(self, responses=None): if responses is None: responses = [(200, [], b"we don't care")] handler = GetRequestHandler(responses) self.server = LoopbackHttpServerThread(handler) self.addCleanup(self.stop_server) self.server.start() self.server.ready.wait() port = self.server.port handler.port = port return handler def start_https_server(self, responses=None, **kwargs): if not hasattr(urllib.request, 'HTTPSHandler'): self.skipTest('ssl support required') from test.ssl_servers import make_https_server if responses is None: responses = [(200, [], b"we care a bit")] handler = GetRequestHandler(responses) server = make_https_server(self, handler_class=handler, **kwargs) handler.port = server.port return handler def test_redirection(self): expected_response = b"We got here..." responses = [ (302, [("Location", "http://localhost:%(port)s/somewhere_else")], ""), (200, [], expected_response) ] handler = self.start_server(responses) data = self.urlopen("http://localhost:%s/" % handler.port) self.assertEqual(data, expected_response) self.assertEqual(handler.requests, ["/", "/somewhere_else"]) def test_chunked(self): expected_response = b"hello world" chunked_start = ( b'a\r\n' b'hello worl\r\n' b'1\r\n' b'd\r\n' b'0\r\n' ) response = [(200, [("Transfer-Encoding", "chunked")], chunked_start)] handler = self.start_server(response) data = self.urlopen("http://localhost:%s/" % handler.port) self.assertEqual(data, expected_response) def test_404(self): expected_response = b"Bad bad bad..." handler = self.start_server([(404, [], expected_response)]) try: self.urlopen("http://localhost:%s/weeble" % handler.port) except urllib.error.URLError as f: data = f.read() f.close() else: self.fail("404 should raise URLError") self.assertEqual(data, expected_response) self.assertEqual(handler.requests, ["/weeble"]) def test_200(self): expected_response = b"pycon 2008..." handler = self.start_server([(200, [], expected_response)]) data = self.urlopen("http://localhost:%s/bizarre" % handler.port) self.assertEqual(data, expected_response) self.assertEqual(handler.requests, ["/bizarre"]) def test_200_with_parameters(self): expected_response = b"pycon 2008..." handler = self.start_server([(200, [], expected_response)]) data = self.urlopen("http://localhost:%s/bizarre" % handler.port, b"get=with_feeling") self.assertEqual(data, expected_response) self.assertEqual(handler.requests, ["/bizarre", b"get=with_feeling"]) def test_https(self): handler = self.start_https_server() context = ssl.create_default_context(cafile=CERT_localhost) data = self.urlopen("https://localhost:%s/bizarre" % handler.port, context=context) self.assertEqual(data, b"we care a bit") def test_https_with_cafile(self): handler = self.start_https_server(certfile=CERT_localhost) with support.check_warnings(('', DeprecationWarning)): # Good cert data = self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_localhost) self.assertEqual(data, b"we care a bit") # Bad cert with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_fakehostname) # Good cert, but mismatching hostname handler = self.start_https_server(certfile=CERT_fakehostname) with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cafile=CERT_fakehostname) def test_https_with_cadefault(self): handler = self.start_https_server(certfile=CERT_localhost) # Self-signed cert should fail verification with system certificate store with support.check_warnings(('', DeprecationWarning)): with self.assertRaises(urllib.error.URLError) as cm: self.urlopen("https://localhost:%s/bizarre" % handler.port, cadefault=True) def test_https_sni(self): if ssl is None: self.skipTest("ssl module required") if not ssl.HAS_SNI: self.skipTest("SNI support required in OpenSSL") sni_name = None def cb_sni(ssl_sock, server_name, initial_context): nonlocal sni_name sni_name = server_name context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.set_servername_callback(cb_sni) handler = self.start_https_server(context=context, certfile=CERT_localhost) context = ssl.create_default_context(cafile=CERT_localhost) self.urlopen("https://localhost:%s" % handler.port, context=context) self.assertEqual(sni_name, "localhost") def test_sending_headers(self): handler = self.start_server() req = urllib.request.Request("http://localhost:%s/" % handler.port, headers={"Range": "bytes=20-39"}) with urllib.request.urlopen(req): pass self.assertEqual(handler.headers_received["Range"], "bytes=20-39") def test_basic(self): handler = self.start_server() open_url = urllib.request.urlopen("http://localhost:%s" % handler.port) for attr in ("read", "close", "info", "geturl"): self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) try: self.assertTrue(open_url.read(), "calling 'read' failed") finally: open_url.close() def test_info(self): handler = self.start_server() open_url = urllib.request.urlopen( "http://localhost:%s" % handler.port) with open_url: info_obj = open_url.info() self.assertIsInstance(info_obj, email.message.Message, "object returned by 'info' is not an " "instance of email.message.Message") self.assertEqual(info_obj.get_content_subtype(), "plain") def test_geturl(self): # Make sure same URL as opened is returned by geturl. handler = self.start_server() open_url = urllib.request.urlopen("http://localhost:%s" % handler.port) with open_url: url = open_url.geturl() self.assertEqual(url, "http://localhost:%s" % handler.port) def test_iteration(self): expected_response = b"pycon 2008..." handler = self.start_server([(200, [], expected_response)]) data = urllib.request.urlopen("http://localhost:%s" % handler.port) for line in data: self.assertEqual(line, expected_response) def test_line_iteration(self): lines = [b"We\n", b"got\n", b"here\n", b"verylong " * 8192 + b"\n"] expected_response = b"".join(lines) handler = self.start_server([(200, [], expected_response)]) data = urllib.request.urlopen("http://localhost:%s" % handler.port) for index, line in enumerate(data): self.assertEqual(line, lines[index], "Fetched line number %s doesn't match expected:\n" " Expected length was %s, got %s" % (index, len(lines[index]), len(line))) self.assertEqual(index + 1, len(lines)) threads_key = None def setUpModule(): # Store the threading_setup in a key and ensure that it is cleaned up # in the tearDown global threads_key threads_key = support.threading_setup() def tearDownModule(): if threads_key: support.threading_cleanup(*threads_key) 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_slice.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_slice.py
# tests for slice objects; in particular the indices method. import itertools import operator import sys import unittest import weakref from pickle import loads, dumps from test import support def evaluate_slice_index(arg): """ Helper function to convert a slice argument to an integer, and raise TypeError with a suitable message on failure. """ if hasattr(arg, '__index__'): return operator.index(arg) else: raise TypeError( "slice indices must be integers or " "None or have an __index__ method") def slice_indices(slice, length): """ Reference implementation for the slice.indices method. """ # Compute step and length as integers. length = operator.index(length) step = 1 if slice.step is None else evaluate_slice_index(slice.step) # Raise ValueError for negative length or zero step. if length < 0: raise ValueError("length should not be negative") if step == 0: raise ValueError("slice step cannot be zero") # Find lower and upper bounds for start and stop. lower = -1 if step < 0 else 0 upper = length - 1 if step < 0 else length # Compute start. if slice.start is None: start = upper if step < 0 else lower else: start = evaluate_slice_index(slice.start) start = max(start + length, lower) if start < 0 else min(start, upper) # Compute stop. if slice.stop is None: stop = lower if step < 0 else upper else: stop = evaluate_slice_index(slice.stop) stop = max(stop + length, lower) if stop < 0 else min(stop, upper) return start, stop, step # Class providing an __index__ method. Used for testing slice.indices. class MyIndexable(object): def __init__(self, value): self.value = value def __index__(self): return self.value class SliceTest(unittest.TestCase): def test_constructor(self): self.assertRaises(TypeError, slice) self.assertRaises(TypeError, slice, 1, 2, 3, 4) def test_repr(self): self.assertEqual(repr(slice(1, 2, 3)), "slice(1, 2, 3)") def test_hash(self): # Verify clearing of SF bug #800796 self.assertRaises(TypeError, hash, slice(5)) with self.assertRaises(TypeError): slice(5).__hash__() def test_cmp(self): s1 = slice(1, 2, 3) s2 = slice(1, 2, 3) s3 = slice(1, 2, 4) self.assertEqual(s1, s2) self.assertNotEqual(s1, s3) self.assertNotEqual(s1, None) self.assertNotEqual(s1, (1, 2, 3)) self.assertNotEqual(s1, "") class Exc(Exception): pass class BadCmp(object): def __eq__(self, other): raise Exc s1 = slice(BadCmp()) s2 = slice(BadCmp()) self.assertEqual(s1, s1) self.assertRaises(Exc, lambda: s1 == s2) s1 = slice(1, BadCmp()) s2 = slice(1, BadCmp()) self.assertEqual(s1, s1) self.assertRaises(Exc, lambda: s1 == s2) s1 = slice(1, 2, BadCmp()) s2 = slice(1, 2, BadCmp()) self.assertEqual(s1, s1) self.assertRaises(Exc, lambda: s1 == s2) def test_members(self): s = slice(1) self.assertEqual(s.start, None) self.assertEqual(s.stop, 1) self.assertEqual(s.step, None) s = slice(1, 2) self.assertEqual(s.start, 1) self.assertEqual(s.stop, 2) self.assertEqual(s.step, None) s = slice(1, 2, 3) self.assertEqual(s.start, 1) self.assertEqual(s.stop, 2) self.assertEqual(s.step, 3) class AnyClass: pass obj = AnyClass() s = slice(obj) self.assertTrue(s.stop is obj) def check_indices(self, slice, length): try: actual = slice.indices(length) except ValueError: actual = "valueerror" try: expected = slice_indices(slice, length) except ValueError: expected = "valueerror" self.assertEqual(actual, expected) if length >= 0 and slice.step != 0: actual = range(*slice.indices(length)) expected = range(length)[slice] self.assertEqual(actual, expected) def test_indices(self): self.assertEqual(slice(None ).indices(10), (0, 10, 1)) self.assertEqual(slice(None, None, 2).indices(10), (0, 10, 2)) self.assertEqual(slice(1, None, 2).indices(10), (1, 10, 2)) self.assertEqual(slice(None, None, -1).indices(10), (9, -1, -1)) self.assertEqual(slice(None, None, -2).indices(10), (9, -1, -2)) self.assertEqual(slice(3, None, -2).indices(10), (3, -1, -2)) # issue 3004 tests self.assertEqual(slice(None, -9).indices(10), (0, 1, 1)) self.assertEqual(slice(None, -10).indices(10), (0, 0, 1)) self.assertEqual(slice(None, -11).indices(10), (0, 0, 1)) self.assertEqual(slice(None, -10, -1).indices(10), (9, 0, -1)) self.assertEqual(slice(None, -11, -1).indices(10), (9, -1, -1)) self.assertEqual(slice(None, -12, -1).indices(10), (9, -1, -1)) self.assertEqual(slice(None, 9).indices(10), (0, 9, 1)) self.assertEqual(slice(None, 10).indices(10), (0, 10, 1)) self.assertEqual(slice(None, 11).indices(10), (0, 10, 1)) self.assertEqual(slice(None, 8, -1).indices(10), (9, 8, -1)) self.assertEqual(slice(None, 9, -1).indices(10), (9, 9, -1)) self.assertEqual(slice(None, 10, -1).indices(10), (9, 9, -1)) self.assertEqual( slice(-100, 100 ).indices(10), slice(None).indices(10) ) self.assertEqual( slice(100, -100, -1).indices(10), slice(None, None, -1).indices(10) ) self.assertEqual(slice(-100, 100, 2).indices(10), (0, 10, 2)) self.assertEqual(list(range(10))[::sys.maxsize - 1], [0]) # Check a variety of start, stop, step and length values, including # values exceeding sys.maxsize (see issue #14794). vals = [None, -2**100, -2**30, -53, -7, -1, 0, 1, 7, 53, 2**30, 2**100] lengths = [0, 1, 7, 53, 2**30, 2**100] for slice_args in itertools.product(vals, repeat=3): s = slice(*slice_args) for length in lengths: self.check_indices(s, length) self.check_indices(slice(0, 10, 1), -3) # Negative length should raise ValueError with self.assertRaises(ValueError): slice(None).indices(-1) # Zero step should raise ValueError with self.assertRaises(ValueError): slice(0, 10, 0).indices(5) # Using a start, stop or step or length that can't be interpreted as an # integer should give a TypeError ... with self.assertRaises(TypeError): slice(0.0, 10, 1).indices(5) with self.assertRaises(TypeError): slice(0, 10.0, 1).indices(5) with self.assertRaises(TypeError): slice(0, 10, 1.0).indices(5) with self.assertRaises(TypeError): slice(0, 10, 1).indices(5.0) # ... but it should be fine to use a custom class that provides index. self.assertEqual(slice(0, 10, 1).indices(5), (0, 5, 1)) self.assertEqual(slice(MyIndexable(0), 10, 1).indices(5), (0, 5, 1)) self.assertEqual(slice(0, MyIndexable(10), 1).indices(5), (0, 5, 1)) self.assertEqual(slice(0, 10, MyIndexable(1)).indices(5), (0, 5, 1)) self.assertEqual(slice(0, 10, 1).indices(MyIndexable(5)), (0, 5, 1)) def test_setslice_without_getslice(self): tmp = [] class X(object): def __setitem__(self, i, k): tmp.append((i, k)) x = X() x[1:2] = 42 self.assertEqual(tmp, [(slice(1, 2), 42)]) def test_pickle(self): s = slice(10, 20, 3) for protocol in (0,1,2): t = loads(dumps(s, protocol)) self.assertEqual(s, t) self.assertEqual(s.indices(15), t.indices(15)) self.assertNotEqual(id(s), id(t)) def test_cycle(self): class myobj(): pass o = myobj() o.s = slice(o) w = weakref.ref(o) o = None support.gc_collect() self.assertIsNone(w()) 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_decorators.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decorators.py
import unittest def funcattrs(**kwds): def decorate(func): func.__dict__.update(kwds) return func return decorate class MiscDecorators (object): @staticmethod def author(name): def decorate(func): func.__dict__['author'] = name return func return decorate # ----------------------------------------------- class DbcheckError (Exception): def __init__(self, exprstr, func, args, kwds): # A real version of this would set attributes here Exception.__init__(self, "dbcheck %r failed (func=%s args=%s kwds=%s)" % (exprstr, func, args, kwds)) def dbcheck(exprstr, globals=None, locals=None): "Decorator to implement debugging assertions" def decorate(func): expr = compile(exprstr, "dbcheck-%s" % func.__name__, "eval") def check(*args, **kwds): if not eval(expr, globals, locals): raise DbcheckError(exprstr, func, args, kwds) return func(*args, **kwds) return check return decorate # ----------------------------------------------- def countcalls(counts): "Decorator to count calls to a function" def decorate(func): func_name = func.__name__ counts[func_name] = 0 def call(*args, **kwds): counts[func_name] += 1 return func(*args, **kwds) call.__name__ = func_name return call return decorate # ----------------------------------------------- def memoize(func): saved = {} def call(*args): try: return saved[args] except KeyError: res = func(*args) saved[args] = res return res except TypeError: # Unhashable argument return func(*args) call.__name__ = func.__name__ return call # ----------------------------------------------- class TestDecorators(unittest.TestCase): def test_single(self): class C(object): @staticmethod def foo(): return 42 self.assertEqual(C.foo(), 42) self.assertEqual(C().foo(), 42) def test_staticmethod_function(self): @staticmethod def notamethod(x): return x self.assertRaises(TypeError, notamethod, 1) def test_dotted(self): decorators = MiscDecorators() @decorators.author('Cleese') def foo(): return 42 self.assertEqual(foo(), 42) self.assertEqual(foo.author, 'Cleese') def test_argforms(self): # A few tests of argument passing, as we use restricted form # of expressions for decorators. def noteargs(*args, **kwds): def decorate(func): setattr(func, 'dbval', (args, kwds)) return func return decorate args = ( 'Now', 'is', 'the', 'time' ) kwds = dict(one=1, two=2) @noteargs(*args, **kwds) def f1(): return 42 self.assertEqual(f1(), 42) self.assertEqual(f1.dbval, (args, kwds)) @noteargs('terry', 'gilliam', eric='idle', john='cleese') def f2(): return 84 self.assertEqual(f2(), 84) self.assertEqual(f2.dbval, (('terry', 'gilliam'), dict(eric='idle', john='cleese'))) @noteargs(1, 2,) def f3(): pass self.assertEqual(f3.dbval, ((1, 2), {})) def test_dbcheck(self): @dbcheck('args[1] is not None') def f(a, b): return a + b self.assertEqual(f(1, 2), 3) self.assertRaises(DbcheckError, f, 1, None) def test_memoize(self): counts = {} @memoize @countcalls(counts) def double(x): return x * 2 self.assertEqual(double.__name__, 'double') self.assertEqual(counts, dict(double=0)) # Only the first call with a given argument bumps the call count: # self.assertEqual(double(2), 4) self.assertEqual(counts['double'], 1) self.assertEqual(double(2), 4) self.assertEqual(counts['double'], 1) self.assertEqual(double(3), 6) self.assertEqual(counts['double'], 2) # Unhashable arguments do not get memoized: # self.assertEqual(double([10]), [10, 10]) self.assertEqual(counts['double'], 3) self.assertEqual(double([10]), [10, 10]) self.assertEqual(counts['double'], 4) def test_errors(self): # Test syntax restrictions - these are all compile-time errors: # for expr in [ "1+2", "x[3]", "(1, 2)" ]: # Sanity check: is expr is a valid expression by itself? compile(expr, "testexpr", "exec") codestr = "@%s\ndef f(): pass" % expr self.assertRaises(SyntaxError, compile, codestr, "test", "exec") # You can't put multiple decorators on a single line: # self.assertRaises(SyntaxError, compile, "@f1 @f2\ndef f(): pass", "test", "exec") # Test runtime errors def unimp(func): raise NotImplementedError context = dict(nullval=None, unimp=unimp) for expr, exc in [ ("undef", NameError), ("nullval", TypeError), ("nullval.attr", AttributeError), ("unimp", NotImplementedError)]: codestr = "@%s\ndef f(): pass\nassert f() is None" % expr code = compile(codestr, "test", "exec") self.assertRaises(exc, eval, code, context) def test_double(self): class C(object): @funcattrs(abc=1, xyz="haha") @funcattrs(booh=42) def foo(self): return 42 self.assertEqual(C().foo(), 42) self.assertEqual(C.foo.abc, 1) self.assertEqual(C.foo.xyz, "haha") self.assertEqual(C.foo.booh, 42) def test_order(self): # Test that decorators are applied in the proper order to the function # they are decorating. def callnum(num): """Decorator factory that returns a decorator that replaces the passed-in function with one that returns the value of 'num'""" def deco(func): return lambda: num return deco @callnum(2) @callnum(1) def foo(): return 42 self.assertEqual(foo(), 2, "Application order of decorators is incorrect") def test_eval_order(self): # Evaluating a decorated function involves four steps for each # decorator-maker (the function that returns a decorator): # # 1: Evaluate the decorator-maker name # 2: Evaluate the decorator-maker arguments (if any) # 3: Call the decorator-maker to make a decorator # 4: Call the decorator # # When there are multiple decorators, these steps should be # performed in the above order for each decorator, but we should # iterate through the decorators in the reverse of the order they # appear in the source. actions = [] def make_decorator(tag): actions.append('makedec' + tag) def decorate(func): actions.append('calldec' + tag) return func return decorate class NameLookupTracer (object): def __init__(self, index): self.index = index def __getattr__(self, fname): if fname == 'make_decorator': opname, res = ('evalname', make_decorator) elif fname == 'arg': opname, res = ('evalargs', str(self.index)) else: assert False, "Unknown attrname %s" % fname actions.append('%s%d' % (opname, self.index)) return res c1, c2, c3 = map(NameLookupTracer, [ 1, 2, 3 ]) expected_actions = [ 'evalname1', 'evalargs1', 'makedec1', 'evalname2', 'evalargs2', 'makedec2', 'evalname3', 'evalargs3', 'makedec3', 'calldec3', 'calldec2', 'calldec1' ] actions = [] @c1.make_decorator(c1.arg) @c2.make_decorator(c2.arg) @c3.make_decorator(c3.arg) def foo(): return 42 self.assertEqual(foo(), 42) self.assertEqual(actions, expected_actions) # Test the equivalence claim in chapter 7 of the reference manual. # actions = [] def bar(): return 42 bar = c1.make_decorator(c1.arg)(c2.make_decorator(c2.arg)(c3.make_decorator(c3.arg)(bar))) self.assertEqual(bar(), 42) self.assertEqual(actions, expected_actions) class TestClassDecorators(unittest.TestCase): def test_simple(self): def plain(x): x.extra = 'Hello' return x @plain class C(object): pass self.assertEqual(C.extra, 'Hello') def test_double(self): def ten(x): x.extra = 10 return x def add_five(x): x.extra += 5 return x @add_five @ten class C(object): pass self.assertEqual(C.extra, 15) def test_order(self): def applied_first(x): x.extra = 'first' return x def applied_second(x): x.extra = 'second' return x @applied_second @applied_first class C(object): pass self.assertEqual(C.extra, 'second') 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_asyncore.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncore.py
import asyncore import unittest import select import os import socket import sys import time import errno import struct import threading from test import support from io import BytesIO if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") TIMEOUT = 3 HAS_UNIX_SOCKETS = hasattr(socket, 'AF_UNIX') class dummysocket: def __init__(self): self.closed = False def close(self): self.closed = True def fileno(self): return 42 class dummychannel: def __init__(self): self.socket = dummysocket() def close(self): self.socket.close() class exitingdummy: def __init__(self): pass def handle_read_event(self): raise asyncore.ExitNow() handle_write_event = handle_read_event handle_close = handle_read_event handle_expt_event = handle_read_event class crashingdummy: def __init__(self): self.error_handled = False def handle_read_event(self): raise Exception() handle_write_event = handle_read_event handle_close = handle_read_event handle_expt_event = handle_read_event def handle_error(self): self.error_handled = True # used when testing senders; just collects what it gets until newline is sent def capture_server(evt, buf, serv): try: serv.listen() conn, addr = serv.accept() except socket.timeout: pass else: n = 200 start = time.monotonic() while n > 0 and time.monotonic() - start < 3.0: r, w, e = select.select([conn], [], [], 0.1) if r: n -= 1 data = conn.recv(10) # keep everything except for the newline terminator buf.write(data.replace(b'\n', b'')) if b'\n' in data: break time.sleep(0.01) conn.close() finally: serv.close() evt.set() def bind_af_aware(sock, addr): """Helper function to bind a socket according to its family.""" if HAS_UNIX_SOCKETS and sock.family == socket.AF_UNIX: # Make sure the path doesn't exist. support.unlink(addr) support.bind_unix_socket(sock, addr) else: sock.bind(addr) class HelperFunctionTests(unittest.TestCase): def test_readwriteexc(self): # Check exception handling behavior of read, write and _exception # check that ExitNow exceptions in the object handler method # bubbles all the way up through asyncore read/write/_exception calls tr1 = exitingdummy() self.assertRaises(asyncore.ExitNow, asyncore.read, tr1) self.assertRaises(asyncore.ExitNow, asyncore.write, tr1) self.assertRaises(asyncore.ExitNow, asyncore._exception, tr1) # check that an exception other than ExitNow in the object handler # method causes the handle_error method to get called tr2 = crashingdummy() asyncore.read(tr2) self.assertEqual(tr2.error_handled, True) tr2 = crashingdummy() asyncore.write(tr2) self.assertEqual(tr2.error_handled, True) tr2 = crashingdummy() asyncore._exception(tr2) self.assertEqual(tr2.error_handled, True) # asyncore.readwrite uses constants in the select module that # are not present in Windows systems (see this thread: # http://mail.python.org/pipermail/python-list/2001-October/109973.html) # These constants should be present as long as poll is available @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') def test_readwrite(self): # Check that correct methods are called by readwrite() attributes = ('read', 'expt', 'write', 'closed', 'error_handled') expected = ( (select.POLLIN, 'read'), (select.POLLPRI, 'expt'), (select.POLLOUT, 'write'), (select.POLLERR, 'closed'), (select.POLLHUP, 'closed'), (select.POLLNVAL, 'closed'), ) class testobj: def __init__(self): self.read = False self.write = False self.closed = False self.expt = False self.error_handled = False def handle_read_event(self): self.read = True def handle_write_event(self): self.write = True def handle_close(self): self.closed = True def handle_expt_event(self): self.expt = True def handle_error(self): self.error_handled = True for flag, expectedattr in expected: tobj = testobj() self.assertEqual(getattr(tobj, expectedattr), False) asyncore.readwrite(tobj, flag) # Only the attribute modified by the routine we expect to be # called should be True. for attr in attributes: self.assertEqual(getattr(tobj, attr), attr==expectedattr) # check that ExitNow exceptions in the object handler method # bubbles all the way up through asyncore readwrite call tr1 = exitingdummy() self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag) # check that an exception other than ExitNow in the object handler # method causes the handle_error method to get called tr2 = crashingdummy() self.assertEqual(tr2.error_handled, False) asyncore.readwrite(tr2, flag) self.assertEqual(tr2.error_handled, True) def test_closeall(self): self.closeall_check(False) def test_closeall_default(self): self.closeall_check(True) def closeall_check(self, usedefault): # Check that close_all() closes everything in a given map l = [] testmap = {} for i in range(10): c = dummychannel() l.append(c) self.assertEqual(c.socket.closed, False) testmap[i] = c if usedefault: socketmap = asyncore.socket_map try: asyncore.socket_map = testmap asyncore.close_all() finally: testmap, asyncore.socket_map = asyncore.socket_map, socketmap else: asyncore.close_all(testmap) self.assertEqual(len(testmap), 0) for c in l: self.assertEqual(c.socket.closed, True) def test_compact_traceback(self): try: raise Exception("I don't like spam!") except: real_t, real_v, real_tb = sys.exc_info() r = asyncore.compact_traceback() else: self.fail("Expected exception") (f, function, line), t, v, info = r self.assertEqual(os.path.split(f)[-1], 'test_asyncore.py') self.assertEqual(function, 'test_compact_traceback') self.assertEqual(t, real_t) self.assertEqual(v, real_v) self.assertEqual(info, '[%s|%s|%s]' % (f, function, line)) class DispatcherTests(unittest.TestCase): def setUp(self): pass def tearDown(self): asyncore.close_all() def test_basic(self): d = asyncore.dispatcher() self.assertEqual(d.readable(), True) self.assertEqual(d.writable(), True) def test_repr(self): d = asyncore.dispatcher() self.assertEqual(repr(d), '<asyncore.dispatcher at %#x>' % id(d)) def test_log(self): d = asyncore.dispatcher() # capture output of dispatcher.log() (to stderr) l1 = "Lovely spam! Wonderful spam!" l2 = "I don't like spam!" with support.captured_stderr() as stderr: d.log(l1) d.log(l2) lines = stderr.getvalue().splitlines() self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2]) def test_log_info(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) l1 = "Have you got anything without spam?" l2 = "Why can't she have egg bacon spam and sausage?" l3 = "THAT'S got spam in it!" with support.captured_stdout() as stdout: d.log_info(l1, 'EGGS') d.log_info(l2) d.log_info(l3, 'SPAM') lines = stdout.getvalue().splitlines() expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3] self.assertEqual(lines, expected) def test_unhandled(self): d = asyncore.dispatcher() d.ignore_log_types = () # capture output of dispatcher.log_info() (to stdout via print) with support.captured_stdout() as stdout: d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() lines = stdout.getvalue().splitlines() expected = ['warning: unhandled incoming priority event', 'warning: unhandled read event', 'warning: unhandled write event', 'warning: unhandled connect event'] self.assertEqual(lines, expected) def test_strerror(self): # refers to bug #8573 err = asyncore._strerror(errno.EPERM) if hasattr(os, 'strerror'): self.assertEqual(err, os.strerror(errno.EPERM)) err = asyncore._strerror(-1) self.assertTrue(err != "") class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): return False def handle_connect(self): pass class DispatcherWithSendTests(unittest.TestCase): def setUp(self): pass def tearDown(self): asyncore.close_all() @support.reap_threads def test_send(self): evt = threading.Event() sock = socket.socket() sock.settimeout(3) port = support.bind_port(sock) cap = BytesIO() args = (evt, cap, sock) t = threading.Thread(target=capture_server, args=args) t.start() try: # wait a little longer for the server to initialize (it sometimes # refuses connections on slow machines without this wait) time.sleep(0.2) data = b"Suppose there isn't a 16-ton weight?" d = dispatcherwithsend_noread() d.create_socket() d.connect((support.HOST, port)) # give time for socket to connect time.sleep(0.1) d.send(data) d.send(data) d.send(b'\n') n = 1000 while d.out_buffer and n > 0: asyncore.poll() n -= 1 evt.wait() self.assertEqual(cap.getvalue(), data*2) finally: support.join_thread(t, timeout=TIMEOUT) @unittest.skipUnless(hasattr(asyncore, 'file_wrapper'), 'asyncore.file_wrapper required') class FileWrapperTest(unittest.TestCase): def setUp(self): self.d = b"It's not dead, it's sleeping!" with open(support.TESTFN, 'wb') as file: file.write(self.d) def tearDown(self): support.unlink(support.TESTFN) def test_recv(self): fd = os.open(support.TESTFN, os.O_RDONLY) w = asyncore.file_wrapper(fd) os.close(fd) self.assertNotEqual(w.fd, fd) self.assertNotEqual(w.fileno(), fd) self.assertEqual(w.recv(13), b"It's not dead") self.assertEqual(w.read(6), b", it's") w.close() self.assertRaises(OSError, w.read, 1) def test_send(self): d1 = b"Come again?" d2 = b"I want to buy some cheese." fd = os.open(support.TESTFN, os.O_WRONLY | os.O_APPEND) w = asyncore.file_wrapper(fd) os.close(fd) w.write(d1) w.send(d2) w.close() with open(support.TESTFN, 'rb') as file: self.assertEqual(file.read(), self.d + d1 + d2) @unittest.skipUnless(hasattr(asyncore, 'file_dispatcher'), 'asyncore.file_dispatcher required') def test_dispatcher(self): fd = os.open(support.TESTFN, os.O_RDONLY) data = [] class FileDispatcher(asyncore.file_dispatcher): def handle_read(self): data.append(self.recv(29)) s = FileDispatcher(fd) os.close(fd) asyncore.loop(timeout=0.01, use_poll=True, count=2) self.assertEqual(b"".join(data), self.d) def test_resource_warning(self): # Issue #11453 fd = os.open(support.TESTFN, os.O_RDONLY) f = asyncore.file_wrapper(fd) os.close(fd) with support.check_warnings(('', ResourceWarning)): f = None support.gc_collect() def test_close_twice(self): fd = os.open(support.TESTFN, os.O_RDONLY) f = asyncore.file_wrapper(fd) os.close(fd) os.close(f.fd) # file_wrapper dupped fd with self.assertRaises(OSError): f.close() self.assertEqual(f.fd, -1) # calling close twice should not fail f.close() class BaseTestHandler(asyncore.dispatcher): def __init__(self, sock=None): asyncore.dispatcher.__init__(self, sock) self.flag = False def handle_accept(self): raise Exception("handle_accept not supposed to be called") def handle_accepted(self): raise Exception("handle_accepted not supposed to be called") def handle_connect(self): raise Exception("handle_connect not supposed to be called") def handle_expt(self): raise Exception("handle_expt not supposed to be called") def handle_close(self): raise Exception("handle_close not supposed to be called") def handle_error(self): raise class BaseServer(asyncore.dispatcher): """A server which listens on an address and dispatches the connection to a handler. """ def __init__(self, family, addr, handler=BaseTestHandler): asyncore.dispatcher.__init__(self) self.create_socket(family) self.set_reuse_addr() bind_af_aware(self.socket, addr) self.listen(5) self.handler = handler @property def address(self): return self.socket.getsockname() def handle_accepted(self, sock, addr): self.handler(sock) def handle_error(self): raise class BaseClient(BaseTestHandler): def __init__(self, family, address): BaseTestHandler.__init__(self) self.create_socket(family) self.connect(address) def handle_connect(self): pass class BaseTestAPI: def tearDown(self): asyncore.close_all(ignore_all=True) def loop_waiting_for_flag(self, instance, timeout=5): timeout = float(timeout) / 100 count = 100 while asyncore.socket_map and count > 0: asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll) if instance.flag: return count -= 1 time.sleep(timeout) self.fail("flag not set") def test_handle_connect(self): # make sure handle_connect is called on connect() class TestClient(BaseClient): def handle_connect(self): self.flag = True server = BaseServer(self.family, self.addr) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_handle_accept(self): # make sure handle_accept() is called when a client connects class TestListener(BaseTestHandler): def __init__(self, family, addr): BaseTestHandler.__init__(self) self.create_socket(family) bind_af_aware(self.socket, addr) self.listen(5) self.address = self.socket.getsockname() def handle_accept(self): self.flag = True server = TestListener(self.family, self.addr) client = BaseClient(self.family, server.address) self.loop_waiting_for_flag(server) def test_handle_accepted(self): # make sure handle_accepted() is called when a client connects class TestListener(BaseTestHandler): def __init__(self, family, addr): BaseTestHandler.__init__(self) self.create_socket(family) bind_af_aware(self.socket, addr) self.listen(5) self.address = self.socket.getsockname() def handle_accept(self): asyncore.dispatcher.handle_accept(self) def handle_accepted(self, sock, addr): sock.close() self.flag = True server = TestListener(self.family, self.addr) client = BaseClient(self.family, server.address) self.loop_waiting_for_flag(server) def test_handle_read(self): # make sure handle_read is called on data received class TestClient(BaseClient): def handle_read(self): self.flag = True class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.send(b'x' * 1024) server = BaseServer(self.family, self.addr, TestHandler) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_handle_write(self): # make sure handle_write is called class TestClient(BaseClient): def handle_write(self): self.flag = True server = BaseServer(self.family, self.addr) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_handle_close(self): # make sure handle_close is called when the other end closes # the connection class TestClient(BaseClient): def handle_read(self): # in order to make handle_close be called we are supposed # to make at least one recv() call self.recv(1024) def handle_close(self): self.flag = True self.close() class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.close() server = BaseServer(self.family, self.addr, TestHandler) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_handle_close_after_conn_broken(self): # Check that ECONNRESET/EPIPE is correctly handled (issues #5661 and # #11265). data = b'\0' * 128 class TestClient(BaseClient): def handle_write(self): self.send(data) def handle_close(self): self.flag = True self.close() def handle_expt(self): self.flag = True self.close() class TestHandler(BaseTestHandler): def handle_read(self): self.recv(len(data)) self.close() def writable(self): return False server = BaseServer(self.family, self.addr, TestHandler) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) @unittest.skipIf(sys.platform.startswith("sunos"), "OOB support is broken on Solaris") def test_handle_expt(self): # Make sure handle_expt is called on OOB data received. # Note: this might fail on some platforms as OOB data is # tenuously supported and rarely used. if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") if sys.platform == "darwin" and self.use_poll: self.skipTest("poll may fail on macOS; see issue #28087") class TestClient(BaseClient): def handle_expt(self): self.socket.recv(1024, socket.MSG_OOB) self.flag = True class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB) server = BaseServer(self.family, self.addr, TestHandler) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_handle_error(self): class TestClient(BaseClient): def handle_write(self): 1.0 / 0 def handle_error(self): self.flag = True try: raise except ZeroDivisionError: pass else: raise Exception("exception not raised") server = BaseServer(self.family, self.addr) client = TestClient(self.family, server.address) self.loop_waiting_for_flag(client) def test_connection_attributes(self): server = BaseServer(self.family, self.addr) client = BaseClient(self.family, server.address) # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) # this can't be taken for granted across all platforms #self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100) self.assertFalse(server.connected) self.assertTrue(server.accepting) self.assertTrue(client.connected) self.assertFalse(client.accepting) # disconnect the client client.close() self.assertFalse(server.connected) self.assertTrue(server.accepting) self.assertFalse(client.connected) self.assertFalse(client.accepting) # stop serving server.close() self.assertFalse(server.connected) self.assertFalse(server.accepting) def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(self.family) self.assertEqual(s.socket.type, socket.SOCK_STREAM) self.assertEqual(s.socket.family, self.family) self.assertEqual(s.socket.gettimeout(), 0) self.assertFalse(s.socket.get_inheritable()) def test_bind(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") s1 = asyncore.dispatcher() s1.create_socket(self.family) s1.bind(self.addr) s1.listen(5) port = s1.socket.getsockname()[1] s2 = asyncore.dispatcher() s2.create_socket(self.family) # EADDRINUSE indicates the socket was correctly bound self.assertRaises(OSError, s2.bind, (self.addr[0], port)) def test_set_reuse_addr(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: self.skipTest("Not applicable to AF_UNIX sockets.") with socket.socket(self.family) as sock: try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except OSError: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket(self.family)) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.socket.close() s.create_socket(self.family) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) @support.reap_threads def test_quick_connect(self): # see: http://bugs.python.org/issue10340 if self.family not in (socket.AF_INET, getattr(socket, "AF_INET6", object())): self.skipTest("test specific to AF_INET and AF_INET6") server = BaseServer(self.family, self.addr) # run the thread 500 ms: the socket should be connected in 200 ms t = threading.Thread(target=lambda: asyncore.loop(timeout=0.1, count=5)) t.start() try: with socket.socket(self.family, socket.SOCK_STREAM) as s: s.settimeout(.2) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) try: s.connect(server.address) except OSError: pass finally: support.join_thread(t, timeout=TIMEOUT) class TestAPI_UseIPv4Sockets(BaseTestAPI): family = socket.AF_INET addr = (support.HOST, 0) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 support required') class TestAPI_UseIPv6Sockets(BaseTestAPI): family = socket.AF_INET6 addr = (support.HOSTv6, 0) @unittest.skipUnless(HAS_UNIX_SOCKETS, 'Unix sockets required') class TestAPI_UseUnixSockets(BaseTestAPI): if HAS_UNIX_SOCKETS: family = socket.AF_UNIX addr = support.TESTFN def tearDown(self): support.unlink(self.addr) BaseTestAPI.tearDown(self) class TestAPI_UseIPv4Select(TestAPI_UseIPv4Sockets, unittest.TestCase): use_poll = False @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') class TestAPI_UseIPv4Poll(TestAPI_UseIPv4Sockets, unittest.TestCase): use_poll = True class TestAPI_UseIPv6Select(TestAPI_UseIPv6Sockets, unittest.TestCase): use_poll = False @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') class TestAPI_UseIPv6Poll(TestAPI_UseIPv6Sockets, unittest.TestCase): use_poll = True class TestAPI_UseUnixSocketsSelect(TestAPI_UseUnixSockets, unittest.TestCase): use_poll = False @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') class TestAPI_UseUnixSocketsPoll(TestAPI_UseUnixSockets, unittest.TestCase): use_poll = True 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_hash.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_hash.py
# test the invariant that # iff a==b then hash(a)==hash(b) # # Also test that hash implementations are inherited as expected import datetime import os import sys import unittest from test.support.script_helper import assert_python_ok from collections.abc import Hashable IS_64BIT = sys.maxsize > 2**32 def lcg(x, length=16): """Linear congruential generator""" if x == 0: return bytes(length) out = bytearray(length) for i in range(length): x = (214013 * x + 2531011) & 0x7fffffff out[i] = (x >> 16) & 0xff return bytes(out) def pysiphash(uint64): """Convert SipHash24 output to Py_hash_t """ assert 0 <= uint64 < (1 << 64) # simple unsigned to signed int64 if uint64 > (1 << 63) - 1: int64 = uint64 - (1 << 64) else: int64 = uint64 # mangle uint64 to uint32 uint32 = (uint64 ^ uint64 >> 32) & 0xffffffff # simple unsigned to signed int32 if uint32 > (1 << 31) - 1: int32 = uint32 - (1 << 32) else: int32 = uint32 return int32, int64 def skip_unless_internalhash(test): """Skip decorator for tests that depend on SipHash24 or FNV""" ok = sys.hash_info.algorithm in {"fnv", "siphash24"} msg = "Requires SipHash24 or FNV" return test if ok else unittest.skip(msg)(test) class HashEqualityTestCase(unittest.TestCase): def same_hash(self, *objlist): # Hash each object given and fail if # the hash values are not all the same. hashed = list(map(hash, objlist)) for h in hashed[1:]: if h != hashed[0]: self.fail("hashed values differ: %r" % (objlist,)) def test_numeric_literals(self): self.same_hash(1, 1, 1.0, 1.0+0.0j) self.same_hash(0, 0.0, 0.0+0.0j) self.same_hash(-1, -1.0, -1.0+0.0j) self.same_hash(-2, -2.0, -2.0+0.0j) def test_coerced_integers(self): self.same_hash(int(1), int(1), float(1), complex(1), int('1'), float('1.0')) self.same_hash(int(-2**31), float(-2**31)) self.same_hash(int(1-2**31), float(1-2**31)) self.same_hash(int(2**31-1), float(2**31-1)) # for 64-bit platforms self.same_hash(int(2**31), float(2**31)) self.same_hash(int(-2**63), float(-2**63)) self.same_hash(int(2**63), float(2**63)) def test_coerced_floats(self): self.same_hash(int(1.23e300), float(1.23e300)) self.same_hash(float(0.5), complex(0.5, 0.0)) def test_unaligned_buffers(self): # The hash function for bytes-like objects shouldn't have # alignment-dependent results (example in issue #16427). b = b"123456789abcdefghijklmnopqrstuvwxyz" * 128 for i in range(16): for j in range(16): aligned = b[i:128+j] unaligned = memoryview(b)[i:128+j] self.assertEqual(hash(aligned), hash(unaligned)) _default_hash = object.__hash__ class DefaultHash(object): pass _FIXED_HASH_VALUE = 42 class FixedHash(object): def __hash__(self): return _FIXED_HASH_VALUE class OnlyEquality(object): def __eq__(self, other): return self is other class OnlyInequality(object): def __ne__(self, other): return self is not other class InheritedHashWithEquality(FixedHash, OnlyEquality): pass class InheritedHashWithInequality(FixedHash, OnlyInequality): pass class NoHash(object): __hash__ = None class HashInheritanceTestCase(unittest.TestCase): default_expected = [object(), DefaultHash(), OnlyInequality(), ] fixed_expected = [FixedHash(), InheritedHashWithEquality(), InheritedHashWithInequality(), ] error_expected = [NoHash(), OnlyEquality(), ] def test_default_hash(self): for obj in self.default_expected: self.assertEqual(hash(obj), _default_hash(obj)) def test_fixed_hash(self): for obj in self.fixed_expected: self.assertEqual(hash(obj), _FIXED_HASH_VALUE) def test_error_hash(self): for obj in self.error_expected: self.assertRaises(TypeError, hash, obj) def test_hashable(self): objects = (self.default_expected + self.fixed_expected) for obj in objects: self.assertIsInstance(obj, Hashable) def test_not_hashable(self): for obj in self.error_expected: self.assertNotIsInstance(obj, Hashable) # Issue #4701: Check that some builtin types are correctly hashable class DefaultIterSeq(object): seq = range(10) def __len__(self): return len(self.seq) def __getitem__(self, index): return self.seq[index] class HashBuiltinsTestCase(unittest.TestCase): hashes_to_check = [enumerate(range(10)), iter(DefaultIterSeq()), iter(lambda: 0, 0), ] def test_hashes(self): _default_hash = object.__hash__ for obj in self.hashes_to_check: self.assertEqual(hash(obj), _default_hash(obj)) class HashRandomizationTests: # Each subclass should define a field "repr_", containing the repr() of # an object to be tested def get_hash_command(self, repr_): return 'print(hash(eval(%a)))' % repr_ def get_hash(self, repr_, seed=None): env = os.environ.copy() env['__cleanenv'] = True # signal to assert_python not to do a copy # of os.environ on its own if seed is not None: env['PYTHONHASHSEED'] = str(seed) else: env.pop('PYTHONHASHSEED', None) out = assert_python_ok( '-c', self.get_hash_command(repr_), **env) stdout = out[1].strip() return int(stdout) def test_randomized_hash(self): # two runs should return different hashes run1 = self.get_hash(self.repr_, seed='random') run2 = self.get_hash(self.repr_, seed='random') self.assertNotEqual(run1, run2) class StringlikeHashRandomizationTests(HashRandomizationTests): repr_ = None repr_long = None # 32bit little, 64bit little, 32bit big, 64bit big known_hashes = { 'djba33x': [ # only used for small strings # seed 0, 'abc' [193485960, 193485960, 193485960, 193485960], # seed 42, 'abc' [-678966196, 573763426263223372, -820489388, -4282905804826039665], ], 'siphash24': [ # NOTE: PyUCS2 layout depends on endianness # seed 0, 'abc' [1198583518, 4596069200710135518, 1198583518, 4596069200710135518], # seed 42, 'abc' [273876886, -4501618152524544106, 273876886, -4501618152524544106], # seed 42, 'abcdefghijk' [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975], # seed 0, 'äú∑ℇ' [493570806, 5749986484189612790, -1006381564, -5915111450199468540], # seed 42, 'äú∑ℇ' [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017], ], 'fnv': [ # seed 0, 'abc' [-1600925533, 1453079729188098211, -1600925533, 1453079729188098211], # seed 42, 'abc' [-206076799, -4410911502303878509, -1024014457, -3570150969479994130], # seed 42, 'abcdefghijk' [811136751, -5046230049376118746, -77208053 , -4779029615281019666], # seed 0, 'äú∑ℇ' [44402817, 8998297579845987431, -1956240331, -782697888614047887], # seed 42, 'äú∑ℇ' [-283066365, -4576729883824601543, -271871407, -3927695501187247084], ] } def get_expected_hash(self, position, length): if length < sys.hash_info.cutoff: algorithm = "djba33x" else: algorithm = sys.hash_info.algorithm if sys.byteorder == 'little': platform = 1 if IS_64BIT else 0 else: assert(sys.byteorder == 'big') platform = 3 if IS_64BIT else 2 return self.known_hashes[algorithm][position][platform] def test_null_hash(self): # PYTHONHASHSEED=0 disables the randomized hash known_hash_of_obj = self.get_expected_hash(0, 3) # Randomization is enabled by default: self.assertNotEqual(self.get_hash(self.repr_), known_hash_of_obj) # It can also be disabled by setting the seed to 0: self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj) @skip_unless_internalhash def test_fixed_hash(self): # test a fixed seed for the randomized hash # Note that all types share the same values: h = self.get_expected_hash(1, 3) self.assertEqual(self.get_hash(self.repr_, seed=42), h) @skip_unless_internalhash def test_long_fixed_hash(self): if self.repr_long is None: return h = self.get_expected_hash(2, 11) self.assertEqual(self.get_hash(self.repr_long, seed=42), h) class StrHashRandomizationTests(StringlikeHashRandomizationTests, unittest.TestCase): repr_ = repr('abc') repr_long = repr('abcdefghijk') repr_ucs2 = repr('äú∑ℇ') @skip_unless_internalhash def test_empty_string(self): self.assertEqual(hash(""), 0) @skip_unless_internalhash def test_ucs2_string(self): h = self.get_expected_hash(3, 6) self.assertEqual(self.get_hash(self.repr_ucs2, seed=0), h) h = self.get_expected_hash(4, 6) self.assertEqual(self.get_hash(self.repr_ucs2, seed=42), h) class BytesHashRandomizationTests(StringlikeHashRandomizationTests, unittest.TestCase): repr_ = repr(b'abc') repr_long = repr(b'abcdefghijk') @skip_unless_internalhash def test_empty_string(self): self.assertEqual(hash(b""), 0) class MemoryviewHashRandomizationTests(StringlikeHashRandomizationTests, unittest.TestCase): repr_ = "memoryview(b'abc')" repr_long = "memoryview(b'abcdefghijk')" @skip_unless_internalhash def test_empty_string(self): self.assertEqual(hash(memoryview(b"")), 0) class DatetimeTests(HashRandomizationTests): def get_hash_command(self, repr_): return 'import datetime; print(hash(%s))' % repr_ class DatetimeDateTests(DatetimeTests, unittest.TestCase): repr_ = repr(datetime.date(1066, 10, 14)) class DatetimeDatetimeTests(DatetimeTests, unittest.TestCase): repr_ = repr(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) class DatetimeTimeTests(DatetimeTests, unittest.TestCase): repr_ = repr(datetime.time(0)) class HashDistributionTestCase(unittest.TestCase): def test_hash_distribution(self): # check for hash collision base = "abcdefghabcdefg" for i in range(1, len(base)): prefix = base[:i] with self.subTest(prefix=prefix): s15 = set() s255 = set() for c in range(256): h = hash(prefix + chr(c)) s15.add(h & 0xf) s255.add(h & 0xff) # SipHash24 distribution depends on key, usually > 60% self.assertGreater(len(s15), 8, prefix) self.assertGreater(len(s255), 128, prefix) 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_queue.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_queue.py
# Some simple queue module tests, plus some failure conditions # to ensure the Queue locks remain stable. import collections import itertools import queue import random import sys import threading import time import unittest import weakref from test import support try: import _queue except ImportError: _queue = None QUEUE_SIZE = 5 def qfull(q): return q.maxsize > 0 and q.qsize() == q.maxsize # A thread to run a function that unclogs a blocked Queue. class _TriggerThread(threading.Thread): def __init__(self, fn, args): self.fn = fn self.args = args self.startedEvent = threading.Event() threading.Thread.__init__(self) def run(self): # The sleep isn't necessary, but is intended to give the blocking # function in the main thread a chance at actually blocking before # we unclog it. But if the sleep is longer than the timeout-based # tests wait in their blocking functions, those tests will fail. # So we give them much longer timeout values compared to the # sleep here (I aimed at 10 seconds for blocking functions -- # they should never actually wait that long - they should make # progress as soon as we call self.fn()). time.sleep(0.1) self.startedEvent.set() self.fn(*self.args) # Execute a function that blocks, and in a separate thread, a function that # triggers the release. Returns the result of the blocking function. Caution: # block_func must guarantee to block until trigger_func is called, and # trigger_func must guarantee to change queue state so that block_func can make # enough progress to return. In particular, a block_func that just raises an # exception regardless of whether trigger_func is called will lead to # timing-dependent sporadic failures, and one of those went rarely seen but # undiagnosed for years. Now block_func must be unexceptional. If block_func # is supposed to raise an exception, call do_exceptional_blocking_test() # instead. class BlockingTestMixin: def do_blocking_test(self, block_func, block_args, trigger_func, trigger_args): thread = _TriggerThread(trigger_func, trigger_args) thread.start() try: self.result = block_func(*block_args) # If block_func returned before our thread made the call, we failed! if not thread.startedEvent.is_set(): self.fail("blocking function %r appeared not to block" % block_func) return self.result finally: support.join_thread(thread, 10) # make sure the thread terminates # Call this instead if block_func is supposed to raise an exception. def do_exceptional_blocking_test(self,block_func, block_args, trigger_func, trigger_args, expected_exception_class): thread = _TriggerThread(trigger_func, trigger_args) thread.start() try: try: block_func(*block_args) except expected_exception_class: raise else: self.fail("expected exception of kind %r" % expected_exception_class) finally: support.join_thread(thread, 10) # make sure the thread terminates if not thread.startedEvent.is_set(): self.fail("trigger thread ended but event never set") class BaseQueueTestMixin(BlockingTestMixin): def setUp(self): self.cum = 0 self.cumlock = threading.Lock() def basic_queue_test(self, q): if q.qsize(): raise RuntimeError("Call this function with an empty queue") self.assertTrue(q.empty()) self.assertFalse(q.full()) # I guess we better check things actually queue correctly a little :) q.put(111) q.put(333) q.put(222) target_order = dict(Queue = [111, 333, 222], LifoQueue = [222, 333, 111], PriorityQueue = [111, 222, 333]) actual_order = [q.get(), q.get(), q.get()] self.assertEqual(actual_order, target_order[q.__class__.__name__], "Didn't seem to queue the correct data!") for i in range(QUEUE_SIZE-1): q.put(i) self.assertTrue(q.qsize(), "Queue should not be empty") self.assertTrue(not qfull(q), "Queue should not be full") last = 2 * QUEUE_SIZE full = 3 * 2 * QUEUE_SIZE q.put(last) self.assertTrue(qfull(q), "Queue should be full") self.assertFalse(q.empty()) self.assertTrue(q.full()) try: q.put(full, block=0) self.fail("Didn't appear to block with a full queue") except queue.Full: pass try: q.put(full, timeout=0.01) self.fail("Didn't appear to time-out with a full queue") except queue.Full: pass # Test a blocking put self.do_blocking_test(q.put, (full,), q.get, ()) self.do_blocking_test(q.put, (full, True, 10), q.get, ()) # Empty it for i in range(QUEUE_SIZE): q.get() self.assertTrue(not q.qsize(), "Queue should be empty") try: q.get(block=0) self.fail("Didn't appear to block with an empty queue") except queue.Empty: pass try: q.get(timeout=0.01) self.fail("Didn't appear to time-out with an empty queue") except queue.Empty: pass # Test a blocking get self.do_blocking_test(q.get, (), q.put, ('empty',)) self.do_blocking_test(q.get, (True, 10), q.put, ('empty',)) def worker(self, q): while True: x = q.get() if x < 0: q.task_done() return with self.cumlock: self.cum += x q.task_done() def queue_join_test(self, q): self.cum = 0 threads = [] for i in (0,1): thread = threading.Thread(target=self.worker, args=(q,)) thread.start() threads.append(thread) for i in range(100): q.put(i) q.join() self.assertEqual(self.cum, sum(range(100)), "q.join() did not block until all tasks were done") for i in (0,1): q.put(-1) # instruct the threads to close q.join() # verify that you can join twice for thread in threads: thread.join() def test_queue_task_done(self): # Test to make sure a queue task completed successfully. q = self.type2test() try: q.task_done() except ValueError: pass else: self.fail("Did not detect task count going negative") def test_queue_join(self): # Test that a queue join()s successfully, and before anything else # (done twice for insurance). q = self.type2test() self.queue_join_test(q) self.queue_join_test(q) try: q.task_done() except ValueError: pass else: self.fail("Did not detect task count going negative") def test_basic(self): # Do it a couple of times on the same queue. # Done twice to make sure works with same instance reused. q = self.type2test(QUEUE_SIZE) self.basic_queue_test(q) self.basic_queue_test(q) def test_negative_timeout_raises_exception(self): q = self.type2test(QUEUE_SIZE) with self.assertRaises(ValueError): q.put(1, timeout=-1) with self.assertRaises(ValueError): q.get(1, timeout=-1) def test_nowait(self): q = self.type2test(QUEUE_SIZE) for i in range(QUEUE_SIZE): q.put_nowait(1) with self.assertRaises(queue.Full): q.put_nowait(1) for i in range(QUEUE_SIZE): q.get_nowait() with self.assertRaises(queue.Empty): q.get_nowait() def test_shrinking_queue(self): # issue 10110 q = self.type2test(3) q.put(1) q.put(2) q.put(3) with self.assertRaises(queue.Full): q.put_nowait(4) self.assertEqual(q.qsize(), 3) q.maxsize = 2 # shrink the queue with self.assertRaises(queue.Full): q.put_nowait(4) class QueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.Queue class LifoQueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.LifoQueue class PriorityQueueTest(BaseQueueTestMixin, unittest.TestCase): type2test = queue.PriorityQueue # A Queue subclass that can provoke failure at a moment's notice :) class FailingQueueException(Exception): pass class FailingQueue(queue.Queue): def __init__(self, *args): self.fail_next_put = False self.fail_next_get = False queue.Queue.__init__(self, *args) def _put(self, item): if self.fail_next_put: self.fail_next_put = False raise FailingQueueException("You Lose") return queue.Queue._put(self, item) def _get(self): if self.fail_next_get: self.fail_next_get = False raise FailingQueueException("You Lose") return queue.Queue._get(self) class FailingQueueTest(BlockingTestMixin, unittest.TestCase): def failing_queue_test(self, q): if q.qsize(): raise RuntimeError("Call this function with an empty queue") for i in range(QUEUE_SIZE-1): q.put(i) # Test a failing non-blocking put. q.fail_next_put = True try: q.put("oops", block=0) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass q.fail_next_put = True try: q.put("oops", timeout=0.1) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass q.put("last") self.assertTrue(qfull(q), "Queue should be full") # Test a failing blocking put q.fail_next_put = True try: self.do_blocking_test(q.put, ("full",), q.get, ()) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") # Test a failing timeout put q.fail_next_put = True try: self.do_exceptional_blocking_test(q.put, ("full", True, 10), q.get, (), FailingQueueException) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") self.assertTrue(qfull(q), "Queue should be full") q.get() self.assertTrue(not qfull(q), "Queue should not be full") q.put("last") self.assertTrue(qfull(q), "Queue should be full") # Test a blocking put self.do_blocking_test(q.put, ("full",), q.get, ()) # Empty it for i in range(QUEUE_SIZE): q.get() self.assertTrue(not q.qsize(), "Queue should be empty") q.put("first") q.fail_next_get = True try: q.get() self.fail("The queue didn't fail when it should have") except FailingQueueException: pass self.assertTrue(q.qsize(), "Queue should not be empty") q.fail_next_get = True try: q.get(timeout=0.1) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass self.assertTrue(q.qsize(), "Queue should not be empty") q.get() self.assertTrue(not q.qsize(), "Queue should be empty") q.fail_next_get = True try: self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), FailingQueueException) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass # put succeeded, but get failed. self.assertTrue(q.qsize(), "Queue should not be empty") q.get() self.assertTrue(not q.qsize(), "Queue should be empty") def test_failing_queue(self): # Test to make sure a queue is functioning correctly. # Done twice to the same instance. q = FailingQueue(QUEUE_SIZE) self.failing_queue_test(q) self.failing_queue_test(q) class BaseSimpleQueueTest: def setUp(self): self.q = self.type2test() def feed(self, q, seq, rnd): while True: try: val = seq.pop() except IndexError: return q.put(val) if rnd.random() > 0.5: time.sleep(rnd.random() * 1e-3) def consume(self, q, results, sentinel): while True: val = q.get() if val == sentinel: return results.append(val) def consume_nonblock(self, q, results, sentinel): while True: while True: try: val = q.get(block=False) except queue.Empty: time.sleep(1e-5) else: break if val == sentinel: return results.append(val) def consume_timeout(self, q, results, sentinel): while True: while True: try: val = q.get(timeout=1e-5) except queue.Empty: pass else: break if val == sentinel: return results.append(val) def run_threads(self, n_feeders, n_consumers, q, inputs, feed_func, consume_func): results = [] sentinel = None seq = inputs + [sentinel] * n_consumers seq.reverse() rnd = random.Random(42) exceptions = [] def log_exceptions(f): def wrapper(*args, **kwargs): try: f(*args, **kwargs) except BaseException as e: exceptions.append(e) return wrapper feeders = [threading.Thread(target=log_exceptions(feed_func), args=(q, seq, rnd)) for i in range(n_feeders)] consumers = [threading.Thread(target=log_exceptions(consume_func), args=(q, results, sentinel)) for i in range(n_consumers)] with support.start_threads(feeders + consumers): pass self.assertFalse(exceptions) self.assertTrue(q.empty()) self.assertEqual(q.qsize(), 0) return results def test_basic(self): # Basic tests for get(), put() etc. q = self.q self.assertTrue(q.empty()) self.assertEqual(q.qsize(), 0) q.put(1) self.assertFalse(q.empty()) self.assertEqual(q.qsize(), 1) q.put(2) q.put_nowait(3) q.put(4) self.assertFalse(q.empty()) self.assertEqual(q.qsize(), 4) self.assertEqual(q.get(), 1) self.assertEqual(q.qsize(), 3) self.assertEqual(q.get_nowait(), 2) self.assertEqual(q.qsize(), 2) self.assertEqual(q.get(block=False), 3) self.assertFalse(q.empty()) self.assertEqual(q.qsize(), 1) self.assertEqual(q.get(timeout=0.1), 4) self.assertTrue(q.empty()) self.assertEqual(q.qsize(), 0) with self.assertRaises(queue.Empty): q.get(block=False) with self.assertRaises(queue.Empty): q.get(timeout=1e-3) with self.assertRaises(queue.Empty): q.get_nowait() self.assertTrue(q.empty()) self.assertEqual(q.qsize(), 0) def test_negative_timeout_raises_exception(self): q = self.q q.put(1) with self.assertRaises(ValueError): q.get(timeout=-1) def test_order(self): # Test a pair of concurrent put() and get() q = self.q inputs = list(range(100)) results = self.run_threads(1, 1, q, inputs, self.feed, self.consume) # One producer, one consumer => results appended in well-defined order self.assertEqual(results, inputs) def test_many_threads(self): # Test multiple concurrent put() and get() N = 50 q = self.q inputs = list(range(10000)) results = self.run_threads(N, N, q, inputs, self.feed, self.consume) # Multiple consumers without synchronization append the # results in random order self.assertEqual(sorted(results), inputs) def test_many_threads_nonblock(self): # Test multiple concurrent put() and get(block=False) N = 50 q = self.q inputs = list(range(10000)) results = self.run_threads(N, N, q, inputs, self.feed, self.consume_nonblock) self.assertEqual(sorted(results), inputs) def test_many_threads_timeout(self): # Test multiple concurrent put() and get(timeout=...) N = 50 q = self.q inputs = list(range(1000)) results = self.run_threads(N, N, q, inputs, self.feed, self.consume_timeout) self.assertEqual(sorted(results), inputs) def test_references(self): # The queue should lose references to each item as soon as # it leaves the queue. class C: pass N = 20 q = self.q for i in range(N): q.put(C()) for i in range(N): wr = weakref.ref(q.get()) self.assertIsNone(wr()) class PySimpleQueueTest(BaseSimpleQueueTest, unittest.TestCase): type2test = queue._PySimpleQueue @unittest.skipIf(_queue is None, "No _queue module found") class CSimpleQueueTest(BaseSimpleQueueTest, unittest.TestCase): def setUp(self): self.type2test = _queue.SimpleQueue super().setUp() def test_is_default(self): self.assertIs(self.type2test, queue.SimpleQueue) def test_reentrancy(self): # bpo-14976: put() may be called reentrantly in an asynchronous # callback. q = self.q gen = itertools.count() N = 10000 results = [] # This test exploits the fact that __del__ in a reference cycle # can be called any time the GC may run. class Circular(object): def __init__(self): self.circular = self def __del__(self): q.put(next(gen)) while True: o = Circular() q.put(next(gen)) del o results.append(q.get()) if results[-1] >= N: break self.assertEqual(results, list(range(N + 1))) 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_eintr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_eintr.py
import os import signal import subprocess import sys import unittest from test import support from test.support import script_helper @unittest.skipUnless(os.name == "posix", "only supported on Unix") class EINTRTests(unittest.TestCase): @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") def test_all(self): # Run the tester in a sub-process, to make sure there is only one # thread (for reliable signal delivery). tester = support.findfile("eintr_tester.py", subdir="eintrdata") # use -u to try to get the full output if the test hangs or crash args = ["-u", tester, "-v"] if support.verbose: print() print("--- run eintr_tester.py ---", flush=True) # In verbose mode, the child process inherit stdout and stdout, # to see output in realtime and reduce the risk of losing output. args = [sys.executable, "-E", "-X", "faulthandler", *args] proc = subprocess.run(args) print(f"--- eintr_tester.py completed: " f"exit code {proc.returncode} ---", flush=True) if proc.returncode: self.fail("eintr_tester.py failed") else: script_helper.assert_python_ok("-u", tester, "-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_gnu.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dbm_gnu.py
from test import support gdbm = support.import_module("dbm.gnu") #skip if not supported import unittest import os from test.support import TESTFN, TESTFN_NONASCII, unlink filename = TESTFN class TestGdbm(unittest.TestCase): def setUp(self): self.g = None def tearDown(self): if self.g is not None: self.g.close() unlink(filename) def test_key_methods(self): self.g = gdbm.open(filename, 'c') self.assertEqual(self.g.keys(), []) self.g['a'] = 'b' self.g['12345678910'] = '019237410982340912840198242' self.g[b'bytes'] = b'data' key_set = set(self.g.keys()) self.assertEqual(key_set, set([b'a', b'bytes', b'12345678910'])) self.assertIn('a', self.g) self.assertIn(b'a', self.g) self.assertEqual(self.g[b'bytes'], b'data') key = self.g.firstkey() while key: self.assertIn(key, key_set) key_set.remove(key) key = self.g.nextkey(key) # get() and setdefault() work as in the dict interface self.assertEqual(self.g.get(b'a'), b'b') self.assertIsNone(self.g.get(b'xxx')) self.assertEqual(self.g.get(b'xxx', b'foo'), b'foo') with self.assertRaises(KeyError): self.g['xxx'] self.assertEqual(self.g.setdefault(b'xxx', b'foo'), b'foo') self.assertEqual(self.g[b'xxx'], b'foo') def test_error_conditions(self): # Try to open a non-existent database. unlink(filename) self.assertRaises(gdbm.error, gdbm.open, filename, 'r') # Try to access a closed database. self.g = gdbm.open(filename, 'c') self.g.close() self.assertRaises(gdbm.error, lambda: self.g['a']) # try pass an invalid open flag self.assertRaises(gdbm.error, lambda: gdbm.open(filename, 'rx').close()) def test_flags(self): # Test the flag parameter open() by trying all supported flag modes. all = set(gdbm.open_flags) # Test standard flags (presumably "crwn"). modes = all - set('fsu') for mode in sorted(modes): # put "c" mode first self.g = gdbm.open(filename, mode) self.g.close() # Test additional flags (presumably "fsu"). flags = all - set('crwn') for mode in modes: for flag in flags: self.g = gdbm.open(filename, mode + flag) self.g.close() def test_reorganize(self): self.g = gdbm.open(filename, 'c') size0 = os.path.getsize(filename) # bpo-33901: on macOS with gdbm 1.15, an empty database uses 16 MiB # and adding an entry of 10,000 B has no effect on the file size. # Add size0 bytes to make sure that the file size changes. value_size = max(size0, 10000) self.g['x'] = 'x' * value_size size1 = os.path.getsize(filename) self.assertGreater(size1, size0) del self.g['x'] # 'size' is supposed to be the same even after deleting an entry. self.assertEqual(os.path.getsize(filename), size1) self.g.reorganize() size2 = os.path.getsize(filename) self.assertLess(size2, size1) self.assertGreaterEqual(size2, size0) def test_context_manager(self): with gdbm.open(filename, 'c') as db: db["gdbm context manager"] = "context manager" with gdbm.open(filename, 'r') as db: self.assertEqual(list(db.keys()), [b"gdbm context manager"]) with self.assertRaises(gdbm.error) as cm: db.keys() self.assertEqual(str(cm.exception), "GDBM object has already been closed") def test_bytes(self): with gdbm.open(filename, 'c') as db: db[b'bytes key \xbd'] = b'bytes value \xbd' with gdbm.open(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 gdbm.open(filename, 'c') as db: db['Unicode key \U0001f40d'] = 'Unicode value \U0001f40d' with gdbm.open(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(TESTFN_NONASCII, 'requires OS support of non-ASCII encodings') def test_nonascii_filename(self): filename = TESTFN_NONASCII self.addCleanup(unlink, filename) with gdbm.open(filename, 'c') as db: db[b'key'] = b'value' self.assertTrue(os.path.exists(filename)) with gdbm.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_osx_env.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_osx_env.py
""" Test suite for OS X interpreter environment variables. """ from test.support import EnvironmentVarGuard import subprocess import sys import sysconfig import unittest @unittest.skipUnless(sys.platform == 'darwin' and sysconfig.get_config_var('WITH_NEXT_FRAMEWORK'), 'unnecessary on this platform') class OSXEnvironmentVariableTestCase(unittest.TestCase): def _check_sys(self, ev, cond, sv, val = sys.executable + 'dummy'): with EnvironmentVarGuard() as evg: subpc = [str(sys.executable), '-c', 'import sys; sys.exit(2 if "%s" %s %s else 3)' % (val, cond, sv)] # ensure environment variable does not exist evg.unset(ev) # test that test on sys.xxx normally fails rc = subprocess.call(subpc) self.assertEqual(rc, 3, "expected %s not %s %s" % (ev, cond, sv)) # set environ variable evg.set(ev, val) # test that sys.xxx has been influenced by the environ value rc = subprocess.call(subpc) self.assertEqual(rc, 2, "expected %s %s %s" % (ev, cond, sv)) def test_pythonexecutable_sets_sys_executable(self): self._check_sys('PYTHONEXECUTABLE', '==', 'sys.executable') 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_pprint.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pprint.py
# -*- coding: utf-8 -*- import collections import io import itertools import pprint import random import test.support import test.test_set import types import unittest # list, tuple and dict subclasses that do or don't overwrite __repr__ class list2(list): pass class list3(list): def __repr__(self): return list.__repr__(self) class tuple2(tuple): pass class tuple3(tuple): def __repr__(self): return tuple.__repr__(self) class set2(set): pass class set3(set): def __repr__(self): return set.__repr__(self) class frozenset2(frozenset): pass class frozenset3(frozenset): def __repr__(self): return frozenset.__repr__(self) class dict2(dict): pass class dict3(dict): def __repr__(self): return dict.__repr__(self) class Unorderable: def __repr__(self): return str(id(self)) # Class Orderable is orderable with any type class Orderable: def __init__(self, hash): self._hash = hash def __lt__(self, other): return False def __gt__(self, other): return self != other def __le__(self, other): return self == other def __ge__(self, other): return True def __eq__(self, other): return self is other def __ne__(self, other): return self is not other def __hash__(self): return self._hash class QueryTestCase(unittest.TestCase): def setUp(self): self.a = list(range(100)) self.b = list(range(200)) self.a[-12] = self.b def test_init(self): pp = pprint.PrettyPrinter() pp = pprint.PrettyPrinter(indent=4, width=40, depth=5, stream=io.StringIO(), compact=True) pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO()) with self.assertRaises(TypeError): pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True) self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1) self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0) self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1) self.assertRaises(ValueError, pprint.PrettyPrinter, width=0) def test_basic(self): # Verify .isrecursive() and .isreadable() w/o recursion pp = pprint.PrettyPrinter() for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, b"def", bytearray(b"ghi"), True, False, None, ..., self.a, self.b): # module-level convenience functions self.assertFalse(pprint.isrecursive(safe), "expected not isrecursive for %r" % (safe,)) self.assertTrue(pprint.isreadable(safe), "expected isreadable for %r" % (safe,)) # PrettyPrinter methods self.assertFalse(pp.isrecursive(safe), "expected not isrecursive for %r" % (safe,)) self.assertTrue(pp.isreadable(safe), "expected isreadable for %r" % (safe,)) def test_knotted(self): # Verify .isrecursive() and .isreadable() w/ recursion # Tie a knot. self.b[67] = self.a # Messy dict. self.d = {} self.d[0] = self.d[1] = self.d[2] = self.d pp = pprint.PrettyPrinter() for icky in self.a, self.b, self.d, (self.d, self.d): self.assertTrue(pprint.isrecursive(icky), "expected isrecursive") self.assertFalse(pprint.isreadable(icky), "expected not isreadable") self.assertTrue(pp.isrecursive(icky), "expected isrecursive") self.assertFalse(pp.isreadable(icky), "expected not isreadable") # Break the cycles. self.d.clear() del self.a[:] del self.b[:] for safe in self.a, self.b, self.d, (self.d, self.d): # module-level convenience functions self.assertFalse(pprint.isrecursive(safe), "expected not isrecursive for %r" % (safe,)) self.assertTrue(pprint.isreadable(safe), "expected isreadable for %r" % (safe,)) # PrettyPrinter methods self.assertFalse(pp.isrecursive(safe), "expected not isrecursive for %r" % (safe,)) self.assertTrue(pp.isreadable(safe), "expected isreadable for %r" % (safe,)) def test_unreadable(self): # Not recursive but not readable anyway pp = pprint.PrettyPrinter() for unreadable in type(3), pprint, pprint.isrecursive: # module-level convenience functions self.assertFalse(pprint.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,)) self.assertFalse(pprint.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,)) # PrettyPrinter methods self.assertFalse(pp.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,)) self.assertFalse(pp.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,)) def test_same_as_repr(self): # Simple objects, small containers and classes that overwrite __repr__ # For those the result should be the same as repr(). # Ahem. The docs don't say anything about that -- this appears to # be testing an implementation quirk. Starting in Python 2.5, it's # not true for dicts: pprint always sorts dicts by key now; before, # it sorted a dict display if and only if the display required # multiple lines. For that reason, dicts with more than one element # aren't tested here. for simple in (0, 0, 0+0j, 0.0, "", b"", bytearray(), (), tuple2(), tuple3(), [], list2(), list3(), set(), set2(), set3(), frozenset(), frozenset2(), frozenset3(), {}, dict2(), dict3(), self.assertTrue, pprint, -6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"), (3,), [3], {3: 6}, (1,2), [3,4], {5: 6}, tuple2((1,2)), tuple3((1,2)), tuple3(range(100)), [3,4], list2([3,4]), list3([3,4]), list3(range(100)), set({7}), set2({7}), set3({7}), frozenset({8}), frozenset2({8}), frozenset3({8}), dict2({5: 6}), dict3({5: 6}), range(10, -11, -1), True, False, None, ..., ): native = repr(simple) self.assertEqual(pprint.pformat(simple), native) self.assertEqual(pprint.pformat(simple, width=1, indent=0) .replace('\n', ' '), native) self.assertEqual(pprint.saferepr(simple), native) def test_basic_line_wrap(self): # verify basic line-wrapping operation o = {'RPM_cal': 0, 'RPM_cal2': 48059, 'Speed_cal': 0, 'controldesk_runtime_us': 0, 'main_code_runtime_us': 0, 'read_io_runtime_us': 0, 'write_io_runtime_us': 43690} exp = """\ {'RPM_cal': 0, 'RPM_cal2': 48059, 'Speed_cal': 0, 'controldesk_runtime_us': 0, 'main_code_runtime_us': 0, 'read_io_runtime_us': 0, 'write_io_runtime_us': 43690}""" for type in [dict, dict2]: self.assertEqual(pprint.pformat(type(o)), exp) o = range(100) exp = '[%s]' % ',\n '.join(map(str, o)) for type in [list, list2]: self.assertEqual(pprint.pformat(type(o)), exp) o = tuple(range(100)) exp = '(%s)' % ',\n '.join(map(str, o)) for type in [tuple, tuple2]: self.assertEqual(pprint.pformat(type(o)), exp) # indent parameter o = range(100) exp = '[ %s]' % ',\n '.join(map(str, o)) for type in [list, list2]: self.assertEqual(pprint.pformat(type(o), indent=4), exp) def test_nested_indentations(self): o1 = list(range(10)) o2 = dict(first=1, second=2, third=3) o = [o1, o2] expected = """\ [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], {'first': 1, 'second': 2, 'third': 3}]""" self.assertEqual(pprint.pformat(o, indent=4, width=42), expected) expected = """\ [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], { 'first': 1, 'second': 2, 'third': 3}]""" self.assertEqual(pprint.pformat(o, indent=4, width=41), expected) def test_width(self): expected = """\ [[[[[[1, 2, 3], '1 2']]]], {1: [1, 2, 3], 2: [12, 34]}, 'abc def ghi', ('ab cd ef',), set2({1, 23}), [[[[[1, 2, 3], '1 2']]]]]""" o = eval(expected) self.assertEqual(pprint.pformat(o, width=15), expected) self.assertEqual(pprint.pformat(o, width=16), expected) self.assertEqual(pprint.pformat(o, width=25), expected) self.assertEqual(pprint.pformat(o, width=14), """\ [[[[[[1, 2, 3], '1 ' '2']]]], {1: [1, 2, 3], 2: [12, 34]}, 'abc def ' 'ghi', ('ab cd ' 'ef',), set2({1, 23}), [[[[[1, 2, 3], '1 ' '2']]]]]""") def test_sorted_dict(self): # Starting in Python 2.5, pprint sorts dict displays by key regardless # of how small the dictionary may be. # Before the change, on 32-bit Windows pformat() gave order # 'a', 'c', 'b' here, so this test failed. d = {'a': 1, 'b': 1, 'c': 1} self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}") self.assertEqual(pprint.pformat([d, d]), "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]") # The next one is kind of goofy. The sorted order depends on the # alphabetic order of type names: "int" < "str" < "tuple". Before # Python 2.5, this was in the test_same_as_repr() test. It's worth # keeping around for now because it's one of few tests of pprint # against a crazy mix of types. self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}), r"{5: [[]], 'xy\tab\n': (3,), (): {}}") def test_ordered_dict(self): d = collections.OrderedDict() self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()') d = collections.OrderedDict([]) self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()') words = 'the quick brown fox jumped over a lazy dog'.split() d = collections.OrderedDict(zip(words, itertools.count())) self.assertEqual(pprint.pformat(d), """\ OrderedDict([('the', 0), ('quick', 1), ('brown', 2), ('fox', 3), ('jumped', 4), ('over', 5), ('a', 6), ('lazy', 7), ('dog', 8)])""") def test_mapping_proxy(self): words = 'the quick brown fox jumped over a lazy dog'.split() d = dict(zip(words, itertools.count())) m = types.MappingProxyType(d) self.assertEqual(pprint.pformat(m), """\ mappingproxy({'a': 6, 'brown': 2, 'dog': 8, 'fox': 3, 'jumped': 4, 'lazy': 7, 'over': 5, 'quick': 1, 'the': 0})""") d = collections.OrderedDict(zip(words, itertools.count())) m = types.MappingProxyType(d) self.assertEqual(pprint.pformat(m), """\ mappingproxy(OrderedDict([('the', 0), ('quick', 1), ('brown', 2), ('fox', 3), ('jumped', 4), ('over', 5), ('a', 6), ('lazy', 7), ('dog', 8)]))""") def test_subclassing(self): o = {'names with spaces': 'should be presented using repr()', 'others.should.not.be': 'like.this'} exp = """\ {'names with spaces': 'should be presented using repr()', others.should.not.be: like.this}""" self.assertEqual(DottedPrettyPrinter().pformat(o), exp) def test_set_reprs(self): self.assertEqual(pprint.pformat(set()), 'set()') self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}') self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\ {0, 1, 2, 3, 4, 5, 6}''') self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\ set2({0, 1, 2, 3, 4, 5, 6})''') self.assertEqual(pprint.pformat(set3(range(7)), width=20), 'set3({0, 1, 2, 3, 4, 5, 6})') self.assertEqual(pprint.pformat(frozenset()), 'frozenset()') self.assertEqual(pprint.pformat(frozenset(range(3))), 'frozenset({0, 1, 2})') self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\ frozenset({0, 1, 2, 3, 4, 5, 6})''') self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\ frozenset2({0, 1, 2, 3, 4, 5, 6})''') self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20), 'frozenset3({0, 1, 2, 3, 4, 5, 6})') @unittest.expectedFailure #See http://bugs.python.org/issue13907 @test.support.cpython_only def test_set_of_sets_reprs(self): # This test creates a complex arrangement of frozensets and # compares the pretty-printed repr against a string hard-coded in # the test. The hard-coded repr depends on the sort order of # frozensets. # # However, as the docs point out: "Since sets only define # partial ordering (subset relationships), the output of the # list.sort() method is undefined for lists of sets." # # In a nutshell, the test assumes frozenset({0}) will always # sort before frozenset({1}), but: # # >>> frozenset({0}) < frozenset({1}) # False # >>> frozenset({1}) < frozenset({0}) # False # # Consequently, this test is fragile and # implementation-dependent. Small changes to Python's sort # algorithm cause the test to fail when it should pass. # XXX Or changes to the dictionary implmentation... cube_repr_tgt = """\ {frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}), frozenset({0}): frozenset({frozenset(), frozenset({0, 2}), frozenset({0, 1})}), frozenset({1}): frozenset({frozenset(), frozenset({1, 2}), frozenset({0, 1})}), frozenset({2}): frozenset({frozenset(), frozenset({1, 2}), frozenset({0, 2})}), frozenset({1, 2}): frozenset({frozenset({2}), frozenset({1}), frozenset({0, 1, 2})}), frozenset({0, 2}): frozenset({frozenset({2}), frozenset({0}), frozenset({0, 1, 2})}), frozenset({0, 1}): frozenset({frozenset({0}), frozenset({1}), frozenset({0, 1, 2})}), frozenset({0, 1, 2}): frozenset({frozenset({1, 2}), frozenset({0, 2}), frozenset({0, 1})})}""" cube = test.test_set.cube(3) self.assertEqual(pprint.pformat(cube), cube_repr_tgt) cubo_repr_tgt = """\ {frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({0}), frozenset({0, 1})}), frozenset({frozenset(), frozenset({0})}), frozenset({frozenset({2}), frozenset({0, 2})})}), frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0, 1}), frozenset({0, 1, 2})}), frozenset({frozenset({0}), frozenset({0, 1})}), frozenset({frozenset({1}), frozenset({1, 2})}), frozenset({frozenset(), frozenset({1})})}), frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({2}), frozenset({1, 2})}), frozenset({frozenset(), frozenset({1})}), frozenset({frozenset({1}), frozenset({0, 1})})}), frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({1}), frozenset({1, 2})}), frozenset({frozenset({2}), frozenset({0, 2})}), frozenset({frozenset(), frozenset({2})})}), frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}), frozenset({0, 1})}), frozenset({frozenset({0}), frozenset({0, 2})}), frozenset({frozenset(), frozenset({1})}), frozenset({frozenset(), frozenset({2})})}), frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(), frozenset({0})}), frozenset({frozenset({1}), frozenset({1, 2})}), frozenset({frozenset(), frozenset({2})}), frozenset({frozenset({1}), frozenset({0, 1})})}), frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}), frozenset({1, 2})}), frozenset({frozenset(), frozenset({0})}), frozenset({frozenset(), frozenset({1})}), frozenset({frozenset({2}), frozenset({0, 2})})}), frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({0, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({0}), frozenset({0, 1})}), frozenset({frozenset({1}), frozenset({0, 1})})}), frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(), frozenset({0})}), frozenset({frozenset({0, 1}), frozenset({0, 1, 2})}), frozenset({frozenset({0}), frozenset({0, 2})}), frozenset({frozenset({1}), frozenset({0, 1})})}), frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({2}), frozenset({1, 2})}), frozenset({frozenset({0}), frozenset({0, 2})}), frozenset({frozenset(), frozenset({2})})}), frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({0, 1}), frozenset({0, 1, 2})}), frozenset({frozenset({0}), frozenset({0, 2})}), frozenset({frozenset({2}), frozenset({0, 2})})}), frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0, 2}), frozenset({0, 1, 2})}), frozenset({frozenset({0, 1}), frozenset({0, 1, 2})}), frozenset({frozenset({2}), frozenset({1, 2})}), frozenset({frozenset({1}), frozenset({1, 2})})})}""" cubo = test.test_set.linegraph(cube) self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt) def test_depth(self): nested_tuple = (1, (2, (3, (4, (5, 6))))) nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}} nested_list = [1, [2, [3, [4, [5, [6, []]]]]]] self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple)) self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict)) self.assertEqual(pprint.pformat(nested_list), repr(nested_list)) lv1_tuple = '(1, (...))' lv1_dict = '{1: {...}}' lv1_list = '[1, [...]]' self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple) self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict) self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list) def test_sort_unorderable_values(self): # Issue 3976: sorted pprints fail for unorderable values. n = 20 keys = [Unorderable() for i in range(n)] random.shuffle(keys) skeys = sorted(keys, key=id) clean = lambda s: s.replace(' ', '').replace('\n','') self.assertEqual(clean(pprint.pformat(set(keys))), '{' + ','.join(map(repr, skeys)) + '}') self.assertEqual(clean(pprint.pformat(frozenset(keys))), 'frozenset({' + ','.join(map(repr, skeys)) + '})') self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))), '{' + ','.join('%r:None' % k for k in skeys) + '}') # Issue 10017: TypeError on user-defined types as dict keys. self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}), '{1: 0, ' + repr(Unorderable) +': 0}') # Issue 14998: TypeError on tuples with NoneTypes as dict keys. keys = [(1,), (None,)] self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)), '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id))) def test_sort_orderable_and_unorderable_values(self): # Issue 22721: sorted pprints is not stable a = Unorderable() b = Orderable(hash(a)) # should have the same hash value # self-test self.assertLess(a, b) self.assertLess(str(type(b)), str(type(a))) self.assertEqual(sorted([b, a]), [a, b]) self.assertEqual(sorted([a, b]), [a, b]) # set self.assertEqual(pprint.pformat(set([b, a]), width=1), '{%r,\n %r}' % (a, b)) self.assertEqual(pprint.pformat(set([a, b]), width=1), '{%r,\n %r}' % (a, b)) # dict self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1), '{%r: None,\n %r: None}' % (a, b)) self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1), '{%r: None,\n %r: None}' % (a, b)) def test_str_wrap(self): # pprint tries to wrap strings intelligently fox = 'the quick brown fox jumped over a lazy dog' self.assertEqual(pprint.pformat(fox, width=19), """\ ('the quick brown ' 'fox jumped over ' 'a lazy dog')""")
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_c_locale_coercion.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
# Tests the attempted automatic coercion of the C locale to a UTF-8 locale import locale import os import shutil import subprocess import sys import sysconfig import unittest from collections import namedtuple import test.support from test.support.script_helper import ( run_python_until_end, interpreter_requires_environment, ) # Set the list of ways we expect to be able to ask for the "C" locale EXPECTED_C_LOCALE_EQUIVALENTS = ["C", "invalid.ascii"] # Set our expectation for the default encoding used in the C locale # for the filesystem encoding and the standard streams EXPECTED_C_LOCALE_STREAM_ENCODING = "ascii" EXPECTED_C_LOCALE_FS_ENCODING = "ascii" # Set our expectation for the default locale used when none is specified EXPECT_COERCION_IN_DEFAULT_LOCALE = True TARGET_LOCALES = ["C.UTF-8", "C.utf8", "UTF-8"] # Apply some platform dependent overrides if sys.platform.startswith("linux"): if test.support.is_android: # Android defaults to using UTF-8 for all system interfaces EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8" EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" else: # Linux distros typically alias the POSIX locale directly to the C # locale. # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be # able to check this case unconditionally EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX") elif sys.platform.startswith("aix"): # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1" EXPECTED_C_LOCALE_FS_ENCODING = "iso8859-1" elif sys.platform == "darwin": # FS encoding is UTF-8 on macOS EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" elif sys.platform == "cygwin": # Cygwin defaults to using C.UTF-8 # TODO: Work out a robust dynamic test for this that doesn't rely on # CPython's own locale handling machinery EXPECT_COERCION_IN_DEFAULT_LOCALE = False # Note that the above expectations are still wrong in some cases, such as: # * Windows when PYTHONLEGACYWINDOWSFSENCODING is set # * Any platform other than AIX that uses latin-1 in the C locale # * Any Linux distro where POSIX isn't a simple alias for the C locale # * Any Linux distro where the default locale is something other than "C" # # Options for dealing with this: # * Don't set the PY_COERCE_C_LOCALE preprocessor definition on # such platforms (e.g. it isn't set on Windows) # * Fix the test expectations to match the actual platform behaviour # In order to get the warning messages to match up as expected, the candidate # order here must much the target locale order in Python/pylifecycle.c _C_UTF8_LOCALES = ("C.UTF-8", "C.utf8", "UTF-8") # There's no reliable cross-platform way of checking locale alias # lists, so the only way of knowing which of these locales will work # is to try them with locale.setlocale(). We do that in a subprocess # in setUpModule() below to avoid altering the locale of the test runner. # # If the relevant locale module attributes exist, and we're not on a platform # where we expect it to always succeed, we also check that # `locale.nl_langinfo(locale.CODESET)` works, as if it fails, the interpreter # will skip locale coercion for that particular target locale _check_nl_langinfo_CODESET = bool( sys.platform not in ("darwin", "linux") and hasattr(locale, "nl_langinfo") and hasattr(locale, "CODESET") ) def _set_locale_in_subprocess(locale_name): cmd_fmt = "import locale; print(locale.setlocale(locale.LC_CTYPE, '{}'))" if _check_nl_langinfo_CODESET: # If there's no valid CODESET, we expect coercion to be skipped cmd_fmt += "; import sys; sys.exit(not locale.nl_langinfo(locale.CODESET))" cmd = cmd_fmt.format(locale_name) result, py_cmd = run_python_until_end("-c", cmd, PYTHONCOERCECLOCALE='') return result.rc == 0 _fields = "fsencoding stdin_info stdout_info stderr_info lang lc_ctype lc_all" _EncodingDetails = namedtuple("EncodingDetails", _fields) class EncodingDetails(_EncodingDetails): # XXX (ncoghlan): Using JSON for child state reporting may be less fragile CHILD_PROCESS_SCRIPT = ";".join([ "import sys, os, codecs", "print(codecs.lookup(sys.getfilesystemencoding()).name)", "print(codecs.lookup(sys.stdin.encoding).name + ':' + sys.stdin.errors)", "print(codecs.lookup(sys.stdout.encoding).name + ':' + sys.stdout.errors)", "print(codecs.lookup(sys.stderr.encoding).name + ':' + sys.stderr.errors)", "print(os.environ.get('LANG', 'not set'))", "print(os.environ.get('LC_CTYPE', 'not set'))", "print(os.environ.get('LC_ALL', 'not set'))", ]) @classmethod def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, env_vars): """Returns expected child process details for a given encoding""" _stream = stream_encoding + ":{}" # stdin and stdout should use surrogateescape either because the # coercion triggered, or because the C locale was detected stream_info = 2*[_stream.format("surrogateescape")] # stderr should always use backslashreplace stream_info.append(_stream.format("backslashreplace")) expected_lang = env_vars.get("LANG", "not set") if coercion_expected: expected_lc_ctype = CLI_COERCION_TARGET else: expected_lc_ctype = env_vars.get("LC_CTYPE", "not set") expected_lc_all = env_vars.get("LC_ALL", "not set") env_info = expected_lang, expected_lc_ctype, expected_lc_all return dict(cls(fs_encoding, *stream_info, *env_info)._asdict()) @classmethod def get_child_details(cls, env_vars): """Retrieves fsencoding and standard stream details from a child process Returns (encoding_details, stderr_lines): - encoding_details: EncodingDetails for eager decoding - stderr_lines: result of calling splitlines() on the stderr output The child is run in isolated mode if the current interpreter supports that. """ result, py_cmd = run_python_until_end( "-X", "utf8=0", "-c", cls.CHILD_PROCESS_SCRIPT, **env_vars ) if not result.rc == 0: result.fail(py_cmd) # All subprocess outputs in this test case should be pure ASCII stdout_lines = result.out.decode("ascii").splitlines() child_encoding_details = dict(cls(*stdout_lines)._asdict()) stderr_lines = result.err.decode("ascii").rstrip().splitlines() return child_encoding_details, stderr_lines # Details of the shared library warning emitted at runtime LEGACY_LOCALE_WARNING = ( "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII " "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, " "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible " "locales is recommended." ) # Details of the CLI locale coercion warning emitted at runtime CLI_COERCION_WARNING_FMT = ( "Python detected LC_CTYPE=C: LC_CTYPE coerced to {} (set another locale " "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior)." ) AVAILABLE_TARGETS = None CLI_COERCION_TARGET = None CLI_COERCION_WARNING = None def setUpModule(): global AVAILABLE_TARGETS global CLI_COERCION_TARGET global CLI_COERCION_WARNING if AVAILABLE_TARGETS is not None: # initialization already done return AVAILABLE_TARGETS = [] # Find the target locales available in the current system for target_locale in _C_UTF8_LOCALES: if _set_locale_in_subprocess(target_locale): AVAILABLE_TARGETS.append(target_locale) if AVAILABLE_TARGETS: # Coercion is expected to use the first available target locale CLI_COERCION_TARGET = AVAILABLE_TARGETS[0] CLI_COERCION_WARNING = CLI_COERCION_WARNING_FMT.format(CLI_COERCION_TARGET) class _LocaleHandlingTestCase(unittest.TestCase): # Base class to check expected locale handling behaviour def _check_child_encoding_details(self, env_vars, expected_fs_encoding, expected_stream_encoding, expected_warnings, coercion_expected): """Check the C locale handling for the given process environment Parameters: expected_fs_encoding: expected sys.getfilesystemencoding() result expected_stream_encoding: expected encoding for standard streams expected_warning: stderr output to expect (if any) """ result = EncodingDetails.get_child_details(env_vars) encoding_details, stderr_lines = result expected_details = EncodingDetails.get_expected_details( coercion_expected, expected_fs_encoding, expected_stream_encoding, env_vars ) self.assertEqual(encoding_details, expected_details) if expected_warnings is None: expected_warnings = [] self.assertEqual(stderr_lines, expected_warnings) class LocaleConfigurationTests(_LocaleHandlingTestCase): # Test explicit external configuration via the process environment @classmethod def setUpClass(cls): # This relies on setUpModule() having been run, so it can't be # handled via the @unittest.skipUnless decorator if not AVAILABLE_TARGETS: raise unittest.SkipTest("No C-with-UTF-8 locale available") def test_external_target_locale_configuration(self): # Explicitly setting a target locale should give the same behaviour as # is seen when implicitly coercing to that target locale self.maxDiff = None expected_fs_encoding = "utf-8" expected_stream_encoding = "utf-8" base_var_dict = { "LANG": "", "LC_CTYPE": "", "LC_ALL": "", "PYTHONCOERCECLOCALE": "", } for env_var in ("LANG", "LC_CTYPE"): for locale_to_set in AVAILABLE_TARGETS: # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as # expected, so skip that combination for now # See https://bugs.python.org/issue30672 for discussion if env_var == "LANG" and locale_to_set == "UTF-8": continue with self.subTest(env_var=env_var, configured_locale=locale_to_set): var_dict = base_var_dict.copy() var_dict[env_var] = locale_to_set self._check_child_encoding_details(var_dict, expected_fs_encoding, expected_stream_encoding, expected_warnings=None, coercion_expected=False) @test.support.cpython_only @unittest.skipUnless(sysconfig.get_config_var("PY_COERCE_C_LOCALE"), "C locale coercion disabled at build time") class LocaleCoercionTests(_LocaleHandlingTestCase): # Test implicit reconfiguration of the environment during CLI startup def _check_c_locale_coercion(self, fs_encoding, stream_encoding, coerce_c_locale, expected_warnings=None, coercion_expected=True, **extra_vars): """Check the C locale handling for various configurations Parameters: fs_encoding: expected sys.getfilesystemencoding() result stream_encoding: expected encoding for standard streams coerce_c_locale: setting to use for PYTHONCOERCECLOCALE None: don't set the variable at all str: the value set in the child's environment expected_warnings: expected warning lines on stderr extra_vars: additional environment variables to set in subprocess """ self.maxDiff = None if not AVAILABLE_TARGETS: # Locale coercion is disabled when there aren't any target locales fs_encoding = EXPECTED_C_LOCALE_FS_ENCODING stream_encoding = EXPECTED_C_LOCALE_STREAM_ENCODING coercion_expected = False if expected_warnings: expected_warnings = [LEGACY_LOCALE_WARNING] base_var_dict = { "LANG": "", "LC_CTYPE": "", "LC_ALL": "", "PYTHONCOERCECLOCALE": "", } base_var_dict.update(extra_vars) if coerce_c_locale is not None: base_var_dict["PYTHONCOERCECLOCALE"] = coerce_c_locale # Check behaviour for the default locale with self.subTest(default_locale=True, PYTHONCOERCECLOCALE=coerce_c_locale): if EXPECT_COERCION_IN_DEFAULT_LOCALE: _expected_warnings = expected_warnings _coercion_expected = coercion_expected else: _expected_warnings = None _coercion_expected = False # On Android CLI_COERCION_WARNING is not printed when all the # locale environment variables are undefined or empty. When # this code path is run with environ['LC_ALL'] == 'C', then # LEGACY_LOCALE_WARNING is printed. if (test.support.is_android and _expected_warnings == [CLI_COERCION_WARNING]): _expected_warnings = None self._check_child_encoding_details(base_var_dict, fs_encoding, stream_encoding, _expected_warnings, _coercion_expected) # Check behaviour for explicitly configured locales for locale_to_set in EXPECTED_C_LOCALE_EQUIVALENTS: for env_var in ("LANG", "LC_CTYPE"): with self.subTest(env_var=env_var, nominal_locale=locale_to_set, PYTHONCOERCECLOCALE=coerce_c_locale): var_dict = base_var_dict.copy() var_dict[env_var] = locale_to_set # Check behaviour on successful coercion self._check_child_encoding_details(var_dict, fs_encoding, stream_encoding, expected_warnings, coercion_expected) def test_PYTHONCOERCECLOCALE_not_set(self): # This should coerce to the first available target locale by default self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=None) def test_PYTHONCOERCECLOCALE_not_zero(self): # *Any* string other than "0" is considered "set" for our purposes # and hence should result in the locale coercion being enabled for setting in ("", "1", "true", "false"): self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=setting) def test_PYTHONCOERCECLOCALE_set_to_warn(self): # PYTHONCOERCECLOCALE=warn enables runtime warnings for legacy locales self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale="warn", expected_warnings=[CLI_COERCION_WARNING]) def test_PYTHONCOERCECLOCALE_set_to_zero(self): # The setting "0" should result in the locale coercion being disabled self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING, EXPECTED_C_LOCALE_STREAM_ENCODING, coerce_c_locale="0", coercion_expected=False) # Setting LC_ALL=C shouldn't make any difference to the behaviour self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING, EXPECTED_C_LOCALE_STREAM_ENCODING, coerce_c_locale="0", LC_ALL="C", coercion_expected=False) def test_LC_ALL_set_to_C(self): # Setting LC_ALL should render the locale coercion ineffective self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING, EXPECTED_C_LOCALE_STREAM_ENCODING, coerce_c_locale=None, LC_ALL="C", coercion_expected=False) # And result in a warning about a lack of locale compatibility self._check_c_locale_coercion(EXPECTED_C_LOCALE_FS_ENCODING, EXPECTED_C_LOCALE_STREAM_ENCODING, coerce_c_locale="warn", LC_ALL="C", expected_warnings=[LEGACY_LOCALE_WARNING], coercion_expected=False) def test_PYTHONCOERCECLOCALE_set_to_one(self): # skip the test if the LC_CTYPE locale is C or coerced old_loc = locale.setlocale(locale.LC_CTYPE, None) self.addCleanup(locale.setlocale, locale.LC_CTYPE, old_loc) loc = locale.setlocale(locale.LC_CTYPE, "") if loc == "C": self.skipTest("test requires LC_CTYPE locale different than C") if loc in TARGET_LOCALES : self.skipTest("coerced LC_CTYPE locale: %s" % loc) # bpo-35336: PYTHONCOERCECLOCALE=1 must not coerce the LC_CTYPE locale # if it's not equal to "C" code = 'import locale; print(locale.setlocale(locale.LC_CTYPE, None))' env = dict(os.environ, PYTHONCOERCECLOCALE='1') cmd = subprocess.run([sys.executable, '-c', code], stdout=subprocess.PIPE, env=env, text=True) self.assertEqual(cmd.stdout.rstrip(), loc) def test_main(): test.support.run_unittest( LocaleConfigurationTests, LocaleCoercionTests ) test.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_nntplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_nntplib.py
import io import socket import datetime import textwrap import unittest import functools import contextlib import os.path import re import threading from test import support from nntplib import NNTP, GroupInfo import nntplib from unittest.mock import patch try: import ssl except ImportError: ssl = None TIMEOUT = 30 certfile = os.path.join(os.path.dirname(__file__), 'keycert3.pem') if ssl is not None: SSLError = ssl.SSLError else: class SSLError(Exception): """Non-existent exception class when we lack SSL support.""" reason = "This will never be raised." # TODO: # - test the `file` arg to more commands # - test error conditions # - test auth and `usenetrc` class NetworkedNNTPTestsMixin: def test_welcome(self): welcome = self.server.getwelcome() self.assertEqual(str, type(welcome)) def test_help(self): resp, lines = self.server.help() self.assertTrue(resp.startswith("100 "), resp) for line in lines: self.assertEqual(str, type(line)) def test_list(self): resp, groups = self.server.list() if len(groups) > 0: self.assertEqual(GroupInfo, type(groups[0])) self.assertEqual(str, type(groups[0].group)) def test_list_active(self): resp, groups = self.server.list(self.GROUP_PAT) if len(groups) > 0: self.assertEqual(GroupInfo, type(groups[0])) self.assertEqual(str, type(groups[0].group)) def test_unknown_command(self): with self.assertRaises(nntplib.NNTPPermanentError) as cm: self.server._shortcmd("XYZZY") resp = cm.exception.response self.assertTrue(resp.startswith("500 "), resp) def test_newgroups(self): # gmane gets a constant influx of new groups. In order not to stress # the server too much, we choose a recent date in the past. dt = datetime.date.today() - datetime.timedelta(days=7) resp, groups = self.server.newgroups(dt) if len(groups) > 0: self.assertIsInstance(groups[0], GroupInfo) self.assertIsInstance(groups[0].group, str) def test_description(self): def _check_desc(desc): # Sanity checks self.assertIsInstance(desc, str) self.assertNotIn(self.GROUP_NAME, desc) desc = self.server.description(self.GROUP_NAME) _check_desc(desc) # Another sanity check self.assertIn("Python", desc) # With a pattern desc = self.server.description(self.GROUP_PAT) _check_desc(desc) # Shouldn't exist desc = self.server.description("zk.brrtt.baz") self.assertEqual(desc, '') def test_descriptions(self): resp, descs = self.server.descriptions(self.GROUP_PAT) # 215 for LIST NEWSGROUPS, 282 for XGTITLE self.assertTrue( resp.startswith("215 ") or resp.startswith("282 "), resp) self.assertIsInstance(descs, dict) desc = descs[self.GROUP_NAME] self.assertEqual(desc, self.server.description(self.GROUP_NAME)) def test_group(self): result = self.server.group(self.GROUP_NAME) self.assertEqual(5, len(result)) resp, count, first, last, group = result self.assertEqual(group, self.GROUP_NAME) self.assertIsInstance(count, int) self.assertIsInstance(first, int) self.assertIsInstance(last, int) self.assertLessEqual(first, last) self.assertTrue(resp.startswith("211 "), resp) def test_date(self): resp, date = self.server.date() self.assertIsInstance(date, datetime.datetime) # Sanity check self.assertGreaterEqual(date.year, 1995) self.assertLessEqual(date.year, 2030) def _check_art_dict(self, art_dict): # Some sanity checks for a field dictionary returned by OVER / XOVER self.assertIsInstance(art_dict, dict) # NNTP has 7 mandatory fields self.assertGreaterEqual(art_dict.keys(), {"subject", "from", "date", "message-id", "references", ":bytes", ":lines"} ) for v in art_dict.values(): self.assertIsInstance(v, (str, type(None))) def test_xover(self): resp, count, first, last, name = self.server.group(self.GROUP_NAME) resp, lines = self.server.xover(last - 5, last) if len(lines) == 0: self.skipTest("no articles retrieved") # The 'last' article is not necessarily part of the output (cancelled?) art_num, art_dict = lines[0] self.assertGreaterEqual(art_num, last - 5) self.assertLessEqual(art_num, last) self._check_art_dict(art_dict) @unittest.skipIf(True, 'temporarily skipped until a permanent solution' ' is found for issue #28971') def test_over(self): resp, count, first, last, name = self.server.group(self.GROUP_NAME) start = last - 10 # The "start-" article range form resp, lines = self.server.over((start, None)) art_num, art_dict = lines[0] self._check_art_dict(art_dict) # The "start-end" article range form resp, lines = self.server.over((start, last)) art_num, art_dict = lines[-1] # The 'last' article is not necessarily part of the output (cancelled?) self.assertGreaterEqual(art_num, start) self.assertLessEqual(art_num, last) self._check_art_dict(art_dict) # XXX The "message_id" form is unsupported by gmane # 503 Overview by message-ID unsupported def test_xhdr(self): resp, count, first, last, name = self.server.group(self.GROUP_NAME) resp, lines = self.server.xhdr('subject', last) for line in lines: self.assertEqual(str, type(line[1])) def check_article_resp(self, resp, article, art_num=None): self.assertIsInstance(article, nntplib.ArticleInfo) if art_num is not None: self.assertEqual(article.number, art_num) for line in article.lines: self.assertIsInstance(line, bytes) # XXX this could exceptionally happen... self.assertNotIn(article.lines[-1], (b".", b".\n", b".\r\n")) @unittest.skipIf(True, "FIXME: see bpo-32128") def test_article_head_body(self): resp, count, first, last, name = self.server.group(self.GROUP_NAME) # Try to find an available article for art_num in (last, first, last - 1): try: resp, head = self.server.head(art_num) except nntplib.NNTPTemporaryError as e: if not e.response.startswith("423 "): raise # "423 No such article" => choose another one continue break else: self.skipTest("could not find a suitable article number") self.assertTrue(resp.startswith("221 "), resp) self.check_article_resp(resp, head, art_num) resp, body = self.server.body(art_num) self.assertTrue(resp.startswith("222 "), resp) self.check_article_resp(resp, body, art_num) resp, article = self.server.article(art_num) self.assertTrue(resp.startswith("220 "), resp) self.check_article_resp(resp, article, art_num) # Tolerate running the tests from behind a NNTP virus checker blacklist = lambda line: line.startswith(b'X-Antivirus') filtered_head_lines = [line for line in head.lines if not blacklist(line)] filtered_lines = [line for line in article.lines if not blacklist(line)] self.assertEqual(filtered_lines, filtered_head_lines + [b''] + body.lines) def test_capabilities(self): # The server under test implements NNTP version 2 and has a # couple of well-known capabilities. Just sanity check that we # got them. def _check_caps(caps): caps_list = caps['LIST'] self.assertIsInstance(caps_list, (list, tuple)) self.assertIn('OVERVIEW.FMT', caps_list) self.assertGreaterEqual(self.server.nntp_version, 2) _check_caps(self.server.getcapabilities()) # This re-emits the command resp, caps = self.server.capabilities() _check_caps(caps) def test_zlogin(self): # This test must be the penultimate because further commands will be # refused. baduser = "notarealuser" badpw = "notarealpassword" # Check that bogus credentials cause failure self.assertRaises(nntplib.NNTPError, self.server.login, user=baduser, password=badpw, usenetrc=False) # FIXME: We should check that correct credentials succeed, but that # would require valid details for some server somewhere to be in the # test suite, I think. Gmane is anonymous, at least as used for the # other tests. def test_zzquit(self): # This test must be called last, hence the name cls = type(self) try: self.server.quit() finally: cls.server = None @classmethod def wrap_methods(cls): # Wrap all methods in a transient_internet() exception catcher # XXX put a generic version in test.support? def wrap_meth(meth): @functools.wraps(meth) def wrapped(self): with support.transient_internet(self.NNTP_HOST): meth(self) return wrapped for name in dir(cls): if not name.startswith('test_'): continue meth = getattr(cls, name) if not callable(meth): continue # Need to use a closure so that meth remains bound to its current # value setattr(cls, name, wrap_meth(meth)) def test_with_statement(self): def is_connected(): if not hasattr(server, 'file'): return False try: server.help() except (OSError, EOFError): return False return True try: with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: self.assertTrue(is_connected()) self.assertTrue(server.help()) self.assertFalse(is_connected()) with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: server.quit() self.assertFalse(is_connected()) except SSLError as ssl_err: # matches "[SSL: DH_KEY_TOO_SMALL] dh key too small" if re.search(r'(?i)KEY.TOO.SMALL', ssl_err.reason): raise unittest.SkipTest(f"Got {ssl_err} connecting " f"to {self.NNTP_HOST!r}") raise NetworkedNNTPTestsMixin.wrap_methods() EOF_ERRORS = (EOFError,) if ssl is not None: EOF_ERRORS += (ssl.SSLEOFError,) class NetworkedNNTPTests(NetworkedNNTPTestsMixin, unittest.TestCase): # This server supports STARTTLS (gmane doesn't) NNTP_HOST = 'news.trigofacile.com' GROUP_NAME = 'fr.comp.lang.python' GROUP_PAT = 'fr.comp.lang.*' NNTP_CLASS = NNTP @classmethod def setUpClass(cls): support.requires("network") with support.transient_internet(cls.NNTP_HOST): try: cls.server = cls.NNTP_CLASS(cls.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) except SSLError as ssl_err: # matches "[SSL: DH_KEY_TOO_SMALL] dh key too small" if re.search(r'(?i)KEY.TOO.SMALL', ssl_err.reason): raise unittest.SkipTest(f"{cls} got {ssl_err} connecting " f"to {cls.NNTP_HOST!r}") raise except EOF_ERRORS: raise unittest.SkipTest(f"{cls} got EOF error on connecting " f"to {cls.NNTP_HOST!r}") @classmethod def tearDownClass(cls): if cls.server is not None: cls.server.quit() @unittest.skipUnless(ssl, 'requires SSL support') class NetworkedNNTP_SSLTests(NetworkedNNTPTests): # Technical limits for this public NNTP server (see http://www.aioe.org): # "Only two concurrent connections per IP address are allowed and # 400 connections per day are accepted from each IP address." NNTP_HOST = 'nntp.aioe.org' GROUP_NAME = 'comp.lang.python' GROUP_PAT = 'comp.lang.*' NNTP_CLASS = getattr(nntplib, 'NNTP_SSL', None) # Disabled as it produces too much data test_list = None # Disabled as the connection will already be encrypted. test_starttls = None # # Non-networked tests using a local server (or something mocking it). # class _NNTPServerIO(io.RawIOBase): """A raw IO object allowing NNTP commands to be received and processed by a handler. The handler can push responses which can then be read from the IO object.""" def __init__(self, handler): io.RawIOBase.__init__(self) # The channel from the client self.c2s = io.BytesIO() # The channel to the client self.s2c = io.BytesIO() self.handler = handler self.handler.start(self.c2s.readline, self.push_data) def readable(self): return True def writable(self): return True def push_data(self, data): """Push (buffer) some data to send to the client.""" pos = self.s2c.tell() self.s2c.seek(0, 2) self.s2c.write(data) self.s2c.seek(pos) def write(self, b): """The client sends us some data""" pos = self.c2s.tell() self.c2s.write(b) self.c2s.seek(pos) self.handler.process_pending() return len(b) def readinto(self, buf): """The client wants to read a response""" self.handler.process_pending() b = self.s2c.read(len(buf)) n = len(b) buf[:n] = b return n def make_mock_file(handler): sio = _NNTPServerIO(handler) # Using BufferedRWPair instead of BufferedRandom ensures the file # isn't seekable. file = io.BufferedRWPair(sio, sio) return (sio, file) class MockedNNTPTestsMixin: # Override in derived classes handler_class = None def setUp(self): super().setUp() self.make_server() def tearDown(self): super().tearDown() del self.server def make_server(self, *args, **kwargs): self.handler = self.handler_class() self.sio, file = make_mock_file(self.handler) self.server = nntplib._NNTPBase(file, 'test.server', *args, **kwargs) return self.server class MockedNNTPWithReaderModeMixin(MockedNNTPTestsMixin): def setUp(self): super().setUp() self.make_server(readermode=True) class NNTPv1Handler: """A handler for RFC 977""" welcome = "200 NNTP mock server" def start(self, readline, push_data): self.in_body = False self.allow_posting = True self._readline = readline self._push_data = push_data self._logged_in = False self._user_sent = False # Our welcome self.handle_welcome() def _decode(self, data): return str(data, "utf-8", "surrogateescape") def process_pending(self): if self.in_body: while True: line = self._readline() if not line: return self.body.append(line) if line == b".\r\n": break try: meth, tokens = self.body_callback meth(*tokens, body=self.body) finally: self.body_callback = None self.body = None self.in_body = False while True: line = self._decode(self._readline()) if not line: return if not line.endswith("\r\n"): raise ValueError("line doesn't end with \\r\\n: {!r}".format(line)) line = line[:-2] cmd, *tokens = line.split() #meth = getattr(self.handler, "handle_" + cmd.upper(), None) meth = getattr(self, "handle_" + cmd.upper(), None) if meth is None: self.handle_unknown() else: try: meth(*tokens) except Exception as e: raise ValueError("command failed: {!r}".format(line)) from e else: if self.in_body: self.body_callback = meth, tokens self.body = [] def expect_body(self): """Flag that the client is expected to post a request body""" self.in_body = True def push_data(self, data): """Push some binary data""" self._push_data(data) def push_lit(self, lit): """Push a string literal""" lit = textwrap.dedent(lit) lit = "\r\n".join(lit.splitlines()) + "\r\n" lit = lit.encode('utf-8') self.push_data(lit) def handle_unknown(self): self.push_lit("500 What?") def handle_welcome(self): self.push_lit(self.welcome) def handle_QUIT(self): self.push_lit("205 Bye!") def handle_DATE(self): self.push_lit("111 20100914001155") def handle_GROUP(self, group): if group == "fr.comp.lang.python": self.push_lit("211 486 761 1265 fr.comp.lang.python") else: self.push_lit("411 No such group {}".format(group)) def handle_HELP(self): self.push_lit("""\ 100 Legal commands authinfo user Name|pass Password|generic <prog> <args> date help Report problems to <root@example.org> .""") def handle_STAT(self, message_spec=None): if message_spec is None: self.push_lit("412 No newsgroup selected") elif message_spec == "3000234": self.push_lit("223 3000234 <45223423@example.com>") elif message_spec == "<45223423@example.com>": self.push_lit("223 0 <45223423@example.com>") else: self.push_lit("430 No Such Article Found") def handle_NEXT(self): self.push_lit("223 3000237 <668929@example.org> retrieved") def handle_LAST(self): self.push_lit("223 3000234 <45223423@example.com> retrieved") def handle_LIST(self, action=None, param=None): if action is None: self.push_lit("""\ 215 Newsgroups in form "group high low flags". comp.lang.python 0000052340 0000002828 y comp.lang.python.announce 0000001153 0000000993 m free.it.comp.lang.python 0000000002 0000000002 y fr.comp.lang.python 0000001254 0000000760 y free.it.comp.lang.python.learner 0000000000 0000000001 y tw.bbs.comp.lang.python 0000000304 0000000304 y .""") elif action == "ACTIVE": if param == "*distutils*": self.push_lit("""\ 215 Newsgroups in form "group high low flags" gmane.comp.python.distutils.devel 0000014104 0000000001 m gmane.comp.python.distutils.cvs 0000000000 0000000001 m .""") else: self.push_lit("""\ 215 Newsgroups in form "group high low flags" .""") elif action == "OVERVIEW.FMT": self.push_lit("""\ 215 Order of fields in overview database. Subject: From: Date: Message-ID: References: Bytes: Lines: Xref:full .""") elif action == "NEWSGROUPS": assert param is not None if param == "comp.lang.python": self.push_lit("""\ 215 Descriptions in form "group description". comp.lang.python\tThe Python computer language. .""") elif param == "comp.lang.python*": self.push_lit("""\ 215 Descriptions in form "group description". comp.lang.python.announce\tAnnouncements about the Python language. (Moderated) comp.lang.python\tThe Python computer language. .""") else: self.push_lit("""\ 215 Descriptions in form "group description". .""") else: self.push_lit('501 Unknown LIST keyword') def handle_NEWNEWS(self, group, date_str, time_str): # We hard code different return messages depending on passed # argument and date syntax. if (group == "comp.lang.python" and date_str == "20100913" and time_str == "082004"): # Date was passed in RFC 3977 format (NNTP "v2") self.push_lit("""\ 230 list of newsarticles (NNTP v2) created after Mon Sep 13 08:20:04 2010 follows <a4929a40-6328-491a-aaaf-cb79ed7309a2@q2g2000vbk.googlegroups.com> <f30c0419-f549-4218-848f-d7d0131da931@y3g2000vbm.googlegroups.com> .""") elif (group == "comp.lang.python" and date_str == "100913" and time_str == "082004"): # Date was passed in RFC 977 format (NNTP "v1") self.push_lit("""\ 230 list of newsarticles (NNTP v1) created after Mon Sep 13 08:20:04 2010 follows <a4929a40-6328-491a-aaaf-cb79ed7309a2@q2g2000vbk.googlegroups.com> <f30c0419-f549-4218-848f-d7d0131da931@y3g2000vbm.googlegroups.com> .""") elif (group == 'comp.lang.python' and date_str in ('20100101', '100101') and time_str == '090000'): self.push_lit('too long line' * 3000 + '\n.') else: self.push_lit("""\ 230 An empty list of newsarticles follows .""") # (Note for experiments: many servers disable NEWNEWS. # As of this writing, sicinfo3.epfl.ch doesn't.) def handle_XOVER(self, message_spec): if message_spec == "57-59": self.push_lit( "224 Overview information for 57-58 follows\n" "57\tRe: ANN: New Plone book with strong Python (and Zope) themes throughout" "\tDoug Hellmann <doug.hellmann-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>" "\tSat, 19 Jun 2010 18:04:08 -0400" "\t<4FD05F05-F98B-44DC-8111-C6009C925F0C@gmail.com>" "\t<hvalf7$ort$1@dough.gmane.org>\t7103\t16" "\tXref: news.gmane.io gmane.comp.python.authors:57" "\n" "58\tLooking for a few good bloggers" "\tDoug Hellmann <doug.hellmann-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>" "\tThu, 22 Jul 2010 09:14:14 -0400" "\t<A29863FA-F388-40C3-AA25-0FD06B09B5BF@gmail.com>" "\t\t6683\t16" "\t" "\n" # A UTF-8 overview line from fr.comp.lang.python "59\tRe: Message d'erreur incompréhensible (par moi)" "\tEric Brunel <eric.brunel@pragmadev.nospam.com>" "\tWed, 15 Sep 2010 18:09:15 +0200" "\t<eric.brunel-2B8B56.18091515092010@news.wanadoo.fr>" "\t<4c90ec87$0$32425$ba4acef3@reader.news.orange.fr>\t1641\t27" "\tXref: saria.nerim.net fr.comp.lang.python:1265" "\n" ".\n") else: self.push_lit("""\ 224 No articles .""") def handle_POST(self, *, body=None): if body is None: if self.allow_posting: self.push_lit("340 Input article; end with <CR-LF>.<CR-LF>") self.expect_body() else: self.push_lit("440 Posting not permitted") else: assert self.allow_posting self.push_lit("240 Article received OK") self.posted_body = body def handle_IHAVE(self, message_id, *, body=None): if body is None: if (self.allow_posting and message_id == "<i.am.an.article.you.will.want@example.com>"): self.push_lit("335 Send it; end with <CR-LF>.<CR-LF>") self.expect_body() else: self.push_lit("435 Article not wanted") else: assert self.allow_posting self.push_lit("235 Article transferred OK") self.posted_body = body sample_head = """\ From: "Demo User" <nobody@example.net> Subject: I am just a test article Content-Type: text/plain; charset=UTF-8; format=flowed Message-ID: <i.am.an.article.you.will.want@example.com>""" sample_body = """\ This is just a test article. ..Here is a dot-starting line. -- Signed by Andr\xe9.""" sample_article = sample_head + "\n\n" + sample_body def handle_ARTICLE(self, message_spec=None): if message_spec is None: self.push_lit("220 3000237 <45223423@example.com>") elif message_spec == "<45223423@example.com>": self.push_lit("220 0 <45223423@example.com>") elif message_spec == "3000234": self.push_lit("220 3000234 <45223423@example.com>") else: self.push_lit("430 No Such Article Found") return self.push_lit(self.sample_article) self.push_lit(".") def handle_HEAD(self, message_spec=None): if message_spec is None: self.push_lit("221 3000237 <45223423@example.com>") elif message_spec == "<45223423@example.com>": self.push_lit("221 0 <45223423@example.com>") elif message_spec == "3000234": self.push_lit("221 3000234 <45223423@example.com>") else: self.push_lit("430 No Such Article Found") return self.push_lit(self.sample_head) self.push_lit(".") def handle_BODY(self, message_spec=None): if message_spec is None: self.push_lit("222 3000237 <45223423@example.com>") elif message_spec == "<45223423@example.com>": self.push_lit("222 0 <45223423@example.com>") elif message_spec == "3000234": self.push_lit("222 3000234 <45223423@example.com>") else: self.push_lit("430 No Such Article Found") return self.push_lit(self.sample_body) self.push_lit(".") def handle_AUTHINFO(self, cred_type, data): if self._logged_in: self.push_lit('502 Already Logged In') elif cred_type == 'user': if self._user_sent: self.push_lit('482 User Credential Already Sent') else: self.push_lit('381 Password Required') self._user_sent = True elif cred_type == 'pass': self.push_lit('281 Login Successful') self._logged_in = True else: raise Exception('Unknown cred type {}'.format(cred_type)) class NNTPv2Handler(NNTPv1Handler): """A handler for RFC 3977 (NNTP "v2")""" def handle_CAPABILITIES(self): fmt = """\ 101 Capability list: VERSION 2 3 IMPLEMENTATION INN 2.5.1{} HDR LIST ACTIVE ACTIVE.TIMES DISTRIB.PATS HEADERS NEWSGROUPS OVERVIEW.FMT OVER POST READER .""" if not self._logged_in: self.push_lit(fmt.format('\n AUTHINFO USER')) else: self.push_lit(fmt.format('')) def handle_MODE(self, _): raise Exception('MODE READER sent despite READER has been advertised') def handle_OVER(self, message_spec=None): return self.handle_XOVER(message_spec) class CapsAfterLoginNNTPv2Handler(NNTPv2Handler): """A handler that allows CAPABILITIES only after login""" def handle_CAPABILITIES(self): if not self._logged_in: self.push_lit('480 You must log in.') else: super().handle_CAPABILITIES() class ModeSwitchingNNTPv2Handler(NNTPv2Handler): """A server that starts in transit mode""" def __init__(self): self._switched = False def handle_CAPABILITIES(self): fmt = """\ 101 Capability list: VERSION 2 3 IMPLEMENTATION INN 2.5.1 HDR LIST ACTIVE ACTIVE.TIMES DISTRIB.PATS HEADERS NEWSGROUPS OVERVIEW.FMT OVER POST {}READER .""" if self._switched: self.push_lit(fmt.format('')) else: self.push_lit(fmt.format('MODE-')) def handle_MODE(self, what): assert not self._switched and what == 'reader' self._switched = True self.push_lit('200 Posting allowed') class NNTPv1v2TestsMixin: def setUp(self): super().setUp() def test_welcome(self): self.assertEqual(self.server.welcome, self.handler.welcome) def test_authinfo(self): if self.nntp_version == 2: self.assertIn('AUTHINFO', self.server._caps) self.server.login('testuser', 'testpw') # if AUTHINFO is gone from _caps we also know that getcapabilities() # has been called after login as it should self.assertNotIn('AUTHINFO', self.server._caps) def test_date(self): resp, date = self.server.date() self.assertEqual(resp, "111 20100914001155") self.assertEqual(date, datetime.datetime(2010, 9, 14, 0, 11, 55)) def test_quit(self): self.assertFalse(self.sio.closed) resp = self.server.quit() self.assertEqual(resp, "205 Bye!") self.assertTrue(self.sio.closed) def test_help(self): resp, help = self.server.help() self.assertEqual(resp, "100 Legal commands") self.assertEqual(help, [ ' authinfo user Name|pass Password|generic <prog> <args>', ' date', ' help', 'Report problems to <root@example.org>', ]) def test_list(self): resp, groups = self.server.list() self.assertEqual(len(groups), 6) g = groups[1] self.assertEqual(g, GroupInfo("comp.lang.python.announce", "0000001153", "0000000993", "m")) resp, groups = self.server.list("*distutils*") self.assertEqual(len(groups), 2) g = groups[0] self.assertEqual(g, GroupInfo("gmane.comp.python.distutils.devel", "0000014104", "0000000001", "m")) def test_stat(self): resp, art_num, message_id = self.server.stat(3000234) self.assertEqual(resp, "223 3000234 <45223423@example.com>") self.assertEqual(art_num, 3000234) self.assertEqual(message_id, "<45223423@example.com>") resp, art_num, message_id = self.server.stat("<45223423@example.com>") self.assertEqual(resp, "223 0 <45223423@example.com>") self.assertEqual(art_num, 0) self.assertEqual(message_id, "<45223423@example.com>") with self.assertRaises(nntplib.NNTPTemporaryError) as cm: self.server.stat("<non.existent.id>") self.assertEqual(cm.exception.response, "430 No Such Article Found") with self.assertRaises(nntplib.NNTPTemporaryError) as cm: self.server.stat() self.assertEqual(cm.exception.response, "412 No newsgroup selected") def test_next(self): resp, art_num, message_id = self.server.next() self.assertEqual(resp, "223 3000237 <668929@example.org> retrieved") self.assertEqual(art_num, 3000237) self.assertEqual(message_id, "<668929@example.org>") def test_last(self): resp, art_num, message_id = self.server.last() self.assertEqual(resp, "223 3000234 <45223423@example.com> retrieved") self.assertEqual(art_num, 3000234) self.assertEqual(message_id, "<45223423@example.com>")
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_codecs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecs.py
import codecs import contextlib import io import locale import sys import unittest import encodings from unittest import mock from test import support try: import ctypes except ImportError: ctypes = None SIZEOF_WCHAR_T = -1 else: SIZEOF_WCHAR_T = ctypes.sizeof(ctypes.c_wchar) def coding_checker(self, coder): def check(input, expect): self.assertEqual(coder(input), (expect, len(input))) return check class Queue(object): """ queue: write bytes at one end, read bytes from the other end """ def __init__(self, buffer): self._buffer = buffer def write(self, chars): self._buffer += chars def read(self, size=-1): if size<0: s = self._buffer self._buffer = self._buffer[:0] # make empty return s else: s = self._buffer[:size] self._buffer = self._buffer[size:] return s class MixInCheckStateHandling: def check_state_handling_decode(self, encoding, u, s): for i in range(len(s)+1): d = codecs.getincrementaldecoder(encoding)() part1 = d.decode(s[:i]) state = d.getstate() self.assertIsInstance(state[1], int) # Check that the condition stated in the documentation for # IncrementalDecoder.getstate() holds if not state[1]: # reset decoder to the default state without anything buffered d.setstate((state[0][:0], 0)) # Feeding the previous input may not produce any output self.assertTrue(not d.decode(state[0])) # The decoder must return to the same state self.assertEqual(state, d.getstate()) # Create a new decoder and set it to the state # we extracted from the old one d = codecs.getincrementaldecoder(encoding)() d.setstate(state) part2 = d.decode(s[i:], True) self.assertEqual(u, part1+part2) def check_state_handling_encode(self, encoding, u, s): for i in range(len(u)+1): d = codecs.getincrementalencoder(encoding)() part1 = d.encode(u[:i]) state = d.getstate() d = codecs.getincrementalencoder(encoding)() d.setstate(state) part2 = d.encode(u[i:], True) self.assertEqual(s, part1+part2) class ReadTest(MixInCheckStateHandling): def check_partial(self, input, partialresults): # get a StreamReader for the encoding and feed the bytestring version # of input to the reader byte by byte. Read everything available from # the StreamReader and check that the results equal the appropriate # entries from partialresults. q = Queue(b"") r = codecs.getreader(self.encoding)(q) result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): q.write(bytes([c])) result += r.read() self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(r.read(), "") self.assertEqual(r.bytebuffer, b"") # do the check again, this time using an incremental decoder d = codecs.getincrementaldecoder(self.encoding)() result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(bytes([c])) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode(b"", True), "") self.assertEqual(d.buffer, b"") # Check whether the reset method works properly d.reset() result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(bytes([c])) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode(b"", True), "") self.assertEqual(d.buffer, b"") # check iterdecode() encoded = input.encode(self.encoding) self.assertEqual( input, "".join(codecs.iterdecode([bytes([c]) for c in encoded], self.encoding)) ) def test_readline(self): def getreader(input): stream = io.BytesIO(input.encode(self.encoding)) return codecs.getreader(self.encoding)(stream) def readalllines(input, keepends=True, size=None): reader = getreader(input) lines = [] while True: line = reader.readline(size=size, keepends=keepends) if not line: break lines.append(line) return "|".join(lines) s = "foo\nbar\r\nbaz\rspam\u2028eggs" sexpected = "foo\n|bar\r\n|baz\r|spam\u2028|eggs" sexpectednoends = "foo|bar|baz|spam|eggs" self.assertEqual(readalllines(s, True), sexpected) self.assertEqual(readalllines(s, False), sexpectednoends) self.assertEqual(readalllines(s, True, 10), sexpected) self.assertEqual(readalllines(s, False, 10), sexpectednoends) lineends = ("\n", "\r\n", "\r", "\u2028") # Test long lines (multiple calls to read() in readline()) vw = [] vwo = [] for (i, lineend) in enumerate(lineends): vw.append((i*200+200)*"\u3042" + lineend) vwo.append((i*200+200)*"\u3042") self.assertEqual(readalllines("".join(vw), True), "|".join(vw)) self.assertEqual(readalllines("".join(vw), False), "|".join(vwo)) # Test lines where the first read might end with \r, so the # reader has to look ahead whether this is a lone \r or a \r\n for size in range(80): for lineend in lineends: s = 10*(size*"a" + lineend + "xxx\n") reader = getreader(s) for i in range(10): self.assertEqual( reader.readline(keepends=True), size*"a" + lineend, ) self.assertEqual( reader.readline(keepends=True), "xxx\n", ) reader = getreader(s) for i in range(10): self.assertEqual( reader.readline(keepends=False), size*"a", ) self.assertEqual( reader.readline(keepends=False), "xxx", ) def test_mixed_readline_and_read(self): lines = ["Humpty Dumpty sat on a wall,\n", "Humpty Dumpty had a great fall.\r\n", "All the king's horses and all the king's men\r", "Couldn't put Humpty together again."] data = ''.join(lines) def getreader(): stream = io.BytesIO(data.encode(self.encoding)) return codecs.getreader(self.encoding)(stream) # Issue #8260: Test readline() followed by read() f = getreader() self.assertEqual(f.readline(), lines[0]) self.assertEqual(f.read(), ''.join(lines[1:])) self.assertEqual(f.read(), '') # Issue #32110: Test readline() followed by read(n) f = getreader() self.assertEqual(f.readline(), lines[0]) self.assertEqual(f.read(1), lines[1][0]) self.assertEqual(f.read(0), '') self.assertEqual(f.read(100), data[len(lines[0]) + 1:][:100]) # Issue #16636: Test readline() followed by readlines() f = getreader() self.assertEqual(f.readline(), lines[0]) self.assertEqual(f.readlines(), lines[1:]) self.assertEqual(f.read(), '') # Test read(n) followed by read() f = getreader() self.assertEqual(f.read(size=40, chars=5), data[:5]) self.assertEqual(f.read(), data[5:]) self.assertEqual(f.read(), '') # Issue #32110: Test read(n) followed by read(n) f = getreader() self.assertEqual(f.read(size=40, chars=5), data[:5]) self.assertEqual(f.read(1), data[5]) self.assertEqual(f.read(0), '') self.assertEqual(f.read(100), data[6:106]) # Issue #12446: Test read(n) followed by readlines() f = getreader() self.assertEqual(f.read(size=40, chars=5), data[:5]) self.assertEqual(f.readlines(), [lines[0][5:]] + lines[1:]) self.assertEqual(f.read(), '') def test_bug1175396(self): s = [ '<%!--===================================================\r\n', ' BLOG index page: show recent articles,\r\n', ' today\'s articles, or articles of a specific date.\r\n', '========================================================--%>\r\n', '<%@inputencoding="ISO-8859-1"%>\r\n', '<%@pagetemplate=TEMPLATE.y%>\r\n', '<%@import=import frog.util, frog%>\r\n', '<%@import=import frog.objects%>\r\n', '<%@import=from frog.storageerrors import StorageError%>\r\n', '<%\r\n', '\r\n', 'import logging\r\n', 'log=logging.getLogger("Snakelets.logger")\r\n', '\r\n', '\r\n', 'user=self.SessionCtx.user\r\n', 'storageEngine=self.SessionCtx.storageEngine\r\n', '\r\n', '\r\n', 'def readArticlesFromDate(date, count=None):\r\n', ' entryids=storageEngine.listBlogEntries(date)\r\n', ' entryids.reverse() # descending\r\n', ' if count:\r\n', ' entryids=entryids[:count]\r\n', ' try:\r\n', ' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n', ' except StorageError,x:\r\n', ' log.error("Error loading articles: "+str(x))\r\n', ' self.abort("cannot load articles")\r\n', '\r\n', 'showdate=None\r\n', '\r\n', 'arg=self.Request.getArg()\r\n', 'if arg=="today":\r\n', ' #-------------------- TODAY\'S ARTICLES\r\n', ' self.write("<h2>Today\'s articles</h2>")\r\n', ' showdate = frog.util.isodatestr() \r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'elif arg=="active":\r\n', ' #-------------------- ACTIVE ARTICLES redirect\r\n', ' self.Yredirect("active.y")\r\n', 'elif arg=="login":\r\n', ' #-------------------- LOGIN PAGE redirect\r\n', ' self.Yredirect("login.y")\r\n', 'elif arg=="date":\r\n', ' #-------------------- ARTICLES OF A SPECIFIC DATE\r\n', ' showdate = self.Request.getParameter("date")\r\n', ' self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'else:\r\n', ' #-------------------- RECENT ARTICLES\r\n', ' self.write("<h2>Recent articles</h2>")\r\n', ' dates=storageEngine.listBlogEntryDates()\r\n', ' if dates:\r\n', ' entries=[]\r\n', ' SHOWAMOUNT=10\r\n', ' for showdate in dates:\r\n', ' entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n', ' if len(entries)>=SHOWAMOUNT:\r\n', ' break\r\n', ' \r\n', ] stream = io.BytesIO("".join(s).encode(self.encoding)) reader = codecs.getreader(self.encoding)(stream) for (i, line) in enumerate(reader): self.assertEqual(line, s[i]) def test_readlinequeue(self): q = Queue(b"") writer = codecs.getwriter(self.encoding)(q) reader = codecs.getreader(self.encoding)(q) # No lineends writer.write("foo\r") self.assertEqual(reader.readline(keepends=False), "foo") writer.write("\nbar\r") self.assertEqual(reader.readline(keepends=False), "") self.assertEqual(reader.readline(keepends=False), "bar") writer.write("baz") self.assertEqual(reader.readline(keepends=False), "baz") self.assertEqual(reader.readline(keepends=False), "") # Lineends writer.write("foo\r") self.assertEqual(reader.readline(keepends=True), "foo\r") writer.write("\nbar\r") self.assertEqual(reader.readline(keepends=True), "\n") self.assertEqual(reader.readline(keepends=True), "bar\r") writer.write("baz") self.assertEqual(reader.readline(keepends=True), "baz") self.assertEqual(reader.readline(keepends=True), "") writer.write("foo\r\n") self.assertEqual(reader.readline(keepends=True), "foo\r\n") def test_bug1098990_a(self): s1 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n" s2 = "offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n" s3 = "next line.\r\n" s = (s1+s2+s3).encode(self.encoding) stream = io.BytesIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), "") def test_bug1098990_b(self): s1 = "aaaaaaaaaaaaaaaaaaaaaaaa\r\n" s2 = "bbbbbbbbbbbbbbbbbbbbbbbb\r\n" s3 = "stillokay:bbbbxx\r\n" s4 = "broken!!!!badbad\r\n" s5 = "againokay.\r\n" s = (s1+s2+s3+s4+s5).encode(self.encoding) stream = io.BytesIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), s4) self.assertEqual(reader.readline(), s5) self.assertEqual(reader.readline(), "") ill_formed_sequence_replace = "\ufffd" def test_lone_surrogates(self): self.assertRaises(UnicodeEncodeError, "\ud800".encode, self.encoding) self.assertEqual("[\uDC80]".encode(self.encoding, "backslashreplace"), "[\\udc80]".encode(self.encoding)) self.assertEqual("[\uDC80]".encode(self.encoding, "namereplace"), "[\\udc80]".encode(self.encoding)) self.assertEqual("[\uDC80]".encode(self.encoding, "xmlcharrefreplace"), "[&#56448;]".encode(self.encoding)) self.assertEqual("[\uDC80]".encode(self.encoding, "ignore"), "[]".encode(self.encoding)) self.assertEqual("[\uDC80]".encode(self.encoding, "replace"), "[?]".encode(self.encoding)) # sequential surrogate characters self.assertEqual("[\uD800\uDC80]".encode(self.encoding, "ignore"), "[]".encode(self.encoding)) self.assertEqual("[\uD800\uDC80]".encode(self.encoding, "replace"), "[??]".encode(self.encoding)) bom = "".encode(self.encoding) for before, after in [("\U00010fff", "A"), ("[", "]"), ("A", "\U00010fff")]: before_sequence = before.encode(self.encoding)[len(bom):] after_sequence = after.encode(self.encoding)[len(bom):] test_string = before + "\uDC80" + after test_sequence = (bom + before_sequence + self.ill_formed_sequence + after_sequence) self.assertRaises(UnicodeDecodeError, test_sequence.decode, self.encoding) self.assertEqual(test_string.encode(self.encoding, "surrogatepass"), test_sequence) self.assertEqual(test_sequence.decode(self.encoding, "surrogatepass"), test_string) self.assertEqual(test_sequence.decode(self.encoding, "ignore"), before + after) self.assertEqual(test_sequence.decode(self.encoding, "replace"), before + self.ill_formed_sequence_replace + after) backslashreplace = ''.join('\\x%02x' % b for b in self.ill_formed_sequence) self.assertEqual(test_sequence.decode(self.encoding, "backslashreplace"), before + backslashreplace + after) def test_incremental_surrogatepass(self): # Test incremental decoder for surrogatepass handler: # see issue #24214 # High surrogate data = '\uD901'.encode(self.encoding, 'surrogatepass') for i in range(1, len(data)): dec = codecs.getincrementaldecoder(self.encoding)('surrogatepass') self.assertEqual(dec.decode(data[:i]), '') self.assertEqual(dec.decode(data[i:], True), '\uD901') # Low surrogate data = '\uDC02'.encode(self.encoding, 'surrogatepass') for i in range(1, len(data)): dec = codecs.getincrementaldecoder(self.encoding)('surrogatepass') self.assertEqual(dec.decode(data[:i]), '') final = self.encoding == "cp65001" self.assertEqual(dec.decode(data[i:], final), '\uDC02') class UTF32Test(ReadTest, unittest.TestCase): encoding = "utf-32" if sys.byteorder == 'little': ill_formed_sequence = b"\x80\xdc\x00\x00" else: ill_formed_sequence = b"\x00\x00\xdc\x80" spamle = (b'\xff\xfe\x00\x00' b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00' b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00') spambe = (b'\x00\x00\xfe\xff' b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m' b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m') def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = io.BytesIO() f = writer(s) f.write("spam") f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = io.BytesIO(d) f = reader(s) self.assertEqual(f.read(), "spamspam") def test_badbom(self): s = io.BytesIO(4*b"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = io.BytesIO(8*b"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", # first byte of BOM read "", # second byte of BOM read "", # third byte of BOM read "", # fourth byte of BOM read => byteorder known "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_handlers(self): self.assertEqual(('\ufffd', 1), codecs.utf_32_decode(b'\x01', 'replace', True)) self.assertEqual(('', 1), codecs.utf_32_decode(b'\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode, b"\xff", "strict", True) def test_decoder_state(self): self.check_state_handling_decode(self.encoding, "spamspam", self.spamle) self.check_state_handling_decode(self.encoding, "spamspam", self.spambe) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded_le = b'\xff\xfe\x00\x00' + b'\x00\x00\x01\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_decode(encoded_le)[0]) encoded_be = b'\x00\x00\xfe\xff' + b'\x00\x01\x00\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_decode(encoded_be)[0]) class UTF32LETest(ReadTest, unittest.TestCase): encoding = "utf-32-le" ill_formed_sequence = b"\x80\xdc\x00\x00" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_simple(self): self.assertEqual("\U00010203".encode(self.encoding), b"\x03\x02\x01\x00") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode, b"\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = b'\x00\x00\x01\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_le_decode(encoded)[0]) class UTF32BETest(ReadTest, unittest.TestCase): encoding = "utf-32-be" ill_formed_sequence = b"\x00\x00\xdc\x80" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_simple(self): self.assertEqual("\U00010203".encode(self.encoding), b"\x00\x01\x02\x03") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode, b"\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = b'\x00\x01\x00\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_be_decode(encoded)[0]) class UTF16Test(ReadTest, unittest.TestCase): encoding = "utf-16" if sys.byteorder == 'little': ill_formed_sequence = b"\x80\xdc" else: ill_formed_sequence = b"\xdc\x80" spamle = b'\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00' spambe = b'\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m' def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = io.BytesIO() f = writer(s) f.write("spam") f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = io.BytesIO(d) f = reader(s) self.assertEqual(f.read(), "spamspam") def test_badbom(self): s = io.BytesIO(b"\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = io.BytesIO(b"\xff\xff\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", # first byte of BOM read "", # second byte of BOM read => byteorder known "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_handlers(self): self.assertEqual(('\ufffd', 1), codecs.utf_16_decode(b'\x01', 'replace', True)) self.assertEqual(('', 1), codecs.utf_16_decode(b'\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, b"\xff", "strict", True) def test_decoder_state(self): self.check_state_handling_decode(self.encoding, "spamspam", self.spamle) self.check_state_handling_decode(self.encoding, "spamspam", self.spambe) def test_bug691291(self): # Files are always opened in binary mode, even if no binary mode was # specified. This means that no automatic conversion of '\n' is done # on reading and writing. s1 = 'Hello\r\nworld\r\n' s = s1.encode(self.encoding) self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, 'wb') as fp: fp.write(s) with support.check_warnings(('', DeprecationWarning)): reader = codecs.open(support.TESTFN, 'U', encoding=self.encoding) with reader: self.assertEqual(reader.read(), s1) class UTF16LETest(ReadTest, unittest.TestCase): encoding = "utf-16-le" ill_formed_sequence = b"\x80\xdc" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_errors(self): tests = [ (b'\xff', '\ufffd'), (b'A\x00Z', 'A\ufffd'), (b'A\x00B\x00C\x00D\x00Z', 'ABCD\ufffd'), (b'\x00\xd8', '\ufffd'), (b'\x00\xd8A', '\ufffd'), (b'\x00\xd8A\x00', '\ufffdA'), (b'\x00\xdcA\x00', '\ufffdA'), ] for raw, expected in tests: self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, raw, 'strict', True) self.assertEqual(raw.decode('utf-16le', 'replace'), expected) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding), b'\x00\xd8\x03\xde') self.assertEqual(b'\x00\xd8\x03\xde'.decode(self.encoding), "\U00010203") class UTF16BETest(ReadTest, unittest.TestCase): encoding = "utf-16-be" ill_formed_sequence = b"\xdc\x80" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff\U00010000", [ "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff", "\x00\xff\u0100\uffff\U00010000", ] ) def test_errors(self): tests = [ (b'\xff', '\ufffd'), (b'\x00A\xff', 'A\ufffd'), (b'\x00A\x00B\x00C\x00DZ', 'ABCD\ufffd'), (b'\xd8\x00', '\ufffd'), (b'\xd8\x00\xdc', '\ufffd'), (b'\xd8\x00\x00A', '\ufffdA'), (b'\xdc\x00\x00A', '\ufffdA'), ] for raw, expected in tests: self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, raw, 'strict', True) self.assertEqual(raw.decode('utf-16be', 'replace'), expected) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding), b'\xd8\x00\xde\x03') self.assertEqual(b'\xd8\x00\xde\x03'.decode(self.encoding), "\U00010203") class UTF8Test(ReadTest, unittest.TestCase): encoding = "utf-8" ill_formed_sequence = b"\xed\xb2\x80" ill_formed_sequence_replace = "\ufffd" * 3 BOM = b'' def test_partial(self): self.check_partial( "\x00\xff\u07ff\u0800\uffff\U00010000", [ "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u07ff", "\x00\xff\u07ff", "\x00\xff\u07ff", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800\uffff", "\x00\xff\u07ff\u0800\uffff", "\x00\xff\u07ff\u0800\uffff", "\x00\xff\u07ff\u0800\uffff", "\x00\xff\u07ff\u0800\uffff\U00010000", ] ) def test_decoder_state(self): u = "\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff" self.check_state_handling_decode(self.encoding, u, u.encode(self.encoding)) def test_decode_error(self): for data, error_handler, expected in ( (b'[\x80\xff]', 'ignore', '[]'), (b'[\x80\xff]', 'replace', '[\ufffd\ufffd]'), (b'[\x80\xff]', 'surrogateescape', '[\udc80\udcff]'), (b'[\x80\xff]', 'backslashreplace', '[\\x80\\xff]'), ): with self.subTest(data=data, error_handler=error_handler, expected=expected): self.assertEqual(data.decode(self.encoding, error_handler), expected) def test_lone_surrogates(self): super().test_lone_surrogates() # not sure if this is making sense for # UTF-16 and UTF-32 self.assertEqual("[\uDC80]".encode(self.encoding, "surrogateescape"), self.BOM + b'[\x80]') with self.assertRaises(UnicodeEncodeError) as cm: "[\uDC80\uD800\uDFFF]".encode(self.encoding, "surrogateescape") exc = cm.exception self.assertEqual(exc.object[exc.start:exc.end], '\uD800\uDFFF') def test_surrogatepass_handler(self): self.assertEqual("abc\ud800def".encode(self.encoding, "surrogatepass"), self.BOM + b"abc\xed\xa0\x80def") self.assertEqual("\U00010fff\uD800".encode(self.encoding, "surrogatepass"),
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/sample_doctest_no_docstrings.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/sample_doctest_no_docstrings.py
# This is a sample module used for testing doctest. # # This module is for testing how doctest handles a module with no # docstrings. class Foo(object): # A class with no docstring. def __init__(self): pass
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/relimport.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/relimport.py
from .test_import import *
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_imp.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_imp.py
import importlib import importlib.util import os import os.path import py_compile import sys from test import support from test.support import script_helper import unittest import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) import imp import _imp def requires_load_dynamic(meth): """Decorator to skip a test if not running under CPython or lacking imp.load_dynamic().""" meth = support.cpython_only(meth) return unittest.skipIf(not hasattr(imp, 'load_dynamic'), 'imp.load_dynamic() required')(meth) class LockTests(unittest.TestCase): """Very basic test of import lock functions.""" def verify_lock_state(self, expected): self.assertEqual(imp.lock_held(), expected, "expected imp.lock_held() to be %r" % expected) def testLock(self): LOOPS = 50 # The import lock may already be held, e.g. if the test suite is run # via "import test.autotest". lock_held_at_start = imp.lock_held() self.verify_lock_state(lock_held_at_start) for i in range(LOOPS): imp.acquire_lock() self.verify_lock_state(True) for i in range(LOOPS): imp.release_lock() # The original state should be restored now. self.verify_lock_state(lock_held_at_start) if not lock_held_at_start: try: imp.release_lock() except RuntimeError: pass else: self.fail("release_lock() without lock should raise " "RuntimeError") class ImportTests(unittest.TestCase): def setUp(self): mod = importlib.import_module('test.encoded_modules') self.test_strings = mod.test_strings self.test_path = mod.__path__ def test_import_encoded_module(self): for modname, encoding, teststr in self.test_strings: mod = importlib.import_module('test.encoded_modules.' 'module_' + modname) self.assertEqual(teststr, mod.test) def test_find_module_encoding(self): for mod, encoding, _ in self.test_strings: with imp.find_module('module_' + mod, self.test_path)[0] as fd: self.assertEqual(fd.encoding, encoding) path = [os.path.dirname(__file__)] with self.assertRaises(SyntaxError): imp.find_module('badsyntax_pep3120', path) def test_issue1267(self): for mod, encoding, _ in self.test_strings: fp, filename, info = imp.find_module('module_' + mod, self.test_path) with fp: self.assertNotEqual(fp, None) self.assertEqual(fp.encoding, encoding) self.assertEqual(fp.tell(), 0) self.assertEqual(fp.readline(), '# test %s encoding\n' % encoding) fp, filename, info = imp.find_module("tokenize") with fp: self.assertNotEqual(fp, None) self.assertEqual(fp.encoding, "utf-8") self.assertEqual(fp.tell(), 0) self.assertEqual(fp.readline(), '"""Tokenization help for Python programs.\n') def test_issue3594(self): temp_mod_name = 'test_imp_helper' sys.path.insert(0, '.') try: with open(temp_mod_name + '.py', 'w') as file: file.write("# coding: cp1252\nu = 'test.test_imp'\n") file, filename, info = imp.find_module(temp_mod_name) file.close() self.assertEqual(file.encoding, 'cp1252') finally: del sys.path[0] support.unlink(temp_mod_name + '.py') support.unlink(temp_mod_name + '.pyc') def test_issue5604(self): # Test cannot cover imp.load_compiled function. # Martin von Loewis note what shared library cannot have non-ascii # character because init_xxx function cannot be compiled # and issue never happens for dynamic modules. # But sources modified to follow generic way for processing paths. # the return encoding could be uppercase or None fs_encoding = sys.getfilesystemencoding() # covers utf-8 and Windows ANSI code pages # one non-space symbol from every page # (http://en.wikipedia.org/wiki/Code_page) known_locales = { 'utf-8' : b'\xc3\xa4', 'cp1250' : b'\x8C', 'cp1251' : b'\xc0', 'cp1252' : b'\xc0', 'cp1253' : b'\xc1', 'cp1254' : b'\xc0', 'cp1255' : b'\xe0', 'cp1256' : b'\xe0', 'cp1257' : b'\xc0', 'cp1258' : b'\xc0', } if sys.platform == 'darwin': self.assertEqual(fs_encoding, 'utf-8') # Mac OS X uses the Normal Form D decomposition # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html special_char = b'a\xcc\x88' else: special_char = known_locales.get(fs_encoding) if not special_char: self.skipTest("can't run this test with %s as filesystem encoding" % fs_encoding) decoded_char = special_char.decode(fs_encoding) temp_mod_name = 'test_imp_helper_' + decoded_char test_package_name = 'test_imp_helper_package_' + decoded_char init_file_name = os.path.join(test_package_name, '__init__.py') try: # if the curdir is not in sys.path the test fails when run with # ./python ./Lib/test/regrtest.py test_imp sys.path.insert(0, os.curdir) with open(temp_mod_name + '.py', 'w') as file: file.write('a = 1\n') file, filename, info = imp.find_module(temp_mod_name) with file: self.assertIsNotNone(file) self.assertTrue(filename[:-3].endswith(temp_mod_name)) self.assertEqual(info[0], '.py') self.assertEqual(info[1], 'r') self.assertEqual(info[2], imp.PY_SOURCE) mod = imp.load_module(temp_mod_name, file, filename, info) self.assertEqual(mod.a, 1) with warnings.catch_warnings(): warnings.simplefilter('ignore') mod = imp.load_source(temp_mod_name, temp_mod_name + '.py') self.assertEqual(mod.a, 1) with warnings.catch_warnings(): warnings.simplefilter('ignore') if not sys.dont_write_bytecode: mod = imp.load_compiled( temp_mod_name, imp.cache_from_source(temp_mod_name + '.py')) self.assertEqual(mod.a, 1) if not os.path.exists(test_package_name): os.mkdir(test_package_name) with open(init_file_name, 'w') as file: file.write('b = 2\n') with warnings.catch_warnings(): warnings.simplefilter('ignore') package = imp.load_package(test_package_name, test_package_name) self.assertEqual(package.b, 2) finally: del sys.path[0] for ext in ('.py', '.pyc'): support.unlink(temp_mod_name + ext) support.unlink(init_file_name + ext) support.rmtree(test_package_name) support.rmtree('__pycache__') def test_issue9319(self): path = os.path.dirname(__file__) self.assertRaises(SyntaxError, imp.find_module, "badsyntax_pep3120", [path]) def test_load_from_source(self): # Verify that the imp module can correctly load and find .py files # XXX (ncoghlan): It would be nice to use support.CleanImport # here, but that breaks because the os module registers some # handlers in copy_reg on import. Since CleanImport doesn't # revert that registration, the module is left in a broken # state after reversion. Reinitialising the module contents # and just reverting os.environ to its previous state is an OK # workaround orig_path = os.path orig_getenv = os.getenv with support.EnvironmentVarGuard(): x = imp.find_module("os") self.addCleanup(x[0].close) new_os = imp.load_module("os", *x) self.assertIs(os, new_os) self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv) @requires_load_dynamic def test_issue15828_load_extensions(self): # Issue 15828 picked up that the adapter between the old imp API # and importlib couldn't handle C extensions example = "_heapq" x = imp.find_module(example) file_ = x[0] if file_ is not None: self.addCleanup(file_.close) mod = imp.load_module(example, *x) self.assertEqual(mod.__name__, example) @requires_load_dynamic def test_issue16421_multiple_modules_in_one_dll(self): # Issue 16421: loading several modules from the same compiled file fails m = '_testimportmultiple' fileobj, pathname, description = imp.find_module(m) fileobj.close() mod0 = imp.load_dynamic(m, pathname) mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname) mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname) self.assertEqual(mod0.__name__, m) self.assertEqual(mod1.__name__, '_testimportmultiple_foo') self.assertEqual(mod2.__name__, '_testimportmultiple_bar') with self.assertRaises(ImportError): imp.load_dynamic('nonexistent', pathname) @requires_load_dynamic def test_load_dynamic_ImportError_path(self): # Issue #1559549 added `name` and `path` attributes to ImportError # in order to provide better detail. Issue #10854 implemented those # attributes on import failures of extensions on Windows. path = 'bogus file path' name = 'extension' with self.assertRaises(ImportError) as err: imp.load_dynamic(name, path) self.assertIn(path, err.exception.path) self.assertEqual(name, err.exception.name) @requires_load_dynamic def test_load_module_extension_file_is_None(self): # When loading an extension module and the file is None, open one # on the behalf of imp.load_dynamic(). # Issue #15902 name = '_testimportmultiple' found = imp.find_module(name) if found[0] is not None: found[0].close() if found[2][2] != imp.C_EXTENSION: self.skipTest("found module doesn't appear to be a C extension") imp.load_module(name, None, *found[1:]) @requires_load_dynamic def test_issue24748_load_module_skips_sys_modules_check(self): name = 'test.imp_dummy' try: del sys.modules[name] except KeyError: pass try: module = importlib.import_module(name) spec = importlib.util.find_spec('_testmultiphase') module = imp.load_dynamic(name, spec.origin) self.assertEqual(module.__name__, name) self.assertEqual(module.__spec__.name, name) self.assertEqual(module.__spec__.origin, spec.origin) self.assertRaises(AttributeError, getattr, module, 'dummy_name') self.assertEqual(module.int_const, 1969) self.assertIs(sys.modules[name], module) finally: try: del sys.modules[name] except KeyError: pass @unittest.skipIf(sys.dont_write_bytecode, "test meaningful only when writing bytecode") def test_bug7732(self): with support.temp_cwd(): source = support.TESTFN + '.py' os.mkdir(source) self.assertRaisesRegex(ImportError, '^No module', imp.find_module, support.TESTFN, ["."]) def test_multiple_calls_to_get_data(self): # Issue #18755: make sure multiple calls to get_data() can succeed. loader = imp._LoadSourceCompatibility('imp', imp.__file__, open(imp.__file__)) loader.get_data(imp.__file__) # File should be closed loader.get_data(imp.__file__) # Will need to create a newly opened file def test_load_source(self): # Create a temporary module since load_source(name) modifies # sys.modules[name] attributes like __loader___ modname = f"tmp{__name__}" mod = type(sys.modules[__name__])(modname) with support.swap_item(sys.modules, modname, mod): with self.assertRaisesRegex(ValueError, 'embedded null'): imp.load_source(modname, __file__ + "\0") @support.cpython_only def test_issue31315(self): # There shouldn't be an assertion failure in imp.create_dynamic(), # when spec.name is not a string. create_dynamic = support.get_attribute(imp, 'create_dynamic') class BadSpec: name = None origin = 'foo' with self.assertRaises(TypeError): create_dynamic(BadSpec()) def test_source_hash(self): self.assertEqual(_imp.source_hash(42, b'hi'), b'\xc6\xe7Z\r\x03:}\xab') self.assertEqual(_imp.source_hash(43, b'hi'), b'\x85\x9765\xf8\x9a\x8b9') def test_pyc_invalidation_mode_from_cmdline(self): cases = [ ([], "default"), (["--check-hash-based-pycs", "default"], "default"), (["--check-hash-based-pycs", "always"], "always"), (["--check-hash-based-pycs", "never"], "never"), ] for interp_args, expected in cases: args = interp_args + [ "-c", "import _imp; print(_imp.check_hash_based_pycs)", ] res = script_helper.assert_python_ok(*args) self.assertEqual(res.out.strip().decode('utf-8'), expected) def test_find_and_load_checked_pyc(self): # issue 34056 with support.temp_cwd(): with open('mymod.py', 'wb') as fp: fp.write(b'x = 42\n') py_compile.compile( 'mymod.py', doraise=True, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH, ) file, path, description = imp.find_module('mymod', path=['.']) mod = imp.load_module('mymod', file, path, description) self.assertEqual(mod.x, 42) class ReloadTests(unittest.TestCase): """Very basic tests to make sure that imp.reload() operates just like reload().""" def test_source(self): # XXX (ncoghlan): It would be nice to use test.support.CleanImport # here, but that breaks because the os module registers some # handlers in copy_reg on import. Since CleanImport doesn't # revert that registration, the module is left in a broken # state after reversion. Reinitialising the module contents # and just reverting os.environ to its previous state is an OK # workaround with support.EnvironmentVarGuard(): import os imp.reload(os) def test_extension(self): with support.CleanImport('time'): import time imp.reload(time) def test_builtin(self): with support.CleanImport('marshal'): import marshal imp.reload(marshal) def test_with_deleted_parent(self): # see #18681 from html import parser html = sys.modules.pop('html') def cleanup(): sys.modules['html'] = html self.addCleanup(cleanup) with self.assertRaisesRegex(ImportError, 'html'): imp.reload(parser) class PEP3147Tests(unittest.TestCase): """Tests of PEP 3147.""" tag = imp.get_tag() @unittest.skipUnless(sys.implementation.cache_tag is not None, 'requires sys.implementation.cache_tag not be None') def test_cache_from_source(self): # Given the path to a .py file, return the path to its PEP 3147 # defined .pyc file (i.e. under __pycache__). path = os.path.join('foo', 'bar', 'baz', 'qux.py') expect = os.path.join('foo', 'bar', 'baz', '__pycache__', 'qux.{}.pyc'.format(self.tag)) self.assertEqual(imp.cache_from_source(path, True), expect) @unittest.skipUnless(sys.implementation.cache_tag is not None, 'requires sys.implementation.cache_tag to not be ' 'None') def test_source_from_cache(self): # Given the path to a PEP 3147 defined .pyc file, return the path to # its source. This tests the good path. path = os.path.join('foo', 'bar', 'baz', '__pycache__', 'qux.{}.pyc'.format(self.tag)) expect = os.path.join('foo', 'bar', 'baz', 'qux.py') self.assertEqual(imp.source_from_cache(path), expect) class NullImporterTests(unittest.TestCase): @unittest.skipIf(support.TESTFN_UNENCODABLE is None, "Need an undecodeable filename") def test_unencodeable(self): name = support.TESTFN_UNENCODABLE os.mkdir(name) try: self.assertRaises(ImportError, imp.NullImporter, name) finally: os.rmdir(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_smtpd.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_smtpd.py
import unittest import textwrap from test import support, mock_socket import socket import io import smtpd import asyncore class DummyServer(smtpd.SMTPServer): def __init__(self, *args, **kwargs): smtpd.SMTPServer.__init__(self, *args, **kwargs) self.messages = [] if self._decode_data: self.return_status = 'return status' else: self.return_status = b'return status' def process_message(self, peer, mailfrom, rcpttos, data, **kw): self.messages.append((peer, mailfrom, rcpttos, data)) if data == self.return_status: return '250 Okish' if 'mail_options' in kw and 'SMTPUTF8' in kw['mail_options']: return '250 SMTPUTF8 message okish' class DummyDispatcherBroken(Exception): pass class BrokenDummyServer(DummyServer): def listen(self, num): raise DummyDispatcherBroken() class SMTPDServerTest(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket def test_process_message_unimplemented(self): server = smtpd.SMTPServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True) def write_line(line): channel.socket.queue_recv(line) channel.handle_read() write_line(b'HELO example') write_line(b'MAIL From:eggs@example') write_line(b'RCPT To:spam@example') write_line(b'DATA') self.assertRaises(NotImplementedError, write_line, b'spam\r\n.\r\n') def test_decode_data_and_enable_SMTPUTF8_raises(self): self.assertRaises( ValueError, smtpd.SMTPServer, (support.HOST, 0), ('b', 0), enable_SMTPUTF8=True, decode_data=True) def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket class DebuggingServerTest(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket def send_data(self, channel, data, enable_SMTPUTF8=False): def write_line(line): channel.socket.queue_recv(line) channel.handle_read() write_line(b'EHLO example') if enable_SMTPUTF8: write_line(b'MAIL From:eggs@example BODY=8BITMIME SMTPUTF8') else: write_line(b'MAIL From:eggs@example') write_line(b'RCPT To:spam@example') write_line(b'DATA') write_line(data) write_line(b'.') def test_process_message_with_decode_data_true(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nhello\n') stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- From: test X-Peer: peer-address hello ------------ END MESSAGE ------------ """)) def test_process_message_with_decode_data_false(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0)) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n') stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- b'From: test' b'X-Peer: peer-address' b'' b'h\\xc3\\xa9llo\\xff' ------------ END MESSAGE ------------ """)) def test_process_message_with_enable_SMTPUTF8_true(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0), enable_SMTPUTF8=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n') stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- b'From: test' b'X-Peer: peer-address' b'' b'h\\xc3\\xa9llo\\xff' ------------ END MESSAGE ------------ """)) def test_process_SMTPUTF8_message_with_enable_SMTPUTF8_true(self): server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0), enable_SMTPUTF8=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True) with support.captured_stdout() as s: self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n', enable_SMTPUTF8=True) stdout = s.getvalue() self.assertEqual(stdout, textwrap.dedent("""\ ---------- MESSAGE FOLLOWS ---------- mail options: ['BODY=8BITMIME', 'SMTPUTF8'] b'From: test' b'X-Peer: peer-address' b'' b'h\\xc3\\xa9llo\\xff' ------------ END MESSAGE ------------ """)) def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket class TestFamilyDetection(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket @unittest.skipUnless(support.IPV6_ENABLED, "IPv6 not enabled") def test_socket_uses_IPv6(self): server = smtpd.SMTPServer((support.HOSTv6, 0), (support.HOSTv4, 0)) self.assertEqual(server.socket.family, socket.AF_INET6) def test_socket_uses_IPv4(self): server = smtpd.SMTPServer((support.HOSTv4, 0), (support.HOSTv6, 0)) self.assertEqual(server.socket.family, socket.AF_INET) class TestRcptOptionParsing(unittest.TestCase): error_response = (b'555 RCPT TO parameters not recognized or not ' b'implemented\r\n') def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket smtpd.DEBUGSTREAM = self.old_debugstream def write_line(self, channel, line): channel.socket.queue_recv(line) channel.handle_read() def test_params_rejected(self): server = DummyServer((support.HOST, 0), ('b', 0)) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr) self.write_line(channel, b'EHLO example') self.write_line(channel, b'MAIL from: <foo@example.com> size=20') self.write_line(channel, b'RCPT to: <foo@example.com> foo=bar') self.assertEqual(channel.socket.last, self.error_response) def test_nothing_accepted(self): server = DummyServer((support.HOST, 0), ('b', 0)) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr) self.write_line(channel, b'EHLO example') self.write_line(channel, b'MAIL from: <foo@example.com> size=20') self.write_line(channel, b'RCPT to: <foo@example.com>') self.assertEqual(channel.socket.last, b'250 OK\r\n') class TestMailOptionParsing(unittest.TestCase): error_response = (b'555 MAIL FROM parameters not recognized or not ' b'implemented\r\n') def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket smtpd.DEBUGSTREAM = self.old_debugstream def write_line(self, channel, line): channel.socket.queue_recv(line) channel.handle_read() def test_with_decode_data_true(self): server = DummyServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, decode_data=True) self.write_line(channel, b'EHLO example') for line in [ b'MAIL from: <foo@example.com> size=20 SMTPUTF8', b'MAIL from: <foo@example.com> size=20 SMTPUTF8 BODY=8BITMIME', b'MAIL from: <foo@example.com> size=20 BODY=UNKNOWN', b'MAIL from: <foo@example.com> size=20 body=8bitmime', ]: self.write_line(channel, line) self.assertEqual(channel.socket.last, self.error_response) self.write_line(channel, b'MAIL from: <foo@example.com> size=20') self.assertEqual(channel.socket.last, b'250 OK\r\n') def test_with_decode_data_false(self): server = DummyServer((support.HOST, 0), ('b', 0)) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr) self.write_line(channel, b'EHLO example') for line in [ b'MAIL from: <foo@example.com> size=20 SMTPUTF8', b'MAIL from: <foo@example.com> size=20 SMTPUTF8 BODY=8BITMIME', ]: self.write_line(channel, line) self.assertEqual(channel.socket.last, self.error_response) self.write_line( channel, b'MAIL from: <foo@example.com> size=20 SMTPUTF8 BODY=UNKNOWN') self.assertEqual( channel.socket.last, b'501 Error: BODY can only be one of 7BIT, 8BITMIME\r\n') self.write_line( channel, b'MAIL from: <foo@example.com> size=20 body=8bitmime') self.assertEqual(channel.socket.last, b'250 OK\r\n') def test_with_enable_smtputf8_true(self): server = DummyServer((support.HOST, 0), ('b', 0), enable_SMTPUTF8=True) conn, addr = server.accept() channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True) self.write_line(channel, b'EHLO example') self.write_line( channel, b'MAIL from: <foo@example.com> size=20 body=8bitmime smtputf8') self.assertEqual(channel.socket.last, b'250 OK\r\n') class SMTPDChannelTest(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() self.server = DummyServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = self.server.accept() self.channel = smtpd.SMTPChannel(self.server, conn, addr, decode_data=True) def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket smtpd.DEBUGSTREAM = self.old_debugstream def write_line(self, line): self.channel.socket.queue_recv(line) self.channel.handle_read() def test_broken_connect(self): self.assertRaises( DummyDispatcherBroken, BrokenDummyServer, (support.HOST, 0), ('b', 0), decode_data=True) def test_decode_data_and_enable_SMTPUTF8_raises(self): self.assertRaises( ValueError, smtpd.SMTPChannel, self.server, self.channel.conn, self.channel.addr, enable_SMTPUTF8=True, decode_data=True) def test_server_accept(self): self.server.handle_accept() def test_missing_data(self): self.write_line(b'') self.assertEqual(self.channel.socket.last, b'500 Error: bad syntax\r\n') def test_EHLO(self): self.write_line(b'EHLO example') self.assertEqual(self.channel.socket.last, b'250 HELP\r\n') def test_EHLO_bad_syntax(self): self.write_line(b'EHLO') self.assertEqual(self.channel.socket.last, b'501 Syntax: EHLO hostname\r\n') def test_EHLO_duplicate(self): self.write_line(b'EHLO example') self.write_line(b'EHLO example') self.assertEqual(self.channel.socket.last, b'503 Duplicate HELO/EHLO\r\n') def test_EHLO_HELO_duplicate(self): self.write_line(b'EHLO example') self.write_line(b'HELO example') self.assertEqual(self.channel.socket.last, b'503 Duplicate HELO/EHLO\r\n') def test_HELO(self): name = smtpd.socket.getfqdn() self.write_line(b'HELO example') self.assertEqual(self.channel.socket.last, '250 {}\r\n'.format(name).encode('ascii')) def test_HELO_EHLO_duplicate(self): self.write_line(b'HELO example') self.write_line(b'EHLO example') self.assertEqual(self.channel.socket.last, b'503 Duplicate HELO/EHLO\r\n') def test_HELP(self): self.write_line(b'HELP') self.assertEqual(self.channel.socket.last, b'250 Supported commands: EHLO HELO MAIL RCPT ' + \ b'DATA RSET NOOP QUIT VRFY\r\n') def test_HELP_command(self): self.write_line(b'HELP MAIL') self.assertEqual(self.channel.socket.last, b'250 Syntax: MAIL FROM: <address>\r\n') def test_HELP_command_unknown(self): self.write_line(b'HELP SPAM') self.assertEqual(self.channel.socket.last, b'501 Supported commands: EHLO HELO MAIL RCPT ' + \ b'DATA RSET NOOP QUIT VRFY\r\n') def test_HELO_bad_syntax(self): self.write_line(b'HELO') self.assertEqual(self.channel.socket.last, b'501 Syntax: HELO hostname\r\n') def test_HELO_duplicate(self): self.write_line(b'HELO example') self.write_line(b'HELO example') self.assertEqual(self.channel.socket.last, b'503 Duplicate HELO/EHLO\r\n') def test_HELO_parameter_rejected_when_extensions_not_enabled(self): self.extended_smtp = False self.write_line(b'HELO example') self.write_line(b'MAIL from:<foo@example.com> SIZE=1234') self.assertEqual(self.channel.socket.last, b'501 Syntax: MAIL FROM: <address>\r\n') def test_MAIL_allows_space_after_colon(self): self.write_line(b'HELO example') self.write_line(b'MAIL from: <foo@example.com>') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_extended_MAIL_allows_space_after_colon(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from: <foo@example.com> size=20') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_NOOP(self): self.write_line(b'NOOP') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_HELO_NOOP(self): self.write_line(b'HELO example') self.write_line(b'NOOP') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_NOOP_bad_syntax(self): self.write_line(b'NOOP hi') self.assertEqual(self.channel.socket.last, b'501 Syntax: NOOP\r\n') def test_QUIT(self): self.write_line(b'QUIT') self.assertEqual(self.channel.socket.last, b'221 Bye\r\n') def test_HELO_QUIT(self): self.write_line(b'HELO example') self.write_line(b'QUIT') self.assertEqual(self.channel.socket.last, b'221 Bye\r\n') def test_QUIT_arg_ignored(self): self.write_line(b'QUIT bye bye') self.assertEqual(self.channel.socket.last, b'221 Bye\r\n') def test_bad_state(self): self.channel.smtp_state = 'BAD STATE' self.write_line(b'HELO example') self.assertEqual(self.channel.socket.last, b'451 Internal confusion\r\n') def test_command_too_long(self): self.write_line(b'HELO example') self.write_line(b'MAIL from: ' + b'a' * self.channel.command_size_limit + b'@example') self.assertEqual(self.channel.socket.last, b'500 Error: line too long\r\n') def test_MAIL_command_limit_extended_with_SIZE(self): self.write_line(b'EHLO example') fill_len = self.channel.command_size_limit - len('MAIL from:<@example>') self.write_line(b'MAIL from:<' + b'a' * fill_len + b'@example> SIZE=1234') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'MAIL from:<' + b'a' * (fill_len + 26) + b'@example> SIZE=1234') self.assertEqual(self.channel.socket.last, b'500 Error: line too long\r\n') def test_MAIL_command_rejects_SMTPUTF8_by_default(self): self.write_line(b'EHLO example') self.write_line( b'MAIL from: <naive@example.com> BODY=8BITMIME SMTPUTF8') self.assertEqual(self.channel.socket.last[0:1], b'5') def test_data_longer_than_default_data_size_limit(self): # Hack the default so we don't have to generate so much data. self.channel.data_size_limit = 1048 self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA') self.write_line(b'A' * self.channel.data_size_limit + b'A\r\n.') self.assertEqual(self.channel.socket.last, b'552 Error: Too much mail data\r\n') def test_MAIL_size_parameter(self): self.write_line(b'EHLO example') self.write_line(b'MAIL FROM:<eggs@example> SIZE=512') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_MAIL_invalid_size_parameter(self): self.write_line(b'EHLO example') self.write_line(b'MAIL FROM:<eggs@example> SIZE=invalid') self.assertEqual(self.channel.socket.last, b'501 Syntax: MAIL FROM: <address> [SP <mail-parameters>]\r\n') def test_MAIL_RCPT_unknown_parameters(self): self.write_line(b'EHLO example') self.write_line(b'MAIL FROM:<eggs@example> ham=green') self.assertEqual(self.channel.socket.last, b'555 MAIL FROM parameters not recognized or not implemented\r\n') self.write_line(b'MAIL FROM:<eggs@example>') self.write_line(b'RCPT TO:<eggs@example> ham=green') self.assertEqual(self.channel.socket.last, b'555 RCPT TO parameters not recognized or not implemented\r\n') def test_MAIL_size_parameter_larger_than_default_data_size_limit(self): self.channel.data_size_limit = 1048 self.write_line(b'EHLO example') self.write_line(b'MAIL FROM:<eggs@example> SIZE=2096') self.assertEqual(self.channel.socket.last, b'552 Error: message size exceeds fixed maximum message size\r\n') def test_need_MAIL(self): self.write_line(b'HELO example') self.write_line(b'RCPT to:spam@example') self.assertEqual(self.channel.socket.last, b'503 Error: need MAIL command\r\n') def test_MAIL_syntax_HELO(self): self.write_line(b'HELO example') self.write_line(b'MAIL from eggs@example') self.assertEqual(self.channel.socket.last, b'501 Syntax: MAIL FROM: <address>\r\n') def test_MAIL_syntax_EHLO(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from eggs@example') self.assertEqual(self.channel.socket.last, b'501 Syntax: MAIL FROM: <address> [SP <mail-parameters>]\r\n') def test_MAIL_missing_address(self): self.write_line(b'HELO example') self.write_line(b'MAIL from:') self.assertEqual(self.channel.socket.last, b'501 Syntax: MAIL FROM: <address>\r\n') def test_MAIL_chevrons(self): self.write_line(b'HELO example') self.write_line(b'MAIL from:<eggs@example>') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_MAIL_empty_chevrons(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from:<>') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_MAIL_quoted_localpart(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from: <"Fred Blogs"@example.com>') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com') def test_MAIL_quoted_localpart_no_angles(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from: "Fred Blogs"@example.com') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com') def test_MAIL_quoted_localpart_with_size(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from: <"Fred Blogs"@example.com> SIZE=1000') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com') def test_MAIL_quoted_localpart_with_size_no_angles(self): self.write_line(b'EHLO example') self.write_line(b'MAIL from: "Fred Blogs"@example.com SIZE=1000') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.channel.mailfrom, '"Fred Blogs"@example.com') def test_nested_MAIL(self): self.write_line(b'HELO example') self.write_line(b'MAIL from:eggs@example') self.write_line(b'MAIL from:spam@example') self.assertEqual(self.channel.socket.last, b'503 Error: nested MAIL command\r\n') def test_VRFY(self): self.write_line(b'VRFY eggs@example') self.assertEqual(self.channel.socket.last, b'252 Cannot VRFY user, but will accept message and attempt ' + \ b'delivery\r\n') def test_VRFY_syntax(self): self.write_line(b'VRFY') self.assertEqual(self.channel.socket.last, b'501 Syntax: VRFY <address>\r\n') def test_EXPN_not_implemented(self): self.write_line(b'EXPN') self.assertEqual(self.channel.socket.last, b'502 EXPN not implemented\r\n') def test_no_HELO_MAIL(self): self.write_line(b'MAIL from:<foo@example.com>') self.assertEqual(self.channel.socket.last, b'503 Error: send HELO first\r\n') def test_need_RCPT(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'DATA') self.assertEqual(self.channel.socket.last, b'503 Error: need RCPT command\r\n') def test_RCPT_syntax_HELO(self): self.write_line(b'HELO example') self.write_line(b'MAIL From: eggs@example') self.write_line(b'RCPT to eggs@example') self.assertEqual(self.channel.socket.last, b'501 Syntax: RCPT TO: <address>\r\n') def test_RCPT_syntax_EHLO(self): self.write_line(b'EHLO example') self.write_line(b'MAIL From: eggs@example') self.write_line(b'RCPT to eggs@example') self.assertEqual(self.channel.socket.last, b'501 Syntax: RCPT TO: <address> [SP <mail-parameters>]\r\n') def test_RCPT_lowercase_to_OK(self): self.write_line(b'HELO example') self.write_line(b'MAIL From: eggs@example') self.write_line(b'RCPT to: <eggs@example>') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_no_HELO_RCPT(self): self.write_line(b'RCPT to eggs@example') self.assertEqual(self.channel.socket.last, b'503 Error: send HELO first\r\n') def test_data_dialog(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'RCPT To:spam@example') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'DATA') self.assertEqual(self.channel.socket.last, b'354 End data with <CR><LF>.<CR><LF>\r\n') self.write_line(b'data\r\nmore\r\n.') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.server.messages, [(('peer-address', 'peer-port'), 'eggs@example', ['spam@example'], 'data\nmore')]) def test_DATA_syntax(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA spam') self.assertEqual(self.channel.socket.last, b'501 Syntax: DATA\r\n') def test_no_HELO_DATA(self): self.write_line(b'DATA spam') self.assertEqual(self.channel.socket.last, b'503 Error: send HELO first\r\n') def test_data_transparency_section_4_5_2(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA') self.write_line(b'..\r\n.\r\n') self.assertEqual(self.channel.received_data, '.') def test_multiple_RCPT(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'RCPT To:ham@example') self.write_line(b'DATA') self.write_line(b'data\r\n.') self.assertEqual(self.server.messages, [(('peer-address', 'peer-port'), 'eggs@example', ['spam@example','ham@example'], 'data')]) def test_manual_status(self): # checks that the Channel is able to return a custom status message self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA') self.write_line(b'return status\r\n.') self.assertEqual(self.channel.socket.last, b'250 Okish\r\n') def test_RSET(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'RSET') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'MAIL From:foo@example') self.write_line(b'RCPT To:eggs@example') self.write_line(b'DATA') self.write_line(b'data\r\n.') self.assertEqual(self.server.messages, [(('peer-address', 'peer-port'), 'foo@example', ['eggs@example'], 'data')]) def test_HELO_RSET(self): self.write_line(b'HELO example') self.write_line(b'RSET') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') def test_RSET_syntax(self): self.write_line(b'RSET hi') self.assertEqual(self.channel.socket.last, b'501 Syntax: RSET\r\n') def test_unknown_command(self): self.write_line(b'UNKNOWN_CMD') self.assertEqual(self.channel.socket.last, b'500 Error: command "UNKNOWN_CMD" not ' + \ b'recognized\r\n') def test_attribute_deprecations(self): with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__server with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__server = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__line with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__line = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__state with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__state = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__greeting with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__greeting = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__mailfrom with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__mailfrom = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__rcpttos with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__rcpttos = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__data with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__data = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__fqdn with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__fqdn = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__peer with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__peer = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__conn with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__conn = 'spam' with support.check_warnings(('', DeprecationWarning)): spam = self.channel._SMTPChannel__addr with support.check_warnings(('', DeprecationWarning)): self.channel._SMTPChannel__addr = 'spam' @unittest.skipUnless(support.IPV6_ENABLED, "IPv6 not enabled") class SMTPDChannelIPv6Test(SMTPDChannelTest): def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() self.server = DummyServer((support.HOSTv6, 0), ('b', 0), decode_data=True) conn, addr = self.server.accept() self.channel = smtpd.SMTPChannel(self.server, conn, addr, decode_data=True) class SMTPDChannelWithDataSizeLimitTest(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() self.server = DummyServer((support.HOST, 0), ('b', 0), decode_data=True) conn, addr = self.server.accept() # Set DATA size limit to 32 bytes for easy testing self.channel = smtpd.SMTPChannel(self.server, conn, addr, 32, decode_data=True) def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket smtpd.DEBUGSTREAM = self.old_debugstream def write_line(self, line): self.channel.socket.queue_recv(line) self.channel.handle_read() def test_data_limit_dialog(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'RCPT To:spam@example') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.write_line(b'DATA') self.assertEqual(self.channel.socket.last, b'354 End data with <CR><LF>.<CR><LF>\r\n') self.write_line(b'data\r\nmore\r\n.') self.assertEqual(self.channel.socket.last, b'250 OK\r\n') self.assertEqual(self.server.messages, [(('peer-address', 'peer-port'),
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_errno.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_errno.py
"""Test the errno module Roger E. Masse """ import errno import unittest std_c_errors = frozenset(['EDOM', 'ERANGE']) class ErrnoAttributeTests(unittest.TestCase): def test_for_improper_attributes(self): # No unexpected attributes should be on the module. for error_code in std_c_errors: self.assertTrue(hasattr(errno, error_code), "errno is missing %s" % error_code) def test_using_errorcode(self): # Every key value in errno.errorcode should be on the module. for value in errno.errorcode.values(): self.assertTrue(hasattr(errno, value), 'no %s attr in errno' % value) class ErrorcodeTests(unittest.TestCase): def test_attributes_in_errorcode(self): for attribute in errno.__dict__.keys(): if attribute.isupper(): self.assertIn(getattr(errno, attribute), errno.errorcode, 'no %s attr in errno.errorcode' % attribute) 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_b.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/final_b.py
""" Fodder for module finalization tests in test_module. """ import shutil import test.final_a x = 'b' class C: def __del__(self): # Inspect module globals and builtins print("x =", x) print("final_a.x =", test.final_a.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_opcodes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_opcodes.py
# Python test set -- part 2, opcodes import unittest from test import ann_module, support class OpcodeTest(unittest.TestCase): def test_try_inside_for_loop(self): n = 0 for i in range(10): n = n+i try: 1/0 except NameError: pass except ZeroDivisionError: pass except TypeError: pass try: pass except: pass try: pass finally: pass n = n+i if n != 90: self.fail('try inside for') def test_setup_annotations_line(self): # check that SETUP_ANNOTATIONS does not create spurious line numbers try: with open(ann_module.__file__) as f: txt = f.read() co = compile(txt, ann_module.__file__, 'exec') self.assertEqual(co.co_firstlineno, 6) except OSError: pass def test_no_annotations_if_not_needed(self): class C: pass with self.assertRaises(AttributeError): C.__annotations__ def test_use_existing_annotations(self): ns = {'__annotations__': {1: 2}} exec('x: int', ns) self.assertEqual(ns['__annotations__'], {'x': int, 1: 2}) def test_do_not_recreate_annotations(self): # Don't rely on the existence of the '__annotations__' global. with support.swap_item(globals(), '__annotations__', {}): del globals()['__annotations__'] class C: del __annotations__ with self.assertRaises(NameError): x: int def test_raise_class_exceptions(self): class AClass(Exception): pass class BClass(AClass): pass class CClass(Exception): pass class DClass(AClass): def __init__(self, ignore): pass try: raise AClass() except: pass try: raise AClass() except AClass: pass try: raise BClass() except AClass: pass try: raise BClass() except CClass: self.fail() except: pass a = AClass() b = BClass() try: raise b except AClass as v: self.assertEqual(v, b) else: self.fail("no exception") # not enough arguments ##try: raise BClass, a ##except TypeError: pass ##else: self.fail("no exception") try: raise DClass(a) except DClass as v: self.assertIsInstance(v, DClass) else: self.fail("no exception") def test_compare_function_objects(self): f = eval('lambda: None') g = eval('lambda: None') self.assertNotEqual(f, g) f = eval('lambda a: a') g = eval('lambda a: a') self.assertNotEqual(f, g) f = eval('lambda a=1: a') g = eval('lambda a=1: a') self.assertNotEqual(f, g) f = eval('lambda: 0') g = eval('lambda: 1') self.assertNotEqual(f, g) f = eval('lambda: None') g = eval('lambda a: None') self.assertNotEqual(f, g) f = eval('lambda a: None') g = eval('lambda b: None') self.assertNotEqual(f, g) f = eval('lambda a: None') g = eval('lambda a=None: None') self.assertNotEqual(f, g) f = eval('lambda a=0: None') g = eval('lambda a=1: None') self.assertNotEqual(f, g) def test_modulo_of_string_subclasses(self): class MyString(str): def __mod__(self, value): return 42 self.assertEqual(MyString() % 3, 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/test_normalization.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_normalization.py
from test.support import open_urlresource import unittest from http.client import HTTPException import sys from unicodedata import normalize, unidata_version TESTDATAFILE = "NormalizationTest.txt" TESTDATAURL = "http://www.pythontest.net/unicode/" + unidata_version + "/" + TESTDATAFILE def check_version(testfile): hdr = testfile.readline() return unidata_version in hdr class RangeError(Exception): pass def NFC(str): return normalize("NFC", str) def NFKC(str): return normalize("NFKC", str) def NFD(str): return normalize("NFD", str) def NFKD(str): return normalize("NFKD", str) def unistr(data): data = [int(x, 16) for x in data.split(" ")] for x in data: if x > sys.maxunicode: raise RangeError return "".join([chr(x) for x in data]) class NormalizationTest(unittest.TestCase): def test_main(self): # Hit the exception early try: testdata = open_urlresource(TESTDATAURL, encoding="utf-8", check=check_version) except PermissionError: self.skipTest(f"Permission error when downloading {TESTDATAURL} " f"into the test data directory") except (OSError, HTTPException): self.fail(f"Could not retrieve {TESTDATAURL}") with testdata: self.run_normalization_tests(testdata) def run_normalization_tests(self, testdata): part = None part1_data = {} for line in testdata: if '#' in line: line = line.split('#')[0] line = line.strip() if not line: continue if line.startswith("@Part"): part = line.split()[0] continue try: c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]] except RangeError: # Skip unsupported characters; # try at least adding c1 if we are in part1 if part == "@Part1": try: c1 = unistr(line.split(';')[0]) except RangeError: pass else: part1_data[c1] = 1 continue # Perform tests self.assertTrue(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) self.assertTrue(c4 == NFC(c4) == NFC(c5), line) self.assertTrue(c3 == NFD(c1) == NFD(c2) == NFD(c3), line) self.assertTrue(c5 == NFD(c4) == NFD(c5), line) self.assertTrue(c4 == NFKC(c1) == NFKC(c2) == \ NFKC(c3) == NFKC(c4) == NFKC(c5), line) self.assertTrue(c5 == NFKD(c1) == NFKD(c2) == \ NFKD(c3) == NFKD(c4) == NFKD(c5), line) # Record part 1 data if part == "@Part1": part1_data[c1] = 1 # Perform tests for all other data for c in range(sys.maxunicode+1): X = chr(c) if X in part1_data: continue self.assertTrue(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c) def test_bug_834676(self): # Check for bug 834676 normalize('NFC', '\ud55c\uae00') 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_flufl.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_flufl.py
import __future__ import unittest class FLUFLTests(unittest.TestCase): def test_barry_as_bdfl(self): code = "from __future__ import barry_as_FLUFL\n2 {0} 3" compile(code.format('<>'), '<BDFL test>', 'exec', __future__.CO_FUTURE_BARRY_AS_BDFL) with self.assertRaises(SyntaxError) as cm: compile(code.format('!='), '<FLUFL test>', 'exec', __future__.CO_FUTURE_BARRY_AS_BDFL) self.assertRegex(str(cm.exception), "with Barry as BDFL, use '<>' instead of '!='") self.assertEqual(cm.exception.text, '2 != 3\n') self.assertEqual(cm.exception.filename, '<FLUFL test>') self.assertEqual(cm.exception.lineno, 2) self.assertEqual(cm.exception.offset, 4) def test_guido_as_bdfl(self): code = '2 {0} 3' compile(code.format('!='), '<BDFL test>', 'exec') with self.assertRaises(SyntaxError) as cm: compile(code.format('<>'), '<FLUFL test>', 'exec') self.assertRegex(str(cm.exception), "invalid syntax") self.assertEqual(cm.exception.text, '2 <> 3\n') self.assertEqual(cm.exception.filename, '<FLUFL test>') self.assertEqual(cm.exception.lineno, 1) self.assertEqual(cm.exception.offset, 4) 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_ensurepip.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ensurepip.py
import unittest import unittest.mock import test.support import os import os.path import contextlib import sys import ensurepip import ensurepip._uninstall class TestEnsurePipVersion(unittest.TestCase): def test_returns_version(self): self.assertEqual(ensurepip._PIP_VERSION, ensurepip.version()) class EnsurepipMixin: def setUp(self): run_pip_patch = unittest.mock.patch("ensurepip._run_pip") self.run_pip = run_pip_patch.start() self.run_pip.return_value = 0 self.addCleanup(run_pip_patch.stop) # Avoid side effects on the actual os module real_devnull = os.devnull os_patch = unittest.mock.patch("ensurepip.os") patched_os = os_patch.start() self.addCleanup(os_patch.stop) patched_os.devnull = real_devnull patched_os.path = os.path self.os_environ = patched_os.environ = os.environ.copy() class TestBootstrap(EnsurepipMixin, unittest.TestCase): def test_basic_bootstrapping(self): ensurepip.bootstrap() self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "setuptools", "pip", ], unittest.mock.ANY, ) additional_paths = self.run_pip.call_args[0][1] self.assertEqual(len(additional_paths), 2) def test_bootstrapping_with_root(self): ensurepip.bootstrap(root="/foo/bar/") self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "--root", "/foo/bar/", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_user(self): ensurepip.bootstrap(user=True) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "--user", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_upgrade(self): ensurepip.bootstrap(upgrade=True) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "--upgrade", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_verbosity_1(self): ensurepip.bootstrap(verbosity=1) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "-v", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_verbosity_2(self): ensurepip.bootstrap(verbosity=2) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "-vv", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_verbosity_3(self): ensurepip.bootstrap(verbosity=3) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "-vvv", "setuptools", "pip", ], unittest.mock.ANY, ) def test_bootstrapping_with_regular_install(self): ensurepip.bootstrap() self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "install") def test_bootstrapping_with_alt_install(self): ensurepip.bootstrap(altinstall=True) self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "altinstall") def test_bootstrapping_with_default_pip(self): ensurepip.bootstrap(default_pip=True) self.assertNotIn("ENSUREPIP_OPTIONS", self.os_environ) def test_altinstall_default_pip_conflict(self): with self.assertRaises(ValueError): ensurepip.bootstrap(altinstall=True, default_pip=True) self.assertFalse(self.run_pip.called) def test_pip_environment_variables_removed(self): # ensurepip deliberately ignores all pip environment variables # See http://bugs.python.org/issue19734 for details self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder" ensurepip.bootstrap() self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ) def test_pip_config_file_disabled(self): # ensurepip deliberately ignores the pip config file # See http://bugs.python.org/issue20053 for details ensurepip.bootstrap() self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull) @contextlib.contextmanager def fake_pip(version=ensurepip._PIP_VERSION): if version is None: pip = None else: class FakePip(): __version__ = version pip = FakePip() sentinel = object() orig_pip = sys.modules.get("pip", sentinel) sys.modules["pip"] = pip try: yield pip finally: if orig_pip is sentinel: del sys.modules["pip"] else: sys.modules["pip"] = orig_pip class TestUninstall(EnsurepipMixin, unittest.TestCase): def test_uninstall_skipped_when_not_installed(self): with fake_pip(None): ensurepip._uninstall_helper() self.assertFalse(self.run_pip.called) def test_uninstall_skipped_with_warning_for_wrong_version(self): with fake_pip("not a valid version"): with test.support.captured_stderr() as stderr: ensurepip._uninstall_helper() warning = stderr.getvalue().strip() self.assertIn("only uninstall a matching version", warning) self.assertFalse(self.run_pip.called) def test_uninstall(self): with fake_pip(): ensurepip._uninstall_helper() self.run_pip.assert_called_once_with( [ "uninstall", "-y", "--disable-pip-version-check", "pip", "setuptools", ] ) def test_uninstall_with_verbosity_1(self): with fake_pip(): ensurepip._uninstall_helper(verbosity=1) self.run_pip.assert_called_once_with( [ "uninstall", "-y", "--disable-pip-version-check", "-v", "pip", "setuptools", ] ) def test_uninstall_with_verbosity_2(self): with fake_pip(): ensurepip._uninstall_helper(verbosity=2) self.run_pip.assert_called_once_with( [ "uninstall", "-y", "--disable-pip-version-check", "-vv", "pip", "setuptools", ] ) def test_uninstall_with_verbosity_3(self): with fake_pip(): ensurepip._uninstall_helper(verbosity=3) self.run_pip.assert_called_once_with( [ "uninstall", "-y", "--disable-pip-version-check", "-vvv", "pip", "setuptools", ] ) def test_pip_environment_variables_removed(self): # ensurepip deliberately ignores all pip environment variables # See http://bugs.python.org/issue19734 for details self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder" with fake_pip(): ensurepip._uninstall_helper() self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ) def test_pip_config_file_disabled(self): # ensurepip deliberately ignores the pip config file # See http://bugs.python.org/issue20053 for details with fake_pip(): ensurepip._uninstall_helper() self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull) # Basic testing of the main functions and their argument parsing EXPECTED_VERSION_OUTPUT = "pip " + ensurepip._PIP_VERSION class TestBootstrappingMainFunction(EnsurepipMixin, unittest.TestCase): def test_bootstrap_version(self): with test.support.captured_stdout() as stdout: with self.assertRaises(SystemExit): ensurepip._main(["--version"]) result = stdout.getvalue().strip() self.assertEqual(result, EXPECTED_VERSION_OUTPUT) self.assertFalse(self.run_pip.called) def test_basic_bootstrapping(self): exit_code = ensurepip._main([]) self.run_pip.assert_called_once_with( [ "install", "--no-index", "--find-links", unittest.mock.ANY, "setuptools", "pip", ], unittest.mock.ANY, ) additional_paths = self.run_pip.call_args[0][1] self.assertEqual(len(additional_paths), 2) self.assertEqual(exit_code, 0) def test_bootstrapping_error_code(self): self.run_pip.return_value = 2 exit_code = ensurepip._main([]) self.assertEqual(exit_code, 2) class TestUninstallationMainFunction(EnsurepipMixin, unittest.TestCase): def test_uninstall_version(self): with test.support.captured_stdout() as stdout: with self.assertRaises(SystemExit): ensurepip._uninstall._main(["--version"]) result = stdout.getvalue().strip() self.assertEqual(result, EXPECTED_VERSION_OUTPUT) self.assertFalse(self.run_pip.called) def test_basic_uninstall(self): with fake_pip(): exit_code = ensurepip._uninstall._main([]) self.run_pip.assert_called_once_with( [ "uninstall", "-y", "--disable-pip-version-check", "pip", "setuptools", ] ) self.assertEqual(exit_code, 0) def test_uninstall_error_code(self): with fake_pip(): self.run_pip.return_value = 2 exit_code = ensurepip._uninstall._main([]) self.assertEqual(exit_code, 2) 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_pathlib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pathlib.py
import collections.abc import io import os import sys import errno import pathlib import pickle import socket import stat import tempfile import unittest from unittest import mock from test import support from test.support import TESTFN, FakePath try: import grp, pwd except ImportError: grp = pwd = None class _BaseFlavourTest(object): def _check_parse_parts(self, arg, expected): f = self.flavour.parse_parts sep = self.flavour.sep altsep = self.flavour.altsep actual = f([x.replace('/', sep) for x in arg]) self.assertEqual(actual, expected) if altsep: actual = f([x.replace('/', altsep) for x in arg]) self.assertEqual(actual, expected) def test_parse_parts_common(self): check = self._check_parse_parts sep = self.flavour.sep # Unanchored parts check([], ('', '', [])) check(['a'], ('', '', ['a'])) check(['a/'], ('', '', ['a'])) check(['a', 'b'], ('', '', ['a', 'b'])) # Expansion check(['a/b'], ('', '', ['a', 'b'])) check(['a/b/'], ('', '', ['a', 'b'])) check(['a', 'b/c', 'd'], ('', '', ['a', 'b', 'c', 'd'])) # Collapsing and stripping excess slashes check(['a', 'b//c', 'd'], ('', '', ['a', 'b', 'c', 'd'])) check(['a', 'b/c/', 'd'], ('', '', ['a', 'b', 'c', 'd'])) # Eliminating standalone dots check(['.'], ('', '', [])) check(['.', '.', 'b'], ('', '', ['b'])) check(['a', '.', 'b'], ('', '', ['a', 'b'])) check(['a', '.', '.'], ('', '', ['a'])) # The first part is anchored check(['/a/b'], ('', sep, [sep, 'a', 'b'])) check(['/a', 'b'], ('', sep, [sep, 'a', 'b'])) check(['/a/', 'b'], ('', sep, [sep, 'a', 'b'])) # Ignoring parts before an anchored part check(['a', '/b', 'c'], ('', sep, [sep, 'b', 'c'])) check(['a', '/b', '/c'], ('', sep, [sep, 'c'])) class PosixFlavourTest(_BaseFlavourTest, unittest.TestCase): flavour = pathlib._posix_flavour def test_parse_parts(self): check = self._check_parse_parts # Collapsing of excess leading slashes, except for the double-slash # special case. check(['//a', 'b'], ('', '//', ['//', 'a', 'b'])) check(['///a', 'b'], ('', '/', ['/', 'a', 'b'])) check(['////a', 'b'], ('', '/', ['/', 'a', 'b'])) # Paths which look like NT paths aren't treated specially check(['c:a'], ('', '', ['c:a'])) check(['c:\\a'], ('', '', ['c:\\a'])) check(['\\a'], ('', '', ['\\a'])) def test_splitroot(self): f = self.flavour.splitroot self.assertEqual(f(''), ('', '', '')) self.assertEqual(f('a'), ('', '', 'a')) self.assertEqual(f('a/b'), ('', '', 'a/b')) self.assertEqual(f('a/b/'), ('', '', 'a/b/')) self.assertEqual(f('/a'), ('', '/', 'a')) self.assertEqual(f('/a/b'), ('', '/', 'a/b')) self.assertEqual(f('/a/b/'), ('', '/', 'a/b/')) # The root is collapsed when there are redundant slashes # except when there are exactly two leading slashes, which # is a special case in POSIX. self.assertEqual(f('//a'), ('', '//', 'a')) self.assertEqual(f('///a'), ('', '/', 'a')) self.assertEqual(f('///a/b'), ('', '/', 'a/b')) # Paths which look like NT paths aren't treated specially self.assertEqual(f('c:/a/b'), ('', '', 'c:/a/b')) self.assertEqual(f('\\/a/b'), ('', '', '\\/a/b')) self.assertEqual(f('\\a\\b'), ('', '', '\\a\\b')) class NTFlavourTest(_BaseFlavourTest, unittest.TestCase): flavour = pathlib._windows_flavour def test_parse_parts(self): check = self._check_parse_parts # First part is anchored check(['c:'], ('c:', '', ['c:'])) check(['c:/'], ('c:', '\\', ['c:\\'])) check(['/'], ('', '\\', ['\\'])) check(['c:a'], ('c:', '', ['c:', 'a'])) check(['c:/a'], ('c:', '\\', ['c:\\', 'a'])) check(['/a'], ('', '\\', ['\\', 'a'])) # UNC paths check(['//a/b'], ('\\\\a\\b', '\\', ['\\\\a\\b\\'])) check(['//a/b/'], ('\\\\a\\b', '\\', ['\\\\a\\b\\'])) check(['//a/b/c'], ('\\\\a\\b', '\\', ['\\\\a\\b\\', 'c'])) # Second part is anchored, so that the first part is ignored check(['a', 'Z:b', 'c'], ('Z:', '', ['Z:', 'b', 'c'])) check(['a', 'Z:/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c'])) # UNC paths check(['a', '//b/c', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd'])) # Collapsing and stripping excess slashes check(['a', 'Z://b//c/', 'd/'], ('Z:', '\\', ['Z:\\', 'b', 'c', 'd'])) # UNC paths check(['a', '//b/c//', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd'])) # Extended paths check(['//?/c:/'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\'])) check(['//?/c:/a'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'a'])) check(['//?/c:/a', '/b'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'b'])) # Extended UNC paths (format is "\\?\UNC\server\share") check(['//?/UNC/b/c'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\'])) check(['//?/UNC/b/c/d'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\', 'd'])) # Second part has a root but not drive check(['a', '/b', 'c'], ('', '\\', ['\\', 'b', 'c'])) check(['Z:/a', '/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c'])) check(['//?/Z:/a', '/b', 'c'], ('\\\\?\\Z:', '\\', ['\\\\?\\Z:\\', 'b', 'c'])) def test_splitroot(self): f = self.flavour.splitroot self.assertEqual(f(''), ('', '', '')) self.assertEqual(f('a'), ('', '', 'a')) self.assertEqual(f('a\\b'), ('', '', 'a\\b')) self.assertEqual(f('\\a'), ('', '\\', 'a')) self.assertEqual(f('\\a\\b'), ('', '\\', 'a\\b')) self.assertEqual(f('c:a\\b'), ('c:', '', 'a\\b')) self.assertEqual(f('c:\\a\\b'), ('c:', '\\', 'a\\b')) # Redundant slashes in the root are collapsed self.assertEqual(f('\\\\a'), ('', '\\', 'a')) self.assertEqual(f('\\\\\\a/b'), ('', '\\', 'a/b')) self.assertEqual(f('c:\\\\a'), ('c:', '\\', 'a')) self.assertEqual(f('c:\\\\\\a/b'), ('c:', '\\', 'a/b')) # Valid UNC paths self.assertEqual(f('\\\\a\\b'), ('\\\\a\\b', '\\', '')) self.assertEqual(f('\\\\a\\b\\'), ('\\\\a\\b', '\\', '')) self.assertEqual(f('\\\\a\\b\\c\\d'), ('\\\\a\\b', '\\', 'c\\d')) # These are non-UNC paths (according to ntpath.py and test_ntpath) # However, command.com says such paths are invalid, so it's # difficult to know what the right semantics are self.assertEqual(f('\\\\\\a\\b'), ('', '\\', 'a\\b')) self.assertEqual(f('\\\\a'), ('', '\\', 'a')) # # Tests for the pure classes # class _BasePurePathTest(object): # keys are canonical paths, values are list of tuples of arguments # supposed to produce equal paths equivalences = { 'a/b': [ ('a', 'b'), ('a/', 'b'), ('a', 'b/'), ('a/', 'b/'), ('a/b/',), ('a//b',), ('a//b//',), # empty components get removed ('', 'a', 'b'), ('a', '', 'b'), ('a', 'b', ''), ], '/b/c/d': [ ('a', '/b/c', 'd'), ('a', '///b//c', 'd/'), ('/a', '/b/c', 'd'), # empty components get removed ('/', 'b', '', 'c/d'), ('/', '', 'b/c/d'), ('', '/b/c/d'), ], } def setUp(self): p = self.cls('a') self.flavour = p._flavour self.sep = self.flavour.sep self.altsep = self.flavour.altsep def test_constructor_common(self): P = self.cls p = P('a') self.assertIsInstance(p, P) P('a', 'b', 'c') P('/a', 'b', 'c') P('a/b/c') P('/a/b/c') P(FakePath("a/b/c")) self.assertEqual(P(P('a')), P('a')) self.assertEqual(P(P('a'), 'b'), P('a/b')) self.assertEqual(P(P('a'), P('b')), P('a/b')) self.assertEqual(P(P('a'), P('b'), P('c')), P(FakePath("a/b/c"))) def _check_str_subclass(self, *args): # Issue #21127: it should be possible to construct a PurePath object # from a str subclass instance, and it then gets converted to # a pure str object. class StrSubclass(str): pass P = self.cls p = P(*(StrSubclass(x) for x in args)) self.assertEqual(p, P(*args)) for part in p.parts: self.assertIs(type(part), str) def test_str_subclass_common(self): self._check_str_subclass('') self._check_str_subclass('.') self._check_str_subclass('a') self._check_str_subclass('a/b.txt') self._check_str_subclass('/a/b.txt') def test_join_common(self): P = self.cls p = P('a/b') pp = p.joinpath('c') self.assertEqual(pp, P('a/b/c')) self.assertIs(type(pp), type(p)) pp = p.joinpath('c', 'd') self.assertEqual(pp, P('a/b/c/d')) pp = p.joinpath(P('c')) self.assertEqual(pp, P('a/b/c')) pp = p.joinpath('/c') self.assertEqual(pp, P('/c')) def test_div_common(self): # Basically the same as joinpath() P = self.cls p = P('a/b') pp = p / 'c' self.assertEqual(pp, P('a/b/c')) self.assertIs(type(pp), type(p)) pp = p / 'c/d' self.assertEqual(pp, P('a/b/c/d')) pp = p / 'c' / 'd' self.assertEqual(pp, P('a/b/c/d')) pp = 'c' / p / 'd' self.assertEqual(pp, P('c/a/b/d')) pp = p / P('c') self.assertEqual(pp, P('a/b/c')) pp = p/ '/c' self.assertEqual(pp, P('/c')) def _check_str(self, expected, args): p = self.cls(*args) self.assertEqual(str(p), expected.replace('/', self.sep)) def test_str_common(self): # Canonicalized paths roundtrip for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'): self._check_str(pathstr, (pathstr,)) # Special case for the empty path self._check_str('.', ('',)) # Other tests for str() are in test_equivalences() def test_as_posix_common(self): P = self.cls for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'): self.assertEqual(P(pathstr).as_posix(), pathstr) # Other tests for as_posix() are in test_equivalences() def test_as_bytes_common(self): sep = os.fsencode(self.sep) P = self.cls self.assertEqual(bytes(P('a/b')), b'a' + sep + b'b') def test_as_uri_common(self): P = self.cls with self.assertRaises(ValueError): P('a').as_uri() with self.assertRaises(ValueError): P().as_uri() def test_repr_common(self): for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'): p = self.cls(pathstr) clsname = p.__class__.__name__ r = repr(p) # The repr() is in the form ClassName("forward-slashes path") self.assertTrue(r.startswith(clsname + '('), r) self.assertTrue(r.endswith(')'), r) inner = r[len(clsname) + 1 : -1] self.assertEqual(eval(inner), p.as_posix()) # The repr() roundtrips q = eval(r, pathlib.__dict__) self.assertIs(q.__class__, p.__class__) self.assertEqual(q, p) self.assertEqual(repr(q), r) def test_eq_common(self): P = self.cls self.assertEqual(P('a/b'), P('a/b')) self.assertEqual(P('a/b'), P('a', 'b')) self.assertNotEqual(P('a/b'), P('a')) self.assertNotEqual(P('a/b'), P('/a/b')) self.assertNotEqual(P('a/b'), P()) self.assertNotEqual(P('/a/b'), P('/')) self.assertNotEqual(P(), P('/')) self.assertNotEqual(P(), "") self.assertNotEqual(P(), {}) self.assertNotEqual(P(), int) def test_match_common(self): P = self.cls self.assertRaises(ValueError, P('a').match, '') self.assertRaises(ValueError, P('a').match, '.') # Simple relative pattern self.assertTrue(P('b.py').match('b.py')) self.assertTrue(P('a/b.py').match('b.py')) self.assertTrue(P('/a/b.py').match('b.py')) self.assertFalse(P('a.py').match('b.py')) self.assertFalse(P('b/py').match('b.py')) self.assertFalse(P('/a.py').match('b.py')) self.assertFalse(P('b.py/c').match('b.py')) # Wilcard relative pattern self.assertTrue(P('b.py').match('*.py')) self.assertTrue(P('a/b.py').match('*.py')) self.assertTrue(P('/a/b.py').match('*.py')) self.assertFalse(P('b.pyc').match('*.py')) self.assertFalse(P('b./py').match('*.py')) self.assertFalse(P('b.py/c').match('*.py')) # Multi-part relative pattern self.assertTrue(P('ab/c.py').match('a*/*.py')) self.assertTrue(P('/d/ab/c.py').match('a*/*.py')) self.assertFalse(P('a.py').match('a*/*.py')) self.assertFalse(P('/dab/c.py').match('a*/*.py')) self.assertFalse(P('ab/c.py/d').match('a*/*.py')) # Absolute pattern self.assertTrue(P('/b.py').match('/*.py')) self.assertFalse(P('b.py').match('/*.py')) self.assertFalse(P('a/b.py').match('/*.py')) self.assertFalse(P('/a/b.py').match('/*.py')) # Multi-part absolute pattern self.assertTrue(P('/a/b.py').match('/a/*.py')) self.assertFalse(P('/ab.py').match('/a/*.py')) self.assertFalse(P('/a/b/c.py').match('/a/*.py')) def test_ordering_common(self): # Ordering is tuple-alike def assertLess(a, b): self.assertLess(a, b) self.assertGreater(b, a) P = self.cls a = P('a') b = P('a/b') c = P('abc') d = P('b') assertLess(a, b) assertLess(a, c) assertLess(a, d) assertLess(b, c) assertLess(c, d) P = self.cls a = P('/a') b = P('/a/b') c = P('/abc') d = P('/b') assertLess(a, b) assertLess(a, c) assertLess(a, d) assertLess(b, c) assertLess(c, d) with self.assertRaises(TypeError): P() < {} def test_parts_common(self): # `parts` returns a tuple sep = self.sep P = self.cls p = P('a/b') parts = p.parts self.assertEqual(parts, ('a', 'b')) # The object gets reused self.assertIs(parts, p.parts) # When the path is absolute, the anchor is a separate part p = P('/a/b') parts = p.parts self.assertEqual(parts, (sep, 'a', 'b')) def test_fspath_common(self): P = self.cls p = P('a/b') self._check_str(p.__fspath__(), ('a/b',)) self._check_str(os.fspath(p), ('a/b',)) def test_equivalences(self): for k, tuples in self.equivalences.items(): canon = k.replace('/', self.sep) posix = k.replace(self.sep, '/') if canon != posix: tuples = tuples + [ tuple(part.replace('/', self.sep) for part in t) for t in tuples ] tuples.append((posix, )) pcanon = self.cls(canon) for t in tuples: p = self.cls(*t) self.assertEqual(p, pcanon, "failed with args {}".format(t)) self.assertEqual(hash(p), hash(pcanon)) self.assertEqual(str(p), canon) self.assertEqual(p.as_posix(), posix) def test_parent_common(self): # Relative P = self.cls p = P('a/b/c') self.assertEqual(p.parent, P('a/b')) self.assertEqual(p.parent.parent, P('a')) self.assertEqual(p.parent.parent.parent, P()) self.assertEqual(p.parent.parent.parent.parent, P()) # Anchored p = P('/a/b/c') self.assertEqual(p.parent, P('/a/b')) self.assertEqual(p.parent.parent, P('/a')) self.assertEqual(p.parent.parent.parent, P('/')) self.assertEqual(p.parent.parent.parent.parent, P('/')) def test_parents_common(self): # Relative P = self.cls p = P('a/b/c') par = p.parents self.assertEqual(len(par), 3) self.assertEqual(par[0], P('a/b')) self.assertEqual(par[1], P('a')) self.assertEqual(par[2], P('.')) self.assertEqual(list(par), [P('a/b'), P('a'), P('.')]) with self.assertRaises(IndexError): par[-1] with self.assertRaises(IndexError): par[3] with self.assertRaises(TypeError): par[0] = p # Anchored p = P('/a/b/c') par = p.parents self.assertEqual(len(par), 3) self.assertEqual(par[0], P('/a/b')) self.assertEqual(par[1], P('/a')) self.assertEqual(par[2], P('/')) self.assertEqual(list(par), [P('/a/b'), P('/a'), P('/')]) with self.assertRaises(IndexError): par[3] def test_drive_common(self): P = self.cls self.assertEqual(P('a/b').drive, '') self.assertEqual(P('/a/b').drive, '') self.assertEqual(P('').drive, '') def test_root_common(self): P = self.cls sep = self.sep self.assertEqual(P('').root, '') self.assertEqual(P('a/b').root, '') self.assertEqual(P('/').root, sep) self.assertEqual(P('/a/b').root, sep) def test_anchor_common(self): P = self.cls sep = self.sep self.assertEqual(P('').anchor, '') self.assertEqual(P('a/b').anchor, '') self.assertEqual(P('/').anchor, sep) self.assertEqual(P('/a/b').anchor, sep) def test_name_common(self): P = self.cls self.assertEqual(P('').name, '') self.assertEqual(P('.').name, '') self.assertEqual(P('/').name, '') self.assertEqual(P('a/b').name, 'b') self.assertEqual(P('/a/b').name, 'b') self.assertEqual(P('/a/b/.').name, 'b') self.assertEqual(P('a/b.py').name, 'b.py') self.assertEqual(P('/a/b.py').name, 'b.py') def test_suffix_common(self): P = self.cls self.assertEqual(P('').suffix, '') self.assertEqual(P('.').suffix, '') self.assertEqual(P('..').suffix, '') self.assertEqual(P('/').suffix, '') self.assertEqual(P('a/b').suffix, '') self.assertEqual(P('/a/b').suffix, '') self.assertEqual(P('/a/b/.').suffix, '') self.assertEqual(P('a/b.py').suffix, '.py') self.assertEqual(P('/a/b.py').suffix, '.py') self.assertEqual(P('a/.hgrc').suffix, '') self.assertEqual(P('/a/.hgrc').suffix, '') self.assertEqual(P('a/.hg.rc').suffix, '.rc') self.assertEqual(P('/a/.hg.rc').suffix, '.rc') self.assertEqual(P('a/b.tar.gz').suffix, '.gz') self.assertEqual(P('/a/b.tar.gz').suffix, '.gz') self.assertEqual(P('a/Some name. Ending with a dot.').suffix, '') self.assertEqual(P('/a/Some name. Ending with a dot.').suffix, '') def test_suffixes_common(self): P = self.cls self.assertEqual(P('').suffixes, []) self.assertEqual(P('.').suffixes, []) self.assertEqual(P('/').suffixes, []) self.assertEqual(P('a/b').suffixes, []) self.assertEqual(P('/a/b').suffixes, []) self.assertEqual(P('/a/b/.').suffixes, []) self.assertEqual(P('a/b.py').suffixes, ['.py']) self.assertEqual(P('/a/b.py').suffixes, ['.py']) self.assertEqual(P('a/.hgrc').suffixes, []) self.assertEqual(P('/a/.hgrc').suffixes, []) self.assertEqual(P('a/.hg.rc').suffixes, ['.rc']) self.assertEqual(P('/a/.hg.rc').suffixes, ['.rc']) self.assertEqual(P('a/b.tar.gz').suffixes, ['.tar', '.gz']) self.assertEqual(P('/a/b.tar.gz').suffixes, ['.tar', '.gz']) self.assertEqual(P('a/Some name. Ending with a dot.').suffixes, []) self.assertEqual(P('/a/Some name. Ending with a dot.').suffixes, []) def test_stem_common(self): P = self.cls self.assertEqual(P('').stem, '') self.assertEqual(P('.').stem, '') self.assertEqual(P('..').stem, '..') self.assertEqual(P('/').stem, '') self.assertEqual(P('a/b').stem, 'b') self.assertEqual(P('a/b.py').stem, 'b') self.assertEqual(P('a/.hgrc').stem, '.hgrc') self.assertEqual(P('a/.hg.rc').stem, '.hg') self.assertEqual(P('a/b.tar.gz').stem, 'b.tar') self.assertEqual(P('a/Some name. Ending with a dot.').stem, 'Some name. Ending with a dot.') def test_with_name_common(self): P = self.cls self.assertEqual(P('a/b').with_name('d.xml'), P('a/d.xml')) self.assertEqual(P('/a/b').with_name('d.xml'), P('/a/d.xml')) self.assertEqual(P('a/b.py').with_name('d.xml'), P('a/d.xml')) self.assertEqual(P('/a/b.py').with_name('d.xml'), P('/a/d.xml')) self.assertEqual(P('a/Dot ending.').with_name('d.xml'), P('a/d.xml')) self.assertEqual(P('/a/Dot ending.').with_name('d.xml'), P('/a/d.xml')) self.assertRaises(ValueError, P('').with_name, 'd.xml') self.assertRaises(ValueError, P('.').with_name, 'd.xml') self.assertRaises(ValueError, P('/').with_name, 'd.xml') self.assertRaises(ValueError, P('a/b').with_name, '') self.assertRaises(ValueError, P('a/b').with_name, '/c') self.assertRaises(ValueError, P('a/b').with_name, 'c/') self.assertRaises(ValueError, P('a/b').with_name, 'c/d') def test_with_suffix_common(self): P = self.cls self.assertEqual(P('a/b').with_suffix('.gz'), P('a/b.gz')) self.assertEqual(P('/a/b').with_suffix('.gz'), P('/a/b.gz')) self.assertEqual(P('a/b.py').with_suffix('.gz'), P('a/b.gz')) self.assertEqual(P('/a/b.py').with_suffix('.gz'), P('/a/b.gz')) # Stripping suffix self.assertEqual(P('a/b.py').with_suffix(''), P('a/b')) self.assertEqual(P('/a/b').with_suffix(''), P('/a/b')) # Path doesn't have a "filename" component self.assertRaises(ValueError, P('').with_suffix, '.gz') self.assertRaises(ValueError, P('.').with_suffix, '.gz') self.assertRaises(ValueError, P('/').with_suffix, '.gz') # Invalid suffix self.assertRaises(ValueError, P('a/b').with_suffix, 'gz') self.assertRaises(ValueError, P('a/b').with_suffix, '/') self.assertRaises(ValueError, P('a/b').with_suffix, '.') self.assertRaises(ValueError, P('a/b').with_suffix, '/.gz') self.assertRaises(ValueError, P('a/b').with_suffix, 'c/d') self.assertRaises(ValueError, P('a/b').with_suffix, '.c/.d') self.assertRaises(ValueError, P('a/b').with_suffix, './.d') self.assertRaises(ValueError, P('a/b').with_suffix, '.d/.') self.assertRaises(ValueError, P('a/b').with_suffix, (self.flavour.sep, 'd')) def test_relative_to_common(self): P = self.cls p = P('a/b') self.assertRaises(TypeError, p.relative_to) self.assertRaises(TypeError, p.relative_to, b'a') self.assertEqual(p.relative_to(P()), P('a/b')) self.assertEqual(p.relative_to(''), P('a/b')) self.assertEqual(p.relative_to(P('a')), P('b')) self.assertEqual(p.relative_to('a'), P('b')) self.assertEqual(p.relative_to('a/'), P('b')) self.assertEqual(p.relative_to(P('a/b')), P()) self.assertEqual(p.relative_to('a/b'), P()) # With several args self.assertEqual(p.relative_to('a', 'b'), P()) # Unrelated paths self.assertRaises(ValueError, p.relative_to, P('c')) self.assertRaises(ValueError, p.relative_to, P('a/b/c')) self.assertRaises(ValueError, p.relative_to, P('a/c')) self.assertRaises(ValueError, p.relative_to, P('/a')) p = P('/a/b') self.assertEqual(p.relative_to(P('/')), P('a/b')) self.assertEqual(p.relative_to('/'), P('a/b')) self.assertEqual(p.relative_to(P('/a')), P('b')) self.assertEqual(p.relative_to('/a'), P('b')) self.assertEqual(p.relative_to('/a/'), P('b')) self.assertEqual(p.relative_to(P('/a/b')), P()) self.assertEqual(p.relative_to('/a/b'), P()) # Unrelated paths self.assertRaises(ValueError, p.relative_to, P('/c')) self.assertRaises(ValueError, p.relative_to, P('/a/b/c')) self.assertRaises(ValueError, p.relative_to, P('/a/c')) self.assertRaises(ValueError, p.relative_to, P()) self.assertRaises(ValueError, p.relative_to, '') self.assertRaises(ValueError, p.relative_to, P('a')) def test_pickling_common(self): P = self.cls p = P('/a/b') for proto in range(0, pickle.HIGHEST_PROTOCOL + 1): dumped = pickle.dumps(p, proto) pp = pickle.loads(dumped) self.assertIs(pp.__class__, p.__class__) self.assertEqual(pp, p) self.assertEqual(hash(pp), hash(p)) self.assertEqual(str(pp), str(p)) class PurePosixPathTest(_BasePurePathTest, unittest.TestCase): cls = pathlib.PurePosixPath def test_root(self): P = self.cls self.assertEqual(P('/a/b').root, '/') self.assertEqual(P('///a/b').root, '/') # POSIX special case for two leading slashes self.assertEqual(P('//a/b').root, '//') def test_eq(self): P = self.cls self.assertNotEqual(P('a/b'), P('A/b')) self.assertEqual(P('/a'), P('///a')) self.assertNotEqual(P('/a'), P('//a')) def test_as_uri(self): P = self.cls self.assertEqual(P('/').as_uri(), 'file:///') self.assertEqual(P('/a/b.c').as_uri(), 'file:///a/b.c') self.assertEqual(P('/a/b%#c').as_uri(), 'file:///a/b%25%23c') def test_as_uri_non_ascii(self): from urllib.parse import quote_from_bytes P = self.cls try: os.fsencode('\xe9') except UnicodeEncodeError: self.skipTest("\\xe9 cannot be encoded to the filesystem encoding") self.assertEqual(P('/a/b\xe9').as_uri(), 'file:///a/b' + quote_from_bytes(os.fsencode('\xe9'))) def test_match(self): P = self.cls self.assertFalse(P('A.py').match('a.PY')) def test_is_absolute(self): P = self.cls self.assertFalse(P().is_absolute()) self.assertFalse(P('a').is_absolute()) self.assertFalse(P('a/b/').is_absolute()) self.assertTrue(P('/').is_absolute()) self.assertTrue(P('/a').is_absolute()) self.assertTrue(P('/a/b/').is_absolute()) self.assertTrue(P('//a').is_absolute()) self.assertTrue(P('//a/b').is_absolute()) def test_is_reserved(self): P = self.cls self.assertIs(False, P('').is_reserved()) self.assertIs(False, P('/').is_reserved()) self.assertIs(False, P('/foo/bar').is_reserved()) self.assertIs(False, P('/dev/con/PRN/NUL').is_reserved()) def test_join(self): P = self.cls p = P('//a') pp = p.joinpath('b') self.assertEqual(pp, P('//a/b')) pp = P('/a').joinpath('//c') self.assertEqual(pp, P('//c')) pp = P('//a').joinpath('/c') self.assertEqual(pp, P('/c')) def test_div(self): # Basically the same as joinpath() P = self.cls p = P('//a') pp = p / 'b' self.assertEqual(pp, P('//a/b')) pp = P('/a') / '//c' self.assertEqual(pp, P('//c')) pp = P('//a') / '/c' self.assertEqual(pp, P('/c')) class PureWindowsPathTest(_BasePurePathTest, unittest.TestCase): cls = pathlib.PureWindowsPath equivalences = _BasePurePathTest.equivalences.copy() equivalences.update({ 'c:a': [ ('c:', 'a'), ('c:', 'a/'), ('/', 'c:', 'a') ], 'c:/a': [ ('c:/', 'a'), ('c:', '/', 'a'), ('c:', '/a'), ('/z', 'c:/', 'a'), ('//x/y', 'c:/', 'a'), ], '//a/b/': [ ('//a/b',) ], '//a/b/c': [ ('//a/b', 'c'), ('//a/b/', 'c'), ], }) def test_str(self): p = self.cls('a/b/c') self.assertEqual(str(p), 'a\\b\\c') p = self.cls('c:/a/b/c') self.assertEqual(str(p), 'c:\\a\\b\\c') p = self.cls('//a/b') self.assertEqual(str(p), '\\\\a\\b\\') p = self.cls('//a/b/c') self.assertEqual(str(p), '\\\\a\\b\\c') p = self.cls('//a/b/c/d') self.assertEqual(str(p), '\\\\a\\b\\c\\d') def test_str_subclass(self): self._check_str_subclass('c:') self._check_str_subclass('c:a') self._check_str_subclass('c:a\\b.txt') self._check_str_subclass('c:\\') self._check_str_subclass('c:\\a') self._check_str_subclass('c:\\a\\b.txt') self._check_str_subclass('\\\\some\\share') self._check_str_subclass('\\\\some\\share\\a') self._check_str_subclass('\\\\some\\share\\a\\b.txt') def test_eq(self): P = self.cls self.assertEqual(P('c:a/b'), P('c:a/b')) self.assertEqual(P('c:a/b'), P('c:', 'a', 'b')) self.assertNotEqual(P('c:a/b'), P('d:a/b')) self.assertNotEqual(P('c:a/b'), P('c:/a/b')) self.assertNotEqual(P('/a/b'), P('c:/a/b')) # Case-insensitivity self.assertEqual(P('a/B'), P('A/b')) self.assertEqual(P('C:a/B'), P('c:A/b')) self.assertEqual(P('//Some/SHARE/a/B'), P('//somE/share/A/b')) def test_as_uri(self): P = self.cls with self.assertRaises(ValueError): P('/a/b').as_uri() with self.assertRaises(ValueError): P('c:a/b').as_uri() self.assertEqual(P('c:/').as_uri(), 'file:///c:/') self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c') self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c') self.assertEqual(P('c:/a/b\xe9').as_uri(), 'file:///c:/a/b%C3%A9') self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/') self.assertEqual(P('//some/share/a/b.c').as_uri(), 'file://some/share/a/b.c') self.assertEqual(P('//some/share/a/b%#c\xe9').as_uri(), 'file://some/share/a/b%25%23c%C3%A9') def test_match_common(self): P = self.cls # Absolute patterns self.assertTrue(P('c:/b.py').match('/*.py')) self.assertTrue(P('c:/b.py').match('c:*.py')) self.assertTrue(P('c:/b.py').match('c:/*.py')) self.assertFalse(P('d:/b.py').match('c:/*.py')) # wrong drive self.assertFalse(P('b.py').match('/*.py')) self.assertFalse(P('b.py').match('c:*.py')) self.assertFalse(P('b.py').match('c:/*.py')) self.assertFalse(P('c:b.py').match('/*.py')) self.assertFalse(P('c:b.py').match('c:/*.py')) self.assertFalse(P('/b.py').match('c:*.py')) self.assertFalse(P('/b.py').match('c:/*.py')) # UNC patterns self.assertTrue(P('//some/share/a.py').match('/*.py')) self.assertTrue(P('//some/share/a.py').match('//some/share/*.py')) self.assertFalse(P('//other/share/a.py').match('//some/share/*.py')) self.assertFalse(P('//some/share/a/b.py').match('//some/share/*.py')) # Case-insensitivity self.assertTrue(P('B.py').match('b.PY')) self.assertTrue(P('c:/a/B.Py').match('C:/A/*.pY')) self.assertTrue(P('//Some/Share/B.Py').match('//somE/sharE/*.pY')) def test_ordering_common(self): # Case-insensitivity def assertOrderedEqual(a, b): self.assertLessEqual(a, b) self.assertGreaterEqual(b, a) P = self.cls p = P('c:A/b') q = P('C:a/B') assertOrderedEqual(p, q) self.assertFalse(p < q) self.assertFalse(p > q) p = P('//some/Share/A/b') q = P('//Some/SHARE/a/B') assertOrderedEqual(p, q)
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_strftime.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_strftime.py
""" Unittest for time.strftime """ import calendar import sys import re from test import support import time import unittest # helper functions def fixasctime(s): if s[8] == ' ': s = s[:8] + '0' + s[9:] return s def escapestr(text, ampm): """ Escape text to deal with possible locale values that have regex syntax while allowing regex syntax used for comparison. """ new_text = re.escape(text) new_text = new_text.replace(re.escape(ampm), ampm) new_text = new_text.replace(r'\%', '%') new_text = new_text.replace(r'\:', ':') new_text = new_text.replace(r'\?', '?') return new_text class StrftimeTest(unittest.TestCase): def _update_variables(self, now): # we must update the local variables on every cycle self.gmt = time.gmtime(now) now = time.localtime(now) if now[3] < 12: self.ampm='(AM|am)' else: self.ampm='(PM|pm)' self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0))) try: if now[8]: self.tz = time.tzname[1] else: self.tz = time.tzname[0] except AttributeError: self.tz = '' if now[3] > 12: self.clock12 = now[3] - 12 elif now[3] > 0: self.clock12 = now[3] else: self.clock12 = 12 self.now = now def setUp(self): try: import java java.util.Locale.setDefault(java.util.Locale.US) except ImportError: from locale import setlocale, LC_TIME saved_locale = setlocale(LC_TIME) setlocale(LC_TIME, 'C') self.addCleanup(setlocale, LC_TIME, saved_locale) def test_strftime(self): now = time.time() self._update_variables(now) self.strftest1(now) self.strftest2(now) if support.verbose: print("Strftime test, platform: %s, Python version: %s" % \ (sys.platform, sys.version.split()[0])) for j in range(-5, 5): for i in range(25): arg = now + (i+j*100)*23*3603 self._update_variables(arg) self.strftest1(arg) self.strftest2(arg) def strftest1(self, now): if support.verbose: print("strftime test for", time.ctime(now)) now = self.now # Make sure any characters that could be taken as regex syntax is # escaped in escapestr() expectations = ( ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%A', calendar.day_name[now[6]], 'full weekday name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%B', calendar.month_name[now[1]], 'full month name'), # %c see below ('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%H', '%02d' % now[3], 'hour (00-23)'), ('%I', '%02d' % self.clock12, 'hour (01-12)'), ('%j', '%03d' % now[7], 'julian day (001-366)'), ('%m', '%02d' % now[1], 'month as number (01-12)'), ('%M', '%02d' % now[4], 'minute, (00-59)'), ('%p', self.ampm, 'AM or PM as appropriate'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%U', '%02d' % ((now[7] + self.jan1[6])//7), 'week number of the year (Sun 1st)'), ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%W', '%02d' % ((now[7] + (self.jan1[6] - 1)%7)//7), 'week number of the year (Mon 1st)'), # %x see below ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Y', '%d' % now[0], 'year with century'), # %Z see below ('%%', '%', 'single percent sign'), ) for e in expectations: # musn't raise a value error try: result = time.strftime(e[0], now) except ValueError as error: self.fail("strftime '%s' format gave error: %s" % (e[0], error)) if re.match(escapestr(e[1], self.ampm), result): continue if not result or result[0] == '%': self.fail("strftime does not support standard '%s' format (%s)" % (e[0], e[2])) else: self.fail("Conflict for %s (%s): expected %s, but got %s" % (e[0], e[2], e[1], result)) def strftest2(self, now): nowsecs = str(int(now))[:-1] now = self.now nonstandard_expectations = ( # These are standard but don't have predictable output ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), '%m/%d/%y %H:%M:%S'), ('%Z', '%s' % self.tz, 'time zone name'), # These are some platform specific extensions ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%n', '\n', 'newline character'), ('%r', '%02d:%02d:%02d %s' % (self.clock12, now[4], now[5], self.ampm), '%I:%M:%S %p'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%s', nowsecs, 'seconds since the Epoch in UCT'), ('%t', '\t', 'tab character'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%3y', '%03d' % (now[0]%100), 'year without century rendered using fieldwidth'), ) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError as result: msg = "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) if support.verbose: print(msg) continue if re.match(escapestr(e[1], self.ampm), result): if support.verbose: print("Supports nonstandard '%s' format (%s)" % (e[0], e[2])) elif not result or result[0] == '%': if support.verbose: print("Does not appear to support '%s' format (%s)" % \ (e[0], e[2])) else: if support.verbose: print("Conflict for nonstandard '%s' format (%s):" % \ (e[0], e[2])) print(" Expected %s, but got %s" % (e[1], result)) class Y1900Tests(unittest.TestCase): """A limitation of the MS C runtime library is that it crashes if a date before 1900 is passed with a format string containing "%y" """ def test_y_before_1900(self): # Issue #13674, #19634 t = (1899, 1, 1, 0, 0, 0, 0, 0, 0) if (sys.platform == "win32" or sys.platform.startswith(("aix", "sunos", "solaris"))): with self.assertRaises(ValueError): time.strftime("%y", t) else: self.assertEqual(time.strftime("%y", t), "99") def test_y_1900(self): self.assertEqual( time.strftime("%y", (1900, 1, 1, 0, 0, 0, 0, 0, 0)), "00") def test_y_after_1900(self): self.assertEqual( time.strftime("%y", (2013, 1, 1, 0, 0, 0, 0, 0, 0)), "13") 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_pulldom.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pulldom.py
import io import unittest import xml.sax from xml.sax.xmlreader import AttributesImpl from xml.sax.handler import feature_external_ges from xml.dom import pulldom from test.support import findfile tstfile = findfile("test.xml", subdir="xmltestdata") # A handy XML snippet, containing attributes, a namespace prefix, and a # self-closing tag: SMALL_SAMPLE = """<?xml version="1.0"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xdc="http://www.xml.com/books"> <!-- A comment --> <title>Introduction to XSL</title> <hr/> <p><xdc:author xdc:attrib="prefixed attribute" attrib="other attrib">A. Namespace</xdc:author></p> </html>""" class PullDOMTestCase(unittest.TestCase): def test_parse(self): """Minimal test of DOMEventStream.parse()""" # This just tests that parsing from a stream works. Actual parser # semantics are tested using parseString with a more focused XML # fragment. # Test with a filename: handler = pulldom.parse(tstfile) self.addCleanup(handler.stream.close) list(handler) # Test with a file object: with open(tstfile, "rb") as fin: list(pulldom.parse(fin)) def test_parse_semantics(self): """Test DOMEventStream parsing semantics.""" items = pulldom.parseString(SMALL_SAMPLE) evt, node = next(items) # Just check the node is a Document: self.assertTrue(hasattr(node, "createElement")) self.assertEqual(pulldom.START_DOCUMENT, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("html", node.tagName) self.assertEqual(2, len(node.attributes)) self.assertEqual(node.attributes.getNamedItem("xmlns:xdc").value, "http://www.xml.com/books") evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) # Line break evt, node = next(items) # XXX - A comment should be reported here! # self.assertEqual(pulldom.COMMENT, evt) # Line break after swallowed comment: self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual("title", node.tagName) title_node = node evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) self.assertEqual("Introduction to XSL", node.data) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("title", node.tagName) self.assertTrue(title_node is node) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("hr", node.tagName) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("hr", node.tagName) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(items) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("xdc:author", node.tagName) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("xdc:author", node.tagName) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) evt, node = next(items) self.assertEqual(pulldom.CHARACTERS, evt) evt, node = next(items) self.assertEqual(pulldom.END_ELEMENT, evt) # XXX No END_DOCUMENT item is ever obtained: #evt, node = next(items) #self.assertEqual(pulldom.END_DOCUMENT, evt) def test_expandItem(self): """Ensure expandItem works as expected.""" items = pulldom.parseString(SMALL_SAMPLE) # Loop through the nodes until we get to a "title" start tag: for evt, item in items: if evt == pulldom.START_ELEMENT and item.tagName == "title": items.expandNode(item) self.assertEqual(1, len(item.childNodes)) break else: self.fail("No \"title\" element detected in SMALL_SAMPLE!") # Loop until we get to the next start-element: for evt, node in items: if evt == pulldom.START_ELEMENT: break self.assertEqual("hr", node.tagName, "expandNode did not leave DOMEventStream in the correct state.") # Attempt to expand a standalone element: items.expandNode(node) self.assertEqual(next(items)[0], pulldom.CHARACTERS) evt, node = next(items) self.assertEqual(node.tagName, "p") items.expandNode(node) next(items) # Skip character data evt, node = next(items) self.assertEqual(node.tagName, "html") with self.assertRaises(StopIteration): next(items) items.clear() self.assertIsNone(items.parser) self.assertIsNone(items.stream) @unittest.expectedFailure def test_comment(self): """PullDOM does not receive "comment" events.""" items = pulldom.parseString(SMALL_SAMPLE) for evt, _ in items: if evt == pulldom.COMMENT: break else: self.fail("No comment was encountered") @unittest.expectedFailure def test_end_document(self): """PullDOM does not receive "end-document" events.""" items = pulldom.parseString(SMALL_SAMPLE) # Read all of the nodes up to and including </html>: for evt, node in items: if evt == pulldom.END_ELEMENT and node.tagName == "html": break try: # Assert that the next node is END_DOCUMENT: evt, node = next(items) self.assertEqual(pulldom.END_DOCUMENT, evt) except StopIteration: self.fail( "Ran out of events, but should have received END_DOCUMENT") def test_external_ges_default(self): parser = pulldom.parseString(SMALL_SAMPLE) saxparser = parser.parser ges = saxparser.getFeature(feature_external_ges) self.assertEqual(ges, False) class ThoroughTestCase(unittest.TestCase): """Test the hard-to-reach parts of pulldom.""" def test_thorough_parse(self): """Test some of the hard-to-reach parts of PullDOM.""" self._test_thorough(pulldom.parse(None, parser=SAXExerciser())) @unittest.expectedFailure def test_sax2dom_fail(self): """SAX2DOM can"t handle a PI before the root element.""" pd = SAX2DOMTestHelper(None, SAXExerciser(), 12) self._test_thorough(pd) def test_thorough_sax2dom(self): """Test some of the hard-to-reach parts of SAX2DOM.""" pd = SAX2DOMTestHelper(None, SAX2DOMExerciser(), 12) self._test_thorough(pd, False) def _test_thorough(self, pd, before_root=True): """Test some of the hard-to-reach parts of the parser, using a mock parser.""" evt, node = next(pd) self.assertEqual(pulldom.START_DOCUMENT, evt) # Just check the node is a Document: self.assertTrue(hasattr(node, "createElement")) if before_root: evt, node = next(pd) self.assertEqual(pulldom.COMMENT, evt) self.assertEqual("a comment", node.data) evt, node = next(pd) self.assertEqual(pulldom.PROCESSING_INSTRUCTION, evt) self.assertEqual("target", node.target) self.assertEqual("data", node.data) evt, node = next(pd) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("html", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.COMMENT, evt) self.assertEqual("a comment", node.data) evt, node = next(pd) self.assertEqual(pulldom.PROCESSING_INSTRUCTION, evt) self.assertEqual("target", node.target) self.assertEqual("data", node.data) evt, node = next(pd) self.assertEqual(pulldom.START_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.CHARACTERS, evt) self.assertEqual("text", node.data) evt, node = next(pd) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("p", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.END_ELEMENT, evt) self.assertEqual("html", node.tagName) evt, node = next(pd) self.assertEqual(pulldom.END_DOCUMENT, evt) class SAXExerciser(object): """A fake sax parser that calls some of the harder-to-reach sax methods to ensure it emits the correct events""" def setContentHandler(self, handler): self._handler = handler def parse(self, _): h = self._handler h.startDocument() # The next two items ensure that items preceding the first # start_element are properly stored and emitted: h.comment("a comment") h.processingInstruction("target", "data") h.startElement("html", AttributesImpl({})) h.comment("a comment") h.processingInstruction("target", "data") h.startElement("p", AttributesImpl({"class": "paraclass"})) h.characters("text") h.endElement("p") h.endElement("html") h.endDocument() def stub(self, *args, **kwargs): """Stub method. Does nothing.""" pass setProperty = stub setFeature = stub class SAX2DOMExerciser(SAXExerciser): """The same as SAXExerciser, but without the processing instruction and comment before the root element, because S2D can"t handle it""" def parse(self, _): h = self._handler h.startDocument() h.startElement("html", AttributesImpl({})) h.comment("a comment") h.processingInstruction("target", "data") h.startElement("p", AttributesImpl({"class": "paraclass"})) h.characters("text") h.endElement("p") h.endElement("html") h.endDocument() class SAX2DOMTestHelper(pulldom.DOMEventStream): """Allows us to drive SAX2DOM from a DOMEventStream.""" def reset(self): self.pulldom = pulldom.SAX2DOM() # This content handler relies on namespace support self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) self.parser.setContentHandler(self.pulldom) class SAX2DOMTestCase(unittest.TestCase): def confirm(self, test, testname="Test"): self.assertTrue(test, testname) def test_basic(self): """Ensure SAX2DOM can parse from a stream.""" with io.StringIO(SMALL_SAMPLE) as fin: sd = SAX2DOMTestHelper(fin, xml.sax.make_parser(), len(SMALL_SAMPLE)) for evt, node in sd: if evt == pulldom.START_ELEMENT and node.tagName == "html": break # Because the buffer is the same length as the XML, all the # nodes should have been parsed and added: self.assertGreater(len(node.childNodes), 0) def testSAX2DOM(self): """Ensure SAX2DOM expands nodes as expected.""" sax2dom = pulldom.SAX2DOM() sax2dom.startDocument() sax2dom.startElement("doc", {}) sax2dom.characters("text") sax2dom.startElement("subelm", {}) sax2dom.characters("text") sax2dom.endElement("subelm") sax2dom.characters("text") sax2dom.endElement("doc") sax2dom.endDocument() doc = sax2dom.document root = doc.documentElement (text1, elm1, text2) = root.childNodes text3 = elm1.childNodes[0] self.assertIsNone(text1.previousSibling) self.assertIs(text1.nextSibling, elm1) self.assertIs(elm1.previousSibling, text1) self.assertIs(elm1.nextSibling, text2) self.assertIs(text2.previousSibling, elm1) self.assertIsNone(text2.nextSibling) self.assertIsNone(text3.previousSibling) self.assertIsNone(text3.nextSibling) self.assertIs(root.parentNode, doc) self.assertIs(text1.parentNode, root) self.assertIs(elm1.parentNode, root) self.assertIs(text2.parentNode, root) self.assertIs(text3.parentNode, elm1) doc.unlink() 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_parser.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_parser.py
import copy import parser import pickle import unittest import operator import struct from test import support from test.support.script_helper import assert_python_failure # # First, we test that we can generate trees from valid source fragments, # and that these valid trees are indeed allowed by the tree-loading side # of the parser module. # class RoundtripLegalSyntaxTestCase(unittest.TestCase): def roundtrip(self, f, s): st1 = f(s) t = st1.totuple() try: st2 = parser.sequence2st(t) except parser.ParserError as why: self.fail("could not roundtrip %r: %s" % (s, why)) self.assertEqual(t, st2.totuple(), "could not re-generate syntax tree") def check_expr(self, s): self.roundtrip(parser.expr, s) def test_flags_passed(self): # The unicode literals flags has to be passed from the parser to AST # generation. suite = parser.suite("from __future__ import unicode_literals; x = ''") code = suite.compile() scope = {} exec(code, {}, scope) self.assertIsInstance(scope["x"], str) def check_suite(self, s): self.roundtrip(parser.suite, s) def test_yield_statement(self): self.check_suite("def f(): yield 1") self.check_suite("def f(): yield") self.check_suite("def f(): x += yield") self.check_suite("def f(): x = yield 1") self.check_suite("def f(): x = y = yield 1") self.check_suite("def f(): x = yield") self.check_suite("def f(): x = y = yield") self.check_suite("def f(): 1 + (yield)*2") self.check_suite("def f(): (yield 1)*2") self.check_suite("def f(): return; yield 1") self.check_suite("def f(): yield 1; return") self.check_suite("def f(): yield from 1") self.check_suite("def f(): x = yield from 1") self.check_suite("def f(): f((yield from 1))") self.check_suite("def f(): yield 1; return 1") self.check_suite("def f():\n" " for x in range(30):\n" " yield x\n") self.check_suite("def f():\n" " if (yield):\n" " yield x\n") def test_await_statement(self): self.check_suite("async def f():\n await smth()") self.check_suite("async def f():\n foo = await smth()") self.check_suite("async def f():\n foo, bar = await smth()") self.check_suite("async def f():\n (await smth())") self.check_suite("async def f():\n foo((await smth()))") self.check_suite("async def f():\n await foo(); return 42") def test_async_with_statement(self): self.check_suite("async def f():\n async with 1: pass") self.check_suite("async def f():\n async with a as b, c as d: pass") def test_async_for_statement(self): self.check_suite("async def f():\n async for i in (): pass") self.check_suite("async def f():\n async for i, b in (): pass") def test_nonlocal_statement(self): self.check_suite("def f():\n" " x = 0\n" " def g():\n" " nonlocal x\n") self.check_suite("def f():\n" " x = y = 0\n" " def g():\n" " nonlocal x, y\n") def test_expressions(self): self.check_expr("foo(1)") self.check_expr("[1, 2, 3]") self.check_expr("[x**3 for x in range(20)]") self.check_expr("[x**3 for x in range(20) if x % 3]") self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]") self.check_expr("list(x**3 for x in range(20))") self.check_expr("list(x**3 for x in range(20) if x % 3)") self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)") self.check_expr("foo(*args)") self.check_expr("foo(*args, **kw)") self.check_expr("foo(**kw)") self.check_expr("foo(key=value)") self.check_expr("foo(key=value, *args)") self.check_expr("foo(key=value, *args, **kw)") self.check_expr("foo(key=value, **kw)") self.check_expr("foo(a, b, c, *args)") self.check_expr("foo(a, b, c, *args, **kw)") self.check_expr("foo(a, b, c, **kw)") self.check_expr("foo(a, *args, keyword=23)") self.check_expr("foo + bar") self.check_expr("foo - bar") self.check_expr("foo * bar") self.check_expr("foo / bar") self.check_expr("foo // bar") self.check_expr("lambda: 0") self.check_expr("lambda x: 0") self.check_expr("lambda *y: 0") self.check_expr("lambda *y, **z: 0") self.check_expr("lambda **z: 0") self.check_expr("lambda x, y: 0") self.check_expr("lambda foo=bar: 0") self.check_expr("lambda foo=bar, spaz=nifty+spit: 0") self.check_expr("lambda foo=bar, **z: 0") self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0") self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0") self.check_expr("lambda x, *y, **z: 0") self.check_expr("(x for x in range(10))") self.check_expr("foo(x for x in range(10))") self.check_expr("...") self.check_expr("a[...]") def test_simple_expression(self): # expr_stmt self.check_suite("a") def test_simple_assignments(self): self.check_suite("a = b") self.check_suite("a = b = c = d = e") def test_var_annot(self): self.check_suite("x: int = 5") self.check_suite("y: List[T] = []; z: [list] = fun()") self.check_suite("x: tuple = (1, 2)") self.check_suite("d[f()]: int = 42") self.check_suite("f(d[x]): str = 'abc'") self.check_suite("x.y.z.w: complex = 42j") self.check_suite("x: int") self.check_suite("def f():\n" " x: str\n" " y: int = 5\n") self.check_suite("class C:\n" " x: str\n" " y: int = 5\n") self.check_suite("class C:\n" " def __init__(self, x: int) -> None:\n" " self.x: int = x\n") # double check for nonsense with self.assertRaises(SyntaxError): exec("2+2: int", {}, {}) with self.assertRaises(SyntaxError): exec("[]: int = 5", {}, {}) with self.assertRaises(SyntaxError): exec("x, *y, z: int = range(5)", {}, {}) with self.assertRaises(SyntaxError): exec("t: tuple = 1, 2", {}, {}) with self.assertRaises(SyntaxError): exec("u = v: int", {}, {}) with self.assertRaises(SyntaxError): exec("False: int", {}, {}) with self.assertRaises(SyntaxError): exec("x.False: int", {}, {}) with self.assertRaises(SyntaxError): exec("x.y,: int", {}, {}) with self.assertRaises(SyntaxError): exec("[0]: int", {}, {}) with self.assertRaises(SyntaxError): exec("f(): int", {}, {}) def test_simple_augmented_assignments(self): self.check_suite("a += b") self.check_suite("a -= b") self.check_suite("a *= b") self.check_suite("a /= b") self.check_suite("a //= b") self.check_suite("a %= b") self.check_suite("a &= b") self.check_suite("a |= b") self.check_suite("a ^= b") self.check_suite("a <<= b") self.check_suite("a >>= b") self.check_suite("a **= b") def test_function_defs(self): self.check_suite("def f(): pass") self.check_suite("def f(*args): pass") self.check_suite("def f(*args, **kw): pass") self.check_suite("def f(**kw): pass") self.check_suite("def f(foo=bar): pass") self.check_suite("def f(foo=bar, *args): pass") self.check_suite("def f(foo=bar, *args, **kw): pass") self.check_suite("def f(foo=bar, **kw): pass") self.check_suite("def f(a, b): pass") self.check_suite("def f(a, b, *args): pass") self.check_suite("def f(a, b, *args, **kw): pass") self.check_suite("def f(a, b, **kw): pass") self.check_suite("def f(a, b, foo=bar): pass") self.check_suite("def f(a, b, foo=bar, *args): pass") self.check_suite("def f(a, b, foo=bar, *args, **kw): pass") self.check_suite("def f(a, b, foo=bar, **kw): pass") self.check_suite("@staticmethod\n" "def f(): pass") self.check_suite("@staticmethod\n" "@funcattrs(x, y)\n" "def f(): pass") self.check_suite("@funcattrs()\n" "def f(): pass") # keyword-only arguments self.check_suite("def f(*, a): pass") self.check_suite("def f(*, a = 5): pass") self.check_suite("def f(*, a = 5, b): pass") self.check_suite("def f(*, a, b = 5): pass") self.check_suite("def f(*, a, b = 5, **kwds): pass") self.check_suite("def f(*args, a): pass") self.check_suite("def f(*args, a = 5): pass") self.check_suite("def f(*args, a = 5, b): pass") self.check_suite("def f(*args, a, b = 5): pass") self.check_suite("def f(*args, a, b = 5, **kwds): pass") # function annotations self.check_suite("def f(a: int): pass") self.check_suite("def f(a: int = 5): pass") self.check_suite("def f(*args: list): pass") self.check_suite("def f(**kwds: dict): pass") self.check_suite("def f(*, a: int): pass") self.check_suite("def f(*, a: int = 5): pass") self.check_suite("def f() -> int: pass") def test_class_defs(self): self.check_suite("class foo():pass") self.check_suite("class foo(object):pass") self.check_suite("@class_decorator\n" "class foo():pass") self.check_suite("@class_decorator(arg)\n" "class foo():pass") self.check_suite("@decorator1\n" "@decorator2\n" "class foo():pass") def test_import_from_statement(self): self.check_suite("from sys.path import *") self.check_suite("from sys.path import dirname") self.check_suite("from sys.path import (dirname)") self.check_suite("from sys.path import (dirname,)") self.check_suite("from sys.path import dirname as my_dirname") self.check_suite("from sys.path import (dirname as my_dirname)") self.check_suite("from sys.path import (dirname as my_dirname,)") self.check_suite("from sys.path import dirname, basename") self.check_suite("from sys.path import (dirname, basename)") self.check_suite("from sys.path import (dirname, basename,)") self.check_suite( "from sys.path import dirname as my_dirname, basename") self.check_suite( "from sys.path import (dirname as my_dirname, basename)") self.check_suite( "from sys.path import (dirname as my_dirname, basename,)") self.check_suite( "from sys.path import dirname, basename as my_basename") self.check_suite( "from sys.path import (dirname, basename as my_basename)") self.check_suite( "from sys.path import (dirname, basename as my_basename,)") self.check_suite("from .bogus import x") def test_basic_import_statement(self): self.check_suite("import sys") self.check_suite("import sys as system") self.check_suite("import sys, math") self.check_suite("import sys as system, math") self.check_suite("import sys, math as my_math") def test_relative_imports(self): self.check_suite("from . import name") self.check_suite("from .. import name") # check all the way up to '....', since '...' is tokenized # differently from '.' (it's an ellipsis token). self.check_suite("from ... import name") self.check_suite("from .... import name") self.check_suite("from .pkg import name") self.check_suite("from ..pkg import name") self.check_suite("from ...pkg import name") self.check_suite("from ....pkg import name") def test_pep263(self): self.check_suite("# -*- coding: iso-8859-1 -*-\n" "pass\n") def test_assert(self): self.check_suite("assert alo < ahi and blo < bhi\n") def test_with(self): self.check_suite("with open('x'): pass\n") self.check_suite("with open('x') as f: pass\n") self.check_suite("with open('x') as f, open('y') as g: pass\n") def test_try_stmt(self): self.check_suite("try: pass\nexcept: pass\n") self.check_suite("try: pass\nfinally: pass\n") self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n") self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n" "finally: pass\n") self.check_suite("try: pass\nexcept: pass\nelse: pass\n") self.check_suite("try: pass\nexcept: pass\nelse: pass\n" "finally: pass\n") def test_if_stmt(self): self.check_suite("if True:\n pass\nelse:\n pass\n") self.check_suite("if True:\n pass\nelif True:\n pass\nelse:\n pass\n") def test_position(self): # An absolutely minimal test of position information. Better # tests would be a big project. code = "def f(x):\n return x + 1" st = parser.suite(code) def walk(tree): node_type = tree[0] next = tree[1] if isinstance(next, (tuple, list)): for elt in tree[1:]: for x in walk(elt): yield x else: yield tree expected = [ (1, 'def', 1, 0), (1, 'f', 1, 4), (7, '(', 1, 5), (1, 'x', 1, 6), (8, ')', 1, 7), (11, ':', 1, 8), (4, '', 1, 9), (5, '', 2, -1), (1, 'return', 2, 4), (1, 'x', 2, 11), (14, '+', 2, 13), (2, '1', 2, 15), (4, '', 2, 16), (6, '', 2, -1), (4, '', 2, -1), (0, '', 2, -1), ] self.assertEqual(list(walk(st.totuple(line_info=True, col_info=True))), expected) self.assertEqual(list(walk(st.totuple())), [(t, n) for t, n, l, c in expected]) self.assertEqual(list(walk(st.totuple(line_info=True))), [(t, n, l) for t, n, l, c in expected]) self.assertEqual(list(walk(st.totuple(col_info=True))), [(t, n, c) for t, n, l, c in expected]) self.assertEqual(list(walk(st.tolist(line_info=True, col_info=True))), [list(x) for x in expected]) self.assertEqual(list(walk(parser.st2tuple(st, line_info=True, col_info=True))), expected) self.assertEqual(list(walk(parser.st2list(st, line_info=True, col_info=True))), [list(x) for x in expected]) def test_extended_unpacking(self): self.check_suite("*a = y") self.check_suite("x, *b, = m") self.check_suite("[*a, *b] = y") self.check_suite("for [*x, b] in x: pass") def test_raise_statement(self): self.check_suite("raise\n") self.check_suite("raise e\n") self.check_suite("try:\n" " suite\n" "except Exception as e:\n" " raise ValueError from e\n") def test_list_displays(self): self.check_expr('[]') self.check_expr('[*{2}, 3, *[4]]') def test_set_displays(self): self.check_expr('{*{2}, 3, *[4]}') self.check_expr('{2}') self.check_expr('{2,}') self.check_expr('{2, 3}') self.check_expr('{2, 3,}') def test_dict_displays(self): self.check_expr('{}') self.check_expr('{a:b}') self.check_expr('{a:b,}') self.check_expr('{a:b, c:d}') self.check_expr('{a:b, c:d,}') self.check_expr('{**{}}') self.check_expr('{**{}, 3:4, **{5:6, 7:8}}') def test_argument_unpacking(self): self.check_expr("f(*a, **b)") self.check_expr('f(a, *b, *c, *d)') self.check_expr('f(**a, **b)') self.check_expr('f(2, *a, *b, **b, **c, **d)') self.check_expr("f(*b, *() or () and (), **{} and {}, **() or {})") def test_set_comprehensions(self): self.check_expr('{x for x in seq}') self.check_expr('{f(x) for x in seq}') self.check_expr('{f(x) for x in seq if condition(x)}') def test_dict_comprehensions(self): self.check_expr('{x:x for x in seq}') self.check_expr('{x**2:x[3] for x in seq if condition(x)}') self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}') # # Second, we take *invalid* trees and make sure we get ParserError # rejections for them. # class IllegalSyntaxTestCase(unittest.TestCase): def check_bad_tree(self, tree, label): try: parser.sequence2st(tree) except parser.ParserError: pass else: self.fail("did not detect invalid tree for %r" % label) def test_junk(self): # not even remotely valid: self.check_bad_tree((1, 2, 3), "<junk>") def test_illegal_terminal(self): tree = \ (257, (269, (270, (271, (277, (1,))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "too small items in terminal node") tree = \ (257, (269, (270, (271, (277, (1, b'pass'))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "non-string second item in terminal node") tree = \ (257, (269, (270, (271, (277, (1, 'pass', '0', 0))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "non-integer third item in terminal node") tree = \ (257, (269, (270, (271, (277, (1, 'pass', 0, 0))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "too many items in terminal node") def test_illegal_yield_1(self): # Illegal yield statement: def f(): return 1; yield 1 tree = \ (257, (264, (285, (259, (1, 'def'), (1, 'f'), (260, (7, '('), (8, ')')), (11, ':'), (291, (4, ''), (5, ''), (264, (265, (266, (272, (275, (1, 'return'), (313, (292, (293, (294, (295, (297, (298, (299, (300, (301, (302, (303, (304, (305, (2, '1')))))))))))))))))), (264, (265, (266, (272, (276, (1, 'yield'), (313, (292, (293, (294, (295, (297, (298, (299, (300, (301, (302, (303, (304, (305, (2, '1')))))))))))))))))), (4, ''))), (6, ''))))), (4, ''), (0, '')))) self.check_bad_tree(tree, "def f():\n return 1\n yield 1") def test_illegal_yield_2(self): # Illegal return in generator: def f(): return 1; yield 1 tree = \ (257, (264, (265, (266, (278, (1, 'from'), (281, (1, '__future__')), (1, 'import'), (279, (1, 'generators')))), (4, ''))), (264, (285, (259, (1, 'def'), (1, 'f'), (260, (7, '('), (8, ')')), (11, ':'), (291, (4, ''), (5, ''), (264, (265, (266, (272, (275, (1, 'return'), (313, (292, (293, (294, (295, (297, (298, (299, (300, (301, (302, (303, (304, (305, (2, '1')))))))))))))))))), (264, (265, (266, (272, (276, (1, 'yield'), (313, (292, (293, (294, (295, (297, (298, (299, (300, (301, (302, (303, (304, (305, (2, '1')))))))))))))))))), (4, ''))), (6, ''))))), (4, ''), (0, '')))) self.check_bad_tree(tree, "def f():\n return 1\n yield 1") def test_a_comma_comma_c(self): # Illegal input: a,,c tree = \ (258, (311, (290, (291, (292, (293, (295, (296, (297, (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))), (12, ','), (12, ','), (290, (291, (292, (293, (295, (296, (297, (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))), (4, ''), (0, '')) self.check_bad_tree(tree, "a,,c") def test_illegal_operator(self): # Illegal input: a $= b tree = \ (257, (264, (265, (266, (267, (312, (291, (292, (293, (294, (296, (297, (298, (299, (300, (301, (302, (303, (304, (1, 'a'))))))))))))))), (268, (37, '$=')), (312, (291, (292, (293, (294, (296, (297, (298, (299, (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))), (4, ''))), (0, '')) self.check_bad_tree(tree, "a $= b") def test_malformed_global(self): #doesn't have global keyword in ast tree = (257, (264, (265, (266, (282, (1, 'foo'))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "malformed global ast") def test_missing_import_source(self): # from import fred tree = \ (257, (268, (269, (270, (282, (284, (1, 'from'), (1, 'import'), (287, (285, (1, 'fred')))))), (4, ''))), (4, ''), (0, '')) self.check_bad_tree(tree, "from import fred") def test_illegal_encoding(self): # Illegal encoding declaration tree = \ (340, (257, (0, ''))) self.check_bad_tree(tree, "missed encoding") tree = \ (340, (257, (0, '')), b'iso-8859-1') self.check_bad_tree(tree, "non-string encoding") tree = \ (340, (257, (0, '')), '\udcff') with self.assertRaises(UnicodeEncodeError): parser.sequence2st(tree) def test_invalid_node_id(self): tree = (257, (269, (-7, ''))) self.check_bad_tree(tree, "negative node id") tree = (257, (269, (99, ''))) self.check_bad_tree(tree, "invalid token id") tree = (257, (269, (9999, (0, '')))) self.check_bad_tree(tree, "invalid symbol id") def test_ParserError_message(self): try: parser.sequence2st((257,(269,(257,(0,''))))) except parser.ParserError as why: self.assertIn("simple_stmt", str(why)) # Expected self.assertIn("file_input", str(why)) # Got class CompileTestCase(unittest.TestCase): # These tests are very minimal. :-( def test_compile_expr(self): st = parser.expr('2 + 3') code = parser.compilest(st) self.assertEqual(eval(code), 5) def test_compile_suite(self): st = parser.suite('x = 2; y = x + 3') code = parser.compilest(st) globs = {} exec(code, globs) self.assertEqual(globs['y'], 5) def test_compile_error(self): st = parser.suite('1 = 3 + 4') self.assertRaises(SyntaxError, parser.compilest, st) def test_compile_badunicode(self): st = parser.suite('a = "\\U12345678"') self.assertRaises(SyntaxError, parser.compilest, st) st = parser.suite('a = "\\u1"') self.assertRaises(SyntaxError, parser.compilest, st) def test_issue_9011(self): # Issue 9011: compilation of an unary minus expression changed # the meaning of the ST, so that a second compilation produced # incorrect results. st = parser.expr('-3') code1 = parser.compilest(st) self.assertEqual(eval(code1), -3) code2 = parser.compilest(st) self.assertEqual(eval(code2), -3) def test_compile_filename(self): st = parser.expr('a + 5') code = parser.compilest(st) self.assertEqual(code.co_filename, '<syntax-tree>') code = st.compile() self.assertEqual(code.co_filename, '<syntax-tree>') for filename in 'file.py', b'file.py': code = parser.compilest(st, filename) self.assertEqual(code.co_filename, 'file.py') code = st.compile(filename) self.assertEqual(code.co_filename, 'file.py') for filename in bytearray(b'file.py'), memoryview(b'file.py'): with self.assertWarns(DeprecationWarning): code = parser.compilest(st, filename) self.assertEqual(code.co_filename, 'file.py') with self.assertWarns(DeprecationWarning): code = st.compile(filename) self.assertEqual(code.co_filename, 'file.py') self.assertRaises(TypeError, parser.compilest, st, list(b'file.py')) self.assertRaises(TypeError, st.compile, list(b'file.py')) class ParserStackLimitTestCase(unittest.TestCase): """try to push the parser to/over its limits. see http://bugs.python.org/issue1881 for a discussion """ def _nested_expression(self, level): return "["*level+"]"*level def test_deeply_nested_list(self): # XXX used to be 99 levels in 2.x e = self._nested_expression(93) st = parser.expr(e) st.compile() def test_trigger_memory_error(self): e = self._nested_expression(100) rc, out, err = assert_python_failure('-c', e) # parsing the expression will result in an error message # followed by a MemoryError (see #11963) self.assertIn(b's_push: parser stack overflow', err) self.assertIn(b'MemoryError', err) class STObjectTestCase(unittest.TestCase): """Test operations on ST objects themselves""" def test_comparisons(self): # ST objects should support order and equality comparisons st1 = parser.expr('2 + 3') st2 = parser.suite('x = 2; y = x + 3') st3 = parser.expr('list(x**3 for x in range(20))') st1_copy = parser.expr('2 + 3') st2_copy = parser.suite('x = 2; y = x + 3') st3_copy = parser.expr('list(x**3 for x in range(20))') # exercise fast path for object identity self.assertEqual(st1 == st1, True) self.assertEqual(st2 == st2, True) self.assertEqual(st3 == st3, True) # slow path equality self.assertEqual(st1, st1_copy) self.assertEqual(st2, st2_copy) self.assertEqual(st3, st3_copy) self.assertEqual(st1 == st2, False) self.assertEqual(st1 == st3, False) self.assertEqual(st2 == st3, False) self.assertEqual(st1 != st1, False) self.assertEqual(st2 != st2, False) self.assertEqual(st3 != st3, False) self.assertEqual(st1 != st1_copy, False) self.assertEqual(st2 != st2_copy, False) self.assertEqual(st3 != st3_copy, False) self.assertEqual(st2 != st1, True) self.assertEqual(st1 != st3, True) self.assertEqual(st3 != st2, True) # we don't particularly care what the ordering is; just that # it's usable and self-consistent self.assertEqual(st1 < st2, not (st2 <= st1)) self.assertEqual(st1 < st3, not (st3 <= st1)) self.assertEqual(st2 < st3, not (st3 <= st2)) self.assertEqual(st1 < st2, st2 > st1) self.assertEqual(st1 < st3, st3 > st1) self.assertEqual(st2 < st3, st3 > st2) self.assertEqual(st1 <= st2, st2 >= st1) self.assertEqual(st3 <= st1, st1 >= st3) self.assertEqual(st2 <= st3, st3 >= st2) # transitivity bottom = min(st1, st2, st3) top = max(st1, st2, st3) mid = sorted([st1, st2, st3])[1] self.assertTrue(bottom < mid) self.assertTrue(bottom < top) self.assertTrue(mid < top) self.assertTrue(bottom <= mid) self.assertTrue(bottom <= top) self.assertTrue(mid <= top) self.assertTrue(bottom <= bottom) self.assertTrue(mid <= mid) self.assertTrue(top <= top) # interaction with other types self.assertEqual(st1 == 1588.602459, False) self.assertEqual('spanish armada' != st2, True) self.assertRaises(TypeError, operator.ge, st3, None) self.assertRaises(TypeError, operator.le, False, st1) self.assertRaises(TypeError, operator.lt, st1, 1815) self.assertRaises(TypeError, operator.gt, b'waterloo', st2) def test_copy_pickle(self): sts = [ parser.expr('2 + 3'), parser.suite('x = 2; y = x + 3'), parser.expr('list(x**3 for x in range(20))') ] for st in sts: st_copy = copy.copy(st) self.assertEqual(st_copy.totuple(), st.totuple()) st_copy = copy.deepcopy(st) self.assertEqual(st_copy.totuple(), st.totuple()) for proto in range(pickle.HIGHEST_PROTOCOL+1): st_copy = pickle.loads(pickle.dumps(st, proto)) self.assertEqual(st_copy.totuple(), st.totuple()) check_sizeof = support.check_sizeof @support.cpython_only def test_sizeof(self): def XXXROUNDUP(n): if n <= 1: return n if n <= 128: return (n + 3) & ~3 return 1 << (n - 1).bit_length() basesize = support.calcobjsize('Pii') nodesize = struct.calcsize('hP3iP0h') def sizeofchildren(node): if node is None: return 0 res = 0
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_array.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_array.py
"""Test the arraymodule. Roger E. Masse """ import unittest from test import support import weakref import pickle import operator import struct import sys import warnings import array from array import _array_reconstructor as array_reconstructor sizeof_wchar = array.array('u').itemsize class ArraySubclass(array.array): pass class ArraySubclassWithKwargs(array.array): def __init__(self, typecode, newarg=None): array.array.__init__(self) typecodes = 'ubBhHiIlLfdqQ' class MiscTest(unittest.TestCase): def test_bad_constructor(self): self.assertRaises(TypeError, array.array) self.assertRaises(TypeError, array.array, spam=42) self.assertRaises(TypeError, array.array, 'xx') self.assertRaises(ValueError, array.array, 'x') def test_empty(self): # Exercise code for handling zero-length arrays a = array.array('B') a[:] = a self.assertEqual(len(a), 0) self.assertEqual(len(a + a), 0) self.assertEqual(len(a * 3), 0) a += a self.assertEqual(len(a), 0) # Machine format codes. # # Search for "enum machine_format_code" in Modules/arraymodule.c to get the # authoritative values. UNKNOWN_FORMAT = -1 UNSIGNED_INT8 = 0 SIGNED_INT8 = 1 UNSIGNED_INT16_LE = 2 UNSIGNED_INT16_BE = 3 SIGNED_INT16_LE = 4 SIGNED_INT16_BE = 5 UNSIGNED_INT32_LE = 6 UNSIGNED_INT32_BE = 7 SIGNED_INT32_LE = 8 SIGNED_INT32_BE = 9 UNSIGNED_INT64_LE = 10 UNSIGNED_INT64_BE = 11 SIGNED_INT64_LE = 12 SIGNED_INT64_BE = 13 IEEE_754_FLOAT_LE = 14 IEEE_754_FLOAT_BE = 15 IEEE_754_DOUBLE_LE = 16 IEEE_754_DOUBLE_BE = 17 UTF16_LE = 18 UTF16_BE = 19 UTF32_LE = 20 UTF32_BE = 21 class ArrayReconstructorTest(unittest.TestCase): def test_error(self): self.assertRaises(TypeError, array_reconstructor, "", "b", 0, b"") self.assertRaises(TypeError, array_reconstructor, str, "b", 0, b"") self.assertRaises(TypeError, array_reconstructor, array.array, "b", '', b"") self.assertRaises(TypeError, array_reconstructor, array.array, "b", 0, "") self.assertRaises(ValueError, array_reconstructor, array.array, "?", 0, b"") self.assertRaises(ValueError, array_reconstructor, array.array, "b", UNKNOWN_FORMAT, b"") self.assertRaises(ValueError, array_reconstructor, array.array, "b", 22, b"") self.assertRaises(ValueError, array_reconstructor, array.array, "d", 16, b"a") def test_numbers(self): testcases = ( (['B', 'H', 'I', 'L'], UNSIGNED_INT8, '=BBBB', [0x80, 0x7f, 0, 0xff]), (['b', 'h', 'i', 'l'], SIGNED_INT8, '=bbb', [-0x80, 0x7f, 0]), (['H', 'I', 'L'], UNSIGNED_INT16_LE, '<HHHH', [0x8000, 0x7fff, 0, 0xffff]), (['H', 'I', 'L'], UNSIGNED_INT16_BE, '>HHHH', [0x8000, 0x7fff, 0, 0xffff]), (['h', 'i', 'l'], SIGNED_INT16_LE, '<hhh', [-0x8000, 0x7fff, 0]), (['h', 'i', 'l'], SIGNED_INT16_BE, '>hhh', [-0x8000, 0x7fff, 0]), (['I', 'L'], UNSIGNED_INT32_LE, '<IIII', [1<<31, (1<<31)-1, 0, (1<<32)-1]), (['I', 'L'], UNSIGNED_INT32_BE, '>IIII', [1<<31, (1<<31)-1, 0, (1<<32)-1]), (['i', 'l'], SIGNED_INT32_LE, '<iii', [-1<<31, (1<<31)-1, 0]), (['i', 'l'], SIGNED_INT32_BE, '>iii', [-1<<31, (1<<31)-1, 0]), (['L'], UNSIGNED_INT64_LE, '<QQQQ', [1<<31, (1<<31)-1, 0, (1<<32)-1]), (['L'], UNSIGNED_INT64_BE, '>QQQQ', [1<<31, (1<<31)-1, 0, (1<<32)-1]), (['l'], SIGNED_INT64_LE, '<qqq', [-1<<31, (1<<31)-1, 0]), (['l'], SIGNED_INT64_BE, '>qqq', [-1<<31, (1<<31)-1, 0]), # The following tests for INT64 will raise an OverflowError # when run on a 32-bit machine. The tests are simply skipped # in that case. (['L'], UNSIGNED_INT64_LE, '<QQQQ', [1<<63, (1<<63)-1, 0, (1<<64)-1]), (['L'], UNSIGNED_INT64_BE, '>QQQQ', [1<<63, (1<<63)-1, 0, (1<<64)-1]), (['l'], SIGNED_INT64_LE, '<qqq', [-1<<63, (1<<63)-1, 0]), (['l'], SIGNED_INT64_BE, '>qqq', [-1<<63, (1<<63)-1, 0]), (['f'], IEEE_754_FLOAT_LE, '<ffff', [16711938.0, float('inf'), float('-inf'), -0.0]), (['f'], IEEE_754_FLOAT_BE, '>ffff', [16711938.0, float('inf'), float('-inf'), -0.0]), (['d'], IEEE_754_DOUBLE_LE, '<dddd', [9006104071832581.0, float('inf'), float('-inf'), -0.0]), (['d'], IEEE_754_DOUBLE_BE, '>dddd', [9006104071832581.0, float('inf'), float('-inf'), -0.0]) ) for testcase in testcases: valid_typecodes, mformat_code, struct_fmt, values = testcase arraystr = struct.pack(struct_fmt, *values) for typecode in valid_typecodes: try: a = array.array(typecode, values) except OverflowError: continue # Skip this test case. b = array_reconstructor( array.array, typecode, mformat_code, arraystr) self.assertEqual(a, b, msg="{0!r} != {1!r}; testcase={2!r}".format(a, b, testcase)) def test_unicode(self): teststr = "Bonne Journ\xe9e \U0002030a\U00020347" testcases = ( (UTF16_LE, "UTF-16-LE"), (UTF16_BE, "UTF-16-BE"), (UTF32_LE, "UTF-32-LE"), (UTF32_BE, "UTF-32-BE") ) for testcase in testcases: mformat_code, encoding = testcase a = array.array('u', teststr) b = array_reconstructor( array.array, 'u', mformat_code, teststr.encode(encoding)) self.assertEqual(a, b, msg="{0!r} != {1!r}; testcase={2!r}".format(a, b, testcase)) class BaseTest: # Required class attributes (provided by subclasses # typecode: the typecode to test # example: an initializer usable in the constructor for this type # smallerexample: the same length as example, but smaller # biggerexample: the same length as example, but bigger # outside: An entry that is not in example # minitemsize: the minimum guaranteed itemsize def assertEntryEqual(self, entry1, entry2): self.assertEqual(entry1, entry2) def badtypecode(self): # Return a typecode that is different from our own return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)] def test_constructor(self): a = array.array(self.typecode) self.assertEqual(a.typecode, self.typecode) self.assertGreaterEqual(a.itemsize, self.minitemsize) self.assertRaises(TypeError, array.array, self.typecode, None) def test_len(self): a = array.array(self.typecode) a.append(self.example[0]) self.assertEqual(len(a), 1) a = array.array(self.typecode, self.example) self.assertEqual(len(a), len(self.example)) def test_buffer_info(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() self.assertIsInstance(bi, tuple) self.assertEqual(len(bi), 2) self.assertIsInstance(bi[0], int) self.assertIsInstance(bi[1], int) self.assertEqual(bi[1], len(a)) def test_byteswap(self): if self.typecode == 'u': example = '\U00100100' else: example = self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): b = array.array(self.typecode, example) b.byteswap() if a.itemsize==1: self.assertEqual(a, b) else: self.assertNotEqual(a, b) b.byteswap() self.assertEqual(a, b) def test_copy(self): import copy a = array.array(self.typecode, self.example) b = copy.copy(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_deepcopy(self): import copy a = array.array(self.typecode, self.example) b = copy.deepcopy(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_reduce_ex(self): a = array.array(self.typecode, self.example) for protocol in range(3): self.assertIs(a.__reduce_ex__(protocol)[0], array.array) for protocol in range(3, pickle.HIGHEST_PROTOCOL): self.assertIs(a.__reduce_ex__(protocol)[0], array_reconstructor) def test_pickle(self): for protocol in range(pickle.HIGHEST_PROTOCOL + 1): a = array.array(self.typecode, self.example) b = pickle.loads(pickle.dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) a = ArraySubclass(self.typecode, self.example) a.x = 10 b = pickle.loads(pickle.dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) self.assertEqual(a.x, b.x) self.assertEqual(type(a), type(b)) def test_pickle_for_empty_array(self): for protocol in range(pickle.HIGHEST_PROTOCOL + 1): a = array.array(self.typecode) b = pickle.loads(pickle.dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) a = ArraySubclass(self.typecode) a.x = 10 b = pickle.loads(pickle.dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) self.assertEqual(a.x, b.x) self.assertEqual(type(a), type(b)) def test_iterator_pickle(self): orig = array.array(self.typecode, self.example) data = list(orig) data2 = data[::-1] for proto in range(pickle.HIGHEST_PROTOCOL + 1): # initial iterator itorig = iter(orig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a.fromlist(data2) self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data + data2) # running iterator next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a.fromlist(data2) self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data[1:] + data2) # empty iterator for i in range(1, len(data)): next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a.fromlist(data2) self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data2) # exhausted iterator self.assertRaises(StopIteration, next, itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a.fromlist(data2) self.assertEqual(list(it), []) def test_exhausted_iterator(self): a = array.array(self.typecode, self.example) self.assertEqual(list(a), list(self.example)) exhit = iter(a) empit = iter(a) for x in exhit: # exhaust the iterator next(empit) # not exhausted a.append(self.outside) self.assertEqual(list(exhit), []) self.assertEqual(list(empit), [self.outside]) self.assertEqual(list(a), list(self.example) + [self.outside]) def test_insert(self): a = array.array(self.typecode, self.example) a.insert(0, self.example[0]) self.assertEqual(len(a), 1+len(self.example)) self.assertEqual(a[0], a[1]) self.assertRaises(TypeError, a.insert) self.assertRaises(TypeError, a.insert, None) self.assertRaises(TypeError, a.insert, 0, None) a = array.array(self.typecode, self.example) a.insert(-1, self.example[0]) self.assertEqual( a, array.array( self.typecode, self.example[:-1] + self.example[:1] + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a.insert(-1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a.insert(1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[:1]) ) def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) support.unlink(support.TESTFN) f = open(support.TESTFN, 'wb') try: a.tofile(f) f.close() b = array.array(self.typecode) f = open(support.TESTFN, 'rb') self.assertRaises(TypeError, b.fromfile) b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) self.assertRaises(EOFError, b.fromfile, f, len(self.example)+1) self.assertEqual(a, b) f.close() finally: if not f.closed: f.close() support.unlink(support.TESTFN) def test_fromfile_ioerror(self): # Issue #5395: Check if fromfile raises a proper OSError # instead of EOFError. a = array.array(self.typecode) f = open(support.TESTFN, 'wb') try: self.assertRaises(OSError, a.fromfile, f, len(self.example)) finally: f.close() support.unlink(support.TESTFN) def test_filewrite(self): a = array.array(self.typecode, 2*self.example) f = open(support.TESTFN, 'wb') try: f.write(a) f.close() b = array.array(self.typecode) f = open(support.TESTFN, 'rb') b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) f.close() finally: if not f.closed: f.close() support.unlink(support.TESTFN) def test_tofromlist(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tolist, 42) self.assertRaises(TypeError, b.fromlist) self.assertRaises(TypeError, b.fromlist, 42) self.assertRaises(TypeError, b.fromlist, [None]) b.fromlist(a.tolist()) self.assertEqual(a, b) def test_tofromstring(self): # Warnings not raised when arguments are incorrect as Argument Clinic # handles that before the warning can be raised. nb_warnings = 2 with warnings.catch_warnings(record=True) as r: warnings.filterwarnings("always", message=r"(to|from)string\(\) is deprecated", category=DeprecationWarning) a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tostring, 42) self.assertRaises(TypeError, b.fromstring) self.assertRaises(TypeError, b.fromstring, 42) b.fromstring(a.tostring()) self.assertEqual(a, b) if a.itemsize>1: self.assertRaises(ValueError, b.fromstring, "x") nb_warnings += 1 self.assertEqual(len(r), nb_warnings) def test_tofrombytes(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tobytes, 42) self.assertRaises(TypeError, b.frombytes) self.assertRaises(TypeError, b.frombytes, 42) b.frombytes(a.tobytes()) c = array.array(self.typecode, bytearray(a.tobytes())) self.assertEqual(a, b) self.assertEqual(a, c) if a.itemsize>1: self.assertRaises(ValueError, b.frombytes, b"x") def test_fromarray(self): a = array.array(self.typecode, self.example) b = array.array(self.typecode, a) self.assertEqual(a, b) def test_repr(self): a = array.array(self.typecode, 2*self.example) self.assertEqual(a, eval(repr(a), {"array": array.array})) a = array.array(self.typecode) self.assertEqual(repr(a), "array('%s')" % self.typecode) def test_str(self): a = array.array(self.typecode, 2*self.example) str(a) def test_cmp(self): a = array.array(self.typecode, self.example) self.assertIs(a == 42, False) self.assertIs(a != 42, True) self.assertIs(a == a, True) self.assertIs(a != a, False) self.assertIs(a < a, False) self.assertIs(a <= a, True) self.assertIs(a > a, False) self.assertIs(a >= a, True) al = array.array(self.typecode, self.smallerexample) ab = array.array(self.typecode, self.biggerexample) self.assertIs(a == 2*a, False) self.assertIs(a != 2*a, True) self.assertIs(a < 2*a, True) self.assertIs(a <= 2*a, True) self.assertIs(a > 2*a, False) self.assertIs(a >= 2*a, False) self.assertIs(a == al, False) self.assertIs(a != al, True) self.assertIs(a < al, False) self.assertIs(a <= al, False) self.assertIs(a > al, True) self.assertIs(a >= al, True) self.assertIs(a == ab, False) self.assertIs(a != ab, True) self.assertIs(a < ab, True) self.assertIs(a <= ab, True) self.assertIs(a > ab, False) self.assertIs(a >= ab, False) def test_add(self): a = array.array(self.typecode, self.example) \ + array.array(self.typecode, self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[::-1]) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__add__, "bad") def test_iadd(self): a = array.array(self.typecode, self.example[::-1]) b = a a += array.array(self.typecode, 2*self.example) self.assertIs(a, b) self.assertEqual( a, array.array(self.typecode, self.example[::-1]+2*self.example) ) a = array.array(self.typecode, self.example) a += a self.assertEqual( a, array.array(self.typecode, self.example + self.example) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__iadd__, "bad") def test_mul(self): a = 5*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a = array.array(self.typecode, self.example)*5 self.assertEqual( a, array.array(self.typecode, self.example*5) ) a = 0*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) a = (-1)*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) a = 5 * array.array(self.typecode, self.example[:1]) self.assertEqual( a, array.array(self.typecode, [a[0]] * 5) ) self.assertRaises(TypeError, a.__mul__, "bad") def test_imul(self): a = array.array(self.typecode, self.example) b = a a *= 5 self.assertIs(a, b) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a *= 0 self.assertIs(a, b) self.assertEqual(a, array.array(self.typecode)) a *= 1000 self.assertIs(a, b) self.assertEqual(a, array.array(self.typecode)) a *= -1 self.assertIs(a, b) self.assertEqual(a, array.array(self.typecode)) a = array.array(self.typecode, self.example) a *= -1 self.assertEqual(a, array.array(self.typecode)) self.assertRaises(TypeError, a.__imul__, "bad") def test_getitem(self): a = array.array(self.typecode, self.example) self.assertEntryEqual(a[0], self.example[0]) self.assertEntryEqual(a[0], self.example[0]) self.assertEntryEqual(a[-1], self.example[-1]) self.assertEntryEqual(a[-1], self.example[-1]) self.assertEntryEqual(a[len(self.example)-1], self.example[-1]) self.assertEntryEqual(a[-len(self.example)], self.example[0]) self.assertRaises(TypeError, a.__getitem__) self.assertRaises(IndexError, a.__getitem__, len(self.example)) self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1) def test_setitem(self): a = array.array(self.typecode, self.example) a[0] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[0] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[len(self.example)-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-len(self.example)] = a[-1] self.assertEntryEqual(a[0], a[-1]) self.assertRaises(TypeError, a.__setitem__) self.assertRaises(TypeError, a.__setitem__, None) self.assertRaises(TypeError, a.__setitem__, 0, None) self.assertRaises( IndexError, a.__setitem__, len(self.example), self.example[0] ) self.assertRaises( IndexError, a.__setitem__, -len(self.example)-1, self.example[0] ) def test_delitem(self): a = array.array(self.typecode, self.example) del a[0] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) a = array.array(self.typecode, self.example) del a[-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[len(self.example)-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[-len(self.example)] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) self.assertRaises(TypeError, a.__delitem__) self.assertRaises(TypeError, a.__delitem__, None) self.assertRaises(IndexError, a.__delitem__, len(self.example)) self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1) def test_getslice(self): a = array.array(self.typecode, self.example) self.assertEqual(a[:], a) self.assertEqual( a[1:], array.array(self.typecode, self.example[1:]) ) self.assertEqual( a[:1], array.array(self.typecode, self.example[:1]) ) self.assertEqual( a[:-1], array.array(self.typecode, self.example[:-1]) ) self.assertEqual( a[-1:], array.array(self.typecode, self.example[-1:]) ) self.assertEqual( a[-1:-1], array.array(self.typecode) ) self.assertEqual( a[2:1], array.array(self.typecode) ) self.assertEqual( a[1000:], array.array(self.typecode) ) self.assertEqual(a[-1000:], a) self.assertEqual(a[:1000], a) self.assertEqual( a[:-1000], array.array(self.typecode) ) self.assertEqual(a[-1000:1000], a) self.assertEqual( a[2000:1000], array.array(self.typecode) ) def test_extended_getslice(self): # Test extended slicing by comparing with list slicing # (Assumes list conversion works correctly, too) a = array.array(self.typecode, self.example) indices = (0, None, 1, 3, 19, 100, sys.maxsize, -1, -2, -31, -100) for start in indices: for stop in indices: # Everything except the initial 0 (invalid step) for step in indices[1:]: self.assertEqual(list(a[start:stop:step]), list(a)[start:stop:step]) def test_setslice(self): a = array.array(self.typecode, self.example) a[:1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[:-1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[-1:]) ) a = array.array(self.typecode, self.example) a[-1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:-1] + self.example) ) a = array.array(self.typecode, self.example) a[1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a[1:-1] = a self.assertEqual( a, array.array( self.typecode, self.example[:1] + self.example + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a[1000:] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[-1000:] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:1000] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:-1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[1:0] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[2000:1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setitem__, slice(0, 0), None) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__setitem__, slice(0, 0), b) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b) def test_extended_set_del_slice(self): indices = (0, None, 1, 3, 19, 100, sys.maxsize, -1, -2, -31, -100) for start in indices: for stop in indices: # Everything except the initial 0 (invalid step) for step in indices[1:]: a = array.array(self.typecode, self.example) L = list(a) # Make sure we have a slice of exactly the right length, # but with (hopefully) different data. data = L[start:stop:step] data.reverse() L[start:stop:step] = data a[start:stop:step] = array.array(self.typecode, data) self.assertEqual(a, array.array(self.typecode, L)) del L[start:stop:step] del a[start:stop:step] self.assertEqual(a, array.array(self.typecode, L)) def test_index(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.index) for x in example: self.assertEqual(a.index(x), example.index(x)) self.assertRaises(ValueError, a.index, None) self.assertRaises(ValueError, a.index, self.outside) def test_count(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.count) for x in example: self.assertEqual(a.count(x), example.count(x)) self.assertEqual(a.count(self.outside), 0) self.assertEqual(a.count(None), 0) def test_remove(self): for x in self.example: example = 2*self.example a = array.array(self.typecode, example) pos = example.index(x) example2 = example[:pos] + example[pos+1:] a.remove(x) self.assertEqual(a, array.array(self.typecode, example2)) a = array.array(self.typecode, self.example) self.assertRaises(ValueError, a.remove, self.outside) self.assertRaises(ValueError, a.remove, None) def test_pop(self): a = array.array(self.typecode) self.assertRaises(IndexError, a.pop) a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.pop, 42, 42) self.assertRaises(TypeError, a.pop, None) self.assertRaises(IndexError, a.pop, len(a)) self.assertRaises(IndexError, a.pop, -len(a)-1) self.assertEntryEqual(a.pop(0), self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[1:]+self.example) ) self.assertEntryEqual(a.pop(1), self.example[2]) self.assertEqual( a, array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example) ) self.assertEntryEqual(a.pop(0), self.example[1]) self.assertEntryEqual(a.pop(), self.example[-1]) self.assertEqual( a, array.array(self.typecode, self.example[3:]+self.example[:-1]) ) def test_reverse(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.reverse, 42) a.reverse() self.assertEqual( a, array.array(self.typecode, self.example[::-1]) ) def test_extend(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.extend) a.extend(array.array(self.typecode, self.example[::-1])) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) a = array.array(self.typecode, self.example) a.extend(a) self.assertEqual( a, array.array(self.typecode, self.example+self.example) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.extend, b) a = array.array(self.typecode, self.example) a.extend(self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) def test_constructor_with_iterable_argument(self): a = array.array(self.typecode, iter(self.example)) b = array.array(self.typecode, self.example)
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_strptime.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_strptime.py
"""PyUnit testing against strptime""" import unittest import time import locale import re import os import sys from test import support from datetime import date as datetime_date import _strptime class getlang_Tests(unittest.TestCase): """Test _getlang""" def test_basic(self): self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) class LocaleTime_Tests(unittest.TestCase): """Tests for _strptime.LocaleTime. All values are lower-cased when stored in LocaleTime, so make sure to compare values after running ``lower`` on them. """ def setUp(self): """Create time tuple based on current time.""" self.time_tuple = time.localtime() self.LT_ins = _strptime.LocaleTime() def compare_against_time(self, testing, directive, tuple_position, error_msg): """Helper method that tests testing against directive based on the tuple_position of time_tuple. Uses error_msg as error message. """ strftime_output = time.strftime(directive, self.time_tuple).lower() comparison = testing[self.time_tuple[tuple_position]] self.assertIn(strftime_output, testing, "%s: not found in tuple" % error_msg) self.assertEqual(comparison, strftime_output, "%s: position within tuple incorrect; %s != %s" % (error_msg, comparison, strftime_output)) def test_weekday(self): # Make sure that full and abbreviated weekday names are correct in # both string and position with tuple self.compare_against_time(self.LT_ins.f_weekday, '%A', 6, "Testing of full weekday name failed") self.compare_against_time(self.LT_ins.a_weekday, '%a', 6, "Testing of abbreviated weekday name failed") def test_month(self): # Test full and abbreviated month names; both string and position # within the tuple self.compare_against_time(self.LT_ins.f_month, '%B', 1, "Testing against full month name failed") self.compare_against_time(self.LT_ins.a_month, '%b', 1, "Testing against abbreviated month name failed") def test_am_pm(self): # Make sure AM/PM representation done properly strftime_output = time.strftime("%p", self.time_tuple).lower() self.assertIn(strftime_output, self.LT_ins.am_pm, "AM/PM representation not in tuple") if self.time_tuple[3] < 12: position = 0 else: position = 1 self.assertEqual(self.LT_ins.am_pm[position], strftime_output, "AM/PM representation in the wrong position within the tuple") def test_timezone(self): # Make sure timezone is correct timezone = time.strftime("%Z", self.time_tuple).lower() if timezone: self.assertTrue(timezone in self.LT_ins.timezone[0] or timezone in self.LT_ins.timezone[1], "timezone %s not found in %s" % (timezone, self.LT_ins.timezone)) def test_date_time(self): # Check that LC_date_time, LC_date, and LC_time are correct # the magic date is used so as to not have issues with %c when day of # the month is a single digit and has a leading space. This is not an # issue since strptime still parses it correctly. The problem is # testing these directives for correctness by comparing strftime # output. magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0) strftime_output = time.strftime("%c", magic_date) self.assertEqual(time.strftime(self.LT_ins.LC_date_time, magic_date), strftime_output, "LC_date_time incorrect") strftime_output = time.strftime("%x", magic_date) self.assertEqual(time.strftime(self.LT_ins.LC_date, magic_date), strftime_output, "LC_date incorrect") strftime_output = time.strftime("%X", magic_date) self.assertEqual(time.strftime(self.LT_ins.LC_time, magic_date), strftime_output, "LC_time incorrect") LT = _strptime.LocaleTime() LT.am_pm = ('', '') self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle " "empty strings") def test_lang(self): # Make sure lang is set to what _getlang() returns # Assuming locale has not changed between now and when self.LT_ins was created self.assertEqual(self.LT_ins.lang, _strptime._getlang()) class TimeRETests(unittest.TestCase): """Tests for TimeRE.""" def setUp(self): """Construct generic TimeRE object.""" self.time_re = _strptime.TimeRE() self.locale_time = _strptime.LocaleTime() def test_pattern(self): # Test TimeRE.pattern pattern_string = self.time_re.pattern(r"%a %A %d") self.assertTrue(pattern_string.find(self.locale_time.a_weekday[2]) != -1, "did not find abbreviated weekday in pattern string '%s'" % pattern_string) self.assertTrue(pattern_string.find(self.locale_time.f_weekday[4]) != -1, "did not find full weekday in pattern string '%s'" % pattern_string) self.assertTrue(pattern_string.find(self.time_re['d']) != -1, "did not find 'd' directive pattern string '%s'" % pattern_string) def test_pattern_escaping(self): # Make sure any characters in the format string that might be taken as # regex syntax is escaped. pattern_string = self.time_re.pattern(r"\d+") self.assertIn(r"\\d\+", pattern_string, "%s does not have re characters escaped properly" % pattern_string) def test_compile(self): # Check that compiled regex is correct found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6]) self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6], "re object for '%A' failed") compiled = self.time_re.compile(r"%a %b") found = compiled.match("%s %s" % (self.locale_time.a_weekday[4], self.locale_time.a_month[4])) self.assertTrue(found, "Match failed with '%s' regex and '%s' string" % (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4], self.locale_time.a_month[4]))) self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and found.group('b') == self.locale_time.a_month[4], "re object couldn't find the abbreviated weekday month in " "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" % (found.string, found.re.pattern, found.group('a'), found.group('b'))) for directive in ('a','A','b','B','c','d','G','H','I','j','m','M','p', 'S','u','U','V','w','W','x','X','y','Y','Z','%'): compiled = self.time_re.compile("%" + directive) found = compiled.match(time.strftime("%" + directive)) self.assertTrue(found, "Matching failed on '%s' using '%s' regex" % (time.strftime("%" + directive), compiled.pattern)) def test_blankpattern(self): # Make sure when tuple or something has no values no regex is generated. # Fixes bug #661354 test_locale = _strptime.LocaleTime() test_locale.timezone = (frozenset(), frozenset()) self.assertEqual(_strptime.TimeRE(test_locale).pattern("%Z"), '', "with timezone == ('',''), TimeRE().pattern('%Z') != ''") def test_matching_with_escapes(self): # Make sure a format that requires escaping of characters works compiled_re = self.time_re.compile(r"\w+ %m") found = compiled_re.match(r"\w+ 10") self.assertTrue(found, r"Escaping failed of format '\w+ 10'") def test_locale_data_w_regex_metacharacters(self): # Check that if locale data contains regex metacharacters they are # escaped properly. # Discovered by bug #1039270 . locale_time = _strptime.LocaleTime() locale_time.timezone = (frozenset(("utc", "gmt", "Tokyo (standard time)")), frozenset("Tokyo (daylight time)")) time_re = _strptime.TimeRE(locale_time) self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"), "locale data that contains regex metacharacters is not" " properly escaped") def test_whitespace_substitution(self): # When pattern contains whitespace, make sure it is taken into account # so as to not allow subpatterns to end up next to each other and # "steal" characters from each other. pattern = self.time_re.pattern('%j %H') self.assertFalse(re.match(pattern, "180")) self.assertTrue(re.match(pattern, "18 0")) class StrptimeTests(unittest.TestCase): """Tests for _strptime.strptime.""" def setUp(self): """Create testing time tuple.""" self.time_tuple = time.gmtime() def test_ValueError(self): # Make sure ValueError is raised when match fails or format is bad self.assertRaises(ValueError, _strptime._strptime_time, data_string="%d", format="%A") for bad_format in ("%", "% ", "%e"): try: _strptime._strptime_time("2005", bad_format) except ValueError: continue except Exception as err: self.fail("'%s' raised %s, not ValueError" % (bad_format, err.__class__.__name__)) else: self.fail("'%s' did not raise ValueError" % bad_format) # Ambiguous or incomplete cases using ISO year/week/weekday directives # 1. ISO week (%V) is specified, but the year is specified with %Y # instead of %G with self.assertRaises(ValueError): _strptime._strptime("1999 50", "%Y %V") # 2. ISO year (%G) and ISO week (%V) are specified, but weekday is not with self.assertRaises(ValueError): _strptime._strptime("1999 51", "%G %V") # 3. ISO year (%G) and weekday are specified, but ISO week (%V) is not for w in ('A', 'a', 'w', 'u'): with self.assertRaises(ValueError): _strptime._strptime("1999 51","%G %{}".format(w)) # 4. ISO year is specified alone (e.g. time.strptime('2015', '%G')) with self.assertRaises(ValueError): _strptime._strptime("2015", "%G") # 5. Julian/ordinal day (%j) is specified with %G, but not %Y with self.assertRaises(ValueError): _strptime._strptime("1999 256", "%G %j") def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see #17572) with self.assertRaises(ValueError) as e: _strptime._strptime_time('', '%D') self.assertIs(e.exception.__suppress_context__, True) # additional check for IndexError branch (issue #19545) with self.assertRaises(ValueError) as e: _strptime._strptime_time('19', '%Y %') self.assertIs(e.exception.__suppress_context__, True) def test_unconverteddata(self): # Check ValueError is raised when there is unconverted data self.assertRaises(ValueError, _strptime._strptime_time, "10 12", "%m") def helper(self, directive, position): """Helper fxn in testing.""" strf_output = time.strftime("%" + directive, self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%" + directive) self.assertTrue(strp_output[position] == self.time_tuple[position], "testing of '%s' directive failed; '%s' -> %s != %s" % (directive, strf_output, strp_output[position], self.time_tuple[position])) def test_year(self): # Test that the year is handled properly for directive in ('y', 'Y'): self.helper(directive, 0) # Must also make sure %y values are correct for bounds set by Open Group for century, bounds in ((1900, ('69', '99')), (2000, ('00', '68'))): for bound in bounds: strp_output = _strptime._strptime_time(bound, '%y') expected_result = century + int(bound) self.assertTrue(strp_output[0] == expected_result, "'y' test failed; passed in '%s' " "and returned '%s'" % (bound, strp_output[0])) def test_month(self): # Test for month directives for directive in ('B', 'b', 'm'): self.helper(directive, 1) def test_day(self): # Test for day directives self.helper('d', 2) def test_hour(self): # Test hour directives self.helper('H', 3) strf_output = time.strftime("%I %p", self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%I %p") self.assertTrue(strp_output[3] == self.time_tuple[3], "testing of '%%I %%p' directive failed; '%s' -> %s != %s" % (strf_output, strp_output[3], self.time_tuple[3])) def test_minute(self): # Test minute directives self.helper('M', 4) def test_second(self): # Test second directives self.helper('S', 5) def test_fraction(self): # Test microseconds import datetime d = datetime.datetime(2012, 12, 20, 12, 34, 56, 78987) tup, frac, _ = _strptime._strptime(str(d), format="%Y-%m-%d %H:%M:%S.%f") self.assertEqual(frac, d.microsecond) def test_weekday(self): # Test weekday directives for directive in ('A', 'a', 'w', 'u'): self.helper(directive,6) def test_julian(self): # Test julian directives self.helper('j', 7) def test_offset(self): one_hour = 60 * 60 half_hour = 30 * 60 half_minute = 30 (*_, offset), _, offset_fraction = _strptime._strptime("+0130", "%z") self.assertEqual(offset, one_hour + half_hour) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-0100", "%z") self.assertEqual(offset, -one_hour) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-013030", "%z") self.assertEqual(offset, -(one_hour + half_hour + half_minute)) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-013030.000001", "%z") self.assertEqual(offset, -(one_hour + half_hour + half_minute)) self.assertEqual(offset_fraction, -1) (*_, offset), _, offset_fraction = _strptime._strptime("+01:00", "%z") self.assertEqual(offset, one_hour) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-01:30", "%z") self.assertEqual(offset, -(one_hour + half_hour)) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30", "%z") self.assertEqual(offset, -(one_hour + half_hour + half_minute)) self.assertEqual(offset_fraction, 0) (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30.000001", "%z") self.assertEqual(offset, -(one_hour + half_hour + half_minute)) self.assertEqual(offset_fraction, -1) (*_, offset), _, offset_fraction = _strptime._strptime("+01:30:30.001", "%z") self.assertEqual(offset, one_hour + half_hour + half_minute) self.assertEqual(offset_fraction, 1000) (*_, offset), _, offset_fraction = _strptime._strptime("Z", "%z") self.assertEqual(offset, 0) self.assertEqual(offset_fraction, 0) def test_bad_offset(self): with self.assertRaises(ValueError): _strptime._strptime("-01:30:30.", "%z") with self.assertRaises(ValueError): _strptime._strptime("-0130:30", "%z") with self.assertRaises(ValueError): _strptime._strptime("-01:30:30.1234567", "%z") with self.assertRaises(ValueError): _strptime._strptime("-01:30:30:123456", "%z") with self.assertRaises(ValueError) as err: _strptime._strptime("-01:3030", "%z") self.assertEqual("Inconsistent use of : in -01:3030", str(err.exception)) def test_timezone(self): # Test timezone directives. # When gmtime() is used with %Z, entire result of strftime() is empty. # Check for equal timezone names deals with bad locale info when this # occurs; first found in FreeBSD 4.4. strp_output = _strptime._strptime_time("UTC", "%Z") self.assertEqual(strp_output.tm_isdst, 0) strp_output = _strptime._strptime_time("GMT", "%Z") self.assertEqual(strp_output.tm_isdst, 0) time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone strp_output = _strptime._strptime_time(strf_output, "%Z") locale_time = _strptime.LocaleTime() if time.tzname[0] != time.tzname[1] or not time.daylight: self.assertTrue(strp_output[8] == time_tuple[8], "timezone check failed; '%s' -> %s != %s" % (strf_output, strp_output[8], time_tuple[8])) else: self.assertTrue(strp_output[8] == -1, "LocaleTime().timezone has duplicate values and " "time.daylight but timezone value not set to -1") def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight tz_name = time.tzname[0] if tz_name.upper() in ("UTC", "GMT"): self.skipTest('need non-UTC/GMT timezone') with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \ support.swap_attr(time, 'daylight', 1), \ support.swap_attr(time, 'tzset', lambda: None): time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime._strptime_time(tz_name, "%Z")[8] self.assertEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % (time.tzname, tz_value, time.daylight, tz_name)) def test_date_time(self): # Test %c directive for position in range(6): self.helper('c', position) def test_date(self): # Test %x directive for position in range(0,3): self.helper('x', position) def test_time(self): # Test %X directive for position in range(3,6): self.helper('X', position) def test_percent(self): # Make sure % signs are handled properly strf_output = time.strftime("%m %% %Y", self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%m %% %Y") self.assertTrue(strp_output[0] == self.time_tuple[0] and strp_output[1] == self.time_tuple[1], "handling of percent sign failed") def test_caseinsensitive(self): # Should handle names case-insensitively. strf_output = time.strftime("%B", self.time_tuple) self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"), "strptime does not handle ALL-CAPS names properly") self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"), "strptime does not handle lowercase names properly") self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"), "strptime does not handle capword names properly") def test_defaults(self): # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0) defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1) strp_output = _strptime._strptime_time('1', '%m') self.assertTrue(strp_output == defaults, "Default values for strptime() are incorrect;" " %s != %s" % (strp_output, defaults)) def test_escaping(self): # Make sure all characters that have regex significance are escaped. # Parentheses are in a purposeful order; will cause an error of # unbalanced parentheses when the regex is compiled if they are not # escaped. # Test instigated by bug #796149 . need_escaping = r".^$*+?{}\[]|)(" self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping)) def test_feb29_on_leap_year_without_year(self): time.strptime("Feb 29", "%b %d") def test_mar1_comes_after_feb29_even_when_omitting_the_year(self): self.assertLess( time.strptime("Feb 29", "%b %d"), time.strptime("Mar 1", "%b %d")) class Strptime12AMPMTests(unittest.TestCase): """Test a _strptime regression in '%I %p' at 12 noon (12 PM)""" def test_twelve_noon_midnight(self): eq = self.assertEqual eq(time.strptime('12 PM', '%I %p')[3], 12) eq(time.strptime('12 AM', '%I %p')[3], 0) eq(_strptime._strptime_time('12 PM', '%I %p')[3], 12) eq(_strptime._strptime_time('12 AM', '%I %p')[3], 0) class JulianTests(unittest.TestCase): """Test a _strptime regression that all julian (1-366) are accepted""" def test_all_julian_days(self): eq = self.assertEqual for i in range(1, 367): # use 2004, since it is a leap year, we have 366 days eq(_strptime._strptime_time('%d 2004' % i, '%j %Y')[7], i) class CalculationTests(unittest.TestCase): """Test that strptime() fills in missing info correctly""" def setUp(self): self.time_tuple = time.gmtime() def test_julian_calculation(self): # Make sure that when Julian is missing that it is calculated format_string = "%Y %m %d %H %M %S %w %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.assertTrue(result.tm_yday == self.time_tuple.tm_yday, "Calculation of tm_yday failed; %s != %s" % (result.tm_yday, self.time_tuple.tm_yday)) def test_gregorian_calculation(self): # Test that Gregorian date can be calculated from Julian day format_string = "%Y %H %M %S %w %j %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.assertTrue(result.tm_year == self.time_tuple.tm_year and result.tm_mon == self.time_tuple.tm_mon and result.tm_mday == self.time_tuple.tm_mday, "Calculation of Gregorian date failed; " "%s-%s-%s != %s-%s-%s" % (result.tm_year, result.tm_mon, result.tm_mday, self.time_tuple.tm_year, self.time_tuple.tm_mon, self.time_tuple.tm_mday)) def test_day_of_week_calculation(self): # Test that the day of the week is calculated as needed format_string = "%Y %m %d %H %S %j %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) self.assertTrue(result.tm_wday == self.time_tuple.tm_wday, "Calculation of day of the week failed; " "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) if support.is_android: # Issue #26929: strftime() on Android incorrectly formats %V or %G for # the last or the first incomplete week in a year. _ymd_excluded = ((1905, 1, 1), (1906, 12, 31), (2008, 12, 29), (1917, 12, 31)) _formats_excluded = ('%G %V',) else: _ymd_excluded = () _formats_excluded = () @unittest.skipIf(sys.platform.startswith('aix'), 'bpo-29972: broken test on AIX') def test_week_of_year_and_day_of_week_calculation(self): # Should be able to infer date if given year, week of year (%U or %W) # and day of the week def test_helper(ymd_tuple, test_reason): for year_week_format in ('%Y %W', '%Y %U', '%G %V'): if (year_week_format in self._formats_excluded and ymd_tuple in self._ymd_excluded): return for weekday_format in ('%w', '%u', '%a', '%A'): format_string = year_week_format + ' ' + weekday_format with self.subTest(test_reason, date=ymd_tuple, format=format_string): dt_date = datetime_date(*ymd_tuple) strp_input = dt_date.strftime(format_string) strp_output = _strptime._strptime_time(strp_input, format_string) msg = "%r: %s != %s" % (strp_input, strp_output[7], dt_date.timetuple()[7]) self.assertEqual(strp_output[:3], ymd_tuple, msg) test_helper((1901, 1, 3), "week 0") test_helper((1901, 1, 8), "common case") test_helper((1901, 1, 13), "day on Sunday") test_helper((1901, 1, 14), "day on Monday") test_helper((1905, 1, 1), "Jan 1 on Sunday") test_helper((1906, 1, 1), "Jan 1 on Monday") test_helper((1906, 1, 7), "first Sunday in a year starting on Monday") test_helper((1905, 12, 31), "Dec 31 on Sunday") test_helper((1906, 12, 31), "Dec 31 on Monday") test_helper((2008, 12, 29), "Monday in the last week of the year") test_helper((2008, 12, 22), "Monday in the second-to-last week of the " "year") test_helper((1978, 10, 23), "randomly chosen date") test_helper((2004, 12, 18), "randomly chosen date") test_helper((1978, 10, 23), "year starting and ending on Monday while " "date not on Sunday or Monday") test_helper((1917, 12, 17), "year starting and ending on Monday with " "a Monday not at the beginning or end " "of the year") test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " "ending on Monday") test_helper((2007, 1, 7), "First Sunday of 2007") test_helper((2007, 1, 14), "Second Sunday of 2007") test_helper((2006, 12, 31), "Last Sunday of 2006") test_helper((2006, 12, 24), "Second to last Sunday of 2006") def test_week_0(self): def check(value, format, *expected): self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected) check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, 362) check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4) check('2015 1 1', '%G %V %u', 2014, 12, 29, 0, 0, 0, 0, 363) check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, 363) check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, 363) check('2015 1 2', '%G %V %u', 2014, 12, 30, 0, 0, 0, 1, 364) check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, 364) check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, 364) check('2015 1 3', '%G %V %u', 2014, 12, 31, 0, 0, 0, 2, 365) check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 365) check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 365) check('2015 1 4', '%G %V %u', 2015, 1, 1, 0, 0, 0, 3, 1) check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1) check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1) check('2015 1 5', '%G %V %u', 2015, 1, 2, 0, 0, 0, 4, 2) check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2) check('2015 0 5', '%Y %W %w', 2015, 1, 2, 0, 0, 0, 4, 2) check('2015 1 6', '%G %V %u', 2015, 1, 3, 0, 0, 0, 5, 3) check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3) check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3) check('2015 1 7', '%G %V %u', 2015, 1, 4, 0, 0, 0, 6, 4) check('2009 0 0', '%Y %U %w', 2008, 12, 28, 0, 0, 0, 6, 363) check('2009 0 0', '%Y %W %w', 2009, 1, 4, 0, 0, 0, 6, 4) check('2009 1 1', '%G %V %u', 2008, 12, 29, 0, 0, 0, 0, 364) check('2009 0 1', '%Y %U %w', 2008, 12, 29, 0, 0, 0, 0, 364) check('2009 0 1', '%Y %W %w', 2008, 12, 29, 0, 0, 0, 0, 364) check('2009 1 2', '%G %V %u', 2008, 12, 30, 0, 0, 0, 1, 365) check('2009 0 2', '%Y %U %w', 2008, 12, 30, 0, 0, 0, 1, 365) check('2009 0 2', '%Y %W %w', 2008, 12, 30, 0, 0, 0, 1, 365) check('2009 1 3', '%G %V %u', 2008, 12, 31, 0, 0, 0, 2, 366) check('2009 0 3', '%Y %U %w', 2008, 12, 31, 0, 0, 0, 2, 366) check('2009 0 3', '%Y %W %w', 2008, 12, 31, 0, 0, 0, 2, 366) check('2009 1 4', '%G %V %u', 2009, 1, 1, 0, 0, 0, 3, 1) check('2009 0 4', '%Y %U %w', 2009, 1, 1, 0, 0, 0, 3, 1) check('2009 0 4', '%Y %W %w', 2009, 1, 1, 0, 0, 0, 3, 1) check('2009 1 5', '%G %V %u', 2009, 1, 2, 0, 0, 0, 4, 2) check('2009 0 5', '%Y %U %w', 2009, 1, 2, 0, 0, 0, 4, 2) check('2009 0 5', '%Y %W %w', 2009, 1, 2, 0, 0, 0, 4, 2) check('2009 1 6', '%G %V %u', 2009, 1, 3, 0, 0, 0, 5, 3) check('2009 0 6', '%Y %U %w', 2009, 1, 3, 0, 0, 0, 5, 3) check('2009 0 6', '%Y %W %w', 2009, 1, 3, 0, 0, 0, 5, 3) check('2009 1 7', '%G %V %u', 2009, 1, 4, 0, 0, 0, 6, 4) class CacheTests(unittest.TestCase): """Test that caching works properly.""" def test_time_re_recreation(self): # Make sure cache is recreated when current locale does not match what # cached object was created with. _strptime._strptime_time("10", "%d") _strptime._strptime_time("2005", "%Y") _strptime._TimeRE_cache.locale_time.lang = "Ni" original_time_re = _strptime._TimeRE_cache _strptime._strptime_time("10", "%d") self.assertIsNot(original_time_re, _strptime._TimeRE_cache) self.assertEqual(len(_strptime._regex_cache), 1) def test_regex_cleanup(self): # Make sure cached regexes are discarded when cache becomes "full". try: del _strptime._regex_cache['%d'] except KeyError: pass bogus_key = 0 while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE: _strptime._regex_cache[bogus_key] = None bogus_key += 1 _strptime._strptime_time("10", "%d") self.assertEqual(len(_strptime._regex_cache), 1) def test_new_localetime(self): # A new LocaleTime instance should be created when a new TimeRE object # is created. locale_time_id = _strptime._TimeRE_cache.locale_time _strptime._TimeRE_cache.locale_time.lang = "Ni" _strptime._strptime_time("10", "%d") self.assertIsNot(locale_time_id, _strptime._TimeRE_cache.locale_time) def test_TimeRE_recreation_locale(self): # The TimeRE instance should be recreated upon changing the locale. locale_info = locale.getlocale(locale.LC_TIME) try: locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8')) except locale.Error: self.skipTest('test needs en_US.UTF8 locale') try: _strptime._strptime_time('10', '%d') # Get id of current cache object.
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_tw.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_tw.py
# # test_codecmaps_tw.py # Codec mapping tests for ROC encodings # from test import multibytecodec_support import unittest class TestBIG5Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'big5' mapfileurl = 'http://www.pythontest.net/unicode/BIG5.TXT' class TestCP950Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'cp950' mapfileurl = 'http://www.pythontest.net/unicode/CP950.TXT' pass_enctest = [ (b'\xa2\xcc', '\u5341'), (b'\xa2\xce', '\u5345'), ] codectests = ( (b"\xFFxy", "replace", "\ufffdxy"), ) 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_literal.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_int_literal.py
"""Test correct treatment of hex/oct constants. This is complex because of changes due to PEP 237. """ import unittest class TestHexOctBin(unittest.TestCase): def test_hex_baseline(self): # A few upper/lowercase tests self.assertEqual(0x0, 0X0) self.assertEqual(0x1, 0X1) self.assertEqual(0x123456789abcdef, 0X123456789abcdef) # Baseline tests self.assertEqual(0x0, 0) self.assertEqual(0x10, 16) self.assertEqual(0x7fffffff, 2147483647) self.assertEqual(0x7fffffffffffffff, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(0x0), 0) self.assertEqual(-(0x10), -16) self.assertEqual(-(0x7fffffff), -2147483647) self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-0x0, 0) self.assertEqual(-0x10, -16) self.assertEqual(-0x7fffffff, -2147483647) self.assertEqual(-0x7fffffffffffffff, -9223372036854775807) def test_hex_unsigned(self): # Positive constants self.assertEqual(0x80000000, 2147483648) self.assertEqual(0xffffffff, 4294967295) # Ditto with a minus sign and parentheses self.assertEqual(-(0x80000000), -2147483648) self.assertEqual(-(0xffffffff), -4294967295) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0x80000000, -2147483648) self.assertEqual(-0xffffffff, -4294967295) # Positive constants self.assertEqual(0x8000000000000000, 9223372036854775808) self.assertEqual(0xffffffffffffffff, 18446744073709551615) # Ditto with a minus sign and parentheses self.assertEqual(-(0x8000000000000000), -9223372036854775808) self.assertEqual(-(0xffffffffffffffff), -18446744073709551615) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0x8000000000000000, -9223372036854775808) self.assertEqual(-0xffffffffffffffff, -18446744073709551615) def test_oct_baseline(self): # A few upper/lowercase tests self.assertEqual(0o0, 0O0) self.assertEqual(0o1, 0O1) self.assertEqual(0o1234567, 0O1234567) # Baseline tests self.assertEqual(0o0, 0) self.assertEqual(0o20, 16) self.assertEqual(0o17777777777, 2147483647) self.assertEqual(0o777777777777777777777, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(0o0), 0) self.assertEqual(-(0o20), -16) self.assertEqual(-(0o17777777777), -2147483647) self.assertEqual(-(0o777777777777777777777), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-0o0, 0) self.assertEqual(-0o20, -16) self.assertEqual(-0o17777777777, -2147483647) self.assertEqual(-0o777777777777777777777, -9223372036854775807) def test_oct_unsigned(self): # Positive constants self.assertEqual(0o20000000000, 2147483648) self.assertEqual(0o37777777777, 4294967295) # Ditto with a minus sign and parentheses self.assertEqual(-(0o20000000000), -2147483648) self.assertEqual(-(0o37777777777), -4294967295) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0o20000000000, -2147483648) self.assertEqual(-0o37777777777, -4294967295) # Positive constants self.assertEqual(0o1000000000000000000000, 9223372036854775808) self.assertEqual(0o1777777777777777777777, 18446744073709551615) # Ditto with a minus sign and parentheses self.assertEqual(-(0o1000000000000000000000), -9223372036854775808) self.assertEqual(-(0o1777777777777777777777), -18446744073709551615) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0o1000000000000000000000, -9223372036854775808) self.assertEqual(-0o1777777777777777777777, -18446744073709551615) def test_bin_baseline(self): # A few upper/lowercase tests self.assertEqual(0b0, 0B0) self.assertEqual(0b1, 0B1) self.assertEqual(0b10101010101, 0B10101010101) # Baseline tests self.assertEqual(0b0, 0) self.assertEqual(0b10000, 16) self.assertEqual(0b1111111111111111111111111111111, 2147483647) self.assertEqual(0b111111111111111111111111111111111111111111111111111111111111111, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(0b0), 0) self.assertEqual(-(0b10000), -16) self.assertEqual(-(0b1111111111111111111111111111111), -2147483647) self.assertEqual(-(0b111111111111111111111111111111111111111111111111111111111111111), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-0b0, 0) self.assertEqual(-0b10000, -16) self.assertEqual(-0b1111111111111111111111111111111, -2147483647) self.assertEqual(-0b111111111111111111111111111111111111111111111111111111111111111, -9223372036854775807) def test_bin_unsigned(self): # Positive constants self.assertEqual(0b10000000000000000000000000000000, 2147483648) self.assertEqual(0b11111111111111111111111111111111, 4294967295) # Ditto with a minus sign and parentheses self.assertEqual(-(0b10000000000000000000000000000000), -2147483648) self.assertEqual(-(0b11111111111111111111111111111111), -4294967295) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0b10000000000000000000000000000000, -2147483648) self.assertEqual(-0b11111111111111111111111111111111, -4294967295) # Positive constants self.assertEqual(0b1000000000000000000000000000000000000000000000000000000000000000, 9223372036854775808) self.assertEqual(0b1111111111111111111111111111111111111111111111111111111111111111, 18446744073709551615) # Ditto with a minus sign and parentheses self.assertEqual(-(0b1000000000000000000000000000000000000000000000000000000000000000), -9223372036854775808) self.assertEqual(-(0b1111111111111111111111111111111111111111111111111111111111111111), -18446744073709551615) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0b1000000000000000000000000000000000000000000000000000000000000000, -9223372036854775808) self.assertEqual(-0b1111111111111111111111111111111111111111111111111111111111111111, -18446744073709551615) 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_urllibnet.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllibnet.py
import unittest from test import support import contextlib import socket import urllib.parse import urllib.request import os import email.message import time support.requires('network') class URLTimeoutTest(unittest.TestCase): # XXX this test doesn't seem to test anything useful. TIMEOUT = 30.0 def setUp(self): socket.setdefaulttimeout(self.TIMEOUT) def tearDown(self): socket.setdefaulttimeout(None) def testURLread(self): domain = urllib.parse.urlparse(support.TEST_HTTP_URL).netloc with support.transient_internet(domain): f = urllib.request.urlopen(support.TEST_HTTP_URL) f.read() class urlopenNetworkTests(unittest.TestCase): """Tests urllib.request.urlopen using the network. These tests are not exhaustive. Assuming that testing using files does a good job overall of some of the basic interface features. There are no tests exercising the optional 'data' and 'proxies' arguments. No tests for transparent redirection have been written. setUp is not used for always constructing a connection to http://www.pythontest.net/ since there a few tests that don't use that address and making a connection is expensive enough to warrant minimizing unneeded connections. """ url = 'http://www.pythontest.net/' @contextlib.contextmanager def urlopen(self, *args, **kwargs): resource = args[0] with support.transient_internet(resource): r = urllib.request.urlopen(*args, **kwargs) try: yield r finally: r.close() def test_basic(self): # Simple test expected to pass. with self.urlopen(self.url) as open_url: for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl"): self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) self.assertTrue(open_url.read(), "calling 'read' failed") def test_readlines(self): # Test both readline and readlines. with self.urlopen(self.url) as open_url: self.assertIsInstance(open_url.readline(), bytes, "readline did not return a string") self.assertIsInstance(open_url.readlines(), list, "readlines did not return a list") def test_info(self): # Test 'info'. with self.urlopen(self.url) as open_url: info_obj = open_url.info() self.assertIsInstance(info_obj, email.message.Message, "object returned by 'info' is not an " "instance of email.message.Message") self.assertEqual(info_obj.get_content_subtype(), "html") def test_geturl(self): # Make sure same URL as opened is returned by geturl. with self.urlopen(self.url) as open_url: gotten_url = open_url.geturl() self.assertEqual(gotten_url, self.url) def test_getcode(self): # test getcode() with the fancy opener to get 404 error codes URL = self.url + "XXXinvalidXXX" with support.transient_internet(URL): with self.assertWarns(DeprecationWarning): open_url = urllib.request.FancyURLopener().open(URL) try: code = open_url.getcode() finally: open_url.close() self.assertEqual(code, 404) def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus # address. # Given that both VeriSign and various ISPs have in # the past or are presently hijacking various invalid # domain name requests in an attempt to boost traffic # to their own sites, finding a domain name to use # for this test is difficult. RFC2606 leads one to # believe that '.invalid' should work, but experience # seemed to indicate otherwise. Single character # TLDs are likely to remain invalid, so this seems to # be the best choice. The trailing '.' prevents a # related problem: The normal DNS resolver appends # the domain names from the search path if there is # no '.' the end and, and if one of those domains # implements a '*' rule a result is returned. # However, none of this will prevent the test from # failing if the ISP hijacks all invalid domain # requests. The real solution would be to be able to # parameterize the framework with a mock resolver. bogus_domain = "sadflkjsasf.i.nvali.d." try: socket.gethostbyname(bogus_domain) except OSError: # socket.gaierror is too narrow, since getaddrinfo() may also # fail with EAI_SYSTEM and ETIMEDOUT (seen on Ubuntu 13.04), # i.e. Python's TimeoutError. pass else: # This happens with some overzealous DNS providers such as OpenDNS self.skipTest("%r should not resolve for test to work" % bogus_domain) failure_explanation = ('opening an invalid URL did not raise OSError; ' 'can be caused by a broken DNS server ' '(e.g. returns 404 or hijacks page)') with self.assertRaises(OSError, msg=failure_explanation): urllib.request.urlopen("http://{}/".format(bogus_domain)) class urlretrieveNetworkTests(unittest.TestCase): """Tests urllib.request.urlretrieve using the network.""" @contextlib.contextmanager def urlretrieve(self, *args, **kwargs): resource = args[0] with support.transient_internet(resource): file_location, info = urllib.request.urlretrieve(*args, **kwargs) try: yield file_location, info finally: support.unlink(file_location) def test_basic(self): # Test basic functionality. with self.urlretrieve(self.logo) as (file_location, info): self.assertTrue(os.path.exists(file_location), "file location returned by" " urlretrieve is not a valid path") with open(file_location, 'rb') as f: self.assertTrue(f.read(), "reading from the file location returned" " by urlretrieve failed") def test_specified_path(self): # Make sure that specifying the location of the file to write to works. with self.urlretrieve(self.logo, support.TESTFN) as (file_location, info): self.assertEqual(file_location, support.TESTFN) self.assertTrue(os.path.exists(file_location)) with open(file_location, 'rb') as f: self.assertTrue(f.read(), "reading from temporary file failed") def test_header(self): # Make sure header returned as 2nd value from urlretrieve is good. with self.urlretrieve(self.logo) as (file_location, info): self.assertIsInstance(info, email.message.Message, "info is not an instance of email.message.Message") logo = "http://www.pythontest.net/" def test_data_header(self): with self.urlretrieve(self.logo) as (file_location, fileheaders): datevalue = fileheaders.get('Date') dateformat = '%a, %d %b %Y %H:%M:%S GMT' try: time.strptime(datevalue, dateformat) except ValueError: self.fail('Date value not in %r format' % dateformat) def test_reporthook(self): records = [] def recording_reporthook(blocks, block_size, total_size): records.append((blocks, block_size, total_size)) with self.urlretrieve(self.logo, reporthook=recording_reporthook) as ( file_location, fileheaders): expected_size = int(fileheaders['Content-Length']) records_repr = repr(records) # For use in error messages. self.assertGreater(len(records), 1, msg="There should always be two " "calls; the first one before the transfer starts.") self.assertEqual(records[0][0], 0) self.assertGreater(records[0][1], 0, msg="block size can't be 0 in %s" % records_repr) self.assertEqual(records[0][2], expected_size) self.assertEqual(records[-1][2], expected_size) block_sizes = {block_size for _, block_size, _ in records} self.assertEqual({records[0][1]}, block_sizes, msg="block sizes in %s must be equal" % records_repr) self.assertGreaterEqual(records[-1][0]*records[0][1], expected_size, msg="number of blocks * block size must be" " >= total size in %s" % records_repr) 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_fstring.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fstring.py
import ast import types import decimal import unittest a_global = 'global variable' # You could argue that I'm too strict in looking for specific error # values with assertRaisesRegex, but without it it's way too easy to # make a syntax error in the test strings. Especially with all of the # triple quotes, raw strings, backslashes, etc. I think it's a # worthwhile tradeoff. When I switched to this method, I found many # examples where I wasn't testing what I thought I was. class TestCase(unittest.TestCase): def assertAllRaise(self, exception_type, regex, error_strings): for str in error_strings: with self.subTest(str=str): with self.assertRaisesRegex(exception_type, regex): eval(str) def test__format__lookup(self): # Make sure __format__ is looked up on the type, not the instance. class X: def __format__(self, spec): return 'class' x = X() # Add a bound __format__ method to the 'y' instance, but not # the 'x' instance. y = X() y.__format__ = types.MethodType(lambda self, spec: 'instance', y) self.assertEqual(f'{y}', format(y)) self.assertEqual(f'{y}', 'class') self.assertEqual(format(x), format(y)) # __format__ is not called this way, but still make sure it # returns what we expect (so we can make sure we're bypassing # it). self.assertEqual(x.__format__(''), 'class') self.assertEqual(y.__format__(''), 'instance') # This is how __format__ is actually called. self.assertEqual(type(x).__format__(x, ''), 'class') self.assertEqual(type(y).__format__(y, ''), 'class') def test_ast(self): # Inspired by http://bugs.python.org/issue24975 class X: def __init__(self): self.called = False def __call__(self): self.called = True return 4 x = X() expr = """ a = 10 f'{a * x()}'""" t = ast.parse(expr) c = compile(t, '', 'exec') # Make sure x was not called. self.assertFalse(x.called) # Actually run the code. exec(c) # Make sure x was called. self.assertTrue(x.called) def test_ast_line_numbers(self): expr = """ a = 10 f'{a * x()}'""" t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `a = 10` self.assertEqual(type(t.body[0]), ast.Assign) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 1) self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue) self.assertEqual(t.body[1].lineno, 3) self.assertEqual(t.body[1].value.lineno, 3) self.assertEqual(t.body[1].value.values[0].lineno, 3) # check the binop location binop = t.body[1].value.values[0].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) self.assertEqual(binop.left.col_offset, 3) self.assertEqual(binop.right.col_offset, 7) def test_ast_line_numbers_multiple_formattedvalues(self): expr = """ f'no formatted values' f'eggs {a * x()} spam {b + y()}'""" t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `f'no formatted value'` self.assertEqual(type(t.body[0]), ast.Expr) self.assertEqual(type(t.body[0].value), ast.JoinedStr) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 4) self.assertEqual(type(t.body[1].value.values[0]), ast.Str) self.assertEqual(type(t.body[1].value.values[1]), ast.FormattedValue) self.assertEqual(type(t.body[1].value.values[2]), ast.Str) self.assertEqual(type(t.body[1].value.values[3]), ast.FormattedValue) self.assertEqual(t.body[1].lineno, 3) self.assertEqual(t.body[1].value.lineno, 3) self.assertEqual(t.body[1].value.values[0].lineno, 3) self.assertEqual(t.body[1].value.values[1].lineno, 3) self.assertEqual(t.body[1].value.values[2].lineno, 3) self.assertEqual(t.body[1].value.values[3].lineno, 3) # check the first binop location binop1 = t.body[1].value.values[1].value self.assertEqual(type(binop1), ast.BinOp) self.assertEqual(type(binop1.left), ast.Name) self.assertEqual(type(binop1.op), ast.Mult) self.assertEqual(type(binop1.right), ast.Call) self.assertEqual(binop1.lineno, 3) self.assertEqual(binop1.left.lineno, 3) self.assertEqual(binop1.right.lineno, 3) self.assertEqual(binop1.col_offset, 8) self.assertEqual(binop1.left.col_offset, 8) self.assertEqual(binop1.right.col_offset, 12) # check the second binop location binop2 = t.body[1].value.values[3].value self.assertEqual(type(binop2), ast.BinOp) self.assertEqual(type(binop2.left), ast.Name) self.assertEqual(type(binop2.op), ast.Add) self.assertEqual(type(binop2.right), ast.Call) self.assertEqual(binop2.lineno, 3) self.assertEqual(binop2.left.lineno, 3) self.assertEqual(binop2.right.lineno, 3) self.assertEqual(binop2.col_offset, 23) self.assertEqual(binop2.left.col_offset, 23) self.assertEqual(binop2.right.col_offset, 27) def test_ast_line_numbers_nested(self): expr = """ a = 10 f'{a * f"-{x()}-"}'""" t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `a = 10` self.assertEqual(type(t.body[0]), ast.Assign) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 1) self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue) self.assertEqual(t.body[1].lineno, 3) self.assertEqual(t.body[1].value.lineno, 3) self.assertEqual(t.body[1].value.values[0].lineno, 3) # check the binop location binop = t.body[1].value.values[0].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.JoinedStr) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) self.assertEqual(binop.left.col_offset, 3) self.assertEqual(binop.right.col_offset, 7) # check the nested call location self.assertEqual(len(binop.right.values), 3) self.assertEqual(type(binop.right.values[0]), ast.Str) self.assertEqual(type(binop.right.values[1]), ast.FormattedValue) self.assertEqual(type(binop.right.values[2]), ast.Str) self.assertEqual(binop.right.values[0].lineno, 3) self.assertEqual(binop.right.values[1].lineno, 3) self.assertEqual(binop.right.values[2].lineno, 3) call = binop.right.values[1].value self.assertEqual(type(call), ast.Call) self.assertEqual(call.lineno, 3) self.assertEqual(call.col_offset, 11) def test_ast_line_numbers_duplicate_expression(self): """Duplicate expression NOTE: this is currently broken, always sets location of the first expression. """ expr = """ a = 10 f'{a * x()} {a * x()} {a * x()}' """ t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `a = 10` self.assertEqual(type(t.body[0]), ast.Assign) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 5) self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue) self.assertEqual(type(t.body[1].value.values[1]), ast.Str) self.assertEqual(type(t.body[1].value.values[2]), ast.FormattedValue) self.assertEqual(type(t.body[1].value.values[3]), ast.Str) self.assertEqual(type(t.body[1].value.values[4]), ast.FormattedValue) self.assertEqual(t.body[1].lineno, 3) self.assertEqual(t.body[1].value.lineno, 3) self.assertEqual(t.body[1].value.values[0].lineno, 3) self.assertEqual(t.body[1].value.values[1].lineno, 3) self.assertEqual(t.body[1].value.values[2].lineno, 3) self.assertEqual(t.body[1].value.values[3].lineno, 3) self.assertEqual(t.body[1].value.values[4].lineno, 3) # check the first binop location binop = t.body[1].value.values[0].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) self.assertEqual(binop.left.col_offset, 3) self.assertEqual(binop.right.col_offset, 7) # check the second binop location binop = t.body[1].value.values[2].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) # FIXME: this is wrong self.assertEqual(binop.left.col_offset, 3) # FIXME: this is wrong self.assertEqual(binop.right.col_offset, 7) # FIXME: this is wrong # check the third binop location binop = t.body[1].value.values[4].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) # FIXME: this is wrong self.assertEqual(binop.left.col_offset, 3) # FIXME: this is wrong self.assertEqual(binop.right.col_offset, 7) # FIXME: this is wrong def test_ast_line_numbers_multiline_fstring(self): # FIXME: This test demonstrates invalid behavior due to JoinedStr's # immediate child nodes containing the wrong lineno. The enclosed # expressions have valid line information and column offsets. # See bpo-16806 and bpo-30465 for details. expr = """ a = 10 f''' {a * x()} non-important content ''' """ t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `a = 10` self.assertEqual(type(t.body[0]), ast.Assign) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 3) self.assertEqual(type(t.body[1].value.values[0]), ast.Str) self.assertEqual(type(t.body[1].value.values[1]), ast.FormattedValue) self.assertEqual(type(t.body[1].value.values[2]), ast.Str) # NOTE: the following invalid behavior is described in bpo-16806. # - line number should be the *first* line (3), not the *last* (8) # - column offset should not be -1 self.assertEqual(t.body[1].lineno, 8) self.assertEqual(t.body[1].value.lineno, 8) self.assertEqual(t.body[1].value.values[0].lineno, 8) self.assertEqual(t.body[1].value.values[1].lineno, 8) self.assertEqual(t.body[1].value.values[2].lineno, 8) self.assertEqual(t.body[1].col_offset, -1) self.assertEqual(t.body[1].value.col_offset, -1) self.assertEqual(t.body[1].value.values[0].col_offset, -1) self.assertEqual(t.body[1].value.values[1].col_offset, -1) self.assertEqual(t.body[1].value.values[2].col_offset, -1) # NOTE: the following lineno information and col_offset is correct for # expressions within FormattedValues. binop = t.body[1].value.values[1].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 4) self.assertEqual(binop.left.lineno, 4) self.assertEqual(binop.right.lineno, 6) self.assertEqual(binop.col_offset, 3) self.assertEqual(binop.left.col_offset, 3) self.assertEqual(binop.right.col_offset, 7) def test_docstring(self): def f(): f'''Not a docstring''' self.assertIsNone(f.__doc__) def g(): '''Not a docstring''' \ f'' self.assertIsNone(g.__doc__) def test_literal_eval(self): with self.assertRaisesRegex(ValueError, 'malformed node or string'): ast.literal_eval("f'x'") def test_ast_compile_time_concat(self): x = [''] expr = """x[0] = 'foo' f'{3}'""" t = ast.parse(expr) c = compile(t, '', 'exec') exec(c) self.assertEqual(x[0], 'foo3') def test_compile_time_concat_errors(self): self.assertAllRaise(SyntaxError, 'cannot mix bytes and nonbytes literals', [r"""f'' b''""", r"""b'' f''""", ]) def test_literal(self): self.assertEqual(f'', '') self.assertEqual(f'a', 'a') self.assertEqual(f' ', ' ') def test_unterminated_string(self): self.assertAllRaise(SyntaxError, 'f-string: unterminated string', [r"""f'{"x'""", r"""f'{"x}'""", r"""f'{("x'""", r"""f'{("x}'""", ]) def test_mismatched_parens(self): self.assertAllRaise(SyntaxError, 'f-string: mismatched', ["f'{((}'", ]) def test_double_braces(self): self.assertEqual(f'{{', '{') self.assertEqual(f'a{{', 'a{') self.assertEqual(f'{{b', '{b') self.assertEqual(f'a{{b', 'a{b') self.assertEqual(f'}}', '}') self.assertEqual(f'a}}', 'a}') self.assertEqual(f'}}b', '}b') self.assertEqual(f'a}}b', 'a}b') self.assertEqual(f'{{}}', '{}') self.assertEqual(f'a{{}}', 'a{}') self.assertEqual(f'{{b}}', '{b}') self.assertEqual(f'{{}}c', '{}c') self.assertEqual(f'a{{b}}', 'a{b}') self.assertEqual(f'a{{}}c', 'a{}c') self.assertEqual(f'{{b}}c', '{b}c') self.assertEqual(f'a{{b}}c', 'a{b}c') self.assertEqual(f'{{{10}', '{10') self.assertEqual(f'}}{10}', '}10') self.assertEqual(f'}}{{{10}', '}{10') self.assertEqual(f'}}a{{{10}', '}a{10') self.assertEqual(f'{10}{{', '10{') self.assertEqual(f'{10}}}', '10}') self.assertEqual(f'{10}}}{{', '10}{') self.assertEqual(f'{10}}}a{{' '}', '10}a{}') # Inside of strings, don't interpret doubled brackets. self.assertEqual(f'{"{{}}"}', '{{}}') self.assertAllRaise(TypeError, 'unhashable type', ["f'{ {{}} }'", # dict in a set ]) def test_compile_time_concat(self): x = 'def' self.assertEqual('abc' f'## {x}ghi', 'abc## defghi') self.assertEqual('abc' f'{x}' 'ghi', 'abcdefghi') self.assertEqual('abc' f'{x}' 'gh' f'i{x:4}', 'abcdefghidef ') self.assertEqual('{x}' f'{x}', '{x}def') self.assertEqual('{x' f'{x}', '{xdef') self.assertEqual('{x}' f'{x}', '{x}def') self.assertEqual('{{x}}' f'{x}', '{{x}}def') self.assertEqual('{{x' f'{x}', '{{xdef') self.assertEqual('x}}' f'{x}', 'x}}def') self.assertEqual(f'{x}' 'x}}', 'defx}}') self.assertEqual(f'{x}' '', 'def') self.assertEqual('' f'{x}' '', 'def') self.assertEqual('' f'{x}', 'def') self.assertEqual(f'{x}' '2', 'def2') self.assertEqual('1' f'{x}' '2', '1def2') self.assertEqual('1' f'{x}', '1def') self.assertEqual(f'{x}' f'-{x}', 'def-def') self.assertEqual('' f'', '') self.assertEqual('' f'' '', '') self.assertEqual('' f'' '' f'', '') self.assertEqual(f'', '') self.assertEqual(f'' '', '') self.assertEqual(f'' '' f'', '') self.assertEqual(f'' '' f'' '', '') self.assertAllRaise(SyntaxError, "f-string: expecting '}'", ["f'{3' f'}'", # can't concat to get a valid f-string ]) def test_comments(self): # These aren't comments, since they're in strings. d = {'#': 'hash'} self.assertEqual(f'{"#"}', '#') self.assertEqual(f'{d["#"]}', 'hash') self.assertAllRaise(SyntaxError, "f-string expression part cannot include '#'", ["f'{1#}'", # error because the expression becomes "(1#)" "f'{3(#)}'", "f'{#}'", "f'{)#}'", # When wrapped in parens, this becomes # '()#)'. Make sure that doesn't compile. ]) def test_many_expressions(self): # Create a string with many expressions in it. Note that # because we have a space in here as a literal, we're actually # going to use twice as many ast nodes: one for each literal # plus one for each expression. def build_fstr(n, extra=''): return "f'" + ('{x} ' * n) + extra + "'" x = 'X' width = 1 # Test around 256. for i in range(250, 260): self.assertEqual(eval(build_fstr(i)), (x+' ')*i) # Test concatenating 2 largs fstrings. self.assertEqual(eval(build_fstr(255)*256), (x+' ')*(255*256)) s = build_fstr(253, '{x:{width}} ') self.assertEqual(eval(s), (x+' ')*254) # Test lots of expressions and constants, concatenated. s = "f'{1}' 'x' 'y'" * 1024 self.assertEqual(eval(s), '1xy' * 1024) def test_format_specifier_expressions(self): width = 10 precision = 4 value = decimal.Decimal('12.34567') self.assertEqual(f'result: {value:{width}.{precision}}', 'result: 12.35') self.assertEqual(f'result: {value:{width!r}.{precision}}', 'result: 12.35') self.assertEqual(f'result: {value:{width:0}.{precision:1}}', 'result: 12.35') self.assertEqual(f'result: {value:{1}{0:0}.{precision:1}}', 'result: 12.35') self.assertEqual(f'result: {value:{ 1}{ 0:0}.{ precision:1}}', 'result: 12.35') self.assertEqual(f'{10:#{1}0x}', ' 0xa') self.assertEqual(f'{10:{"#"}1{0}{"x"}}', ' 0xa') self.assertEqual(f'{-10:-{"#"}1{0}x}', ' -0xa') self.assertEqual(f'{-10:{"-"}#{1}0{"x"}}', ' -0xa') self.assertEqual(f'{10:#{3 != {4:5} and width}x}', ' 0xa') self.assertAllRaise(SyntaxError, "f-string: expecting '}'", ["""f'{"s"!r{":10"}}'""", # This looks like a nested format spec. ]) self.assertAllRaise(SyntaxError, "invalid syntax", [# Invalid syntax inside a nested spec. "f'{4:{/5}}'", ]) self.assertAllRaise(SyntaxError, "f-string: expressions nested too deeply", [# Can't nest format specifiers. "f'result: {value:{width:{0}}.{precision:1}}'", ]) self.assertAllRaise(SyntaxError, 'f-string: invalid conversion character', [# No expansion inside conversion or for # the : or ! itself. """f'{"s"!{"r"}}'""", ]) def test_side_effect_order(self): class X: def __init__(self): self.i = 0 def __format__(self, spec): self.i += 1 return str(self.i) x = X() self.assertEqual(f'{x} {x}', '1 2') def test_missing_expression(self): self.assertAllRaise(SyntaxError, 'f-string: empty expression not allowed', ["f'{}'", "f'{ }'" "f' {} '", "f'{!r}'", "f'{ !r}'", "f'{10:{ }}'", "f' { } '", # The Python parser ignores also the following # whitespace characters in additional to a space. "f'''{\t\f\r\n}'''", # Catch the empty expression before the # invalid conversion. "f'{!x}'", "f'{ !xr}'", "f'{!x:}'", "f'{!x:a}'", "f'{ !xr:}'", "f'{ !xr:a}'", "f'{!}'", "f'{:}'", # We find the empty expression before the # missing closing brace. "f'{!'", "f'{!s:'", "f'{:'", "f'{:x'", ]) # Different error message is raised for other whitespace characters. self.assertAllRaise(SyntaxError, 'invalid character in identifier', ["f'''{\xa0}'''", "\xa0", ]) def test_parens_in_expressions(self): self.assertEqual(f'{3,}', '(3,)') # Add these because when an expression is evaluated, parens # are added around it. But we shouldn't go from an invalid # expression to a valid one. The added parens are just # supposed to allow whitespace (including newlines). self.assertAllRaise(SyntaxError, 'invalid syntax', ["f'{,}'", "f'{,}'", # this is (,), which is an error ]) self.assertAllRaise(SyntaxError, "f-string: expecting '}'", ["f'{3)+(4}'", ]) self.assertAllRaise(SyntaxError, 'EOL while scanning string literal', ["f'{\n}'", ]) def test_backslashes_in_string_part(self): self.assertEqual(f'\t', '\t') self.assertEqual(r'\t', '\\t') self.assertEqual(rf'\t', '\\t') self.assertEqual(f'{2}\t', '2\t') self.assertEqual(f'{2}\t{3}', '2\t3') self.assertEqual(f'\t{3}', '\t3') self.assertEqual(f'\u0394', '\u0394') self.assertEqual(r'\u0394', '\\u0394') self.assertEqual(rf'\u0394', '\\u0394') self.assertEqual(f'{2}\u0394', '2\u0394') self.assertEqual(f'{2}\u0394{3}', '2\u03943') self.assertEqual(f'\u0394{3}', '\u03943') self.assertEqual(f'\U00000394', '\u0394') self.assertEqual(r'\U00000394', '\\U00000394') self.assertEqual(rf'\U00000394', '\\U00000394') self.assertEqual(f'{2}\U00000394', '2\u0394') self.assertEqual(f'{2}\U00000394{3}', '2\u03943') self.assertEqual(f'\U00000394{3}', '\u03943') self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}', '\u0394') self.assertEqual(f'{2}\N{GREEK CAPITAL LETTER DELTA}', '2\u0394') self.assertEqual(f'{2}\N{GREEK CAPITAL LETTER DELTA}{3}', '2\u03943') self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}{3}', '\u03943') self.assertEqual(f'2\N{GREEK CAPITAL LETTER DELTA}', '2\u0394') self.assertEqual(f'2\N{GREEK CAPITAL LETTER DELTA}3', '2\u03943') self.assertEqual(f'\N{GREEK CAPITAL LETTER DELTA}3', '\u03943') self.assertEqual(f'\x20', ' ') self.assertEqual(r'\x20', '\\x20') self.assertEqual(rf'\x20', '\\x20') self.assertEqual(f'{2}\x20', '2 ') self.assertEqual(f'{2}\x20{3}', '2 3') self.assertEqual(f'\x20{3}', ' 3') self.assertEqual(f'2\x20', '2 ') self.assertEqual(f'2\x203', '2 3') self.assertEqual(f'\x203', ' 3') with self.assertWarns(DeprecationWarning): # invalid escape sequence value = eval(r"f'\{6*7}'") self.assertEqual(value, '\\42') self.assertEqual(f'\\{6*7}', '\\42') self.assertEqual(fr'\{6*7}', '\\42') AMPERSAND = 'spam' # Get the right unicode character (&), or pick up local variable # depending on the number of backslashes. self.assertEqual(f'\N{AMPERSAND}', '&') self.assertEqual(f'\\N{AMPERSAND}', '\\Nspam') self.assertEqual(fr'\N{AMPERSAND}', '\\Nspam') self.assertEqual(f'\\\N{AMPERSAND}', '\\&') def test_misformed_unicode_character_name(self): # These test are needed because unicode names are parsed # differently inside f-strings. self.assertAllRaise(SyntaxError, r"\(unicode error\) 'unicodeescape' codec can't decode bytes in position .*: malformed \\N character escape", [r"f'\N'", r"f'\N{'", r"f'\N{GREEK CAPITAL LETTER DELTA'", # Here are the non-f-string versions, # which should give the same errors. r"'\N'", r"'\N{'", r"'\N{GREEK CAPITAL LETTER DELTA'", ]) def test_no_backslashes_in_expression_part(self): self.assertAllRaise(SyntaxError, 'f-string expression part cannot include a backslash', [r"f'{\'a\'}'", r"f'{\t3}'", r"f'{\}'", r"rf'{\'a\'}'", r"rf'{\t3}'", r"rf'{\}'", r"""rf'{"\N{LEFT CURLY BRACKET}"}'""", r"f'{\n}'", ]) def test_no_escapes_for_braces(self): """ Only literal curly braces begin an expression. """ # \x7b is '{'. self.assertEqual(f'\x7b1+1}}', '{1+1}') self.assertEqual(f'\x7b1+1', '{1+1') self.assertEqual(f'\u007b1+1', '{1+1') self.assertEqual(f'\N{LEFT CURLY BRACKET}1+1\N{RIGHT CURLY BRACKET}', '{1+1}') def test_newlines_in_expressions(self): self.assertEqual(f'{0}', '0') self.assertEqual(rf'''{3+ 4}''', '7') def test_lambda(self): x = 5 self.assertEqual(f'{(lambda y:x*y)("8")!r}', "'88888'") self.assertEqual(f'{(lambda y:x*y)("8")!r:10}', "'88888' ") self.assertEqual(f'{(lambda y:x*y)("8"):10}', "88888 ") # lambda doesn't work without parens, because the colon # makes the parser think it's a format_spec self.assertAllRaise(SyntaxError, 'unexpected EOF while parsing', ["f'{lambda x:x}'", ]) def test_yield(self): # Not terribly useful, but make sure the yield turns # a function into a generator def fn(y): f'y:{yield y*2}' g = fn(4) self.assertEqual(next(g), 8) def test_yield_send(self): def fn(x): yield f'x:{yield (lambda i: x * i)}' g = fn(10) the_lambda = next(g) self.assertEqual(the_lambda(4), 40) self.assertEqual(g.send('string'), 'x:string') def test_expressions_with_triple_quoted_strings(self): self.assertEqual(f"{'''x'''}", 'x') self.assertEqual(f"{'''eric's'''}", "eric's") # Test concatenation within an expression self.assertEqual(f'{"x" """eric"s""" "y"}', 'xeric"sy') self.assertEqual(f'{"x" """eric"s"""}', 'xeric"s') self.assertEqual(f'{"""eric"s""" "y"}', 'eric"sy') self.assertEqual(f'{"""x""" """eric"s""" "y"}', 'xeric"sy') self.assertEqual(f'{"""x""" """eric"s""" """y"""}', 'xeric"sy') self.assertEqual(f'{r"""x""" """eric"s""" """y"""}', 'xeric"sy') def test_multiple_vars(self): x = 98 y = 'abc' self.assertEqual(f'{x}{y}', '98abc') self.assertEqual(f'X{x}{y}', 'X98abc') self.assertEqual(f'{x}X{y}', '98Xabc') self.assertEqual(f'{x}{y}X', '98abcX') self.assertEqual(f'X{x}Y{y}', 'X98Yabc') self.assertEqual(f'X{x}{y}Y', 'X98abcY') self.assertEqual(f'{x}X{y}Y', '98XabcY') self.assertEqual(f'X{x}Y{y}Z', 'X98YabcZ') def test_closure(self): def outer(x): def inner(): return f'x:{x}' return inner self.assertEqual(outer('987')(), 'x:987') self.assertEqual(outer(7)(), 'x:7') def test_arguments(self): y = 2 def f(x, width): return f'x={x*y:{width}}' self.assertEqual(f('foo', 10), 'x=foofoo ') x = 'bar' self.assertEqual(f(10, 10), 'x= 20') def test_locals(self): value = 123 self.assertEqual(f'v:{value}', 'v:123') def test_missing_variable(self): with self.assertRaises(NameError): f'v:{value}' def test_missing_format_spec(self): class O: def __format__(self, spec): if not spec: return '*' return spec self.assertEqual(f'{O():x}', 'x') self.assertEqual(f'{O()}', '*') self.assertEqual(f'{O():}', '*') self.assertEqual(f'{3:}', '3') self.assertEqual(f'{3!s:}', '3') def test_global(self): self.assertEqual(f'g:{a_global}', 'g:global variable') self.assertEqual(f'g:{a_global!r}', "g:'global variable'") a_local = 'local variable' self.assertEqual(f'g:{a_global} l:{a_local}', 'g:global variable l:local variable') self.assertEqual(f'g:{a_global!r}', "g:'global variable'") self.assertEqual(f'g:{a_global} l:{a_local!r}', "g:global variable l:'local variable'") self.assertIn("module 'unittest' from", f'{unittest}') def test_shadowed_global(self): a_global = 'really a local' self.assertEqual(f'g:{a_global}', 'g:really a local') self.assertEqual(f'g:{a_global!r}', "g:'really a local'") a_local = 'local variable' self.assertEqual(f'g:{a_global} l:{a_local}', 'g:really a local l:local variable') self.assertEqual(f'g:{a_global!r}',
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_binop.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_binop.py
"""Tests for binary operators on subtypes of built-in types.""" import unittest from operator import eq, le, ne from abc import ABCMeta def gcd(a, b): """Greatest common divisor using Euclid's algorithm.""" while a: a, b = b%a, a return b def isint(x): """Test whether an object is an instance of int.""" return isinstance(x, int) def isnum(x): """Test whether an object is an instance of a built-in numeric type.""" for T in int, float, complex: if isinstance(x, T): return 1 return 0 def isRat(x): """Test whether an object is an instance of the Rat class.""" return isinstance(x, Rat) class Rat(object): """Rational number implemented as a normalized pair of ints.""" __slots__ = ['_Rat__num', '_Rat__den'] def __init__(self, num=0, den=1): """Constructor: Rat([num[, den]]). The arguments must be ints, and default to (0, 1).""" if not isint(num): raise TypeError("Rat numerator must be int (%r)" % num) if not isint(den): raise TypeError("Rat denominator must be int (%r)" % den) # But the zero is always on if den == 0: raise ZeroDivisionError("zero denominator") g = gcd(den, num) self.__num = int(num//g) self.__den = int(den//g) def _get_num(self): """Accessor function for read-only 'num' attribute of Rat.""" return self.__num num = property(_get_num, None) def _get_den(self): """Accessor function for read-only 'den' attribute of Rat.""" return self.__den den = property(_get_den, None) def __repr__(self): """Convert a Rat to a string resembling a Rat constructor call.""" return "Rat(%d, %d)" % (self.__num, self.__den) def __str__(self): """Convert a Rat to a string resembling a decimal numeric value.""" return str(float(self)) def __float__(self): """Convert a Rat to a float.""" return self.__num*1.0/self.__den def __int__(self): """Convert a Rat to an int; self.den must be 1.""" if self.__den == 1: try: return int(self.__num) except OverflowError: raise OverflowError("%s too large to convert to int" % repr(self)) raise ValueError("can't convert %s to int" % repr(self)) def __add__(self, other): """Add two Rats, or a Rat and a number.""" if isint(other): other = Rat(other) if isRat(other): return Rat(self.__num*other.__den + other.__num*self.__den, self.__den*other.__den) if isnum(other): return float(self) + other return NotImplemented __radd__ = __add__ def __sub__(self, other): """Subtract two Rats, or a Rat and a number.""" if isint(other): other = Rat(other) if isRat(other): return Rat(self.__num*other.__den - other.__num*self.__den, self.__den*other.__den) if isnum(other): return float(self) - other return NotImplemented def __rsub__(self, other): """Subtract two Rats, or a Rat and a number (reversed args).""" if isint(other): other = Rat(other) if isRat(other): return Rat(other.__num*self.__den - self.__num*other.__den, self.__den*other.__den) if isnum(other): return other - float(self) return NotImplemented def __mul__(self, other): """Multiply two Rats, or a Rat and a number.""" if isRat(other): return Rat(self.__num*other.__num, self.__den*other.__den) if isint(other): return Rat(self.__num*other, self.__den) if isnum(other): return float(self)*other return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): """Divide two Rats, or a Rat and a number.""" if isRat(other): return Rat(self.__num*other.__den, self.__den*other.__num) if isint(other): return Rat(self.__num, self.__den*other) if isnum(other): return float(self) / other return NotImplemented def __rtruediv__(self, other): """Divide two Rats, or a Rat and a number (reversed args).""" if isRat(other): return Rat(other.__num*self.__den, other.__den*self.__num) if isint(other): return Rat(other*self.__den, self.__num) if isnum(other): return other / float(self) return NotImplemented def __floordiv__(self, other): """Divide two Rats, returning the floored result.""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented x = self/other return x.__num // x.__den def __rfloordiv__(self, other): """Divide two Rats, returning the floored result (reversed args).""" x = other/self return x.__num // x.__den def __divmod__(self, other): """Divide two Rats, returning quotient and remainder.""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented x = self//other return (x, self - other * x) def __rdivmod__(self, other): """Divide two Rats, returning quotient and remainder (reversed args).""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented return divmod(other, self) def __mod__(self, other): """Take one Rat modulo another.""" return divmod(self, other)[1] def __rmod__(self, other): """Take one Rat modulo another (reversed args).""" return divmod(other, self)[1] def __eq__(self, other): """Compare two Rats for equality.""" if isint(other): return self.__den == 1 and self.__num == other if isRat(other): return self.__num == other.__num and self.__den == other.__den if isnum(other): return float(self) == other return NotImplemented class RatTestCase(unittest.TestCase): """Unit tests for Rat class and its support utilities.""" def test_gcd(self): self.assertEqual(gcd(10, 12), 2) self.assertEqual(gcd(10, 15), 5) self.assertEqual(gcd(10, 11), 1) self.assertEqual(gcd(100, 15), 5) self.assertEqual(gcd(-10, 2), -2) self.assertEqual(gcd(10, -2), 2) self.assertEqual(gcd(-10, -2), -2) for i in range(1, 20): for j in range(1, 20): self.assertTrue(gcd(i, j) > 0) self.assertTrue(gcd(-i, j) < 0) self.assertTrue(gcd(i, -j) > 0) self.assertTrue(gcd(-i, -j) < 0) def test_constructor(self): a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10, -15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, 15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, -15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(7) self.assertEqual(a.num, 7) self.assertEqual(a.den, 1) try: a = Rat(1, 0) except ZeroDivisionError: pass else: self.fail("Rat(1, 0) didn't raise ZeroDivisionError") for bad in "0", 0.0, 0j, (), [], {}, None, Rat, unittest: try: a = Rat(bad) except TypeError: pass else: self.fail("Rat(%r) didn't raise TypeError" % bad) try: a = Rat(1, bad) except TypeError: pass else: self.fail("Rat(1, %r) didn't raise TypeError" % bad) def test_add(self): self.assertEqual(Rat(2, 3) + Rat(1, 3), 1) self.assertEqual(Rat(2, 3) + 1, Rat(5, 3)) self.assertEqual(1 + Rat(2, 3), Rat(5, 3)) self.assertEqual(1.0 + Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) + 1.0, 1.5) def test_sub(self): self.assertEqual(Rat(7, 2) - Rat(7, 5), Rat(21, 10)) self.assertEqual(Rat(7, 5) - 1, Rat(2, 5)) self.assertEqual(1 - Rat(3, 5), Rat(2, 5)) self.assertEqual(Rat(3, 2) - 1.0, 0.5) self.assertEqual(1.0 - Rat(1, 2), 0.5) def test_mul(self): self.assertEqual(Rat(2, 3) * Rat(5, 7), Rat(10, 21)) self.assertEqual(Rat(10, 3) * 3, 10) self.assertEqual(3 * Rat(10, 3), 10) self.assertEqual(Rat(10, 5) * 0.5, 1.0) self.assertEqual(0.5 * Rat(10, 5), 1.0) def test_div(self): self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3)) self.assertEqual(Rat(10, 3) / 3, Rat(10, 9)) self.assertEqual(2 / Rat(5), Rat(2, 5)) self.assertEqual(3.0 * Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) * 3.0, 1.5) def test_floordiv(self): self.assertEqual(Rat(10) // Rat(4), 2) self.assertEqual(Rat(10, 3) // Rat(4, 3), 2) self.assertEqual(Rat(10) // 4, 2) self.assertEqual(10 // Rat(4), 2) def test_eq(self): self.assertEqual(Rat(10), Rat(20, 2)) self.assertEqual(Rat(10), 10) self.assertEqual(10, Rat(10)) self.assertEqual(Rat(10), 10.0) self.assertEqual(10.0, Rat(10)) def test_true_div(self): self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3)) self.assertEqual(Rat(10, 3) / 3, Rat(10, 9)) self.assertEqual(2 / Rat(5), Rat(2, 5)) self.assertEqual(3.0 * Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) * 3.0, 1.5) self.assertEqual(eval('1/2'), 0.5) # XXX Ran out of steam; TO DO: divmod, div, future division class OperationLogger: """Base class for classes with operation logging.""" def __init__(self, logger): self.logger = logger def log_operation(self, *args): self.logger(*args) def op_sequence(op, *classes): """Return the sequence of operations that results from applying the operation `op` to instances of the given classes.""" log = [] instances = [] for c in classes: instances.append(c(log.append)) try: op(*instances) except TypeError: pass return log class A(OperationLogger): def __eq__(self, other): self.log_operation('A.__eq__') return NotImplemented def __le__(self, other): self.log_operation('A.__le__') return NotImplemented def __ge__(self, other): self.log_operation('A.__ge__') return NotImplemented class B(OperationLogger, metaclass=ABCMeta): def __eq__(self, other): self.log_operation('B.__eq__') return NotImplemented def __le__(self, other): self.log_operation('B.__le__') return NotImplemented def __ge__(self, other): self.log_operation('B.__ge__') return NotImplemented class C(B): def __eq__(self, other): self.log_operation('C.__eq__') return NotImplemented def __le__(self, other): self.log_operation('C.__le__') return NotImplemented def __ge__(self, other): self.log_operation('C.__ge__') return NotImplemented class V(OperationLogger): """Virtual subclass of B""" def __eq__(self, other): self.log_operation('V.__eq__') return NotImplemented def __le__(self, other): self.log_operation('V.__le__') return NotImplemented def __ge__(self, other): self.log_operation('V.__ge__') return NotImplemented B.register(V) class OperationOrderTests(unittest.TestCase): def test_comparison_orders(self): self.assertEqual(op_sequence(eq, A, A), ['A.__eq__', 'A.__eq__']) self.assertEqual(op_sequence(eq, A, B), ['A.__eq__', 'B.__eq__']) self.assertEqual(op_sequence(eq, B, A), ['B.__eq__', 'A.__eq__']) # C is a subclass of B, so C.__eq__ is called first self.assertEqual(op_sequence(eq, B, C), ['C.__eq__', 'B.__eq__']) self.assertEqual(op_sequence(eq, C, B), ['C.__eq__', 'B.__eq__']) self.assertEqual(op_sequence(le, A, A), ['A.__le__', 'A.__ge__']) self.assertEqual(op_sequence(le, A, B), ['A.__le__', 'B.__ge__']) self.assertEqual(op_sequence(le, B, A), ['B.__le__', 'A.__ge__']) self.assertEqual(op_sequence(le, B, C), ['C.__ge__', 'B.__le__']) self.assertEqual(op_sequence(le, C, B), ['C.__le__', 'B.__ge__']) self.assertTrue(issubclass(V, B)) self.assertEqual(op_sequence(eq, B, V), ['B.__eq__', 'V.__eq__']) self.assertEqual(op_sequence(le, B, V), ['B.__le__', 'V.__ge__']) class SupEq(object): """Class that can test equality""" def __eq__(self, other): return True class S(SupEq): """Subclass of SupEq that should fail""" __eq__ = None class F(object): """Independent class that should fall back""" class X(object): """Independent class that should fail""" __eq__ = None class SN(SupEq): """Subclass of SupEq that can test equality, but not non-equality""" __ne__ = None class XN: """Independent class that can test equality, but not non-equality""" def __eq__(self, other): return True __ne__ = None class FallbackBlockingTests(unittest.TestCase): """Unit tests for None method blocking""" def test_fallback_rmethod_blocking(self): e, f, s, x = SupEq(), F(), S(), X() self.assertEqual(e, e) self.assertEqual(e, f) self.assertEqual(f, e) # left operand is checked first self.assertEqual(e, x) self.assertRaises(TypeError, eq, x, e) # S is a subclass, so it's always checked first self.assertRaises(TypeError, eq, e, s) self.assertRaises(TypeError, eq, s, e) def test_fallback_ne_blocking(self): e, sn, xn = SupEq(), SN(), XN() self.assertFalse(e != e) self.assertRaises(TypeError, ne, e, sn) self.assertRaises(TypeError, ne, sn, e) self.assertFalse(e != xn) self.assertRaises(TypeError, ne, xn, 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/test_bool.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bool.py
# Test properties of bool promised by PEP 285 import unittest from test import support import os class BoolTest(unittest.TestCase): def test_subclass(self): try: class C(bool): pass except TypeError: pass else: self.fail("bool should not be subclassable") self.assertRaises(TypeError, int.__new__, bool, 0) def test_print(self): try: fo = open(support.TESTFN, "w") print(False, True, file=fo) fo.close() fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), 'False True\n') finally: fo.close() os.remove(support.TESTFN) def test_repr(self): self.assertEqual(repr(False), 'False') self.assertEqual(repr(True), 'True') self.assertEqual(eval(repr(False)), False) self.assertEqual(eval(repr(True)), True) def test_str(self): self.assertEqual(str(False), 'False') self.assertEqual(str(True), 'True') def test_int(self): self.assertEqual(int(False), 0) self.assertIsNot(int(False), False) self.assertEqual(int(True), 1) self.assertIsNot(int(True), True) def test_float(self): self.assertEqual(float(False), 0.0) self.assertIsNot(float(False), False) self.assertEqual(float(True), 1.0) self.assertIsNot(float(True), True) def test_math(self): self.assertEqual(+False, 0) self.assertIsNot(+False, False) self.assertEqual(-False, 0) self.assertIsNot(-False, False) self.assertEqual(abs(False), 0) self.assertIsNot(abs(False), False) self.assertEqual(+True, 1) self.assertIsNot(+True, True) self.assertEqual(-True, -1) self.assertEqual(abs(True), 1) self.assertIsNot(abs(True), True) self.assertEqual(~False, -1) self.assertEqual(~True, -2) self.assertEqual(False+2, 2) self.assertEqual(True+2, 3) self.assertEqual(2+False, 2) self.assertEqual(2+True, 3) self.assertEqual(False+False, 0) self.assertIsNot(False+False, False) self.assertEqual(False+True, 1) self.assertIsNot(False+True, True) self.assertEqual(True+False, 1) self.assertIsNot(True+False, True) self.assertEqual(True+True, 2) self.assertEqual(True-True, 0) self.assertIsNot(True-True, False) self.assertEqual(False-False, 0) self.assertIsNot(False-False, False) self.assertEqual(True-False, 1) self.assertIsNot(True-False, True) self.assertEqual(False-True, -1) self.assertEqual(True*1, 1) self.assertEqual(False*1, 0) self.assertIsNot(False*1, False) self.assertEqual(True/1, 1) self.assertIsNot(True/1, True) self.assertEqual(False/1, 0) self.assertIsNot(False/1, False) self.assertEqual(True%1, 0) self.assertIsNot(True%1, False) self.assertEqual(True%2, 1) self.assertIsNot(True%2, True) self.assertEqual(False%1, 0) self.assertIsNot(False%1, False) for b in False, True: for i in 0, 1, 2: self.assertEqual(b**i, int(b)**i) self.assertIsNot(b**i, bool(int(b)**i)) for a in False, True: for b in False, True: self.assertIs(a&b, bool(int(a)&int(b))) self.assertIs(a|b, bool(int(a)|int(b))) self.assertIs(a^b, bool(int(a)^int(b))) self.assertEqual(a&int(b), int(a)&int(b)) self.assertIsNot(a&int(b), bool(int(a)&int(b))) self.assertEqual(a|int(b), int(a)|int(b)) self.assertIsNot(a|int(b), bool(int(a)|int(b))) self.assertEqual(a^int(b), int(a)^int(b)) self.assertIsNot(a^int(b), bool(int(a)^int(b))) self.assertEqual(int(a)&b, int(a)&int(b)) self.assertIsNot(int(a)&b, bool(int(a)&int(b))) self.assertEqual(int(a)|b, int(a)|int(b)) self.assertIsNot(int(a)|b, bool(int(a)|int(b))) self.assertEqual(int(a)^b, int(a)^int(b)) self.assertIsNot(int(a)^b, bool(int(a)^int(b))) self.assertIs(1==1, True) self.assertIs(1==0, False) self.assertIs(0<1, True) self.assertIs(1<0, False) self.assertIs(0<=0, True) self.assertIs(1<=0, False) self.assertIs(1>0, True) self.assertIs(1>1, False) self.assertIs(1>=1, True) self.assertIs(0>=1, False) self.assertIs(0!=1, True) self.assertIs(0!=0, False) x = [1] self.assertIs(x is x, True) self.assertIs(x is not x, False) self.assertIs(1 in x, True) self.assertIs(0 in x, False) self.assertIs(1 not in x, False) self.assertIs(0 not in x, True) x = {1: 2} self.assertIs(x is x, True) self.assertIs(x is not x, False) self.assertIs(1 in x, True) self.assertIs(0 in x, False) self.assertIs(1 not in x, False) self.assertIs(0 not in x, True) self.assertIs(not True, False) self.assertIs(not False, True) def test_convert(self): self.assertRaises(TypeError, bool, 42, 42) self.assertIs(bool(10), True) self.assertIs(bool(1), True) self.assertIs(bool(-1), True) self.assertIs(bool(0), False) self.assertIs(bool("hello"), True) self.assertIs(bool(""), False) self.assertIs(bool(), False) def test_keyword_args(self): with self.assertRaisesRegex(TypeError, 'keyword argument'): bool(x=10) def test_format(self): self.assertEqual("%d" % False, "0") self.assertEqual("%d" % True, "1") self.assertEqual("%x" % False, "0") self.assertEqual("%x" % True, "1") def test_hasattr(self): self.assertIs(hasattr([], "append"), True) self.assertIs(hasattr([], "wobble"), False) def test_callable(self): self.assertIs(callable(len), True) self.assertIs(callable(1), False) def test_isinstance(self): self.assertIs(isinstance(True, bool), True) self.assertIs(isinstance(False, bool), True) self.assertIs(isinstance(True, int), True) self.assertIs(isinstance(False, int), True) self.assertIs(isinstance(1, bool), False) self.assertIs(isinstance(0, bool), False) def test_issubclass(self): self.assertIs(issubclass(bool, int), True) self.assertIs(issubclass(int, bool), False) def test_contains(self): self.assertIs(1 in {}, False) self.assertIs(1 in {1:1}, True) def test_string(self): self.assertIs("xyz".endswith("z"), True) self.assertIs("xyz".endswith("x"), False) self.assertIs("xyz0123".isalnum(), True) self.assertIs("@#$%".isalnum(), False) self.assertIs("xyz".isalpha(), True) self.assertIs("@#$%".isalpha(), False) self.assertIs("0123".isdigit(), True) self.assertIs("xyz".isdigit(), False) self.assertIs("xyz".islower(), True) self.assertIs("XYZ".islower(), False) self.assertIs("0123".isdecimal(), True) self.assertIs("xyz".isdecimal(), False) self.assertIs("0123".isnumeric(), True) self.assertIs("xyz".isnumeric(), False) self.assertIs(" ".isspace(), True) self.assertIs("\xa0".isspace(), True) self.assertIs("\u3000".isspace(), True) self.assertIs("XYZ".isspace(), False) self.assertIs("X".istitle(), True) self.assertIs("x".istitle(), False) self.assertIs("XYZ".isupper(), True) self.assertIs("xyz".isupper(), False) self.assertIs("xyz".startswith("x"), True) self.assertIs("xyz".startswith("z"), False) def test_boolean(self): self.assertEqual(True & 1, 1) self.assertNotIsInstance(True & 1, bool) self.assertIs(True & True, True) self.assertEqual(True | 1, 1) self.assertNotIsInstance(True | 1, bool) self.assertIs(True | True, True) self.assertEqual(True ^ 1, 0) self.assertNotIsInstance(True ^ 1, bool) self.assertIs(True ^ True, False) def test_fileclosed(self): try: f = open(support.TESTFN, "w") self.assertIs(f.closed, False) f.close() self.assertIs(f.closed, True) finally: os.remove(support.TESTFN) def test_types(self): # types are always true. for t in [bool, complex, dict, float, int, list, object, set, str, tuple, type]: self.assertIs(bool(t), True) def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True) def test_marshal(self): import marshal self.assertIs(marshal.loads(marshal.dumps(True)), True) self.assertIs(marshal.loads(marshal.dumps(False)), False) def test_pickle(self): import pickle for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.assertIs(pickle.loads(pickle.dumps(True, proto)), True) self.assertIs(pickle.loads(pickle.dumps(False, proto)), False) def test_picklevalues(self): # Test for specific backwards-compatible pickle values import pickle self.assertEqual(pickle.dumps(True, protocol=0), b"I01\n.") self.assertEqual(pickle.dumps(False, protocol=0), b"I00\n.") self.assertEqual(pickle.dumps(True, protocol=1), b"I01\n.") self.assertEqual(pickle.dumps(False, protocol=1), b"I00\n.") self.assertEqual(pickle.dumps(True, protocol=2), b'\x80\x02\x88.') self.assertEqual(pickle.dumps(False, protocol=2), b'\x80\x02\x89.') def test_convert_to_bool(self): # Verify that TypeError occurs when bad things are returned # from __bool__(). This isn't really a bool test, but # it's related. check = lambda o: self.assertRaises(TypeError, bool, o) class Foo(object): def __bool__(self): return self check(Foo()) class Bar(object): def __bool__(self): return "Yes" check(Bar()) class Baz(int): def __bool__(self): return self check(Baz()) # __bool__() must return a bool not an int class Spam(int): def __bool__(self): return 1 check(Spam()) class Eggs: def __len__(self): return -1 self.assertRaises(ValueError, bool, Eggs()) def test_from_bytes(self): self.assertIs(bool.from_bytes(b'\x00'*8, 'big'), False) self.assertIs(bool.from_bytes(b'abcd', 'little'), True) def test_sane_len(self): # this test just tests our assumptions about __len__ # this will start failing if __len__ changes assertions for badval in ['illegal', -1, 1 << 32]: class A: def __len__(self): return badval try: bool(A()) except (Exception) as e_bool: try: len(A()) except (Exception) as e_len: self.assertEqual(str(e_bool), str(e_len)) def test_blocked(self): class A: __bool__ = None self.assertRaises(TypeError, bool, A()) class B: def __len__(self): return 10 __bool__ = None self.assertRaises(TypeError, bool, B()) def test_real_and_imag(self): self.assertEqual(True.real, 1) self.assertEqual(True.imag, 0) self.assertIs(type(True.real), int) self.assertIs(type(True.imag), int) self.assertEqual(False.real, 0) self.assertEqual(False.imag, 0) self.assertIs(type(False.real), int) self.assertIs(type(False.imag), int) def test_main(): support.run_unittest(BoolTest) 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_scope.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_scope.py
import unittest import weakref from test.support import check_syntax_error, cpython_only class ScopeTests(unittest.TestCase): def testSimpleNesting(self): def make_adder(x): def adder(y): return x + y return adder inc = make_adder(1) plus10 = make_adder(10) self.assertEqual(inc(1), 2) self.assertEqual(plus10(-2), 8) def testExtraNesting(self): def make_adder2(x): def extra(): # check freevars passing through non-use scopes def adder(y): return x + y return adder return extra() inc = make_adder2(1) plus10 = make_adder2(10) self.assertEqual(inc(1), 2) self.assertEqual(plus10(-2), 8) def testSimpleAndRebinding(self): def make_adder3(x): def adder(y): return x + y x = x + 1 # check tracking of assignment to x in defining scope return adder inc = make_adder3(0) plus10 = make_adder3(9) self.assertEqual(inc(1), 2) self.assertEqual(plus10(-2), 8) def testNestingGlobalNoFree(self): def make_adder4(): # XXX add exta level of indirection def nest(): def nest(): def adder(y): return global_x + y # check that plain old globals work return adder return nest() return nest() global_x = 1 adder = make_adder4() self.assertEqual(adder(1), 2) global_x = 10 self.assertEqual(adder(-2), 8) def testNestingThroughClass(self): def make_adder5(x): class Adder: def __call__(self, y): return x + y return Adder() inc = make_adder5(1) plus10 = make_adder5(10) self.assertEqual(inc(1), 2) self.assertEqual(plus10(-2), 8) def testNestingPlusFreeRefToGlobal(self): def make_adder6(x): global global_nest_x def adder(y): return global_nest_x + y global_nest_x = x return adder inc = make_adder6(1) plus10 = make_adder6(10) self.assertEqual(inc(1), 11) # there's only one global self.assertEqual(plus10(-2), 8) def testNearestEnclosingScope(self): def f(x): def g(y): x = 42 # check that this masks binding in f() def h(z): return x + z return h return g(2) test_func = f(10) self.assertEqual(test_func(5), 47) def testMixedFreevarsAndCellvars(self): def identity(x): return x def f(x, y, z): def g(a, b, c): a = a + x # 3 def h(): # z * (4 + 9) # 3 * 13 return identity(z * (b + y)) y = c + z # 9 return h return g g = f(1, 2, 3) h = g(2, 4, 6) self.assertEqual(h(), 39) def testFreeVarInMethod(self): def test(): method_and_var = "var" class Test: def method_and_var(self): return "method" def test(self): return method_and_var def actual_global(self): return str("global") def str(self): return str(self) return Test() t = test() self.assertEqual(t.test(), "var") self.assertEqual(t.method_and_var(), "method") self.assertEqual(t.actual_global(), "global") method_and_var = "var" class Test: # this class is not nested, so the rules are different def method_and_var(self): return "method" def test(self): return method_and_var def actual_global(self): return str("global") def str(self): return str(self) t = Test() self.assertEqual(t.test(), "var") self.assertEqual(t.method_and_var(), "method") self.assertEqual(t.actual_global(), "global") def testCellIsKwonlyArg(self): # Issue 1409: Initialisation of a cell value, # when it comes from a keyword-only parameter def foo(*, a=17): def bar(): return a + 5 return bar() + 3 self.assertEqual(foo(a=42), 50) self.assertEqual(foo(), 25) def testRecursion(self): def f(x): def fact(n): if n == 0: return 1 else: return n * fact(n - 1) if x >= 0: return fact(x) else: raise ValueError("x must be >= 0") self.assertEqual(f(6), 720) def testUnoptimizedNamespaces(self): check_syntax_error(self, """if 1: def unoptimized_clash1(strip): def f(s): from sys import * return getrefcount(s) # ambiguity: free or local return f """) check_syntax_error(self, """if 1: def unoptimized_clash2(): from sys import * def f(s): return getrefcount(s) # ambiguity: global or local return f """) check_syntax_error(self, """if 1: def unoptimized_clash2(): from sys import * def g(): def f(s): return getrefcount(s) # ambiguity: global or local return f """) check_syntax_error(self, """if 1: def f(): def g(): from sys import * return getrefcount # global or local? """) def testLambdas(self): f1 = lambda x: lambda y: x + y inc = f1(1) plus10 = f1(10) self.assertEqual(inc(1), 2) self.assertEqual(plus10(5), 15) f2 = lambda x: (lambda : lambda y: x + y)() inc = f2(1) plus10 = f2(10) self.assertEqual(inc(1), 2) self.assertEqual(plus10(5), 15) f3 = lambda x: lambda y: global_x + y global_x = 1 inc = f3(None) self.assertEqual(inc(2), 3) f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) g = f8(1, 2, 3) h = g(2, 4, 6) self.assertEqual(h(), 18) def testUnboundLocal(self): def errorInOuter(): print(y) def inner(): return y y = 1 def errorInInner(): def inner(): return y inner() y = 1 self.assertRaises(UnboundLocalError, errorInOuter) self.assertRaises(NameError, errorInInner) def testUnboundLocal_AfterDel(self): # #4617: It is now legal to delete a cell variable. # The following functions must obviously compile, # and give the correct error when accessing the deleted name. def errorInOuter(): y = 1 del y print(y) def inner(): return y def errorInInner(): def inner(): return y y = 1 del y inner() self.assertRaises(UnboundLocalError, errorInOuter) self.assertRaises(NameError, errorInInner) def testUnboundLocal_AugAssign(self): # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation exec("""if 1: global_x = 1 def f(): global_x += 1 try: f() except UnboundLocalError: pass else: fail('scope of global_x not correctly determined') """, {'fail': self.fail}) def testComplexDefinitions(self): def makeReturner(*lst): def returner(): return lst return returner self.assertEqual(makeReturner(1,2,3)(), (1,2,3)) def makeReturner2(**kwargs): def returner(): return kwargs return returner self.assertEqual(makeReturner2(a=11)()['a'], 11) def testScopeOfGlobalStmt(self): # Examples posted by Samuele Pedroni to python-dev on 3/1/2001 exec("""if 1: # I x = 7 def f(): x = 1 def g(): global x def i(): def h(): return x return h() return i() return g() self.assertEqual(f(), 7) self.assertEqual(x, 7) # II x = 7 def f(): x = 1 def g(): x = 2 def i(): def h(): return x return h() return i() return g() self.assertEqual(f(), 2) self.assertEqual(x, 7) # III x = 7 def f(): x = 1 def g(): global x x = 2 def i(): def h(): return x return h() return i() return g() self.assertEqual(f(), 2) self.assertEqual(x, 2) # IV x = 7 def f(): x = 3 def g(): global x x = 2 def i(): def h(): return x return h() return i() return g() self.assertEqual(f(), 2) self.assertEqual(x, 2) # XXX what about global statements in class blocks? # do they affect methods? x = 12 class Global: global x x = 13 def set(self, val): x = val def get(self): return x g = Global() self.assertEqual(g.get(), 13) g.set(15) self.assertEqual(g.get(), 13) """) def testLeaks(self): class Foo: count = 0 def __init__(self): Foo.count += 1 def __del__(self): Foo.count -= 1 def f1(): x = Foo() def f2(): return x f2() for i in range(100): f1() self.assertEqual(Foo.count, 0) def testClassAndGlobal(self): exec("""if 1: def test(x): class Foo: global x def __call__(self, y): return x + y return Foo() x = 0 self.assertEqual(test(6)(2), 8) x = -1 self.assertEqual(test(3)(2), 5) looked_up_by_load_name = False class X: # Implicit globals inside classes are be looked up by LOAD_NAME, not # LOAD_GLOBAL. locals()['looked_up_by_load_name'] = True passed = looked_up_by_load_name self.assertTrue(X.passed) """) def testLocalsFunction(self): def f(x): def g(y): def h(z): return y + z w = x + y y += 3 return locals() return g d = f(2)(4) self.assertIn('h', d) del d['h'] self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) def testLocalsClass(self): # This test verifies that calling locals() does not pollute # the local namespace of the class with free variables. Old # versions of Python had a bug, where a free variable being # passed through a class namespace would be inserted into # locals() by locals() or exec or a trace function. # # The real bug lies in frame code that copies variables # between fast locals and the locals dict, e.g. when executing # a trace function. def f(x): class C: x = 12 def m(self): return x locals() return C self.assertEqual(f(1).x, 12) def f(x): class C: y = x def m(self): return x z = list(locals()) return C varnames = f(1).z self.assertNotIn("x", varnames) self.assertIn("y", varnames) @cpython_only def testLocalsClass_WithTrace(self): # Issue23728: after the trace function returns, the locals() # dictionary is used to update all variables, this used to # include free variables. But in class statements, free # variables are not inserted... import sys self.addCleanup(sys.settrace, sys.gettrace()) sys.settrace(lambda a,b,c:None) x = 12 class C: def f(self): return x self.assertEqual(x, 12) # Used to raise UnboundLocalError def testBoundAndFree(self): # var is bound and free in class def f(x): class C: def m(self): return x a = x return C inst = f(3)() self.assertEqual(inst.a, inst.m()) @cpython_only def testInteractionWithTraceFunc(self): import sys def tracer(a,b,c): return tracer def adaptgetter(name, klass, getter): kind, des = getter if kind == 1: # AV happens when stepping from this line to next if des == "": des = "_%s__%s" % (klass.__name__, name) return lambda obj: getattr(obj, des) class TestClass: pass self.addCleanup(sys.settrace, sys.gettrace()) sys.settrace(tracer) adaptgetter("foo", TestClass, (1, "")) sys.settrace(None) self.assertRaises(TypeError, sys.settrace) def testEvalExecFreeVars(self): def f(x): return lambda: x + 1 g = f(3) self.assertRaises(TypeError, eval, g.__code__) try: exec(g.__code__, {}) except TypeError: pass else: self.fail("exec should have failed, because code contained free vars") def testListCompLocalVars(self): try: print(bad) except NameError: pass else: print("bad should not be defined") def x(): [bad for s in 'a b' for bad in s.split()] x() try: print(bad) except NameError: pass def testEvalFreeVars(self): def f(x): def g(): x eval("x + 1") return g f(4)() def testFreeingCell(self): # Test what happens when a finalizer accesses # the cell where the object was stored. class Special: def __del__(self): nestedcell_get() def testNonLocalFunction(self): def f(x): def inc(): nonlocal x x += 1 return x def dec(): nonlocal x x -= 1 return x return inc, dec inc, dec = f(0) self.assertEqual(inc(), 1) self.assertEqual(inc(), 2) self.assertEqual(dec(), 1) self.assertEqual(dec(), 0) def testNonLocalMethod(self): def f(x): class c: def inc(self): nonlocal x x += 1 return x def dec(self): nonlocal x x -= 1 return x return c() c = f(0) self.assertEqual(c.inc(), 1) self.assertEqual(c.inc(), 2) self.assertEqual(c.dec(), 1) self.assertEqual(c.dec(), 0) def testGlobalInParallelNestedFunctions(self): # A symbol table bug leaked the global statement from one # function to other nested functions in the same block. # This test verifies that a global statement in the first # function does not affect the second function. local_ns = {} global_ns = {} exec("""if 1: def f(): y = 1 def g(): global y return y def h(): return y + 1 return g, h y = 9 g, h = f() result9 = g() result2 = h() """, local_ns, global_ns) self.assertEqual(2, global_ns["result2"]) self.assertEqual(9, global_ns["result9"]) def testNonLocalClass(self): def f(x): class c: nonlocal x x += 1 def get(self): return x return c() c = f(0) self.assertEqual(c.get(), 1) self.assertNotIn("x", c.__class__.__dict__) def testNonLocalGenerator(self): def f(x): def g(y): nonlocal x for i in range(y): x += 1 yield x return g g = f(0) self.assertEqual(list(g(5)), [1, 2, 3, 4, 5]) def testNestedNonLocal(self): def f(x): def g(): nonlocal x x -= 2 def h(): nonlocal x x += 4 return x return h return g g = f(1) h = g() self.assertEqual(h(), 3) def testTopIsNotSignificant(self): # See #9997. def top(a): pass def b(): global a def testClassNamespaceOverridesClosure(self): # See #17853. x = 42 class X: locals()["x"] = 43 y = x self.assertEqual(X.y, 43) class X: locals()["x"] = 43 del x self.assertFalse(hasattr(X, "x")) self.assertEqual(x, 42) @cpython_only def testCellLeak(self): # Issue 17927. # # The issue was that if self was part of a cycle involving the # frame of a method call, *and* the method contained a nested # function referencing self, thereby forcing 'self' into a # cell, setting self to None would not be enough to break the # frame -- the frame had another reference to the instance, # which could not be cleared by the code running in the frame # (though it will be cleared when the frame is collected). # Without the lambda, setting self to None is enough to break # the cycle. class Tester: def dig(self): if 0: lambda: self try: 1/0 except Exception as exc: self.exc = exc self = None # Break the cycle tester = Tester() tester.dig() ref = weakref.ref(tester) del tester self.assertIsNone(ref()) 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_variations.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exception_variations.py
import unittest class ExceptionTestCase(unittest.TestCase): def test_try_except_else_finally(self): hit_except = False hit_else = False hit_finally = False try: raise Exception('nyaa!') except: hit_except = True else: hit_else = True finally: hit_finally = True self.assertTrue(hit_except) self.assertTrue(hit_finally) self.assertFalse(hit_else) def test_try_except_else_finally_no_exception(self): hit_except = False hit_else = False hit_finally = False try: pass except: hit_except = True else: hit_else = True finally: hit_finally = True self.assertFalse(hit_except) self.assertTrue(hit_finally) self.assertTrue(hit_else) def test_try_except_finally(self): hit_except = False hit_finally = False try: raise Exception('yarr!') except: hit_except = True finally: hit_finally = True self.assertTrue(hit_except) self.assertTrue(hit_finally) def test_try_except_finally_no_exception(self): hit_except = False hit_finally = False try: pass except: hit_except = True finally: hit_finally = True self.assertFalse(hit_except) self.assertTrue(hit_finally) def test_try_except(self): hit_except = False try: raise Exception('ahoy!') except: hit_except = True self.assertTrue(hit_except) def test_try_except_no_exception(self): hit_except = False try: pass except: hit_except = True self.assertFalse(hit_except) def test_try_except_else(self): hit_except = False hit_else = False try: raise Exception('foo!') except: hit_except = True else: hit_else = True self.assertFalse(hit_else) self.assertTrue(hit_except) def test_try_except_else_no_exception(self): hit_except = False hit_else = False try: pass except: hit_except = True else: hit_else = True self.assertFalse(hit_except) self.assertTrue(hit_else) def test_try_finally_no_exception(self): hit_finally = False try: pass finally: hit_finally = True self.assertTrue(hit_finally) def test_nested(self): hit_finally = False hit_inner_except = False hit_inner_finally = False try: try: raise Exception('inner exception') except: hit_inner_except = True finally: hit_inner_finally = True finally: hit_finally = True self.assertTrue(hit_inner_except) self.assertTrue(hit_inner_finally) self.assertTrue(hit_finally) def test_nested_else(self): hit_else = False hit_finally = False hit_except = False hit_inner_except = False hit_inner_else = False try: try: pass except: hit_inner_except = True else: hit_inner_else = True raise Exception('outer exception') except: hit_except = True else: hit_else = True finally: hit_finally = True self.assertFalse(hit_inner_except) self.assertTrue(hit_inner_else) self.assertFalse(hit_else) self.assertTrue(hit_finally) self.assertTrue(hit_except) 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_list.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_list.py
import sys from test import list_tests import pickle import unittest class ListTest(list_tests.CommonTest): type2test = list def test_basic(self): self.assertEqual(list([]), []) l0_3 = [0, 1, 2, 3] l0_3_bis = list(l0_3) self.assertEqual(l0_3, l0_3_bis) self.assertTrue(l0_3 is not l0_3_bis) self.assertEqual(list(()), []) self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) self.assertEqual(list(''), []) self.assertEqual(list('spam'), ['s', 'p', 'a', 'm']) self.assertEqual(list(x for x in range(10) if x % 2), [1, 3, 5, 7, 9]) if sys.maxsize == 0x7fffffff: # This test can currently only work on 32-bit machines. # XXX If/when PySequence_Length() returns a ssize_t, it should be # XXX re-enabled. # Verify clearing of bug #556025. # This assumes that the max data size (sys.maxint) == max # address size this also assumes that the address size is at # least 4 bytes with 8 byte addresses, the bug is not well # tested # # Note: This test is expected to SEGV under Cygwin 1.3.12 or # earlier due to a newlib bug. See the following mailing list # thread for the details: # http://sources.redhat.com/ml/newlib/2002/msg00369.html self.assertRaises(MemoryError, list, range(sys.maxsize // 2)) # This code used to segfault in Py2.4a3 x = [] x.extend(-y for y in x) self.assertEqual(x, []) def test_keyword_args(self): with self.assertRaisesRegex(TypeError, 'keyword argument'): list(sequence=[]) def test_truth(self): super().test_truth() self.assertTrue(not []) self.assertTrue([42]) def test_identity(self): self.assertTrue([] is not []) def test_len(self): super().test_len() self.assertEqual(len([]), 0) self.assertEqual(len([0]), 1) self.assertEqual(len([0, 1, 2]), 3) def test_overflow(self): lst = [4, 5, 6, 7] n = int((sys.maxsize*2+2) // len(lst)) def mul(a, b): return a * b def imul(a, b): a *= b self.assertRaises((MemoryError, OverflowError), mul, lst, n) self.assertRaises((MemoryError, OverflowError), imul, lst, n) def test_repr_large(self): # Check the repr of large list objects def check(n): l = [0] * n s = repr(l) self.assertEqual(s, '[' + ', '.join(['0'] * n) + ']') check(10) # check our checking code check(1000000) def test_iterator_pickle(self): orig = self.type2test([4, 5, 6, 7]) data = [10, 11, 12, 13, 14, 15] for proto in range(pickle.HIGHEST_PROTOCOL + 1): # initial iterator itorig = iter(orig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data) # running iterator next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data[1:]) # empty iterator for i in range(1, len(orig)): next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data[len(orig):]) # exhausted iterator self.assertRaises(StopIteration, next, itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(list(it), []) def test_reversed_pickle(self): orig = self.type2test([4, 5, 6, 7]) data = [10, 11, 12, 13, 14, 15] for proto in range(pickle.HIGHEST_PROTOCOL + 1): # initial iterator itorig = reversed(orig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data[len(orig)-1::-1]) # running iterator next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), data[len(orig)-2::-1]) # empty iterator for i in range(1, len(orig)): next(itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(type(it), type(itorig)) self.assertEqual(list(it), []) # exhausted iterator self.assertRaises(StopIteration, next, itorig) d = pickle.dumps((itorig, orig), proto) it, a = pickle.loads(d) a[:] = data self.assertEqual(list(it), []) def test_step_overflow(self): a = [0, 1, 2, 3, 4] a[1::sys.maxsize] = [0] self.assertEqual(a[3::sys.maxsize], [3]) def test_no_comdat_folding(self): # Issue 8847: In the PGO build, the MSVC linker's COMDAT folding # optimization causes failures in code that relies on distinct # function addresses. class L(list): pass with self.assertRaises(TypeError): (3,) + L([1,2]) def test_equal_operator_modifying_operand(self): # test fix for seg fault reported in bpo-38588 part 2. class X: def __eq__(self,other) : list2.clear() return NotImplemented class Y: def __eq__(self, other): list1.clear() return NotImplemented class Z: def __eq__(self, other): list3.clear() return NotImplemented list1 = [X()] list2 = [Y()] self.assertTrue(list1 == list2) list3 = [Z()] list4 = [1] self.assertFalse(list3 == list4) def test_count_index_remove_crashes(self): # bpo-38610: The count(), index(), and remove() methods were not # holding strong references to list elements while calling # PyObject_RichCompareBool(). class X: def __eq__(self, other): lst.clear() return NotImplemented lst = [X()] with self.assertRaises(ValueError): lst.index(lst) class L(list): def __eq__(self, other): str(other) return NotImplemented lst = L([X()]) lst.count(lst) lst = L([X()]) with self.assertRaises(ValueError): lst.remove(lst) # bpo-39453: list.__contains__ was not holding strong references # to list elements while calling PyObject_RichCompareBool(). lst = [X(), X()] 3 in lst lst = [X(), X()] X() in lst 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_argparse.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_argparse.py
# Author: Steven J. Bethard <steven.bethard@gmail.com>. import codecs import inspect import os import shutil import stat import sys import textwrap import tempfile import unittest import argparse from io import StringIO from test import support from unittest import mock class StdIOBuffer(StringIO): pass class TestCase(unittest.TestCase): def setUp(self): # The tests assume that line wrapping occurs at 80 columns, but this # behaviour can be overridden by setting the COLUMNS environment # variable. To ensure that this assumption is true, unset COLUMNS. env = support.EnvironmentVarGuard() env.unset("COLUMNS") self.addCleanup(env.__exit__) class TempDirMixin(object): def setUp(self): self.temp_dir = tempfile.mkdtemp() self.old_dir = os.getcwd() os.chdir(self.temp_dir) def tearDown(self): os.chdir(self.old_dir) for root, dirs, files in os.walk(self.temp_dir, topdown=False): for name in files: os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE) shutil.rmtree(self.temp_dir, True) def create_readonly_file(self, filename): file_path = os.path.join(self.temp_dir, filename) with open(file_path, 'w') as file: file.write(filename) os.chmod(file_path, stat.S_IREAD) class Sig(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class NS(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __repr__(self): sorted_items = sorted(self.__dict__.items()) kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items]) return '%s(%s)' % (type(self).__name__, kwarg_str) def __eq__(self, other): return vars(self) == vars(other) class ArgumentParserError(Exception): def __init__(self, message, stdout=None, stderr=None, error_code=None): Exception.__init__(self, message, stdout, stderr) self.message = message self.stdout = stdout self.stderr = stderr self.error_code = error_code def stderr_to_parser_error(parse_args, *args, **kwargs): # if this is being called recursively and stderr or stdout is already being # redirected, simply call the function and let the enclosing function # catch the exception if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer): return parse_args(*args, **kwargs) # if this is not being called recursively, redirect stderr and # use it as the ArgumentParserError message old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = StdIOBuffer() sys.stderr = StdIOBuffer() try: try: result = parse_args(*args, **kwargs) for key in list(vars(result)): if getattr(result, key) is sys.stdout: setattr(result, key, old_stdout) if getattr(result, key) is sys.stderr: setattr(result, key, old_stderr) return result except SystemExit: code = sys.exc_info()[1].code stdout = sys.stdout.getvalue() stderr = sys.stderr.getvalue() raise ArgumentParserError("SystemExit", stdout, stderr, code) finally: sys.stdout = old_stdout sys.stderr = old_stderr class ErrorRaisingArgumentParser(argparse.ArgumentParser): def parse_args(self, *args, **kwargs): parse_args = super(ErrorRaisingArgumentParser, self).parse_args return stderr_to_parser_error(parse_args, *args, **kwargs) def exit(self, *args, **kwargs): exit = super(ErrorRaisingArgumentParser, self).exit return stderr_to_parser_error(exit, *args, **kwargs) def error(self, *args, **kwargs): error = super(ErrorRaisingArgumentParser, self).error return stderr_to_parser_error(error, *args, **kwargs) class ParserTesterMetaclass(type): """Adds parser tests using the class attributes. Classes of this type should specify the following attributes: argument_signatures -- a list of Sig objects which specify the signatures of Argument objects to be created failures -- a list of args lists that should cause the parser to fail successes -- a list of (initial_args, options, remaining_args) tuples where initial_args specifies the string args to be parsed, options is a dict that should match the vars() of the options parsed out of initial_args, and remaining_args should be any remaining unparsed arguments """ def __init__(cls, name, bases, bodydict): if name == 'ParserTestCase': return # default parser signature is empty if not hasattr(cls, 'parser_signature'): cls.parser_signature = Sig() if not hasattr(cls, 'parser_class'): cls.parser_class = ErrorRaisingArgumentParser # --------------------------------------- # functions for adding optional arguments # --------------------------------------- def no_groups(parser, argument_signatures): """Add all arguments directly to the parser""" for sig in argument_signatures: parser.add_argument(*sig.args, **sig.kwargs) def one_group(parser, argument_signatures): """Add all arguments under a single group in the parser""" group = parser.add_argument_group('foo') for sig in argument_signatures: group.add_argument(*sig.args, **sig.kwargs) def many_groups(parser, argument_signatures): """Add each argument in its own group to the parser""" for i, sig in enumerate(argument_signatures): group = parser.add_argument_group('foo:%i' % i) group.add_argument(*sig.args, **sig.kwargs) # -------------------------- # functions for parsing args # -------------------------- def listargs(parser, args): """Parse the args by passing in a list""" return parser.parse_args(args) def sysargs(parser, args): """Parse the args by defaulting to sys.argv""" old_sys_argv = sys.argv sys.argv = [old_sys_argv[0]] + args try: return parser.parse_args() finally: sys.argv = old_sys_argv # class that holds the combination of one optional argument # addition method and one arg parsing method class AddTests(object): def __init__(self, tester_cls, add_arguments, parse_args): self._add_arguments = add_arguments self._parse_args = parse_args add_arguments_name = self._add_arguments.__name__ parse_args_name = self._parse_args.__name__ for test_func in [self.test_failures, self.test_successes]: func_name = test_func.__name__ names = func_name, add_arguments_name, parse_args_name test_name = '_'.join(names) def wrapper(self, test_func=test_func): test_func(self) try: wrapper.__name__ = test_name except TypeError: pass setattr(tester_cls, test_name, wrapper) def _get_parser(self, tester): args = tester.parser_signature.args kwargs = tester.parser_signature.kwargs parser = tester.parser_class(*args, **kwargs) self._add_arguments(parser, tester.argument_signatures) return parser def test_failures(self, tester): parser = self._get_parser(tester) for args_str in tester.failures: args = args_str.split() with tester.assertRaises(ArgumentParserError, msg=args): parser.parse_args(args) def test_successes(self, tester): parser = self._get_parser(tester) for args, expected_ns in tester.successes: if isinstance(args, str): args = args.split() result_ns = self._parse_args(parser, args) tester.assertEqual(expected_ns, result_ns) # add tests for each combination of an optionals adding method # and an arg parsing method for add_arguments in [no_groups, one_group, many_groups]: for parse_args in [listargs, sysargs]: AddTests(cls, add_arguments, parse_args) bases = TestCase, ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {}) # =============== # Optionals tests # =============== class TestOptionalsSingleDash(ParserTestCase): """Test an Optional with a single-dash option string""" argument_signatures = [Sig('-x')] failures = ['-x', 'a', '--foo', '-x --foo', '-x -y'] successes = [ ('', NS(x=None)), ('-x a', NS(x='a')), ('-xa', NS(x='a')), ('-x -1', NS(x='-1')), ('-x-1', NS(x='-1')), ] class TestOptionalsSingleDashCombined(ParserTestCase): """Test an Optional with a single-dash option string""" argument_signatures = [ Sig('-x', action='store_true'), Sig('-yyy', action='store_const', const=42), Sig('-z'), ] failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x', '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza'] successes = [ ('', NS(x=False, yyy=None, z=None)), ('-x', NS(x=True, yyy=None, z=None)), ('-za', NS(x=False, yyy=None, z='a')), ('-z a', NS(x=False, yyy=None, z='a')), ('-xza', NS(x=True, yyy=None, z='a')), ('-xz a', NS(x=True, yyy=None, z='a')), ('-x -za', NS(x=True, yyy=None, z='a')), ('-x -z a', NS(x=True, yyy=None, z='a')), ('-y', NS(x=False, yyy=42, z=None)), ('-yyy', NS(x=False, yyy=42, z=None)), ('-x -yyy -za', NS(x=True, yyy=42, z='a')), ('-x -yyy -z a', NS(x=True, yyy=42, z='a')), ] class TestOptionalsSingleDashLong(ParserTestCase): """Test an Optional with a multi-character single-dash option string""" argument_signatures = [Sig('-foo')] failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa'] successes = [ ('', NS(foo=None)), ('-foo a', NS(foo='a')), ('-foo -1', NS(foo='-1')), ('-fo a', NS(foo='a')), ('-f a', NS(foo='a')), ] class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase): """Test Optionals where option strings are subsets of each other""" argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')] failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora'] successes = [ ('', NS(f=None, foobar=None, foorab=None)), ('-f a', NS(f='a', foobar=None, foorab=None)), ('-fa', NS(f='a', foobar=None, foorab=None)), ('-foa', NS(f='oa', foobar=None, foorab=None)), ('-fooa', NS(f='ooa', foobar=None, foorab=None)), ('-foobar a', NS(f=None, foobar='a', foorab=None)), ('-foorab a', NS(f=None, foobar=None, foorab='a')), ] class TestOptionalsSingleDashAmbiguous(ParserTestCase): """Test Optionals that partially match but are not subsets""" argument_signatures = [Sig('-foobar'), Sig('-foorab')] failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b'] successes = [ ('', NS(foobar=None, foorab=None)), ('-foob a', NS(foobar='a', foorab=None)), ('-foor a', NS(foobar=None, foorab='a')), ('-fooba a', NS(foobar='a', foorab=None)), ('-foora a', NS(foobar=None, foorab='a')), ('-foobar a', NS(foobar='a', foorab=None)), ('-foorab a', NS(foobar=None, foorab='a')), ] class TestOptionalsNumeric(ParserTestCase): """Test an Optional with a short opt string""" argument_signatures = [Sig('-1', dest='one')] failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2'] successes = [ ('', NS(one=None)), ('-1 a', NS(one='a')), ('-1a', NS(one='a')), ('-1-2', NS(one='-2')), ] class TestOptionalsDoubleDash(ParserTestCase): """Test an Optional with a double-dash option string""" argument_signatures = [Sig('--foo')] failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar'] successes = [ ('', NS(foo=None)), ('--foo a', NS(foo='a')), ('--foo=a', NS(foo='a')), ('--foo -2.5', NS(foo='-2.5')), ('--foo=-2.5', NS(foo='-2.5')), ] class TestOptionalsDoubleDashPartialMatch(ParserTestCase): """Tests partial matching with a double-dash option string""" argument_signatures = [ Sig('--badger', action='store_true'), Sig('--bat'), ] failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5'] successes = [ ('', NS(badger=False, bat=None)), ('--bat X', NS(badger=False, bat='X')), ('--bad', NS(badger=True, bat=None)), ('--badg', NS(badger=True, bat=None)), ('--badge', NS(badger=True, bat=None)), ('--badger', NS(badger=True, bat=None)), ] class TestOptionalsDoubleDashPrefixMatch(ParserTestCase): """Tests when one double-dash option string is a prefix of another""" argument_signatures = [ Sig('--badger', action='store_true'), Sig('--ba'), ] failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5'] successes = [ ('', NS(badger=False, ba=None)), ('--ba X', NS(badger=False, ba='X')), ('--ba=X', NS(badger=False, ba='X')), ('--bad', NS(badger=True, ba=None)), ('--badg', NS(badger=True, ba=None)), ('--badge', NS(badger=True, ba=None)), ('--badger', NS(badger=True, ba=None)), ] class TestOptionalsSingleDoubleDash(ParserTestCase): """Test an Optional with single- and double-dash option strings""" argument_signatures = [ Sig('-f', action='store_true'), Sig('--bar'), Sig('-baz', action='store_const', const=42), ] failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B'] successes = [ ('', NS(f=False, bar=None, baz=None)), ('-f', NS(f=True, bar=None, baz=None)), ('--ba B', NS(f=False, bar='B', baz=None)), ('-f --bar B', NS(f=True, bar='B', baz=None)), ('-f -b', NS(f=True, bar=None, baz=42)), ('-ba -f', NS(f=True, bar=None, baz=42)), ] class TestOptionalsAlternatePrefixChars(ParserTestCase): """Test an Optional with option strings with custom prefixes""" parser_signature = Sig(prefix_chars='+:/', add_help=False) argument_signatures = [ Sig('+f', action='store_true'), Sig('::bar'), Sig('/baz', action='store_const', const=42), ] failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help'] successes = [ ('', NS(f=False, bar=None, baz=None)), ('+f', NS(f=True, bar=None, baz=None)), ('::ba B', NS(f=False, bar='B', baz=None)), ('+f ::bar B', NS(f=True, bar='B', baz=None)), ('+f /b', NS(f=True, bar=None, baz=42)), ('/ba +f', NS(f=True, bar=None, baz=42)), ] class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase): """When ``-`` not in prefix_chars, default operators created for help should use the prefix_chars in use rather than - or -- http://bugs.python.org/issue9444""" parser_signature = Sig(prefix_chars='+:/', add_help=True) argument_signatures = [ Sig('+f', action='store_true'), Sig('::bar'), Sig('/baz', action='store_const', const=42), ] failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz'] successes = [ ('', NS(f=False, bar=None, baz=None)), ('+f', NS(f=True, bar=None, baz=None)), ('::ba B', NS(f=False, bar='B', baz=None)), ('+f ::bar B', NS(f=True, bar='B', baz=None)), ('+f /b', NS(f=True, bar=None, baz=42)), ('/ba +f', NS(f=True, bar=None, baz=42)) ] class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase): """Verify that Optionals must be called with their defined prefixes""" parser_signature = Sig(prefix_chars='+-', add_help=False) argument_signatures = [ Sig('-x', action='store_true'), Sig('+y', action='store_true'), Sig('+z', action='store_true'), ] failures = ['-w', '-xyz', '+x', '-y', '+xyz', ] successes = [ ('', NS(x=False, y=False, z=False)), ('-x', NS(x=True, y=False, z=False)), ('+y -x', NS(x=True, y=True, z=False)), ('+yz -x', NS(x=True, y=True, z=True)), ] class TestOptionalsShortLong(ParserTestCase): """Test a combination of single- and double-dash option strings""" argument_signatures = [ Sig('-v', '--verbose', '-n', '--noisy', action='store_true'), ] failures = ['--x --verbose', '-N', 'a', '-v x'] successes = [ ('', NS(verbose=False)), ('-v', NS(verbose=True)), ('--verbose', NS(verbose=True)), ('-n', NS(verbose=True)), ('--noisy', NS(verbose=True)), ] class TestOptionalsDest(ParserTestCase): """Tests various means of setting destination""" argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')] failures = ['a'] successes = [ ('--foo-bar f', NS(foo_bar='f', zabbaz=None)), ('--baz g', NS(foo_bar=None, zabbaz='g')), ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')), ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')), ] class TestOptionalsDefault(ParserTestCase): """Tests specifying a default for an Optional""" argument_signatures = [Sig('-x'), Sig('-y', default=42)] failures = ['a'] successes = [ ('', NS(x=None, y=42)), ('-xx', NS(x='x', y=42)), ('-yy', NS(x=None, y='y')), ] class TestOptionalsNargsDefault(ParserTestCase): """Tests not specifying the number of args for an Optional""" argument_signatures = [Sig('-x')] failures = ['a', '-x'] successes = [ ('', NS(x=None)), ('-x a', NS(x='a')), ] class TestOptionalsNargs1(ParserTestCase): """Tests specifying 1 arg for an Optional""" argument_signatures = [Sig('-x', nargs=1)] failures = ['a', '-x'] successes = [ ('', NS(x=None)), ('-x a', NS(x=['a'])), ] class TestOptionalsNargs3(ParserTestCase): """Tests specifying 3 args for an Optional""" argument_signatures = [Sig('-x', nargs=3)] failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b'] successes = [ ('', NS(x=None)), ('-x a b c', NS(x=['a', 'b', 'c'])), ] class TestOptionalsNargsOptional(ParserTestCase): """Tests specifying an Optional arg for an Optional""" argument_signatures = [ Sig('-w', nargs='?'), Sig('-x', nargs='?', const=42), Sig('-y', nargs='?', default='spam'), Sig('-z', nargs='?', type=int, const='42', default='84'), ] failures = ['2'] successes = [ ('', NS(w=None, x=None, y='spam', z=84)), ('-w', NS(w=None, x=None, y='spam', z=84)), ('-w 2', NS(w='2', x=None, y='spam', z=84)), ('-x', NS(w=None, x=42, y='spam', z=84)), ('-x 2', NS(w=None, x='2', y='spam', z=84)), ('-y', NS(w=None, x=None, y=None, z=84)), ('-y 2', NS(w=None, x=None, y='2', z=84)), ('-z', NS(w=None, x=None, y='spam', z=42)), ('-z 2', NS(w=None, x=None, y='spam', z=2)), ] class TestOptionalsNargsZeroOrMore(ParserTestCase): """Tests specifying args for an Optional that accepts zero or more""" argument_signatures = [ Sig('-x', nargs='*'), Sig('-y', nargs='*', default='spam'), ] failures = ['a'] successes = [ ('', NS(x=None, y='spam')), ('-x', NS(x=[], y='spam')), ('-x a', NS(x=['a'], y='spam')), ('-x a b', NS(x=['a', 'b'], y='spam')), ('-y', NS(x=None, y=[])), ('-y a', NS(x=None, y=['a'])), ('-y a b', NS(x=None, y=['a', 'b'])), ] class TestOptionalsNargsOneOrMore(ParserTestCase): """Tests specifying args for an Optional that accepts one or more""" argument_signatures = [ Sig('-x', nargs='+'), Sig('-y', nargs='+', default='spam'), ] failures = ['a', '-x', '-y', 'a -x', 'a -y b'] successes = [ ('', NS(x=None, y='spam')), ('-x a', NS(x=['a'], y='spam')), ('-x a b', NS(x=['a', 'b'], y='spam')), ('-y a', NS(x=None, y=['a'])), ('-y a b', NS(x=None, y=['a', 'b'])), ] class TestOptionalsChoices(ParserTestCase): """Tests specifying the choices for an Optional""" argument_signatures = [ Sig('-f', choices='abc'), Sig('-g', type=int, choices=range(5))] failures = ['a', '-f d', '-fad', '-ga', '-g 6'] successes = [ ('', NS(f=None, g=None)), ('-f a', NS(f='a', g=None)), ('-f c', NS(f='c', g=None)), ('-g 0', NS(f=None, g=0)), ('-g 03', NS(f=None, g=3)), ('-fb -g4', NS(f='b', g=4)), ] class TestOptionalsRequired(ParserTestCase): """Tests an optional action that is required""" argument_signatures = [ Sig('-x', type=int, required=True), ] failures = ['a', ''] successes = [ ('-x 1', NS(x=1)), ('-x42', NS(x=42)), ] class TestOptionalsActionStore(ParserTestCase): """Tests the store action for an Optional""" argument_signatures = [Sig('-x', action='store')] failures = ['a', 'a -x'] successes = [ ('', NS(x=None)), ('-xfoo', NS(x='foo')), ] class TestOptionalsActionStoreConst(ParserTestCase): """Tests the store_const action for an Optional""" argument_signatures = [Sig('-y', action='store_const', const=object)] failures = ['a'] successes = [ ('', NS(y=None)), ('-y', NS(y=object)), ] class TestOptionalsActionStoreFalse(ParserTestCase): """Tests the store_false action for an Optional""" argument_signatures = [Sig('-z', action='store_false')] failures = ['a', '-za', '-z a'] successes = [ ('', NS(z=True)), ('-z', NS(z=False)), ] class TestOptionalsActionStoreTrue(ParserTestCase): """Tests the store_true action for an Optional""" argument_signatures = [Sig('--apple', action='store_true')] failures = ['a', '--apple=b', '--apple b'] successes = [ ('', NS(apple=False)), ('--apple', NS(apple=True)), ] class TestOptionalsActionAppend(ParserTestCase): """Tests the append action for an Optional""" argument_signatures = [Sig('--baz', action='append')] failures = ['a', '--baz', 'a --baz', '--baz a b'] successes = [ ('', NS(baz=None)), ('--baz a', NS(baz=['a'])), ('--baz a --baz b', NS(baz=['a', 'b'])), ] class TestOptionalsActionAppendWithDefault(ParserTestCase): """Tests the append action for an Optional""" argument_signatures = [Sig('--baz', action='append', default=['X'])] failures = ['a', '--baz', 'a --baz', '--baz a b'] successes = [ ('', NS(baz=['X'])), ('--baz a', NS(baz=['X', 'a'])), ('--baz a --baz b', NS(baz=['X', 'a', 'b'])), ] class TestOptionalsActionAppendConst(ParserTestCase): """Tests the append_const action for an Optional""" argument_signatures = [ Sig('-b', action='append_const', const=Exception), Sig('-c', action='append', dest='b'), ] failures = ['a', '-c', 'a -c', '-bx', '-b x'] successes = [ ('', NS(b=None)), ('-b', NS(b=[Exception])), ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])), ] class TestOptionalsActionAppendConstWithDefault(ParserTestCase): """Tests the append_const action for an Optional""" argument_signatures = [ Sig('-b', action='append_const', const=Exception, default=['X']), Sig('-c', action='append', dest='b'), ] failures = ['a', '-c', 'a -c', '-bx', '-b x'] successes = [ ('', NS(b=['X'])), ('-b', NS(b=['X', Exception])), ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])), ] class TestOptionalsActionCount(ParserTestCase): """Tests the count action for an Optional""" argument_signatures = [Sig('-x', action='count')] failures = ['a', '-x a', '-x b', '-x a -x b'] successes = [ ('', NS(x=None)), ('-x', NS(x=1)), ] class TestOptionalsAllowLongAbbreviation(ParserTestCase): """Allow long options to be abbreviated unambiguously""" argument_signatures = [ Sig('--foo'), Sig('--foobaz'), Sig('--fooble', action='store_true'), ] failures = ['--foob 5', '--foob'] successes = [ ('', NS(foo=None, foobaz=None, fooble=False)), ('--foo 7', NS(foo='7', foobaz=None, fooble=False)), ('--fooba a', NS(foo=None, foobaz='a', fooble=False)), ('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)), ] class TestOptionalsDisallowLongAbbreviation(ParserTestCase): """Do not allow abbreviations of long options at all""" parser_signature = Sig(allow_abbrev=False) argument_signatures = [ Sig('--foo'), Sig('--foodle', action='store_true'), Sig('--foonly'), ] failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2'] successes = [ ('', NS(foo=None, foodle=False, foonly=None)), ('--foo 3', NS(foo='3', foodle=False, foonly=None)), ('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')), ] # ================ # Positional tests # ================ class TestPositionalsNargsNone(ParserTestCase): """Test a Positional that doesn't specify nargs""" argument_signatures = [Sig('foo')] failures = ['', '-x', 'a b'] successes = [ ('a', NS(foo='a')), ] class TestPositionalsNargs1(ParserTestCase): """Test a Positional that specifies an nargs of 1""" argument_signatures = [Sig('foo', nargs=1)] failures = ['', '-x', 'a b'] successes = [ ('a', NS(foo=['a'])), ] class TestPositionalsNargs2(ParserTestCase): """Test a Positional that specifies an nargs of 2""" argument_signatures = [Sig('foo', nargs=2)] failures = ['', 'a', '-x', 'a b c'] successes = [ ('a b', NS(foo=['a', 'b'])), ] class TestPositionalsNargsZeroOrMore(ParserTestCase): """Test a Positional that specifies unlimited nargs""" argument_signatures = [Sig('foo', nargs='*')] failures = ['-x'] successes = [ ('', NS(foo=[])), ('a', NS(foo=['a'])), ('a b', NS(foo=['a', 'b'])), ] class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase): """Test a Positional that specifies unlimited nargs and a default""" argument_signatures = [Sig('foo', nargs='*', default='bar')] failures = ['-x'] successes = [ ('', NS(foo='bar')), ('a', NS(foo=['a'])), ('a b', NS(foo=['a', 'b'])), ] class TestPositionalsNargsOneOrMore(ParserTestCase): """Test a Positional that specifies one or more nargs""" argument_signatures = [Sig('foo', nargs='+')] failures = ['', '-x'] successes = [ ('a', NS(foo=['a'])), ('a b', NS(foo=['a', 'b'])), ] class TestPositionalsNargsOptional(ParserTestCase): """Tests an Optional Positional""" argument_signatures = [Sig('foo', nargs='?')] failures = ['-x', 'a b'] successes = [ ('', NS(foo=None)), ('a', NS(foo='a')), ] class TestPositionalsNargsOptionalDefault(ParserTestCase): """Tests an Optional Positional with a default value""" argument_signatures = [Sig('foo', nargs='?', default=42)] failures = ['-x', 'a b'] successes = [ ('', NS(foo=42)), ('a', NS(foo='a')), ] class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase): """Tests an Optional Positional with a default value that needs to be converted to the appropriate type. """ argument_signatures = [ Sig('foo', nargs='?', type=int, default='42'), ] failures = ['-x', 'a b', '1 2'] successes = [ ('', NS(foo=42)), ('1', NS(foo=1)), ] class TestPositionalsNargsNoneNone(ParserTestCase): """Test two Positionals that don't specify nargs""" argument_signatures = [Sig('foo'), Sig('bar')] failures = ['', '-x', 'a', 'a b c'] successes = [ ('a b', NS(foo='a', bar='b')), ] class TestPositionalsNargsNone1(ParserTestCase): """Test a Positional with no nargs followed by one with 1""" argument_signatures = [Sig('foo'), Sig('bar', nargs=1)] failures = ['', '--foo', 'a', 'a b c'] successes = [ ('a b', NS(foo='a', bar=['b'])), ] class TestPositionalsNargs2None(ParserTestCase): """Test a Positional with 2 nargs followed by one with none""" argument_signatures = [Sig('foo', nargs=2), Sig('bar')] failures = ['', '--foo', 'a', 'a b', 'a b c d'] successes = [ ('a b c', NS(foo=['a', 'b'], bar='c')), ] class TestPositionalsNargsNoneZeroOrMore(ParserTestCase): """Test a Positional with no nargs followed by one with unlimited""" argument_signatures = [Sig('foo'), Sig('bar', nargs='*')] failures = ['', '--foo'] successes = [ ('a', NS(foo='a', bar=[])), ('a b', NS(foo='a', bar=['b'])), ('a b c', NS(foo='a', bar=['b', 'c'])), ] class TestPositionalsNargsNoneOneOrMore(ParserTestCase): """Test a Positional with no nargs followed by one with one or more""" argument_signatures = [Sig('foo'), Sig('bar', nargs='+')] failures = ['', '--foo', 'a'] successes = [ ('a b', NS(foo='a', bar=['b'])), ('a b c', NS(foo='a', bar=['b', 'c'])), ] class TestPositionalsNargsNoneOptional(ParserTestCase): """Test a Positional with no nargs followed by one with an Optional""" argument_signatures = [Sig('foo'), Sig('bar', nargs='?')] failures = ['', '--foo', 'a b c'] successes = [ ('a', NS(foo='a', bar=None)), ('a b', NS(foo='a', bar='b')), ] class TestPositionalsNargsZeroOrMoreNone(ParserTestCase): """Test a Positional with unlimited nargs followed by one with none""" argument_signatures = [Sig('foo', nargs='*'), Sig('bar')] failures = ['', '--foo'] successes = [ ('a', NS(foo=[], bar='a')), ('a b', NS(foo=['a'], bar='b')), ('a b c', NS(foo=['a', 'b'], bar='c')), ] class TestPositionalsNargsOneOrMoreNone(ParserTestCase): """Test a Positional with one or more nargs followed by one with none""" argument_signatures = [Sig('foo', nargs='+'), Sig('bar')] failures = ['', '--foo', 'a'] successes = [ ('a b', NS(foo=['a'], bar='b')), ('a b c', NS(foo=['a', 'b'], bar='c')), ] class TestPositionalsNargsOptionalNone(ParserTestCase): """Test a Positional with an Optional nargs followed by one with none""" argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')] failures = ['', '--foo', 'a b c'] successes = [ ('a', NS(foo=42, bar='a')), ('a b', NS(foo='a', bar='b')), ] class TestPositionalsNargs2ZeroOrMore(ParserTestCase): """Test a Positional with 2 nargs followed by one with unlimited""" argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')] failures = ['', '--foo', 'a'] successes = [ ('a b', NS(foo=['a', 'b'], bar=[])), ('a b c', NS(foo=['a', 'b'], bar=['c'])), ] class TestPositionalsNargs2OneOrMore(ParserTestCase): """Test a Positional with 2 nargs followed by one with one or more""" argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')] failures = ['', '--foo', 'a', 'a b'] successes = [ ('a b c', NS(foo=['a', 'b'], bar=['c'])), ] class TestPositionalsNargs2Optional(ParserTestCase): """Test a Positional with 2 nargs followed by one optional""" argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')] failures = ['', '--foo', 'a', 'a b c d'] successes = [ ('a b', NS(foo=['a', 'b'], bar=None)), ('a b c', NS(foo=['a', 'b'], bar='c')), ]
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_abc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_abc.py
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Note: each test is run with Python and C versions of ABCMeta. Except for # test_ABC_helper(), which assures that abc.ABC is an instance of abc.ABCMeta. """Unit tests for abc.py.""" import unittest import abc import _py_abc from inspect import isabstract def test_factory(abc_ABCMeta, abc_get_cache_token): class TestLegacyAPI(unittest.TestCase): def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C(metaclass=abc_ABCMeta): @abc.abstractproperty def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @property def foo(self): return super().foo self.assertEqual(D().foo, 3) self.assertFalse(getattr(D.foo, "__isabstractmethod__", False)) def test_abstractclassmethod_basics(self): @abc.abstractclassmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @abc.abstractclassmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @abc.abstractstaticmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @abc.abstractstaticmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) class TestABC(unittest.TestCase): def test_ABC_helper(self): # create an ABC using the helper class and perform basic checks class C(abc.ABC): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertEqual(type(C), abc.ABCMeta) self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') def test_abstractmethod_basics(self): @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) def test_abstractproperty_basics(self): @property @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @property @abc.abstractmethod def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertEqual(D().foo, 3) def test_abstractclassmethod_basics(self): @classmethod @abc.abstractmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @staticmethod @abc.abstractmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc_ABCMeta): @staticmethod @abc.abstractmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc_ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F)) def test_descriptors_with_abstractmethod(self): class C(metaclass=abc_ABCMeta): @property @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertEqual(E().foo, 3) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __bool__(self): raise ValueError() __len__ = __bool__ with self.assertRaises(ValueError): class F(C): def bar(self): pass bar.__isabstractmethod__ = NotBool() foo = property(bar) def test_customdescriptors_with_abstractmethod(self): class Descriptor: def __init__(self, fget, fset=None): self._fget = fget self._fset = fset def getter(self, callable): return Descriptor(callable, self._fget) def setter(self, callable): return Descriptor(self._fget, callable) @property def __isabstractmethod__(self): return (getattr(self._fget, '__isabstractmethod__', False) or getattr(self._fset, '__isabstractmethod__', False)) class C(metaclass=abc_ABCMeta): @Descriptor @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertFalse(E.foo.__isabstractmethod__) def test_metaclass_abc(self): # Metaclasses can be ABCs, too. class A(metaclass=abc_ABCMeta): @abc.abstractmethod def x(self): pass self.assertEqual(A.__abstractmethods__, {"x"}) class meta(type, A): def x(self): return 1 class C(metaclass=meta): pass def test_registration_basics(self): class A(metaclass=abc_ABCMeta): pass class B(object): pass b = B() self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) self.assertNotIsInstance(b, A) self.assertNotIsInstance(b, (A,)) B1 = A.register(B) self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) self.assertIs(B1, B) class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) def test_register_as_class_deco(self): class A(metaclass=abc_ABCMeta): pass @A.register class B(object): pass b = B() self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) @A.register class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) self.assertIs(C, A.register(C)) def test_isinstance_invalidation(self): class A(metaclass=abc_ABCMeta): pass class B: pass b = B() self.assertFalse(isinstance(b, A)) self.assertFalse(isinstance(b, (A,))) token_old = abc_get_cache_token() A.register(B) token_new = abc_get_cache_token() self.assertNotEqual(token_old, token_new) self.assertTrue(isinstance(b, A)) self.assertTrue(isinstance(b, (A,))) def test_registration_builtins(self): class A(metaclass=abc_ABCMeta): pass A.register(int) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) self.assertTrue(issubclass(int, A)) self.assertTrue(issubclass(int, (A,))) class B(A): pass B.register(str) class C(str): pass self.assertIsInstance("", A) self.assertIsInstance("", (A,)) self.assertTrue(issubclass(str, A)) self.assertTrue(issubclass(str, (A,))) self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) def test_registration_edge_cases(self): class A(metaclass=abc_ABCMeta): pass A.register(A) # should pass silently class A1(A): pass self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed class B(object): pass A1.register(B) # ok A1.register(B) # should pass silently class C(A): pass A.register(C) # should pass silently self.assertRaises(RuntimeError, C.register, A) # cycles not allowed C.register(B) # ok def test_register_non_class(self): class A(metaclass=abc_ABCMeta): pass self.assertRaisesRegex(TypeError, "Can only register classes", A.register, 4) def test_registration_transitiveness(self): class A(metaclass=abc_ABCMeta): pass self.assertTrue(issubclass(A, A)) self.assertTrue(issubclass(A, (A,))) class B(metaclass=abc_ABCMeta): pass self.assertFalse(issubclass(A, B)) self.assertFalse(issubclass(A, (B,))) self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) class C(metaclass=abc_ABCMeta): pass A.register(B) class B1(B): pass self.assertTrue(issubclass(B1, A)) self.assertTrue(issubclass(B1, (A,))) class C1(C): pass B1.register(C1) self.assertFalse(issubclass(C, B)) self.assertFalse(issubclass(C, (B,))) self.assertFalse(issubclass(C, B1)) self.assertFalse(issubclass(C, (B1,))) self.assertTrue(issubclass(C1, A)) self.assertTrue(issubclass(C1, (A,))) self.assertTrue(issubclass(C1, B)) self.assertTrue(issubclass(C1, (B,))) self.assertTrue(issubclass(C1, B1)) self.assertTrue(issubclass(C1, (B1,))) C1.register(int) class MyInt(int): pass self.assertTrue(issubclass(MyInt, A)) self.assertTrue(issubclass(MyInt, (A,))) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) def test_issubclass_bad_arguments(self): class A(metaclass=abc_ABCMeta): pass with self.assertRaises(TypeError): issubclass({}, A) # unhashable with self.assertRaises(TypeError): issubclass(42, A) # No __mro__ # Python version supports any iterable as __mro__. # But it's implementation detail and don't emulate it in C version. class C: __mro__ = 42 # __mro__ is not tuple with self.assertRaises(TypeError): issubclass(C(), A) # bpo-34441: Check that issubclass() doesn't crash on bogus # classes. bogus_subclasses = [ None, lambda x: [], lambda: 42, lambda: [42], ] for i, func in enumerate(bogus_subclasses): class S(metaclass=abc_ABCMeta): __subclasses__ = func with self.subTest(i=i): with self.assertRaises(TypeError): issubclass(int, S) # Also check that issubclass() propagates exceptions raised by # __subclasses__. exc_msg = "exception from __subclasses__" def raise_exc(): raise Exception(exc_msg) class S(metaclass=abc_ABCMeta): __subclasses__ = raise_exc with self.assertRaisesRegex(Exception, exc_msg): issubclass(int, S) def test_all_new_methods_are_called(self): class A(metaclass=abc_ABCMeta): pass class B(object): counter = 0 def __new__(cls): B.counter += 1 return super().__new__(cls) class C(A, B): pass self.assertEqual(B.counter, 0) C() self.assertEqual(B.counter, 1) def test_ABC_has___slots__(self): self.assertTrue(hasattr(abc.ABC, '__slots__')) def test_tricky_new_works(self): def with_metaclass(meta, *bases): class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) class A: ... class B: ... class C(with_metaclass(abc_ABCMeta, A, B)): pass self.assertEqual(C.__class__, abc_ABCMeta) class TestABCWithInitSubclass(unittest.TestCase): def test_works_with_init_subclass(self): class abc_ABC(metaclass=abc_ABCMeta): __slots__ = () saved_kwargs = {} class ReceivesClassKwargs: def __init_subclass__(cls, **kwargs): super().__init_subclass__() saved_kwargs.update(kwargs) class Receiver(ReceivesClassKwargs, abc_ABC, x=1, y=2, z=3): pass self.assertEqual(saved_kwargs, dict(x=1, y=2, z=3)) return TestLegacyAPI, TestABC, TestABCWithInitSubclass TestLegacyAPI_Py, TestABC_Py, TestABCWithInitSubclass_Py = test_factory(abc.ABCMeta, abc.get_cache_token) TestLegacyAPI_C, TestABC_C, TestABCWithInitSubclass_C = test_factory(_py_abc.ABCMeta, _py_abc.get_cache_token) 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_inspect.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py
import builtins import collections import datetime import functools import importlib import inspect import io import linecache import os from os.path import normcase import _pickle import pickle import shutil import sys import types import textwrap import unicodedata import unittest import unittest.mock import warnings try: from concurrent.futures import ThreadPoolExecutor except ImportError: ThreadPoolExecutor = None from test.support import run_unittest, TESTFN, DirsOnSysPath, cpython_only from test.support import MISSING_C_DOCSTRINGS, cpython_only from test.support.script_helper import assert_python_ok, assert_python_failure from test import inspect_fodder as mod from test import inspect_fodder2 as mod2 from test import support from test.test_import import _ready_to_import # Functions tested in this suite: # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, # isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers, # getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, # getclasstree, getargvalues, formatargspec, formatargvalues, # currentframe, stack, trace, isdatadescriptor # NOTE: There are some additional tests relating to interaction with # zipimport in the test_zipimport_support test module. modfile = mod.__file__ if modfile.endswith(('c', 'o')): modfile = modfile[:-1] # Normalize file names: on Windows, the case of file names of compiled # modules depends on the path used to start the python executable. modfile = normcase(modfile) def revise(filename, *args): return (normcase(filename),) + args git = mod.StupidGit() def signatures_with_lexicographic_keyword_only_parameters(): """ Yields a whole bunch of functions with only keyword-only parameters, where those parameters are always in lexicographically sorted order. """ parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z'] for i in range(1, 2**len(parameters)): p = [] bit = 1 for j in range(len(parameters)): if i & (bit << j): p.append(parameters[j]) fn_text = "def foo(*, " + ", ".join(p) + "): pass" symbols = {} exec(fn_text, symbols, symbols) yield symbols['foo'] def unsorted_keyword_only_parameters_fn(*, throw, out, the, baby, with_, the_, bathwater): pass unsorted_keyword_only_parameters = 'throw out the baby with_ the_ bathwater'.split() class IsTestBase(unittest.TestCase): predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, inspect.isframe, inspect.isfunction, inspect.ismethod, inspect.ismodule, inspect.istraceback, inspect.isgenerator, inspect.isgeneratorfunction, inspect.iscoroutine, inspect.iscoroutinefunction, inspect.isasyncgen, inspect.isasyncgenfunction]) def istest(self, predicate, exp): obj = eval(exp) self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) for other in self.predicates - set([predicate]): if (predicate == inspect.isgeneratorfunction or \ predicate == inspect.isasyncgenfunction or \ predicate == inspect.iscoroutinefunction) and \ other == inspect.isfunction: continue self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) def generator_function_example(self): for i in range(2): yield i async def async_generator_function_example(self): async for i in range(2): yield i async def coroutine_function_example(self): return 'spam' @types.coroutine def gen_coroutine_function_example(self): yield return 'spam' class EqualsToAll: def __eq__(self, other): return True class TestPredicates(IsTestBase): def test_excluding_predicates(self): global tb self.istest(inspect.isbuiltin, 'sys.exit') self.istest(inspect.isbuiltin, '[].append') self.istest(inspect.iscode, 'mod.spam.__code__') try: 1/0 except: tb = sys.exc_info()[2] self.istest(inspect.isframe, 'tb.tb_frame') self.istest(inspect.istraceback, 'tb') if hasattr(types, 'GetSetDescriptorType'): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') else: self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) finally: # Clear traceback and all the frames and local variables hanging to it. tb = None self.istest(inspect.isfunction, 'mod.spam') self.istest(inspect.isfunction, 'mod.StupidGit.abuse') self.istest(inspect.ismethod, 'git.argue') self.istest(inspect.ismodule, 'mod') self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory') self.istest(inspect.isgenerator, '(x for x in range(2))') self.istest(inspect.isgeneratorfunction, 'generator_function_example') self.istest(inspect.isasyncgen, 'async_generator_function_example(1)') self.istest(inspect.isasyncgenfunction, 'async_generator_function_example') with warnings.catch_warnings(): warnings.simplefilter("ignore") self.istest(inspect.iscoroutine, 'coroutine_function_example(1)') self.istest(inspect.iscoroutinefunction, 'coroutine_function_example') if hasattr(types, 'MemberDescriptorType'): self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') else: self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) def test_iscoroutine(self): gen_coro = gen_coroutine_function_example(1) coro = coroutine_function_example(1) self.assertFalse( inspect.iscoroutinefunction(gen_coroutine_function_example)) self.assertFalse(inspect.iscoroutine(gen_coro)) self.assertTrue( inspect.isgeneratorfunction(gen_coroutine_function_example)) self.assertTrue(inspect.isgenerator(gen_coro)) self.assertTrue( inspect.iscoroutinefunction(coroutine_function_example)) self.assertTrue(inspect.iscoroutine(coro)) self.assertFalse( inspect.isgeneratorfunction(coroutine_function_example)) self.assertFalse(inspect.isgenerator(coro)) coro.close(); gen_coro.close() # silence warnings def test_isawaitable(self): def gen(): yield self.assertFalse(inspect.isawaitable(gen())) coro = coroutine_function_example(1) gen_coro = gen_coroutine_function_example(1) self.assertTrue(inspect.isawaitable(coro)) self.assertTrue(inspect.isawaitable(gen_coro)) class Future: def __await__(): pass self.assertTrue(inspect.isawaitable(Future())) self.assertFalse(inspect.isawaitable(Future)) class NotFuture: pass not_fut = NotFuture() not_fut.__await__ = lambda: None self.assertFalse(inspect.isawaitable(not_fut)) coro.close(); gen_coro.close() # silence warnings def test_isroutine(self): self.assertTrue(inspect.isroutine(mod.spam)) self.assertTrue(inspect.isroutine([].count)) def test_isclass(self): self.istest(inspect.isclass, 'mod.StupidGit') self.assertTrue(inspect.isclass(list)) class CustomGetattr(object): def __getattr__(self, attr): return None self.assertFalse(inspect.isclass(CustomGetattr())) def test_get_slot_members(self): class C(object): __slots__ = ("a", "b") x = C() x.a = 42 members = dict(inspect.getmembers(x)) self.assertIn('a', members) self.assertNotIn('b', members) def test_isabstract(self): from abc import ABCMeta, abstractmethod class AbstractClassExample(metaclass=ABCMeta): @abstractmethod def foo(self): pass class ClassExample(AbstractClassExample): def foo(self): pass a = ClassExample() # Test general behaviour. self.assertTrue(inspect.isabstract(AbstractClassExample)) self.assertFalse(inspect.isabstract(ClassExample)) self.assertFalse(inspect.isabstract(a)) self.assertFalse(inspect.isabstract(int)) self.assertFalse(inspect.isabstract(5)) def test_isabstract_during_init_subclass(self): from abc import ABCMeta, abstractmethod isabstract_checks = [] class AbstractChecker(metaclass=ABCMeta): def __init_subclass__(cls): isabstract_checks.append(inspect.isabstract(cls)) class AbstractClassExample(AbstractChecker): @abstractmethod def foo(self): pass class ClassExample(AbstractClassExample): def foo(self): pass self.assertEqual(isabstract_checks, [True, False]) isabstract_checks.clear() class AbstractChild(AbstractClassExample): pass class AbstractGrandchild(AbstractChild): pass class ConcreteGrandchild(ClassExample): pass self.assertEqual(isabstract_checks, [True, True, False]) class TestInterpreterStack(IsTestBase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) git.abuse(7, 8, 9) def test_abuse_done(self): self.istest(inspect.istraceback, 'git.ex[2]') self.istest(inspect.isframe, 'mod.fr') def test_stack(self): self.assertTrue(len(mod.st) >= 5) self.assertEqual(revise(*mod.st[0][1:]), (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) self.assertEqual(revise(*mod.st[1][1:]), (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) self.assertEqual(revise(*mod.st[2][1:]), (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) self.assertEqual(revise(*mod.st[3][1:]), (modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0)) # Test named tuple fields record = mod.st[0] self.assertIs(record.frame, mod.fr) self.assertEqual(record.lineno, 16) self.assertEqual(record.filename, mod.__file__) self.assertEqual(record.function, 'eggs') self.assertIn('inspect.stack()', record.code_context[0]) self.assertEqual(record.index, 0) def test_trace(self): self.assertEqual(len(git.tr), 3) self.assertEqual(revise(*git.tr[0][1:]), (modfile, 43, 'argue', [' spam(a, b, c)\n'], 0)) self.assertEqual(revise(*git.tr[1][1:]), (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) self.assertEqual(revise(*git.tr[2][1:]), (modfile, 18, 'eggs', [' q = y / 0\n'], 0)) def test_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr) self.assertEqual(args, ['x', 'y']) self.assertEqual(varargs, None) self.assertEqual(varkw, None) self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(x=11, y=14)') def test_previous_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) self.assertEqual(varargs, 'g') self.assertEqual(varkw, 'h') self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})') class GetSourceBase(unittest.TestCase): # Subclasses must override. fodderModule = None def setUp(self): with open(inspect.getsourcefile(self.fodderModule)) as fp: self.source = fp.read() def sourcerange(self, top, bottom): lines = self.source.split("\n") return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "") def assertSourceEqual(self, obj, top, bottom): self.assertEqual(inspect.getsource(obj), self.sourcerange(top, bottom)) class TestRetrievingSourceCode(GetSourceBase): fodderModule = mod def test_getclasses(self): classes = inspect.getmembers(mod, inspect.isclass) self.assertEqual(classes, [('FesteringGob', mod.FesteringGob), ('MalodorousPervert', mod.MalodorousPervert), ('ParrotDroppings', mod.ParrotDroppings), ('StupidGit', mod.StupidGit), ('Tit', mod.MalodorousPervert), ]) tree = inspect.getclasstree([cls[1] for cls in classes]) self.assertEqual(tree, [(object, ()), [(mod.ParrotDroppings, (object,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ], (mod.StupidGit, (object,)), [(mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ] ] ] ]) tree = inspect.getclasstree([cls[1] for cls in classes], True) self.assertEqual(tree, [(object, ()), [(mod.ParrotDroppings, (object,)), (mod.StupidGit, (object,)), [(mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ] ] ] ]) def test_getfunctions(self): functions = inspect.getmembers(mod, inspect.isfunction) self.assertEqual(functions, [('eggs', mod.eggs), ('lobbest', mod.lobbest), ('spam', mod.spam)]) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_getdoc(self): self.assertEqual(inspect.getdoc(mod), 'A module docstring.') self.assertEqual(inspect.getdoc(mod.StupidGit), 'A longer,\n\nindented\n\ndocstring.') self.assertEqual(inspect.getdoc(git.abuse), 'Another\n\ndocstring\n\ncontaining\n\ntabs') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_getdoc_inherited(self): self.assertEqual(inspect.getdoc(mod.FesteringGob), 'A longer,\n\nindented\n\ndocstring.') self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse), 'Another\n\ndocstring\n\ncontaining\n\ntabs') self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse), 'Another\n\ndocstring\n\ncontaining\n\ntabs') self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction), 'The automatic gainsaying.') @unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings") def test_finddoc(self): finddoc = inspect._finddoc self.assertEqual(finddoc(int), int.__doc__) self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__) self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__) self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__) self.assertEqual(finddoc(int.real), int.real.__doc__) def test_cleandoc(self): self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'), 'An\nindented\ndocstring.') def test_getcomments(self): self.assertEqual(inspect.getcomments(mod), '# line 1\n') self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') # If the object source file is not available, return None. co = compile('x=1', '_non_existing_filename.py', 'exec') self.assertIsNone(inspect.getcomments(co)) # If the object has been defined in C, return None. self.assertIsNone(inspect.getcomments(list)) def test_getmodule(self): # Check actual module self.assertEqual(inspect.getmodule(mod), mod) # Check class (uses __module__ attribute) self.assertEqual(inspect.getmodule(mod.StupidGit), mod) # Check a method (no __module__ attribute, falls back to filename) self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) # Do it again (check the caching isn't broken) self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod) # Check a builtin self.assertEqual(inspect.getmodule(str), sys.modules["builtins"]) # Check filename override self.assertEqual(inspect.getmodule(None, modfile), mod) def test_getframeinfo_get_first_line(self): frame_info = inspect.getframeinfo(self.fodderModule.fr, 50) self.assertEqual(frame_info.code_context[0], "# line 1\n") self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n") def test_getsource(self): self.assertSourceEqual(git.abuse, 29, 39) self.assertSourceEqual(mod.StupidGit, 21, 51) self.assertSourceEqual(mod.lobbest, 75, 76) def test_getsourcefile(self): self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile) self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile) fn = "_non_existing_filename_used_for_sourcefile_test.py" co = compile("x=1", fn, "exec") self.assertEqual(inspect.getsourcefile(co), None) linecache.cache[co.co_filename] = (1, None, "None", co.co_filename) try: self.assertEqual(normcase(inspect.getsourcefile(co)), fn) finally: del linecache.cache[co.co_filename] def test_getfile(self): self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) def test_getfile_builtin_module(self): with self.assertRaises(TypeError) as e: inspect.getfile(sys) self.assertTrue(str(e.exception).startswith('<module')) def test_getfile_builtin_class(self): with self.assertRaises(TypeError) as e: inspect.getfile(int) self.assertTrue(str(e.exception).startswith('<class')) def test_getfile_builtin_function_or_method(self): with self.assertRaises(TypeError) as e_abs: inspect.getfile(abs) self.assertIn('expected, got', str(e_abs.exception)) with self.assertRaises(TypeError) as e_append: inspect.getfile(list.append) self.assertIn('expected, got', str(e_append.exception)) def test_getfile_class_without_module(self): class CM(type): @property def __module__(cls): raise AttributeError class C(metaclass=CM): pass with self.assertRaises(TypeError): inspect.getfile(C) def test_getfile_broken_repr(self): class ErrorRepr: def __repr__(self): raise Exception('xyz') er = ErrorRepr() with self.assertRaises(TypeError): inspect.getfile(er) def test_getmodule_recursion(self): from types import ModuleType name = '__inspect_dummy' m = sys.modules[name] = ModuleType(name) m.__file__ = "<string>" # hopefully not a real filename... m.__loader__ = "dummy" # pretend the filename is understood by a loader exec("def x(): pass", m.__dict__) self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>') del sys.modules[name] inspect.getmodule(compile('a=10','','single')) def test_proceed_with_fake_filename(self): '''doctest monkeypatches linecache to enable inspection''' fn, source = '<test>', 'def x(): pass\n' getlines = linecache.getlines def monkey(filename, module_globals=None): if filename == fn: return source.splitlines(keepends=True) else: return getlines(filename, module_globals) linecache.getlines = monkey try: ns = {} exec(compile(source, fn, 'single'), ns) inspect.getsource(ns["x"]) finally: linecache.getlines = getlines def test_getsource_on_code_object(self): self.assertSourceEqual(mod.eggs.__code__, 12, 18) class TestGettingSourceOfToplevelFrames(GetSourceBase): fodderModule = mod def test_range_toplevel_frame(self): self.maxDiff = None self.assertSourceEqual(mod.currentframe, 1, None) def test_range_traceback_toplevel_frame(self): self.assertSourceEqual(mod.tb, 1, None) class TestDecorators(GetSourceBase): fodderModule = mod2 def test_wrapped_decorator(self): self.assertSourceEqual(mod2.wrapped, 14, 17) def test_replacing_decorator(self): self.assertSourceEqual(mod2.gone, 9, 10) def test_getsource_unwrap(self): self.assertSourceEqual(mod2.real, 130, 132) def test_decorator_with_lambda(self): self.assertSourceEqual(mod2.func114, 113, 115) class TestOneliners(GetSourceBase): fodderModule = mod2 def test_oneline_lambda(self): # Test inspect.getsource with a one-line lambda function. self.assertSourceEqual(mod2.oll, 25, 25) def test_threeline_lambda(self): # Test inspect.getsource with a three-line lambda function, # where the second and third lines are _not_ indented. self.assertSourceEqual(mod2.tll, 28, 30) def test_twoline_indented_lambda(self): # Test inspect.getsource with a two-line lambda function, # where the second line _is_ indented. self.assertSourceEqual(mod2.tlli, 33, 34) def test_onelinefunc(self): # Test inspect.getsource with a regular one-line function. self.assertSourceEqual(mod2.onelinefunc, 37, 37) def test_manyargs(self): # Test inspect.getsource with a regular function where # the arguments are on two lines and _not_ indented and # the body on the second line with the last arguments. self.assertSourceEqual(mod2.manyargs, 40, 41) def test_twolinefunc(self): # Test inspect.getsource with a regular function where # the body is on two lines, following the argument list and # continued on the next line by a \\. self.assertSourceEqual(mod2.twolinefunc, 44, 45) def test_lambda_in_list(self): # Test inspect.getsource with a one-line lambda function # defined in a list, indented. self.assertSourceEqual(mod2.a[1], 49, 49) def test_anonymous(self): # Test inspect.getsource with a lambda function defined # as argument to another function. self.assertSourceEqual(mod2.anonymous, 55, 55) class TestBuggyCases(GetSourceBase): fodderModule = mod2 def test_with_comment(self): self.assertSourceEqual(mod2.with_comment, 58, 59) def test_multiline_sig(self): self.assertSourceEqual(mod2.multiline_sig[0], 63, 64) def test_nested_class(self): self.assertSourceEqual(mod2.func69().func71, 71, 72) def test_one_liner_followed_by_non_name(self): self.assertSourceEqual(mod2.func77, 77, 77) def test_one_liner_dedent_non_name(self): self.assertSourceEqual(mod2.cls82.func83, 83, 83) def test_with_comment_instead_of_docstring(self): self.assertSourceEqual(mod2.func88, 88, 90) def test_method_in_dynamic_class(self): self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97) # This should not skip for CPython, but might on a repackaged python where # unicodedata is not an external module, or on pypy. @unittest.skipIf(not hasattr(unicodedata, '__file__') or unicodedata.__file__.endswith('.py'), "unicodedata is not an external binary module") def test_findsource_binary(self): self.assertRaises(OSError, inspect.getsource, unicodedata) self.assertRaises(OSError, inspect.findsource, unicodedata) def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(OSError, inspect.findsource, co) self.assertRaises(OSError, inspect.getsource, co) linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) try: self.assertEqual(inspect.findsource(co), (lines,0)) self.assertEqual(inspect.getsource(co), lines[0]) finally: del linecache.cache[co.co_filename] def test_findsource_without_filename(self): for fname in ['', '<string>']: co = compile('x=1', fname, "exec") self.assertRaises(IOError, inspect.findsource, co) self.assertRaises(IOError, inspect.getsource, co) def test_getsource_on_method(self): self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119) def test_nested_func(self): self.assertSourceEqual(mod2.cls135.func136, 136, 139) class TestNoEOL(GetSourceBase): def setUp(self): self.tempdir = TESTFN + '_dir' os.mkdir(self.tempdir) with open(os.path.join(self.tempdir, 'inspect_fodder3%spy' % os.extsep), 'w') as f: f.write("class X:\n pass # No EOL") with DirsOnSysPath(self.tempdir): import inspect_fodder3 as mod3 self.fodderModule = mod3 super().setUp() def tearDown(self): shutil.rmtree(self.tempdir) def test_class(self): self.assertSourceEqual(self.fodderModule.X, 1, 2) class _BrokenDataDescriptor(object): """ A broken data descriptor. See bug #1785. """ def __get__(*args): raise AttributeError("broken data descriptor") def __set__(*args): raise RuntimeError def __getattr__(*args): raise AttributeError("broken data descriptor") class _BrokenMethodDescriptor(object): """ A broken method descriptor. See bug #1785. """ def __get__(*args): raise AttributeError("broken method descriptor") def __getattr__(*args): raise AttributeError("broken method descriptor") # Helper for testing classify_class_attrs. def attrs_wo_objs(cls): return [t[:3] for t in inspect.classify_class_attrs(cls)] class TestClassesAndFunctions(unittest.TestCase): def test_newstyle_mro(self): # The same w/ new-class MRO. class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass expected = (D, B, C, A, object) got = inspect.getmro(D) self.assertEqual(expected, got) def assertArgSpecEquals(self, routine, args_e, varargs_e=None, varkw_e=None, defaults_e=None, formatted=None): with self.assertWarns(DeprecationWarning): args, varargs, varkw, defaults = inspect.getargspec(routine) self.assertEqual(args, args_e) self.assertEqual(varargs, varargs_e) self.assertEqual(varkw, varkw_e) self.assertEqual(defaults, defaults_e) if formatted is not None: with self.assertWarns(DeprecationWarning): self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults), formatted) def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None, varkw_e=None, defaults_e=None, kwonlyargs_e=[], kwonlydefaults_e=None, ann_e={}, formatted=None): args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ inspect.getfullargspec(routine) self.assertEqual(args, args_e) self.assertEqual(varargs, varargs_e) self.assertEqual(varkw, varkw_e) self.assertEqual(defaults, defaults_e) self.assertEqual(kwonlyargs, kwonlyargs_e) self.assertEqual(kwonlydefaults, kwonlydefaults_e) self.assertEqual(ann, ann_e) if formatted is not None: with self.assertWarns(DeprecationWarning): self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann), formatted) def test_getargspec(self): self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted='(x, y)') self.assertArgSpecEquals(mod.spam, ['a', 'b', 'c', 'd', 'e', 'f'], 'g', 'h', (3, 4, 5), '(a, b, c, d=3, e=4, f=5, *g, **h)') self.assertRaises(ValueError, self.assertArgSpecEquals, mod2.keyworded, []) self.assertRaises(ValueError, self.assertArgSpecEquals, mod2.annotated, []) self.assertRaises(ValueError, self.assertArgSpecEquals, mod2.keyword_only_arg, []) def test_getfullargspec(self): self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1', kwonlyargs_e=['arg2'], kwonlydefaults_e={'arg2':1}, formatted='(*arg1, arg2=1)') self.assertFullArgSpecEquals(mod2.annotated, ['arg1'], ann_e={'arg1' : list}, formatted='(arg1: list)') self.assertFullArgSpecEquals(mod2.keyword_only_arg, [], kwonlyargs_e=['arg'], formatted='(*, arg)') def test_argspec_api_ignores_wrapped(self): # Issue 20684: low level introspection API must ignore __wrapped__ @functools.wraps(mod.spam) def ham(x, y): pass # Basic check self.assertArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)') self.assertFullArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)') self.assertFullArgSpecEquals(functools.partial(ham), ['x', 'y'], formatted='(x, y)') # Other variants def check_method(f): self.assertArgSpecEquals(f, ['self', 'x', 'y'], formatted='(self, x, y)') class C: @functools.wraps(mod.spam) def ham(self, x, y): pass pham = functools.partialmethod(ham) @functools.wraps(mod.spam) def __call__(self, x, y): pass check_method(C()) check_method(C.ham) check_method(C().ham) check_method(C.pham) check_method(C().pham) class C_new: @functools.wraps(mod.spam) def __new__(self, x, y): pass check_method(C_new) class C_init: @functools.wraps(mod.spam) def __init__(self, x, y): pass check_method(C_init) def test_getfullargspec_signature_attr(self): def test(): pass spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) test.__signature__ = inspect.Signature(parameters=(spam_param,)) self.assertFullArgSpecEquals(test, args_e=['spam'], formatted='(spam)') def test_getfullargspec_signature_annos(self): def test(a:'spam') -> 'ham': pass spec = inspect.getfullargspec(test) self.assertEqual(test.__annotations__, spec.annotations) def test(): pass spec = inspect.getfullargspec(test) self.assertEqual(test.__annotations__, spec.annotations) @unittest.skipIf(MISSING_C_DOCSTRINGS,
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_tokenize.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
from test import support from tokenize import (tokenize, _tokenize, untokenize, NUMBER, NAME, OP, STRING, ENDMARKER, ENCODING, tok_name, detect_encoding, open as tokenize_open, Untokenizer, generate_tokens, NEWLINE) from io import BytesIO import unittest from unittest import TestCase, mock from test.test_grammar import (VALID_UNDERSCORE_LITERALS, INVALID_UNDERSCORE_LITERALS) import os import token # Converts a source string into a list of textual representation # of the tokens such as: # ` NAME 'if' (1, 0) (1, 2)` # to make writing tests easier. def stringify_tokens_from_source(token_generator, source_string): result = [] num_lines = len(source_string.splitlines()) missing_trailing_nl = source_string[-1] not in '\r\n' for type, token, start, end, line in token_generator: if type == ENDMARKER: break # Ignore the new line on the last line if the input lacks one if missing_trailing_nl and type == NEWLINE and end[0] == num_lines: continue type = tok_name[type] result.append(f" {type:10} {token!r:13} {start} {end}") return result class TokenizeTest(TestCase): # Tests for the tokenize module. # The tests can be really simple. Given a small fragment of source # code, print out a table with tokens. The ENDMARKER, ENCODING and # final NEWLINE are omitted for brevity. def check_tokenize(self, s, expected): # Format the tokens in s in a table format. # The ENDMARKER and final NEWLINE are omitted. f = BytesIO(s.encode('utf-8')) result = stringify_tokens_from_source(tokenize(f.readline), s) self.assertEqual(result, [" ENCODING 'utf-8' (0, 0) (0, 0)"] + expected.rstrip().splitlines()) def test_implicit_newline(self): # Make sure that the tokenizer puts in an implicit NEWLINE # when the input lacks a trailing new line. f = BytesIO("x".encode('utf-8')) tokens = list(tokenize(f.readline)) self.assertEqual(tokens[-2].type, NEWLINE) self.assertEqual(tokens[-1].type, ENDMARKER) def test_basic(self): self.check_tokenize("1 + 1", """\ NUMBER '1' (1, 0) (1, 1) OP '+' (1, 2) (1, 3) NUMBER '1' (1, 4) (1, 5) """) self.check_tokenize("if False:\n" " # NL\n" " \n" " True = False # NEWLINE\n", """\ NAME 'if' (1, 0) (1, 2) NAME 'False' (1, 3) (1, 8) OP ':' (1, 8) (1, 9) NEWLINE '\\n' (1, 9) (1, 10) COMMENT '# NL' (2, 4) (2, 8) NL '\\n' (2, 8) (2, 9) NL '\\n' (3, 4) (3, 5) INDENT ' ' (4, 0) (4, 4) NAME 'True' (4, 4) (4, 8) OP '=' (4, 9) (4, 10) NAME 'False' (4, 11) (4, 16) COMMENT '# NEWLINE' (4, 17) (4, 26) NEWLINE '\\n' (4, 26) (4, 27) DEDENT '' (5, 0) (5, 0) """) indent_error_file = b"""\ def k(x): x += 2 x += 5 """ readline = BytesIO(indent_error_file).readline with self.assertRaisesRegex(IndentationError, "unindent does not match any " "outer indentation level"): for tok in tokenize(readline): pass def test_int(self): # Ordinary integers and binary operators self.check_tokenize("0xff <= 255", """\ NUMBER '0xff' (1, 0) (1, 4) OP '<=' (1, 5) (1, 7) NUMBER '255' (1, 8) (1, 11) """) self.check_tokenize("0b10 <= 255", """\ NUMBER '0b10' (1, 0) (1, 4) OP '<=' (1, 5) (1, 7) NUMBER '255' (1, 8) (1, 11) """) self.check_tokenize("0o123 <= 0O123", """\ NUMBER '0o123' (1, 0) (1, 5) OP '<=' (1, 6) (1, 8) NUMBER '0O123' (1, 9) (1, 14) """) self.check_tokenize("1234567 > ~0x15", """\ NUMBER '1234567' (1, 0) (1, 7) OP '>' (1, 8) (1, 9) OP '~' (1, 10) (1, 11) NUMBER '0x15' (1, 11) (1, 15) """) self.check_tokenize("2134568 != 1231515", """\ NUMBER '2134568' (1, 0) (1, 7) OP '!=' (1, 8) (1, 10) NUMBER '1231515' (1, 11) (1, 18) """) self.check_tokenize("(-124561-1) & 200000000", """\ OP '(' (1, 0) (1, 1) OP '-' (1, 1) (1, 2) NUMBER '124561' (1, 2) (1, 8) OP '-' (1, 8) (1, 9) NUMBER '1' (1, 9) (1, 10) OP ')' (1, 10) (1, 11) OP '&' (1, 12) (1, 13) NUMBER '200000000' (1, 14) (1, 23) """) self.check_tokenize("0xdeadbeef != -1", """\ NUMBER '0xdeadbeef' (1, 0) (1, 10) OP '!=' (1, 11) (1, 13) OP '-' (1, 14) (1, 15) NUMBER '1' (1, 15) (1, 16) """) self.check_tokenize("0xdeadc0de & 12345", """\ NUMBER '0xdeadc0de' (1, 0) (1, 10) OP '&' (1, 11) (1, 12) NUMBER '12345' (1, 13) (1, 18) """) self.check_tokenize("0xFF & 0x15 | 1234", """\ NUMBER '0xFF' (1, 0) (1, 4) OP '&' (1, 5) (1, 6) NUMBER '0x15' (1, 7) (1, 11) OP '|' (1, 12) (1, 13) NUMBER '1234' (1, 14) (1, 18) """) def test_long(self): # Long integers self.check_tokenize("x = 0", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '0' (1, 4) (1, 5) """) self.check_tokenize("x = 0xfffffffffff", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '0xfffffffffff' (1, 4) (1, 17) """) self.check_tokenize("x = 123141242151251616110", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '123141242151251616110' (1, 4) (1, 25) """) self.check_tokenize("x = -15921590215012591", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) OP '-' (1, 4) (1, 5) NUMBER '15921590215012591' (1, 5) (1, 22) """) def test_float(self): # Floating point numbers self.check_tokenize("x = 3.14159", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '3.14159' (1, 4) (1, 11) """) self.check_tokenize("x = 314159.", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '314159.' (1, 4) (1, 11) """) self.check_tokenize("x = .314159", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '.314159' (1, 4) (1, 11) """) self.check_tokenize("x = 3e14159", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '3e14159' (1, 4) (1, 11) """) self.check_tokenize("x = 3E123", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '3E123' (1, 4) (1, 9) """) self.check_tokenize("x+y = 3e-1230", """\ NAME 'x' (1, 0) (1, 1) OP '+' (1, 1) (1, 2) NAME 'y' (1, 2) (1, 3) OP '=' (1, 4) (1, 5) NUMBER '3e-1230' (1, 6) (1, 13) """) self.check_tokenize("x = 3.14e159", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '3.14e159' (1, 4) (1, 12) """) def test_underscore_literals(self): def number_token(s): f = BytesIO(s.encode('utf-8')) for toktype, token, start, end, line in tokenize(f.readline): if toktype == NUMBER: return token return 'invalid token' for lit in VALID_UNDERSCORE_LITERALS: if '(' in lit: # this won't work with compound complex inputs continue self.assertEqual(number_token(lit), lit) for lit in INVALID_UNDERSCORE_LITERALS: self.assertNotEqual(number_token(lit), lit) def test_string(self): # String literals self.check_tokenize("x = ''; y = \"\"", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING "''" (1, 4) (1, 6) OP ';' (1, 6) (1, 7) NAME 'y' (1, 8) (1, 9) OP '=' (1, 10) (1, 11) STRING '""' (1, 12) (1, 14) """) self.check_tokenize("x = '\"'; y = \"'\"", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING '\\'"\\'' (1, 4) (1, 7) OP ';' (1, 7) (1, 8) NAME 'y' (1, 9) (1, 10) OP '=' (1, 11) (1, 12) STRING '"\\'"' (1, 13) (1, 16) """) self.check_tokenize("x = \"doesn't \"shrink\", does it\"", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING '"doesn\\'t "' (1, 4) (1, 14) NAME 'shrink' (1, 14) (1, 20) STRING '", does it"' (1, 20) (1, 31) """) self.check_tokenize("x = 'abc' + 'ABC'", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING "'abc'" (1, 4) (1, 9) OP '+' (1, 10) (1, 11) STRING "'ABC'" (1, 12) (1, 17) """) self.check_tokenize('y = "ABC" + "ABC"', """\ NAME 'y' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING '"ABC"' (1, 4) (1, 9) OP '+' (1, 10) (1, 11) STRING '"ABC"' (1, 12) (1, 17) """) self.check_tokenize("x = r'abc' + r'ABC' + R'ABC' + R'ABC'", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING "r'abc'" (1, 4) (1, 10) OP '+' (1, 11) (1, 12) STRING "r'ABC'" (1, 13) (1, 19) OP '+' (1, 20) (1, 21) STRING "R'ABC'" (1, 22) (1, 28) OP '+' (1, 29) (1, 30) STRING "R'ABC'" (1, 31) (1, 37) """) self.check_tokenize('y = r"abc" + r"ABC" + R"ABC" + R"ABC"', """\ NAME 'y' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) STRING 'r"abc"' (1, 4) (1, 10) OP '+' (1, 11) (1, 12) STRING 'r"ABC"' (1, 13) (1, 19) OP '+' (1, 20) (1, 21) STRING 'R"ABC"' (1, 22) (1, 28) OP '+' (1, 29) (1, 30) STRING 'R"ABC"' (1, 31) (1, 37) """) self.check_tokenize("u'abc' + U'abc'", """\ STRING "u'abc'" (1, 0) (1, 6) OP '+' (1, 7) (1, 8) STRING "U'abc'" (1, 9) (1, 15) """) self.check_tokenize('u"abc" + U"abc"', """\ STRING 'u"abc"' (1, 0) (1, 6) OP '+' (1, 7) (1, 8) STRING 'U"abc"' (1, 9) (1, 15) """) self.check_tokenize("b'abc' + B'abc'", """\ STRING "b'abc'" (1, 0) (1, 6) OP '+' (1, 7) (1, 8) STRING "B'abc'" (1, 9) (1, 15) """) self.check_tokenize('b"abc" + B"abc"', """\ STRING 'b"abc"' (1, 0) (1, 6) OP '+' (1, 7) (1, 8) STRING 'B"abc"' (1, 9) (1, 15) """) self.check_tokenize("br'abc' + bR'abc' + Br'abc' + BR'abc'", """\ STRING "br'abc'" (1, 0) (1, 7) OP '+' (1, 8) (1, 9) STRING "bR'abc'" (1, 10) (1, 17) OP '+' (1, 18) (1, 19) STRING "Br'abc'" (1, 20) (1, 27) OP '+' (1, 28) (1, 29) STRING "BR'abc'" (1, 30) (1, 37) """) self.check_tokenize('br"abc" + bR"abc" + Br"abc" + BR"abc"', """\ STRING 'br"abc"' (1, 0) (1, 7) OP '+' (1, 8) (1, 9) STRING 'bR"abc"' (1, 10) (1, 17) OP '+' (1, 18) (1, 19) STRING 'Br"abc"' (1, 20) (1, 27) OP '+' (1, 28) (1, 29) STRING 'BR"abc"' (1, 30) (1, 37) """) self.check_tokenize("rb'abc' + rB'abc' + Rb'abc' + RB'abc'", """\ STRING "rb'abc'" (1, 0) (1, 7) OP '+' (1, 8) (1, 9) STRING "rB'abc'" (1, 10) (1, 17) OP '+' (1, 18) (1, 19) STRING "Rb'abc'" (1, 20) (1, 27) OP '+' (1, 28) (1, 29) STRING "RB'abc'" (1, 30) (1, 37) """) self.check_tokenize('rb"abc" + rB"abc" + Rb"abc" + RB"abc"', """\ STRING 'rb"abc"' (1, 0) (1, 7) OP '+' (1, 8) (1, 9) STRING 'rB"abc"' (1, 10) (1, 17) OP '+' (1, 18) (1, 19) STRING 'Rb"abc"' (1, 20) (1, 27) OP '+' (1, 28) (1, 29) STRING 'RB"abc"' (1, 30) (1, 37) """) # Check 0, 1, and 2 character string prefixes. self.check_tokenize(r'"a\ de\ fg"', """\ STRING '"a\\\\\\nde\\\\\\nfg"\' (1, 0) (3, 3) """) self.check_tokenize(r'u"a\ de"', """\ STRING 'u"a\\\\\\nde"\' (1, 0) (2, 3) """) self.check_tokenize(r'rb"a\ d"', """\ STRING 'rb"a\\\\\\nd"\' (1, 0) (2, 2) """) self.check_tokenize(r'"""a\ b"""', """\ STRING '\"\""a\\\\\\nb\"\""' (1, 0) (2, 4) """) self.check_tokenize(r'u"""a\ b"""', """\ STRING 'u\"\""a\\\\\\nb\"\""' (1, 0) (2, 4) """) self.check_tokenize(r'rb"""a\ b\ c"""', """\ STRING 'rb"\""a\\\\\\nb\\\\\\nc"\""' (1, 0) (3, 4) """) self.check_tokenize('f"abc"', """\ STRING 'f"abc"' (1, 0) (1, 6) """) self.check_tokenize('fR"a{b}c"', """\ STRING 'fR"a{b}c"' (1, 0) (1, 9) """) self.check_tokenize('f"""abc"""', """\ STRING 'f\"\"\"abc\"\"\"' (1, 0) (1, 10) """) self.check_tokenize(r'f"abc\ def"', """\ STRING 'f"abc\\\\\\ndef"' (1, 0) (2, 4) """) self.check_tokenize(r'Rf"abc\ def"', """\ STRING 'Rf"abc\\\\\\ndef"' (1, 0) (2, 4) """) def test_function(self): self.check_tokenize("def d22(a, b, c=2, d=2, *k): pass", """\ NAME 'def' (1, 0) (1, 3) NAME 'd22' (1, 4) (1, 7) OP '(' (1, 7) (1, 8) NAME 'a' (1, 8) (1, 9) OP ',' (1, 9) (1, 10) NAME 'b' (1, 11) (1, 12) OP ',' (1, 12) (1, 13) NAME 'c' (1, 14) (1, 15) OP '=' (1, 15) (1, 16) NUMBER '2' (1, 16) (1, 17) OP ',' (1, 17) (1, 18) NAME 'd' (1, 19) (1, 20) OP '=' (1, 20) (1, 21) NUMBER '2' (1, 21) (1, 22) OP ',' (1, 22) (1, 23) OP '*' (1, 24) (1, 25) NAME 'k' (1, 25) (1, 26) OP ')' (1, 26) (1, 27) OP ':' (1, 27) (1, 28) NAME 'pass' (1, 29) (1, 33) """) self.check_tokenize("def d01v_(a=1, *k, **w): pass", """\ NAME 'def' (1, 0) (1, 3) NAME 'd01v_' (1, 4) (1, 9) OP '(' (1, 9) (1, 10) NAME 'a' (1, 10) (1, 11) OP '=' (1, 11) (1, 12) NUMBER '1' (1, 12) (1, 13) OP ',' (1, 13) (1, 14) OP '*' (1, 15) (1, 16) NAME 'k' (1, 16) (1, 17) OP ',' (1, 17) (1, 18) OP '**' (1, 19) (1, 21) NAME 'w' (1, 21) (1, 22) OP ')' (1, 22) (1, 23) OP ':' (1, 23) (1, 24) NAME 'pass' (1, 25) (1, 29) """) self.check_tokenize("def d23(a: str, b: int=3) -> int: pass", """\ NAME 'def' (1, 0) (1, 3) NAME 'd23' (1, 4) (1, 7) OP '(' (1, 7) (1, 8) NAME 'a' (1, 8) (1, 9) OP ':' (1, 9) (1, 10) NAME 'str' (1, 11) (1, 14) OP ',' (1, 14) (1, 15) NAME 'b' (1, 16) (1, 17) OP ':' (1, 17) (1, 18) NAME 'int' (1, 19) (1, 22) OP '=' (1, 22) (1, 23) NUMBER '3' (1, 23) (1, 24) OP ')' (1, 24) (1, 25) OP '->' (1, 26) (1, 28) NAME 'int' (1, 29) (1, 32) OP ':' (1, 32) (1, 33) NAME 'pass' (1, 34) (1, 38) """) def test_comparison(self): # Comparison self.check_tokenize("if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != " "1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass", """\ NAME 'if' (1, 0) (1, 2) NUMBER '1' (1, 3) (1, 4) OP '<' (1, 5) (1, 6) NUMBER '1' (1, 7) (1, 8) OP '>' (1, 9) (1, 10) NUMBER '1' (1, 11) (1, 12) OP '==' (1, 13) (1, 15) NUMBER '1' (1, 16) (1, 17) OP '>=' (1, 18) (1, 20) NUMBER '5' (1, 21) (1, 22) OP '<=' (1, 23) (1, 25) NUMBER '0x15' (1, 26) (1, 30) OP '<=' (1, 31) (1, 33) NUMBER '0x12' (1, 34) (1, 38) OP '!=' (1, 39) (1, 41) NUMBER '1' (1, 42) (1, 43) NAME 'and' (1, 44) (1, 47) NUMBER '5' (1, 48) (1, 49) NAME 'in' (1, 50) (1, 52) NUMBER '1' (1, 53) (1, 54) NAME 'not' (1, 55) (1, 58) NAME 'in' (1, 59) (1, 61) NUMBER '1' (1, 62) (1, 63) NAME 'is' (1, 64) (1, 66) NUMBER '1' (1, 67) (1, 68) NAME 'or' (1, 69) (1, 71) NUMBER '5' (1, 72) (1, 73) NAME 'is' (1, 74) (1, 76) NAME 'not' (1, 77) (1, 80) NUMBER '1' (1, 81) (1, 82) OP ':' (1, 82) (1, 83) NAME 'pass' (1, 84) (1, 88) """) def test_shift(self): # Shift self.check_tokenize("x = 1 << 1 >> 5", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '1' (1, 4) (1, 5) OP '<<' (1, 6) (1, 8) NUMBER '1' (1, 9) (1, 10) OP '>>' (1, 11) (1, 13) NUMBER '5' (1, 14) (1, 15) """) def test_additive(self): # Additive self.check_tokenize("x = 1 - y + 15 - 1 + 0x124 + z + a[5]", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '1' (1, 4) (1, 5) OP '-' (1, 6) (1, 7) NAME 'y' (1, 8) (1, 9) OP '+' (1, 10) (1, 11) NUMBER '15' (1, 12) (1, 14) OP '-' (1, 15) (1, 16) NUMBER '1' (1, 17) (1, 18) OP '+' (1, 19) (1, 20) NUMBER '0x124' (1, 21) (1, 26) OP '+' (1, 27) (1, 28) NAME 'z' (1, 29) (1, 30) OP '+' (1, 31) (1, 32) NAME 'a' (1, 33) (1, 34) OP '[' (1, 34) (1, 35) NUMBER '5' (1, 35) (1, 36) OP ']' (1, 36) (1, 37) """) def test_multiplicative(self): # Multiplicative self.check_tokenize("x = 1//1*1/5*12%0x12@42", """\ NAME 'x' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) NUMBER '1' (1, 4) (1, 5) OP '//' (1, 5) (1, 7) NUMBER '1' (1, 7) (1, 8) OP '*' (1, 8) (1, 9) NUMBER '1' (1, 9) (1, 10) OP '/' (1, 10) (1, 11) NUMBER '5' (1, 11) (1, 12) OP '*' (1, 12) (1, 13) NUMBER '12' (1, 13) (1, 15) OP '%' (1, 15) (1, 16) NUMBER '0x12' (1, 16) (1, 20) OP '@' (1, 20) (1, 21) NUMBER '42' (1, 21) (1, 23) """) def test_unary(self): # Unary self.check_tokenize("~1 ^ 1 & 1 |1 ^ -1", """\ OP '~' (1, 0) (1, 1) NUMBER '1' (1, 1) (1, 2) OP '^' (1, 3) (1, 4) NUMBER '1' (1, 5) (1, 6) OP '&' (1, 7) (1, 8) NUMBER '1' (1, 9) (1, 10) OP '|' (1, 11) (1, 12) NUMBER '1' (1, 12) (1, 13) OP '^' (1, 14) (1, 15) OP '-' (1, 16) (1, 17) NUMBER '1' (1, 17) (1, 18) """) self.check_tokenize("-1*1/1+1*1//1 - ---1**1", """\ OP '-' (1, 0) (1, 1) NUMBER '1' (1, 1) (1, 2) OP '*' (1, 2) (1, 3) NUMBER '1' (1, 3) (1, 4) OP '/' (1, 4) (1, 5) NUMBER '1' (1, 5) (1, 6) OP '+' (1, 6) (1, 7) NUMBER '1' (1, 7) (1, 8) OP '*' (1, 8) (1, 9) NUMBER '1' (1, 9) (1, 10) OP '//' (1, 10) (1, 12) NUMBER '1' (1, 12) (1, 13) OP '-' (1, 14) (1, 15) OP '-' (1, 16) (1, 17) OP '-' (1, 17) (1, 18) OP '-' (1, 18) (1, 19) NUMBER '1' (1, 19) (1, 20) OP '**' (1, 20) (1, 22) NUMBER '1' (1, 22) (1, 23) """) def test_selector(self): # Selector self.check_tokenize("import sys, time\nx = sys.modules['time'].time()", """\ NAME 'import' (1, 0) (1, 6) NAME 'sys' (1, 7) (1, 10) OP ',' (1, 10) (1, 11) NAME 'time' (1, 12) (1, 16) NEWLINE '\\n' (1, 16) (1, 17) NAME 'x' (2, 0) (2, 1) OP '=' (2, 2) (2, 3) NAME 'sys' (2, 4) (2, 7) OP '.' (2, 7) (2, 8) NAME 'modules' (2, 8) (2, 15) OP '[' (2, 15) (2, 16) STRING "'time'" (2, 16) (2, 22) OP ']' (2, 22) (2, 23) OP '.' (2, 23) (2, 24) NAME 'time' (2, 24) (2, 28) OP '(' (2, 28) (2, 29) OP ')' (2, 29) (2, 30) """) def test_method(self): # Methods self.check_tokenize("@staticmethod\ndef foo(x,y): pass", """\ OP '@' (1, 0) (1, 1) NAME 'staticmethod' (1, 1) (1, 13) NEWLINE '\\n' (1, 13) (1, 14) NAME 'def' (2, 0) (2, 3) NAME 'foo' (2, 4) (2, 7) OP '(' (2, 7) (2, 8) NAME 'x' (2, 8) (2, 9) OP ',' (2, 9) (2, 10) NAME 'y' (2, 10) (2, 11) OP ')' (2, 11) (2, 12) OP ':' (2, 12) (2, 13) NAME 'pass' (2, 14) (2, 18) """) def test_tabs(self): # Evil tabs self.check_tokenize("def f():\n" "\tif x\n" " \tpass", """\ NAME 'def' (1, 0) (1, 3) NAME 'f' (1, 4) (1, 5) OP '(' (1, 5) (1, 6) OP ')' (1, 6) (1, 7) OP ':' (1, 7) (1, 8) NEWLINE '\\n' (1, 8) (1, 9) INDENT '\\t' (2, 0) (2, 1) NAME 'if' (2, 1) (2, 3) NAME 'x' (2, 4) (2, 5) NEWLINE '\\n' (2, 5) (2, 6) INDENT ' \\t' (3, 0) (3, 9) NAME 'pass' (3, 9) (3, 13) DEDENT '' (4, 0) (4, 0) DEDENT '' (4, 0) (4, 0) """) def test_non_ascii_identifiers(self): # Non-ascii identifiers self.check_tokenize("Örter = 'places'\ngrün = 'green'", """\ NAME 'Örter' (1, 0) (1, 5) OP '=' (1, 6) (1, 7) STRING "'places'" (1, 8) (1, 16) NEWLINE '\\n' (1, 16) (1, 17) NAME 'grün' (2, 0) (2, 4) OP '=' (2, 5) (2, 6) STRING "'green'" (2, 7) (2, 14) """) def test_unicode(self): # Legacy unicode literals: self.check_tokenize("Örter = u'places'\ngrün = U'green'", """\ NAME 'Örter' (1, 0) (1, 5) OP '=' (1, 6) (1, 7) STRING "u'places'" (1, 8) (1, 17) NEWLINE '\\n' (1, 17) (1, 18) NAME 'grün' (2, 0) (2, 4) OP '=' (2, 5) (2, 6) STRING "U'green'" (2, 7) (2, 15) """) def test_async(self): # Async/await extension: self.check_tokenize("async = 1", """\ NAME 'async' (1, 0) (1, 5) OP '=' (1, 6) (1, 7) NUMBER '1' (1, 8) (1, 9) """) self.check_tokenize("a = (async = 1)", """\ NAME 'a' (1, 0) (1, 1) OP '=' (1, 2) (1, 3) OP '(' (1, 4) (1, 5) NAME 'async' (1, 5) (1, 10) OP '=' (1, 11) (1, 12) NUMBER '1' (1, 13) (1, 14) OP ')' (1, 14) (1, 15) """) self.check_tokenize("async()", """\ NAME 'async' (1, 0) (1, 5) OP '(' (1, 5) (1, 6) OP ')' (1, 6) (1, 7) """) self.check_tokenize("class async(Bar):pass", """\ NAME 'class' (1, 0) (1, 5) NAME 'async' (1, 6) (1, 11) OP '(' (1, 11) (1, 12) NAME 'Bar' (1, 12) (1, 15) OP ')' (1, 15) (1, 16) OP ':' (1, 16) (1, 17) NAME 'pass' (1, 17) (1, 21) """) self.check_tokenize("class async:pass", """\ NAME 'class' (1, 0) (1, 5) NAME 'async' (1, 6) (1, 11) OP ':' (1, 11) (1, 12) NAME 'pass' (1, 12) (1, 16) """) self.check_tokenize("await = 1", """\ NAME 'await' (1, 0) (1, 5) OP '=' (1, 6) (1, 7) NUMBER '1' (1, 8) (1, 9) """) self.check_tokenize("foo.async", """\ NAME 'foo' (1, 0) (1, 3) OP '.' (1, 3) (1, 4) NAME 'async' (1, 4) (1, 9) """) self.check_tokenize("async for a in b: pass", """\ NAME 'async' (1, 0) (1, 5) NAME 'for' (1, 6) (1, 9) NAME 'a' (1, 10) (1, 11) NAME 'in' (1, 12) (1, 14) NAME 'b' (1, 15) (1, 16) OP ':' (1, 16) (1, 17) NAME 'pass' (1, 18) (1, 22) """) self.check_tokenize("async with a as b: pass", """\ NAME 'async' (1, 0) (1, 5) NAME 'with' (1, 6) (1, 10) NAME 'a' (1, 11) (1, 12) NAME 'as' (1, 13) (1, 15) NAME 'b' (1, 16) (1, 17) OP ':' (1, 17) (1, 18) NAME 'pass' (1, 19) (1, 23) """) self.check_tokenize("async.foo", """\ NAME 'async' (1, 0) (1, 5) OP '.' (1, 5) (1, 6) NAME 'foo' (1, 6) (1, 9) """) self.check_tokenize("async", """\ NAME 'async' (1, 0) (1, 5) """) self.check_tokenize("async\n#comment\nawait", """\ NAME 'async' (1, 0) (1, 5) NEWLINE '\\n' (1, 5) (1, 6) COMMENT '#comment' (2, 0) (2, 8) NL '\\n' (2, 8) (2, 9) NAME 'await' (3, 0) (3, 5) """) self.check_tokenize("async\n...\nawait", """\ NAME 'async' (1, 0) (1, 5) NEWLINE '\\n' (1, 5) (1, 6) OP '...' (2, 0) (2, 3) NEWLINE '\\n' (2, 3) (2, 4) NAME 'await' (3, 0) (3, 5) """) self.check_tokenize("async\nawait", """\ NAME 'async' (1, 0) (1, 5) NEWLINE '\\n' (1, 5) (1, 6) NAME 'await' (2, 0) (2, 5) """) self.check_tokenize("foo.async + 1", """\ NAME 'foo' (1, 0) (1, 3) OP '.' (1, 3) (1, 4) NAME 'async' (1, 4) (1, 9) OP '+' (1, 10) (1, 11) NUMBER '1' (1, 12) (1, 13) """) self.check_tokenize("async def foo(): pass", """\ NAME 'async' (1, 0) (1, 5) NAME 'def' (1, 6) (1, 9) NAME 'foo' (1, 10) (1, 13) OP '(' (1, 13) (1, 14) OP ')' (1, 14) (1, 15) OP ':' (1, 15) (1, 16) NAME 'pass' (1, 17) (1, 21) """) self.check_tokenize('''\ async def foo(): def foo(await): await = 1 if 1: await async += 1 ''', """\ NAME 'async' (1, 0) (1, 5) NAME 'def' (1, 6) (1, 9) NAME 'foo' (1, 10) (1, 13) OP '(' (1, 13) (1, 14) OP ')' (1, 14) (1, 15) OP ':' (1, 15) (1, 16) NEWLINE '\\n' (1, 16) (1, 17) INDENT ' ' (2, 0) (2, 2) NAME 'def' (2, 2) (2, 5) NAME 'foo' (2, 6) (2, 9) OP '(' (2, 9) (2, 10) NAME 'await' (2, 10) (2, 15) OP ')' (2, 15) (2, 16) OP ':' (2, 16) (2, 17) NEWLINE '\\n' (2, 17) (2, 18) INDENT ' ' (3, 0) (3, 4) NAME 'await' (3, 4) (3, 9) OP '=' (3, 10) (3, 11) NUMBER '1' (3, 12) (3, 13) NEWLINE '\\n' (3, 13) (3, 14) DEDENT '' (4, 2) (4, 2) NAME 'if' (4, 2) (4, 4) NUMBER '1' (4, 5) (4, 6) OP ':' (4, 6) (4, 7) NEWLINE '\\n' (4, 7) (4, 8) INDENT ' ' (5, 0) (5, 4) NAME 'await' (5, 4) (5, 9) NEWLINE '\\n' (5, 9) (5, 10) DEDENT '' (6, 0) (6, 0) DEDENT '' (6, 0) (6, 0) NAME 'async' (6, 0) (6, 5) OP '+=' (6, 6) (6, 8) NUMBER '1' (6, 9) (6, 10) NEWLINE '\\n' (6, 10) (6, 11) """) self.check_tokenize('''\ async def foo(): async for i in 1: pass''', """\ NAME 'async' (1, 0) (1, 5) NAME 'def' (1, 6) (1, 9) NAME 'foo' (1, 10) (1, 13) OP '(' (1, 13) (1, 14) OP ')' (1, 14) (1, 15) OP ':' (1, 15) (1, 16) NEWLINE '\\n' (1, 16) (1, 17) INDENT ' ' (2, 0) (2, 2) NAME 'async' (2, 2) (2, 7) NAME 'for' (2, 8) (2, 11) NAME 'i' (2, 12) (2, 13) NAME 'in' (2, 14) (2, 16) NUMBER '1' (2, 17) (2, 18) OP ':' (2, 18) (2, 19) NAME 'pass' (2, 20) (2, 24)
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_selectors.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_selectors.py
import errno import os import random import selectors import signal import socket import sys from test import support from time import sleep import unittest import unittest.mock import tempfile from time import monotonic as time try: import resource except ImportError: resource = None if hasattr(socket, 'socketpair'): socketpair = socket.socketpair else: def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): with socket.socket(family, type, proto) as l: l.bind((support.HOST, 0)) l.listen() c = socket.socket(family, type, proto) try: c.connect(l.getsockname()) caddr = c.getsockname() while True: a, addr = l.accept() # check that we've got the correct client if addr == caddr: return c, a a.close() except OSError: c.close() raise def find_ready_matching(ready, flag): match = [] for key, events in ready: if events & flag: match.append(key.fileobj) return match class BaseSelectorTestCase(unittest.TestCase): def make_socketpair(self): rd, wr = socketpair() self.addCleanup(rd.close) self.addCleanup(wr.close) return rd, wr def test_register(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ, "data") self.assertIsInstance(key, selectors.SelectorKey) self.assertEqual(key.fileobj, rd) self.assertEqual(key.fd, rd.fileno()) self.assertEqual(key.events, selectors.EVENT_READ) self.assertEqual(key.data, "data") # register an unknown event self.assertRaises(ValueError, s.register, 0, 999999) # register an invalid FD self.assertRaises(ValueError, s.register, -10, selectors.EVENT_READ) # register twice self.assertRaises(KeyError, s.register, rd, selectors.EVENT_READ) # register the same FD, but with a different object self.assertRaises(KeyError, s.register, rd.fileno(), selectors.EVENT_READ) def test_unregister(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.unregister(rd) # unregister an unknown file obj self.assertRaises(KeyError, s.unregister, 999999) # unregister twice self.assertRaises(KeyError, s.unregister, rd) def test_unregister_after_fd_close(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() r, w = rd.fileno(), wr.fileno() s.register(r, selectors.EVENT_READ) s.register(w, selectors.EVENT_WRITE) rd.close() wr.close() s.unregister(r) s.unregister(w) @unittest.skipUnless(os.name == 'posix', "requires posix") def test_unregister_after_fd_close_and_reuse(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() r, w = rd.fileno(), wr.fileno() s.register(r, selectors.EVENT_READ) s.register(w, selectors.EVENT_WRITE) rd2, wr2 = self.make_socketpair() rd.close() wr.close() os.dup2(rd2.fileno(), r) os.dup2(wr2.fileno(), w) self.addCleanup(os.close, r) self.addCleanup(os.close, w) s.unregister(r) s.unregister(w) def test_unregister_after_socket_close(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) rd.close() wr.close() s.unregister(rd) s.unregister(wr) def test_modify(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ) # modify events key2 = s.modify(rd, selectors.EVENT_WRITE) self.assertNotEqual(key.events, key2.events) self.assertEqual(key2, s.get_key(rd)) s.unregister(rd) # modify data d1 = object() d2 = object() key = s.register(rd, selectors.EVENT_READ, d1) key2 = s.modify(rd, selectors.EVENT_READ, d2) self.assertEqual(key.events, key2.events) self.assertNotEqual(key.data, key2.data) self.assertEqual(key2, s.get_key(rd)) self.assertEqual(key2.data, d2) # modify unknown file obj self.assertRaises(KeyError, s.modify, 999999, selectors.EVENT_READ) # modify use a shortcut d3 = object() s.register = unittest.mock.Mock() s.unregister = unittest.mock.Mock() s.modify(rd, selectors.EVENT_READ, d3) self.assertFalse(s.register.called) self.assertFalse(s.unregister.called) def test_modify_unregister(self): # Make sure the fd is unregister()ed in case of error on # modify(): http://bugs.python.org/issue30014 if self.SELECTOR.__name__ == 'EpollSelector': patch = unittest.mock.patch( 'selectors.EpollSelector._selector_cls') elif self.SELECTOR.__name__ == 'PollSelector': patch = unittest.mock.patch( 'selectors.PollSelector._selector_cls') elif self.SELECTOR.__name__ == 'DevpollSelector': patch = unittest.mock.patch( 'selectors.DevpollSelector._selector_cls') else: raise self.skipTest("") with patch as m: m.return_value.modify = unittest.mock.Mock( side_effect=ZeroDivisionError) s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) self.assertEqual(len(s._map), 1) with self.assertRaises(ZeroDivisionError): s.modify(rd, selectors.EVENT_WRITE) self.assertEqual(len(s._map), 0) def test_close(self): s = self.SELECTOR() self.addCleanup(s.close) mapping = s.get_map() rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) s.close() self.assertRaises(RuntimeError, s.get_key, rd) self.assertRaises(RuntimeError, s.get_key, wr) self.assertRaises(KeyError, mapping.__getitem__, rd) self.assertRaises(KeyError, mapping.__getitem__, wr) def test_get_key(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ, "data") self.assertEqual(key, s.get_key(rd)) # unknown file obj self.assertRaises(KeyError, s.get_key, 999999) def test_get_map(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() keys = s.get_map() self.assertFalse(keys) self.assertEqual(len(keys), 0) self.assertEqual(list(keys), []) key = s.register(rd, selectors.EVENT_READ, "data") self.assertIn(rd, keys) self.assertEqual(key, keys[rd]) self.assertEqual(len(keys), 1) self.assertEqual(list(keys), [rd.fileno()]) self.assertEqual(list(keys.values()), [key]) # unknown file obj with self.assertRaises(KeyError): keys[999999] # Read-only mapping with self.assertRaises(TypeError): del keys[rd] def test_select(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) wr_key = s.register(wr, selectors.EVENT_WRITE) result = s.select() for key, events in result: self.assertTrue(isinstance(key, selectors.SelectorKey)) self.assertTrue(events) self.assertFalse(events & ~(selectors.EVENT_READ | selectors.EVENT_WRITE)) self.assertEqual([(wr_key, selectors.EVENT_WRITE)], result) def test_context_manager(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() with s as sel: sel.register(rd, selectors.EVENT_READ) sel.register(wr, selectors.EVENT_WRITE) self.assertRaises(RuntimeError, s.get_key, rd) self.assertRaises(RuntimeError, s.get_key, wr) def test_fileno(self): s = self.SELECTOR() self.addCleanup(s.close) if hasattr(s, 'fileno'): fd = s.fileno() self.assertTrue(isinstance(fd, int)) self.assertGreaterEqual(fd, 0) def test_selector(self): s = self.SELECTOR() self.addCleanup(s.close) NUM_SOCKETS = 12 MSG = b" This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_SOCKETS): rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd bufs = [] while writers: ready = s.select() ready_writers = find_ready_matching(ready, selectors.EVENT_WRITE) if not ready_writers: self.fail("no sockets ready for writing") wr = random.choice(ready_writers) wr.send(MSG) for i in range(10): ready = s.select() ready_readers = find_ready_matching(ready, selectors.EVENT_READ) if ready_readers: break # there might be a delay between the write to the write end and # the read end is reported ready sleep(0.1) else: self.fail("no sockets ready for reading") self.assertEqual([w2r[wr]], ready_readers) rd = ready_readers[0] buf = rd.recv(MSG_LEN) self.assertEqual(len(buf), MSG_LEN) bufs.append(buf) s.unregister(r2w[rd]) s.unregister(rd) writers.remove(r2w[rd]) self.assertEqual(bufs, [MSG] * NUM_SOCKETS) @unittest.skipIf(sys.platform == 'win32', 'select.select() cannot be used with empty fd sets') def test_empty_select(self): # Issue #23009: Make sure EpollSelector.select() works when no FD is # registered. s = self.SELECTOR() self.addCleanup(s.close) self.assertEqual(s.select(timeout=0), []) def test_timeout(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(wr, selectors.EVENT_WRITE) t = time() self.assertEqual(1, len(s.select(0))) self.assertEqual(1, len(s.select(-1))) self.assertLess(time() - t, 0.5) s.unregister(wr) s.register(rd, selectors.EVENT_READ) t = time() self.assertFalse(s.select(0)) self.assertFalse(s.select(-1)) self.assertLess(time() - t, 0.5) t0 = time() self.assertFalse(s.select(1)) t1 = time() dt = t1 - t0 # Tolerate 2.0 seconds for very slow buildbots self.assertTrue(0.8 <= dt <= 2.0, dt) @unittest.skipUnless(hasattr(signal, "alarm"), "signal.alarm() required for this test") def test_select_interrupt_exc(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() class InterruptSelect(Exception): pass def handler(*args): raise InterruptSelect orig_alrm_handler = signal.signal(signal.SIGALRM, handler) self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) try: signal.alarm(1) s.register(rd, selectors.EVENT_READ) t = time() # select() is interrupted by a signal which raises an exception with self.assertRaises(InterruptSelect): s.select(30) # select() was interrupted before the timeout of 30 seconds self.assertLess(time() - t, 5.0) finally: signal.alarm(0) @unittest.skipUnless(hasattr(signal, "alarm"), "signal.alarm() required for this test") def test_select_interrupt_noraise(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() orig_alrm_handler = signal.signal(signal.SIGALRM, lambda *args: None) self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) try: signal.alarm(1) s.register(rd, selectors.EVENT_READ) t = time() # select() is interrupted by a signal, but the signal handler doesn't # raise an exception, so select() should by retries with a recomputed # timeout self.assertFalse(s.select(1.5)) self.assertGreaterEqual(time() - t, 1.0) finally: signal.alarm(0) class ScalableSelectorMixIn: # see issue #18963 for why it's skipped on older OS X versions @support.requires_mac_ver(10, 5) @unittest.skipUnless(resource, "Test needs resource module") def test_above_fd_setsize(self): # A scalable implementation should have no problem with more than # FD_SETSIZE file descriptors. Since we don't know the value, we just # try to set the soft RLIMIT_NOFILE to the hard RLIMIT_NOFILE ceiling. soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) try: resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard)) self.addCleanup(resource.setrlimit, resource.RLIMIT_NOFILE, (soft, hard)) NUM_FDS = min(hard, 2**16) except (OSError, ValueError): NUM_FDS = soft # guard for already allocated FDs (stdin, stdout...) NUM_FDS -= 32 s = self.SELECTOR() self.addCleanup(s.close) for i in range(NUM_FDS // 2): try: rd, wr = self.make_socketpair() except OSError: # too many FDs, skip - note that we should only catch EMFILE # here, but apparently *BSD and Solaris can fail upon connect() # or bind() with EADDRNOTAVAIL, so let's be safe self.skipTest("FD limit reached") try: s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) except OSError as e: if e.errno == errno.ENOSPC: # this can be raised by epoll if we go over # fs.epoll.max_user_watches sysctl self.skipTest("FD limit reached") raise try: fds = s.select() except OSError as e: if e.errno == errno.EINVAL and sys.platform == 'darwin': # unexplainable errors on macOS don't need to fail the test self.skipTest("Invalid argument error calling poll()") raise self.assertEqual(NUM_FDS // 2, len(fds)) class DefaultSelectorTestCase(BaseSelectorTestCase): SELECTOR = selectors.DefaultSelector class SelectSelectorTestCase(BaseSelectorTestCase): SELECTOR = selectors.SelectSelector @unittest.skipUnless(hasattr(selectors, 'PollSelector'), "Test needs selectors.PollSelector") class PollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'PollSelector', None) @unittest.skipUnless(hasattr(selectors, 'EpollSelector'), "Test needs selectors.EpollSelector") class EpollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'EpollSelector', None) def test_register_file(self): # epoll(7) returns EPERM when given a file to watch s = self.SELECTOR() with tempfile.NamedTemporaryFile() as f: with self.assertRaises(IOError): s.register(f, selectors.EVENT_READ) # the SelectorKey has been removed with self.assertRaises(KeyError): s.get_key(f) @unittest.skipUnless(hasattr(selectors, 'KqueueSelector'), "Test needs selectors.KqueueSelector)") class KqueueSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'KqueueSelector', None) def test_register_bad_fd(self): # a file descriptor that's been closed should raise an OSError # with EBADF s = self.SELECTOR() bad_f = support.make_bad_fd() with self.assertRaises(OSError) as cm: s.register(bad_f, selectors.EVENT_READ) self.assertEqual(cm.exception.errno, errno.EBADF) # the SelectorKey has been removed with self.assertRaises(KeyError): s.get_key(bad_f) @unittest.skipUnless(hasattr(selectors, 'DevpollSelector'), "Test needs selectors.DevpollSelector") class DevpollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'DevpollSelector', None) def test_main(): tests = [DefaultSelectorTestCase, SelectSelectorTestCase, PollSelectorTestCase, EpollSelectorTestCase, KqueueSelectorTestCase, DevpollSelectorTestCase] support.run_unittest(*tests) 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_utf8_mode.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_utf8_mode.py
""" Test the implementation of the PEP 540: the UTF-8 Mode. """ import locale import os import sys import textwrap import unittest from test import support from test.support.script_helper import assert_python_ok, assert_python_failure MS_WINDOWS = (sys.platform == 'win32') POSIX_LOCALES = ('C', 'POSIX') class UTF8ModeTests(unittest.TestCase): DEFAULT_ENV = { 'PYTHONUTF8': '', 'PYTHONLEGACYWINDOWSFSENCODING': '', 'PYTHONCOERCECLOCALE': '0', } def posix_locale(self): loc = locale.setlocale(locale.LC_CTYPE, None) return (loc in POSIX_LOCALES) def get_output(self, *args, failure=False, **kw): kw = dict(self.DEFAULT_ENV, **kw) if failure: out = assert_python_failure(*args, **kw) out = out[2] else: out = assert_python_ok(*args, **kw) out = out[1] return out.decode().rstrip("\n\r") @unittest.skipIf(MS_WINDOWS, 'Windows has no POSIX locale') def test_posix_locale(self): code = 'import sys; print(sys.flags.utf8_mode)' for loc in POSIX_LOCALES: with self.subTest(LC_ALL=loc): out = self.get_output('-c', code, LC_ALL=loc) self.assertEqual(out, '1') def test_xoption(self): code = 'import sys; print(sys.flags.utf8_mode)' out = self.get_output('-X', 'utf8', '-c', code) self.assertEqual(out, '1') # undocumented but accepted syntax: -X utf8=1 out = self.get_output('-X', 'utf8=1', '-c', code) self.assertEqual(out, '1') out = self.get_output('-X', 'utf8=0', '-c', code) self.assertEqual(out, '0') if MS_WINDOWS: # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 Mode # and has the priority over -X utf8 out = self.get_output('-X', 'utf8', '-c', code, PYTHONLEGACYWINDOWSFSENCODING='1') self.assertEqual(out, '0') def test_env_var(self): code = 'import sys; print(sys.flags.utf8_mode)' out = self.get_output('-c', code, PYTHONUTF8='1') self.assertEqual(out, '1') out = self.get_output('-c', code, PYTHONUTF8='0') self.assertEqual(out, '0') # -X utf8 has the priority over PYTHONUTF8 out = self.get_output('-X', 'utf8=0', '-c', code, PYTHONUTF8='1') self.assertEqual(out, '0') if MS_WINDOWS: # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode # and has the priority over PYTHONUTF8 out = self.get_output('-X', 'utf8', '-c', code, PYTHONUTF8='1', PYTHONLEGACYWINDOWSFSENCODING='1') self.assertEqual(out, '0') # Cannot test with the POSIX locale, since the POSIX locale enables # the UTF-8 mode if not self.posix_locale(): # PYTHONUTF8 should be ignored if -E is used out = self.get_output('-E', '-c', code, PYTHONUTF8='1') self.assertEqual(out, '0') # invalid mode out = self.get_output('-c', code, PYTHONUTF8='xxx', failure=True) self.assertIn('invalid PYTHONUTF8 environment variable value', out.rstrip()) def test_filesystemencoding(self): code = textwrap.dedent(''' import sys print("{}/{}".format(sys.getfilesystemencoding(), sys.getfilesystemencodeerrors())) ''') if MS_WINDOWS: expected = 'utf-8/surrogatepass' else: expected = 'utf-8/surrogateescape' out = self.get_output('-X', 'utf8', '-c', code) self.assertEqual(out, expected) if MS_WINDOWS: # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode # and has the priority over -X utf8 and PYTHONUTF8 out = self.get_output('-X', 'utf8', '-c', code, PYTHONUTF8='strict', PYTHONLEGACYWINDOWSFSENCODING='1') self.assertEqual(out, 'mbcs/replace') def test_stdio(self): code = textwrap.dedent(''' import sys print(f"stdin: {sys.stdin.encoding}/{sys.stdin.errors}") print(f"stdout: {sys.stdout.encoding}/{sys.stdout.errors}") print(f"stderr: {sys.stderr.encoding}/{sys.stderr.errors}") ''') out = self.get_output('-X', 'utf8', '-c', code, PYTHONIOENCODING='') self.assertEqual(out.splitlines(), ['stdin: utf-8/surrogateescape', 'stdout: utf-8/surrogateescape', 'stderr: utf-8/backslashreplace']) # PYTHONIOENCODING has the priority over PYTHONUTF8 out = self.get_output('-X', 'utf8', '-c', code, PYTHONIOENCODING="latin1") self.assertEqual(out.splitlines(), ['stdin: latin1/strict', 'stdout: latin1/strict', 'stderr: latin1/backslashreplace']) out = self.get_output('-X', 'utf8', '-c', code, PYTHONIOENCODING=":namereplace") self.assertEqual(out.splitlines(), ['stdin: utf-8/namereplace', 'stdout: utf-8/namereplace', 'stderr: utf-8/backslashreplace']) def test_io(self): code = textwrap.dedent(''' import sys filename = sys.argv[1] with open(filename) as fp: print(f"{fp.encoding}/{fp.errors}") ''') filename = __file__ out = self.get_output('-c', code, filename, PYTHONUTF8='1') self.assertEqual(out, 'UTF-8/strict') def _check_io_encoding(self, module, encoding=None, errors=None): filename = __file__ # Encoding explicitly set args = [] if encoding: args.append(f'encoding={encoding!r}') if errors: args.append(f'errors={errors!r}') code = textwrap.dedent(''' import sys from %s import open filename = sys.argv[1] with open(filename, %s) as fp: print(f"{fp.encoding}/{fp.errors}") ''') % (module, ', '.join(args)) out = self.get_output('-c', code, filename, PYTHONUTF8='1') if not encoding: encoding = 'UTF-8' if not errors: errors = 'strict' self.assertEqual(out, f'{encoding}/{errors}') def check_io_encoding(self, module): self._check_io_encoding(module, encoding="latin1") self._check_io_encoding(module, errors="namereplace") self._check_io_encoding(module, encoding="latin1", errors="namereplace") def test_io_encoding(self): self.check_io_encoding('io') def test_io_encoding(self): self.check_io_encoding('_pyio') def test_locale_getpreferredencoding(self): code = 'import locale; print(locale.getpreferredencoding(False), locale.getpreferredencoding(True))' out = self.get_output('-X', 'utf8', '-c', code) self.assertEqual(out, 'UTF-8 UTF-8') for loc in POSIX_LOCALES: with self.subTest(LC_ALL=loc): out = self.get_output('-X', 'utf8', '-c', code, LC_ALL=loc) self.assertEqual(out, 'UTF-8 UTF-8') @unittest.skipIf(MS_WINDOWS, 'test specific to Unix') def test_cmd_line(self): arg = 'h\xe9\u20ac'.encode('utf-8') arg_utf8 = arg.decode('utf-8') arg_ascii = arg.decode('ascii', 'surrogateescape') code = 'import locale, sys; print("%s:%s" % (locale.getpreferredencoding(), ascii(sys.argv[1:])))' def check(utf8_opt, expected, **kw): out = self.get_output('-X', utf8_opt, '-c', code, arg, **kw) args = out.partition(':')[2].rstrip() self.assertEqual(args, ascii(expected), out) check('utf8', [arg_utf8]) for loc in POSIX_LOCALES: with self.subTest(LC_ALL=loc): check('utf8', [arg_utf8], LC_ALL=loc) if sys.platform == 'darwin' or support.is_android: c_arg = arg_utf8 elif sys.platform.startswith("aix"): c_arg = arg.decode('iso-8859-1') else: c_arg = arg_ascii for loc in POSIX_LOCALES: with self.subTest(LC_ALL=loc): check('utf8=0', [c_arg], LC_ALL=loc) def test_optim_level(self): # CPython: check that Py_Main() doesn't increment Py_OptimizeFlag # twice when -X utf8 requires to parse the configuration twice (when # the encoding changes after reading the configuration, the # configuration is read again with the new encoding). code = 'import sys; print(sys.flags.optimize)' out = self.get_output('-X', 'utf8', '-O', '-c', code) self.assertEqual(out, '1') out = self.get_output('-X', 'utf8', '-OO', '-c', code) self.assertEqual(out, '2') code = 'import sys; print(sys.flags.ignore_environment)' out = self.get_output('-X', 'utf8', '-E', '-c', code) self.assertEqual(out, '1') 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_urlparse.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urlparse.py
import sys import unicodedata import unittest import urllib.parse RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" RFC3986_BASE = 'http://a/b/c/d;p?q' SIMPLE_BASE = 'http://a/b/c/d' # Each parse_qsl testcase is a two-tuple that contains # a string with the query and a list with the expected result. parse_qsl_test_cases = [ ("", []), ("&", []), ("&&", []), ("=", [('', '')]), ("=a", [('', 'a')]), ("a", [('a', '')]), ("a=", [('a', '')]), ("&a=b", [('a', 'b')]), ("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]), ("a=1&a=2", [('a', '1'), ('a', '2')]), (b"", []), (b"&", []), (b"&&", []), (b"=", [(b'', b'')]), (b"=a", [(b'', b'a')]), (b"a", [(b'a', b'')]), (b"a=", [(b'a', b'')]), (b"&a=b", [(b'a', b'b')]), (b"a=a+b&b=b+c", [(b'a', b'a b'), (b'b', b'b c')]), (b"a=1&a=2", [(b'a', b'1'), (b'a', b'2')]), (";", []), (";;", []), (";a=b", [('a', 'b')]), ("a=a+b;b=b+c", [('a', 'a b'), ('b', 'b c')]), ("a=1;a=2", [('a', '1'), ('a', '2')]), (b";", []), (b";;", []), (b";a=b", [(b'a', b'b')]), (b"a=a+b;b=b+c", [(b'a', b'a b'), (b'b', b'b c')]), (b"a=1;a=2", [(b'a', b'1'), (b'a', b'2')]), ] # Each parse_qs testcase is a two-tuple that contains # a string with the query and a dictionary with the expected result. parse_qs_test_cases = [ ("", {}), ("&", {}), ("&&", {}), ("=", {'': ['']}), ("=a", {'': ['a']}), ("a", {'a': ['']}), ("a=", {'a': ['']}), ("&a=b", {'a': ['b']}), ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}), ("a=1&a=2", {'a': ['1', '2']}), (b"", {}), (b"&", {}), (b"&&", {}), (b"=", {b'': [b'']}), (b"=a", {b'': [b'a']}), (b"a", {b'a': [b'']}), (b"a=", {b'a': [b'']}), (b"&a=b", {b'a': [b'b']}), (b"a=a+b&b=b+c", {b'a': [b'a b'], b'b': [b'b c']}), (b"a=1&a=2", {b'a': [b'1', b'2']}), (";", {}), (";;", {}), (";a=b", {'a': ['b']}), ("a=a+b;b=b+c", {'a': ['a b'], 'b': ['b c']}), ("a=1;a=2", {'a': ['1', '2']}), (b";", {}), (b";;", {}), (b";a=b", {b'a': [b'b']}), (b"a=a+b;b=b+c", {b'a': [b'a b'], b'b': [b'b c']}), (b"a=1;a=2", {b'a': [b'1', b'2']}), ] class UrlParseTestCase(unittest.TestCase): def checkRoundtrips(self, url, parsed, split): result = urllib.parse.urlparse(url) self.assertEqual(result, parsed) t = (result.scheme, result.netloc, result.path, result.params, result.query, result.fragment) self.assertEqual(t, parsed) # put it back together and it should be the same result2 = urllib.parse.urlunparse(result) self.assertEqual(result2, url) self.assertEqual(result2, result.geturl()) # the result of geturl() is a fixpoint; we can always parse it # again to get the same result: result3 = urllib.parse.urlparse(result.geturl()) self.assertEqual(result3.geturl(), result.geturl()) self.assertEqual(result3, result) self.assertEqual(result3.scheme, result.scheme) self.assertEqual(result3.netloc, result.netloc) self.assertEqual(result3.path, result.path) self.assertEqual(result3.params, result.params) self.assertEqual(result3.query, result.query) self.assertEqual(result3.fragment, result.fragment) self.assertEqual(result3.username, result.username) self.assertEqual(result3.password, result.password) self.assertEqual(result3.hostname, result.hostname) self.assertEqual(result3.port, result.port) # check the roundtrip using urlsplit() as well result = urllib.parse.urlsplit(url) self.assertEqual(result, split) t = (result.scheme, result.netloc, result.path, result.query, result.fragment) self.assertEqual(t, split) result2 = urllib.parse.urlunsplit(result) self.assertEqual(result2, url) self.assertEqual(result2, result.geturl()) # check the fixpoint property of re-parsing the result of geturl() result3 = urllib.parse.urlsplit(result.geturl()) self.assertEqual(result3.geturl(), result.geturl()) self.assertEqual(result3, result) self.assertEqual(result3.scheme, result.scheme) self.assertEqual(result3.netloc, result.netloc) self.assertEqual(result3.path, result.path) self.assertEqual(result3.query, result.query) self.assertEqual(result3.fragment, result.fragment) self.assertEqual(result3.username, result.username) self.assertEqual(result3.password, result.password) self.assertEqual(result3.hostname, result.hostname) self.assertEqual(result3.port, result.port) def test_qsl(self): for orig, expect in parse_qsl_test_cases: result = urllib.parse.parse_qsl(orig, keep_blank_values=True) self.assertEqual(result, expect, "Error parsing %r" % orig) expect_without_blanks = [v for v in expect if len(v[1])] result = urllib.parse.parse_qsl(orig, keep_blank_values=False) self.assertEqual(result, expect_without_blanks, "Error parsing %r" % orig) def test_qs(self): for orig, expect in parse_qs_test_cases: result = urllib.parse.parse_qs(orig, keep_blank_values=True) self.assertEqual(result, expect, "Error parsing %r" % orig) expect_without_blanks = {v: expect[v] for v in expect if len(expect[v][0])} result = urllib.parse.parse_qs(orig, keep_blank_values=False) self.assertEqual(result, expect_without_blanks, "Error parsing %r" % orig) def test_roundtrips(self): str_cases = [ ('file:///tmp/junk.txt', ('file', '', '/tmp/junk.txt', '', '', ''), ('file', '', '/tmp/junk.txt', '', '')), ('imap://mail.python.org/mbox1', ('imap', 'mail.python.org', '/mbox1', '', '', ''), ('imap', 'mail.python.org', '/mbox1', '', '')), ('mms://wms.sys.hinet.net/cts/Drama/09006251100.asf', ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', '', '', ''), ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', '', '')), ('nfs://server/path/to/file.txt', ('nfs', 'server', '/path/to/file.txt', '', '', ''), ('nfs', 'server', '/path/to/file.txt', '', '')), ('svn+ssh://svn.zope.org/repos/main/ZConfig/trunk/', ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '')), ('git+ssh://git@github.com/user/project.git', ('git+ssh', 'git@github.com','/user/project.git', '','',''), ('git+ssh', 'git@github.com','/user/project.git', '', '')), ] def _encode(t): return (t[0].encode('ascii'), tuple(x.encode('ascii') for x in t[1]), tuple(x.encode('ascii') for x in t[2])) bytes_cases = [_encode(x) for x in str_cases] for url, parsed, split in str_cases + bytes_cases: self.checkRoundtrips(url, parsed, split) def test_http_roundtrips(self): # urllib.parse.urlsplit treats 'http:' as an optimized special case, # so we test both 'http:' and 'https:' in all the following. # Three cheers for white box knowledge! str_cases = [ ('://www.python.org', ('www.python.org', '', '', '', ''), ('www.python.org', '', '', '')), ('://www.python.org#abc', ('www.python.org', '', '', '', 'abc'), ('www.python.org', '', '', 'abc')), ('://www.python.org?q=abc', ('www.python.org', '', '', 'q=abc', ''), ('www.python.org', '', 'q=abc', '')), ('://www.python.org/#abc', ('www.python.org', '/', '', '', 'abc'), ('www.python.org', '/', '', 'abc')), ('://a/b/c/d;p?q#f', ('a', '/b/c/d', 'p', 'q', 'f'), ('a', '/b/c/d;p', 'q', 'f')), ] def _encode(t): return (t[0].encode('ascii'), tuple(x.encode('ascii') for x in t[1]), tuple(x.encode('ascii') for x in t[2])) bytes_cases = [_encode(x) for x in str_cases] str_schemes = ('http', 'https') bytes_schemes = (b'http', b'https') str_tests = str_schemes, str_cases bytes_tests = bytes_schemes, bytes_cases for schemes, test_cases in (str_tests, bytes_tests): for scheme in schemes: for url, parsed, split in test_cases: url = scheme + url parsed = (scheme,) + parsed split = (scheme,) + split self.checkRoundtrips(url, parsed, split) def checkJoin(self, base, relurl, expected): str_components = (base, relurl, expected) self.assertEqual(urllib.parse.urljoin(base, relurl), expected) bytes_components = baseb, relurlb, expectedb = [ x.encode('ascii') for x in str_components] self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb) def test_unparse_parse(self): str_cases = ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',] bytes_cases = [x.encode('ascii') for x in str_cases] for u in str_cases + bytes_cases: self.assertEqual(urllib.parse.urlunsplit(urllib.parse.urlsplit(u)), u) self.assertEqual(urllib.parse.urlunparse(urllib.parse.urlparse(u)), u) def test_RFC1808(self): # "normal" cases from RFC 1808: self.checkJoin(RFC1808_BASE, 'g:h', 'g:h') self.checkJoin(RFC1808_BASE, 'g', 'http://a/b/c/g') self.checkJoin(RFC1808_BASE, './g', 'http://a/b/c/g') self.checkJoin(RFC1808_BASE, 'g/', 'http://a/b/c/g/') self.checkJoin(RFC1808_BASE, '/g', 'http://a/g') self.checkJoin(RFC1808_BASE, '//g', 'http://g') self.checkJoin(RFC1808_BASE, 'g?y', 'http://a/b/c/g?y') self.checkJoin(RFC1808_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x') self.checkJoin(RFC1808_BASE, '#s', 'http://a/b/c/d;p?q#s') self.checkJoin(RFC1808_BASE, 'g#s', 'http://a/b/c/g#s') self.checkJoin(RFC1808_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC1808_BASE, 'g?y#s', 'http://a/b/c/g?y#s') self.checkJoin(RFC1808_BASE, 'g;x', 'http://a/b/c/g;x') self.checkJoin(RFC1808_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s') self.checkJoin(RFC1808_BASE, '.', 'http://a/b/c/') self.checkJoin(RFC1808_BASE, './', 'http://a/b/c/') self.checkJoin(RFC1808_BASE, '..', 'http://a/b/') self.checkJoin(RFC1808_BASE, '../', 'http://a/b/') self.checkJoin(RFC1808_BASE, '../g', 'http://a/b/g') self.checkJoin(RFC1808_BASE, '../..', 'http://a/') self.checkJoin(RFC1808_BASE, '../../', 'http://a/') self.checkJoin(RFC1808_BASE, '../../g', 'http://a/g') # "abnormal" cases from RFC 1808: self.checkJoin(RFC1808_BASE, '', 'http://a/b/c/d;p?q#f') self.checkJoin(RFC1808_BASE, 'g.', 'http://a/b/c/g.') self.checkJoin(RFC1808_BASE, '.g', 'http://a/b/c/.g') self.checkJoin(RFC1808_BASE, 'g..', 'http://a/b/c/g..') self.checkJoin(RFC1808_BASE, '..g', 'http://a/b/c/..g') self.checkJoin(RFC1808_BASE, './../g', 'http://a/b/g') self.checkJoin(RFC1808_BASE, './g/.', 'http://a/b/c/g/') self.checkJoin(RFC1808_BASE, 'g/./h', 'http://a/b/c/g/h') self.checkJoin(RFC1808_BASE, 'g/../h', 'http://a/b/c/h') # RFC 1808 and RFC 1630 disagree on these (according to RFC 1808), # so we'll not actually run these tests (which expect 1808 behavior). #self.checkJoin(RFC1808_BASE, 'http:g', 'http:g') #self.checkJoin(RFC1808_BASE, 'http:', 'http:') # XXX: The following tests are no longer compatible with RFC3986 # self.checkJoin(RFC1808_BASE, '../../../g', 'http://a/../g') # self.checkJoin(RFC1808_BASE, '../../../../g', 'http://a/../../g') # self.checkJoin(RFC1808_BASE, '/./g', 'http://a/./g') # self.checkJoin(RFC1808_BASE, '/../g', 'http://a/../g') def test_RFC2368(self): # Issue 11467: path that starts with a number is not parsed correctly self.assertEqual(urllib.parse.urlparse('mailto:1337@example.org'), ('mailto', '', '1337@example.org', '', '', '')) def test_RFC2396(self): # cases from RFC 2396 self.checkJoin(RFC2396_BASE, 'g:h', 'g:h') self.checkJoin(RFC2396_BASE, 'g', 'http://a/b/c/g') self.checkJoin(RFC2396_BASE, './g', 'http://a/b/c/g') self.checkJoin(RFC2396_BASE, 'g/', 'http://a/b/c/g/') self.checkJoin(RFC2396_BASE, '/g', 'http://a/g') self.checkJoin(RFC2396_BASE, '//g', 'http://g') self.checkJoin(RFC2396_BASE, 'g?y', 'http://a/b/c/g?y') self.checkJoin(RFC2396_BASE, '#s', 'http://a/b/c/d;p?q#s') self.checkJoin(RFC2396_BASE, 'g#s', 'http://a/b/c/g#s') self.checkJoin(RFC2396_BASE, 'g?y#s', 'http://a/b/c/g?y#s') self.checkJoin(RFC2396_BASE, 'g;x', 'http://a/b/c/g;x') self.checkJoin(RFC2396_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s') self.checkJoin(RFC2396_BASE, '.', 'http://a/b/c/') self.checkJoin(RFC2396_BASE, './', 'http://a/b/c/') self.checkJoin(RFC2396_BASE, '..', 'http://a/b/') self.checkJoin(RFC2396_BASE, '../', 'http://a/b/') self.checkJoin(RFC2396_BASE, '../g', 'http://a/b/g') self.checkJoin(RFC2396_BASE, '../..', 'http://a/') self.checkJoin(RFC2396_BASE, '../../', 'http://a/') self.checkJoin(RFC2396_BASE, '../../g', 'http://a/g') self.checkJoin(RFC2396_BASE, '', RFC2396_BASE) self.checkJoin(RFC2396_BASE, 'g.', 'http://a/b/c/g.') self.checkJoin(RFC2396_BASE, '.g', 'http://a/b/c/.g') self.checkJoin(RFC2396_BASE, 'g..', 'http://a/b/c/g..') self.checkJoin(RFC2396_BASE, '..g', 'http://a/b/c/..g') self.checkJoin(RFC2396_BASE, './../g', 'http://a/b/g') self.checkJoin(RFC2396_BASE, './g/.', 'http://a/b/c/g/') self.checkJoin(RFC2396_BASE, 'g/./h', 'http://a/b/c/g/h') self.checkJoin(RFC2396_BASE, 'g/../h', 'http://a/b/c/h') self.checkJoin(RFC2396_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y') self.checkJoin(RFC2396_BASE, 'g;x=1/../y', 'http://a/b/c/y') self.checkJoin(RFC2396_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x') self.checkJoin(RFC2396_BASE, 'g?y/../x', 'http://a/b/c/g?y/../x') self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') # XXX: The following tests are no longer compatible with RFC3986 # self.checkJoin(RFC2396_BASE, '../../../g', 'http://a/../g') # self.checkJoin(RFC2396_BASE, '../../../../g', 'http://a/../../g') # self.checkJoin(RFC2396_BASE, '/./g', 'http://a/./g') # self.checkJoin(RFC2396_BASE, '/../g', 'http://a/../g') def test_RFC3986(self): self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC3986_BASE, ';x', 'http://a/b/c/;x') self.checkJoin(RFC3986_BASE, 'g:h','g:h') self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') self.checkJoin(RFC3986_BASE, '/g','http://a/g') self.checkJoin(RFC3986_BASE, '//g','http://g') self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') self.checkJoin(RFC3986_BASE, './','http://a/b/c/') self.checkJoin(RFC3986_BASE, '..','http://a/b/') self.checkJoin(RFC3986_BASE, '../','http://a/b/') self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') self.checkJoin(RFC3986_BASE, '../..','http://a/') self.checkJoin(RFC3986_BASE, '../../','http://a/') self.checkJoin(RFC3986_BASE, '../../g','http://a/g') self.checkJoin(RFC3986_BASE, '../../../g', 'http://a/g') # Abnormal Examples # The 'abnormal scenarios' are incompatible with RFC2986 parsing # Tests are here for reference. self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') self.checkJoin(RFC3986_BASE, '/./g','http://a/g') self.checkJoin(RFC3986_BASE, '/../g','http://a/g') self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser # Test for issue9721 self.checkJoin('http://a/b/c/de', ';x','http://a/b/c/;x') def test_urljoins(self): self.checkJoin(SIMPLE_BASE, 'g:h','g:h') self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g') self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d') self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g') self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g') self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/') self.checkJoin(SIMPLE_BASE, '/g','http://a/g') self.checkJoin(SIMPLE_BASE, '//g','http://g') self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y') self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y') self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x') self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/') self.checkJoin(SIMPLE_BASE, './','http://a/b/c/') self.checkJoin(SIMPLE_BASE, '..','http://a/b/') self.checkJoin(SIMPLE_BASE, '../','http://a/b/') self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g') self.checkJoin(SIMPLE_BASE, '../..','http://a/') self.checkJoin(SIMPLE_BASE, '../../g','http://a/g') self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g') self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/') self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h') self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h') self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g') self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d') self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y') self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y') self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x') self.checkJoin('http:///', '..','http:///') self.checkJoin('', 'http://a/b/c/g?y/./x','http://a/b/c/g?y/./x') self.checkJoin('', 'http://a/./g', 'http://a/./g') self.checkJoin('svn://pathtorepo/dir1', 'dir2', 'svn://pathtorepo/dir2') self.checkJoin('svn+ssh://pathtorepo/dir1', 'dir2', 'svn+ssh://pathtorepo/dir2') self.checkJoin('ws://a/b','g','ws://a/g') self.checkJoin('wss://a/b','g','wss://a/g') # XXX: The following tests are no longer compatible with RFC3986 # self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g') # self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g') # test for issue22118 duplicate slashes self.checkJoin(SIMPLE_BASE + '/', 'foo', SIMPLE_BASE + '/foo') # Non-RFC-defined tests, covering variations of base and trailing # slashes self.checkJoin('http://a/b/c/d/e/', '../../f/g/', 'http://a/b/c/f/g/') self.checkJoin('http://a/b/c/d/e', '../../f/g/', 'http://a/b/f/g/') self.checkJoin('http://a/b/c/d/e/', '/../../f/g/', 'http://a/f/g/') self.checkJoin('http://a/b/c/d/e', '/../../f/g/', 'http://a/f/g/') self.checkJoin('http://a/b/c/d/e/', '../../f/g', 'http://a/b/c/f/g') self.checkJoin('http://a/b/', '../../f/g/', 'http://a/f/g/') # issue 23703: don't duplicate filename self.checkJoin('a', 'b', 'b') def test_RFC2732(self): str_cases = [ ('http://Test.python.org:5432/foo/', 'test.python.org', 5432), ('http://12.34.56.78:5432/foo/', '12.34.56.78', 5432), ('http://[::1]:5432/foo/', '::1', 5432), ('http://[dead:beef::1]:5432/foo/', 'dead:beef::1', 5432), ('http://[dead:beef::]:5432/foo/', 'dead:beef::', 5432), ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:5432/foo/', 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', 5432), ('http://[::12.34.56.78]:5432/foo/', '::12.34.56.78', 5432), ('http://[::ffff:12.34.56.78]:5432/foo/', '::ffff:12.34.56.78', 5432), ('http://Test.python.org/foo/', 'test.python.org', None), ('http://12.34.56.78/foo/', '12.34.56.78', None), ('http://[::1]/foo/', '::1', None), ('http://[dead:beef::1]/foo/', 'dead:beef::1', None), ('http://[dead:beef::]/foo/', 'dead:beef::', None), ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/', 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None), ('http://[::12.34.56.78]/foo/', '::12.34.56.78', None), ('http://[::ffff:12.34.56.78]/foo/', '::ffff:12.34.56.78', None), ('http://Test.python.org:/foo/', 'test.python.org', None), ('http://12.34.56.78:/foo/', '12.34.56.78', None), ('http://[::1]:/foo/', '::1', None), ('http://[dead:beef::1]:/foo/', 'dead:beef::1', None), ('http://[dead:beef::]:/foo/', 'dead:beef::', None), ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:/foo/', 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None), ('http://[::12.34.56.78]:/foo/', '::12.34.56.78', None), ('http://[::ffff:12.34.56.78]:/foo/', '::ffff:12.34.56.78', None), ] def _encode(t): return t[0].encode('ascii'), t[1].encode('ascii'), t[2] bytes_cases = [_encode(x) for x in str_cases] for url, hostname, port in str_cases + bytes_cases: urlparsed = urllib.parse.urlparse(url) self.assertEqual((urlparsed.hostname, urlparsed.port) , (hostname, port)) str_cases = [ 'http://::12.34.56.78]/', 'http://[::1/foo/', 'ftp://[::1/foo/bad]/bad', 'http://[::1/foo/bad]/bad', 'http://[::ffff:12.34.56.78'] bytes_cases = [x.encode('ascii') for x in str_cases] for invalid_url in str_cases + bytes_cases: self.assertRaises(ValueError, urllib.parse.urlparse, invalid_url) def test_urldefrag(self): str_cases = [ ('http://python.org#frag', 'http://python.org', 'frag'), ('http://python.org', 'http://python.org', ''), ('http://python.org/#frag', 'http://python.org/', 'frag'), ('http://python.org/', 'http://python.org/', ''), ('http://python.org/?q#frag', 'http://python.org/?q', 'frag'), ('http://python.org/?q', 'http://python.org/?q', ''), ('http://python.org/p#frag', 'http://python.org/p', 'frag'), ('http://python.org/p?q', 'http://python.org/p?q', ''), (RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'), (RFC2396_BASE, 'http://a/b/c/d;p?q', ''), ] def _encode(t): return type(t)(x.encode('ascii') for x in t) bytes_cases = [_encode(x) for x in str_cases] for url, defrag, frag in str_cases + bytes_cases: result = urllib.parse.urldefrag(url) self.assertEqual(result.geturl(), url) self.assertEqual(result, (defrag, frag)) self.assertEqual(result.url, defrag) self.assertEqual(result.fragment, frag) def test_urlsplit_scoped_IPv6(self): p = urllib.parse.urlsplit('http://[FE80::822a:a8ff:fe49:470c%tESt]:1234') self.assertEqual(p.hostname, "fe80::822a:a8ff:fe49:470c%tESt") self.assertEqual(p.netloc, '[FE80::822a:a8ff:fe49:470c%tESt]:1234') p = urllib.parse.urlsplit(b'http://[FE80::822a:a8ff:fe49:470c%tESt]:1234') self.assertEqual(p.hostname, b"fe80::822a:a8ff:fe49:470c%tESt") self.assertEqual(p.netloc, b'[FE80::822a:a8ff:fe49:470c%tESt]:1234') def test_urlsplit_attributes(self): url = "HTTP://WWW.PYTHON.ORG/doc/#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, "http") self.assertEqual(p.netloc, "WWW.PYTHON.ORG") self.assertEqual(p.path, "/doc/") self.assertEqual(p.query, "") self.assertEqual(p.fragment, "frag") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, "www.python.org") self.assertEqual(p.port, None) # geturl() won't return exactly the original URL in this case # since the scheme is always case-normalized # We handle this by ignoring the first 4 characters of the URL self.assertEqual(p.geturl()[4:], url[4:]) url = "http://User:Pass@www.python.org:080/doc/?query=yes#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, "http") self.assertEqual(p.netloc, "User:Pass@www.python.org:080") self.assertEqual(p.path, "/doc/") self.assertEqual(p.query, "query=yes") self.assertEqual(p.fragment, "frag") self.assertEqual(p.username, "User") self.assertEqual(p.password, "Pass") self.assertEqual(p.hostname, "www.python.org") self.assertEqual(p.port, 80) self.assertEqual(p.geturl(), url) # Addressing issue1698, which suggests Username can contain # "@" characters. Though not RFC compliant, many ftp sites allow # and request email addresses as usernames. url = "http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, "http") self.assertEqual(p.netloc, "User@example.com:Pass@www.python.org:080") self.assertEqual(p.path, "/doc/") self.assertEqual(p.query, "query=yes") self.assertEqual(p.fragment, "frag") self.assertEqual(p.username, "User@example.com") self.assertEqual(p.password, "Pass") self.assertEqual(p.hostname, "www.python.org") self.assertEqual(p.port, 80) self.assertEqual(p.geturl(), url) # And check them all again, only with bytes this time url = b"HTTP://WWW.PYTHON.ORG/doc/#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, b"http") self.assertEqual(p.netloc, b"WWW.PYTHON.ORG") self.assertEqual(p.path, b"/doc/") self.assertEqual(p.query, b"") self.assertEqual(p.fragment, b"frag") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, b"www.python.org") self.assertEqual(p.port, None) self.assertEqual(p.geturl()[4:], url[4:]) url = b"http://User:Pass@www.python.org:080/doc/?query=yes#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, b"http") self.assertEqual(p.netloc, b"User:Pass@www.python.org:080") self.assertEqual(p.path, b"/doc/") self.assertEqual(p.query, b"query=yes") self.assertEqual(p.fragment, b"frag") self.assertEqual(p.username, b"User") self.assertEqual(p.password, b"Pass") self.assertEqual(p.hostname, b"www.python.org") self.assertEqual(p.port, 80) self.assertEqual(p.geturl(), url) url = b"http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag" p = urllib.parse.urlsplit(url) self.assertEqual(p.scheme, b"http") self.assertEqual(p.netloc, b"User@example.com:Pass@www.python.org:080") self.assertEqual(p.path, b"/doc/") self.assertEqual(p.query, b"query=yes") self.assertEqual(p.fragment, b"frag") self.assertEqual(p.username, b"User@example.com") self.assertEqual(p.password, b"Pass") self.assertEqual(p.hostname, b"www.python.org") self.assertEqual(p.port, 80) self.assertEqual(p.geturl(), url) # Verify an illegal port raises ValueError url = b"HTTP://WWW.PYTHON.ORG:65536/doc/#frag" p = urllib.parse.urlsplit(url) with self.assertRaisesRegex(ValueError, "out of range"): p.port def test_attributes_bad_port(self): """Check handling of invalid ports.""" for bytes in (False, True): for parse in (urllib.parse.urlsplit, urllib.parse.urlparse): for port in ("foo", "1.5", "-1", "0x10"): with self.subTest(bytes=bytes, parse=parse, port=port): netloc = "www.example.net:" + port url = "http://" + netloc if bytes: netloc = netloc.encode("ascii") url = url.encode("ascii") p = parse(url) self.assertEqual(p.netloc, netloc) with self.assertRaises(ValueError): p.port def test_attributes_without_netloc(self): # This example is straight from RFC 3261. It looks like it # should allow the username, hostname, and port to be filled # in, but doesn't. Since it's a URI and doesn't use the # scheme://netloc syntax, the netloc and related attributes # should be left empty. uri = "sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" p = urllib.parse.urlsplit(uri) self.assertEqual(p.netloc, "") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) self.assertEqual(p.port, None) self.assertEqual(p.geturl(), uri) p = urllib.parse.urlparse(uri) self.assertEqual(p.netloc, "") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) self.assertEqual(p.port, None) self.assertEqual(p.geturl(), uri) # You guessed it, repeating the test with bytes input uri = b"sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" p = urllib.parse.urlsplit(uri) self.assertEqual(p.netloc, b"") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) self.assertEqual(p.port, None) self.assertEqual(p.geturl(), uri) p = urllib.parse.urlparse(uri) self.assertEqual(p.netloc, b"") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None)
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_pydoc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pydoc.py
import os import sys import contextlib import importlib.util import inspect import pydoc import py_compile import keyword import _pickle import pkgutil import re import stat import string import tempfile import test.support import time import types import typing import unittest import urllib.parse import xml.etree import xml.etree.ElementTree import textwrap import threading from io import StringIO from collections import namedtuple from test.support.script_helper import assert_python_ok from test.support import ( TESTFN, rmtree, reap_children, reap_threads, captured_output, captured_stdout, captured_stderr, unlink, requires_docstrings ) from test import pydoc_mod class nonascii: 'Це не латиниця' pass if test.support.HAVE_DOCSTRINGS: expected_data_docstrings = ( 'dictionary for instance variables (if defined)', 'list of weak references to the object (if defined)', ) * 2 else: expected_data_docstrings = ('', '', '', '') expected_text_pattern = """ NAME test.pydoc_mod - This is a test module for test_pydoc %s CLASSES builtins.object A B C \x20\x20\x20\x20 class A(builtins.object) | Hello and goodbye |\x20\x20 | Methods defined here: |\x20\x20 | __init__() | Wow, I have no function! |\x20\x20 | ---------------------------------------------------------------------- | Data descriptors defined here: |\x20\x20 | __dict__%s |\x20\x20 | __weakref__%s \x20\x20\x20\x20 class B(builtins.object) | Data descriptors defined here: |\x20\x20 | __dict__%s |\x20\x20 | __weakref__%s |\x20\x20 | ---------------------------------------------------------------------- | Data and other attributes defined here: |\x20\x20 | NO_MEANING = 'eggs' |\x20\x20 | __annotations__ = {'NO_MEANING': <class 'str'>} \x20\x20\x20\x20 class C(builtins.object) | Methods defined here: |\x20\x20 | get_answer(self) | Return say_no() |\x20\x20 | is_it_true(self) | Return self.get_answer() |\x20\x20 | say_no(self) |\x20\x20 | ---------------------------------------------------------------------- | Data descriptors defined here: |\x20\x20 | __dict__ | dictionary for instance variables (if defined) |\x20\x20 | __weakref__ | list of weak references to the object (if defined) FUNCTIONS doc_func() This function solves all of the world's problems: hunger lack of Python war \x20\x20\x20\x20 nodoc_func() DATA __xyz__ = 'X, Y and Z' VERSION 1.2.3.4 AUTHOR Benjamin Peterson CREDITS Nobody FILE %s """.strip() expected_text_data_docstrings = tuple('\n | ' + s if s else '' for s in expected_data_docstrings) expected_html_pattern = """ <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="#7799ee"> <td valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="test.html"><font color="#ffffff">test</font></a>.pydoc_mod</strong></big></big> (version 1.2.3.4)</font></td ><td align=right valign=bottom ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table> <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p> <p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ee77aa"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%"><dl> <dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a> </font></dt><dd> <dl> <dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a> </font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a> </font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a> </font></dt></dl> </dd> </dl> <p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr> \x20\x20\x20\x20 <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td> <td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr> <tr><td>&nbsp;</td> <td width="100%%">Methods defined here:<br> <dl><dt><a name="A-__init__"><strong>__init__</strong></a>()</dt><dd><tt>Wow,&nbsp;I&nbsp;have&nbsp;no&nbsp;function!</tt></dd></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>%s</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>%s</tt></dd> </dl> </td></tr></table> <p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%">Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>%s</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>%s</tt></dd> </dl> <hr> Data and other attributes defined here:<br> <dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl> <dl><dt><strong>__annotations__</strong> = {'NO_MEANING': &lt;class 'str'&gt;}</dl> </td></tr></table> <p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="C">class <strong>C</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%">Methods defined here:<br> <dl><dt><a name="C-get_answer"><strong>get_answer</strong></a>(self)</dt><dd><tt>Return&nbsp;<a href="#C-say_no">say_no</a>()</tt></dd></dl> <dl><dt><a name="C-is_it_true"><strong>is_it_true</strong></a>(self)</dt><dd><tt>Return&nbsp;self.<a href="#C-get_answer">get_answer</a>()</tt></dd></dl> <dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl> <hr> Data descriptors defined here:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> </td></tr></table></td></tr></table><p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#eeaa77"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%"><dl><dt><a name="-doc_func"><strong>doc_func</strong></a>()</dt><dd><tt>This&nbsp;function&nbsp;solves&nbsp;all&nbsp;of&nbsp;the&nbsp;world's&nbsp;problems:<br> hunger<br> lack&nbsp;of&nbsp;Python<br> war</tt></dd></dl> <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl> </td></tr></table><p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#55aa55"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#7799ee"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#7799ee"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%">Nobody</td></tr></table> """.strip() # ' <- emacs turd expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;') for s in expected_data_docstrings) # output pattern for missing module missing_pattern = '''\ No Python documentation found for %r. Use help() to get the interactive help utility. Use help(str) for help on the str class.'''.replace('\n', os.linesep) # output pattern for module with bad imports badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r" expected_dynamicattribute_pattern = """ Help on class DA in module %s: class DA(builtins.object) | Data descriptors defined here: |\x20\x20 | __dict__%s |\x20\x20 | __weakref__%s |\x20\x20 | ham |\x20\x20 | ---------------------------------------------------------------------- | Data and other attributes inherited from Meta: |\x20\x20 | ham = 'spam' """.strip() expected_virtualattribute_pattern1 = """ Help on class Class in module %s: class Class(builtins.object) | Data and other attributes inherited from Meta: |\x20\x20 | LIFE = 42 """.strip() expected_virtualattribute_pattern2 = """ Help on class Class1 in module %s: class Class1(builtins.object) | Data and other attributes inherited from Meta1: |\x20\x20 | one = 1 """.strip() expected_virtualattribute_pattern3 = """ Help on class Class2 in module %s: class Class2(Class1) | Method resolution order: | Class2 | Class1 | builtins.object |\x20\x20 | Data and other attributes inherited from Meta1: |\x20\x20 | one = 1 |\x20\x20 | ---------------------------------------------------------------------- | Data and other attributes inherited from Meta3: |\x20\x20 | three = 3 |\x20\x20 | ---------------------------------------------------------------------- | Data and other attributes inherited from Meta2: |\x20\x20 | two = 2 """.strip() expected_missingattribute_pattern = """ Help on class C in module %s: class C(builtins.object) | Data and other attributes defined here: |\x20\x20 | here = 'present!' """.strip() def run_pydoc(module_name, *args, **env): """ Runs pydoc on the specified module. Returns the stripped output of pydoc. """ args = args + (module_name,) # do not write bytecode files to avoid caching errors rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env) return out.strip() def get_pydoc_html(module): "Returns pydoc generated output as html" doc = pydoc.HTMLDoc() output = doc.docmodule(module) loc = doc.getdocloc(pydoc_mod) or "" if loc: loc = "<br><a href=\"" + loc + "\">Module Docs</a>" return output.strip(), loc def get_pydoc_link(module): "Returns a documentation web link of a module" abspath = os.path.abspath dirname = os.path.dirname basedir = dirname(dirname(abspath(__file__))) doc = pydoc.TextDoc() loc = doc.getdocloc(module, basedir=basedir) return loc def get_pydoc_text(module): "Returns pydoc generated output as text" doc = pydoc.TextDoc() loc = doc.getdocloc(pydoc_mod) or "" if loc: loc = "\nMODULE DOCS\n " + loc + "\n" output = doc.docmodule(module) # clean up the extra text formatting that pydoc performs patt = re.compile('\b.') output = patt.sub('', output) return output.strip(), loc def get_html_title(text): # Bit of hack, but good enough for test purposes header, _, _ = text.partition("</head>") _, _, title = header.partition("<title>") title, _, _ = title.partition("</title>") return title class PydocBaseTest(unittest.TestCase): def _restricted_walk_packages(self, walk_packages, path=None): """ A version of pkgutil.walk_packages() that will restrict itself to a given path. """ default_path = path or [os.path.dirname(__file__)] def wrapper(path=None, prefix='', onerror=None): return walk_packages(path or default_path, prefix, onerror) return wrapper @contextlib.contextmanager def restrict_walk_packages(self, path=None): walk_packages = pkgutil.walk_packages pkgutil.walk_packages = self._restricted_walk_packages(walk_packages, path) try: yield finally: pkgutil.walk_packages = walk_packages def call_url_handler(self, url, expected_title): text = pydoc._url_handler(url, "text/html") result = get_html_title(text) # Check the title to ensure an unexpected error page was not returned self.assertEqual(result, expected_title, text) return text class PydocDocTest(unittest.TestCase): maxDiff = None @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __locals__ unexpectedly') @requires_docstrings def test_html_doc(self): result, doc_loc = get_pydoc_html(pydoc_mod) mod_file = inspect.getabsfile(pydoc_mod) mod_url = urllib.parse.quote(mod_file) expected_html = expected_html_pattern % ( (mod_url, mod_file, doc_loc) + expected_html_data_docstrings) self.assertEqual(result, expected_html) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __locals__ unexpectedly') @requires_docstrings def test_text_doc(self): result, doc_loc = get_pydoc_text(pydoc_mod) expected_text = expected_text_pattern % ( (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)) self.assertEqual(expected_text, result) def test_text_enum_member_with_value_zero(self): # Test issue #20654 to ensure enum member with value 0 can be # displayed. It used to throw KeyError: 'zero'. import enum class BinaryInteger(enum.IntEnum): zero = 0 one = 1 doc = pydoc.render_doc(BinaryInteger) self.assertIn('<BinaryInteger.zero: 0>', doc) def test_mixed_case_module_names_are_lower_cased(self): # issue16484 doc_link = get_pydoc_link(xml.etree.ElementTree) self.assertIn('xml.etree.elementtree', doc_link) def test_issue8225(self): # Test issue8225 to ensure no doc link appears for xml.etree result, doc_loc = get_pydoc_text(xml.etree) self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link") def test_getpager_with_stdin_none(self): previous_stdin = sys.stdin try: sys.stdin = None pydoc.getpager() # Shouldn't fail. finally: sys.stdin = previous_stdin def test_non_str_name(self): # issue14638 # Treat illegal (non-str) name like no name class A: __name__ = 42 class B: pass adoc = pydoc.render_doc(A()) bdoc = pydoc.render_doc(B()) self.assertEqual(adoc.replace("A", "B"), bdoc) def test_not_here(self): missing_module = "test.i_am_not_here" result = str(run_pydoc(missing_module), 'ascii') expected = missing_pattern % missing_module self.assertEqual(expected, result, "documentation for missing module found") @unittest.skipIf(sys.flags.optimize >= 2, 'Docstrings are omitted with -OO and above') def test_not_ascii(self): result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii') encoded = nonascii.__doc__.encode('ascii', 'backslashreplace') self.assertIn(encoded, result) def test_input_strip(self): missing_module = " test.i_am_not_here " result = str(run_pydoc(missing_module), 'ascii') expected = missing_pattern % missing_module.strip() self.assertEqual(expected, result) def test_stripid(self): # test with strings, other implementations might have different repr() stripid = pydoc.stripid # strip the id self.assertEqual(stripid('<function stripid at 0x88dcee4>'), '<function stripid>') self.assertEqual(stripid('<function stripid at 0x01F65390>'), '<function stripid>') # nothing to strip, return the same text self.assertEqual(stripid('42'), '42') self.assertEqual(stripid("<type 'exceptions.Exception'>"), "<type 'exceptions.Exception'>") @unittest.skipIf(sys.flags.optimize >= 2, 'Docstrings are omitted with -O2 and above') @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __locals__ unexpectedly') @requires_docstrings def test_help_output_redirect(self): # issue 940286, if output is set in Helper, then all output from # Helper.help should be redirected old_pattern = expected_text_pattern getpager_old = pydoc.getpager getpager_new = lambda: (lambda x: x) self.maxDiff = None buf = StringIO() helper = pydoc.Helper(output=buf) unused, doc_loc = get_pydoc_text(pydoc_mod) module = "test.pydoc_mod" help_header = """ Help on module test.pydoc_mod in test: """.lstrip() help_header = textwrap.dedent(help_header) expected_help_pattern = help_header + expected_text_pattern pydoc.getpager = getpager_new try: with captured_output('stdout') as output, \ captured_output('stderr') as err: helper.help(module) result = buf.getvalue().strip() expected_text = expected_help_pattern % ( (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)) self.assertEqual('', output.getvalue()) self.assertEqual('', err.getvalue()) self.assertEqual(expected_text, result) finally: pydoc.getpager = getpager_old def test_namedtuple_public_underscore(self): NT = namedtuple('NT', ['abc', 'def'], rename=True) with captured_stdout() as help_io: pydoc.help(NT) helptext = help_io.getvalue() self.assertIn('_1', helptext) self.assertIn('_replace', helptext) self.assertIn('_asdict', helptext) def test_synopsis(self): self.addCleanup(unlink, TESTFN) for encoding in ('ISO-8859-1', 'UTF-8'): with open(TESTFN, 'w', encoding=encoding) as script: if encoding != 'UTF-8': print('#coding: {}'.format(encoding), file=script) print('"""line 1: h\xe9', file=script) print('line 2: hi"""', file=script) synopsis = pydoc.synopsis(TESTFN, {}) self.assertEqual(synopsis, 'line 1: h\xe9') @unittest.skipIf(sys.flags.optimize >= 2, 'Docstrings are omitted with -OO and above') def test_synopsis_sourceless(self): expected = os.__doc__.splitlines()[0] filename = os.__cached__ synopsis = pydoc.synopsis(filename) self.assertEqual(synopsis, expected) def test_synopsis_sourceless_empty_doc(self): with test.support.temp_cwd() as test_dir: init_path = os.path.join(test_dir, 'foomod42.py') cached_path = importlib.util.cache_from_source(init_path) with open(init_path, 'w') as fobj: fobj.write("foo = 1") py_compile.compile(init_path) synopsis = pydoc.synopsis(init_path, {}) self.assertIsNone(synopsis) synopsis_cached = pydoc.synopsis(cached_path, {}) self.assertIsNone(synopsis_cached) def test_splitdoc_with_description(self): example_string = "I Am A Doc\n\n\nHere is my description" self.assertEqual(pydoc.splitdoc(example_string), ('I Am A Doc', '\nHere is my description')) def test_is_object_or_method(self): doc = pydoc.Doc() # Bound Method self.assertTrue(pydoc._is_some_method(doc.fail)) # Method Descriptor self.assertTrue(pydoc._is_some_method(int.__add__)) # String self.assertFalse(pydoc._is_some_method("I am not a method")) def test_is_package_when_not_package(self): with test.support.temp_cwd() as test_dir: self.assertFalse(pydoc.ispackage(test_dir)) def test_is_package_when_is_package(self): with test.support.temp_cwd() as test_dir: init_path = os.path.join(test_dir, '__init__.py') open(init_path, 'w').close() self.assertTrue(pydoc.ispackage(test_dir)) os.remove(init_path) def test_allmethods(self): # issue 17476: allmethods was no longer returning unbound methods. # This test is a bit fragile in the face of changes to object and type, # but I can't think of a better way to do it without duplicating the # logic of the function under test. class TestClass(object): def method_returning_true(self): return True # What we expect to get back: everything on object... expected = dict(vars(object)) # ...plus our unbound method... expected['method_returning_true'] = TestClass.method_returning_true # ...but not the non-methods on object. del expected['__doc__'] del expected['__class__'] # inspect resolves descriptors on type into methods, but vars doesn't, # so we need to update __subclasshook__ and __init_subclass__. expected['__subclasshook__'] = TestClass.__subclasshook__ expected['__init_subclass__'] = TestClass.__init_subclass__ methods = pydoc.allmethods(TestClass) self.assertDictEqual(methods, expected) def test_method_aliases(self): class A: def tkraise(self, aboveThis=None): """Raise this widget in the stacking order.""" lift = tkraise def a_size(self): """Return size""" class B(A): def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID.""" itemconfig = itemconfigure b_size = A.a_size doc = pydoc.render_doc(B) # clean up the extra text formatting that pydoc performs doc = re.sub('\b.', '', doc) self.assertEqual(doc, '''\ Python Library Documentation: class B in module %s class B(A) | Method resolution order: | B | A | builtins.object |\x20\x20 | Methods defined here: |\x20\x20 | b_size = a_size(self) |\x20\x20 | itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw) |\x20\x20 | itemconfigure(self, tagOrId, cnf=None, **kw) | Configure resources of an item TAGORID. |\x20\x20 | ---------------------------------------------------------------------- | Methods inherited from A: |\x20\x20 | a_size(self) | Return size |\x20\x20 | lift = tkraise(self, aboveThis=None) |\x20\x20 | tkraise(self, aboveThis=None) | Raise this widget in the stacking order. |\x20\x20 | ---------------------------------------------------------------------- | Data descriptors inherited from A: |\x20\x20 | __dict__ | dictionary for instance variables (if defined) |\x20\x20 | __weakref__ | list of weak references to the object (if defined) ''' % __name__) doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc()) self.assertEqual(doc, '''\ Python Library Documentation: class B in module %s <p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(A)</font></td></tr> \x20\x20\x20\x20 <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%%"><dl><dt>Method resolution order:</dt> <dd>B</dd> <dd>A</dd> <dd><a href="builtins.html#object">builtins.object</a></dd> </dl> <hr> Methods defined here:<br> <dl><dt><a name="B-b_size"><strong>b_size</strong></a> = <a href="#B-a_size">a_size</a>(self)</dt></dl> <dl><dt><a name="B-itemconfig"><strong>itemconfig</strong></a> = <a href="#B-itemconfigure">itemconfigure</a>(self, tagOrId, cnf=None, **kw)</dt></dl> <dl><dt><a name="B-itemconfigure"><strong>itemconfigure</strong></a>(self, tagOrId, cnf=None, **kw)</dt><dd><tt>Configure&nbsp;resources&nbsp;of&nbsp;an&nbsp;item&nbsp;TAGORID.</tt></dd></dl> <hr> Methods inherited from A:<br> <dl><dt><a name="B-a_size"><strong>a_size</strong></a>(self)</dt><dd><tt>Return&nbsp;size</tt></dd></dl> <dl><dt><a name="B-lift"><strong>lift</strong></a> = <a href="#B-tkraise">tkraise</a>(self, aboveThis=None)</dt></dl> <dl><dt><a name="B-tkraise"><strong>tkraise</strong></a>(self, aboveThis=None)</dt><dd><tt>Raise&nbsp;this&nbsp;widget&nbsp;in&nbsp;the&nbsp;stacking&nbsp;order.</tt></dd></dl> <hr> Data descriptors inherited from A:<br> <dl><dt><strong>__dict__</strong></dt> <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd> </dl> <dl><dt><strong>__weakref__</strong></dt> <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd> </dl> </td></tr></table>\ ''' % __name__) class PydocImportTest(PydocBaseTest): def setUp(self): self.test_dir = os.mkdir(TESTFN) self.addCleanup(rmtree, TESTFN) importlib.invalidate_caches() def test_badimport(self): # This tests the fix for issue 5230, where if pydoc found the module # but the module had an internal import error pydoc would report no doc # found. modname = 'testmod_xyzzy' testpairs = ( ('i_am_not_here', 'i_am_not_here'), ('test.i_am_not_here_either', 'test.i_am_not_here_either'), ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'), ('i_am_not_here.{}'.format(modname), 'i_am_not_here'), ('test.{}'.format(modname), 'test.{}'.format(modname)), ) sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py" for importstring, expectedinmsg in testpairs: with open(sourcefn, 'w') as f: f.write("import {}\n".format(importstring)) result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii") expected = badimport_pattern % (modname, expectedinmsg) self.assertEqual(expected, result) def test_apropos_with_bad_package(self): # Issue 7425 - pydoc -k failed when bad package on path pkgdir = os.path.join(TESTFN, "syntaxerr") os.mkdir(pkgdir) badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py" with open(badsyntax, 'w') as f: f.write("invalid python syntax = $1\n") with self.restrict_walk_packages(path=[TESTFN]): with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos('xyzzy') # No result, no error self.assertEqual(out.getvalue(), '') self.assertEqual(err.getvalue(), '') # The package name is still matched with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos('syntaxerr') self.assertEqual(out.getvalue().strip(), 'syntaxerr') self.assertEqual(err.getvalue(), '') def test_apropos_with_unreadable_dir(self): # Issue 7367 - pydoc -k failed when unreadable dir on path self.unreadable_dir = os.path.join(TESTFN, "unreadable") os.mkdir(self.unreadable_dir, 0) self.addCleanup(os.rmdir, self.unreadable_dir) # Note, on Windows the directory appears to be still # readable so this is not really testing the issue there with self.restrict_walk_packages(path=[TESTFN]): with captured_stdout() as out: with captured_stderr() as err: pydoc.apropos('SOMEKEY') # No result, no error self.assertEqual(out.getvalue(), '') self.assertEqual(err.getvalue(), '') def test_apropos_empty_doc(self): pkgdir = os.path.join(TESTFN, 'walkpkg') os.mkdir(pkgdir) self.addCleanup(rmtree, pkgdir) init_path = os.path.join(pkgdir, '__init__.py') with open(init_path, 'w') as fobj: fobj.write("foo = 1") current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode) try: os.chmod(pkgdir, current_mode & ~stat.S_IEXEC) with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout: pydoc.apropos('') self.assertIn('walkpkg', stdout.getvalue()) finally: os.chmod(pkgdir, current_mode) def test_url_search_package_error(self): # URL handler search should cope with packages that raise exceptions pkgdir = os.path.join(TESTFN, "test_error_package") os.mkdir(pkgdir) init = os.path.join(pkgdir, "__init__.py") with open(init, "wt", encoding="ascii") as f: f.write("""raise ValueError("ouch")\n""") with self.restrict_walk_packages(path=[TESTFN]): # Package has to be importable for the error to have any effect saved_paths = tuple(sys.path) sys.path.insert(0, TESTFN) try: with self.assertRaisesRegex(ValueError, "ouch"): import test_error_package # Sanity check text = self.call_url_handler("search?key=test_error_package", "Pydoc: Search Results") found = ('<a href="test_error_package.html">' 'test_error_package</a>') self.assertIn(found, text) finally: sys.path[:] = saved_paths @unittest.skip('causes undesirable side-effects (#20128)') def test_modules(self): # See Helper.listmodules(). num_header_lines = 2 num_module_lines_min = 5 # Playing it safe. num_footer_lines = 3 expected = num_header_lines + num_module_lines_min + num_footer_lines output = StringIO() helper = pydoc.Helper(output=output) helper('modules') result = output.getvalue().strip() num_lines = len(result.splitlines()) self.assertGreaterEqual(num_lines, expected) @unittest.skip('causes undesirable side-effects (#20128)') def test_modules_search(self): # See Helper.listmodules(). expected = 'pydoc - ' output = StringIO() helper = pydoc.Helper(output=output) with captured_stdout() as help_io: helper('modules pydoc') result = help_io.getvalue() self.assertIn(expected, result) @unittest.skip('some buildbots are not cooperating (#20128)') def test_modules_search_builtin(self): expected = 'gc - ' output = StringIO() helper = pydoc.Helper(output=output)
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_binhex.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_binhex.py
"""Test script for the binhex C module Uses the mechanism of the python binhex module Based on an original test by Roger E. Masse. """ import binhex import unittest from test import support class BinHexTestCase(unittest.TestCase): def setUp(self): self.fname1 = support.TESTFN + "1" self.fname2 = support.TESTFN + "2" self.fname3 = support.TESTFN + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__" def tearDown(self): support.unlink(self.fname1) support.unlink(self.fname2) support.unlink(self.fname3) DATA = b'Jack is my hero' def test_binhex(self): f = open(self.fname1, 'wb') f.write(self.DATA) f.close() binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) f = open(self.fname1, 'rb') finish = f.readline() f.close() self.assertEqual(self.DATA, finish) def test_binhex_error_on_long_filename(self): """ The testcase fails if no exception is raised when a filename parameter provided to binhex.binhex() is too long, or if the exception raised in binhex.binhex() is not an instance of binhex.Error. """ f3 = open(self.fname3, 'wb') f3.close() self.assertRaises(binhex.Error, binhex.binhex, self.fname3, self.fname2) def test_main(): support.run_unittest(BinHexTestCase) 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_compileall.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_compileall.py
import sys import compileall import importlib.util import test.test_importlib.util import os import pathlib import py_compile import shutil import struct import tempfile import time import unittest import io from unittest import mock, skipUnless try: from concurrent.futures import ProcessPoolExecutor _have_multiprocessing = True except ImportError: _have_multiprocessing = False from test import support from test.support import script_helper from .test_py_compile import without_source_date_epoch from .test_py_compile import SourceDateEpochTestMeta class CompileallTestsBase: def setUp(self): self.directory = tempfile.mkdtemp() self.source_path = os.path.join(self.directory, '_test.py') self.bc_path = importlib.util.cache_from_source(self.source_path) with open(self.source_path, 'w') as file: file.write('x = 123\n') self.source_path2 = os.path.join(self.directory, '_test2.py') self.bc_path2 = importlib.util.cache_from_source(self.source_path2) shutil.copyfile(self.source_path, self.source_path2) self.subdirectory = os.path.join(self.directory, '_subdir') os.mkdir(self.subdirectory) self.source_path3 = os.path.join(self.subdirectory, '_test3.py') shutil.copyfile(self.source_path, self.source_path3) def tearDown(self): shutil.rmtree(self.directory) def add_bad_source_file(self): self.bad_source_path = os.path.join(self.directory, '_test_bad.py') with open(self.bad_source_path, 'w') as file: file.write('x (\n') def timestamp_metadata(self): with open(self.bc_path, 'rb') as file: data = file.read(12) mtime = int(os.stat(self.source_path).st_mtime) compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime) return data, compare @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') def recreation_check(self, metadata): """Check that compileall recreates bytecode when the new metadata is used.""" if os.environ.get('SOURCE_DATE_EPOCH'): raise unittest.SkipTest('SOURCE_DATE_EPOCH is set') py_compile.compile(self.source_path) self.assertEqual(*self.timestamp_metadata()) with open(self.bc_path, 'rb') as file: bc = file.read()[len(metadata):] with open(self.bc_path, 'wb') as file: file.write(metadata) file.write(bc) self.assertNotEqual(*self.timestamp_metadata()) compileall.compile_dir(self.directory, force=False, quiet=True) self.assertTrue(*self.timestamp_metadata()) def test_mtime(self): # Test a change in mtime leads to a new .pyc. self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, 1)) def test_magic_number(self): # Test a change in mtime leads to a new .pyc. self.recreation_check(b'\0\0\0\0') def test_compile_files(self): # Test compiling a single file, and complete directory for fn in (self.bc_path, self.bc_path2): try: os.unlink(fn) except: pass self.assertTrue(compileall.compile_file(self.source_path, force=False, quiet=True)) self.assertTrue(os.path.isfile(self.bc_path) and not os.path.isfile(self.bc_path2)) os.unlink(self.bc_path) self.assertTrue(compileall.compile_dir(self.directory, force=False, quiet=True)) self.assertTrue(os.path.isfile(self.bc_path) and os.path.isfile(self.bc_path2)) os.unlink(self.bc_path) os.unlink(self.bc_path2) # Test against bad files self.add_bad_source_file() self.assertFalse(compileall.compile_file(self.bad_source_path, force=False, quiet=2)) self.assertFalse(compileall.compile_dir(self.directory, force=False, quiet=2)) def test_compile_file_pathlike(self): self.assertFalse(os.path.isfile(self.bc_path)) # we should also test the output with support.captured_stdout() as stdout: self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path))) self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)') self.assertTrue(os.path.isfile(self.bc_path)) def test_compile_file_pathlike_ddir(self): self.assertFalse(os.path.isfile(self.bc_path)) self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path), ddir=pathlib.Path('ddir_path'), quiet=2)) self.assertTrue(os.path.isfile(self.bc_path)) def test_compile_path(self): with test.test_importlib.util.import_state(path=[self.directory]): self.assertTrue(compileall.compile_path(quiet=2)) with test.test_importlib.util.import_state(path=[self.directory]): self.add_bad_source_file() self.assertFalse(compileall.compile_path(skip_curdir=False, force=True, quiet=2)) def test_no_pycache_in_non_package(self): # Bug 8563 reported that __pycache__ directories got created by # compile_file() for non-.py files. data_dir = os.path.join(self.directory, 'data') data_file = os.path.join(data_dir, 'file') os.mkdir(data_dir) # touch data/file with open(data_file, 'w'): pass compileall.compile_file(data_file) self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__'))) def test_optimize(self): # make sure compiling with different optimization settings than the # interpreter's creates the correct file names optimize, opt = (1, 1) if __debug__ else (0, '') compileall.compile_dir(self.directory, quiet=True, optimize=optimize) cached = importlib.util.cache_from_source(self.source_path, optimization=opt) self.assertTrue(os.path.isfile(cached)) cached2 = importlib.util.cache_from_source(self.source_path2, optimization=opt) self.assertTrue(os.path.isfile(cached2)) cached3 = importlib.util.cache_from_source(self.source_path3, optimization=opt) self.assertTrue(os.path.isfile(cached3)) def test_compile_dir_pathlike(self): self.assertFalse(os.path.isfile(self.bc_path)) with support.captured_stdout() as stdout: compileall.compile_dir(pathlib.Path(self.directory)) line = stdout.getvalue().splitlines()[0] self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)') self.assertTrue(os.path.isfile(self.bc_path)) @mock.patch('concurrent.futures.ProcessPoolExecutor') def test_compile_pool_called(self, pool_mock): compileall.compile_dir(self.directory, quiet=True, workers=5) self.assertTrue(pool_mock.called) def test_compile_workers_non_positive(self): with self.assertRaisesRegex(ValueError, "workers must be greater or equal to 0"): compileall.compile_dir(self.directory, workers=-1) @mock.patch('concurrent.futures.ProcessPoolExecutor') def test_compile_workers_cpu_count(self, pool_mock): compileall.compile_dir(self.directory, quiet=True, workers=0) self.assertEqual(pool_mock.call_args[1]['max_workers'], None) @mock.patch('concurrent.futures.ProcessPoolExecutor') @mock.patch('compileall.compile_file') def test_compile_one_worker(self, compile_file_mock, pool_mock): compileall.compile_dir(self.directory, quiet=True) self.assertFalse(pool_mock.called) self.assertTrue(compile_file_mock.called) @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None) @mock.patch('compileall.compile_file') def test_compile_missing_multiprocessing(self, compile_file_mock): compileall.compile_dir(self.directory, quiet=True, workers=5) self.assertTrue(compile_file_mock.called) class CompileallTestsWithSourceEpoch(CompileallTestsBase, unittest.TestCase, metaclass=SourceDateEpochTestMeta, source_date_epoch=True): pass class CompileallTestsWithoutSourceEpoch(CompileallTestsBase, unittest.TestCase, metaclass=SourceDateEpochTestMeta, source_date_epoch=False): pass class EncodingTest(unittest.TestCase): """Issue 6716: compileall should escape source code when printing errors to stdout.""" def setUp(self): self.directory = tempfile.mkdtemp() self.source_path = os.path.join(self.directory, '_test.py') with open(self.source_path, 'w', encoding='utf-8') as file: file.write('# -*- coding: utf-8 -*-\n') file.write('print u"\u20ac"\n') def tearDown(self): shutil.rmtree(self.directory) def test_error(self): try: orig_stdout = sys.stdout sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii') compileall.compile_dir(self.directory) finally: sys.stdout = orig_stdout class CommandLineTestsBase: """Test compileall's CLI.""" @classmethod def setUpClass(cls): for path in filter(os.path.isdir, sys.path): directory_created = False directory = pathlib.Path(path) / '__pycache__' path = directory / 'test.try' try: if not directory.is_dir(): directory.mkdir() directory_created = True with path.open('w') as file: file.write('# for test_compileall') except OSError: sys_path_writable = False break finally: support.unlink(str(path)) if directory_created: directory.rmdir() else: sys_path_writable = True cls._sys_path_writable = sys_path_writable def _skip_if_sys_path_not_writable(self): if not self._sys_path_writable: raise unittest.SkipTest('not all entries on sys.path are writable') def _get_run_args(self, args): return [*support.optim_args_from_interpreter_flags(), '-S', '-m', 'compileall', *args] def assertRunOK(self, *args, **env_vars): rc, out, err = script_helper.assert_python_ok( *self._get_run_args(args), **env_vars) self.assertEqual(b'', err) return out def assertRunNotOK(self, *args, **env_vars): rc, out, err = script_helper.assert_python_failure( *self._get_run_args(args), **env_vars) return rc, out, err def assertCompiled(self, fn): path = importlib.util.cache_from_source(fn) self.assertTrue(os.path.exists(path)) def assertNotCompiled(self, fn): path = importlib.util.cache_from_source(fn) self.assertFalse(os.path.exists(path)) def setUp(self): self.directory = tempfile.mkdtemp() self.addCleanup(support.rmtree, self.directory) self.pkgdir = os.path.join(self.directory, 'foo') os.mkdir(self.pkgdir) self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__') # Create the __init__.py and a package module. self.initfn = script_helper.make_script(self.pkgdir, '__init__', '') self.barfn = script_helper.make_script(self.pkgdir, 'bar', '') def test_no_args_compiles_path(self): # Note that -l is implied for the no args case. self._skip_if_sys_path_not_writable() bazfn = script_helper.make_script(self.directory, 'baz', '') self.assertRunOK(PYTHONPATH=self.directory) self.assertCompiled(bazfn) self.assertNotCompiled(self.initfn) self.assertNotCompiled(self.barfn) @without_source_date_epoch # timestamp invalidation test def test_no_args_respects_force_flag(self): self._skip_if_sys_path_not_writable() bazfn = script_helper.make_script(self.directory, 'baz', '') self.assertRunOK(PYTHONPATH=self.directory) pycpath = importlib.util.cache_from_source(bazfn) # Set atime/mtime backward to avoid file timestamp resolution issues os.utime(pycpath, (time.time()-60,)*2) mtime = os.stat(pycpath).st_mtime # Without force, no recompilation self.assertRunOK(PYTHONPATH=self.directory) mtime2 = os.stat(pycpath).st_mtime self.assertEqual(mtime, mtime2) # Now force it. self.assertRunOK('-f', PYTHONPATH=self.directory) mtime2 = os.stat(pycpath).st_mtime self.assertNotEqual(mtime, mtime2) def test_no_args_respects_quiet_flag(self): self._skip_if_sys_path_not_writable() script_helper.make_script(self.directory, 'baz', '') noisy = self.assertRunOK(PYTHONPATH=self.directory) self.assertIn(b'Listing ', noisy) quiet = self.assertRunOK('-q', PYTHONPATH=self.directory) self.assertNotIn(b'Listing ', quiet) # Ensure that the default behavior of compileall's CLI is to create # PEP 3147/PEP 488 pyc files. for name, ext, switch in [ ('normal', 'pyc', []), ('optimize', 'opt-1.pyc', ['-O']), ('doubleoptimize', 'opt-2.pyc', ['-OO']), ]: def f(self, ext=ext, switch=switch): script_helper.assert_python_ok(*(switch + ['-m', 'compileall', '-q', self.pkgdir])) # Verify the __pycache__ directory contents. self.assertTrue(os.path.exists(self.pkgdir_cachedir)) expected = sorted(base.format(sys.implementation.cache_tag, ext) for base in ('__init__.{}.{}', 'bar.{}.{}')) self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected) # Make sure there are no .pyc files in the source directory. self.assertFalse([fn for fn in os.listdir(self.pkgdir) if fn.endswith(ext)]) locals()['test_pep3147_paths_' + name] = f def test_legacy_paths(self): # Ensure that with the proper switch, compileall leaves legacy # pyc files, and no __pycache__ directory. self.assertRunOK('-b', '-q', self.pkgdir) # Verify the __pycache__ directory contents. self.assertFalse(os.path.exists(self.pkgdir_cachedir)) expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc']) self.assertEqual(sorted(os.listdir(self.pkgdir)), expected) def test_multiple_runs(self): # Bug 8527 reported that multiple calls produced empty # __pycache__/__pycache__ directories. self.assertRunOK('-q', self.pkgdir) # Verify the __pycache__ directory contents. self.assertTrue(os.path.exists(self.pkgdir_cachedir)) cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__') self.assertFalse(os.path.exists(cachecachedir)) # Call compileall again. self.assertRunOK('-q', self.pkgdir) self.assertTrue(os.path.exists(self.pkgdir_cachedir)) self.assertFalse(os.path.exists(cachecachedir)) @without_source_date_epoch # timestamp invalidation test def test_force(self): self.assertRunOK('-q', self.pkgdir) pycpath = importlib.util.cache_from_source(self.barfn) # set atime/mtime backward to avoid file timestamp resolution issues os.utime(pycpath, (time.time()-60,)*2) mtime = os.stat(pycpath).st_mtime # without force, no recompilation self.assertRunOK('-q', self.pkgdir) mtime2 = os.stat(pycpath).st_mtime self.assertEqual(mtime, mtime2) # now force it. self.assertRunOK('-q', '-f', self.pkgdir) mtime2 = os.stat(pycpath).st_mtime self.assertNotEqual(mtime, mtime2) def test_recursion_control(self): subpackage = os.path.join(self.pkgdir, 'spam') os.mkdir(subpackage) subinitfn = script_helper.make_script(subpackage, '__init__', '') hamfn = script_helper.make_script(subpackage, 'ham', '') self.assertRunOK('-q', '-l', self.pkgdir) self.assertNotCompiled(subinitfn) self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__'))) self.assertRunOK('-q', self.pkgdir) self.assertCompiled(subinitfn) self.assertCompiled(hamfn) def test_recursion_limit(self): subpackage = os.path.join(self.pkgdir, 'spam') subpackage2 = os.path.join(subpackage, 'ham') subpackage3 = os.path.join(subpackage2, 'eggs') for pkg in (subpackage, subpackage2, subpackage3): script_helper.make_pkg(pkg) subinitfn = os.path.join(subpackage, '__init__.py') hamfn = script_helper.make_script(subpackage, 'ham', '') spamfn = script_helper.make_script(subpackage2, 'spam', '') eggfn = script_helper.make_script(subpackage3, 'egg', '') self.assertRunOK('-q', '-r 0', self.pkgdir) self.assertNotCompiled(subinitfn) self.assertFalse( os.path.exists(os.path.join(subpackage, '__pycache__'))) self.assertRunOK('-q', '-r 1', self.pkgdir) self.assertCompiled(subinitfn) self.assertCompiled(hamfn) self.assertNotCompiled(spamfn) self.assertRunOK('-q', '-r 2', self.pkgdir) self.assertCompiled(subinitfn) self.assertCompiled(hamfn) self.assertCompiled(spamfn) self.assertNotCompiled(eggfn) self.assertRunOK('-q', '-r 5', self.pkgdir) self.assertCompiled(subinitfn) self.assertCompiled(hamfn) self.assertCompiled(spamfn) self.assertCompiled(eggfn) def test_quiet(self): noisy = self.assertRunOK(self.pkgdir) quiet = self.assertRunOK('-q', self.pkgdir) self.assertNotEqual(b'', noisy) self.assertEqual(b'', quiet) def test_silent(self): script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax') _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir) _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir) self.assertNotEqual(b'', quiet) self.assertEqual(b'', silent) def test_regexp(self): self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir) self.assertNotCompiled(self.barfn) self.assertCompiled(self.initfn) def test_multiple_dirs(self): pkgdir2 = os.path.join(self.directory, 'foo2') os.mkdir(pkgdir2) init2fn = script_helper.make_script(pkgdir2, '__init__', '') bar2fn = script_helper.make_script(pkgdir2, 'bar2', '') self.assertRunOK('-q', self.pkgdir, pkgdir2) self.assertCompiled(self.initfn) self.assertCompiled(self.barfn) self.assertCompiled(init2fn) self.assertCompiled(bar2fn) def test_d_compile_error(self): script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax') rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir) self.assertRegex(out, b'File "dinsdale') def test_d_runtime_error(self): bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception') self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir) fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz') pyc = importlib.util.cache_from_source(bazfn) os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc')) os.remove(bazfn) rc, out, err = script_helper.assert_python_failure(fn, __isolated=False) self.assertRegex(err, b'File "dinsdale') def test_include_bad_file(self): rc, out, err = self.assertRunNotOK( '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir) self.assertRegex(out, b'rror.*nosuchfile') self.assertNotRegex(err, b'Traceback') self.assertFalse(os.path.exists(importlib.util.cache_from_source( self.pkgdir_cachedir))) def test_include_file_with_arg(self): f1 = script_helper.make_script(self.pkgdir, 'f1', '') f2 = script_helper.make_script(self.pkgdir, 'f2', '') f3 = script_helper.make_script(self.pkgdir, 'f3', '') f4 = script_helper.make_script(self.pkgdir, 'f4', '') with open(os.path.join(self.directory, 'l1'), 'w') as l1: l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep) l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep) self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4) self.assertCompiled(f1) self.assertCompiled(f2) self.assertNotCompiled(f3) self.assertCompiled(f4) def test_include_file_no_arg(self): f1 = script_helper.make_script(self.pkgdir, 'f1', '') f2 = script_helper.make_script(self.pkgdir, 'f2', '') f3 = script_helper.make_script(self.pkgdir, 'f3', '') f4 = script_helper.make_script(self.pkgdir, 'f4', '') with open(os.path.join(self.directory, 'l1'), 'w') as l1: l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep) self.assertRunOK('-i', os.path.join(self.directory, 'l1')) self.assertNotCompiled(f1) self.assertCompiled(f2) self.assertNotCompiled(f3) self.assertNotCompiled(f4) def test_include_on_stdin(self): f1 = script_helper.make_script(self.pkgdir, 'f1', '') f2 = script_helper.make_script(self.pkgdir, 'f2', '') f3 = script_helper.make_script(self.pkgdir, 'f3', '') f4 = script_helper.make_script(self.pkgdir, 'f4', '') p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-'])) p.stdin.write((f3+os.linesep).encode('ascii')) script_helper.kill_python(p) self.assertNotCompiled(f1) self.assertNotCompiled(f2) self.assertCompiled(f3) self.assertNotCompiled(f4) def test_compiles_as_much_as_possible(self): bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error') rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn, bingfn, self.barfn) self.assertRegex(out, b'rror') self.assertNotCompiled(bingfn) self.assertCompiled(self.initfn) self.assertCompiled(self.barfn) def test_invalid_arg_produces_message(self): out = self.assertRunOK('badfilename') self.assertRegex(out, b"Can't list 'badfilename'") def test_pyc_invalidation_mode(self): script_helper.make_script(self.pkgdir, 'f1', '') pyc = importlib.util.cache_from_source( os.path.join(self.pkgdir, 'f1.py')) self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir) with open(pyc, 'rb') as fp: data = fp.read() self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11) self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir) with open(pyc, 'rb') as fp: data = fp.read() self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01) @skipUnless(_have_multiprocessing, "requires multiprocessing") def test_workers(self): bar2fn = script_helper.make_script(self.directory, 'bar2', '') files = [] for suffix in range(5): pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix)) os.mkdir(pkgdir) fn = script_helper.make_script(pkgdir, '__init__', '') files.append(script_helper.make_script(pkgdir, 'bar2', '')) self.assertRunOK(self.directory, '-j', '0') self.assertCompiled(bar2fn) for file in files: self.assertCompiled(file) @mock.patch('compileall.compile_dir') def test_workers_available_cores(self, compile_dir): with mock.patch("sys.argv", new=[sys.executable, self.directory, "-j0"]): compileall.main() self.assertTrue(compile_dir.called) self.assertEqual(compile_dir.call_args[-1]['workers'], None) def _test_ddir_only(self, *, ddir, parallel=True): """Recursive compile_dir ddir must contain package paths; bpo39769.""" fullpath = ["test", "foo"] path = self.directory mods = [] for subdir in fullpath: path = os.path.join(path, subdir) os.mkdir(path) script_helper.make_script(path, "__init__", "") mods.append(script_helper.make_script(path, "mod", "def fn(): 1/0\nfn()\n")) compileall.compile_dir( self.directory, quiet=True, ddir=ddir, workers=2 if parallel else 1) self.assertTrue(mods) for mod in mods: self.assertTrue(mod.startswith(self.directory), mod) modcode = importlib.util.cache_from_source(mod) modpath = mod[len(self.directory+os.sep):] _, _, err = script_helper.assert_python_failure(modcode) expected_in = os.path.join(ddir, modpath) mod_code_obj = test.test_importlib.util._get_code_from_pyc(modcode) self.assertEqual(mod_code_obj.co_filename, expected_in) self.assertIn(f'"{expected_in}"', os.fsdecode(err)) def test_ddir_only_one_worker(self): """Recursive compile_dir ddir= contains package paths; bpo39769.""" return self._test_ddir_only(ddir="<a prefix>", parallel=False) def test_ddir_multiple_workers(self): """Recursive compile_dir ddir= contains package paths; bpo39769.""" return self._test_ddir_only(ddir="<a prefix>", parallel=True) def test_ddir_empty_only_one_worker(self): """Recursive compile_dir ddir='' contains package paths; bpo39769.""" return self._test_ddir_only(ddir="", parallel=False) def test_ddir_empty_multiple_workers(self): """Recursive compile_dir ddir='' contains package paths; bpo39769.""" return self._test_ddir_only(ddir="", parallel=True) class CommmandLineTestsWithSourceEpoch(CommandLineTestsBase, unittest.TestCase, metaclass=SourceDateEpochTestMeta, source_date_epoch=True): pass class CommmandLineTestsNoSourceEpoch(CommandLineTestsBase, unittest.TestCase, metaclass=SourceDateEpochTestMeta, source_date_epoch=False): 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/test_getopt.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_getopt.py
# test_getopt.py # David Goodger <dgoodger@bigfoot.com> 2000-08-19 from test.support import verbose, run_doctest, EnvironmentVarGuard import unittest import getopt sentinel = object() class GetoptTests(unittest.TestCase): def setUp(self): self.env = EnvironmentVarGuard() if "POSIXLY_CORRECT" in self.env: del self.env["POSIXLY_CORRECT"] def tearDown(self): self.env.__exit__() del self.env def assertError(self, *args, **kwargs): self.assertRaises(getopt.GetoptError, *args, **kwargs) def test_short_has_arg(self): self.assertTrue(getopt.short_has_arg('a', 'a:')) self.assertFalse(getopt.short_has_arg('a', 'a')) self.assertError(getopt.short_has_arg, 'a', 'b') def test_long_has_args(self): has_arg, option = getopt.long_has_args('abc', ['abc=']) self.assertTrue(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abc']) self.assertFalse(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abcd']) self.assertFalse(has_arg) self.assertEqual(option, 'abcd') self.assertError(getopt.long_has_args, 'abc', ['def']) self.assertError(getopt.long_has_args, 'abc', []) self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde']) def test_do_shorts(self): opts, args = getopt.do_shorts([], 'a', 'a', []) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a1', 'a:', []) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) #opts, args = getopt.do_shorts([], 'a=1', 'a:', []) #self.assertEqual(opts, [('-a', '1')]) #self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, ['2']) self.assertError(getopt.do_shorts, [], 'a1', 'a', []) self.assertError(getopt.do_shorts, [], 'a', 'a:', []) def test_do_longs(self): opts, args = getopt.do_longs([], 'abc', ['abc'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abc='], []) self.assertEqual(opts, [('--abc', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abcd='], []) self.assertEqual(opts, [('--abcd', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) # Much like the preceding, except with a non-alpha character ("-") in # option name that precedes "="; failed in # http://python.org/sf/126863 opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], []) self.assertEqual(opts, [('--foo', '42')]) self.assertEqual(args, []) self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], []) self.assertError(getopt.do_longs, [], 'abc', ['abc='], []) def test_getopt(self): # note: the empty string between '-a' and '--beta' is significant: # it simulates an empty string option argument ('-a ""') on the # command line. cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '', '--beta', 'arg1', 'arg2'] opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta']) self.assertEqual(opts, [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''), ('-a', '3'), ('-a', ''), ('--beta', '')]) # Note ambiguity of ('-b', '') and ('-a', '') above. This must be # accounted for in the code that calls getopt(). self.assertEqual(args, ['arg1', 'arg2']) self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta']) def test_gnu_getopt(self): # Test handling of GNU style scanning mode. cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2'] # GNU style opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(args, ['arg1']) self.assertEqual(opts, [('-a', ''), ('-b', '1'), ('--alpha', ''), ('--beta', '2')]) # recognize "-" as an argument opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', []) self.assertEqual(args, ['-']) self.assertEqual(opts, [('-a', ''), ('-b', '-')]) # Posix style via + opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) # Posix style via POSIXLY_CORRECT self.env["POSIXLY_CORRECT"] = "1" opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) def test_libref_examples(self): s = """ Examples from the Library Reference: Doc/lib/libgetopt.tex An example using only Unix style options: >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] Using long option names is equally easy: >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] """ import types m = types.ModuleType("libreftest", s) run_doctest(m, verbose) def test_issue4629(self): longopts, shortopts = getopt.getopt(['--help='], '', ['help=']) self.assertEqual(longopts, [('--help', '')]) longopts, shortopts = getopt.getopt(['--help=x'], '', ['help=']) self.assertEqual(longopts, [('--help', 'x')]) self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) 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_codecencodings_iso2022.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_iso2022.py
# Codec encoding tests for ISO 2022 encodings. from test import multibytecodec_support import unittest COMMON_CODEC_TESTS = ( # invalid bytes (b'ab\xFFcd', 'replace', 'ab\uFFFDcd'), (b'ab\x1Bdef', 'replace', 'ab\x1Bdef'), (b'ab\x1B$def', 'replace', 'ab\uFFFD'), ) class Test_ISO2022_JP(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'iso2022_jp' tstring = multibytecodec_support.load_teststring('iso2022_jp') codectests = COMMON_CODEC_TESTS + ( (b'ab\x1BNdef', 'replace', 'ab\x1BNdef'), ) class Test_ISO2022_JP2(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'iso2022_jp_2' tstring = multibytecodec_support.load_teststring('iso2022_jp') codectests = COMMON_CODEC_TESTS + ( (b'ab\x1BNdef', 'replace', 'abdef'), ) class Test_ISO2022_KR(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'iso2022_kr' tstring = multibytecodec_support.load_teststring('iso2022_kr') codectests = COMMON_CODEC_TESTS + ( (b'ab\x1BNdef', 'replace', 'ab\x1BNdef'), ) # iso2022_kr.txt cannot be used to test "chunk coding": the escape # sequence is only written on the first line @unittest.skip('iso2022_kr.txt cannot be used to test "chunk coding"') def test_chunkcoding(self): 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_getattr2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/bad_getattr2.py
def __getattr__(): "Bad one" x = 1 def __dir__(bad_sig): return []
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_fork1.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fork1.py
"""This test checks for correct fork() behavior. """ import _imp as imp import os import signal import sys import threading import time import unittest from test.fork_wait import ForkWait from test.support import (reap_children, get_attribute, import_module, verbose) # Skip test if fork does not exist. get_attribute(os, 'fork') class ForkTest(ForkWait): def wait_impl(self, cpid): deadline = time.monotonic() + 10.0 while time.monotonic() <= deadline: # 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(0.1) self.assertEqual(spid, cpid) self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) def test_threaded_import_lock_fork(self): """Check fork() in main thread works while a subthread is doing an import""" import_started = threading.Event() fake_module_name = "fake test module" partial_module = "partial" complete_module = "complete" def importer(): imp.acquire_lock() sys.modules[fake_module_name] = partial_module import_started.set() time.sleep(0.01) # Give the other thread time to try and acquire. sys.modules[fake_module_name] = complete_module imp.release_lock() t = threading.Thread(target=importer) t.start() import_started.wait() pid = os.fork() try: # PyOS_BeforeFork should have waited for the import to complete # before forking, so the child can recreate the import lock # correctly, but also won't see a partially initialised module if not pid: m = __import__(fake_module_name) if m == complete_module: os._exit(0) else: if verbose > 1: print("Child encountered partial module") os._exit(1) else: t.join() # Exitcode 1 means the child got a partial module (bad.) No # exitcode (but a hang, which manifests as 'got pid 0') # means the child deadlocked (also bad.) self.wait_impl(pid) finally: try: os.kill(pid, signal.SIGKILL) except OSError: pass def test_nested_import_lock_fork(self): """Check fork() in main thread works while the main thread is doing an import""" # Issue 9573: this used to trigger RuntimeError in the child process def fork_with_import_lock(level): release = 0 in_child = False try: try: for i in range(level): imp.acquire_lock() release += 1 pid = os.fork() in_child = not pid finally: for i in range(release): imp.release_lock() except RuntimeError: if in_child: if verbose > 1: print("RuntimeError in child") os._exit(1) raise if in_child: os._exit(0) self.wait_impl(pid) # Check this works with various levels of nested # import in the main thread for level in range(5): fork_with_import_lock(level) 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_math.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py
# Python test set -- math module # XXXX Should not do tests around zero only from test.support import run_unittest, verbose, requires_IEEE_754 from test import support import unittest import math import os import platform import struct import sys import sysconfig eps = 1E-05 NAN = float('nan') INF = float('inf') NINF = float('-inf') FLOAT_MAX = sys.float_info.max # detect evidence of double-rounding: fsum is not always correctly # rounded on machines that suffer from double rounding. x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4) # locate file with test values if __name__ == '__main__': file = sys.argv[0] else: file = __file__ test_dir = os.path.dirname(file) or os.curdir math_testcases = os.path.join(test_dir, 'math_testcases.txt') test_file = os.path.join(test_dir, 'cmath_testcases.txt') def to_ulps(x): """Convert a non-NaN float x to an integer, in such a way that adjacent floats are converted to adjacent integers. Then abs(ulps(x) - ulps(y)) gives the difference in ulps between two floats. The results from this function will only make sense on platforms where native doubles are represented in IEEE 754 binary64 format. Note: 0.0 and -0.0 are converted to 0 and -1, respectively. """ n = struct.unpack('<q', struct.pack('<d', x))[0] if n < 0: n = ~(n+2**63) return n def ulp(x): """Return the value of the least significant bit of a float x, such that the first float bigger than x is x+ulp(x). Then, given an expected result x and a tolerance of n ulps, the result y should be such that abs(y-x) <= n * ulp(x). The results from this function will only make sense on platforms where native doubles are represented in IEEE 754 binary64 format. """ x = abs(float(x)) if math.isnan(x) or math.isinf(x): return x # Find next float up from x. n = struct.unpack('<q', struct.pack('<d', x))[0] x_next = struct.unpack('<d', struct.pack('<q', n + 1))[0] if math.isinf(x_next): # Corner case: x was the largest finite float. Then it's # not an exact power of two, so we can take the difference # between x and the previous float. x_prev = struct.unpack('<d', struct.pack('<q', n - 1))[0] return x - x_prev else: return x_next - x # Here's a pure Python version of the math.factorial algorithm, for # documentation and comparison purposes. # # Formula: # # factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) # # where # # factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j # # The outer product above is an infinite product, but once i >= n.bit_length, # (n >> i) < 1 and the corresponding term of the product is empty. So only the # finitely many terms for 0 <= i < n.bit_length() contribute anything. # # We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner # product in the formula above starts at 1 for i == n.bit_length(); for each i # < n.bit_length() we get the inner product for i from that for i + 1 by # multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, # this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). def count_set_bits(n): """Number of '1' bits in binary expansion of a nonnnegative integer.""" return 1 + count_set_bits(n & n - 1) if n else 0 def partial_product(start, stop): """Product of integers in range(start, stop, 2), computed recursively. start and stop should both be odd, with start <= stop. """ numfactors = (stop - start) >> 1 if not numfactors: return 1 elif numfactors == 1: return start else: mid = (start + numfactors) | 1 return partial_product(start, mid) * partial_product(mid, stop) def py_factorial(n): """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" described at http://www.luschny.de/math/factorial/binarysplitfact.html """ inner = outer = 1 for i in reversed(range(n.bit_length())): inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) outer *= inner return outer << (n - count_set_bits(n)) def ulp_abs_check(expected, got, ulp_tol, abs_tol): """Given finite floats `expected` and `got`, check that they're approximately equal to within the given number of ulps or the given absolute tolerance, whichever is bigger. Returns None on success and an error message on failure. """ ulp_error = abs(to_ulps(expected) - to_ulps(got)) abs_error = abs(expected - got) # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol. if abs_error <= abs_tol or ulp_error <= ulp_tol: return None else: fmt = ("error = {:.3g} ({:d} ulps); " "permitted error = {:.3g} or {:d} ulps") return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol) def parse_mtestfile(fname): """Parse a file with test values -- starts a comment blank lines, or lines containing only a comment, are ignored other lines are expected to have the form id fn arg -> expected [flag]* """ with open(fname) as fp: for line in fp: # strip comments, and skip blank lines if '--' in line: line = line[:line.index('--')] if not line.strip(): continue lhs, rhs = line.split('->') id, fn, arg = lhs.split() rhs_pieces = rhs.split() exp = rhs_pieces[0] flags = rhs_pieces[1:] yield (id, fn, float(arg), float(exp), flags) def parse_testfile(fname): """Parse a file with test values Empty lines or lines starting with -- are ignored yields id, fn, arg_real, arg_imag, exp_real, exp_imag """ with open(fname) as fp: for line in fp: # skip comment lines and blank lines if line.startswith('--') or not line.strip(): continue lhs, rhs = line.split('->') id, fn, arg_real, arg_imag = lhs.split() rhs_pieces = rhs.split() exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1] flags = rhs_pieces[2:] yield (id, fn, float(arg_real), float(arg_imag), float(exp_real), float(exp_imag), flags) def result_check(expected, got, ulp_tol=5, abs_tol=0.0): # Common logic of MathTests.(ftest, test_testcases, test_mtestcases) """Compare arguments expected and got, as floats, if either is a float, using a tolerance expressed in multiples of ulp(expected) or absolutely (if given and greater). As a convenience, when neither argument is a float, and for non-finite floats, exact equality is demanded. Also, nan==nan as far as this function is concerned. Returns None on success and an error message on failure. """ # Check exactly equal (applies also to strings representing exceptions) if got == expected: return None failure = "not equal" # Turn mixed float and int comparison (e.g. floor()) to all-float if isinstance(expected, float) and isinstance(got, int): got = float(got) elif isinstance(got, float) and isinstance(expected, int): expected = float(expected) if isinstance(expected, float) and isinstance(got, float): if math.isnan(expected) and math.isnan(got): # Pass, since both nan failure = None elif math.isinf(expected) or math.isinf(got): # We already know they're not equal, drop through to failure pass else: # Both are finite floats (now). Are they close enough? failure = ulp_abs_check(expected, got, ulp_tol, abs_tol) # arguments are not equal, and if numeric, are too far apart if failure is not None: fail_fmt = "expected {!r}, got {!r}" fail_msg = fail_fmt.format(expected, got) fail_msg += ' ({})'.format(failure) return fail_msg else: return None # Class providing an __index__ method. class MyIndexable(object): def __init__(self, value): self.value = value def __index__(self): return self.value class MathTests(unittest.TestCase): def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0): """Compare arguments expected and got, as floats, if either is a float, using a tolerance expressed in multiples of ulp(expected) or absolutely, whichever is greater. As a convenience, when neither argument is a float, and for non-finite floats, exact equality is demanded. Also, nan==nan in this function. """ failure = result_check(expected, got, ulp_tol, abs_tol) if failure is not None: self.fail("{}: {}".format(name, failure)) def testConstants(self): # Ref: Abramowitz & Stegun (Dover, 1965) self.ftest('pi', math.pi, 3.141592653589793238462643) self.ftest('e', math.e, 2.718281828459045235360287) self.assertEqual(math.tau, 2*math.pi) def testAcos(self): self.assertRaises(TypeError, math.acos) self.ftest('acos(-1)', math.acos(-1), math.pi) self.ftest('acos(0)', math.acos(0), math.pi/2) self.ftest('acos(1)', math.acos(1), 0) self.assertRaises(ValueError, math.acos, INF) self.assertRaises(ValueError, math.acos, NINF) self.assertRaises(ValueError, math.acos, 1 + eps) self.assertRaises(ValueError, math.acos, -1 - eps) self.assertTrue(math.isnan(math.acos(NAN))) def testAcosh(self): self.assertRaises(TypeError, math.acosh) self.ftest('acosh(1)', math.acosh(1), 0) self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168) self.assertRaises(ValueError, math.acosh, 0) self.assertRaises(ValueError, math.acosh, -1) self.assertEqual(math.acosh(INF), INF) self.assertRaises(ValueError, math.acosh, NINF) self.assertTrue(math.isnan(math.acosh(NAN))) def testAsin(self): self.assertRaises(TypeError, math.asin) self.ftest('asin(-1)', math.asin(-1), -math.pi/2) self.ftest('asin(0)', math.asin(0), 0) self.ftest('asin(1)', math.asin(1), math.pi/2) self.assertRaises(ValueError, math.asin, INF) self.assertRaises(ValueError, math.asin, NINF) self.assertRaises(ValueError, math.asin, 1 + eps) self.assertRaises(ValueError, math.asin, -1 - eps) self.assertTrue(math.isnan(math.asin(NAN))) def testAsinh(self): self.assertRaises(TypeError, math.asinh) self.ftest('asinh(0)', math.asinh(0), 0) self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305) self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) self.assertEqual(math.asinh(INF), INF) self.assertEqual(math.asinh(NINF), NINF) self.assertTrue(math.isnan(math.asinh(NAN))) def testAtan(self): self.assertRaises(TypeError, math.atan) self.ftest('atan(-1)', math.atan(-1), -math.pi/4) self.ftest('atan(0)', math.atan(0), 0) self.ftest('atan(1)', math.atan(1), math.pi/4) self.ftest('atan(inf)', math.atan(INF), math.pi/2) self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) self.assertTrue(math.isnan(math.atan(NAN))) def testAtanh(self): self.assertRaises(TypeError, math.atan) self.ftest('atanh(0)', math.atanh(0), 0) self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489) self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489) self.assertRaises(ValueError, math.atanh, 1) self.assertRaises(ValueError, math.atanh, -1) self.assertRaises(ValueError, math.atanh, INF) self.assertRaises(ValueError, math.atanh, NINF) self.assertTrue(math.isnan(math.atanh(NAN))) def testAtan2(self): self.assertRaises(TypeError, math.atan2) self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) self.ftest('atan2(0, 1)', math.atan2(0, 1), 0) self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) # math.atan2(0, x) self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi) self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi) self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi) self.assertEqual(math.atan2(0., 0.), 0.) self.assertEqual(math.atan2(0., 2.3), 0.) self.assertEqual(math.atan2(0., INF), 0.) self.assertTrue(math.isnan(math.atan2(0., NAN))) # math.atan2(-0, x) self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi) self.assertEqual(math.atan2(-0., 0.), -0.) self.assertEqual(math.atan2(-0., 2.3), -0.) self.assertEqual(math.atan2(-0., INF), -0.) self.assertTrue(math.isnan(math.atan2(-0., NAN))) # math.atan2(INF, x) self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2) self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) self.assertTrue(math.isnan(math.atan2(INF, NAN))) # math.atan2(NINF, x) self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2) self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) self.assertTrue(math.isnan(math.atan2(NINF, NAN))) # math.atan2(+finite, x) self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) self.assertEqual(math.atan2(2.3, INF), 0.) self.assertTrue(math.isnan(math.atan2(2.3, NAN))) # math.atan2(-finite, x) self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) self.assertEqual(math.atan2(-2.3, INF), -0.) self.assertTrue(math.isnan(math.atan2(-2.3, NAN))) # math.atan2(NAN, x) self.assertTrue(math.isnan(math.atan2(NAN, NINF))) self.assertTrue(math.isnan(math.atan2(NAN, -2.3))) self.assertTrue(math.isnan(math.atan2(NAN, -0.))) self.assertTrue(math.isnan(math.atan2(NAN, 0.))) self.assertTrue(math.isnan(math.atan2(NAN, 2.3))) self.assertTrue(math.isnan(math.atan2(NAN, INF))) self.assertTrue(math.isnan(math.atan2(NAN, NAN))) def testCeil(self): self.assertRaises(TypeError, math.ceil) self.assertEqual(int, type(math.ceil(0.5))) self.ftest('ceil(0.5)', math.ceil(0.5), 1) self.ftest('ceil(1.0)', math.ceil(1.0), 1) self.ftest('ceil(1.5)', math.ceil(1.5), 2) self.ftest('ceil(-0.5)', math.ceil(-0.5), 0) self.ftest('ceil(-1.0)', math.ceil(-1.0), -1) self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) #self.assertEqual(math.ceil(INF), INF) #self.assertEqual(math.ceil(NINF), NINF) #self.assertTrue(math.isnan(math.ceil(NAN))) class TestCeil: def __ceil__(self): return 42 class TestNoCeil: pass self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42) self.assertRaises(TypeError, math.ceil, TestNoCeil()) t = TestNoCeil() t.__ceil__ = lambda *args: args self.assertRaises(TypeError, math.ceil, t) self.assertRaises(TypeError, math.ceil, t, 0) @requires_IEEE_754 def testCopysign(self): self.assertEqual(math.copysign(1, 42), 1.0) self.assertEqual(math.copysign(0., 42), 0.0) self.assertEqual(math.copysign(1., -42), -1.0) self.assertEqual(math.copysign(3, 0.), 3.0) self.assertEqual(math.copysign(4., -0.), -4.0) self.assertRaises(TypeError, math.copysign) # copysign should let us distinguish signs of zeros self.assertEqual(math.copysign(1., 0.), 1.) self.assertEqual(math.copysign(1., -0.), -1.) self.assertEqual(math.copysign(INF, 0.), INF) self.assertEqual(math.copysign(INF, -0.), NINF) self.assertEqual(math.copysign(NINF, 0.), INF) self.assertEqual(math.copysign(NINF, -0.), NINF) # and of infinities self.assertEqual(math.copysign(1., INF), 1.) self.assertEqual(math.copysign(1., NINF), -1.) self.assertEqual(math.copysign(INF, INF), INF) self.assertEqual(math.copysign(INF, NINF), NINF) self.assertEqual(math.copysign(NINF, INF), INF) self.assertEqual(math.copysign(NINF, NINF), NINF) self.assertTrue(math.isnan(math.copysign(NAN, 1.))) self.assertTrue(math.isnan(math.copysign(NAN, INF))) self.assertTrue(math.isnan(math.copysign(NAN, NINF))) self.assertTrue(math.isnan(math.copysign(NAN, NAN))) # copysign(INF, NAN) may be INF or it may be NINF, since # we don't know whether the sign bit of NAN is set on any # given platform. self.assertTrue(math.isinf(math.copysign(INF, NAN))) # similarly, copysign(2., NAN) could be 2. or -2. self.assertEqual(abs(math.copysign(2., NAN)), 2.) def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=ulp(1)) self.ftest('cos(0)', math.cos(0), 1) self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=ulp(1)) self.ftest('cos(pi)', math.cos(math.pi), -1) try: self.assertTrue(math.isnan(math.cos(INF))) self.assertTrue(math.isnan(math.cos(NINF))) except ValueError: self.assertRaises(ValueError, math.cos, INF) self.assertRaises(ValueError, math.cos, NINF) self.assertTrue(math.isnan(math.cos(NAN))) def testCosh(self): self.assertRaises(TypeError, math.cosh) self.ftest('cosh(0)', math.cosh(0), 1) self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert self.assertEqual(math.cosh(INF), INF) self.assertEqual(math.cosh(NINF), INF) self.assertTrue(math.isnan(math.cosh(NAN))) def testDegrees(self): self.assertRaises(TypeError, math.degrees) self.ftest('degrees(pi)', math.degrees(math.pi), 180.0) self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0) self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) self.ftest('degrees(0)', math.degrees(0), 0) def testExp(self): self.assertRaises(TypeError, math.exp) self.ftest('exp(-1)', math.exp(-1), 1/math.e) self.ftest('exp(0)', math.exp(0), 1) self.ftest('exp(1)', math.exp(1), math.e) self.assertEqual(math.exp(INF), INF) self.assertEqual(math.exp(NINF), 0.) self.assertTrue(math.isnan(math.exp(NAN))) self.assertRaises(OverflowError, math.exp, 1000000) def testFabs(self): self.assertRaises(TypeError, math.fabs) self.ftest('fabs(-1)', math.fabs(-1), 1) self.ftest('fabs(0)', math.fabs(0), 0) self.ftest('fabs(1)', math.fabs(1), 1) def testFactorial(self): self.assertEqual(math.factorial(0), 1) self.assertEqual(math.factorial(0.0), 1) total = 1 for i in range(1, 1000): total *= i self.assertEqual(math.factorial(i), total) self.assertEqual(math.factorial(float(i)), total) self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) self.assertRaises(ValueError, math.factorial, -1.0) self.assertRaises(ValueError, math.factorial, -10**100) self.assertRaises(ValueError, math.factorial, -1e100) self.assertRaises(ValueError, math.factorial, math.pi) # Other implementations may place different upper bounds. @support.cpython_only def testFactorialHugeInputs(self): # Currently raises ValueError for inputs that are too large # to fit into a C long. self.assertRaises(OverflowError, math.factorial, 10**100) self.assertRaises(OverflowError, math.factorial, 1e100) def testFloor(self): self.assertRaises(TypeError, math.floor) self.assertEqual(int, type(math.floor(0.5))) self.ftest('floor(0.5)', math.floor(0.5), 0) self.ftest('floor(1.0)', math.floor(1.0), 1) self.ftest('floor(1.5)', math.floor(1.5), 1) self.ftest('floor(-0.5)', math.floor(-0.5), -1) self.ftest('floor(-1.0)', math.floor(-1.0), -1) self.ftest('floor(-1.5)', math.floor(-1.5), -2) # pow() relies on floor() to check for integers # This fails on some platforms - so check it here self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167) self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167) #self.assertEqual(math.ceil(INF), INF) #self.assertEqual(math.ceil(NINF), NINF) #self.assertTrue(math.isnan(math.floor(NAN))) class TestFloor: def __floor__(self): return 42 class TestNoFloor: pass self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42) self.assertRaises(TypeError, math.floor, TestNoFloor()) t = TestNoFloor() t.__floor__ = lambda *args: args self.assertRaises(TypeError, math.floor, t) self.assertRaises(TypeError, math.floor, t, 0) def testFmod(self): self.assertRaises(TypeError, math.fmod) self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0) self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0) self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0) self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0) self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0) self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0) self.assertTrue(math.isnan(math.fmod(NAN, 1.))) self.assertTrue(math.isnan(math.fmod(1., NAN))) self.assertTrue(math.isnan(math.fmod(NAN, NAN))) self.assertRaises(ValueError, math.fmod, 1., 0.) self.assertRaises(ValueError, math.fmod, INF, 1.) self.assertRaises(ValueError, math.fmod, NINF, 1.) self.assertRaises(ValueError, math.fmod, INF, 0.) self.assertEqual(math.fmod(3.0, INF), 3.0) self.assertEqual(math.fmod(-3.0, INF), -3.0) self.assertEqual(math.fmod(3.0, NINF), 3.0) self.assertEqual(math.fmod(-3.0, NINF), -3.0) self.assertEqual(math.fmod(0.0, 3.0), 0.0) self.assertEqual(math.fmod(0.0, NINF), 0.0) def testFrexp(self): self.assertRaises(TypeError, math.frexp) def testfrexp(name, result, expected): (mant, exp), (emant, eexp) = result, expected if abs(mant-emant) > eps or exp != eexp: self.fail('%s returned %r, expected %r'%\ (name, result, expected)) testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) testfrexp('frexp(0)', math.frexp(0), (0, 0)) testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) self.assertEqual(math.frexp(INF)[0], INF) self.assertEqual(math.frexp(NINF)[0], NINF) self.assertTrue(math.isnan(math.frexp(NAN)[0])) @requires_IEEE_754 @unittest.skipIf(HAVE_DOUBLE_ROUNDING, "fsum is not exact on machines with double rounding") def testFsum(self): # math.fsum relies on exact rounding for correct operation. # There's a known problem with IA32 floating-point that causes # inexact rounding in some situations, and will cause the # math.fsum tests below to fail; see issue #2937. On non IEEE # 754 platforms, and on IEEE 754 platforms that exhibit the # problem described in issue #2937, we simply skip the whole # test. # Python version of math.fsum, for comparison. Uses a # different algorithm based on frexp, ldexp and integer # arithmetic. from sys import float_info mant_dig = float_info.mant_dig etiny = float_info.min_exp - mant_dig def msum(iterable): """Full precision summation. Compute sum(iterable) without any intermediate accumulation of error. Based on the 'lsum' function at http://code.activestate.com/recipes/393090/ """ tmant, texp = 0, 0 for x in iterable: mant, exp = math.frexp(x) mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig if texp > exp: tmant <<= texp-exp texp = exp else: mant <<= exp-texp tmant += mant # Round tmant * 2**texp to a float. The original recipe # used float(str(tmant)) * 2.0**texp for this, but that's # a little unsafe because str -> float conversion can't be # relied upon to do correct rounding on all platforms. tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp) if tail > 0: h = 1 << (tail-1) tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1) texp += tail return math.ldexp(tmant, texp) test_values = [ ([], 0.0), ([0.0], 0.0), ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100), ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0), ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0), ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0), ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0), ([1./n for n in range(1, 1001)], float.fromhex('0x1.df11f45f4e61ap+2')), ([(-1.)**n/n for n in range(1, 1001)], float.fromhex('-0x1.62a2af1bd3624p-1')), ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0), ([1e16, 1., 1e-16], 10000000000000002.0), ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0), # exercise code for resizing partials array ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] + [-2.**1022], float.fromhex('0x1.5555555555555p+970')), ] for i, (vals, expected) in enumerate(test_values): try: actual = math.fsum(vals) except OverflowError: self.fail("test %d failed: got OverflowError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) except ValueError: self.fail("test %d failed: got ValueError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) self.assertEqual(actual, expected) from random import random, gauss, shuffle for j in range(1000): vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10 s = 0 for i in range(200): v = gauss(0, random()) ** 7 - s s += v vals.append(v) shuffle(vals) s = msum(vals) self.assertEqual(msum(vals), math.fsum(vals)) def testGcd(self): gcd = math.gcd self.assertEqual(gcd(0, 0), 0) self.assertEqual(gcd(1, 0), 1) self.assertEqual(gcd(-1, 0), 1) self.assertEqual(gcd(0, 1), 1) self.assertEqual(gcd(0, -1), 1) self.assertEqual(gcd(7, 1), 1) self.assertEqual(gcd(7, -1), 1) self.assertEqual(gcd(-23, 15), 1) self.assertEqual(gcd(120, 84), 12) self.assertEqual(gcd(84, -120), 12) self.assertEqual(gcd(1216342683557601535506311712, 436522681849110124616458784), 32) c = 652560 x = 434610456570399902378880679233098819019853229470286994367836600566 y = 1064502245825115327754847244914921553977 a = x * c b = y * c self.assertEqual(gcd(a, b), c) self.assertEqual(gcd(b, a), c) self.assertEqual(gcd(-a, b), c) self.assertEqual(gcd(b, -a), c) self.assertEqual(gcd(a, -b), c) self.assertEqual(gcd(-b, a), c) self.assertEqual(gcd(-a, -b), c) self.assertEqual(gcd(-b, -a), c) c = 576559230871654959816130551884856912003141446781646602790216406874 a = x * c b = y * c self.assertEqual(gcd(a, b), c) self.assertEqual(gcd(b, a), c) self.assertEqual(gcd(-a, b), c) self.assertEqual(gcd(b, -a), c) self.assertEqual(gcd(a, -b), c) self.assertEqual(gcd(-b, a), c) self.assertEqual(gcd(-a, -b), c) self.assertEqual(gcd(-b, -a), c) self.assertRaises(TypeError, gcd, 120.0, 84) self.assertRaises(TypeError, gcd, 120, 84.0) self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12) def testHypot(self): self.assertRaises(TypeError, math.hypot) self.ftest('hypot(0,0)', math.hypot(0,0), 0) self.ftest('hypot(3,4)', math.hypot(3,4), 5) self.assertEqual(math.hypot(NAN, INF), INF) self.assertEqual(math.hypot(INF, NAN), INF) self.assertEqual(math.hypot(NAN, NINF), INF) self.assertEqual(math.hypot(NINF, NAN), INF) self.assertRaises(OverflowError, math.hypot, FLOAT_MAX, FLOAT_MAX) self.assertTrue(math.isnan(math.hypot(1.0, NAN))) self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) def testLdexp(self): self.assertRaises(TypeError, math.ldexp) self.ftest('ldexp(0,1)', math.ldexp(0,1), 0) self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) self.assertRaises(OverflowError, math.ldexp, 1., 1000000) self.assertRaises(OverflowError, math.ldexp, -1., 1000000) self.assertEqual(math.ldexp(1., -1000000), 0.) self.assertEqual(math.ldexp(-1., -1000000), -0.) self.assertEqual(math.ldexp(INF, 30), INF) self.assertEqual(math.ldexp(NINF, -213), NINF) self.assertTrue(math.isnan(math.ldexp(NAN, 0))) # large second argument for n in [10**5, 10**10, 10**20, 10**40]: self.assertEqual(math.ldexp(INF, -n), INF) self.assertEqual(math.ldexp(NINF, -n), NINF) self.assertEqual(math.ldexp(1., -n), 0.) self.assertEqual(math.ldexp(-1., -n), -0.) self.assertEqual(math.ldexp(0., -n), 0.) self.assertEqual(math.ldexp(-0., -n), -0.) self.assertTrue(math.isnan(math.ldexp(NAN, -n))) self.assertRaises(OverflowError, math.ldexp, 1., n) self.assertRaises(OverflowError, math.ldexp, -1., n) self.assertEqual(math.ldexp(0., n), 0.) self.assertEqual(math.ldexp(-0., n), -0.) self.assertEqual(math.ldexp(INF, n), INF) self.assertEqual(math.ldexp(NINF, n), NINF) self.assertTrue(math.isnan(math.ldexp(NAN, n))) def testLog(self): self.assertRaises(TypeError, math.log) self.ftest('log(1/e)', math.log(1/math.e), -1) self.ftest('log(1)', math.log(1), 0) self.ftest('log(e)', math.log(math.e), 1) self.ftest('log(32,2)', math.log(32,2), 5) self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) self.ftest('log(10**1000)', math.log(10**1000),
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_strtod.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_strtod.py
# Tests for the correctly-rounded string -> float conversions # introduced in Python 2.7 and 3.1. import random import unittest import re import sys import test.support if getattr(sys, 'float_repr_style', '') != 'short': raise unittest.SkipTest('correctly-rounded string->float conversions ' 'not available on this system') # Correctly rounded str -> float in pure Python, for comparison. strtod_parser = re.compile(r""" # A numeric string consists of: (?P<sign>[-+])? # an optional sign, followed by (?=\d|\.\d) # a number with at least one digit (?P<int>\d*) # having a (possibly empty) integer part (?:\.(?P<frac>\d*))? # followed by an optional fractional part (?:E(?P<exp>[-+]?\d+))? # and an optional exponent \Z """, re.VERBOSE | re.IGNORECASE).match # Pure Python version of correctly rounded string->float conversion. # Avoids any use of floating-point by returning the result as a hex string. def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024): """Convert a finite decimal string to a hex string representing an IEEE 754 binary64 float. Return 'inf' or '-inf' on overflow. This function makes no use of floating-point arithmetic at any stage.""" # parse string into a pair of integers 'a' and 'b' such that # abs(decimal value) = a/b, along with a boolean 'negative'. m = strtod_parser(s) if m is None: raise ValueError('invalid numeric string') fraction = m.group('frac') or '' intpart = int(m.group('int') + fraction) exp = int(m.group('exp') or '0') - len(fraction) negative = m.group('sign') == '-' a, b = intpart*10**max(exp, 0), 10**max(0, -exp) # quick return for zeros if not a: return '-0x0.0p+0' if negative else '0x0.0p+0' # compute exponent e for result; may be one too small in the case # that the rounded value of a/b lies in a different binade from a/b d = a.bit_length() - b.bit_length() d += (a >> d if d >= 0 else a << -d) >= b e = max(d, min_exp) - mant_dig # approximate a/b by number of the form q * 2**e; adjust e if necessary a, b = a << max(-e, 0), b << max(e, 0) q, r = divmod(a, b) if 2*r > b or 2*r == b and q & 1: q += 1 if q.bit_length() == mant_dig+1: q //= 2 e += 1 # double check that (q, e) has the right form assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig assert q.bit_length() == mant_dig or e == min_exp - mant_dig # check for overflow and underflow if e + q.bit_length() > max_exp: return '-inf' if negative else 'inf' if not q: return '-0x0.0p+0' if negative else '0x0.0p+0' # for hex representation, shift so # bits after point is a multiple of 4 hexdigs = 1 + (mant_dig-2)//4 shift = 3 - (mant_dig-2)%4 q, e = q << shift, e - shift return '{}0x{:x}.{:0{}x}p{:+d}'.format( '-' if negative else '', q // 16**hexdigs, q % 16**hexdigs, hexdigs, e + 4*hexdigs) TEST_SIZE = 10 class StrtodTests(unittest.TestCase): def check_strtod(self, s): """Compare the result of Python's builtin correctly rounded string->float conversion (using float) to a pure Python correctly rounded string->float implementation. Fail if the two methods give different results.""" try: fs = float(s) except OverflowError: got = '-inf' if s[0] == '-' else 'inf' except MemoryError: got = 'memory error' else: got = fs.hex() expected = strtod(s) self.assertEqual(expected, got, "Incorrectly rounded str->float conversion for {}: " "expected {}, got {}".format(s, expected, got)) def test_short_halfway_cases(self): # exact halfway cases with a small number of significant digits for k in 0, 5, 10, 15, 20: # upper = smallest integer >= 2**54/5**k upper = -(-2**54//5**k) # lower = smallest odd number >= 2**53/5**k lower = -(-2**53//5**k) if lower % 2 == 0: lower += 1 for i in range(TEST_SIZE): # Select a random odd n in [2**53/5**k, # 2**54/5**k). Then n * 10**k gives a halfway case # with small number of significant digits. n, e = random.randrange(lower, upper, 2), k # Remove any additional powers of 5. while n % 5 == 0: n, e = n // 5, e + 1 assert n % 10 in (1, 3, 7, 9) # Try numbers of the form n * 2**p2 * 10**e, p2 >= 0, # until n * 2**p2 has more than 20 significant digits. digits, exponent = n, e while digits < 10**20: s = '{}e{}'.format(digits, exponent) self.check_strtod(s) # Same again, but with extra trailing zeros. s = '{}e{}'.format(digits * 10**40, exponent - 40) self.check_strtod(s) digits *= 2 # Try numbers of the form n * 5**p2 * 10**(e - p5), p5 # >= 0, with n * 5**p5 < 10**20. digits, exponent = n, e while digits < 10**20: s = '{}e{}'.format(digits, exponent) self.check_strtod(s) # Same again, but with extra trailing zeros. s = '{}e{}'.format(digits * 10**40, exponent - 40) self.check_strtod(s) digits *= 5 exponent -= 1 def test_halfway_cases(self): # test halfway cases for the round-half-to-even rule for i in range(100 * TEST_SIZE): # bit pattern for a random finite positive (or +0.0) float bits = random.randrange(2047*2**52) # convert bit pattern to a number of the form m * 2**e e, m = divmod(bits, 2**52) if e: m, e = m + 2**52, e - 1 e -= 1074 # add 0.5 ulps m, e = 2*m + 1, e - 1 # convert to a decimal string if e >= 0: digits = m << e exponent = 0 else: # m * 2**e = (m * 5**-e) * 10**e digits = m * 5**-e exponent = e s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_boundaries(self): # boundaries expressed as triples (n, e, u), where # n*10**e is an approximation to the boundary value and # u*10**e is 1ulp boundaries = [ (10000000000000000000, -19, 1110), # a power of 2 boundary (1.0) (17976931348623159077, 289, 1995), # overflow boundary (2.**1024) (22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022) (0, -327, 4941), # zero ] for n, e, u in boundaries: for j in range(1000): digits = n + random.randrange(-3*u, 3*u) exponent = e s = '{}e{}'.format(digits, exponent) self.check_strtod(s) n *= 10 u *= 10 e -= 1 def test_underflow_boundary(self): # test values close to 2**-1075, the underflow boundary; similar # to boundary_tests, except that the random error doesn't scale # with n for exponent in range(-400, -320): base = 10**-exponent // 2**1075 for j in range(TEST_SIZE): digits = base + random.randrange(-1000, 1000) s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_bigcomp(self): for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50: dig10 = 10**ndigs for i in range(10 * TEST_SIZE): digits = random.randrange(dig10) exponent = random.randrange(-400, 400) s = '{}e{}'.format(digits, exponent) self.check_strtod(s) def test_parsing(self): # make '0' more likely to be chosen than other digits digits = '000000123456789' signs = ('+', '-', '') # put together random short valid strings # \d*[.\d*]?e for i in range(1000): for j in range(TEST_SIZE): s = random.choice(signs) intpart_len = random.randrange(5) s += ''.join(random.choice(digits) for _ in range(intpart_len)) if random.choice([True, False]): s += '.' fracpart_len = random.randrange(5) s += ''.join(random.choice(digits) for _ in range(fracpart_len)) else: fracpart_len = 0 if random.choice([True, False]): s += random.choice(['e', 'E']) s += random.choice(signs) exponent_len = random.randrange(1, 4) s += ''.join(random.choice(digits) for _ in range(exponent_len)) if intpart_len + fracpart_len: self.check_strtod(s) else: try: float(s) except ValueError: pass else: assert False, "expected ValueError" @test.support.bigmemtest(size=test.support._2G+10, memuse=3, dry_run=False) def test_oversized_digit_strings(self, maxsize): # Input string whose length doesn't fit in an INT. s = "1." + "1" * maxsize with self.assertRaises(ValueError): float(s) del s s = "0." + "0" * maxsize + "1" with self.assertRaises(ValueError): float(s) del s def test_large_exponents(self): # Verify that the clipping of the exponent in strtod doesn't affect the # output values. def positive_exp(n): """ Long string with value 1.0 and exponent n""" return '0.{}1e+{}'.format('0'*(n-1), n) def negative_exp(n): """ Long string with value 1.0 and exponent -n""" return '1{}e-{}'.format('0'*n, n) self.assertEqual(float(positive_exp(10000)), 1.0) self.assertEqual(float(positive_exp(20000)), 1.0) self.assertEqual(float(positive_exp(30000)), 1.0) self.assertEqual(float(negative_exp(10000)), 1.0) self.assertEqual(float(negative_exp(20000)), 1.0) self.assertEqual(float(negative_exp(30000)), 1.0) def test_particular(self): # inputs that produced crashes or incorrectly rounded results with # previous versions of dtoa.c, for various reasons test_strings = [ # issue 7632 bug 1, originally reported failing case '2183167012312112312312.23538020374420446192e-370', # 5 instances of issue 7632 bug 2 '12579816049008305546974391768996369464963024663104e-357', '17489628565202117263145367596028389348922981857013e-357', '18487398785991994634182916638542680759613590482273e-357', '32002864200581033134358724675198044527469366773928e-358', '94393431193180696942841837085033647913224148539854e-358', '73608278998966969345824653500136787876436005957953e-358', '64774478836417299491718435234611299336288082136054e-358', '13704940134126574534878641876947980878824688451169e-357', '46697445774047060960624497964425416610480524760471e-358', # failing case for bug introduced by METD in r77451 (attempted # fix for issue 7632, bug 2), and fixed in r77482. '28639097178261763178489759107321392745108491825303e-311', # two numbers demonstrating a flaw in the bigcomp 'dig == 0' # correction block (issue 7632, bug 3) '1.00000000000000001e44', '1.0000000000000000100000000000000000000001e44', # dtoa.c bug for numbers just smaller than a power of 2 (issue # 7632, bug 4) '99999999999999994487665465554760717039532578546e-47', # failing case for off-by-one error introduced by METD in # r77483 (dtoa.c cleanup), fixed in r77490 '965437176333654931799035513671997118345570045914469' #... '6213413350821416312194420007991306908470147322020121018368e0', # incorrect lsb detection for round-half-to-even when # bc->scale != 0 (issue 7632, bug 6). '104308485241983990666713401708072175773165034278685' #... '682646111762292409330928739751702404658197872319129' #... '036519947435319418387839758990478549477777586673075' #... '945844895981012024387992135617064532141489278815239' #... '849108105951619997829153633535314849999674266169258' #... '928940692239684771590065027025835804863585454872499' #... '320500023126142553932654370362024104462255244034053' #... '203998964360882487378334860197725139151265590832887' #... '433736189468858614521708567646743455601905935595381' #... '852723723645799866672558576993978025033590728687206' #... '296379801363024094048327273913079612469982585674824' #... '156000783167963081616214710691759864332339239688734' #... '656548790656486646106983450809073750535624894296242' #... '072010195710276073042036425579852459556183541199012' #... '652571123898996574563824424330960027873516082763671875e-1075', # demonstration that original fix for issue 7632 bug 1 was # buggy; the exit condition was too strong '247032822920623295e-341', # demonstrate similar problem to issue 7632 bug1: crash # with 'oversized quotient in quorem' message. '99037485700245683102805043437346965248029601286431e-373', '99617639833743863161109961162881027406769510558457e-373', '98852915025769345295749278351563179840130565591462e-372', '99059944827693569659153042769690930905148015876788e-373', '98914979205069368270421829889078356254059760327101e-372', # issue 7632 bug 5: the following 2 strings convert differently '1000000000000000000000000000000000000000e-16', '10000000000000000000000000000000000000000e-17', # issue 7632 bug 7 '991633793189150720000000000000000000000000000000000000000e-33', # And another, similar, failing halfway case '4106250198039490000000000000000000000000000000000000000e-38', # issue 7632 bug 8: the following produced 10.0 '10.900000000000000012345678912345678912345', # two humongous values from issue 7743 '116512874940594195638617907092569881519034793229385' #... '228569165191541890846564669771714896916084883987920' #... '473321268100296857636200926065340769682863349205363' #... '349247637660671783209907949273683040397979984107806' #... '461822693332712828397617946036239581632976585100633' #... '520260770761060725403904123144384571612073732754774' #... '588211944406465572591022081973828448927338602556287' #... '851831745419397433012491884869454462440536895047499' #... '436551974649731917170099387762871020403582994193439' #... '761933412166821484015883631622539314203799034497982' #... '130038741741727907429575673302461380386596501187482' #... '006257527709842179336488381672818798450229339123527' #... '858844448336815912020452294624916993546388956561522' #... '161875352572590420823607478788399460162228308693742' #... '05287663441403533948204085390898399055004119873046875e-1075', '525440653352955266109661060358202819561258984964913' #... '892256527849758956045218257059713765874251436193619' #... '443248205998870001633865657517447355992225852945912' #... '016668660000210283807209850662224417504752264995360' #... '631512007753855801075373057632157738752800840302596' #... '237050247910530538250008682272783660778181628040733' #... '653121492436408812668023478001208529190359254322340' #... '397575185248844788515410722958784640926528544043090' #... '115352513640884988017342469275006999104519620946430' #... '818767147966495485406577703972687838176778993472989' #... '561959000047036638938396333146685137903018376496408' #... '319705333868476925297317136513970189073693314710318' #... '991252811050501448326875232850600451776091303043715' #... '157191292827614046876950225714743118291034780466325' #... '085141343734564915193426994587206432697337118211527' #... '278968731294639353354774788602467795167875117481660' #... '4738791256853675690543663283782215866825e-1180', # exercise exit conditions in bigcomp comparison loop '2602129298404963083833853479113577253105939995688e2', '260212929840496308383385347911357725310593999568896e0', '26021292984049630838338534791135772531059399956889601e-2', '260212929840496308383385347911357725310593999568895e0', '260212929840496308383385347911357725310593999568897e0', '260212929840496308383385347911357725310593999568996e0', '260212929840496308383385347911357725310593999568866e0', # 2**53 '9007199254740992.00', # 2**1024 - 2**970: exact overflow boundary. All values # smaller than this should round to something finite; any value # greater than or equal to this one overflows. '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497792', # 2**1024 - 2**970 - tiny '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497791.999', # 2**1024 - 2**970 + tiny '179769313486231580793728971405303415079934132710037' #... '826936173778980444968292764750946649017977587207096' #... '330286416692887910946555547851940402630657488671505' #... '820681908902000708383676273854845817711531764475730' #... '270069855571366959622842914819860834936475292719074' #... '168444365510704342711559699508093042880177904174497792.001', # 1 - 2**-54, +-tiny '999999999999999944488848768742172978818416595458984375e-54', '9999999999999999444888487687421729788184165954589843749999999e-54', '9999999999999999444888487687421729788184165954589843750000001e-54', # Value found by Rick Regan that gives a result of 2**-968 # under Gay's dtoa.c (as of Nov 04, 2010); since fixed. # (Fixed some time ago in Python's dtoa.c.) '0.0000000000000000000000000000000000000000100000000' #... '000000000576129113423785429971690421191214034235435' #... '087147763178149762956868991692289869941246658073194' #... '51982237978882039897143840789794921875', ] for s in test_strings: self.check_strtod(s) 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_urllib2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
import unittest from test import support from test import test_urllib import os import io import socket import array import sys import tempfile import subprocess import urllib.request # The proxy bypass method imported below has logic specific to the OSX # proxy config data structure but is testable on all platforms. from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler, HTTPPasswordMgrWithPriorAuth, _parse_proxy, _proxy_bypass_macosx_sysconf, AbstractDigestAuthHandler) from urllib.parse import urlparse import urllib.error import http.client # XXX # Request # CacheFTPHandler (hard to write) # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler class TrivialTests(unittest.TestCase): def test___all__(self): # Verify which names are exposed for module in 'request', 'response', 'parse', 'error', 'robotparser': context = {} exec('from urllib.%s import *' % module, context) del context['__builtins__'] if module == 'request' and os.name == 'nt': u, p = context.pop('url2pathname'), context.pop('pathname2url') self.assertEqual(u.__module__, 'nturl2path') self.assertEqual(p.__module__, 'nturl2path') for k, v in context.items(): self.assertEqual(v.__module__, 'urllib.%s' % module, "%r is exposed in 'urllib.%s' but defined in %r" % (k, module, v.__module__)) def test_trivial(self): # A couple trivial tests self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url') # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/') if os.name == 'nt': file_url = "file:///%s" % fname else: file_url = "file://%s" % fname f = urllib.request.urlopen(file_url) f.read() f.close() def test_parse_http_list(self): tests = [ ('a,b,c', ['a', 'b', 'c']), ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']), ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] for string, list in tests: self.assertEqual(urllib.request.parse_http_list(string), list) def test_URLError_reasonstr(self): err = urllib.error.URLError('reason') self.assertIn(err.reason, str(err)) class RequestHdrsTests(unittest.TestCase): def test_request_headers_dict(self): """ The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset. """ url = "http://example.com" self.assertEqual(Request(url, headers={"Spam-eggs": "blah"} ).headers["Spam-eggs"], "blah") self.assertEqual(Request(url, headers={"spam-EggS": "blah"} ).headers["Spam-eggs"], "blah") def test_request_headers_methods(self): """ Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. Method r.remove_header should remove items both from r.headers and r.unredirected_hdrs dictionaries """ url = "http://example.com" req = Request(url, headers={"Spam-eggs": "blah"}) self.assertTrue(req.has_header("Spam-eggs")) self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')]) req.add_header("Foo-Bar", "baz") self.assertEqual(sorted(req.header_items()), [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]) self.assertFalse(req.has_header("Not-there")) self.assertIsNone(req.get_header("Not-there")) self.assertEqual(req.get_header("Not-there", "default"), "default") req.remove_header("Spam-eggs") self.assertFalse(req.has_header("Spam-eggs")) req.add_unredirected_header("Unredirected-spam", "Eggs") self.assertTrue(req.has_header("Unredirected-spam")) req.remove_header("Unredirected-spam") self.assertFalse(req.has_header("Unredirected-spam")) def test_password_manager(self): mgr = urllib.request.HTTPPasswordMgr() add = mgr.add_password find_user_pass = mgr.find_user_password add("Some Realm", "http://example.com/", "joe", "password") add("Some Realm", "http://example.com/ni", "ni", "ni") add("Some Realm", "http://c.example.com:3128", "3", "c") add("Some Realm", "d.example.com", "4", "d") add("Some Realm", "e.example.com:3128", "5", "e") # For the same realm, password set the highest path is the winner. self.assertEqual(find_user_pass("Some Realm", "example.com"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/spam"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/spam/spam"), ('joe', 'password')) # You can have different passwords for different paths. add("c", "http://example.com/foo", "foo", "ni") add("c", "http://example.com/bar", "bar", "nini") self.assertEqual(find_user_pass("c", "http://example.com/foo"), ('foo', 'ni')) self.assertEqual(find_user_pass("c", "http://example.com/bar"), ('bar', 'nini')) # For the same path, newer password should be considered. add("b", "http://example.com/", "first", "blah") add("b", "http://example.com/", "second", "spam") self.assertEqual(find_user_pass("b", "http://example.com/"), ('second', 'spam')) # No special relationship between a.example.com and example.com: add("a", "http://example.com", "1", "a") self.assertEqual(find_user_pass("a", "http://example.com/"), ('1', 'a')) self.assertEqual(find_user_pass("a", "http://a.example.com/"), (None, None)) # Ports: self.assertEqual(find_user_pass("Some Realm", "c.example.com"), (None, None)) self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"), ('3', 'c')) self.assertEqual( find_user_pass("Some Realm", "http://c.example.com:3128"), ('3', 'c')) self.assertEqual(find_user_pass("Some Realm", "d.example.com"), ('4', 'd')) self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"), ('5', 'e')) def test_password_manager_default_port(self): """ The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password. """ mgr = urllib.request.HTTPPasswordMgr() add = mgr.add_password find_user_pass = mgr.find_user_password add("f", "http://g.example.com:80", "10", "j") add("g", "http://h.example.com", "11", "k") add("h", "i.example.com:80", "12", "l") add("i", "j.example.com", "13", "m") self.assertEqual(find_user_pass("f", "g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "g.example.com"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "http://g.example.com"), ('10', 'j')) self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k')) self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("g", "http://h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("h", "i.example.com"), (None, None)) self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("h", "http://i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "j.example.com:80"), (None, None)) self.assertEqual(find_user_pass("i", "http://j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "http://j.example.com:80"), (None, None)) class MockOpener: addheaders = [] def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.req, self.data, self.timeout = req, data, timeout def error(self, proto, *args): self.proto, self.args = proto, args class MockFile: def read(self, count=None): pass def readline(self, count=None): pass def close(self): pass class MockHeaders(dict): def getheaders(self, name): return list(self.values()) class MockResponse(io.StringIO): def __init__(self, code, msg, headers, data, url=None): io.StringIO.__init__(self, data) self.code, self.msg, self.headers, self.url = code, msg, headers, url def info(self): return self.headers def geturl(self): return self.url class MockCookieJar: def add_cookie_header(self, request): self.ach_req = request def extract_cookies(self, response, request): self.ec_req, self.ec_r = request, response class FakeMethod: def __init__(self, meth_name, action, handle): self.meth_name = meth_name self.handle = handle self.action = action def __call__(self, *args): return self.handle(self.meth_name, self.action, *args) class MockHTTPResponse(io.IOBase): def __init__(self, fp, msg, status, reason): self.fp = fp self.msg = msg self.status = status self.reason = reason self.code = 200 def read(self): return '' def info(self): return {} def geturl(self): return self.url class MockHTTPClass: def __init__(self): self.level = 0 self.req_headers = [] self.data = None self.raise_on_endheaders = False self.sock = None self._tunnel_headers = {} def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.host = host self.timeout = timeout return self def set_debuglevel(self, level): self.level = level def set_tunnel(self, host, port=None, headers=None): self._tunnel_host = host self._tunnel_port = port if headers: self._tunnel_headers = headers else: self._tunnel_headers.clear() def request(self, method, url, body=None, headers=None, *, encode_chunked=False): self.method = method self.selector = url if headers is not None: self.req_headers += headers.items() self.req_headers.sort() if body: self.data = body self.encode_chunked = encode_chunked if self.raise_on_endheaders: raise OSError() def getresponse(self): return MockHTTPResponse(MockFile(), {}, 200, "OK") def close(self): pass class MockHandler: # useful for testing handler machinery # see add_ordered_mock_handlers() docstring handler_order = 500 def __init__(self, methods): self._define_methods(methods) def _define_methods(self, methods): for spec in methods: if len(spec) == 2: name, action = spec else: name, action = spec, None meth = FakeMethod(name, action, self.handle) setattr(self.__class__, name, meth) def handle(self, fn_name, action, *args, **kwds): self.parent.calls.append((self, fn_name, args, kwds)) if action is None: return None elif action == "return self": return self elif action == "return response": res = MockResponse(200, "OK", {}, "") return res elif action == "return request": return Request("http://blah/") elif action.startswith("error"): code = action[action.rfind(" ")+1:] try: code = int(code) except ValueError: pass res = MockResponse(200, "OK", {}, "") return self.parent.error("http", args[0], res, code, "", {}) elif action == "raise": raise urllib.error.URLError("blah") assert False def close(self): pass def add_parent(self, parent): self.parent = parent self.parent.calls = [] def __lt__(self, other): if not hasattr(other, "handler_order"): # No handler_order, leave in original order. Yuck. return True return self.handler_order < other.handler_order def add_ordered_mock_handlers(opener, meth_spec): """Create MockHandlers and add them to an OpenerDirector. meth_spec: list of lists of tuples and strings defining methods to define on handlers. eg: [["http_error", "ftp_open"], ["http_open"]] defines methods .http_error() and .ftp_open() on one handler, and .http_open() on another. These methods just record their arguments and return None. Using a tuple instead of a string causes the method to perform some action (see MockHandler.handle()), eg: [["http_error"], [("http_open", "return request")]] defines .http_error() on one handler (which simply returns None), and .http_open() on another handler, which returns a Request object. """ handlers = [] count = 0 for meths in meth_spec: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order += count h.add_parent(opener) count = count + 1 handlers.append(h) opener.add_handler(h) return handlers def build_test_opener(*handler_instances): opener = OpenerDirector() for h in handler_instances: opener.add_handler(h) return opener class MockHTTPHandler(urllib.request.BaseHandler): # useful for testing redirections and auth # sends supplied headers and code as first response # sends 200 OK as second response def __init__(self, code, headers): self.code = code self.headers = headers self.reset() def reset(self): self._count = 0 self.requests = [] def http_open(self, req): import email, copy self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 name = http.client.responses[self.code] msg = email.message_from_string(self.headers) return self.parent.error( "http", req, MockFile(), self.code, name, msg) else: self.req = req msg = email.message_from_string("\r\n\r\n") return MockResponse(200, "OK", msg, "", req.get_full_url()) class MockHTTPSHandler(urllib.request.AbstractHTTPHandler): # Useful for testing the Proxy-Authorization request by verifying the # properties of httpcon def __init__(self, debuglevel=0): urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel) self.httpconn = MockHTTPClass() def https_open(self, req): return self.do_open(self.httpconn, req) class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler): # useful for testing auth # sends supplied code response # checks if auth header is specified in request def __init__(self, code): self.code = code self.has_auth_header = False def reset(self): self.has_auth_header = False def http_open(self, req): if req.has_header('Authorization'): self.has_auth_header = True name = http.client.responses[self.code] return MockResponse(self.code, name, MockFile(), "", req.get_full_url()) class MockPasswordManager: def add_password(self, realm, uri, user, password): self.realm = realm self.url = uri self.user = user self.password = password def find_user_password(self, realm, authuri): self.target_realm = realm self.target_url = authuri return self.user, self.password class OpenerDirectorTests(unittest.TestCase): def test_add_non_handler(self): class NonHandler(object): pass self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) def test_badly_named_methods(self): # test work-around for three methods that accidentally follow the # naming conventions for handler methods # (*_open() / *_request() / *_response()) # These used to call the accidentally-named methods, causing a # TypeError in real code; here, returning self from these mock # methods would either cause no exception, or AttributeError. from urllib.error import URLError o = OpenerDirector() meth_spec = [ [("do_open", "return self"), ("proxy_open", "return self")], [("redirect_request", "return self")], ] add_ordered_mock_handlers(o, meth_spec) o.add_handler(urllib.request.UnknownHandler()) for scheme in "do", "proxy", "redirect": self.assertRaises(URLError, o.open, scheme+"://example.com/") def test_handled(self): # handler returning non-None means no more handlers will be called o = OpenerDirector() meth_spec = [ ["http_open", "ftp_open", "http_error_302"], ["ftp_open"], [("http_open", "return self")], [("http_open", "return self")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") r = o.open(req) # Second .http_open() gets called, third doesn't, since second returned # non-None. Handlers without .http_open() never get any methods called # on them. # In fact, second mock handler defining .http_open() returns self # (instead of response), which becomes the OpenerDirector's return # value. self.assertEqual(r, handlers[2]) calls = [(handlers[0], "http_open"), (handlers[2], "http_open")] for expected, got in zip(calls, o.calls): handler, name, args, kwds = got self.assertEqual((handler, name), expected) self.assertEqual(args, (req,)) def test_handler_order(self): o = OpenerDirector() handlers = [] for meths, handler_order in [([("http_open", "return self")], 500), (["http_open"], 0)]: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order = handler_order handlers.append(h) o.add_handler(h) o.open("http://example.com/") # handlers called in reverse order, thanks to their sort order self.assertEqual(o.calls[0][0], handlers[1]) self.assertEqual(o.calls[1][0], handlers[0]) def test_raise(self): # raising URLError stops processing of request o = OpenerDirector() meth_spec = [ [("http_open", "raise")], [("http_open", "return self")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") self.assertRaises(urllib.error.URLError, o.open, req) self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})]) def test_http_error(self): # XXX http_error_default # http errors are a special case o = OpenerDirector() meth_spec = [ [("http_open", "error 302")], [("http_error_400", "raise"), "http_open"], [("http_error_302", "return response"), "http_error_303", "http_error"], [("http_error_302")], ] handlers = add_ordered_mock_handlers(o, meth_spec) class Unknown: def __eq__(self, other): return True req = Request("http://example.com/") o.open(req) assert len(o.calls) == 2 calls = [(handlers[0], "http_open", (req,)), (handlers[2], "http_error_302", (req, Unknown(), 302, "", {}))] for expected, got in zip(calls, o.calls): handler, method_name, args = expected self.assertEqual((handler, method_name), got[:2]) self.assertEqual(args, got[2]) def test_processors(self): # *_request / *_response methods get called appropriately o = OpenerDirector() meth_spec = [ [("http_request", "return request"), ("http_response", "return response")], [("http_request", "return request"), ("http_response", "return response")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") o.open(req) # processor methods are called on *all* handlers that define them, # not just the first handler that handles the request calls = [ (handlers[0], "http_request"), (handlers[1], "http_request"), (handlers[0], "http_response"), (handlers[1], "http_response")] for i, (handler, name, args, kwds) in enumerate(o.calls): if i < 2: # *_request self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 1) self.assertIsInstance(args[0], Request) else: # *_response self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 2) self.assertIsInstance(args[0], Request) # response from opener.open is None, because there's no # handler that defines http_open to handle it if args[1] is not None: self.assertIsInstance(args[1], MockResponse) def sanepathname2url(path): try: path.encode("utf-8") except UnicodeEncodeError: raise unittest.SkipTest("path is not encodable to utf8") urlpath = urllib.request.pathname2url(path) if os.name == "nt" and urlpath.startswith("///"): urlpath = urlpath[2:] # XXX don't ask me about the mac... return urlpath class HandlerTests(unittest.TestCase): def test_ftp(self): class MockFTPWrapper: def __init__(self, data): self.data = data def retrfile(self, filename, filetype): self.filename, self.filetype = filename, filetype return io.StringIO(self.data), len(self.data) def close(self): pass class NullFTPHandler(urllib.request.FTPHandler): def __init__(self, data): self.data = data def connect_ftp(self, user, passwd, host, port, dirs, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.user, self.passwd = user, passwd self.host, self.port = host, port self.dirs = dirs self.ftpwrapper = MockFTPWrapper(self.data) return self.ftpwrapper import ftplib data = "rheum rhaponicum" h = NullFTPHandler(data) h.parent = MockOpener() for url, host, port, user, passwd, type_, dirs, filename, mimetype in [ ("ftp://localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%25parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%2542parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%42parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://localhost:80/foo/bar/", "localhost", 80, "", "", "D", ["foo", "bar"], "", None), ("ftp://localhost/baz.gif;type=a", "localhost", ftplib.FTP_PORT, "", "", "A", [], "baz.gif", None), # XXX really this should guess image/gif ]: req = Request(url) req.timeout = None r = h.ftp_open(req) # ftp authentication not yet implemented by FTPHandler self.assertEqual(h.user, user) self.assertEqual(h.passwd, passwd) self.assertEqual(h.host, socket.gethostbyname(host)) self.assertEqual(h.port, port) self.assertEqual(h.dirs, dirs) self.assertEqual(h.ftpwrapper.filename, filename) self.assertEqual(h.ftpwrapper.filetype, type_) headers = r.info() self.assertEqual(headers.get("Content-type"), mimetype) self.assertEqual(int(headers["Content-length"]), len(data)) def test_file(self): import email.utils h = urllib.request.FileHandler() o = h.parent = MockOpener() TESTFN = support.TESTFN urlpath = sanepathname2url(os.path.abspath(TESTFN)) towrite = b"hello, world\n" urls = [ "file://localhost%s" % urlpath, "file://%s" % urlpath, "file://%s%s" % (socket.gethostbyname('localhost'), urlpath), ] try: localaddr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: localaddr = '' if localaddr: urls.append("file://%s%s" % (localaddr, urlpath)) for url in urls: f = open(TESTFN, "wb") try: try: f.write(towrite) finally: f.close() r = h.file_open(Request(url)) try: data = r.read() headers = r.info() respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) modified = email.utils.formatdate(stats.st_mtime, usegmt=True) finally: os.remove(TESTFN) self.assertEqual(data, towrite) self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, "file:///file_does_not_exist.txt", "file://not-a-local-host.com//dir/file.txt", "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), os.getcwd(), TESTFN), "file://somerandomhost.ontheinternet.com%s/%s" % (os.getcwd(), TESTFN), ]: try: f = open(TESTFN, "wb") try: f.write(towrite) finally: f.close() self.assertRaises(urllib.error.URLError, h.file_open, Request(url)) finally: os.remove(TESTFN) h = urllib.request.FileHandler() o = h.parent = MockOpener() # XXXX why does // mean ftp (and /// mean not ftp!), and where # is file: scheme specified? I think this is really a bug, and # what was intended was to distinguish between URLs like: # file:/blah.txt (a file) # file://localhost/blah.txt (a file) # file:///blah.txt (a file) # file://ftp.example.com/blah.txt (an ftp URL) for url, ftp in [ ("file://ftp.example.com//foo.txt", False), ("file://ftp.example.com///foo.txt", False), ("file://ftp.example.com/foo.txt", False), ("file://somehost//foo/something.txt", False), ("file://localhost//foo/something.txt", False), ]: req = Request(url) try: h.file_open(req) except urllib.error.URLError: self.assertFalse(ftp) else: self.assertIs(o.req, req) self.assertEqual(req.type, "ftp") self.assertEqual(req.type == "ftp", ftp) def test_http(self): h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() url = "http://example.com/" for method, data in [("GET", None), ("POST", b"blah")]: req = Request(url, data, {"Foo": "bar"}) req.timeout = None req.add_unredirected_header("Spam", "eggs") http = MockHTTPClass() r = h.do_open(http, req) # result attributes r.read; r.readline # wrapped MockFile methods r.info; r.geturl # addinfourl methods r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() hdrs = r.info() hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply() self.assertEqual(r.geturl(), url) self.assertEqual(http.host, "example.com") self.assertEqual(http.level, 0) self.assertEqual(http.method, method) self.assertEqual(http.selector, "/") self.assertEqual(http.req_headers, [("Connection", "close"), ("Foo", "bar"), ("Spam", "eggs")]) self.assertEqual(http.data, data) # check OSError converted to URLError http.raise_on_endheaders = True self.assertRaises(urllib.error.URLError, h.do_open, http, req) # Check for TypeError on POST data which is str. req = Request("http://example.com/","badpost") self.assertRaises(TypeError, h.do_request_, req) # check adding of standard headers o.addheaders = [("Spam", "eggs")] for data in b"", None: # POST, GET req = Request("http://example.com/", data) r = MockResponse(200, "OK", {}, "") newreq = h.do_request_(req) if data is None: # GET
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/future_test1.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/future_test1.py
"""This is a test""" # Import the name nested_scopes twice to trigger SF bug #407394 (regression). from __future__ import nested_scopes, 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_threaded_import.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threaded_import.py
# This is a variant of the very old (early 90's) file # Demo/threads/bug.py. It simply provokes a number of threads into # trying to import the same module "at the same time". # There are no pleasant failure modes -- most likely is that Python # complains several times about module random having no attribute # randrange, and then Python hangs. import _imp as imp import os import importlib import sys import time import shutil import threading import unittest from unittest import mock from test.support import ( verbose, import_module, run_unittest, TESTFN, reap_threads, forget, unlink, rmtree, start_threads) def task(N, done, done_tasks, errors): try: # We don't use modulefinder but still import it in order to stress # importing of different modules from several threads. if len(done_tasks) % 2: import modulefinder import random else: import random import modulefinder # This will fail if random is not completely initialized x = random.randrange(1, 3) except Exception as e: errors.append(e.with_traceback(None)) finally: done_tasks.append(threading.get_ident()) finished = len(done_tasks) == N if finished: done.set() def mock_register_at_fork(func): # bpo-30599: Mock os.register_at_fork() when importing the random module, # since this function doesn't allow to unregister callbacks and would leak # memory. return mock.patch('os.register_at_fork', create=True)(func) # Create a circular import structure: A -> C -> B -> D -> A # NOTE: `time` is already loaded and therefore doesn't threaten to deadlock. circular_imports_modules = { 'A': """if 1: import time time.sleep(%(delay)s) x = 'a' import C """, 'B': """if 1: import time time.sleep(%(delay)s) x = 'b' import D """, 'C': """import B""", 'D': """import A""", } class Finder: """A dummy finder to detect concurrent access to its find_spec() method.""" def __init__(self): self.numcalls = 0 self.x = 0 self.lock = threading.Lock() def find_spec(self, name, path=None, target=None): # Simulate some thread-unsafe behaviour. If calls to find_spec() # are properly serialized, `x` will end up the same as `numcalls`. # Otherwise not. assert imp.lock_held() with self.lock: self.numcalls += 1 x = self.x time.sleep(0.01) self.x = x + 1 class FlushingFinder: """A dummy finder which flushes sys.path_importer_cache when it gets called.""" def find_spec(self, name, path=None, target=None): sys.path_importer_cache.clear() class ThreadedImportTests(unittest.TestCase): def setUp(self): self.old_random = sys.modules.pop('random', None) def tearDown(self): # If the `random` module was already initialized, we restore the # old module at the end so that pickling tests don't fail. # See http://bugs.python.org/issue3657#msg110461 if self.old_random is not None: sys.modules['random'] = self.old_random @mock_register_at_fork def check_parallel_module_init(self, mock_os): if imp.lock_held(): # This triggers on, e.g., from test import autotest. raise unittest.SkipTest("can't run when import lock is held") done = threading.Event() for N in (20, 50) * 3: if verbose: print("Trying", N, "threads ...", end=' ') # Make sure that random and modulefinder get reimported freshly for modname in ['random', 'modulefinder']: try: del sys.modules[modname] except KeyError: pass errors = [] done_tasks = [] done.clear() t0 = time.monotonic() with start_threads(threading.Thread(target=task, args=(N, done, done_tasks, errors,)) for i in range(N)): pass completed = done.wait(10 * 60) dt = time.monotonic() - t0 if verbose: print("%.1f ms" % (dt*1e3), flush=True, end=" ") dbg_info = 'done: %s/%s' % (len(done_tasks), N) self.assertFalse(errors, dbg_info) self.assertTrue(completed, dbg_info) if verbose: print("OK.") def test_parallel_module_init(self): self.check_parallel_module_init() def test_parallel_meta_path(self): finder = Finder() sys.meta_path.insert(0, finder) try: self.check_parallel_module_init() self.assertGreater(finder.numcalls, 0) self.assertEqual(finder.x, finder.numcalls) finally: sys.meta_path.remove(finder) def test_parallel_path_hooks(self): # Here the Finder instance is only used to check concurrent calls # to path_hook(). finder = Finder() # In order for our path hook to be called at each import, we need # to flush the path_importer_cache, which we do by registering a # dedicated meta_path entry. flushing_finder = FlushingFinder() def path_hook(path): finder.find_spec('') raise ImportError sys.path_hooks.insert(0, path_hook) sys.meta_path.append(flushing_finder) try: # Flush the cache a first time flushing_finder.find_spec('') numtests = self.check_parallel_module_init() self.assertGreater(finder.numcalls, 0) self.assertEqual(finder.x, finder.numcalls) finally: sys.meta_path.remove(flushing_finder) sys.path_hooks.remove(path_hook) def test_import_hangers(self): # In case this test is run again, make sure the helper module # gets loaded from scratch again. try: del sys.modules['test.threaded_import_hangers'] except KeyError: pass import test.threaded_import_hangers self.assertFalse(test.threaded_import_hangers.errors) def test_circular_imports(self): # The goal of this test is to exercise implementations of the import # lock which use a per-module lock, rather than a global lock. # In these implementations, there is a possible deadlock with # circular imports, for example: # - thread 1 imports A (grabbing the lock for A) which imports B # - thread 2 imports B (grabbing the lock for B) which imports A # Such implementations should be able to detect such situations and # resolve them one way or the other, without freezing. # NOTE: our test constructs a slightly less trivial import cycle, # in order to better stress the deadlock avoidance mechanism. delay = 0.5 os.mkdir(TESTFN) self.addCleanup(shutil.rmtree, TESTFN) sys.path.insert(0, TESTFN) self.addCleanup(sys.path.remove, TESTFN) for name, contents in circular_imports_modules.items(): contents = contents % {'delay': delay} with open(os.path.join(TESTFN, name + ".py"), "wb") as f: f.write(contents.encode('utf-8')) self.addCleanup(forget, name) importlib.invalidate_caches() results = [] def import_ab(): import A results.append(getattr(A, 'x', None)) def import_ba(): import B results.append(getattr(B, 'x', None)) t1 = threading.Thread(target=import_ab) t2 = threading.Thread(target=import_ba) t1.start() t2.start() t1.join() t2.join() self.assertEqual(set(results), {'a', 'b'}) @mock_register_at_fork def test_side_effect_import(self, mock_os): code = """if 1: import threading def target(): import random t = threading.Thread(target=target) t.start() t.join() t = None""" sys.path.insert(0, os.curdir) self.addCleanup(sys.path.remove, os.curdir) filename = TESTFN + ".py" with open(filename, "wb") as f: f.write(code.encode('utf-8')) self.addCleanup(unlink, filename) self.addCleanup(forget, TESTFN) self.addCleanup(rmtree, '__pycache__') importlib.invalidate_caches() __import__(TESTFN) del sys.modules[TESTFN] @reap_threads def test_main(): old_switchinterval = None try: old_switchinterval = sys.getswitchinterval() sys.setswitchinterval(1e-5) except AttributeError: pass try: run_unittest(ThreadedImportTests) finally: if old_switchinterval is not None: sys.setswitchinterval(old_switchinterval) 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_atexit.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_atexit.py
import sys import unittest import io import atexit import os from test import support from test.support import script_helper ### helpers def h1(): print("h1") def h2(): print("h2") def h3(): print("h3") def h4(*args, **kwargs): print("h4", args, kwargs) def raise1(): raise TypeError def raise2(): raise SystemError def exit(): raise SystemExit class GeneralTest(unittest.TestCase): def setUp(self): self.save_stdout = sys.stdout self.save_stderr = sys.stderr self.stream = io.StringIO() sys.stdout = sys.stderr = self.stream atexit._clear() def tearDown(self): sys.stdout = self.save_stdout sys.stderr = self.save_stderr atexit._clear() def test_args(self): # be sure args are handled properly atexit.register(h1) atexit.register(h4) atexit.register(h4, 4, kw="abc") atexit._run_exitfuncs() self.assertEqual(self.stream.getvalue(), "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n") def test_badargs(self): atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0) self.assertRaises(TypeError, atexit._run_exitfuncs) def test_order(self): # be sure handlers are executed in reverse order atexit.register(h1) atexit.register(h2) atexit.register(h3) atexit._run_exitfuncs() self.assertEqual(self.stream.getvalue(), "h3\nh2\nh1\n") def test_raise(self): # be sure raises are handled properly atexit.register(raise1) atexit.register(raise2) self.assertRaises(TypeError, atexit._run_exitfuncs) def test_raise_unnormalized(self): # Issue #10756: Make sure that an unnormalized exception is # handled properly atexit.register(lambda: 1 / 0) self.assertRaises(ZeroDivisionError, atexit._run_exitfuncs) self.assertIn("ZeroDivisionError", self.stream.getvalue()) def test_exit(self): # be sure a SystemExit is handled properly atexit.register(exit) self.assertRaises(SystemExit, atexit._run_exitfuncs) self.assertEqual(self.stream.getvalue(), '') def test_print_tracebacks(self): # Issue #18776: the tracebacks should be printed when errors occur. def f(): 1/0 # one def g(): 1/0 # two def h(): 1/0 # three atexit.register(f) atexit.register(g) atexit.register(h) self.assertRaises(ZeroDivisionError, atexit._run_exitfuncs) stderr = self.stream.getvalue() self.assertEqual(stderr.count("ZeroDivisionError"), 3) self.assertIn("# one", stderr) self.assertIn("# two", stderr) self.assertIn("# three", stderr) def test_stress(self): a = [0] def inc(): a[0] += 1 for i in range(128): atexit.register(inc) atexit._run_exitfuncs() self.assertEqual(a[0], 128) def test_clear(self): a = [0] def inc(): a[0] += 1 atexit.register(inc) atexit._clear() atexit._run_exitfuncs() self.assertEqual(a[0], 0) def test_unregister(self): a = [0] def inc(): a[0] += 1 def dec(): a[0] -= 1 for i in range(4): atexit.register(inc) atexit.register(dec) atexit.unregister(inc) atexit._run_exitfuncs() self.assertEqual(a[0], -1) def test_bound_methods(self): l = [] atexit.register(l.append, 5) atexit._run_exitfuncs() self.assertEqual(l, [5]) atexit.unregister(l.append) atexit._run_exitfuncs() self.assertEqual(l, [5]) def test_shutdown(self): # Actually test the shutdown mechanism in a subprocess code = """if 1: import atexit def f(msg): print(msg) atexit.register(f, "one") atexit.register(f, "two") """ res = script_helper.assert_python_ok("-c", code) self.assertEqual(res.out.decode().splitlines(), ["two", "one"]) self.assertFalse(res.err) @support.cpython_only class SubinterpreterTest(unittest.TestCase): def test_callbacks_leak(self): # This test shows a leak in refleak mode if atexit doesn't # take care to free callbacks in its per-subinterpreter module # state. n = atexit._ncallbacks() code = r"""if 1: import atexit def f(): pass atexit.register(f) del atexit """ ret = support.run_in_subinterp(code) self.assertEqual(ret, 0) self.assertEqual(atexit._ncallbacks(), n) def test_callbacks_leak_refcycle(self): # Similar to the above, but with a refcycle through the atexit # module. n = atexit._ncallbacks() code = r"""if 1: import atexit def f(): pass atexit.register(f) atexit.__atexit = atexit """ ret = support.run_in_subinterp(code) self.assertEqual(ret, 0) self.assertEqual(atexit._ncallbacks(), n) def test_callback_on_subinterpreter_teardown(self): # This tests if a callback is called on # subinterpreter teardown. expected = b"The test has passed!" r, w = os.pipe() code = r"""if 1: import os import atexit def callback(): os.write({:d}, b"The test has passed!") atexit.register(callback) """.format(w) ret = support.run_in_subinterp(code) os.close(w) self.assertEqual(os.read(r, len(expected)), expected) os.close(r) 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_aifc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_aifc.py
from test.support import check_no_resource_warning, findfile, TESTFN, unlink import unittest from unittest import mock from test import audiotests from audioop import byteswap import io import sys import struct import aifc import warnings class AifcTest(audiotests.AudioWriteTests, audiotests.AudioTestsWithSourceFile): module = aifc close_fd = True test_unseekable_read = None class AifcPCM8Test(AifcTest, unittest.TestCase): sndfilename = 'pluck-pcm8.aiff' sndfilenframes = 3307 nchannels = 2 sampwidth = 1 framerate = 11025 nframes = 48 comptype = b'NONE' compname = b'not compressed' frames = bytes.fromhex("""\ 02FF 4B00 3104 8008 CB06 4803 BF01 03FE B8FA B4F3 29EB 1AE6 \ EDE4 C6E2 0EE0 EFE0 57E2 FBE8 13EF D8F7 97FB F5FC 08FB DFFB \ 11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F14 8012 \ 490E 520D EF0F CE0F E40C 630A 080A 2B0B 510E 8B11 B60E 440A \ """) class AifcPCM16Test(AifcTest, unittest.TestCase): sndfilename = 'pluck-pcm16.aiff' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = b'NONE' compname = b'not compressed' frames = bytes.fromhex("""\ 022EFFEA 4B5D00F6 311804EA 80E10840 CBE106B1 48A903F5 BFE601B2 036CFE7B \ B858FA3E B4B1F34F 299AEBCA 1A5DE6DA EDFAE491 C628E275 0E09E0B5 EF2AE029 \ 5758E271 FB35E83F 1376EF86 D82BF727 9790FB76 F5FAFC0F 0867FB9C DF30FB43 \ 117EFA36 3EE5FB5B BC79FCB1 66D9FF5D CF150412 431D097C C1BA0EC8 512112A1 \ EEE21753 82071665 7FFF1443 8004128F 49A20EAF 52BB0DBA EFB40F60 CE3C0FBF \ E4B30CEC 63430A5C 08C80A20 2BBB0B08 514A0E43 8BCF1139 B6F60EEB 44120A5E \ """) class AifcPCM24Test(AifcTest, unittest.TestCase): sndfilename = 'pluck-pcm24.aiff' sndfilenframes = 3307 nchannels = 2 sampwidth = 3 framerate = 11025 nframes = 48 comptype = b'NONE' compname = b'not compressed' frames = bytes.fromhex("""\ 022D65FFEB9D 4B5A0F00FA54 3113C304EE2B 80DCD6084303 \ CBDEC006B261 48A99803F2F8 BFE82401B07D 036BFBFE7B5D \ B85756FA3EC9 B4B055F3502B 299830EBCB62 1A5CA7E6D99A \ EDFA3EE491BD C625EBE27884 0E05A9E0B6CF EF2929E02922 \ 5758D8E27067 FB3557E83E16 1377BFEF8402 D82C5BF7272A \ 978F16FB7745 F5F865FC1013 086635FB9C4E DF30FCFB40EE \ 117FE0FA3438 3EE6B8FB5AC3 BC77A3FCB2F4 66D6DAFF5F32 \ CF13B9041275 431D69097A8C C1BB600EC74E 5120B912A2BA \ EEDF641754C0 8207001664B7 7FFFFF14453F 8000001294E6 \ 499C1B0EB3B2 52B73E0DBCA0 EFB2B20F5FD8 CE3CDB0FBE12 \ E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0E \ 51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48 \ """) class AifcPCM32Test(AifcTest, unittest.TestCase): sndfilename = 'pluck-pcm32.aiff' sndfilenframes = 3307 nchannels = 2 sampwidth = 4 framerate = 11025 nframes = 48 comptype = b'NONE' compname = b'not compressed' frames = bytes.fromhex("""\ 022D65BCFFEB9D92 4B5A0F8000FA549C 3113C34004EE2BC0 80DCD680084303E0 \ CBDEC0C006B26140 48A9980003F2F8FC BFE8248001B07D92 036BFB60FE7B5D34 \ B8575600FA3EC920 B4B05500F3502BC0 29983000EBCB6240 1A5CA7A0E6D99A60 \ EDFA3E80E491BD40 C625EB80E27884A0 0E05A9A0E0B6CFE0 EF292940E0292280 \ 5758D800E2706700 FB3557D8E83E1640 1377BF00EF840280 D82C5B80F7272A80 \ 978F1600FB774560 F5F86510FC101364 086635A0FB9C4E20 DF30FC40FB40EE28 \ 117FE0A0FA3438B0 3EE6B840FB5AC3F0 BC77A380FCB2F454 66D6DA80FF5F32B4 \ CF13B980041275B0 431D6980097A8C00 C1BB60000EC74E00 5120B98012A2BAA0 \ EEDF64C01754C060 820700001664B780 7FFFFFFF14453F40 800000001294E6E0 \ 499C1B000EB3B270 52B73E000DBCA020 EFB2B2E00F5FD880 CE3CDB400FBE1270 \ E4B49CC00CEA2D90 6344A8800A5A7CA0 08C8FE800A1FFEE0 2BB986C00B0A0E00 \ 51486F800E44E190 8BCC6480113B0580 B6F4EC000EEB3630 441317800A5B48A0 \ """) class AifcULAWTest(AifcTest, unittest.TestCase): sndfilename = 'pluck-ulaw.aifc' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = b'ulaw' compname = b'' frames = bytes.fromhex("""\ 022CFFE8 497C0104 307C04DC 8284083C CB84069C 497C03DC BE8401AC 036CFE74 \ B684FA24 B684F344 2A7CEC04 19FCE704 EE04E504 C584E204 0E3CE104 EF04DF84 \ 557CE204 FB24E804 12FCEF04 D784F744 9684FB64 F5C4FC24 083CFBA4 DF84FB24 \ 11FCFA24 3E7CFB64 BA84FCB4 657CFF5C CF84041C 417C093C C1840EBC 517C12FC \ EF0416FC 828415FC 7D7C13FC 828412FC 497C0EBC 517C0DBC F0040F3C CD840FFC \ E5040CBC 617C0A3C 08BC0A3C 2C7C0B3C 517C0E3C 8A8410FC B6840EBC 457C0A3C \ """) if sys.byteorder != 'big': frames = byteswap(frames, 2) class AifcALAWTest(AifcTest, unittest.TestCase): sndfilename = 'pluck-alaw.aifc' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = b'alaw' compname = b'' frames = bytes.fromhex("""\ 0230FFE8 4A0000F8 310004E0 82000840 CB0006A0 4A0003F0 BE0001A8 0370FE78 \ BA00FA20 B600F340 2900EB80 1A80E680 ED80E480 C700E280 0E40E080 EF80E080 \ 5600E280 FB20E880 1380EF80 D900F740 9600FB60 F5C0FC10 0840FBA0 DF00FB20 \ 1180FA20 3F00FB60 BE00FCB0 6600FF58 CF000420 42000940 C1000EC0 52001280 \ EE801780 82001680 7E001480 82001280 4A000EC0 52000DC0 EF800F40 CF000FC0 \ E4800CC0 62000A40 08C00A40 2B000B40 52000E40 8A001180 B6000EC0 46000A40 \ """) if sys.byteorder != 'big': frames = byteswap(frames, 2) class AifcMiscTest(audiotests.AudioMiscTests, unittest.TestCase): module = aifc def test_skipunknown(self): #Issue 2245 #This file contains chunk types aifc doesn't recognize. self.f = aifc.open(findfile('Sine-1000Hz-300ms.aif')) def test_close_opened_files_on_error(self): non_aifc_file = findfile('pluck-pcm8.wav', subdir='audiodata') with check_no_resource_warning(self): with self.assertRaises(aifc.Error): # Try opening a non-AIFC file, with the expectation that # `aifc.open` will fail (without raising a ResourceWarning) self.f = aifc.open(non_aifc_file, 'rb') # Aifc_write.initfp() won't raise in normal case. But some errors # (e.g. MemoryError, KeyboardInterrupt, etc..) can happen. with mock.patch.object(aifc.Aifc_write, 'initfp', side_effect=RuntimeError): with self.assertRaises(RuntimeError): self.fout = aifc.open(TESTFN, 'wb') def test_params_added(self): f = self.f = aifc.open(TESTFN, 'wb') f.aiff() f.setparams((1, 1, 1, 1, b'NONE', b'')) f.close() f = self.f = aifc.open(TESTFN, 'rb') params = f.getparams() self.assertEqual(params.nchannels, f.getnchannels()) self.assertEqual(params.sampwidth, f.getsampwidth()) self.assertEqual(params.framerate, f.getframerate()) self.assertEqual(params.nframes, f.getnframes()) self.assertEqual(params.comptype, f.getcomptype()) self.assertEqual(params.compname, f.getcompname()) def test_write_header_comptype_sampwidth(self): for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): fout = aifc.open(io.BytesIO(), 'wb') fout.setnchannels(1) fout.setframerate(1) fout.setcomptype(comptype, b'') fout.close() self.assertEqual(fout.getsampwidth(), 2) fout.initfp(None) def test_write_markers_values(self): fout = aifc.open(io.BytesIO(), 'wb') self.assertEqual(fout.getmarkers(), None) fout.setmark(1, 0, b'foo1') fout.setmark(1, 1, b'foo2') self.assertEqual(fout.getmark(1), (1, 1, b'foo2')) self.assertEqual(fout.getmarkers(), [(1, 1, b'foo2')]) fout.initfp(None) def test_read_markers(self): fout = self.fout = aifc.open(TESTFN, 'wb') fout.aiff() fout.setparams((1, 1, 1, 1, b'NONE', b'')) fout.setmark(1, 0, b'odd') fout.setmark(2, 0, b'even') fout.writeframes(b'\x00') fout.close() f = self.f = aifc.open(TESTFN, 'rb') self.assertEqual(f.getmarkers(), [(1, 0, b'odd'), (2, 0, b'even')]) self.assertEqual(f.getmark(1), (1, 0, b'odd')) self.assertEqual(f.getmark(2), (2, 0, b'even')) self.assertRaises(aifc.Error, f.getmark, 3) class AIFCLowLevelTest(unittest.TestCase): def test_read_written(self): def read_written(self, what): f = io.BytesIO() getattr(aifc, '_write_' + what)(f, x) f.seek(0) return getattr(aifc, '_read_' + what)(f) for x in (-1, 0, 0.1, 1): self.assertEqual(read_written(x, 'float'), x) for x in (float('NaN'), float('Inf')): self.assertEqual(read_written(x, 'float'), aifc._HUGE_VAL) for x in (b'', b'foo', b'a' * 255): self.assertEqual(read_written(x, 'string'), x) for x in (-0x7FFFFFFF, -1, 0, 1, 0x7FFFFFFF): self.assertEqual(read_written(x, 'long'), x) for x in (0, 1, 0xFFFFFFFF): self.assertEqual(read_written(x, 'ulong'), x) for x in (-0x7FFF, -1, 0, 1, 0x7FFF): self.assertEqual(read_written(x, 'short'), x) for x in (0, 1, 0xFFFF): self.assertEqual(read_written(x, 'ushort'), x) def test_read_raises(self): f = io.BytesIO(b'\x00') self.assertRaises(EOFError, aifc._read_ulong, f) self.assertRaises(EOFError, aifc._read_long, f) self.assertRaises(EOFError, aifc._read_ushort, f) self.assertRaises(EOFError, aifc._read_short, f) def test_write_long_string_raises(self): f = io.BytesIO() with self.assertRaises(ValueError): aifc._write_string(f, b'too long' * 255) def test_wrong_open_mode(self): with self.assertRaises(aifc.Error): aifc.open(TESTFN, 'wrong_mode') def test_read_wrong_form(self): b1 = io.BytesIO(b'WRNG' + struct.pack('>L', 0)) b2 = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'WRNG') self.assertRaises(aifc.Error, aifc.open, b1) self.assertRaises(aifc.Error, aifc.open, b2) def test_read_no_comm_chunk(self): b = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'AIFF') self.assertRaises(aifc.Error, aifc.open, b) def test_read_no_ssnd_chunk(self): b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 38, 1, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00' with self.assertRaisesRegex(aifc.Error, 'COMM chunk and/or SSND chunk' ' missing'): aifc.open(io.BytesIO(b)) def test_read_wrong_compression_type(self): b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 23, 1, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'WRNG' + struct.pack('B', 0) self.assertRaises(aifc.Error, aifc.open, io.BytesIO(b)) def test_read_wrong_number_of_channels(self): for nchannels in 0, -1: b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 38, nchannels, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00' b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8 with self.assertRaisesRegex(aifc.Error, 'bad # of channels'): aifc.open(io.BytesIO(b)) def test_read_wrong_sample_width(self): for sampwidth in 0, -1: b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 38, 1, 0, sampwidth, 0x4000 | 12, 11025<<18, 0) b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00' b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8 with self.assertRaisesRegex(aifc.Error, 'bad sample width'): aifc.open(io.BytesIO(b)) def test_read_wrong_marks(self): b = b'FORM' + struct.pack('>L', 4) + b'AIFF' b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8 b += b'MARK' + struct.pack('>LhB', 3, 1, 1) with self.assertWarns(UserWarning) as cm: f = aifc.open(io.BytesIO(b)) self.assertEqual(str(cm.warning), 'Warning: MARK chunk contains ' 'only 0 markers instead of 1') self.assertEqual(f.getmarkers(), None) def test_read_comm_kludge_compname_even(self): b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'NONE' + struct.pack('B', 4) + b'even' + b'\x00' b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8 with self.assertWarns(UserWarning) as cm: f = aifc.open(io.BytesIO(b)) self.assertEqual(str(cm.warning), 'Warning: bad COMM chunk size') self.assertEqual(f.getcompname(), b'even') def test_read_comm_kludge_compname_odd(self): b = b'FORM' + struct.pack('>L', 4) + b'AIFC' b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8, 0x4000 | 12, 11025<<18, 0) b += b'NONE' + struct.pack('B', 3) + b'odd' b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8 with self.assertWarns(UserWarning) as cm: f = aifc.open(io.BytesIO(b)) self.assertEqual(str(cm.warning), 'Warning: bad COMM chunk size') self.assertEqual(f.getcompname(), b'odd') def test_write_params_raises(self): fout = aifc.open(io.BytesIO(), 'wb') wrong_params = (0, 0, 0, 0, b'WRNG', '') self.assertRaises(aifc.Error, fout.setparams, wrong_params) self.assertRaises(aifc.Error, fout.getparams) self.assertRaises(aifc.Error, fout.setnchannels, 0) self.assertRaises(aifc.Error, fout.getnchannels) self.assertRaises(aifc.Error, fout.setsampwidth, 0) self.assertRaises(aifc.Error, fout.getsampwidth) self.assertRaises(aifc.Error, fout.setframerate, 0) self.assertRaises(aifc.Error, fout.getframerate) self.assertRaises(aifc.Error, fout.setcomptype, b'WRNG', '') fout.aiff() fout.setnchannels(1) fout.setsampwidth(1) fout.setframerate(1) fout.setnframes(1) fout.writeframes(b'\x00') self.assertRaises(aifc.Error, fout.setparams, (1, 1, 1, 1, 1, 1)) self.assertRaises(aifc.Error, fout.setnchannels, 1) self.assertRaises(aifc.Error, fout.setsampwidth, 1) self.assertRaises(aifc.Error, fout.setframerate, 1) self.assertRaises(aifc.Error, fout.setnframes, 1) self.assertRaises(aifc.Error, fout.setcomptype, b'NONE', '') self.assertRaises(aifc.Error, fout.aiff) self.assertRaises(aifc.Error, fout.aifc) def test_write_params_singles(self): fout = aifc.open(io.BytesIO(), 'wb') fout.aifc() fout.setnchannels(1) fout.setsampwidth(2) fout.setframerate(3) fout.setnframes(4) fout.setcomptype(b'NONE', b'name') self.assertEqual(fout.getnchannels(), 1) self.assertEqual(fout.getsampwidth(), 2) self.assertEqual(fout.getframerate(), 3) self.assertEqual(fout.getnframes(), 0) self.assertEqual(fout.tell(), 0) self.assertEqual(fout.getcomptype(), b'NONE') self.assertEqual(fout.getcompname(), b'name') fout.writeframes(b'\x00' * 4 * fout.getsampwidth() * fout.getnchannels()) self.assertEqual(fout.getnframes(), 4) self.assertEqual(fout.tell(), 4) def test_write_params_bunch(self): fout = aifc.open(io.BytesIO(), 'wb') fout.aifc() p = (1, 2, 3, 4, b'NONE', b'name') fout.setparams(p) self.assertEqual(fout.getparams(), p) fout.initfp(None) def test_write_header_raises(self): fout = aifc.open(io.BytesIO(), 'wb') self.assertRaises(aifc.Error, fout.close) fout = aifc.open(io.BytesIO(), 'wb') fout.setnchannels(1) self.assertRaises(aifc.Error, fout.close) fout = aifc.open(io.BytesIO(), 'wb') fout.setnchannels(1) fout.setsampwidth(1) self.assertRaises(aifc.Error, fout.close) def test_write_header_comptype_raises(self): for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): fout = aifc.open(io.BytesIO(), 'wb') fout.setsampwidth(1) fout.setcomptype(comptype, b'') self.assertRaises(aifc.Error, fout.close) fout.initfp(None) def test_write_markers_raises(self): fout = aifc.open(io.BytesIO(), 'wb') self.assertRaises(aifc.Error, fout.setmark, 0, 0, b'') self.assertRaises(aifc.Error, fout.setmark, 1, -1, b'') self.assertRaises(aifc.Error, fout.setmark, 1, 0, None) self.assertRaises(aifc.Error, fout.getmark, 1) fout.initfp(None) def test_write_aiff_by_extension(self): sampwidth = 2 filename = TESTFN + '.aiff' fout = self.fout = aifc.open(filename, 'wb') self.addCleanup(unlink, filename) fout.setparams((1, sampwidth, 1, 1, b'ULAW', b'')) frames = b'\x00' * fout.getnchannels() * sampwidth fout.writeframes(frames) fout.close() f = self.f = aifc.open(filename, 'rb') self.assertEqual(f.getcomptype(), b'NONE') f.close() 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_raise.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_raise.py
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Tests for the raise statement.""" from test import support import sys import types import unittest def get_tb(): try: raise OSError() except: return sys.exc_info()[2] class Context: def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): return True class TestRaise(unittest.TestCase): def test_invalid_reraise(self): try: raise except RuntimeError as e: self.assertIn("No active exception", str(e)) else: self.fail("No exception raised") def test_reraise(self): try: try: raise IndexError() except IndexError as e: exc1 = e raise except IndexError as exc2: self.assertIs(exc1, exc2) else: self.fail("No exception raised") def test_except_reraise(self): def reraise(): try: raise TypeError("foo") except: try: raise KeyError("caught") except KeyError: pass raise self.assertRaises(TypeError, reraise) def test_finally_reraise(self): def reraise(): try: raise TypeError("foo") except: try: raise KeyError("caught") finally: raise self.assertRaises(KeyError, reraise) def test_nested_reraise(self): def nested_reraise(): raise def reraise(): try: raise TypeError("foo") except: nested_reraise() self.assertRaises(TypeError, reraise) def test_raise_from_None(self): try: try: raise TypeError("foo") except: raise ValueError() from None except ValueError as e: self.assertIsInstance(e.__context__, TypeError) self.assertIsNone(e.__cause__) def test_with_reraise1(self): def reraise(): try: raise TypeError("foo") except: with Context(): pass raise self.assertRaises(TypeError, reraise) def test_with_reraise2(self): def reraise(): try: raise TypeError("foo") except: with Context(): raise KeyError("caught") raise self.assertRaises(TypeError, reraise) def test_yield_reraise(self): def reraise(): try: raise TypeError("foo") except: yield 1 raise g = reraise() next(g) self.assertRaises(TypeError, lambda: next(g)) self.assertRaises(StopIteration, lambda: next(g)) def test_erroneous_exception(self): class MyException(Exception): def __init__(self): raise RuntimeError() try: raise MyException except RuntimeError: pass else: self.fail("No exception raised") def test_new_returns_invalid_instance(self): # See issue #11627. class MyException(Exception): def __new__(cls, *args): return object() with self.assertRaises(TypeError): raise MyException def test_assert_with_tuple_arg(self): try: assert False, (3,) except AssertionError as e: self.assertEqual(str(e), "(3,)") class TestCause(unittest.TestCase): def testCauseSyntax(self): try: try: try: raise TypeError except Exception: raise ValueError from None except ValueError as exc: self.assertIsNone(exc.__cause__) self.assertTrue(exc.__suppress_context__) exc.__suppress_context__ = False raise exc except ValueError as exc: e = exc self.assertIsNone(e.__cause__) self.assertFalse(e.__suppress_context__) self.assertIsInstance(e.__context__, TypeError) def test_invalid_cause(self): try: raise IndexError from 5 except TypeError as e: self.assertIn("exception cause", str(e)) else: self.fail("No exception raised") def test_class_cause(self): try: raise IndexError from KeyError except IndexError as e: self.assertIsInstance(e.__cause__, KeyError) else: self.fail("No exception raised") def test_instance_cause(self): cause = KeyError() try: raise IndexError from cause except IndexError as e: self.assertIs(e.__cause__, cause) else: self.fail("No exception raised") def test_erroneous_cause(self): class MyException(Exception): def __init__(self): raise RuntimeError() try: raise IndexError from MyException except RuntimeError: pass else: self.fail("No exception raised") class TestTraceback(unittest.TestCase): def test_sets_traceback(self): try: raise IndexError() except IndexError as e: self.assertIsInstance(e.__traceback__, types.TracebackType) else: self.fail("No exception raised") def test_accepts_traceback(self): tb = get_tb() try: raise IndexError().with_traceback(tb) except IndexError as e: self.assertNotEqual(e.__traceback__, tb) self.assertEqual(e.__traceback__.tb_next, tb) else: self.fail("No exception raised") class TestTracebackType(unittest.TestCase): def raiser(self): raise ValueError def test_attrs(self): try: self.raiser() except Exception as exc: tb = exc.__traceback__ self.assertIsInstance(tb.tb_next, types.TracebackType) self.assertIs(tb.tb_frame, sys._getframe()) self.assertIsInstance(tb.tb_lasti, int) self.assertIsInstance(tb.tb_lineno, int) self.assertIs(tb.tb_next.tb_next, None) # Invalid assignments with self.assertRaises(TypeError): del tb.tb_next with self.assertRaises(TypeError): tb.tb_next = "asdf" # Loops with self.assertRaises(ValueError): tb.tb_next = tb with self.assertRaises(ValueError): tb.tb_next.tb_next = tb # Valid assignments tb.tb_next = None self.assertIs(tb.tb_next, None) new_tb = get_tb() tb.tb_next = new_tb self.assertIs(tb.tb_next, new_tb) def test_constructor(self): other_tb = get_tb() frame = sys._getframe() tb = types.TracebackType(other_tb, frame, 1, 2) self.assertEqual(tb.tb_next, other_tb) self.assertEqual(tb.tb_frame, frame) self.assertEqual(tb.tb_lasti, 1) self.assertEqual(tb.tb_lineno, 2) tb = types.TracebackType(None, frame, 1, 2) self.assertEqual(tb.tb_next, None) with self.assertRaises(TypeError): types.TracebackType("no", frame, 1, 2) with self.assertRaises(TypeError): types.TracebackType(other_tb, "no", 1, 2) with self.assertRaises(TypeError): types.TracebackType(other_tb, frame, "no", 2) with self.assertRaises(TypeError): types.TracebackType(other_tb, frame, 1, "nuh-uh") class TestContext(unittest.TestCase): def test_instance_context_instance_raise(self): context = IndexError() try: try: raise context except: raise OSError() except OSError as e: self.assertEqual(e.__context__, context) else: self.fail("No exception raised") def test_class_context_instance_raise(self): context = IndexError try: try: raise context except: raise OSError() except OSError as e: self.assertNotEqual(e.__context__, context) self.assertIsInstance(e.__context__, context) else: self.fail("No exception raised") def test_class_context_class_raise(self): context = IndexError try: try: raise context except: raise OSError except OSError as e: self.assertNotEqual(e.__context__, context) self.assertIsInstance(e.__context__, context) else: self.fail("No exception raised") def test_c_exception_context(self): try: try: 1/0 except: raise OSError except OSError as e: self.assertIsInstance(e.__context__, ZeroDivisionError) else: self.fail("No exception raised") def test_c_exception_raise(self): try: try: 1/0 except: xyzzy except NameError as e: self.assertIsInstance(e.__context__, ZeroDivisionError) else: self.fail("No exception raised") def test_noraise_finally(self): try: try: pass finally: raise OSError except OSError as e: self.assertIsNone(e.__context__) else: self.fail("No exception raised") def test_raise_finally(self): try: try: 1/0 finally: raise OSError except OSError as e: self.assertIsInstance(e.__context__, ZeroDivisionError) else: self.fail("No exception raised") def test_context_manager(self): class ContextManager: def __enter__(self): pass def __exit__(self, t, v, tb): xyzzy try: with ContextManager(): 1/0 except NameError as e: self.assertIsInstance(e.__context__, ZeroDivisionError) else: self.fail("No exception raised") def test_cycle_broken(self): # Self-cycles (when re-raising a caught exception) are broken try: try: 1/0 except ZeroDivisionError as e: raise e except ZeroDivisionError as e: self.assertIsNone(e.__context__) def test_reraise_cycle_broken(self): # Non-trivial context cycles (through re-raising a previous exception) # are broken too. try: try: xyzzy except NameError as a: try: 1/0 except ZeroDivisionError: raise a except NameError as e: self.assertIsNone(e.__context__.__context__) def test_3118(self): # deleting the generator caused the __context__ to be cleared def gen(): try: yield 1 finally: pass def f(): g = gen() next(g) try: try: raise ValueError except: del g raise KeyError except Exception as e: self.assertIsInstance(e.__context__, ValueError) f() def test_3611(self): # A re-raised exception in a __del__ caused the __context__ # to be cleared class C: def __del__(self): try: 1/0 except: raise def f(): x = C() try: try: x.x except AttributeError: del x raise TypeError except Exception as e: self.assertNotEqual(e.__context__, None) self.assertIsInstance(e.__context__, AttributeError) with support.captured_output("stderr"): f() class TestRemovedFunctionality(unittest.TestCase): def test_tuples(self): try: raise (IndexError, KeyError) # This should be a tuple! except TypeError: pass else: self.fail("No exception raised") def test_strings(self): try: raise "foo" except TypeError: pass else: self.fail("No exception raised") 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_http_cookies.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_http_cookies.py
# Simple test suite for http/cookies.py import copy from test.support import run_unittest, run_doctest import unittest from http import cookies import pickle class CookieTests(unittest.TestCase): def test_basic(self): cases = [ {'data': 'chips=ahoy; vienna=finger', 'dict': {'chips':'ahoy', 'vienna':'finger'}, 'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>", 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'}, {'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"', 'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'}, 'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''', 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'}, # Check illegal cookies that have an '=' char in an unquoted value {'data': 'keebler=E=mc2', 'dict': {'keebler' : 'E=mc2'}, 'repr': "<SimpleCookie: keebler='E=mc2'>", 'output': 'Set-Cookie: keebler=E=mc2'}, # Cookies with ':' character in their name. Though not mentioned in # RFC, servers / browsers allow it. {'data': 'key:term=value:term', 'dict': {'key:term' : 'value:term'}, 'repr': "<SimpleCookie: key:term='value:term'>", 'output': 'Set-Cookie: key:term=value:term'}, # issue22931 - Adding '[' and ']' as valid characters in cookie # values as defined in RFC 6265 { 'data': 'a=b; c=[; d=r; f=h', 'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'}, 'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>", 'output': '\n'.join(( 'Set-Cookie: a=b', 'Set-Cookie: c=[', 'Set-Cookie: d=r', 'Set-Cookie: f=h' )) } ] for case in cases: C = cookies.SimpleCookie() C.load(case['data']) self.assertEqual(repr(C), case['repr']) self.assertEqual(C.output(sep='\n'), case['output']) for k, v in sorted(case['dict'].items()): self.assertEqual(C[k].value, v) def test_load(self): C = cookies.SimpleCookie() C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme') self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE') self.assertEqual(C['Customer']['version'], '1') self.assertEqual(C['Customer']['path'], '/acme') self.assertEqual(C.output(['path']), 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme') self.assertEqual(C.js_output(), r""" <script type="text/javascript"> <!-- begin hiding document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1"; // end hiding --> </script> """) self.assertEqual(C.js_output(['path']), r""" <script type="text/javascript"> <!-- begin hiding document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme"; // end hiding --> </script> """) def test_extended_encode(self): # Issue 9824: some browsers don't follow the standard; we now # encode , and ; to keep them from tripping up. C = cookies.SimpleCookie() C['val'] = "some,funky;stuff" self.assertEqual(C.output(['val']), 'Set-Cookie: val="some\\054funky\\073stuff"') def test_special_attrs(self): # 'expires' C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['expires'] = 0 # can't test exact output, it always depends on current date/time self.assertTrue(C.output().endswith('GMT')) # loading 'expires' C = cookies.SimpleCookie() C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT') self.assertEqual(C['Customer']['expires'], 'Wed, 01 Jan 2010 00:00:00 GMT') C = cookies.SimpleCookie() C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT') self.assertEqual(C['Customer']['expires'], 'Wed, 01 Jan 98 00:00:00 GMT') # 'max-age' C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['max-age'] = 10 self.assertEqual(C.output(), 'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10') def test_set_secure_httponly_attrs(self): C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['secure'] = True C['Customer']['httponly'] = True self.assertEqual(C.output(), 'Set-Cookie: Customer="WILE_E_COYOTE"; HttpOnly; Secure') def test_secure_httponly_false_if_not_present(self): C = cookies.SimpleCookie() C.load('eggs=scrambled; Path=/bacon') self.assertFalse(C['eggs']['httponly']) self.assertFalse(C['eggs']['secure']) def test_secure_httponly_true_if_present(self): # Issue 16611 C = cookies.SimpleCookie() C.load('eggs=scrambled; httponly; secure; Path=/bacon') self.assertTrue(C['eggs']['httponly']) self.assertTrue(C['eggs']['secure']) def test_secure_httponly_true_if_have_value(self): # This isn't really valid, but demonstrates what the current code # is expected to do in this case. C = cookies.SimpleCookie() C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon') self.assertTrue(C['eggs']['httponly']) self.assertTrue(C['eggs']['secure']) # Here is what it actually does; don't depend on this behavior. These # checks are testing backward compatibility for issue 16611. self.assertEqual(C['eggs']['httponly'], 'foo') self.assertEqual(C['eggs']['secure'], 'bar') def test_extra_spaces(self): C = cookies.SimpleCookie() C.load('eggs = scrambled ; secure ; path = bar ; foo=foo ') self.assertEqual(C.output(), 'Set-Cookie: eggs=scrambled; Path=bar; Secure\r\nSet-Cookie: foo=foo') def test_quoted_meta(self): # Try cookie with quoted meta-data C = cookies.SimpleCookie() C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE') self.assertEqual(C['Customer']['version'], '1') self.assertEqual(C['Customer']['path'], '/acme') self.assertEqual(C.output(['path']), 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme') self.assertEqual(C.js_output(), r""" <script type="text/javascript"> <!-- begin hiding document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1"; // end hiding --> </script> """) self.assertEqual(C.js_output(['path']), r""" <script type="text/javascript"> <!-- begin hiding document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme"; // end hiding --> </script> """) def test_invalid_cookies(self): # Accepting these could be a security issue C = cookies.SimpleCookie() for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x', 'Set-Cookie: foo=bar', 'Set-Cookie: foo', 'foo=bar; baz', 'baz; foo=bar', 'secure;foo=bar', 'Version=1;foo=bar'): C.load(s) self.assertEqual(dict(C), {}) self.assertEqual(C.output(), '') def test_pickle(self): rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1' expected_output = 'Set-Cookie: %s' % rawdata C = cookies.SimpleCookie() C.load(rawdata) self.assertEqual(C.output(), expected_output) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): C1 = pickle.loads(pickle.dumps(C, protocol=proto)) self.assertEqual(C1.output(), expected_output) def test_illegal_chars(self): rawdata = "a=b; c,d=e" C = cookies.SimpleCookie() with self.assertRaises(cookies.CookieError): C.load(rawdata) def test_comment_quoting(self): c = cookies.SimpleCookie() c['foo'] = '\N{COPYRIGHT SIGN}' self.assertEqual(str(c['foo']), 'Set-Cookie: foo="\\251"') c['foo']['comment'] = 'comment \N{COPYRIGHT SIGN}' self.assertEqual( str(c['foo']), 'Set-Cookie: foo="\\251"; Comment="comment \\251"' ) class MorselTests(unittest.TestCase): """Tests for the Morsel object.""" def test_defaults(self): morsel = cookies.Morsel() self.assertIsNone(morsel.key) self.assertIsNone(morsel.value) self.assertIsNone(morsel.coded_value) self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys()) for key, val in morsel.items(): self.assertEqual(val, '', key) def test_reserved_keys(self): M = cookies.Morsel() # tests valid and invalid reserved keys for Morsels for i in M._reserved: # Test that all valid keys are reported as reserved and set them self.assertTrue(M.isReservedKey(i)) M[i] = '%s_value' % i for i in M._reserved: # Test that valid key values come out fine self.assertEqual(M[i], '%s_value' % i) for i in "the holy hand grenade".split(): # Test that invalid keys raise CookieError self.assertRaises(cookies.CookieError, M.__setitem__, i, '%s_value' % i) def test_setter(self): M = cookies.Morsel() # tests the .set method to set keys and their values for i in M._reserved: # Makes sure that all reserved keys can't be set this way self.assertRaises(cookies.CookieError, M.set, i, '%s_value' % i, '%s_value' % i) for i in "thou cast _the- !holy! ^hand| +*grenade~".split(): # Try typical use case. Setting decent values. # Check output and js_output. M['path'] = '/foo' # Try a reserved key as well M.set(i, "%s_val" % i, "%s_coded_val" % i) self.assertEqual(M.key, i) self.assertEqual(M.value, "%s_val" % i) self.assertEqual(M.coded_value, "%s_coded_val" % i) self.assertEqual( M.output(), "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i)) expected_js_output = """ <script type="text/javascript"> <!-- begin hiding document.cookie = "%s=%s; Path=/foo"; // end hiding --> </script> """ % (i, "%s_coded_val" % i) self.assertEqual(M.js_output(), expected_js_output) for i in ["foo bar", "foo@bar"]: # Try some illegal characters self.assertRaises(cookies.CookieError, M.set, i, '%s_value' % i, '%s_value' % i) def test_set_properties(self): morsel = cookies.Morsel() with self.assertRaises(AttributeError): morsel.key = '' with self.assertRaises(AttributeError): morsel.value = '' with self.assertRaises(AttributeError): morsel.coded_value = '' def test_eq(self): base_case = ('key', 'value', '"value"') attribs = { 'path': '/', 'comment': 'foo', 'domain': 'example.com', 'version': 2, } morsel_a = cookies.Morsel() morsel_a.update(attribs) morsel_a.set(*base_case) morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*base_case) self.assertTrue(morsel_a == morsel_b) self.assertFalse(morsel_a != morsel_b) cases = ( ('key', 'value', 'mismatch'), ('key', 'mismatch', '"value"'), ('mismatch', 'value', '"value"'), ) for case_b in cases: with self.subTest(case_b): morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*case_b) self.assertFalse(morsel_a == morsel_b) self.assertTrue(morsel_a != morsel_b) morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*base_case) morsel_b['comment'] = 'bar' self.assertFalse(morsel_a == morsel_b) self.assertTrue(morsel_a != morsel_b) # test mismatched types self.assertFalse(cookies.Morsel() == 1) self.assertTrue(cookies.Morsel() != 1) self.assertFalse(cookies.Morsel() == '') self.assertTrue(cookies.Morsel() != '') items = list(cookies.Morsel().items()) self.assertFalse(cookies.Morsel() == items) self.assertTrue(cookies.Morsel() != items) # morsel/dict morsel = cookies.Morsel() morsel.set(*base_case) morsel.update(attribs) self.assertTrue(morsel == dict(morsel)) self.assertFalse(morsel != dict(morsel)) def test_copy(self): morsel_a = cookies.Morsel() morsel_a.set('foo', 'bar', 'baz') morsel_a.update({ 'version': 2, 'comment': 'foo', }) morsel_b = morsel_a.copy() self.assertIsInstance(morsel_b, cookies.Morsel) self.assertIsNot(morsel_a, morsel_b) self.assertEqual(morsel_a, morsel_b) morsel_b = copy.copy(morsel_a) self.assertIsInstance(morsel_b, cookies.Morsel) self.assertIsNot(morsel_a, morsel_b) self.assertEqual(morsel_a, morsel_b) def test_setitem(self): morsel = cookies.Morsel() morsel['expires'] = 0 self.assertEqual(morsel['expires'], 0) morsel['Version'] = 2 self.assertEqual(morsel['version'], 2) morsel['DOMAIN'] = 'example.com' self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel['invalid'] = 'value' self.assertNotIn('invalid', morsel) def test_setdefault(self): morsel = cookies.Morsel() morsel.update({ 'domain': 'example.com', 'version': 2, }) # this shouldn't override the default value self.assertEqual(morsel.setdefault('expires', 'value'), '') self.assertEqual(morsel['expires'], '') self.assertEqual(morsel.setdefault('Version', 1), 2) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com') self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel.setdefault('invalid', 'value') self.assertNotIn('invalid', morsel) def test_update(self): attribs = {'expires': 1, 'Version': 2, 'DOMAIN': 'example.com'} # test dict update morsel = cookies.Morsel() morsel.update(attribs) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') # test iterable update morsel = cookies.Morsel() morsel.update(list(attribs.items())) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') # test iterator update morsel = cookies.Morsel() morsel.update((k, v) for k, v in attribs.items()) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel.update({'invalid': 'value'}) self.assertNotIn('invalid', morsel) self.assertRaises(TypeError, morsel.update) self.assertRaises(TypeError, morsel.update, 0) def test_pickle(self): morsel_a = cookies.Morsel() morsel_a.set('foo', 'bar', 'baz') morsel_a.update({ 'version': 2, 'comment': 'foo', }) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): morsel_b = pickle.loads(pickle.dumps(morsel_a, proto)) self.assertIsInstance(morsel_b, cookies.Morsel) self.assertEqual(morsel_b, morsel_a) self.assertEqual(str(morsel_b), str(morsel_a)) def test_repr(self): morsel = cookies.Morsel() self.assertEqual(repr(morsel), '<Morsel: None=None>') self.assertEqual(str(morsel), 'Set-Cookie: None=None') morsel.set('key', 'val', 'coded_val') self.assertEqual(repr(morsel), '<Morsel: key=coded_val>') self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val') morsel.update({ 'path': '/', 'comment': 'foo', 'domain': 'example.com', 'max-age': 0, 'secure': 0, 'version': 1, }) self.assertEqual(repr(morsel), '<Morsel: key=coded_val; Comment=foo; Domain=example.com; ' 'Max-Age=0; Path=/; Version=1>') self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; ' 'Max-Age=0; Path=/; Version=1') morsel['secure'] = True morsel['httponly'] = 1 self.assertEqual(repr(morsel), '<Morsel: key=coded_val; Comment=foo; Domain=example.com; ' 'HttpOnly; Max-Age=0; Path=/; Secure; Version=1>') self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; ' 'HttpOnly; Max-Age=0; Path=/; Secure; Version=1') morsel = cookies.Morsel() morsel.set('key', 'val', 'coded_val') morsel['expires'] = 0 self.assertRegex(repr(morsel), r'<Morsel: key=coded_val; ' r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+>') self.assertRegex(str(morsel), r'Set-Cookie: key=coded_val; ' r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+') def test_main(): run_unittest(CookieTests, MorselTests) run_doctest(cookies) 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/ssltests.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssltests.py
# Convenience test module to run all of the OpenSSL-related tests in the # standard library. import ssl import sys import subprocess TESTS = [ 'test_asyncio', 'test_ensurepip.py', 'test_ftplib', 'test_hashlib', 'test_hmac', 'test_httplib', 'test_imaplib', 'test_nntplib', 'test_poplib', 'test_ssl', 'test_smtplib', 'test_smtpnet', 'test_urllib2_localnet', 'test_venv', 'test_xmlrpc' ] def run_regrtests(*extra_args): print(ssl.OPENSSL_VERSION) args = [ sys.executable, '-Werror', '-bb', # turn warnings into exceptions '-m', 'test', ] if not extra_args: args.extend([ '-r', # randomize '-w', # re-run failed tests with -v '-u', 'network', # use network '-u', 'urlfetch', # download test vectors '-j', '0' # use multiple CPUs ]) else: args.extend(extra_args) args.extend(TESTS) result = subprocess.call(args) sys.exit(result) if __name__ == '__main__': run_regrtests(*sys.argv[1:])
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_buffer.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
# # The ndarray object from _testbuffer.c is a complete implementation of # a PEP-3118 buffer provider. It is independent from NumPy's ndarray # and the tests don't require NumPy. # # If NumPy is present, some tests check both ndarray implementations # against each other. # # Most ndarray tests also check that memoryview(ndarray) behaves in # the same way as the original. Thus, a substantial part of the # memoryview tests is now in this module. # # Written and designed by Stefan Krah for Python 3.3. # import contextlib import unittest from test import support from itertools import permutations, product from random import randrange, sample, choice import warnings import sys, array, io, os from decimal import Decimal from fractions import Fraction try: from _testbuffer import * except ImportError: ndarray = None try: import struct except ImportError: struct = None try: import ctypes except ImportError: ctypes = None try: with support.EnvironmentVarGuard() as os.environ, \ warnings.catch_warnings(): from numpy import ndarray as numpy_array except ImportError: numpy_array = None SHORT_TEST = True # ====================================================================== # Random lists by format specifier # ====================================================================== # Native format chars and their ranges. NATIVE = { '?':0, 'c':0, 'b':0, 'B':0, 'h':0, 'H':0, 'i':0, 'I':0, 'l':0, 'L':0, 'n':0, 'N':0, 'f':0, 'd':0, 'P':0 } # NumPy does not have 'n' or 'N': if numpy_array: del NATIVE['n'] del NATIVE['N'] if struct: try: # Add "qQ" if present in native mode. struct.pack('Q', 2**64-1) NATIVE['q'] = 0 NATIVE['Q'] = 0 except struct.error: pass # Standard format chars and their ranges. STANDARD = { '?':(0, 2), 'c':(0, 1<<8), 'b':(-(1<<7), 1<<7), 'B':(0, 1<<8), 'h':(-(1<<15), 1<<15), 'H':(0, 1<<16), 'i':(-(1<<31), 1<<31), 'I':(0, 1<<32), 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32), 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64), 'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023) } def native_type_range(fmt): """Return range of a native type.""" if fmt == 'c': lh = (0, 256) elif fmt == '?': lh = (0, 2) elif fmt == 'f': lh = (-(1<<63), 1<<63) elif fmt == 'd': lh = (-(1<<1023), 1<<1023) else: for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7): try: struct.pack(fmt, (1<<exp)-1) break except struct.error: pass lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp) return lh fmtdict = { '':NATIVE, '@':NATIVE, '<':STANDARD, '>':STANDARD, '=':STANDARD, '!':STANDARD } if struct: for fmt in fmtdict['@']: fmtdict['@'][fmt] = native_type_range(fmt) MEMORYVIEW = NATIVE.copy() ARRAY = NATIVE.copy() for k in NATIVE: if not k in "bBhHiIlLfd": del ARRAY[k] BYTEFMT = NATIVE.copy() for k in NATIVE: if not k in "Bbc": del BYTEFMT[k] fmtdict['m'] = MEMORYVIEW fmtdict['@m'] = MEMORYVIEW fmtdict['a'] = ARRAY fmtdict['b'] = BYTEFMT fmtdict['@b'] = BYTEFMT # Capabilities of the test objects: MODE = 0 MULT = 1 cap = { # format chars # multiplier 'ndarray': (['', '@', '<', '>', '=', '!'], ['', '1', '2', '3']), 'array': (['a'], ['']), 'numpy': ([''], ['']), 'memoryview': (['@m', 'm'], ['']), 'bytefmt': (['@b', 'b'], ['']), } def randrange_fmt(mode, char, obj): """Return random item for a type specified by a mode and a single format character.""" x = randrange(*fmtdict[mode][char]) if char == 'c': x = bytes([x]) if obj == 'numpy' and x == b'\x00': # http://projects.scipy.org/numpy/ticket/1925 x = b'\x01' if char == '?': x = bool(x) if char == 'f' or char == 'd': x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x def gen_item(fmt, obj): """Return single random item.""" mode, chars = fmt.split('#') x = [] for c in chars: x.append(randrange_fmt(mode, c, obj)) return x[0] if len(x) == 1 else tuple(x) def gen_items(n, fmt, obj): """Return a list of random items (or a scalar).""" if n == 0: return gen_item(fmt, obj) lst = [0] * n for i in range(n): lst[i] = gen_item(fmt, obj) return lst def struct_items(n, obj): mode = choice(cap[obj][MODE]) xfmt = mode + '#' fmt = mode.strip('amb') nmemb = randrange(2, 10) # number of struct members for _ in range(nmemb): char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) xfmt += (char * int(multiplier if multiplier else 1)) fmt += (multiplier + char) items = gen_items(n, xfmt, obj) item = gen_item(xfmt, obj) return fmt, items, item def randitems(n, obj='ndarray', mode=None, char=None): """Return random format, items, item.""" if mode is None: mode = choice(cap[obj][MODE]) if char is None: char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) fmt = mode + '#' + char * int(multiplier if multiplier else 1) items = gen_items(n, fmt, obj) item = gen_item(fmt, obj) fmt = mode.strip('amb') + multiplier + char return fmt, items, item def iter_mode(n, obj='ndarray'): """Iterate through supported mode/char combinations.""" for mode in cap[obj][MODE]: for char in fmtdict[mode]: yield randitems(n, obj, mode, char) def iter_format(nitems, testobj='ndarray'): """Yield (format, items, item) for all possible modes and format characters plus one random compound format string.""" for t in iter_mode(nitems, testobj): yield t if testobj != 'ndarray': return yield struct_items(nitems, testobj) def is_byte_format(fmt): return 'c' in fmt or 'b' in fmt or 'B' in fmt def is_memoryview_format(fmt): """format suitable for memoryview""" x = len(fmt) return ((x == 1 or (x == 2 and fmt[0] == '@')) and fmt[x-1] in MEMORYVIEW) NON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)] # ====================================================================== # Multi-dimensional tolist(), slicing and slice assignments # ====================================================================== def atomp(lst): """Tuple items (representing structs) are regarded as atoms.""" return not isinstance(lst, list) def listp(lst): return isinstance(lst, list) def prod(lst): """Product of list elements.""" if len(lst) == 0: return 0 x = lst[0] for v in lst[1:]: x *= v return x def strides_from_shape(ndim, shape, itemsize, layout): """Calculate strides of a contiguous array. Layout is 'C' or 'F' (Fortran).""" if ndim == 0: return () if layout == 'C': strides = list(shape[1:]) + [itemsize] for i in range(ndim-2, -1, -1): strides[i] *= strides[i+1] else: strides = [itemsize] + list(shape[:-1]) for i in range(1, ndim): strides[i] *= strides[i-1] return strides def _ca(items, s): """Convert flat item list to the nested list representation of a multidimensional C array with shape 's'.""" if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = len(items) // s[0] if s[0] else 0 for i in range(s[0]): start = i*stride lst[i] = _ca(items[start:start+stride], s[1:]) return lst def _fa(items, s): """Convert flat item list to the nested list representation of a multidimensional Fortran array with shape 's'.""" if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = s[0] for i in range(s[0]): lst[i] = _fa(items[i::stride], s[1:]) return lst def carray(items, shape): if listp(items) and not 0 in shape and prod(shape) != len(items): raise ValueError("prod(shape) != len(items)") return _ca(items, shape) def farray(items, shape): if listp(items) and not 0 in shape and prod(shape) != len(items): raise ValueError("prod(shape) != len(items)") return _fa(items, shape) def indices(shape): """Generate all possible tuples of indices.""" iterables = [range(v) for v in shape] return product(*iterables) def getindex(ndim, ind, strides): """Convert multi-dimensional index to the position in the flat list.""" ret = 0 for i in range(ndim): ret += strides[i] * ind[i] return ret def transpose(src, shape): """Transpose flat item list that is regarded as a multi-dimensional matrix defined by shape: dest...[k][j][i] = src[i][j][k]... """ if not shape: return src ndim = len(shape) sstrides = strides_from_shape(ndim, shape, 1, 'C') dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C') dest = [0] * len(src) for ind in indices(shape): fr = getindex(ndim, ind, sstrides) to = getindex(ndim, ind[::-1], dstrides) dest[to] = src[fr] return dest def _flatten(lst): """flatten list""" if lst == []: return lst if atomp(lst): return [lst] return _flatten(lst[0]) + _flatten(lst[1:]) def flatten(lst): """flatten list or return scalar""" if atomp(lst): # scalar return lst return _flatten(lst) def slice_shape(lst, slices): """Get the shape of lst after slicing: slices is a list of slice objects.""" if atomp(lst): return [] return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:]) def multislice(lst, slices): """Multi-dimensional slicing: slices is a list of slice objects.""" if atomp(lst): return lst return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]] def m_assign(llst, rlst, lslices, rslices): """Multi-dimensional slice assignment: llst and rlst are the operands, lslices and rslices are lists of slice objects. llst and rlst must have the same structure. For a two-dimensional example, this is not implemented in Python: llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1] Instead we write: lslices = [slice(0,3,2), slice(0,3,2)] rslices = [slice(1,3,1), slice(1,3,1)] multislice_assign(llst, rlst, lslices, rslices) """ if atomp(rlst): return rlst rlst = [m_assign(l, r, lslices[1:], rslices[1:]) for l, r in zip(llst[lslices[0]], rlst[rslices[0]])] llst[lslices[0]] = rlst return llst def cmp_structure(llst, rlst, lslices, rslices): """Compare the structure of llst[lslices] and rlst[rslices].""" lshape = slice_shape(llst, lslices) rshape = slice_shape(rlst, rslices) if (len(lshape) != len(rshape)): return -1 for i in range(len(lshape)): if lshape[i] != rshape[i]: return -1 if lshape[i] == 0: return 0 return 0 def multislice_assign(llst, rlst, lslices, rslices): """Return llst after assigning: llst[lslices] = rlst[rslices]""" if cmp_structure(llst, rlst, lslices, rslices) < 0: raise ValueError("lvalue and rvalue have different structures") return m_assign(llst, rlst, lslices, rslices) # ====================================================================== # Random structures # ====================================================================== # # PEP-3118 is very permissive with respect to the contents of a # Py_buffer. In particular: # # - shape can be zero # - strides can be any integer, including zero # - offset can point to any location in the underlying # memory block, provided that it is a multiple of # itemsize. # # The functions in this section test and verify random structures # in full generality. A structure is valid iff it fits in the # underlying memory block. # # The structure 't' (short for 'tuple') is fully defined by: # # t = (memlen, itemsize, ndim, shape, strides, offset) # def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf - mem """ if offset % itemsize: return False if offset < 0 or offset+itemsize > memlen: return False if any(v % itemsize for v in strides): return False if ndim <= 0: return ndim == 0 and not shape and not strides if 0 in shape: return True imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) return 0 <= offset+imin and offset+imax+itemsize <= memlen def get_item(lst, indices): for i in indices: lst = lst[i] return lst def memory_index(indices, t): """Location of an item in the underlying memory.""" memlen, itemsize, ndim, shape, strides, offset = t p = offset for i in range(ndim): p += strides[i]*indices[i] return p def is_overlapping(t): """The structure 't' is overlapping if at least one memory location is visited twice while iterating through all possible tuples of indices.""" memlen, itemsize, ndim, shape, strides, offset = t visited = 1<<memlen for ind in indices(shape): i = memory_index(ind, t) bit = 1<<i if visited & bit: return True visited |= bit return False def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): """Return random structure: (memlen, itemsize, ndim, shape, strides, offset) If 'valid' is true, the returned structure is valid, otherwise invalid. If 'shape' is given, use that instead of creating a random shape. """ if not shape: ndim = randrange(maxdim+1) if (ndim == 0): if valid: return itemsize, itemsize, ndim, (), (), 0 else: nitems = randrange(1, 16+1) memlen = nitems * itemsize offset = -itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, (), (), offset minshape = 2 n = randrange(100) if n >= 95 and valid: minshape = 0 elif n >= 90: minshape = 1 shape = [0] * ndim for i in range(ndim): shape[i] = randrange(minshape, maxshape+1) else: ndim = len(shape) maxstride = 5 n = randrange(100) zero_stride = True if n >= 95 and n & 1 else False strides = [0] * ndim strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1) if not zero_stride and strides[ndim-1] == 0: strides[ndim-1] = itemsize for i in range(ndim-2, -1, -1): maxstride *= shape[i+1] if shape[i+1] else 1 if zero_stride: strides[i] = itemsize * randrange(-maxstride, maxstride+1) else: strides[i] = ((1,-1)[randrange(2)] * itemsize * randrange(1, maxstride+1)) imin = imax = 0 if not 0 in shape: imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) nitems = imax - imin if valid: offset = -imin * itemsize memlen = offset + (imax+1) * itemsize else: memlen = (-imin + imax) * itemsize offset = -imin-itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, shape, strides, offset def randslice_from_slicelen(slicelen, listlen): """Create a random slice of len slicelen that fits into listlen.""" maxstart = listlen - slicelen start = randrange(maxstart+1) maxstep = (listlen - start) // slicelen if slicelen else 1 step = randrange(1, maxstep+1) stop = start + slicelen * step s = slice(start, stop, step) _, _, _, control = slice_indices(s, listlen) if control != slicelen: raise RuntimeError return s def randslice_from_shape(ndim, shape): """Create two sets of slices for an array x with shape 'shape' such that shapeof(x[lslices]) == shapeof(x[rslices]).""" lslices = [0] * ndim rslices = [0] * ndim for n in range(ndim): l = shape[n] slicelen = randrange(1, l+1) if l > 0 else 0 lslices[n] = randslice_from_slicelen(slicelen, l) rslices[n] = randslice_from_slicelen(slicelen, l) return tuple(lslices), tuple(rslices) def rand_aligned_slices(maxdim=5, maxshape=16): """Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array with shape 'lshape' and y is an array with shape 'rshape'.""" ndim = randrange(1, maxdim+1) minshape = 2 n = randrange(100) if n >= 95: minshape = 0 elif n >= 90: minshape = 1 all_random = True if randrange(100) >= 80 else False lshape = [0]*ndim; rshape = [0]*ndim lslices = [0]*ndim; rslices = [0]*ndim for n in range(ndim): small = randrange(minshape, maxshape+1) big = randrange(minshape, maxshape+1) if big < small: big, small = small, big # Create a slice that fits the smaller value. if all_random: start = randrange(-small, small+1) stop = randrange(-small, small+1) step = (1,-1)[randrange(2)] * randrange(1, small+2) s_small = slice(start, stop, step) _, _, _, slicelen = slice_indices(s_small, small) else: slicelen = randrange(1, small+1) if small > 0 else 0 s_small = randslice_from_slicelen(slicelen, small) # Create a slice of the same length for the bigger value. s_big = randslice_from_slicelen(slicelen, big) if randrange(2) == 0: rshape[n], lshape[n] = big, small rslices[n], lslices[n] = s_big, s_small else: rshape[n], lshape[n] = small, big rslices[n], lslices[n] = s_small, s_big return lshape, rshape, tuple(lslices), tuple(rslices) def randitems_from_structure(fmt, t): """Return a list of random items for structure 't' with format 'fmtchar'.""" memlen, itemsize, _, _, _, _ = t return gen_items(memlen//itemsize, '#'+fmt, 'numpy') def ndarray_from_structure(items, fmt, t, flags=0): """Return ndarray from the tuple returned by rand_structure()""" memlen, itemsize, ndim, shape, strides, offset = t return ndarray(items, shape=shape, strides=strides, format=fmt, offset=offset, flags=ND_WRITABLE|flags) def numpy_array_from_structure(items, fmt, t): """Return numpy_array from the tuple returned by rand_structure()""" memlen, itemsize, ndim, shape, strides, offset = t buf = bytearray(memlen) for j, v in enumerate(items): struct.pack_into(fmt, buf, j*itemsize, v) return numpy_array(buffer=buf, shape=shape, strides=strides, dtype=fmt, offset=offset) # ====================================================================== # memoryview casts # ====================================================================== def cast_items(exporter, fmt, itemsize, shape=None): """Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1-D with n * itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) * itemsize = bytelen applies. On success, return (items, shape). If the constraints cannot be met, return (None, None). If a chunk of bytes is interpreted as NaN as a result of float conversion, return ('nan', None).""" bytelen = exporter.nbytes if shape: if prod(shape) * itemsize != bytelen: return None, shape elif shape == []: if exporter.ndim == 0 or itemsize != bytelen: return None, shape else: n, r = divmod(bytelen, itemsize) shape = [n] if r != 0: return None, shape mem = exporter.tobytes() byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)] items = [] for v in byteitems: item = struct.unpack(fmt, v)[0] if item != item: return 'nan', shape items.append(item) return (items, shape) if shape != [] else (items[0], shape) def gencastshapes(): """Generate shapes to test casting.""" for n in range(32): yield [n] ndim = randrange(4, 6) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)] ndim = randrange(2, 4) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)] # ====================================================================== # Actual tests # ====================================================================== def genslices(n): """Generate all possible slices for a single dimension.""" return product(range(-n, n+1), range(-n, n+1), range(-n, n+1)) def genslices_ndim(ndim, shape): """Generate all possible slice tuples for 'shape'.""" iterables = [genslices(shape[n]) for n in range(ndim)] return product(*iterables) def rslice(n, allow_empty=False): """Generate random slice for a single dimension of length n. If zero=True, the slices may be empty, otherwise they will be non-empty.""" minlen = 0 if allow_empty or n == 0 else 1 slicelen = randrange(minlen, n+1) return randslice_from_slicelen(slicelen, n) def rslices(n, allow_empty=False): """Generate random slices for a single dimension.""" for _ in range(5): yield rslice(n, allow_empty) def rslices_ndim(ndim, shape, iterations=5): """Generate random slice tuples for 'shape'.""" # non-empty slices for _ in range(iterations): yield tuple(rslice(shape[n]) for n in range(ndim)) # possibly empty slices for _ in range(iterations): yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim)) # invalid slices yield tuple(slice(0,1,0) for _ in range(ndim)) def rpermutation(iterable, r=None): pool = tuple(iterable) r = len(pool) if r is None else r yield tuple(sample(pool, r)) def ndarray_print(nd): """Print ndarray for debugging.""" try: x = nd.tolist() except (TypeError, NotImplementedError): x = nd.tobytes() if isinstance(nd, ndarray): offset = nd.offset flags = nd.flags else: offset = 'unknown' flags = 'unknown' print("ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, " "format='%s', itemsize=%s, flags=%s)" % (x, nd.shape, nd.strides, nd.suboffsets, offset, nd.format, nd.itemsize, flags)) sys.stdout.flush() ITERATIONS = 100 MAXDIM = 5 MAXSHAPE = 10 if SHORT_TEST: ITERATIONS = 10 MAXDIM = 3 MAXSHAPE = 4 genslices = rslices genslices_ndim = rslices_ndim permutations = rpermutation @unittest.skipUnless(struct, 'struct module required for this test.') @unittest.skipUnless(ndarray, 'ndarray object required for this test') class TestBufferProtocol(unittest.TestCase): def setUp(self): # The suboffsets tests need sizeof(void *). self.sizeof_void_p = get_sizeof_void_p() def verify(self, result, obj=-1, itemsize={1}, fmt=-1, readonly={1}, ndim={1}, shape=-1, strides=-1, lst=-1, sliced=False, cast=False): # Verify buffer contents against expected values. Default values # are deliberately initialized to invalid types. if shape: expected_len = prod(shape)*itemsize else: if not fmt: # array has been implicitly cast to unsigned bytes expected_len = len(lst) else: # ndim = 0 expected_len = itemsize # Reconstruct suboffsets from strides. Support for slicing # could be added, but is currently only needed for test_getbuf(). suboffsets = () if result.suboffsets: self.assertGreater(ndim, 0) suboffset0 = 0 for n in range(1, ndim): if shape[n] == 0: break if strides[n] <= 0: suboffset0 += -strides[n] * (shape[n]-1) suboffsets = [suboffset0] + [-1 for v in range(ndim-1)] # Not correct if slicing has occurred in the first dimension. stride0 = self.sizeof_void_p if strides[0] < 0: stride0 = -stride0 strides = [stride0] + list(strides[1:]) self.assertIs(result.obj, obj) self.assertEqual(result.nbytes, expected_len) self.assertEqual(result.itemsize, itemsize) self.assertEqual(result.format, fmt) self.assertEqual(result.readonly, readonly) self.assertEqual(result.ndim, ndim) self.assertEqual(result.shape, tuple(shape)) if not (sliced and suboffsets): self.assertEqual(result.strides, tuple(strides)) self.assertEqual(result.suboffsets, tuple(suboffsets)) if isinstance(result, ndarray) or is_memoryview_format(fmt): rep = result.tolist() if fmt else result.tobytes() self.assertEqual(rep, lst) if not fmt: # array has been cast to unsigned bytes, return # the remaining tests won't work. # PyBuffer_GetPointer() is the definition how to access an item. # If PyBuffer_GetPointer(indices) is correct for all possible # combinations of indices, the buffer is correct. # # Also test tobytes() against the flattened 'lst', with all items # packed to bytes. if not cast: # casts chop up 'lst' in different ways b = bytearray() buf_err = None for ind in indices(shape): try: item1 = get_pointer(result, ind) item2 = get_item(lst, ind) if isinstance(item2, tuple): x = struct.pack(fmt, *item2) else: x = struct.pack(fmt, item2) b.extend(x) except BufferError: buf_err = True # re-exporter does not provide full buffer break self.assertEqual(item1, item2) if not buf_err: # test tobytes() self.assertEqual(result.tobytes(), b) # test hex() m = memoryview(result) h = "".join("%02x" % c for c in b) self.assertEqual(m.hex(), h) # lst := expected multi-dimensional logical representation # flatten(lst) := elements in C-order ff = fmt if fmt else 'B' flattened = flatten(lst) # Rules for 'A': if the array is already contiguous, return # the array unaltered. Otherwise, return a contiguous 'C' # representation. for order in ['C', 'F', 'A']: expected = result if order == 'F': if not is_contiguous(result, 'A') or \ is_contiguous(result, 'C'): # For constructing the ndarray, convert the # flattened logical representation to Fortran order. trans = transpose(flattened, shape) expected = ndarray(trans, shape=shape, format=ff, flags=ND_FORTRAN) else: # 'C', 'A' if not is_contiguous(result, 'A') or \ is_contiguous(result, 'F') and order == 'C': # The flattened list is already in C-order. expected = ndarray(flattened, shape=shape, format=ff) contig = get_contiguous(result, PyBUF_READ, order) self.assertEqual(contig.tobytes(), b) self.assertTrue(cmp_contig(contig, expected)) if ndim == 0: continue nmemb = len(flattened) ro = 0 if readonly else ND_WRITABLE ### See comment in test_py_buffer_to_contiguous for an ### explanation why these tests are valid. # To 'C' contig = py_buffer_to_contiguous(result, 'C', PyBUF_FULL_RO) self.assertEqual(len(contig), nmemb * itemsize) initlst = [struct.unpack_from(fmt, contig, n*itemsize) for n in range(nmemb)] if len(initlst[0]) == 1: initlst = [v[0] for v in initlst] y = ndarray(initlst, shape=shape, flags=ro, format=fmt) self.assertEqual(memoryview(y), memoryview(result)) # To 'F' contig = py_buffer_to_contiguous(result, 'F', PyBUF_FULL_RO) self.assertEqual(len(contig), nmemb * itemsize) initlst = [struct.unpack_from(fmt, contig, n*itemsize) for n in range(nmemb)] if len(initlst[0]) == 1: initlst = [v[0] for v in initlst] y = ndarray(initlst, shape=shape, flags=ro|ND_FORTRAN, format=fmt) self.assertEqual(memoryview(y), memoryview(result)) # To 'A' contig = py_buffer_to_contiguous(result, 'A', PyBUF_FULL_RO) self.assertEqual(len(contig), nmemb * itemsize) initlst = [struct.unpack_from(fmt, contig, n*itemsize) for n in range(nmemb)] if len(initlst[0]) == 1: initlst = [v[0] for v in initlst] f = ND_FORTRAN if is_contiguous(result, 'F') else 0 y = ndarray(initlst, shape=shape, flags=f|ro, format=fmt) self.assertEqual(memoryview(y), memoryview(result)) if is_memoryview_format(fmt): try: m = memoryview(result) except BufferError: # re-exporter does not provide full information return ex = result.obj if isinstance(result, memoryview) else result self.assertIs(m.obj, ex) self.assertEqual(m.nbytes, expected_len) self.assertEqual(m.itemsize, itemsize) self.assertEqual(m.format, fmt) self.assertEqual(m.readonly, readonly) self.assertEqual(m.ndim, ndim) self.assertEqual(m.shape, tuple(shape)) if not (sliced and suboffsets): self.assertEqual(m.strides, tuple(strides)) self.assertEqual(m.suboffsets, tuple(suboffsets)) n = 1 if ndim == 0 else len(lst) self.assertEqual(len(m), n) rep = result.tolist() if fmt else result.tobytes() self.assertEqual(rep, lst) self.assertEqual(m, result) def verify_getbuf(self, orig_ex, ex, req, sliced=False): def simple_fmt(ex): return ex.format == '' or ex.format == 'B' def match(req, flag): return ((req&flag) == flag) if (# writable request to read-only exporter (ex.readonly and match(req, PyBUF_WRITABLE)) or # cannot match explicit contiguity request (match(req, PyBUF_C_CONTIGUOUS) and not ex.c_contiguous) or (match(req, PyBUF_F_CONTIGUOUS) and not ex.f_contiguous) or
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_unicodedata.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_unicodedata.py
""" Test script for the unicodedata module. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import sys import unittest import hashlib from test.support import script_helper encoding = 'utf-8' errors = 'surrogatepass' ### Run tests class UnicodeMethodsTest(unittest.TestCase): # update this, if the database changes expectedchecksum = '97a41f208c53d5e08c77c1175187e95386b82b6f' def test_method_checksum(self): h = hashlib.sha1() for i in range(0x10000): char = chr(i) data = [ # Predicates (single char) "01"[char.isalnum()], "01"[char.isalpha()], "01"[char.isdecimal()], "01"[char.isdigit()], "01"[char.islower()], "01"[char.isnumeric()], "01"[char.isspace()], "01"[char.istitle()], "01"[char.isupper()], # Predicates (multiple chars) "01"[(char + 'abc').isalnum()], "01"[(char + 'abc').isalpha()], "01"[(char + '123').isdecimal()], "01"[(char + '123').isdigit()], "01"[(char + 'abc').islower()], "01"[(char + '123').isnumeric()], "01"[(char + ' \t').isspace()], "01"[(char + 'abc').istitle()], "01"[(char + 'ABC').isupper()], # Mappings (single char) char.lower(), char.upper(), char.title(), # Mappings (multiple chars) (char + 'abc').lower(), (char + 'ABC').upper(), (char + 'abc').title(), (char + 'ABC').title(), ] h.update(''.join(data).encode(encoding, errors)) result = h.hexdigest() self.assertEqual(result, self.expectedchecksum) class UnicodeDatabaseTest(unittest.TestCase): def setUp(self): # In case unicodedata is not available, this will raise an ImportError, # but the other test cases will still be run import unicodedata self.db = unicodedata def tearDown(self): del self.db class UnicodeFunctionsTest(UnicodeDatabaseTest): # Update this if the database changes. Make sure to do a full rebuild # (e.g. 'make distclean && make') to get the correct checksum. expectedchecksum = '4f73278b19c2ec3099724c132f0b90a1d25c19e4' def test_function_checksum(self): data = [] h = hashlib.sha1() for i in range(0x10000): char = chr(i) data = [ # Properties format(self.db.digit(char, -1), '.12g'), format(self.db.numeric(char, -1), '.12g'), format(self.db.decimal(char, -1), '.12g'), self.db.category(char), self.db.bidirectional(char), self.db.decomposition(char), str(self.db.mirrored(char)), str(self.db.combining(char)), ] h.update(''.join(data).encode("ascii")) result = h.hexdigest() self.assertEqual(result, self.expectedchecksum) def test_digit(self): self.assertEqual(self.db.digit('A', None), None) self.assertEqual(self.db.digit('9'), 9) self.assertEqual(self.db.digit('\u215b', None), None) self.assertEqual(self.db.digit('\u2468'), 9) self.assertEqual(self.db.digit('\U00020000', None), None) self.assertEqual(self.db.digit('\U0001D7FD'), 7) self.assertRaises(TypeError, self.db.digit) self.assertRaises(TypeError, self.db.digit, 'xx') self.assertRaises(ValueError, self.db.digit, 'x') def test_numeric(self): self.assertEqual(self.db.numeric('A',None), None) self.assertEqual(self.db.numeric('9'), 9) self.assertEqual(self.db.numeric('\u215b'), 0.125) self.assertEqual(self.db.numeric('\u2468'), 9.0) self.assertEqual(self.db.numeric('\ua627'), 7.0) self.assertEqual(self.db.numeric('\U00020000', None), None) self.assertEqual(self.db.numeric('\U0001012A'), 9000) self.assertRaises(TypeError, self.db.numeric) self.assertRaises(TypeError, self.db.numeric, 'xx') self.assertRaises(ValueError, self.db.numeric, 'x') def test_decimal(self): self.assertEqual(self.db.decimal('A',None), None) self.assertEqual(self.db.decimal('9'), 9) self.assertEqual(self.db.decimal('\u215b', None), None) self.assertEqual(self.db.decimal('\u2468', None), None) self.assertEqual(self.db.decimal('\U00020000', None), None) self.assertEqual(self.db.decimal('\U0001D7FD'), 7) self.assertRaises(TypeError, self.db.decimal) self.assertRaises(TypeError, self.db.decimal, 'xx') self.assertRaises(ValueError, self.db.decimal, 'x') def test_category(self): self.assertEqual(self.db.category('\uFFFE'), 'Cn') self.assertEqual(self.db.category('a'), 'Ll') self.assertEqual(self.db.category('A'), 'Lu') self.assertEqual(self.db.category('\U00020000'), 'Lo') self.assertEqual(self.db.category('\U0001012A'), 'No') self.assertRaises(TypeError, self.db.category) self.assertRaises(TypeError, self.db.category, 'xx') def test_bidirectional(self): self.assertEqual(self.db.bidirectional('\uFFFE'), '') self.assertEqual(self.db.bidirectional(' '), 'WS') self.assertEqual(self.db.bidirectional('A'), 'L') self.assertEqual(self.db.bidirectional('\U00020000'), 'L') self.assertRaises(TypeError, self.db.bidirectional) self.assertRaises(TypeError, self.db.bidirectional, 'xx') def test_decomposition(self): self.assertEqual(self.db.decomposition('\uFFFE'),'') self.assertEqual(self.db.decomposition('\u00bc'), '<fraction> 0031 2044 0034') self.assertRaises(TypeError, self.db.decomposition) self.assertRaises(TypeError, self.db.decomposition, 'xx') def test_mirrored(self): self.assertEqual(self.db.mirrored('\uFFFE'), 0) self.assertEqual(self.db.mirrored('a'), 0) self.assertEqual(self.db.mirrored('\u2201'), 1) self.assertEqual(self.db.mirrored('\U00020000'), 0) self.assertRaises(TypeError, self.db.mirrored) self.assertRaises(TypeError, self.db.mirrored, 'xx') def test_combining(self): self.assertEqual(self.db.combining('\uFFFE'), 0) self.assertEqual(self.db.combining('a'), 0) self.assertEqual(self.db.combining('\u20e1'), 230) self.assertEqual(self.db.combining('\U00020000'), 0) self.assertRaises(TypeError, self.db.combining) self.assertRaises(TypeError, self.db.combining, 'xx') def test_normalize(self): self.assertRaises(TypeError, self.db.normalize) self.assertRaises(ValueError, self.db.normalize, 'unknown', 'xx') self.assertEqual(self.db.normalize('NFKC', ''), '') # The rest can be found in test_normalization.py # which requires an external file. def test_pr29(self): # http://www.unicode.org/review/pr-29.html # See issues #1054943 and #10254. composed = ("\u0b47\u0300\u0b3e", "\u1100\u0300\u1161", 'Li\u030dt-s\u1e73\u0301', '\u092e\u093e\u0930\u094d\u0915 \u091c\u093c' + '\u0941\u0915\u0947\u0930\u092c\u0930\u094d\u0917', '\u0915\u093f\u0930\u094d\u0917\u093f\u091c\u093c' + '\u0938\u094d\u0924\u093e\u0928') for text in composed: self.assertEqual(self.db.normalize('NFC', text), text) def test_issue10254(self): # Crash reported in #10254 a = 'C\u0338' * 20 + 'C\u0327' b = 'C\u0338' * 20 + '\xC7' self.assertEqual(self.db.normalize('NFC', a), b) def test_issue29456(self): # Fix #29456 u1176_str_a = '\u1100\u1176\u11a8' u1176_str_b = '\u1100\u1176\u11a8' u11a7_str_a = '\u1100\u1175\u11a7' u11a7_str_b = '\uae30\u11a7' u11c3_str_a = '\u1100\u1175\u11c3' u11c3_str_b = '\uae30\u11c3' self.assertEqual(self.db.normalize('NFC', u1176_str_a), u1176_str_b) self.assertEqual(self.db.normalize('NFC', u11a7_str_a), u11a7_str_b) self.assertEqual(self.db.normalize('NFC', u11c3_str_a), u11c3_str_b) def test_east_asian_width(self): eaw = self.db.east_asian_width self.assertRaises(TypeError, eaw, b'a') self.assertRaises(TypeError, eaw, bytearray()) self.assertRaises(TypeError, eaw, '') self.assertRaises(TypeError, eaw, 'ra') self.assertEqual(eaw('\x1e'), 'N') self.assertEqual(eaw('\x20'), 'Na') self.assertEqual(eaw('\uC894'), 'W') self.assertEqual(eaw('\uFF66'), 'H') self.assertEqual(eaw('\uFF1F'), 'F') self.assertEqual(eaw('\u2010'), 'A') self.assertEqual(eaw('\U00020000'), 'W') def test_east_asian_width_9_0_changes(self): self.assertEqual(self.db.ucd_3_2_0.east_asian_width('\u231a'), 'N') self.assertEqual(self.db.east_asian_width('\u231a'), 'W') class UnicodeMiscTest(UnicodeDatabaseTest): def test_failed_import_during_compiling(self): # Issue 4367 # Decoding \N escapes requires the unicodedata module. If it can't be # imported, we shouldn't segfault. # This program should raise a SyntaxError in the eval. code = "import sys;" \ "sys.modules['unicodedata'] = None;" \ """eval("'\\\\N{SOFT HYPHEN}'")""" # We use a separate process because the unicodedata module may already # have been loaded in this process. result = script_helper.assert_python_failure("-c", code) error = "SyntaxError: (unicode error) \\N escapes not supported " \ "(can't load unicodedata module)" self.assertIn(error, result.err.decode("ascii")) def test_decimal_numeric_consistent(self): # Test that decimal and numeric are consistent, # i.e. if a character has a decimal value, # its numeric value should be the same. count = 0 for i in range(0x10000): c = chr(i) dec = self.db.decimal(c, -1) if dec != -1: self.assertEqual(dec, self.db.numeric(c)) count += 1 self.assertTrue(count >= 10) # should have tested at least the ASCII digits def test_digit_numeric_consistent(self): # Test that digit and numeric are consistent, # i.e. if a character has a digit value, # its numeric value should be the same. count = 0 for i in range(0x10000): c = chr(i) dec = self.db.digit(c, -1) if dec != -1: self.assertEqual(dec, self.db.numeric(c)) count += 1 self.assertTrue(count >= 10) # should have tested at least the ASCII digits def test_bug_1704793(self): self.assertEqual(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346') def test_ucd_510(self): import unicodedata # In UCD 5.1.0, a mirrored property changed wrt. UCD 3.2.0 self.assertTrue(unicodedata.mirrored("\u0f3a")) self.assertTrue(not unicodedata.ucd_3_2_0.mirrored("\u0f3a")) # Also, we now have two ways of representing # the upper-case mapping: as delta, or as absolute value self.assertTrue("a".upper()=='A') self.assertTrue("\u1d79".upper()=='\ua77d') self.assertTrue(".".upper()=='.') def test_bug_5828(self): self.assertEqual("\u1d79".lower(), "\u1d79") # Only U+0000 should have U+0000 as its upper/lower/titlecase variant self.assertEqual( [ c for c in range(sys.maxunicode+1) if "\x00" in chr(c).lower()+chr(c).upper()+chr(c).title() ], [0] ) def test_bug_4971(self): # LETTER DZ WITH CARON: DZ, Dz, dz self.assertEqual("\u01c4".title(), "\u01c5") self.assertEqual("\u01c5".title(), "\u01c5") self.assertEqual("\u01c6".title(), "\u01c5") def test_linebreak_7643(self): for i in range(0x10000): lines = (chr(i) + 'A').splitlines() if i in (0x0a, 0x0b, 0x0c, 0x0d, 0x85, 0x1c, 0x1d, 0x1e, 0x2028, 0x2029): self.assertEqual(len(lines), 2, r"\u%.4x should be a linebreak" % i) else: self.assertEqual(len(lines), 1, r"\u%.4x should not be a linebreak" % i) 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/doctest_aliases.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/doctest_aliases.py
# Used by test_doctest.py. class TwoNames: '''f() and g() are two names for the same method''' def f(self): ''' >>> print(TwoNames().f()) f ''' return 'f' g = f # define an alias for f
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__opcode.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test__opcode.py
import dis from test.support import import_module import unittest _opcode = import_module("_opcode") class OpcodeTests(unittest.TestCase): def test_stack_effect(self): self.assertEqual(_opcode.stack_effect(dis.opmap['POP_TOP']), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['DUP_TOP_TWO']), 2) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 0), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 1), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 3), -2) self.assertRaises(ValueError, _opcode.stack_effect, 30000) self.assertRaises(ValueError, _opcode.stack_effect, dis.opmap['BUILD_SLICE']) self.assertRaises(ValueError, _opcode.stack_effect, dis.opmap['POP_TOP'], 0) 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_signal.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py
import os import random import signal import socket import statistics import subprocess import sys import threading import time import unittest from test import support from test.support.script_helper import assert_python_ok, spawn_python try: import _testcapi except ImportError: _testcapi = None class GenericTests(unittest.TestCase): def test_enums(self): for name in dir(signal): sig = getattr(signal, name) if name in {'SIG_DFL', 'SIG_IGN'}: self.assertIsInstance(sig, signal.Handlers) elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}: self.assertIsInstance(sig, signal.Sigmasks) elif name.startswith('SIG') and not name.startswith('SIG_'): self.assertIsInstance(sig, signal.Signals) elif name.startswith('CTRL_'): self.assertIsInstance(sig, signal.Signals) self.assertEqual(sys.platform, "win32") @unittest.skipIf(sys.platform == "win32", "Not valid on Windows") class PosixTests(unittest.TestCase): def trivial_signal_handler(self, *args): pass def test_out_of_range_signal_number_raises_error(self): self.assertRaises(ValueError, signal.getsignal, 4242) self.assertRaises(ValueError, signal.signal, 4242, self.trivial_signal_handler) def test_setting_signal_handler_to_none_raises_error(self): self.assertRaises(TypeError, signal.signal, signal.SIGUSR1, None) def test_getsignal(self): hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler) self.assertIsInstance(hup, signal.Handlers) self.assertEqual(signal.getsignal(signal.SIGHUP), self.trivial_signal_handler) signal.signal(signal.SIGHUP, hup) self.assertEqual(signal.getsignal(signal.SIGHUP), hup) # Issue 3864, unknown if this affects earlier versions of freebsd also def test_interprocess_signal(self): dirname = os.path.dirname(__file__) script = os.path.join(dirname, 'signalinterproctester.py') assert_python_ok(script) @unittest.skipUnless(sys.platform == "win32", "Windows specific") class WindowsSignalTests(unittest.TestCase): def test_issue9324(self): # Updated for issue #10003, adding SIGBREAK handler = lambda x, y: None checked = set() for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE, signal.SIGILL, signal.SIGINT, signal.SIGSEGV, signal.SIGTERM): # Set and then reset a handler for signals that work on windows. # Issue #18396, only for signals without a C-level handler. if signal.getsignal(sig) is not None: signal.signal(sig, signal.signal(sig, handler)) checked.add(sig) # Issue #18396: Ensure the above loop at least tested *something* self.assertTrue(checked) with self.assertRaises(ValueError): signal.signal(-1, handler) with self.assertRaises(ValueError): signal.signal(7, handler) class WakeupFDTests(unittest.TestCase): def test_invalid_call(self): # First parameter is positional-only with self.assertRaises(TypeError): signal.set_wakeup_fd(signum=signal.SIGINT) # warn_on_full_buffer is a keyword-only parameter with self.assertRaises(TypeError): signal.set_wakeup_fd(signal.SIGINT, False) def test_invalid_fd(self): fd = support.make_bad_fd() self.assertRaises((ValueError, OSError), signal.set_wakeup_fd, fd) def test_invalid_socket(self): sock = socket.socket() fd = sock.fileno() sock.close() self.assertRaises((ValueError, OSError), signal.set_wakeup_fd, fd) def test_set_wakeup_fd_result(self): r1, w1 = os.pipe() self.addCleanup(os.close, r1) self.addCleanup(os.close, w1) r2, w2 = os.pipe() self.addCleanup(os.close, r2) self.addCleanup(os.close, w2) if hasattr(os, 'set_blocking'): os.set_blocking(w1, False) os.set_blocking(w2, False) signal.set_wakeup_fd(w1) self.assertEqual(signal.set_wakeup_fd(w2), w1) self.assertEqual(signal.set_wakeup_fd(-1), w2) self.assertEqual(signal.set_wakeup_fd(-1), -1) def test_set_wakeup_fd_socket_result(self): sock1 = socket.socket() self.addCleanup(sock1.close) sock1.setblocking(False) fd1 = sock1.fileno() sock2 = socket.socket() self.addCleanup(sock2.close) sock2.setblocking(False) fd2 = sock2.fileno() signal.set_wakeup_fd(fd1) self.assertEqual(signal.set_wakeup_fd(fd2), fd1) self.assertEqual(signal.set_wakeup_fd(-1), fd2) self.assertEqual(signal.set_wakeup_fd(-1), -1) # On Windows, files are always blocking and Windows does not provide a # function to test if a socket is in non-blocking mode. @unittest.skipIf(sys.platform == "win32", "tests specific to POSIX") def test_set_wakeup_fd_blocking(self): rfd, wfd = os.pipe() self.addCleanup(os.close, rfd) self.addCleanup(os.close, wfd) # fd must be non-blocking os.set_blocking(wfd, True) with self.assertRaises(ValueError) as cm: signal.set_wakeup_fd(wfd) self.assertEqual(str(cm.exception), "the fd %s must be in non-blocking mode" % wfd) # non-blocking is ok os.set_blocking(wfd, False) signal.set_wakeup_fd(wfd) signal.set_wakeup_fd(-1) @unittest.skipIf(sys.platform == "win32", "Not valid on Windows") class WakeupSignalTests(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def check_wakeup(self, test_body, *signals, ordered=True): # use a subprocess to have only one thread code = """if 1: import _testcapi import os import signal import struct signals = {!r} def handler(signum, frame): pass def check_signum(signals): data = os.read(read, len(signals)+1) raised = struct.unpack('%uB' % len(data), data) if not {!r}: raised = set(raised) signals = set(signals) if raised != signals: raise Exception("%r != %r" % (raised, signals)) {} signal.signal(signal.SIGALRM, handler) read, write = os.pipe() os.set_blocking(write, False) signal.set_wakeup_fd(write) test() check_signum(signals) os.close(read) os.close(write) """.format(tuple(map(int, signals)), ordered, test_body) assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_wakeup_write_error(self): # Issue #16105: write() errors in the C signal handler should not # pass silently. # Use a subprocess to have only one thread. code = """if 1: import _testcapi import errno import os import signal import sys from test.support import captured_stderr def handler(signum, frame): 1/0 signal.signal(signal.SIGALRM, handler) r, w = os.pipe() os.set_blocking(r, False) # Set wakeup_fd a read-only file descriptor to trigger the error signal.set_wakeup_fd(r) try: with captured_stderr() as err: _testcapi.raise_signal(signal.SIGALRM) except ZeroDivisionError: # An ignored exception should have been printed out on stderr err = err.getvalue() if ('Exception ignored when trying to write to the signal wakeup fd' not in err): raise AssertionError(err) if ('OSError: [Errno %d]' % errno.EBADF) not in err: raise AssertionError(err) else: raise AssertionError("ZeroDivisionError not raised") os.close(r) os.close(w) """ r, w = os.pipe() try: os.write(r, b'x') except OSError: pass else: self.skipTest("OS doesn't report write() error on the read end of a pipe") finally: os.close(r) os.close(w) assert_python_ok('-c', code) def test_wakeup_fd_early(self): self.check_wakeup("""def test(): import select import time TIMEOUT_FULL = 10 TIMEOUT_HALF = 5 class InterruptSelect(Exception): pass def handler(signum, frame): raise InterruptSelect signal.signal(signal.SIGALRM, handler) signal.alarm(1) # We attempt to get a signal during the sleep, # before select is called try: select.select([], [], [], TIMEOUT_FULL) except InterruptSelect: pass else: raise Exception("select() was not interrupted") before_time = time.monotonic() select.select([read], [], [], TIMEOUT_FULL) after_time = time.monotonic() dt = after_time - before_time if dt >= TIMEOUT_HALF: raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) """, signal.SIGALRM) def test_wakeup_fd_during(self): self.check_wakeup("""def test(): import select import time TIMEOUT_FULL = 10 TIMEOUT_HALF = 5 class InterruptSelect(Exception): pass def handler(signum, frame): raise InterruptSelect signal.signal(signal.SIGALRM, handler) signal.alarm(1) before_time = time.monotonic() # We attempt to get a signal during the select call try: select.select([read], [], [], TIMEOUT_FULL) except InterruptSelect: pass else: raise Exception("select() was not interrupted") after_time = time.monotonic() dt = after_time - before_time if dt >= TIMEOUT_HALF: raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) """, signal.SIGALRM) def test_signum(self): self.check_wakeup("""def test(): import _testcapi signal.signal(signal.SIGUSR1, handler) _testcapi.raise_signal(signal.SIGUSR1) _testcapi.raise_signal(signal.SIGALRM) """, signal.SIGUSR1, signal.SIGALRM) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def test_pending(self): self.check_wakeup("""def test(): signum1 = signal.SIGUSR1 signum2 = signal.SIGUSR2 signal.signal(signum1, handler) signal.signal(signum2, handler) signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2)) _testcapi.raise_signal(signum1) _testcapi.raise_signal(signum2) # Unblocking the 2 signals calls the C signal handler twice signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2)) """, signal.SIGUSR1, signal.SIGUSR2, ordered=False) @unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair') class WakeupSocketSignalTests(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_socket(self): # use a subprocess to have only one thread code = """if 1: import signal import socket import struct import _testcapi signum = signal.SIGINT signals = (signum,) def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() write.setblocking(False) signal.set_wakeup_fd(write.fileno()) _testcapi.raise_signal(signum) data = read.recv(1) if not data: raise Exception("no signum written") raised = struct.unpack('B', data) if raised != signals: raise Exception("%r != %r" % (raised, signals)) read.close() write.close() """ assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_send_error(self): # Use a subprocess to have only one thread. if os.name == 'nt': action = 'send' else: action = 'write' code = """if 1: import errno import signal import socket import sys import time import _testcapi from test.support import captured_stderr signum = signal.SIGINT def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() read.setblocking(False) write.setblocking(False) signal.set_wakeup_fd(write.fileno()) # Close sockets: send() will fail read.close() write.close() with captured_stderr() as err: _testcapi.raise_signal(signum) err = err.getvalue() if ('Exception ignored when trying to {action} to the signal wakeup fd' not in err): raise AssertionError(err) """.format(action=action) assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_warn_on_full_buffer(self): # Use a subprocess to have only one thread. if os.name == 'nt': action = 'send' else: action = 'write' code = """if 1: import errno import signal import socket import sys import time import _testcapi from test.support import captured_stderr signum = signal.SIGINT # This handler will be called, but we intentionally won't read from # the wakeup fd. def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() # Fill the socketpair buffer if sys.platform == 'win32': # bpo-34130: On Windows, sometimes non-blocking send fails to fill # the full socketpair buffer, so use a timeout of 50 ms instead. write.settimeout(0.050) else: write.setblocking(False) # Start with large chunk size to reduce the # number of send needed to fill the buffer. written = 0 for chunk_size in (2 ** 16, 2 ** 8, 1): chunk = b"x" * chunk_size try: while True: write.send(chunk) written += chunk_size except (BlockingIOError, socket.timeout): pass print(f"%s bytes written into the socketpair" % written, flush=True) write.setblocking(False) try: write.send(b"x") except BlockingIOError: # The socketpair buffer seems full pass else: raise AssertionError("%s bytes failed to fill the socketpair " "buffer" % written) # By default, we get a warning when a signal arrives msg = ('Exception ignored when trying to {action} ' 'to the signal wakeup fd') signal.set_wakeup_fd(write.fileno()) with captured_stderr() as err: _testcapi.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("first set_wakeup_fd() test failed, " "stderr: %r" % err) # And also if warn_on_full_buffer=True signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=True) with captured_stderr() as err: _testcapi.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("set_wakeup_fd(warn_on_full_buffer=True) " "test failed, stderr: %r" % err) # But not if warn_on_full_buffer=False signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False) with captured_stderr() as err: _testcapi.raise_signal(signum) err = err.getvalue() if err != "": raise AssertionError("set_wakeup_fd(warn_on_full_buffer=False) " "test failed, stderr: %r" % err) # And then check the default again, to make sure warn_on_full_buffer # settings don't leak across calls. signal.set_wakeup_fd(write.fileno()) with captured_stderr() as err: _testcapi.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("second set_wakeup_fd() test failed, " "stderr: %r" % err) """.format(action=action) assert_python_ok('-c', code) @unittest.skipIf(sys.platform == "win32", "Not valid on Windows") class SiginterruptTest(unittest.TestCase): def readpipe_interrupted(self, interrupt): """Perform a read during which a signal will arrive. Return True if the read is interrupted by the signal and raises an exception. Return False if it returns normally. """ # use a subprocess to have only one thread, to have a timeout on the # blocking read and to not touch signal handling in this process code = """if 1: import errno import os import signal import sys interrupt = %r r, w = os.pipe() def handler(signum, frame): 1 / 0 signal.signal(signal.SIGALRM, handler) if interrupt is not None: signal.siginterrupt(signal.SIGALRM, interrupt) print("ready") sys.stdout.flush() # run the test twice try: for loop in range(2): # send a SIGALRM in a second (during the read) signal.alarm(1) try: # blocking call: read from a pipe without data os.read(r, 1) except ZeroDivisionError: pass else: sys.exit(2) sys.exit(3) finally: os.close(r) os.close(w) """ % (interrupt,) with spawn_python('-c', code) as process: try: # wait until the child process is loaded and has started first_line = process.stdout.readline() stdout, stderr = process.communicate(timeout=5.0) except subprocess.TimeoutExpired: process.kill() return False else: stdout = first_line + stdout exitcode = process.wait() if exitcode not in (2, 3): raise Exception("Child error (exit code %s): %r" % (exitcode, stdout)) return (exitcode == 3) def test_without_siginterrupt(self): # If a signal handler is installed and siginterrupt is not called # at all, when that signal arrives, it interrupts a syscall that's in # progress. interrupted = self.readpipe_interrupted(None) self.assertTrue(interrupted) def test_siginterrupt_on(self): # If a signal handler is installed and siginterrupt is called with # a true value for the second argument, when that signal arrives, it # interrupts a syscall that's in progress. interrupted = self.readpipe_interrupted(True) self.assertTrue(interrupted) def test_siginterrupt_off(self): # If a signal handler is installed and siginterrupt is called with # a false value for the second argument, when that signal arrives, it # does not interrupt a syscall that's in progress. interrupted = self.readpipe_interrupted(False) self.assertFalse(interrupted) @unittest.skipIf(sys.platform == "win32", "Not valid on Windows") class ItimerTest(unittest.TestCase): def setUp(self): self.hndl_called = False self.hndl_count = 0 self.itimer = None self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm) def tearDown(self): signal.signal(signal.SIGALRM, self.old_alarm) if self.itimer is not None: # test_itimer_exc doesn't change this attr # just ensure that itimer is stopped signal.setitimer(self.itimer, 0) def sig_alrm(self, *args): self.hndl_called = True def sig_vtalrm(self, *args): self.hndl_called = True if self.hndl_count > 3: # it shouldn't be here, because it should have been disabled. raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL " "timer.") elif self.hndl_count == 3: # disable ITIMER_VIRTUAL, this function shouldn't be called anymore signal.setitimer(signal.ITIMER_VIRTUAL, 0) self.hndl_count += 1 def sig_prof(self, *args): self.hndl_called = True signal.setitimer(signal.ITIMER_PROF, 0) def test_itimer_exc(self): # XXX I'm assuming -1 is an invalid itimer, but maybe some platform # defines it ? self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0) # Negative times are treated as zero on some platforms. if 0: self.assertRaises(signal.ItimerError, signal.setitimer, signal.ITIMER_REAL, -1) def test_itimer_real(self): self.itimer = signal.ITIMER_REAL signal.setitimer(self.itimer, 1.0) signal.pause() self.assertEqual(self.hndl_called, True) # Issue 3864, unknown if this affects earlier versions of freebsd also @unittest.skipIf(sys.platform in ('netbsd5',), 'itimer not reliable (does not mix well with threading) on some BSDs.') def test_itimer_virtual(self): self.itimer = signal.ITIMER_VIRTUAL signal.signal(signal.SIGVTALRM, self.sig_vtalrm) signal.setitimer(self.itimer, 0.3, 0.2) start_time = time.monotonic() while time.monotonic() - start_time < 60.0: # use up some virtual time by doing real work _ = pow(12345, 67890, 10000019) if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 self.skipTest("timeout: likely cause: machine too slow or load too " "high") # virtual itimer should be (0.0, 0.0) now self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0)) # and the handler should have been called self.assertEqual(self.hndl_called, True) def test_itimer_prof(self): self.itimer = signal.ITIMER_PROF signal.signal(signal.SIGPROF, self.sig_prof) signal.setitimer(self.itimer, 0.2, 0.2) start_time = time.monotonic() while time.monotonic() - start_time < 60.0: # do some work _ = pow(12345, 67890, 10000019) if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 self.skipTest("timeout: likely cause: machine too slow or load too " "high") # profiling itimer should be (0.0, 0.0) now self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0)) # and the handler should have been called self.assertEqual(self.hndl_called, True) def test_setitimer_tiny(self): # bpo-30807: C setitimer() takes a microsecond-resolution interval. # Check that float -> timeval conversion doesn't round # the interval down to zero, which would disable the timer. self.itimer = signal.ITIMER_REAL signal.setitimer(self.itimer, 1e-6) time.sleep(1) self.assertEqual(self.hndl_called, True) class PendingSignalsTests(unittest.TestCase): """ Test pthread_sigmask(), pthread_kill(), sigpending() and sigwait() functions. """ @unittest.skipUnless(hasattr(signal, 'sigpending'), 'need signal.sigpending()') def test_sigpending_empty(self): self.assertEqual(signal.sigpending(), set()) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') @unittest.skipUnless(hasattr(signal, 'sigpending'), 'need signal.sigpending()') def test_sigpending(self): code = """if 1: import os import signal def handler(signum, frame): 1/0 signum = signal.SIGUSR1 signal.signal(signum, handler) signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) os.kill(os.getpid(), signum) pending = signal.sigpending() for sig in pending: assert isinstance(sig, signal.Signals), repr(pending) if pending != {signum}: raise Exception('%s != {%s}' % (pending, signum)) try: signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) except ZeroDivisionError: pass else: raise Exception("ZeroDivisionError not raised") """ assert_python_ok('-c', code) @unittest.skipUnless(hasattr(signal, 'pthread_kill'), 'need signal.pthread_kill()') def test_pthread_kill(self): code = """if 1: import signal import threading import sys signum = signal.SIGUSR1 def handler(signum, frame): 1/0 signal.signal(signum, handler) tid = threading.get_ident() try: signal.pthread_kill(tid, signum) except ZeroDivisionError: pass else: raise Exception("ZeroDivisionError not raised") """ assert_python_ok('-c', code) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def wait_helper(self, blocked, test): """ test: body of the "def test(signum):" function. blocked: number of the blocked signal """ code = '''if 1: import signal import sys from signal import Signals def handler(signum, frame): 1/0 %s blocked = %s signum = signal.SIGALRM # child: block and wait the signal try: signal.signal(signum, handler) signal.pthread_sigmask(signal.SIG_BLOCK, [blocked]) # Do the tests test(signum) # The handler must not be called on unblock try: signal.pthread_sigmask(signal.SIG_UNBLOCK, [blocked]) except ZeroDivisionError: print("the signal handler has been called", file=sys.stderr) sys.exit(1) except BaseException as err: print("error: {}".format(err), file=sys.stderr) sys.stderr.flush() sys.exit(1) ''' % (test.strip(), blocked) # sig*wait* must be called with the signal blocked: since the current # process might have several threads running, use a subprocess to have # a single thread. assert_python_ok('-c', code) @unittest.skipUnless(hasattr(signal, 'sigwait'), 'need signal.sigwait()') def test_sigwait(self): self.wait_helper(signal.SIGALRM, ''' def test(signum): signal.alarm(1) received = signal.sigwait([signum]) assert isinstance(received, signal.Signals), received if received != signum: raise Exception('received %s, not %s' % (received, signum)) ''') @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'), 'need signal.sigwaitinfo()') def test_sigwaitinfo(self): self.wait_helper(signal.SIGALRM, ''' def test(signum): signal.alarm(1) info = signal.sigwaitinfo([signum]) if info.si_signo != signum: raise Exception("info.si_signo != %s" % signum) ''') @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigtimedwait()') def test_sigtimedwait(self): self.wait_helper(signal.SIGALRM, ''' def test(signum): signal.alarm(1) info = signal.sigtimedwait([signum], 10.1000) if info.si_signo != signum: raise Exception('info.si_signo != %s' % signum) ''') @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigtimedwait()') def test_sigtimedwait_poll(self): # check that polling with sigtimedwait works self.wait_helper(signal.SIGALRM, ''' def test(signum): import os os.kill(os.getpid(), signum) info = signal.sigtimedwait([signum], 0) if info.si_signo != signum: raise Exception('info.si_signo != %s' % signum) ''') @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigtimedwait()') def test_sigtimedwait_timeout(self): self.wait_helper(signal.SIGALRM, ''' def test(signum): received = signal.sigtimedwait([signum], 1.0) if received is not None: raise Exception("received=%r" % (received,)) ''') @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigtimedwait()') def test_sigtimedwait_negative_timeout(self): signum = signal.SIGALRM self.assertRaises(ValueError, signal.sigtimedwait, [signum], -1.0) @unittest.skipUnless(hasattr(signal, 'sigwait'), 'need signal.sigwait()') @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def test_sigwait_thread(self): # Check that calling sigwait() from a thread doesn't suspend the whole # process. A new interpreter is spawned to avoid problems when mixing # threads and fork(): only async-safe functions are allowed between # fork() and exec(). assert_python_ok("-c", """if True: import os, threading, sys, time, signal # the default handler terminates the process signum = signal.SIGUSR1 def kill_later(): # wait until the main thread is waiting in sigwait() time.sleep(1) os.kill(os.getpid(), signum) # the signal must be blocked by all the threads signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) killer = threading.Thread(target=kill_later) killer.start() received = signal.sigwait([signum]) if received != signum: print("sigwait() received %s, not %s" % (received, signum), file=sys.stderr) sys.exit(1) killer.join() # unblock the signal, which should have been cleared by sigwait() signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) """) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def test_pthread_sigmask_arguments(self): self.assertRaises(TypeError, signal.pthread_sigmask) self.assertRaises(TypeError, signal.pthread_sigmask, 1) self.assertRaises(TypeError, signal.pthread_sigmask, 1, 2, 3) self.assertRaises(OSError, signal.pthread_sigmask, 1700, []) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
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_types.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_types.py
# Python test set -- part 6, built-in types from test.support import run_with_locale import collections.abc import inspect import pickle import locale import sys import types import unittest.mock import weakref class TypesTests(unittest.TestCase): def test_truth_values(self): if None: self.fail('None is true instead of false') if 0: self.fail('0 is true instead of false') if 0.0: self.fail('0.0 is true instead of false') if '': self.fail('\'\' is true instead of false') if not 1: self.fail('1 is false instead of true') if not 1.0: self.fail('1.0 is false instead of true') if not 'x': self.fail('\'x\' is false instead of true') if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true') def f(): pass class C: pass x = C() if not f: self.fail('f is false instead of true') if not C: self.fail('C is false instead of true') if not sys: self.fail('sys is false instead of true') if not x: self.fail('x is false instead of true') def test_boolean_ops(self): if 0 or 0: self.fail('0 or 0 is true instead of false') if 1 and 1: pass else: self.fail('1 and 1 is false instead of true') if not 1: self.fail('not 1 is true instead of false') def test_comparisons(self): if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass else: self.fail('int comparisons failed') if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass else: self.fail('float comparisons failed') if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass else: self.fail('string comparisons failed') if None is None: pass else: self.fail('identity test failed') def test_float_constructor(self): self.assertRaises(ValueError, float, '') self.assertRaises(ValueError, float, '5\0') self.assertRaises(ValueError, float, '5_5\0') def test_zero_division(self): try: 5.0 / 0.0 except ZeroDivisionError: pass else: self.fail("5.0 / 0.0 didn't raise ZeroDivisionError") try: 5.0 // 0.0 except ZeroDivisionError: pass else: self.fail("5.0 // 0.0 didn't raise ZeroDivisionError") try: 5.0 % 0.0 except ZeroDivisionError: pass else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError") try: 5 / 0 except ZeroDivisionError: pass else: self.fail("5 / 0 didn't raise ZeroDivisionError") try: 5 // 0 except ZeroDivisionError: pass else: self.fail("5 // 0 didn't raise ZeroDivisionError") try: 5 % 0 except ZeroDivisionError: pass else: self.fail("5 % 0 didn't raise ZeroDivisionError") def test_numeric_types(self): if 0 != 0.0 or 1 != 1.0 or -1 != -1.0: self.fail('int/float value not equal') # calling built-in types without argument must return 0 if int() != 0: self.fail('int() does not return 0') if float() != 0.0: self.fail('float() does not return 0.0') if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass else: self.fail('int() does not round properly') if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass else: self.fail('float() does not work properly') def test_float_to_string(self): def test(f, result): self.assertEqual(f.__format__('e'), result) self.assertEqual('%e' % f, result) # test all 2 digit exponents, both with __format__ and with # '%' formatting for i in range(-99, 100): test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i)) # test some 3 digit exponents self.assertEqual(1.5e100.__format__('e'), '1.500000e+100') self.assertEqual('%e' % 1.5e100, '1.500000e+100') self.assertEqual(1.5e101.__format__('e'), '1.500000e+101') self.assertEqual('%e' % 1.5e101, '1.500000e+101') self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100') self.assertEqual('%e' % 1.5e-100, '1.500000e-100') self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101') self.assertEqual('%e' % 1.5e-101, '1.500000e-101') self.assertEqual('%g' % 1.0, '1') self.assertEqual('%#g' % 1.0, '1.00000') def test_normal_integers(self): # Ensure the first 256 integers are shared a = 256 b = 128*2 if a is not b: self.fail('256 is not shared') if 12 + 24 != 36: self.fail('int op') if 12 + (-24) != -12: self.fail('int op') if (-12) + 24 != 12: self.fail('int op') if (-12) + (-24) != -36: self.fail('int op') if not 12 < 24: self.fail('int op') if not -24 < -12: self.fail('int op') # Test for a particular bug in integer multiply xsize, ysize, zsize = 238, 356, 4 if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): self.fail('int mul commutativity') # And another. m = -sys.maxsize - 1 for divisor in 1, 2, 4, 8, 16, 32: j = m // divisor prod = divisor * j if prod != m: self.fail("%r * %r == %r != %r" % (divisor, j, prod, m)) if type(prod) is not int: self.fail("expected type(prod) to be int, not %r" % type(prod)) # Check for unified integral type for divisor in 1, 2, 4, 8, 16, 32: j = m // divisor - 1 prod = divisor * j if type(prod) is not int: self.fail("expected type(%r) to be int, not %r" % (prod, type(prod))) # Check for unified integral type m = sys.maxsize for divisor in 1, 2, 4, 8, 16, 32: j = m // divisor + 1 prod = divisor * j if type(prod) is not int: self.fail("expected type(%r) to be int, not %r" % (prod, type(prod))) x = sys.maxsize self.assertIsInstance(x + 1, int, "(sys.maxsize + 1) should have returned int") self.assertIsInstance(-x - 1, int, "(-sys.maxsize - 1) should have returned int") self.assertIsInstance(-x - 2, int, "(-sys.maxsize - 2) should have returned int") try: 5 << -5 except ValueError: pass else: self.fail('int negative shift <<') try: 5 >> -5 except ValueError: pass else: self.fail('int negative shift >>') def test_floats(self): if 12.0 + 24.0 != 36.0: self.fail('float op') if 12.0 + (-24.0) != -12.0: self.fail('float op') if (-12.0) + 24.0 != 12.0: self.fail('float op') if (-12.0) + (-24.0) != -36.0: self.fail('float op') if not 12.0 < 24.0: self.fail('float op') if not -24.0 < -12.0: self.fail('float op') def test_strings(self): if len('') != 0: self.fail('len(\'\')') if len('a') != 1: self.fail('len(\'a\')') if len('abcdef') != 6: self.fail('len(\'abcdef\')') if 'xyz' + 'abcde' != 'xyzabcde': self.fail('string concatenation') if 'xyz'*3 != 'xyzxyzxyz': self.fail('string repetition *3') if 0*'abcde' != '': self.fail('string repetition 0*') if min('abc') != 'a' or max('abc') != 'c': self.fail('min/max string') if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass else: self.fail('in/not in string') x = 'x'*103 if '%s!'%x != x+'!': self.fail('nasty string formatting bug') #extended slices for strings a = '0123456789' self.assertEqual(a[::], a) self.assertEqual(a[::2], '02468') self.assertEqual(a[1::2], '13579') self.assertEqual(a[::-1],'9876543210') self.assertEqual(a[::-2], '97531') self.assertEqual(a[3::-2], '31') self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) self.assertEqual(a[-100:100:2], '02468') def test_type_function(self): self.assertRaises(TypeError, type, 1, 2) self.assertRaises(TypeError, type, 1, 2, 3, 4) def test_int__format__(self): def test(i, format_spec, result): # just make sure we have the unified type for integers assert type(i) == int assert type(format_spec) == str self.assertEqual(i.__format__(format_spec), result) test(123456789, 'd', '123456789') test(123456789, 'd', '123456789') test(1, 'c', '\01') # sign and aligning are interdependent test(1, "-", '1') test(-1, "-", '-1') test(1, "-3", ' 1') test(-1, "-3", ' -1') test(1, "+3", ' +1') test(-1, "+3", ' -1') test(1, " 3", ' 1') test(-1, " 3", ' -1') test(1, " ", ' 1') test(-1, " ", '-1') # hex test(3, "x", "3") test(3, "X", "3") test(1234, "x", "4d2") test(-1234, "x", "-4d2") test(1234, "8x", " 4d2") test(-1234, "8x", " -4d2") test(1234, "x", "4d2") test(-1234, "x", "-4d2") test(-3, "x", "-3") test(-3, "X", "-3") test(int('be', 16), "x", "be") test(int('be', 16), "X", "BE") test(-int('be', 16), "x", "-be") test(-int('be', 16), "X", "-BE") # octal test(3, "o", "3") test(-3, "o", "-3") test(65, "o", "101") test(-65, "o", "-101") test(1234, "o", "2322") test(-1234, "o", "-2322") test(1234, "-o", "2322") test(-1234, "-o", "-2322") test(1234, " o", " 2322") test(-1234, " o", "-2322") test(1234, "+o", "+2322") test(-1234, "+o", "-2322") # binary test(3, "b", "11") test(-3, "b", "-11") test(1234, "b", "10011010010") test(-1234, "b", "-10011010010") test(1234, "-b", "10011010010") test(-1234, "-b", "-10011010010") test(1234, " b", " 10011010010") test(-1234, " b", "-10011010010") test(1234, "+b", "+10011010010") test(-1234, "+b", "-10011010010") # alternate (#) formatting test(0, "#b", '0b0') test(0, "-#b", '0b0') test(1, "-#b", '0b1') test(-1, "-#b", '-0b1') test(-1, "-#5b", ' -0b1') test(1, "+#5b", ' +0b1') test(100, "+#b", '+0b1100100') test(100, "#012b", '0b0001100100') test(-100, "#012b", '-0b001100100') test(0, "#o", '0o0') test(0, "-#o", '0o0') test(1, "-#o", '0o1') test(-1, "-#o", '-0o1') test(-1, "-#5o", ' -0o1') test(1, "+#5o", ' +0o1') test(100, "+#o", '+0o144') test(100, "#012o", '0o0000000144') test(-100, "#012o", '-0o000000144') test(0, "#x", '0x0') test(0, "-#x", '0x0') test(1, "-#x", '0x1') test(-1, "-#x", '-0x1') test(-1, "-#5x", ' -0x1') test(1, "+#5x", ' +0x1') test(100, "+#x", '+0x64') test(100, "#012x", '0x0000000064') test(-100, "#012x", '-0x000000064') test(123456, "#012x", '0x000001e240') test(-123456, "#012x", '-0x00001e240') test(0, "#X", '0X0') test(0, "-#X", '0X0') test(1, "-#X", '0X1') test(-1, "-#X", '-0X1') test(-1, "-#5X", ' -0X1') test(1, "+#5X", ' +0X1') test(100, "+#X", '+0X64') test(100, "#012X", '0X0000000064') test(-100, "#012X", '-0X000000064') test(123456, "#012X", '0X000001E240') test(-123456, "#012X", '-0X00001E240') test(123, ',', '123') test(-123, ',', '-123') test(1234, ',', '1,234') test(-1234, ',', '-1,234') test(123456, ',', '123,456') test(-123456, ',', '-123,456') test(1234567, ',', '1,234,567') test(-1234567, ',', '-1,234,567') # issue 5782, commas with no specifier type test(1234, '010,', '00,001,234') # Unified type for integers test(10**100, 'd', '1' + '0' * 100) test(10**100+100, 'd', '1' + '0' * 97 + '100') # make sure these are errors # precision disallowed self.assertRaises(ValueError, 3 .__format__, "1.3") # sign not allowed with 'c' self.assertRaises(ValueError, 3 .__format__, "+c") # format spec must be string self.assertRaises(TypeError, 3 .__format__, None) self.assertRaises(TypeError, 3 .__format__, 0) # can't have ',' with 'n' self.assertRaises(ValueError, 3 .__format__, ",n") # can't have ',' with 'c' self.assertRaises(ValueError, 3 .__format__, ",c") # can't have '#' with 'c' self.assertRaises(ValueError, 3 .__format__, "#c") # ensure that only int and float type specifiers work for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + [chr(x) for x in range(ord('A'), ord('Z')+1)]): if not format_spec in 'bcdoxXeEfFgGn%': self.assertRaises(ValueError, 0 .__format__, format_spec) self.assertRaises(ValueError, 1 .__format__, format_spec) self.assertRaises(ValueError, (-1) .__format__, format_spec) # ensure that float type specifiers work; format converts # the int to a float for format_spec in 'eEfFgG%': for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]: self.assertEqual(value.__format__(format_spec), float(value).__format__(format_spec)) # Issue 6902 test(123456, "0<20", '12345600000000000000') test(123456, "1<20", '12345611111111111111') test(123456, "*<20", '123456**************') test(123456, "0>20", '00000000000000123456') test(123456, "1>20", '11111111111111123456') test(123456, "*>20", '**************123456') test(123456, "0=20", '00000000000000123456') test(123456, "1=20", '11111111111111123456') test(123456, "*=20", '**************123456') @run_with_locale('LC_NUMERIC', 'en_US.UTF8') def test_float__format__locale(self): # test locale support for __format__ code 'n' for i in range(-10, 10): x = 1234567890.0 * (10.0 ** i) self.assertEqual(locale.format_string('%g', x, grouping=True), format(x, 'n')) self.assertEqual(locale.format_string('%.10g', x, grouping=True), format(x, '.10n')) @run_with_locale('LC_NUMERIC', 'en_US.UTF8') def test_int__format__locale(self): # test locale support for __format__ code 'n' for integers x = 123456789012345678901234567890 for i in range(0, 30): self.assertEqual(locale.format_string('%d', x, grouping=True), format(x, 'n')) # move to the next integer to test x = x // 10 rfmt = ">20n" lfmt = "<20n" cfmt = "^20n" for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900): self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt))) self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt))) self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt))) def test_float__format__(self): def test(f, format_spec, result): self.assertEqual(f.__format__(format_spec), result) self.assertEqual(format(f, format_spec), result) test(0.0, 'f', '0.000000') # the default is 'g', except for empty format spec test(0.0, '', '0.0') test(0.01, '', '0.01') test(0.01, 'g', '0.01') # test for issue 3411 test(1.23, '1', '1.23') test(-1.23, '1', '-1.23') test(1.23, '1g', '1.23') test(-1.23, '1g', '-1.23') test( 1.0, ' g', ' 1') test(-1.0, ' g', '-1') test( 1.0, '+g', '+1') test(-1.0, '+g', '-1') test(1.1234e200, 'g', '1.1234e+200') test(1.1234e200, 'G', '1.1234E+200') test(1.0, 'f', '1.000000') test(-1.0, 'f', '-1.000000') test( 1.0, ' f', ' 1.000000') test(-1.0, ' f', '-1.000000') test( 1.0, '+f', '+1.000000') test(-1.0, '+f', '-1.000000') # Python versions <= 3.0 switched from 'f' to 'g' formatting for # values larger than 1e50. No longer. f = 1.1234e90 for fmt in 'f', 'F': # don't do a direct equality check, since on some # platforms only the first few digits of dtoa # will be reliable result = f.__format__(fmt) self.assertEqual(len(result), 98) self.assertEqual(result[-7], '.') self.assertIn(result[:12], ('112340000000', '112339999999')) f = 1.1234e200 for fmt in 'f', 'F': result = f.__format__(fmt) self.assertEqual(len(result), 208) self.assertEqual(result[-7], '.') self.assertIn(result[:12], ('112340000000', '112339999999')) test( 1.0, 'e', '1.000000e+00') test(-1.0, 'e', '-1.000000e+00') test( 1.0, 'E', '1.000000E+00') test(-1.0, 'E', '-1.000000E+00') test(1.1234e20, 'e', '1.123400e+20') test(1.1234e20, 'E', '1.123400E+20') # No format code means use g, but must have a decimal # and a number after the decimal. This is tricky, because # a totaly empty format specifier means something else. # So, just use a sign flag test(1e200, '+g', '+1e+200') test(1e200, '+', '+1e+200') test(1.1e200, '+g', '+1.1e+200') test(1.1e200, '+', '+1.1e+200') # 0 padding test(1234., '010f', '1234.000000') test(1234., '011f', '1234.000000') test(1234., '012f', '01234.000000') test(-1234., '011f', '-1234.000000') test(-1234., '012f', '-1234.000000') test(-1234., '013f', '-01234.000000') test(-1234.12341234, '013f', '-01234.123412') test(-123456.12341234, '011.2f', '-0123456.12') # issue 5782, commas with no specifier type test(1.2, '010,.2', '0,000,001.2') # 0 padding with commas test(1234., '011,f', '1,234.000000') test(1234., '012,f', '1,234.000000') test(1234., '013,f', '01,234.000000') test(-1234., '012,f', '-1,234.000000') test(-1234., '013,f', '-1,234.000000') test(-1234., '014,f', '-01,234.000000') test(-12345., '015,f', '-012,345.000000') test(-123456., '016,f', '-0,123,456.000000') test(-123456., '017,f', '-0,123,456.000000') test(-123456.12341234, '017,f', '-0,123,456.123412') test(-123456.12341234, '013,.2f', '-0,123,456.12') # % formatting test(-1.0, '%', '-100.000000%') # format spec must be string self.assertRaises(TypeError, 3.0.__format__, None) self.assertRaises(TypeError, 3.0.__format__, 0) # other format specifiers shouldn't work on floats, # in particular int specifiers for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + [chr(x) for x in range(ord('A'), ord('Z')+1)]): if not format_spec in 'eEfFgGn%': self.assertRaises(ValueError, format, 0.0, format_spec) self.assertRaises(ValueError, format, 1.0, format_spec) self.assertRaises(ValueError, format, -1.0, format_spec) self.assertRaises(ValueError, format, 1e100, format_spec) self.assertRaises(ValueError, format, -1e100, format_spec) self.assertRaises(ValueError, format, 1e-100, format_spec) self.assertRaises(ValueError, format, -1e-100, format_spec) # Alternate float formatting test(1.0, '.0e', '1e+00') test(1.0, '#.0e', '1.e+00') test(1.0, '.0f', '1') test(1.0, '#.0f', '1.') test(1.1, 'g', '1.1') test(1.1, '#g', '1.10000') test(1.0, '.0%', '100%') test(1.0, '#.0%', '100.%') # Issue 7094: Alternate formatting (specified by #) test(1.0, '0e', '1.000000e+00') test(1.0, '#0e', '1.000000e+00') test(1.0, '0f', '1.000000' ) test(1.0, '#0f', '1.000000') test(1.0, '.1e', '1.0e+00') test(1.0, '#.1e', '1.0e+00') test(1.0, '.1f', '1.0') test(1.0, '#.1f', '1.0') test(1.0, '.1%', '100.0%') test(1.0, '#.1%', '100.0%') # Issue 6902 test(12345.6, "0<20", '12345.60000000000000') test(12345.6, "1<20", '12345.61111111111111') test(12345.6, "*<20", '12345.6*************') test(12345.6, "0>20", '000000000000012345.6') test(12345.6, "1>20", '111111111111112345.6') test(12345.6, "*>20", '*************12345.6') test(12345.6, "0=20", '000000000000012345.6') test(12345.6, "1=20", '111111111111112345.6') test(12345.6, "*=20", '*************12345.6') def test_format_spec_errors(self): # int, float, and string all share the same format spec # mini-language parser. # Check that we can't ask for too many digits. This is # probably a CPython specific test. It tries to put the width # into a C long. self.assertRaises(ValueError, format, 0, '1'*10000 + 'd') # Similar with the precision. self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd') # And may as well test both. self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd') # Make sure commas aren't allowed with various type codes for code in 'xXobns': self.assertRaises(ValueError, format, 0, ',' + code) def test_internal_sizes(self): self.assertGreater(object.__basicsize__, 0) self.assertGreater(tuple.__itemsize__, 0) def test_slot_wrapper_types(self): self.assertIsInstance(object.__init__, types.WrapperDescriptorType) self.assertIsInstance(object.__str__, types.WrapperDescriptorType) self.assertIsInstance(object.__lt__, types.WrapperDescriptorType) self.assertIsInstance(int.__lt__, types.WrapperDescriptorType) def test_method_wrapper_types(self): self.assertIsInstance(object().__init__, types.MethodWrapperType) self.assertIsInstance(object().__str__, types.MethodWrapperType) self.assertIsInstance(object().__lt__, types.MethodWrapperType) self.assertIsInstance((42).__lt__, types.MethodWrapperType) def test_method_descriptor_types(self): self.assertIsInstance(str.join, types.MethodDescriptorType) self.assertIsInstance(list.append, types.MethodDescriptorType) self.assertIsInstance(''.join, types.BuiltinMethodType) self.assertIsInstance([].append, types.BuiltinMethodType) self.assertIsInstance(int.__dict__['from_bytes'], types.ClassMethodDescriptorType) self.assertIsInstance(int.from_bytes, types.BuiltinMethodType) self.assertIsInstance(int.__new__, types.BuiltinMethodType) class MappingProxyTests(unittest.TestCase): mappingproxy = types.MappingProxyType def test_constructor(self): class userdict(dict): pass mapping = {'x': 1, 'y': 2} self.assertEqual(self.mappingproxy(mapping), mapping) mapping = userdict(x=1, y=2) self.assertEqual(self.mappingproxy(mapping), mapping) mapping = collections.ChainMap({'x': 1}, {'y': 2}) self.assertEqual(self.mappingproxy(mapping), mapping) self.assertRaises(TypeError, self.mappingproxy, 10) self.assertRaises(TypeError, self.mappingproxy, ("a", "tuple")) self.assertRaises(TypeError, self.mappingproxy, ["a", "list"]) def test_methods(self): attrs = set(dir(self.mappingproxy({}))) - set(dir(object())) self.assertEqual(attrs, { '__contains__', '__getitem__', '__iter__', '__len__', 'copy', 'get', 'items', 'keys', 'values', }) def test_get(self): view = self.mappingproxy({'a': 'A', 'b': 'B'}) self.assertEqual(view['a'], 'A') self.assertEqual(view['b'], 'B') self.assertRaises(KeyError, view.__getitem__, 'xxx') self.assertEqual(view.get('a'), 'A') self.assertIsNone(view.get('xxx')) self.assertEqual(view.get('xxx', 42), 42) def test_missing(self): class dictmissing(dict): def __missing__(self, key): return "missing=%s" % key view = self.mappingproxy(dictmissing(x=1)) self.assertEqual(view['x'], 1) self.assertEqual(view['y'], 'missing=y') self.assertEqual(view.get('x'), 1) self.assertEqual(view.get('y'), None) self.assertEqual(view.get('y', 42), 42) self.assertTrue('x' in view) self.assertFalse('y' in view) def test_customdict(self): class customdict(dict): def __contains__(self, key): if key == 'magic': return True else: return dict.__contains__(self, key) def __iter__(self): return iter(('iter',)) def __len__(self): return 500 def copy(self): return 'copy' def keys(self): return 'keys' def items(self): return 'items' def values(self): return 'values' def __getitem__(self, key): return "getitem=%s" % dict.__getitem__(self, key) def get(self, key, default=None): return "get=%s" % dict.get(self, key, 'default=%r' % default) custom = customdict({'key': 'value'}) view = self.mappingproxy(custom) self.assertTrue('key' in view) self.assertTrue('magic' in view) self.assertFalse('xxx' in view) self.assertEqual(view['key'], 'getitem=value') self.assertRaises(KeyError, view.__getitem__, 'xxx') self.assertEqual(tuple(view), ('iter',)) self.assertEqual(len(view), 500) self.assertEqual(view.copy(), 'copy') self.assertEqual(view.get('key'), 'get=value') self.assertEqual(view.get('xxx'), 'get=default=None') self.assertEqual(view.items(), 'items') self.assertEqual(view.keys(), 'keys') self.assertEqual(view.values(), 'values') def test_chainmap(self): d1 = {'x': 1} d2 = {'y': 2} mapping = collections.ChainMap(d1, d2) view = self.mappingproxy(mapping) self.assertTrue('x' in view) self.assertTrue('y' in view) self.assertFalse('z' in view) self.assertEqual(view['x'], 1) self.assertEqual(view['y'], 2) self.assertRaises(KeyError, view.__getitem__, 'z') self.assertEqual(tuple(sorted(view)), ('x', 'y')) self.assertEqual(len(view), 2) copy = view.copy() self.assertIsNot(copy, mapping) self.assertIsInstance(copy, collections.ChainMap) self.assertEqual(copy, mapping) self.assertEqual(view.get('x'), 1) self.assertEqual(view.get('y'), 2) self.assertIsNone(view.get('z')) self.assertEqual(tuple(sorted(view.items())), (('x', 1), ('y', 2))) self.assertEqual(tuple(sorted(view.keys())), ('x', 'y')) self.assertEqual(tuple(sorted(view.values())), (1, 2)) def test_contains(self): view = self.mappingproxy(dict.fromkeys('abc')) self.assertTrue('a' in view) self.assertTrue('b' in view) self.assertTrue('c' in view) self.assertFalse('xxx' in view) def test_views(self): mapping = {} view = self.mappingproxy(mapping) keys = view.keys() values = view.values() items = view.items() self.assertEqual(list(keys), []) self.assertEqual(list(values), []) self.assertEqual(list(items), []) mapping['key'] = 'value' self.assertEqual(list(keys), ['key']) self.assertEqual(list(values), ['value']) self.assertEqual(list(items), [('key', 'value')]) def test_len(self): for expected in range(6): data = dict.fromkeys('abcde'[:expected]) self.assertEqual(len(data), expected) view = self.mappingproxy(data) self.assertEqual(len(view), expected) def test_iterators(self): keys = ('x', 'y') values = (1, 2) items = tuple(zip(keys, values)) view = self.mappingproxy(dict(items)) self.assertEqual(set(view), set(keys)) self.assertEqual(set(view.keys()), set(keys)) self.assertEqual(set(view.values()), set(values)) self.assertEqual(set(view.items()), set(items)) def test_copy(self): original = {'key1': 27, 'key2': 51, 'key3': 93} view = self.mappingproxy(original) copy = view.copy() self.assertEqual(type(copy), dict) self.assertEqual(copy, original) original['key1'] = 70 self.assertEqual(view['key1'], 70) self.assertEqual(copy['key1'], 27) class ClassCreationTests(unittest.TestCase): class Meta(type): def __init__(cls, name, bases, ns, **kw): super().__init__(name, bases, ns) @staticmethod def __new__(mcls, name, bases, ns, **kw): return super().__new__(mcls, name, bases, ns) @classmethod def __prepare__(mcls, name, bases, **kw): ns = super().__prepare__(name, bases) ns["y"] = 1 ns.update(kw) return ns def test_new_class_basics(self): C = types.new_class("C") self.assertEqual(C.__name__, "C") self.assertEqual(C.__bases__, (object,)) def test_new_class_subclass(self): C = types.new_class("C", (int,)) self.assertTrue(issubclass(C, int)) def test_new_class_meta(self): Meta = self.Meta settings = {"metaclass": Meta, "z": 2} # We do this twice to make sure the passed in dict isn't mutated for i in range(2): C = types.new_class("C" + str(i), (), settings) self.assertIsInstance(C, Meta) self.assertEqual(C.y, 1) self.assertEqual(C.z, 2) def test_new_class_exec_body(self): Meta = self.Meta def func(ns): ns["x"] = 0 C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func) self.assertIsInstance(C, Meta) self.assertEqual(C.x, 0) self.assertEqual(C.y, 1) self.assertEqual(C.z, 2) def test_new_class_metaclass_keywords(self): #Test that keywords are passed to the metaclass: def meta_func(name, bases, ns, **kw): return name, bases, ns, kw res = types.new_class("X", (int, object), dict(metaclass=meta_func, x=0)) self.assertEqual(res, ("X", (int, object), {}, {"x": 0})) def test_new_class_defaults(self): # Test defaults/keywords: C = types.new_class("C", (), {}, None) self.assertEqual(C.__name__, "C") self.assertEqual(C.__bases__, (object,)) def test_new_class_meta_with_base(self): Meta = self.Meta def func(ns): ns["x"] = 0 C = types.new_class(name="C", bases=(int,), kwds=dict(metaclass=Meta, z=2), exec_body=func) self.assertTrue(issubclass(C, int)) self.assertIsInstance(C, Meta) self.assertEqual(C.x, 0) self.assertEqual(C.y, 1) self.assertEqual(C.z, 2) def test_new_class_with_mro_entry(self): class A: pass class C: def __mro_entries__(self, bases): return (A,) c = C() D = types.new_class('D', (c,), {}) self.assertEqual(D.__bases__, (A,)) self.assertEqual(D.__orig_bases__, (c,)) self.assertEqual(D.__mro__, (D, A, object)) def test_new_class_with_mro_entry_none(self): class A: pass class B: pass class C: def __mro_entries__(self, bases): return () c = C() D = types.new_class('D', (A, c, B), {})
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_optparse.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
# # Test suite for Optik. Supplied by Johannes Gijsbers # (taradino@softhome.net) -- translated from the original Optik # test suite to this PyUnit-based version. # # $Id$ # import sys import os import re import copy import unittest from io import StringIO from test import support import optparse from optparse import make_option, Option, \ TitledHelpFormatter, OptionParser, OptionGroup, \ SUPPRESS_USAGE, OptionError, OptionConflictError, \ BadOptionError, OptionValueError, Values from optparse import _match_abbrev from optparse import _parse_num class InterceptedError(Exception): def __init__(self, error_message=None, exit_status=None, exit_message=None): self.error_message = error_message self.exit_status = exit_status self.exit_message = exit_message def __str__(self): return self.error_message or self.exit_message or "intercepted error" class InterceptingOptionParser(OptionParser): def exit(self, status=0, msg=None): raise InterceptedError(exit_status=status, exit_message=msg) def error(self, msg): raise InterceptedError(error_message=msg) class BaseTest(unittest.TestCase): def assertParseOK(self, args, expected_opts, expected_positional_args): """Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and positional args for further testing. """ (options, positional_args) = self.parser.parse_args(args) optdict = vars(options) self.assertEqual(optdict, expected_opts, """ Options are %(optdict)s. Should be %(expected_opts)s. Args were %(args)s.""" % locals()) self.assertEqual(positional_args, expected_positional_args, """ Positional arguments are %(positional_args)s. Should be %(expected_positional_args)s. Args were %(args)s.""" % locals ()) return (options, positional_args) def assertRaises(self, func, args, kwargs, expected_exception, expected_message): """ Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_message -- expected exception message (or pattern if a compiled regex object) Returns the exception raised for further testing. """ if args is None: args = () if kwargs is None: kwargs = {} try: func(*args, **kwargs) except expected_exception as err: actual_message = str(err) if isinstance(expected_message, re.Pattern): self.assertTrue(expected_message.search(actual_message), """\ expected exception message pattern: /%s/ actual exception message: '''%s''' """ % (expected_message.pattern, actual_message)) else: self.assertEqual(actual_message, expected_message, """\ expected exception message: '''%s''' actual exception message: '''%s''' """ % (expected_message, actual_message)) return err else: self.fail("""expected exception %(expected_exception)s not raised called %(func)r with args %(args)r and kwargs %(kwargs)r """ % locals ()) # -- Assertions used in more than one class -------------------- def assertParseFail(self, cmdline_args, expected_output): """ Assert the parser fails with the expected message. Caller must ensure that self.parser is an InterceptingOptionParser. """ try: self.parser.parse_args(cmdline_args) except InterceptedError as err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") def assertOutput(self, cmdline_args, expected_output, expected_status=0, expected_error=None): """Assert the parser prints the expected output on stdout.""" save_stdout = sys.stdout try: try: sys.stdout = StringIO() self.parser.parse_args(cmdline_args) finally: output = sys.stdout.getvalue() sys.stdout = save_stdout except InterceptedError as err: self.assertTrue( isinstance(output, str), "expected output to be an ordinary string, not %r" % type(output)) if output != expected_output: self.fail("expected: \n'''\n" + expected_output + "'''\nbut got \n'''\n" + output + "'''") self.assertEqual(err.exit_status, expected_status) self.assertEqual(err.exit_message, expected_error) else: self.assertFalse("expected parser.exit()") def assertTypeError(self, func, expected_message, *args): """Assert that TypeError is raised when executing func.""" self.assertRaises(func, args, None, TypeError, expected_message) def assertHelp(self, parser, expected_help): actual_help = parser.format_help() if actual_help != expected_help: raise self.failureException( 'help text failure; expected:\n"' + expected_help + '"; got:\n"' + actual_help + '"\n') # -- Test make_option() aka Option ------------------------------------- # It's not necessary to test correct options here. All the tests in the # parser.parse_args() section deal with those, because they're needed # there. class TestOptionChecks(BaseTest): def setUp(self): self.parser = OptionParser(usage=SUPPRESS_USAGE) def assertOptionError(self, expected_message, args=[], kwargs={}): self.assertRaises(make_option, args, kwargs, OptionError, expected_message) def test_opt_string_empty(self): self.assertTypeError(make_option, "at least one option string must be supplied") def test_opt_string_too_short(self): self.assertOptionError( "invalid option string 'b': must be at least two characters long", ["b"]) def test_opt_string_short_invalid(self): self.assertOptionError( "invalid short option string '--': must be " "of the form -x, (x any non-dash char)", ["--"]) def test_opt_string_long_invalid(self): self.assertOptionError( "invalid long option string '---': " "must start with --, followed by non-dash", ["---"]) def test_attr_invalid(self): self.assertOptionError( "option -b: invalid keyword arguments: bar, foo", ["-b"], {'foo': None, 'bar': None}) def test_action_invalid(self): self.assertOptionError( "option -b: invalid action: 'foo'", ["-b"], {'action': 'foo'}) def test_type_invalid(self): self.assertOptionError( "option -b: invalid option type: 'foo'", ["-b"], {'type': 'foo'}) self.assertOptionError( "option -b: invalid option type: 'tuple'", ["-b"], {'type': tuple}) def test_no_type_for_action(self): self.assertOptionError( "option -b: must not supply a type for action 'count'", ["-b"], {'action': 'count', 'type': 'int'}) def test_no_choices_list(self): self.assertOptionError( "option -b/--bad: must supply a list of " "choices for type 'choice'", ["-b", "--bad"], {'type': "choice"}) def test_bad_choices_list(self): typename = type('').__name__ self.assertOptionError( "option -b/--bad: choices must be a list of " "strings ('%s' supplied)" % typename, ["-b", "--bad"], {'type': "choice", 'choices':"bad choices"}) def test_no_choices_for_type(self): self.assertOptionError( "option -b: must not supply choices for type 'int'", ["-b"], {'type': 'int', 'choices':"bad"}) def test_no_const_for_action(self): self.assertOptionError( "option -b: 'const' must not be supplied for action 'store'", ["-b"], {'action': 'store', 'const': 1}) def test_no_nargs_for_action(self): self.assertOptionError( "option -b: 'nargs' must not be supplied for action 'count'", ["-b"], {'action': 'count', 'nargs': 2}) def test_callback_not_callable(self): self.assertOptionError( "option -b: callback not callable: 'foo'", ["-b"], {'action': 'callback', 'callback': 'foo'}) def dummy(self): pass def test_callback_args_no_tuple(self): self.assertOptionError( "option -b: callback_args, if supplied, " "must be a tuple: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_args': 'foo'}) def test_callback_kwargs_no_dict(self): self.assertOptionError( "option -b: callback_kwargs, if supplied, " "must be a dict: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_kwargs': 'foo'}) def test_no_callback_for_action(self): self.assertOptionError( "option -b: callback supplied ('foo') for non-callback option", ["-b"], {'action': 'store', 'callback': 'foo'}) def test_no_callback_args_for_action(self): self.assertOptionError( "option -b: callback_args supplied for non-callback option", ["-b"], {'action': 'store', 'callback_args': 'foo'}) def test_no_callback_kwargs_for_action(self): self.assertOptionError( "option -b: callback_kwargs supplied for non-callback option", ["-b"], {'action': 'store', 'callback_kwargs': 'foo'}) def test_no_single_dash(self): self.assertOptionError( "invalid long option string '-debug': " "must start with --, followed by non-dash", ["-debug"]) self.assertOptionError( "option -d: invalid long option string '-debug': must start with" " --, followed by non-dash", ["-d", "-debug"]) self.assertOptionError( "invalid long option string '-debug': " "must start with --, followed by non-dash", ["-debug", "--debug"]) class TestOptionParser(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", "-n", "--noisy", action="store_true", dest="verbose") self.parser.add_option("-q", "--quiet", "--silent", action="store_false", dest="verbose") def test_add_option_no_Option(self): self.assertTypeError(self.parser.add_option, "not an Option instance: None", None) def test_add_option_invalid_arguments(self): self.assertTypeError(self.parser.add_option, "invalid arguments", None, None) def test_get_option(self): opt1 = self.parser.get_option("-v") self.assertIsInstance(opt1, Option) self.assertEqual(opt1._short_opts, ["-v", "-n"]) self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"]) self.assertEqual(opt1.action, "store_true") self.assertEqual(opt1.dest, "verbose") def test_get_option_equals(self): opt1 = self.parser.get_option("-v") opt2 = self.parser.get_option("--verbose") opt3 = self.parser.get_option("-n") opt4 = self.parser.get_option("--noisy") self.assertTrue(opt1 is opt2 is opt3 is opt4) def test_has_option(self): self.assertTrue(self.parser.has_option("-v")) self.assertTrue(self.parser.has_option("--verbose")) def assertTrueremoved(self): self.assertTrue(self.parser.get_option("-v") is None) self.assertTrue(self.parser.get_option("--verbose") is None) self.assertTrue(self.parser.get_option("-n") is None) self.assertTrue(self.parser.get_option("--noisy") is None) self.assertFalse(self.parser.has_option("-v")) self.assertFalse(self.parser.has_option("--verbose")) self.assertFalse(self.parser.has_option("-n")) self.assertFalse(self.parser.has_option("--noisy")) self.assertTrue(self.parser.has_option("-q")) self.assertTrue(self.parser.has_option("--silent")) def test_remove_short_opt(self): self.parser.remove_option("-n") self.assertTrueremoved() def test_remove_long_opt(self): self.parser.remove_option("--verbose") self.assertTrueremoved() def test_remove_nonexistent(self): self.assertRaises(self.parser.remove_option, ('foo',), None, ValueError, "no such option 'foo'") @support.impl_detail('Relies on sys.getrefcount', cpython=True) def test_refleak(self): # If an OptionParser is carrying around a reference to a large # object, various cycles can prevent it from being GC'd in # a timely fashion. destroy() breaks the cycles to ensure stuff # can be cleaned up. big_thing = [42] refcount = sys.getrefcount(big_thing) parser = OptionParser() parser.add_option("-a", "--aaarggh") parser.big_thing = big_thing parser.destroy() #self.assertEqual(refcount, sys.getrefcount(big_thing)) del parser self.assertEqual(refcount, sys.getrefcount(big_thing)) class TestOptionValues(BaseTest): def setUp(self): pass def test_basics(self): values = Values() self.assertEqual(vars(values), {}) self.assertEqual(values, {}) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, "") dict = {"foo": "bar", "baz": 42} values = Values(defaults=dict) self.assertEqual(vars(values), dict) self.assertEqual(values, dict) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, {}) self.assertNotEqual(values, "") self.assertNotEqual(values, []) class TestTypeAliases(BaseTest): def setUp(self): self.parser = OptionParser() def test_str_aliases_string(self): self.parser.add_option("-s", type="str") self.assertEqual(self.parser.get_option("-s").type, "string") def test_type_object(self): self.parser.add_option("-s", type=str) self.assertEqual(self.parser.get_option("-s").type, "string") self.parser.add_option("-x", type=int) self.assertEqual(self.parser.get_option("-x").type, "int") # Custom type for testing processing of default values. _time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 } def _check_duration(option, opt, value): try: if value[-1].isdigit(): return int(value) else: return int(value[:-1]) * _time_units[value[-1]] except (ValueError, IndexError): raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) class DurationOption(Option): TYPES = Option.TYPES + ('duration',) TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) TYPE_CHECKER['duration'] = _check_duration class TestDefaultValues(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", default=True) self.parser.add_option("-q", "--quiet", dest='verbose') self.parser.add_option("-n", type="int", default=37) self.parser.add_option("-m", type="int") self.parser.add_option("-s", default="foo") self.parser.add_option("-t") self.parser.add_option("-u", default=None) self.expected = { 'verbose': True, 'n': 37, 'm': None, 's': "foo", 't': None, 'u': None } def test_basic_defaults(self): self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_post(self): self.parser.set_defaults(n=42, m=-100) self.expected.update({'n': 42, 'm': -100}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_pre(self): self.parser.set_defaults(x="barf", y="blah") self.parser.add_option("-x", default="frob") self.parser.add_option("-y") self.expected.update({'x': "frob", 'y': "blah"}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.remove_option("-y") self.parser.add_option("-y", default=None) self.expected.update({'y': None}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_process_default(self): self.parser.option_class = DurationOption self.parser.add_option("-d", type="duration", default=300) self.parser.add_option("-e", type="duration", default="6m") self.parser.set_defaults(n="42") self.expected.update({'d': 300, 'e': 360, 'n': 42}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.set_process_default_values(False) self.expected.update({'d': 300, 'e': "6m", 'n': "42"}) self.assertEqual(self.parser.get_default_values(), self.expected) class TestProgName(BaseTest): """ Test that %prog expands to the right thing in usage, version, and help strings. """ def assertUsage(self, parser, expected_usage): self.assertEqual(parser.get_usage(), expected_usage) def assertVersion(self, parser, expected_version): self.assertEqual(parser.get_version(), expected_version) def test_default_progname(self): # Make sure that program name taken from sys.argv[0] by default. save_argv = sys.argv[:] try: sys.argv[0] = os.path.join("foo", "bar", "baz.py") parser = OptionParser("%prog ...", version="%prog 1.2") expected_usage = "Usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "Options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") finally: sys.argv[:] = save_argv def test_custom_progname(self): parser = OptionParser(prog="thingy", version="%prog 0.1", usage="%prog arg arg") parser.remove_option("-h") parser.remove_option("--version") expected_usage = "Usage: thingy arg arg\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "thingy 0.1") self.assertHelp(parser, expected_usage + "\n") class TestExpandDefaults(BaseTest): def setUp(self): self.parser = OptionParser(prog="test") self.help_prefix = """\ Usage: test [options] Options: -h, --help show this help message and exit """ self.file_help = "read from FILE [default: %default]" self.expected_help_file = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: foo.txt]\n" self.expected_help_none = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: none]\n" def test_option_default(self): self.parser.add_option("-f", "--file", default="foo.txt", help=self.file_help) self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_1(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_default('file', "foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file="foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_no_default(self): self.parser.add_option("-f", "--file", help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_1(self): self.parser.add_option("-f", "--file", default=None, help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file=None) self.assertHelp(self.parser, self.expected_help_none) def test_float_default(self): self.parser.add_option( "-p", "--prob", help="blow up with probability PROB [default: %default]") self.parser.set_defaults(prob=0.43) expected_help = self.help_prefix + \ " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n" self.assertHelp(self.parser, expected_help) def test_alt_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from FILE [default: *DEFAULT*]") self.parser.formatter.default_tag = "*DEFAULT*" self.assertHelp(self.parser, self.expected_help_file) def test_no_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from %default file") self.parser.formatter.default_tag = None expected_help = self.help_prefix + \ " -f FILE, --file=FILE read from %default file\n" self.assertHelp(self.parser, expected_help) # -- Test parser.parse_args() ------------------------------------------ class TestStandard(BaseTest): def setUp(self): options = [make_option("-a", type="string"), make_option("-b", "--boo", type="int", dest='boo'), make_option("--foo", action="append")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def test_required_value(self): self.assertParseFail(["-a"], "-a option requires 1 argument") def test_invalid_integer(self): self.assertParseFail(["-b", "5x"], "option -b: invalid integer value: '5x'") def test_no_such_option(self): self.assertParseFail(["--boo13"], "no such option: --boo13") def test_long_invalid_integer(self): self.assertParseFail(["--boo=x5"], "option --boo: invalid integer value: 'x5'") def test_empty(self): self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, []) def test_shortopt_empty_longopt_append(self): self.assertParseOK(["-a", "", "--foo=blah", "--foo="], {'a': "", 'boo': None, 'foo': ["blah", ""]}, []) def test_long_option_append(self): self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"], {'a': None, 'boo': None, 'foo': ["bar", "", "x"]}, []) def test_option_argument_joined(self): self.assertParseOK(["-abc"], {'a': "bc", 'boo': None, 'foo': None}, []) def test_option_argument_split(self): self.assertParseOK(["-a", "34"], {'a': "34", 'boo': None, 'foo': None}, []) def test_option_argument_joined_integer(self): self.assertParseOK(["-b34"], {'a': None, 'boo': 34, 'foo': None}, []) def test_option_argument_split_negative_integer(self): self.assertParseOK(["-b", "-5"], {'a': None, 'boo': -5, 'foo': None}, []) def test_long_option_argument_joined(self): self.assertParseOK(["--boo=13"], {'a': None, 'boo': 13, 'foo': None}, []) def test_long_option_argument_split(self): self.assertParseOK(["--boo", "111"], {'a': None, 'boo': 111, 'foo': None}, []) def test_long_option_short_option(self): self.assertParseOK(["--foo=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_abbrev_long_option(self): self.assertParseOK(["--f=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_defaults(self): (options, args) = self.parser.parse_args([]) defaults = self.parser.get_default_values() self.assertEqual(vars(defaults), vars(options)) def test_ambiguous_option(self): self.parser.add_option("--foz", action="store", type="string", dest="foo") self.assertParseFail(["--f=bar"], "ambiguous option: --f (--foo, --foz?)") def test_short_and_long_option_split(self): self.assertParseOK(["-a", "xyz", "--foo", "bar"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_short_option_split_long_option_append(self): self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"], {'a': None, 'boo': 123, 'foo': ["bar", "baz"]}, []) def test_short_option_split_one_positional_arg(self): self.assertParseOK(["-a", "foo", "bar"], {'a': "foo", 'boo': None, 'foo': None}, ["bar"]) def test_short_option_consumes_separator(self): self.assertParseOK(["-a", "--", "foo", "bar"], {'a': "--", 'boo': None, 'foo': None}, ["foo", "bar"]) self.assertParseOK(["-a", "--", "--foo", "bar"], {'a': "--", 'boo': None, 'foo': ["bar"]}, []) def test_short_option_joined_and_separator(self): self.assertParseOK(["-ab", "--", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': None}, ["--foo", "bar"]), def test_hyphen_becomes_positional_arg(self): self.assertParseOK(["-ab", "-", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': ["bar"]}, ["-"]) def test_no_append_versus_append(self): self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"], {'a': None, 'boo': 5, 'foo': ["bar", "baz"]}, []) def test_option_consumes_optionlike_string(self): self.assertParseOK(["-a", "-b3"], {'a': "-b3", 'boo': None, 'foo': None}, []) def test_combined_single_invalid_option(self): self.parser.add_option("-t", action="store_true") self.assertParseFail(["-test"], "no such option: -e") class TestBool(BaseTest): def setUp(self): options = [make_option("-v", "--verbose", action="store_true", dest="verbose", default=''), make_option("-q", "--quiet", action="store_false", dest="verbose")] self.parser = OptionParser(option_list = options) def test_bool_default(self): self.assertParseOK([], {'verbose': ''}, []) def test_bool_false(self): (options, args) = self.assertParseOK(["-q"], {'verbose': 0}, []) self.assertTrue(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) self.assertTrue(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], {'verbose': 1}, []) class TestChoice(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-c", action="store", type="choice", dest="choice", choices=["one", "two", "three"]) def test_valid_choice(self): self.assertParseOK(["-c", "one", "xyz"], {'choice': 'one'}, ["xyz"]) def test_invalid_choice(self): self.assertParseFail(["-c", "four", "abc"], "option -c: invalid choice: 'four' " "(choose from 'one', 'two', 'three')") def test_add_choice_option(self): self.parser.add_option("-d", "--default", choices=["four", "five", "six"]) opt = self.parser.get_option("-d") self.assertEqual(opt.type, "choice") self.assertEqual(opt.action, "store") class TestCount(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.v_opt = make_option("-v", action="count", dest="verbose") self.parser.add_option(self.v_opt) self.parser.add_option("--verbose", type="int", dest="verbose") self.parser.add_option("-q", "--quiet", action="store_const", dest="verbose", const=0) def test_empty(self): self.assertParseOK([], {'verbose': None}, []) def test_count_one(self): self.assertParseOK(["-v"], {'verbose': 1}, []) def test_count_three(self): self.assertParseOK(["-vvv"], {'verbose': 3}, []) def test_count_three_apart(self): self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, []) def test_count_override_amount(self): self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, []) def test_count_override_quiet(self): self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, []) def test_count_overriding(self): self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], {'verbose': 1}, []) def test_count_interspersed_args(self): self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 1}, ["3"]) def test_count_no_interspersed_args(self): self.parser.disable_interspersed_args() self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 0}, ["3", "-v"]) def test_count_no_such_option(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_property.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_property.py
# Test case for property # more tests are in test_descr import sys import unittest from test import support class PropertyBase(Exception): pass class PropertyGet(PropertyBase): pass class PropertySet(PropertyBase): pass class PropertyDel(PropertyBase): pass class BaseClass(object): def __init__(self): self._spam = 5 @property def spam(self): """BaseClass.getter""" return self._spam @spam.setter def spam(self, value): self._spam = value @spam.deleter def spam(self): del self._spam class SubClass(BaseClass): @BaseClass.spam.getter def spam(self): """SubClass.getter""" raise PropertyGet(self._spam) @spam.setter def spam(self, value): raise PropertySet(self._spam) @spam.deleter def spam(self): raise PropertyDel(self._spam) class PropertyDocBase(object): _spam = 1 def _get_spam(self): return self._spam spam = property(_get_spam, doc="spam spam spam") class PropertyDocSub(PropertyDocBase): @PropertyDocBase.spam.getter def spam(self): """The decorator does not use this doc string""" return self._spam class PropertySubNewGetter(BaseClass): @BaseClass.spam.getter def spam(self): """new docstring""" return 5 class PropertyNewGetter(object): @property def spam(self): """original docstring""" return 1 @spam.getter def spam(self): """new docstring""" return 8 class PropertyTests(unittest.TestCase): def test_property_decorator_baseclass(self): # see #1620 base = BaseClass() self.assertEqual(base.spam, 5) self.assertEqual(base._spam, 5) base.spam = 10 self.assertEqual(base.spam, 10) self.assertEqual(base._spam, 10) delattr(base, "spam") self.assertTrue(not hasattr(base, "spam")) self.assertTrue(not hasattr(base, "_spam")) base.spam = 20 self.assertEqual(base.spam, 20) self.assertEqual(base._spam, 20) def test_property_decorator_subclass(self): # see #1620 sub = SubClass() self.assertRaises(PropertyGet, getattr, sub, "spam") self.assertRaises(PropertySet, setattr, sub, "spam", None) self.assertRaises(PropertyDel, delattr, sub, "spam") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_decorator_subclass_doc(self): sub = SubClass() self.assertEqual(sub.__class__.spam.__doc__, "SubClass.getter") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_decorator_baseclass_doc(self): base = BaseClass() self.assertEqual(base.__class__.spam.__doc__, "BaseClass.getter") def test_property_decorator_doc(self): base = PropertyDocBase() sub = PropertyDocSub() self.assertEqual(base.__class__.spam.__doc__, "spam spam spam") self.assertEqual(sub.__class__.spam.__doc__, "spam spam spam") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_getter_doc_override(self): newgettersub = PropertySubNewGetter() self.assertEqual(newgettersub.spam, 5) self.assertEqual(newgettersub.__class__.spam.__doc__, "new docstring") newgetter = PropertyNewGetter() self.assertEqual(newgetter.spam, 8) self.assertEqual(newgetter.__class__.spam.__doc__, "new docstring") def test_property___isabstractmethod__descriptor(self): for val in (True, False, [], [1], '', '1'): class C(object): def foo(self): pass foo.__isabstractmethod__ = val foo = property(foo) self.assertIs(C.foo.__isabstractmethod__, bool(val)) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __bool__(self): raise ValueError() __len__ = __bool__ with self.assertRaises(ValueError): class C(object): def foo(self): pass foo.__isabstractmethod__ = NotBool() foo = property(foo) C.foo.__isabstractmethod__ @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_builtin_doc_writable(self): p = property(doc='basic') self.assertEqual(p.__doc__, 'basic') p.__doc__ = 'extended' self.assertEqual(p.__doc__, 'extended') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_decorator_doc_writable(self): class PropertyWritableDoc(object): @property def spam(self): """Eggs""" return "eggs" sub = PropertyWritableDoc() self.assertEqual(sub.__class__.spam.__doc__, 'Eggs') sub.__class__.spam.__doc__ = 'Spam' self.assertEqual(sub.__class__.spam.__doc__, 'Spam') @support.refcount_test def test_refleaks_in___init__(self): gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') fake_prop = property('fget', 'fset', 'fdel', 'doc') refs_before = gettotalrefcount() for i in range(100): fake_prop.__init__('fget', 'fset', 'fdel', 'doc') self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) # Issue 5890: subclasses of property do not preserve method __doc__ strings class PropertySub(property): """This is a subclass of property""" class PropertySubSlots(property): """This is a subclass of property that defines __slots__""" __slots__ = () class PropertySubclassTests(unittest.TestCase): def test_slots_docstring_copy_exception(self): try: class Foo(object): @PropertySubSlots def spam(self): """Trying to copy this docstring will raise an exception""" return 1 except AttributeError: pass else: raise Exception("AttributeError not raised") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_docstring_copy(self): class Foo(object): @PropertySub def spam(self): """spam wrapped in property subclass""" return 1 self.assertEqual( Foo.spam.__doc__, "spam wrapped in property subclass") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_setter_copies_getter_docstring(self): class Foo(object): def __init__(self): self._spam = 1 @PropertySub def spam(self): """spam wrapped in property subclass""" return self._spam @spam.setter def spam(self, value): """this docstring is ignored""" self._spam = value foo = Foo() self.assertEqual(foo.spam, 1) foo.spam = 2 self.assertEqual(foo.spam, 2) self.assertEqual( Foo.spam.__doc__, "spam wrapped in property subclass") class FooSub(Foo): @Foo.spam.setter def spam(self, value): """another ignored docstring""" self._spam = 'eggs' foosub = FooSub() self.assertEqual(foosub.spam, 1) foosub.spam = 7 self.assertEqual(foosub.spam, 'eggs') self.assertEqual( FooSub.spam.__doc__, "spam wrapped in property subclass") @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_property_new_getter_new_docstring(self): class Foo(object): @PropertySub def spam(self): """a docstring""" return 1 @spam.getter def spam(self): """a new docstring""" return 2 self.assertEqual(Foo.spam.__doc__, "a new docstring") class FooBase(object): @PropertySub def spam(self): """a docstring""" return 1 class Foo2(FooBase): @FooBase.spam.getter def spam(self): """a new docstring""" return 2 self.assertEqual(Foo.spam.__doc__, "a new docstring") 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_nis.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_nis.py
from test import support import unittest # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byname") except ValueError: pass done = 0 for nismap in maps: mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break 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_rlcompleter.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_rlcompleter.py
import unittest from unittest.mock import patch import builtins import rlcompleter class CompleteMe: """ Trivial class used in testing rlcompleter.Completer. """ spam = 1 _ham = 2 class TestRlcompleter(unittest.TestCase): def setUp(self): self.stdcompleter = rlcompleter.Completer() self.completer = rlcompleter.Completer(dict(spam=int, egg=str, CompleteMe=CompleteMe)) # forces stdcompleter to bind builtins namespace self.stdcompleter.complete('', 0) def test_namespace(self): class A(dict): pass class B(list): pass self.assertTrue(self.stdcompleter.use_main_ns) self.assertFalse(self.completer.use_main_ns) self.assertFalse(rlcompleter.Completer(A()).use_main_ns) self.assertRaises(TypeError, rlcompleter.Completer, B((1,))) def test_global_matches(self): # test with builtins namespace self.assertEqual(sorted(self.stdcompleter.global_matches('di')), [x+'(' for x in dir(builtins) if x.startswith('di')]) self.assertEqual(sorted(self.stdcompleter.global_matches('st')), [x+'(' for x in dir(builtins) if x.startswith('st')]) self.assertEqual(self.stdcompleter.global_matches('akaksajadhak'), []) # test with a customized namespace self.assertEqual(self.completer.global_matches('CompleteM'), ['CompleteMe(']) self.assertEqual(self.completer.global_matches('eg'), ['egg(']) # XXX: see issue5256 self.assertEqual(self.completer.global_matches('CompleteM'), ['CompleteMe(']) def test_attr_matches(self): # test with builtins namespace self.assertEqual(self.stdcompleter.attr_matches('str.s'), ['str.{}('.format(x) for x in dir(str) if x.startswith('s')]) self.assertEqual(self.stdcompleter.attr_matches('tuple.foospamegg'), []) expected = sorted({'None.%s%s' % (x, '(' if x != '__doc__' else '') for x in dir(None)}) self.assertEqual(self.stdcompleter.attr_matches('None.'), expected) self.assertEqual(self.stdcompleter.attr_matches('None._'), expected) self.assertEqual(self.stdcompleter.attr_matches('None.__'), expected) # test with a customized namespace self.assertEqual(self.completer.attr_matches('CompleteMe.sp'), ['CompleteMe.spam']) self.assertEqual(self.completer.attr_matches('Completeme.egg'), []) self.assertEqual(self.completer.attr_matches('CompleteMe.'), ['CompleteMe.mro(', 'CompleteMe.spam']) self.assertEqual(self.completer.attr_matches('CompleteMe._'), ['CompleteMe._ham']) matches = self.completer.attr_matches('CompleteMe.__') for x in matches: self.assertTrue(x.startswith('CompleteMe.__'), x) self.assertIn('CompleteMe.__name__', matches) self.assertIn('CompleteMe.__new__(', matches) with patch.object(CompleteMe, "me", CompleteMe, create=True): self.assertEqual(self.completer.attr_matches('CompleteMe.me.me.sp'), ['CompleteMe.me.me.spam']) self.assertEqual(self.completer.attr_matches('egg.s'), ['egg.{}('.format(x) for x in dir(str) if x.startswith('s')]) def test_excessive_getattr(self): # Ensure getattr() is invoked no more than once per attribute class Foo: calls = 0 @property def bar(self): self.calls += 1 return None f = Foo() completer = rlcompleter.Completer(dict(f=f)) self.assertEqual(completer.complete('f.b', 0), 'f.bar') self.assertEqual(f.calls, 1) def test_uncreated_attr(self): # Attributes like properties and slots should be completed even when # they haven't been created on an instance class Foo: __slots__ = ("bar",) completer = rlcompleter.Completer(dict(f=Foo())) self.assertEqual(completer.complete('f.', 0), 'f.bar') @unittest.mock.patch('rlcompleter._readline_available', False) def test_complete(self): completer = rlcompleter.Completer() self.assertEqual(completer.complete('', 0), '\t') self.assertEqual(completer.complete('a', 0), 'and ') self.assertEqual(completer.complete('a', 1), 'as ') self.assertEqual(completer.complete('as', 2), 'assert ') self.assertEqual(completer.complete('an', 0), 'and ') self.assertEqual(completer.complete('pa', 0), 'pass') self.assertEqual(completer.complete('Fa', 0), 'False') self.assertEqual(completer.complete('el', 0), 'elif ') self.assertEqual(completer.complete('el', 1), 'else') self.assertEqual(completer.complete('tr', 0), 'try:') def test_duplicate_globals(self): namespace = { 'False': None, # Keyword vs builtin vs namespace 'assert': None, # Keyword vs namespace 'try': lambda: None, # Keyword vs callable 'memoryview': None, # Callable builtin vs non-callable 'Ellipsis': lambda: None, # Non-callable builtin vs callable } completer = rlcompleter.Completer(namespace) self.assertEqual(completer.complete('False', 0), 'False') self.assertIsNone(completer.complete('False', 1)) # No duplicates # Space or colon added due to being a reserved keyword self.assertEqual(completer.complete('assert', 0), 'assert ') self.assertIsNone(completer.complete('assert', 1)) self.assertEqual(completer.complete('try', 0), 'try:') self.assertIsNone(completer.complete('try', 1)) # No opening bracket "(" because we overrode the built-in class self.assertEqual(completer.complete('memoryview', 0), 'memoryview') self.assertIsNone(completer.complete('memoryview', 1)) self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(') self.assertIsNone(completer.complete('Ellipsis', 1)) 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_file_eintr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_file_eintr.py
# Written to test interrupted system calls interfering with our many buffered # IO implementations. http://bugs.python.org/issue12268 # # It was suggested that this code could be merged into test_io and the tests # made to work using the same method as the existing signal tests in test_io. # I was unable to get single process tests using alarm or setitimer that way # to reproduce the EINTR problems. This process based test suite reproduces # the problems prior to the issue12268 patch reliably on Linux and OSX. # - gregory.p.smith import os import select import signal import subprocess import sys import time import unittest # Test import all of the things we're about to try testing up front. import _io import _pyio @unittest.skipUnless(os.name == 'posix', 'tests requires a posix system.') class TestFileIOSignalInterrupt: def setUp(self): self._process = None def tearDown(self): if self._process and self._process.poll() is None: try: self._process.kill() except OSError: pass def _generate_infile_setup_code(self): """Returns the infile = ... line of code for the reader process. subclasseses should override this to test different IO objects. """ return ('import %s as io ;' 'infile = io.FileIO(sys.stdin.fileno(), "rb")' % self.modname) def fail_with_process_info(self, why, stdout=b'', stderr=b'', communicate=True): """A common way to cleanup and fail with useful debug output. Kills the process if it is still running, collects remaining output and fails the test with an error message including the output. Args: why: Text to go after "Error from IO process" in the message. stdout, stderr: standard output and error from the process so far to include in the error message. communicate: bool, when True we call communicate() on the process after killing it to gather additional output. """ if self._process.poll() is None: time.sleep(0.1) # give it time to finish printing the error. try: self._process.terminate() # Ensure it dies. except OSError: pass if communicate: stdout_end, stderr_end = self._process.communicate() stdout += stdout_end stderr += stderr_end self.fail('Error from IO process %s:\nSTDOUT:\n%sSTDERR:\n%s\n' % (why, stdout.decode(), stderr.decode())) def _test_reading(self, data_to_write, read_and_verify_code): """Generic buffered read method test harness to validate EINTR behavior. Also validates that Python signal handlers are run during the read. Args: data_to_write: String to write to the child process for reading before sending it a signal, confirming the signal was handled, writing a final newline and closing the infile pipe. read_and_verify_code: Single "line" of code to read from a file object named 'infile' and validate the result. This will be executed as part of a python subprocess fed data_to_write. """ infile_setup_code = self._generate_infile_setup_code() # Total pipe IO in this function is smaller than the minimum posix OS # pipe buffer size of 512 bytes. No writer should block. assert len(data_to_write) < 512, 'data_to_write must fit in pipe buf.' # Start a subprocess to call our read method while handling a signal. self._process = subprocess.Popen( [sys.executable, '-u', '-c', 'import signal, sys ;' 'signal.signal(signal.SIGINT, ' 'lambda s, f: sys.stderr.write("$\\n")) ;' + infile_setup_code + ' ;' + 'sys.stderr.write("Worm Sign!\\n") ;' + read_and_verify_code + ' ;' + 'infile.close()' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the signal handler to be installed. worm_sign = self._process.stderr.read(len(b'Worm Sign!\n')) if worm_sign != b'Worm Sign!\n': # See also, Dune by Frank Herbert. self.fail_with_process_info('while awaiting a sign', stderr=worm_sign) self._process.stdin.write(data_to_write) signals_sent = 0 rlist = [] # We don't know when the read_and_verify_code in our child is actually # executing within the read system call we want to interrupt. This # loop waits for a bit before sending the first signal to increase # the likelihood of that. Implementations without correct EINTR # and signal handling usually fail this test. while not rlist: rlist, _, _ = select.select([self._process.stderr], (), (), 0.05) self._process.send_signal(signal.SIGINT) signals_sent += 1 if signals_sent > 200: self._process.kill() self.fail('reader process failed to handle our signals.') # This assumes anything unexpected that writes to stderr will also # write a newline. That is true of the traceback printing code. signal_line = self._process.stderr.readline() if signal_line != b'$\n': self.fail_with_process_info('while awaiting signal', stderr=signal_line) # We append a newline to our input so that a readline call can # end on its own before the EOF is seen and so that we're testing # the read call that was interrupted by a signal before the end of # the data stream has been reached. stdout, stderr = self._process.communicate(input=b'\n') if self._process.returncode: self.fail_with_process_info( 'exited rc=%d' % self._process.returncode, stdout, stderr, communicate=False) # PASS! # String format for the read_and_verify_code used by read methods. _READING_CODE_TEMPLATE = ( 'got = infile.{read_method_name}() ;' 'expected = {expected!r} ;' 'assert got == expected, (' '"{read_method_name} returned wrong data.\\n"' '"got data %r\\nexpected %r" % (got, expected))' ) def test_readline(self): """readline() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='readline', expected=b'hello, world!\n')) def test_readlines(self): """readlines() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='readlines', expected=[b'hello\n', b'world!\n'])) def test_readall(self): """readall() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='readall', expected=b'hello\nworld!\n')) # read() is the same thing as readall(). self._test_reading( data_to_write=b'hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='read', expected=b'hello\nworld!\n')) class CTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase): modname = '_io' class PyTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase): modname = '_pyio' class TestBufferedIOSignalInterrupt(TestFileIOSignalInterrupt): def _generate_infile_setup_code(self): """Returns the infile = ... line of code to make a BufferedReader.""" return ('import %s as io ;infile = io.open(sys.stdin.fileno(), "rb") ;' 'assert isinstance(infile, io.BufferedReader)' % self.modname) def test_readall(self): """BufferedReader.read() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='read', expected=b'hello\nworld!\n')) class CTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase): modname = '_io' class PyTestBufferedIOSignalInterrupt(TestBufferedIOSignalInterrupt, unittest.TestCase): modname = '_pyio' class TestTextIOSignalInterrupt(TestFileIOSignalInterrupt): def _generate_infile_setup_code(self): """Returns the infile = ... line of code to make a TextIOWrapper.""" return ('import %s as io ;' 'infile = io.open(sys.stdin.fileno(), "rt", newline=None) ;' 'assert isinstance(infile, io.TextIOWrapper)' % self.modname) def test_readline(self): """readline() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='readline', expected='hello, world!\n')) def test_readlines(self): """readlines() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello\r\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='readlines', expected=['hello\n', 'world!\n'])) def test_readall(self): """read() must handle signals and not lose data.""" self._test_reading( data_to_write=b'hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format( read_method_name='read', expected="hello\nworld!\n")) class CTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase): modname = '_io' class PyTestTextIOSignalInterrupt(TestTextIOSignalInterrupt, unittest.TestCase): modname = '_pyio' 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_pyclbr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pyclbr.py
''' Test cases for pyclbr.py Nick Mathewson ''' import os import sys from textwrap import dedent from types import FunctionType, MethodType, BuiltinFunctionType import pyclbr from unittest import TestCase, main as unittest_main from test import support from functools import partial StaticMethodType = type(staticmethod(lambda: None)) ClassMethodType = type(classmethod(lambda c: None)) # Here we test the python class browser code. # # The main function in this suite, 'testModule', compares the output # of pyclbr with the introspected members of a module. Because pyclbr # is imperfect (as designed), testModule is called with a set of # members to ignore. class PyclbrTest(TestCase): def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' missing = (set(l1) ^ set(l2)) - set(ignore) if missing: print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr) self.fail("%r missing" % missing.pop()) def assertHasattr(self, obj, attr, ignore): ''' succeed iff hasattr(obj,attr) or attr in ignore. ''' if attr in ignore: return if not hasattr(obj, attr): print("???", attr) self.assertTrue(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) def assertHaskey(self, obj, key, ignore): ''' succeed iff key in obj or key in ignore. ''' if key in ignore: return if key not in obj: print("***",key, file=sys.stderr) self.assertIn(key, obj) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' if a not in ignore and b not in ignore: self.assertEqual(a, b) def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' ignore = set(ignore) | set(['object']) if module is None: # Import it. # ('<silly>' is to work around an API silliness in __import__) module = __import__(moduleName, globals(), {}, ['<silly>']) dict = pyclbr.readmodule_ex(moduleName) def ismethod(oclass, obj, name): classdict = oclass.__dict__ if isinstance(obj, MethodType): # could be a classmethod if (not isinstance(classdict[name], ClassMethodType) or obj.__self__ is not oclass): return False elif not isinstance(obj, FunctionType): return False objname = obj.__name__ if objname.startswith("__") and not objname.endswith("__"): objname = "_%s%s" % (oclass.__name__, objname) return objname == name # Make sure the toplevel functions and classes are the same. for name, value in dict.items(): if name in ignore: continue self.assertHasattr(module, name, ignore) py_item = getattr(module, name) if isinstance(value, pyclbr.Function): self.assertIsInstance(py_item, (FunctionType, BuiltinFunctionType)) if py_item.__module__ != moduleName: continue # skip functions that came from somewhere else self.assertEqual(py_item.__module__, value.module) else: self.assertIsInstance(py_item, type) if py_item.__module__ != moduleName: continue # skip classes that came from somewhere else real_bases = [base.__name__ for base in py_item.__bases__] pyclbr_bases = [ getattr(base, 'name', base) for base in value.super ] try: self.assertListEq(real_bases, pyclbr_bases, ignore) except: print("class=%s" % py_item, file=sys.stderr) raise actualMethods = [] for m in py_item.__dict__.keys(): if ismethod(py_item, getattr(py_item, m), m): actualMethods.append(m) foundMethods = [] for m in value.methods.keys(): if m[:2] == '__' and m[-2:] != '__': foundMethods.append('_'+name+m) else: foundMethods.append(m) try: self.assertListEq(foundMethods, actualMethods, ignore) self.assertEqual(py_item.__module__, value.module) self.assertEqualsOrIgnored(py_item.__name__, value.name, ignore) # can't check file or lineno except: print("class=%s" % py_item, file=sys.stderr) raise # Now check for missing stuff. def defined_in(item, module): if isinstance(item, type): return item.__module__ == module.__name__ if isinstance(item, FunctionType): return item.__globals__ is module.__dict__ return False for name in dir(module): item = getattr(module, name) if isinstance(item, (type, FunctionType)): if defined_in(item, module): self.assertHaskey(dict, name, ignore) def test_easy(self): self.checkModule('pyclbr') self.checkModule('ast') self.checkModule('doctest', ignore=("TestResults", "_SpoofOut", "DocTestCase", '_DocTestSuite')) self.checkModule('difflib', ignore=("Match",)) def test_decorators(self): # XXX: See comment in pyclbr_input.py for a test that would fail # if it were not commented out. # self.checkModule('test.pyclbr_input', ignore=['om']) def test_nested(self): mb = pyclbr # Set arguments for descriptor creation and _creat_tree call. m, p, f, t, i = 'test', '', 'test.py', {}, None source = dedent("""\ def f0: def f1(a,b,c): def f2(a=1, b=2, c=3): pass return f1(a,b,d) class c1: pass class C0: "Test class." def F1(): "Method." return 'return' class C1(): class C2: "Class nested within nested class." def F3(): return 1+1 """) actual = mb._create_tree(m, p, f, source, t, i) # Create descriptors, linked together, and expected dict. f0 = mb.Function(m, 'f0', f, 1) f1 = mb._nest_function(f0, 'f1', 2) f2 = mb._nest_function(f1, 'f2', 3) c1 = mb._nest_class(f0, 'c1', 5) C0 = mb.Class(m, 'C0', None, f, 6) F1 = mb._nest_function(C0, 'F1', 8) C1 = mb._nest_class(C0, 'C1', 11) C2 = mb._nest_class(C1, 'C2', 12) F3 = mb._nest_function(C2, 'F3', 14) expected = {'f0':f0, 'C0':C0} def compare(parent1, children1, parent2, children2): """Return equality of tree pairs. Each parent,children pair define a tree. The parents are assumed equal. Comparing the children dictionaries as such does not work due to comparison by identity and double linkage. We separate comparing string and number attributes from comparing the children of input children. """ self.assertEqual(children1.keys(), children2.keys()) for ob in children1.values(): self.assertIs(ob.parent, parent1) for ob in children2.values(): self.assertIs(ob.parent, parent2) for key in children1.keys(): o1, o2 = children1[key], children2[key] t1 = type(o1), o1.name, o1.file, o1.module, o1.lineno t2 = type(o2), o2.name, o2.file, o2.module, o2.lineno self.assertEqual(t1, t2) if type(o1) is mb.Class: self.assertEqual(o1.methods, o2.methods) # Skip superclasses for now as not part of example compare(o1, o1.children, o2, o2.children) compare(None, actual, None, expected) def test_others(self): cm = self.checkModule # These were once about the 10 longest modules cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator cm('cgi', ignore=('log',)) # set with = in module cm('pickle', ignore=('partial',)) # TODO(briancurtin): openfp is deprecated as of 3.7. # Update this once it has been removed. cm('aifc', ignore=('openfp', '_aifc_params')) # set with = in module cm('sre_parse', ignore=('dump', 'groups', 'pos')) # from sre_constants import *; property cm('pdb') cm('pydoc', ignore=('input', 'output',)) # properties # Tests for modules inside packages cm('email.parser') cm('test.test_pyclbr') def test_issue_14798(self): # test ImportError is raised when the first part of a dotted name is # not a package self.assertRaises(ImportError, pyclbr.readmodule_ex, 'asyncore.foo') 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_timeout.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_timeout.py
"""Unit tests for socket timeout feature.""" import functools import unittest from test import support # This requires the 'network' resource as given on the regrtest command line. skip_expected = not support.is_resource_enabled('network') import time import errno import socket @functools.lru_cache() def resolve_address(host, port): """Resolve an (host, port) to an address. We must perform name resolution before timeout tests, otherwise it will be performed by connect(). """ with support.transient_internet(host): return socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)[0][4] class CreationTestCase(unittest.TestCase): """Test case for socket.gettimeout() and socket.settimeout()""" def setUp(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def tearDown(self): self.sock.close() def testObjectCreation(self): # Test Socket creation self.assertEqual(self.sock.gettimeout(), None, "timeout not disabled by default") def testFloatReturnValue(self): # Test return value of gettimeout() self.sock.settimeout(7.345) self.assertEqual(self.sock.gettimeout(), 7.345) self.sock.settimeout(3) self.assertEqual(self.sock.gettimeout(), 3) self.sock.settimeout(None) self.assertEqual(self.sock.gettimeout(), None) def testReturnType(self): # Test return type of gettimeout() self.sock.settimeout(1) self.assertEqual(type(self.sock.gettimeout()), type(1.0)) self.sock.settimeout(3.9) self.assertEqual(type(self.sock.gettimeout()), type(1.0)) def testTypeCheck(self): # Test type checking by settimeout() self.sock.settimeout(0) self.sock.settimeout(0) self.sock.settimeout(0.0) self.sock.settimeout(None) self.assertRaises(TypeError, self.sock.settimeout, "") self.assertRaises(TypeError, self.sock.settimeout, "") self.assertRaises(TypeError, self.sock.settimeout, ()) self.assertRaises(TypeError, self.sock.settimeout, []) self.assertRaises(TypeError, self.sock.settimeout, {}) self.assertRaises(TypeError, self.sock.settimeout, 0j) def testRangeCheck(self): # Test range checking by settimeout() self.assertRaises(ValueError, self.sock.settimeout, -1) self.assertRaises(ValueError, self.sock.settimeout, -1) self.assertRaises(ValueError, self.sock.settimeout, -1.0) def testTimeoutThenBlocking(self): # Test settimeout() followed by setblocking() self.sock.settimeout(10) self.sock.setblocking(1) self.assertEqual(self.sock.gettimeout(), None) self.sock.setblocking(0) self.assertEqual(self.sock.gettimeout(), 0.0) self.sock.settimeout(10) self.sock.setblocking(0) self.assertEqual(self.sock.gettimeout(), 0.0) self.sock.setblocking(1) self.assertEqual(self.sock.gettimeout(), None) def testBlockingThenTimeout(self): # Test setblocking() followed by settimeout() self.sock.setblocking(0) self.sock.settimeout(1) self.assertEqual(self.sock.gettimeout(), 1) self.sock.setblocking(1) self.sock.settimeout(1) self.assertEqual(self.sock.gettimeout(), 1) class TimeoutTestCase(unittest.TestCase): # There are a number of tests here trying to make sure that an operation # doesn't take too much longer than expected. But competing machine # activity makes it inevitable that such tests will fail at times. # When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K # and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real # solution. fuzz = 2.0 localhost = support.HOST def setUp(self): raise NotImplementedError() tearDown = setUp def _sock_operation(self, count, timeout, method, *args): """ Test the specified socket method. The method is run at most `count` times and must raise a socket.timeout within `timeout` + self.fuzz seconds. """ self.sock.settimeout(timeout) method = getattr(self.sock, method) for i in range(count): t1 = time.monotonic() try: method(*args) except socket.timeout as e: delta = time.monotonic() - t1 break else: self.fail('socket.timeout was not raised') # These checks should account for timing unprecision self.assertLess(delta, timeout + self.fuzz) self.assertGreater(delta, timeout - 1.0) class TCPTimeoutTestCase(TimeoutTestCase): """TCP test case for socket.socket() timeout functions""" def setUp(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.addr_remote = resolve_address('www.python.org.', 80) def tearDown(self): self.sock.close() @unittest.skipIf(True, 'need to replace these hosts; see bpo-35518') def testConnectTimeout(self): # Testing connect timeout is tricky: we need to have IP connectivity # to a host that silently drops our packets. We can't simulate this # from Python because it's a function of the underlying TCP/IP stack. # So, the following Snakebite host has been defined: blackhole = resolve_address('blackhole.snakebite.net', 56666) # Blackhole has been configured to silently drop any incoming packets. # No RSTs (for TCP) or ICMP UNREACH (for UDP/ICMP) will be sent back # to hosts that attempt to connect to this address: which is exactly # what we need to confidently test connect timeout. # However, we want to prevent false positives. It's not unreasonable # to expect certain hosts may not be able to reach the blackhole, due # to firewalling or general network configuration. In order to improve # our confidence in testing the blackhole, a corresponding 'whitehole' # has also been set up using one port higher: whitehole = resolve_address('whitehole.snakebite.net', 56667) # This address has been configured to immediately drop any incoming # packets as well, but it does it respectfully with regards to the # incoming protocol. RSTs are sent for TCP packets, and ICMP UNREACH # is sent for UDP/ICMP packets. This means our attempts to connect to # it should be met immediately with ECONNREFUSED. The test case has # been structured around this premise: if we get an ECONNREFUSED from # the whitehole, we proceed with testing connect timeout against the # blackhole. If we don't, we skip the test (with a message about not # getting the required RST from the whitehole within the required # timeframe). # For the records, the whitehole/blackhole configuration has been set # up using the 'pf' firewall (available on BSDs), using the following: # # ext_if="bge0" # # blackhole_ip="35.8.247.6" # whitehole_ip="35.8.247.6" # blackhole_port="56666" # whitehole_port="56667" # # block return in log quick on $ext_if proto { tcp udp } \ # from any to $whitehole_ip port $whitehole_port # block drop in log quick on $ext_if proto { tcp udp } \ # from any to $blackhole_ip port $blackhole_port # skip = True sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Use a timeout of 3 seconds. Why 3? Because it's more than 1, and # less than 5. i.e. no particular reason. Feel free to tweak it if # you feel a different value would be more appropriate. timeout = 3 sock.settimeout(timeout) try: sock.connect((whitehole)) except socket.timeout: pass except OSError as err: if err.errno == errno.ECONNREFUSED: skip = False finally: sock.close() del sock if skip: self.skipTest( "We didn't receive a connection reset (RST) packet from " "{}:{} within {} seconds, so we're unable to test connect " "timeout against the corresponding {}:{} (which is " "configured to silently drop packets)." .format( whitehole[0], whitehole[1], timeout, blackhole[0], blackhole[1], ) ) # All that hard work just to test if connect times out in 0.001s ;-) self.addr_remote = blackhole with support.transient_internet(self.addr_remote[0]): self._sock_operation(1, 0.001, 'connect', self.addr_remote) def testRecvTimeout(self): # Test recv() timeout with support.transient_internet(self.addr_remote[0]): self.sock.connect(self.addr_remote) self._sock_operation(1, 1.5, 'recv', 1024) def testAcceptTimeout(self): # Test accept() timeout support.bind_port(self.sock, self.localhost) self.sock.listen() self._sock_operation(1, 1.5, 'accept') def testSend(self): # Test send() timeout with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv: support.bind_port(serv, self.localhost) serv.listen() self.sock.connect(serv.getsockname()) # Send a lot of data in order to bypass buffering in the TCP stack. self._sock_operation(100, 1.5, 'send', b"X" * 200000) def testSendto(self): # Test sendto() timeout with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv: support.bind_port(serv, self.localhost) serv.listen() self.sock.connect(serv.getsockname()) # The address argument is ignored since we already connected. self._sock_operation(100, 1.5, 'sendto', b"X" * 200000, serv.getsockname()) def testSendall(self): # Test sendall() timeout with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv: support.bind_port(serv, self.localhost) serv.listen() self.sock.connect(serv.getsockname()) # Send a lot of data in order to bypass buffering in the TCP stack. self._sock_operation(100, 1.5, 'sendall', b"X" * 200000) class UDPTimeoutTestCase(TimeoutTestCase): """UDP test case for socket.socket() timeout functions""" def setUp(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def tearDown(self): self.sock.close() def testRecvfromTimeout(self): # Test recvfrom() timeout # Prevent "Address already in use" socket exceptions support.bind_port(self.sock, self.localhost) self._sock_operation(1, 1.5, 'recvfrom', 1024) def test_main(): support.requires('network') support.run_unittest( CreationTestCase, TCPTimeoutTestCase, UDPTimeoutTestCase, ) 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_codecencodings_jp.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_jp.py
# # test_codecencodings_jp.py # Codec encoding tests for Japanese encodings. # from test import multibytecodec_support import unittest class Test_CP932(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'cp932' tstring = multibytecodec_support.load_teststring('shift_jis') codectests = ( # invalid bytes (b"abc\x81\x00\x81\x00\x82\x84", "strict", None), (b"abc\xf8", "strict", None), (b"abc\x81\x00\x82\x84", "replace", "abc\ufffd\x00\uff44"), (b"abc\x81\x00\x82\x84\x88", "replace", "abc\ufffd\x00\uff44\ufffd"), (b"abc\x81\x00\x82\x84", "ignore", "abc\x00\uff44"), (b"ab\xEBxy", "replace", "ab\uFFFDxy"), (b"ab\xF0\x39xy", "replace", "ab\uFFFD9xy"), (b"ab\xEA\xF0xy", "replace", 'ab\ufffd\ue038y'), # sjis vs cp932 (b"\\\x7e", "replace", "\\\x7e"), (b"\x81\x5f\x81\x61\x81\x7c", "replace", "\uff3c\u2225\uff0d"), ) euc_commontests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\u7956"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u7956\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\u7956"), (b"abc\xc8", "strict", None), (b"abc\x8f\x83\x83", "replace", "abc\ufffd\ufffd\ufffd"), (b"\x82\xFCxy", "replace", "\ufffd\ufffdxy"), (b"\xc1\x64", "strict", None), (b"\xa1\xc0", "strict", "\uff3c"), (b"\xa1\xc0\\", "strict", "\uff3c\\"), (b"\x8eXY", "replace", "\ufffdXY"), ) class Test_EUC_JIS_2004(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'euc_jis_2004' tstring = multibytecodec_support.load_teststring('euc_jisx0213') codectests = euc_commontests xmlcharnametest = ( "\xab\u211c\xbb = \u2329\u1234\u232a", b"\xa9\xa8&real;\xa9\xb2 = &lang;&#4660;&rang;" ) class Test_EUC_JISX0213(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'euc_jisx0213' tstring = multibytecodec_support.load_teststring('euc_jisx0213') codectests = euc_commontests xmlcharnametest = ( "\xab\u211c\xbb = \u2329\u1234\u232a", b"\xa9\xa8&real;\xa9\xb2 = &lang;&#4660;&rang;" ) class Test_EUC_JP_COMPAT(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'euc_jp' tstring = multibytecodec_support.load_teststring('euc_jp') codectests = euc_commontests + ( ("\xa5", "strict", b"\x5c"), ("\u203e", "strict", b"\x7e"), ) shiftjis_commonenctests = ( (b"abc\x80\x80\x82\x84", "strict", None), (b"abc\xf8", "strict", None), (b"abc\x80\x80\x82\x84def", "ignore", "abc\uff44def"), ) class Test_SJIS_COMPAT(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'shift_jis' tstring = multibytecodec_support.load_teststring('shift_jis') codectests = shiftjis_commonenctests + ( (b"abc\x80\x80\x82\x84", "replace", "abc\ufffd\ufffd\uff44"), (b"abc\x80\x80\x82\x84\x88", "replace", "abc\ufffd\ufffd\uff44\ufffd"), (b"\\\x7e", "strict", "\\\x7e"), (b"\x81\x5f\x81\x61\x81\x7c", "strict", "\uff3c\u2016\u2212"), (b"abc\x81\x39", "replace", "abc\ufffd9"), (b"abc\xEA\xFC", "replace", "abc\ufffd\ufffd"), (b"abc\xFF\x58", "replace", "abc\ufffdX"), ) class Test_SJIS_2004(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'shift_jis_2004' tstring = multibytecodec_support.load_teststring('shift_jis') codectests = shiftjis_commonenctests + ( (b"\\\x7e", "strict", "\xa5\u203e"), (b"\x81\x5f\x81\x61\x81\x7c", "strict", "\\\u2016\u2212"), (b"abc\xEA\xFC", "strict", "abc\u64bf"), (b"\x81\x39xy", "replace", "\ufffd9xy"), (b"\xFF\x58xy", "replace", "\ufffdXxy"), (b"\x80\x80\x82\x84xy", "replace", "\ufffd\ufffd\uff44xy"), (b"\x80\x80\x82\x84\x88xy", "replace", "\ufffd\ufffd\uff44\u5864y"), (b"\xFC\xFBxy", "replace", '\ufffd\u95b4y'), ) xmlcharnametest = ( "\xab\u211c\xbb = \u2329\u1234\u232a", b"\x85G&real;\x85Q = &lang;&#4660;&rang;" ) class Test_SJISX0213(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'shift_jisx0213' tstring = multibytecodec_support.load_teststring('shift_jisx0213') codectests = shiftjis_commonenctests + ( (b"abc\x80\x80\x82\x84", "replace", "abc\ufffd\ufffd\uff44"), (b"abc\x80\x80\x82\x84\x88", "replace", "abc\ufffd\ufffd\uff44\ufffd"), # sjis vs cp932 (b"\\\x7e", "replace", "\xa5\u203e"), (b"\x81\x5f\x81\x61\x81\x7c", "replace", "\x5c\u2016\u2212"), ) xmlcharnametest = ( "\xab\u211c\xbb = \u2329\u1234\u232a", b"\x85G&real;\x85Q = &lang;&#4660;&rang;" ) 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/sample_doctest_no_doctests.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/sample_doctest_no_doctests.py
"""This is a sample module used for testing doctest. This module is for testing how doctest handles a module with docstrings but no doctest examples. """ class Foo(object): """A docstring with no doctest examples. """ def __init__(self): pass
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_doctest.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
""" Test script for doctest. """ from test import support import doctest import functools import os import sys import importlib import unittest import tempfile # NOTE: There are some additional tests relating to interaction with # zipimport in the test_zipimport_support test module. ###################################################################### ## Sample Objects (used by test cases) ###################################################################### def sample_func(v): """ Blah blah >>> print(sample_func(22)) 44 Yee ha! """ return v+v class SampleClass: """ >>> print(1) 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: >>> ... Multiline example: >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() ... print(' ', sc.get(), sep='', end='') 6 12 24 48 96 192 384 768 1536 3072 """ def __init__(self, val): """ >>> print(SampleClass(12).get()) 12 """ self.val = val def double(self): """ >>> print(SampleClass(12).double().get()) 24 """ return SampleClass(self.val + self.val) def get(self): """ >>> print(SampleClass(-5).get()) -5 """ return self.val def a_staticmethod(v): """ >>> print(SampleClass.a_staticmethod(10)) 11 """ return v+1 a_staticmethod = staticmethod(a_staticmethod) def a_classmethod(cls, v): """ >>> print(SampleClass.a_classmethod(10)) 12 >>> print(SampleClass(0).a_classmethod(10)) 12 """ return v+2 a_classmethod = classmethod(a_classmethod) a_property = property(get, doc=""" >>> print(SampleClass(22).a_property) 22 """) class NestedClass: """ >>> x = SampleClass.NestedClass(5) >>> y = x.square() >>> print(y.get()) 25 """ def __init__(self, val=0): """ >>> print(SampleClass.NestedClass().get()) 0 """ self.val = val def square(self): return SampleClass.NestedClass(self.val*self.val) def get(self): return self.val class SampleNewStyleClass(object): r""" >>> print('1\n2\n3') 1 2 3 """ def __init__(self, val): """ >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ >>> print(SampleNewStyleClass(12).double().get()) 24 """ return SampleNewStyleClass(self.val + self.val) def get(self): """ >>> print(SampleNewStyleClass(-5).get()) -5 """ return self.val ###################################################################### ## Fake stdin (for testing interactive debugging) ###################################################################### class _FakeInput: """ A fake input stream for pdb's interactive debugger. Whenever a line is read, print it (to simulate the user typing it), and then return it. The set of lines to return is specified in the constructor; they should not have trailing newlines. """ def __init__(self, lines): self.lines = lines def readline(self): line = self.lines.pop(0) print(line) return line+'\n' ###################################################################### ## Test Cases ###################################################################### def test_Example(): r""" Unit tests for the `Example` class. Example is a simple container class that holds: - `source`: A source string. - `want`: An expected output string. - `exc_msg`: An expected exception message string (or None if no exception is expected). - `lineno`: A line number (within the docstring). - `indent`: The example's indentation in the input string. - `options`: An option dictionary, mapping option flags to True or False. These attributes are set by the constructor. `source` and `want` are required; the other attributes all have default values: >>> example = doctest.Example('print(1)', '1\n') >>> (example.source, example.want, example.exc_msg, ... example.lineno, example.indent, example.options) ('print(1)\n', '1\n', None, 0, 0, {}) The first three attributes (`source`, `want`, and `exc_msg`) may be specified positionally; the remaining arguments should be specified as keyword arguments: >>> exc_msg = 'IndexError: pop from an empty list' >>> example = doctest.Example('[].pop()', '', exc_msg, ... lineno=5, indent=4, ... options={doctest.ELLIPSIS: True}) >>> (example.source, example.want, example.exc_msg, ... example.lineno, example.indent, example.options) ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True}) The constructor normalizes the `source` string to end in a newline: Source spans a single line: no terminating newline. >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want ('print(1)\n', '1\n') >>> e = doctest.Example('print(1)\n', '1\n') >>> e.source, e.want ('print(1)\n', '1\n') Source spans multiple lines: require terminating newline. >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n') >>> e.source, e.want ('print(1);\nprint(2)\n', '1\n2\n') >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n') >>> e.source, e.want ('print(1);\nprint(2)\n', '1\n2\n') Empty source string (which should never appear in real examples) >>> e = doctest.Example('', '') >>> e.source, e.want ('\n', '') The constructor normalizes the `want` string to end in a newline, unless it's the empty string: >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want ('print(1)\n', '1\n') >>> e = doctest.Example('print(1)', '1') >>> e.source, e.want ('print(1)\n', '1\n') >>> e = doctest.Example('print', '') >>> e.source, e.want ('print\n', '') The constructor normalizes the `exc_msg` string to end in a newline, unless it's `None`: Message spans one line >>> exc_msg = 'IndexError: pop from an empty list' >>> e = doctest.Example('[].pop()', '', exc_msg) >>> e.exc_msg 'IndexError: pop from an empty list\n' >>> exc_msg = 'IndexError: pop from an empty list\n' >>> e = doctest.Example('[].pop()', '', exc_msg) >>> e.exc_msg 'IndexError: pop from an empty list\n' Message spans multiple lines >>> exc_msg = 'ValueError: 1\n 2' >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg) >>> e.exc_msg 'ValueError: 1\n 2\n' >>> exc_msg = 'ValueError: 1\n 2\n' >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg) >>> e.exc_msg 'ValueError: 1\n 2\n' Empty (but non-None) exception message (which should never appear in real examples) >>> exc_msg = '' >>> e = doctest.Example('raise X()', '', exc_msg) >>> e.exc_msg '\n' Compare `Example`: >>> example = doctest.Example('print 1', '1\n') >>> same_example = doctest.Example('print 1', '1\n') >>> other_example = doctest.Example('print 42', '42\n') >>> example == same_example True >>> example != same_example False >>> hash(example) == hash(same_example) True >>> example == other_example False >>> example != other_example True """ def test_DocTest(): r""" Unit tests for the `DocTest` class. DocTest is a collection of examples, extracted from a docstring, along with information about where the docstring comes from (a name, filename, and line number). The docstring is parsed by the `DocTest` constructor: >>> docstring = ''' ... >>> print(12) ... 12 ... ... Non-example text. ... ... >>> print('another\\example') ... another ... example ... ''' >>> globs = {} # globals to run the test in. >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_file', 20) >>> print(test) <DocTest some_test from some_file:20 (2 examples)> >>> len(test.examples) 2 >>> e1, e2 = test.examples >>> (e1.source, e1.want, e1.lineno) ('print(12)\n', '12\n', 1) >>> (e2.source, e2.want, e2.lineno) ("print('another\\example')\n", 'another\nexample\n', 6) Source information (name, filename, and line number) is available as attributes on the doctest object: >>> (test.name, test.filename, test.lineno) ('some_test', 'some_file', 20) The line number of an example within its containing file is found by adding the line number of the example and the line number of its containing test: >>> test.lineno + e1.lineno 21 >>> test.lineno + e2.lineno 26 If the docstring contains inconsistent leading whitespace in the expected output of an example, then `DocTest` will raise a ValueError: >>> docstring = r''' ... >>> print('bad\nindentation') ... bad ... indentation ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation' If the docstring contains inconsistent leading whitespace on continuation lines, then `DocTest` will raise a ValueError: >>> docstring = r''' ... >>> print(('bad indentation', ... ... 2)) ... ('bad', 'indentation') ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))' If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: >>> docstring = '>>>print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)' If there's no blank space after a PS2 prompt ('...'), then `DocTest` will raise a ValueError: >>> docstring = '>>> if 1:\n...print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)' Compare `DocTest`: >>> docstring = ''' ... >>> print 12 ... 12 ... ''' >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_test', 20) >>> same_test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_test', 20) >>> test == same_test True >>> test != same_test False >>> hash(test) == hash(same_test) True >>> docstring = ''' ... >>> print 42 ... 42 ... ''' >>> other_test = parser.get_doctest(docstring, globs, 'other_test', ... 'other_file', 10) >>> test == other_test False >>> test != other_test True Compare `DocTestCase`: >>> DocTestCase = doctest.DocTestCase >>> test_case = DocTestCase(test) >>> same_test_case = DocTestCase(same_test) >>> other_test_case = DocTestCase(other_test) >>> test_case == same_test_case True >>> test_case != same_test_case False >>> hash(test_case) == hash(same_test_case) True >>> test == other_test_case False >>> test != other_test_case True """ class test_DocTestFinder: def basics(): r""" Unit tests for the `DocTestFinder` class. DocTestFinder is used to extract DocTests from an object's docstring and the docstrings of its contained objects. It can be used with modules, functions, classes, methods, staticmethods, classmethods, and properties. Finding Tests in Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~ For a function whose docstring contains examples, DocTestFinder.find() will return a single test (for that function's docstring): >>> finder = doctest.DocTestFinder() We'll simulate a __file__ attr that ends in pyc: >>> import test.test_doctest >>> old = test.test_doctest.__file__ >>> test.test_doctest.__file__ = 'test_doctest.pyc' >>> tests = finder.find(sample_func) >>> print(tests) # doctest: +ELLIPSIS [<DocTest sample_func from ...:21 (1 example)>] The exact name depends on how test_doctest was invoked, so allow for leading path components. >>> tests[0].filename # doctest: +ELLIPSIS '...test_doctest.py' >>> test.test_doctest.__file__ = old >>> e = tests[0].examples[0] >>> (e.source, e.want, e.lineno) ('print(sample_func(22))\n', '44\n', 3) By default, tests are created for objects with no docstring: >>> def no_docstring(v): ... pass >>> finder.find(no_docstring) [] However, the optional argument `exclude_empty` to the DocTestFinder constructor can be used to exclude tests for objects with empty docstrings: >>> def no_docstring(v): ... pass >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True) >>> excl_empty_finder.find(no_docstring) [] If the function has a docstring with no examples, then a test with no examples is returned. (This lets `DocTestRunner` collect statistics about which functions have no tests -- but is that useful? And should an empty test also be created when there's no docstring?) >>> def no_examples(v): ... ''' no doctest examples ''' >>> finder.find(no_examples) # doctest: +ELLIPSIS [<DocTest no_examples from ...:1 (no examples)>] Finding Tests in Classes ~~~~~~~~~~~~~~~~~~~~~~~~ For a class, DocTestFinder will create a test for the class's docstring, and will recursively explore its contents, including methods, classmethods, staticmethods, properties, and nested classes. >>> finder = doctest.DocTestFinder() >>> tests = finder.find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get New-style classes are also supported: >>> tests = finder.find(SampleNewStyleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 1 SampleNewStyleClass 1 SampleNewStyleClass.__init__ 1 SampleNewStyleClass.double 1 SampleNewStyleClass.get Finding Tests in Modules ~~~~~~~~~~~~~~~~~~~~~~~~ For a module, DocTestFinder will create a test for the class's docstring, and will recursively explore its contents, including functions, classes, and the `__test__` dictionary, if it exists: >>> # A module >>> import types >>> m = types.ModuleType('some_module') >>> def triple(val): ... ''' ... >>> print(triple(11)) ... 33 ... ''' ... return val*3 >>> m.__dict__.update({ ... 'sample_func': sample_func, ... 'SampleClass': SampleClass, ... '__doc__': ''' ... Module docstring. ... >>> print('module') ... module ... ''', ... '__test__': { ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n', ... 'c': triple}}) >>> finder = doctest.DocTestFinder() >>> # Use module=test.test_doctest, to prevent doctest from >>> # ignoring the objects since they weren't defined in m. >>> import test.test_doctest >>> tests = finder.find(m, module=test.test_doctest) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 1 some_module 3 some_module.SampleClass 3 some_module.SampleClass.NestedClass 1 some_module.SampleClass.NestedClass.__init__ 1 some_module.SampleClass.__init__ 2 some_module.SampleClass.a_classmethod 1 some_module.SampleClass.a_property 1 some_module.SampleClass.a_staticmethod 1 some_module.SampleClass.double 1 some_module.SampleClass.get 1 some_module.__test__.c 2 some_module.__test__.d 1 some_module.sample_func Duplicate Removal ~~~~~~~~~~~~~~~~~ If a single object is listed twice (under different names), then tests will only be generated for it once: >>> from test import doctest_aliases >>> assert doctest_aliases.TwoNames.f >>> assert doctest_aliases.TwoNames.g >>> tests = excl_empty_finder.find(doctest_aliases) >>> print(len(tests)) 2 >>> print(tests[0].name) test.doctest_aliases.TwoNames TwoNames.f and TwoNames.g are bound to the same object. We can't guess which will be found in doctest's traversal of TwoNames.__dict__ first, so we have to allow for either. >>> tests[1].name.split('.')[-1] in ['f', 'g'] True Empty Tests ~~~~~~~~~~~ By default, an object with no doctests doesn't create any tests: >>> tests = doctest.DocTestFinder().find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get By default, that excluded objects with no doctests. exclude_empty=False tells it to include (empty) tests for objects with no doctests. This feature is really to support backward compatibility in what doctest.master.summarize() displays. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 0 SampleClass.NestedClass.get 0 SampleClass.NestedClass.square 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get Turning off Recursion ~~~~~~~~~~~~~~~~~~~~~ DocTestFinder can be told not to look for tests in contained objects using the `recurse` flag: >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass Line numbers ~~~~~~~~~~~~ DocTestFinder finds the line number of each example: >>> def f(x): ... ''' ... >>> x = 12 ... ... some text ... ... >>> # examples are not created for comments & bare prompts. ... >>> ... ... ... ... >>> for x in range(10): ... ... print(x, end=' ') ... 0 1 2 3 4 5 6 7 8 9 ... >>> x//2 ... 6 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> [e.lineno for e in test.examples] [1, 9, 12] """ if int.__doc__: # simple check for --without-doc-strings, skip if lacking def non_Python_modules(): r""" Finding Doctests in Modules Not Written in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DocTestFinder can also find doctests in most modules not written in Python. We'll use builtins as an example, since it almost certainly isn't written in plain ol' Python and is guaranteed to be available. >>> import builtins >>> tests = doctest.DocTestFinder().find(builtins) >>> 800 < len(tests) < 820 # approximate number of objects with docstrings True >>> real_tests = [t for t in tests if len(t.examples) > 0] >>> len(real_tests) # objects that actually have doctests 8 >>> for t in real_tests: ... print('{} {}'.format(len(t.examples), t.name)) ... 1 builtins.bin 3 builtins.float.as_integer_ratio 2 builtins.float.fromhex 2 builtins.float.hex 1 builtins.hex 1 builtins.int 2 builtins.int.bit_length 1 builtins.oct Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio', 'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod, and 'int' is a type. """ class TestDocTestFinder(unittest.TestCase): def test_empty_namespace_package(self): pkg_name = 'doctest_empty_pkg' with tempfile.TemporaryDirectory() as parent_dir: pkg_dir = os.path.join(parent_dir, pkg_name) os.mkdir(pkg_dir) sys.path.append(parent_dir) try: mod = importlib.import_module(pkg_name) finally: support.forget(pkg_name) sys.path.pop() include_empty_finder = doctest.DocTestFinder(exclude_empty=False) exclude_empty_finder = doctest.DocTestFinder(exclude_empty=True) self.assertEqual(len(include_empty_finder.find(mod)), 1) self.assertEqual(len(exclude_empty_finder.find(mod)), 0) def test_DocTestParser(): r""" Unit tests for the `DocTestParser` class. DocTestParser is used to parse docstrings containing doctest examples. The `parse` method divides a docstring into examples and intervening text: >>> s = ''' ... >>> x, y = 2, 3 # no output expected ... >>> if 1: ... ... print(x) ... ... print(y) ... 2 ... 3 ... ... Some text. ... >>> x+y ... 5 ... ''' >>> parser = doctest.DocTestParser() >>> for piece in parser.parse(s): ... if isinstance(piece, doctest.Example): ... print('Example:', (piece.source, piece.want, piece.lineno)) ... else: ... print(' Text:', repr(piece)) Text: '\n' Example: ('x, y = 2, 3 # no output expected\n', '', 1) Text: '' Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) Text: '\nSome text.\n' Example: ('x+y\n', '5\n', 9) Text: '' The `get_examples` method returns just the examples: >>> for piece in parser.get_examples(s): ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) The `get_doctest` method creates a Test from the examples, along with the given arguments: >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5) >>> (test.name, test.filename, test.lineno) ('name', 'filename', 5) >>> for piece in test.examples: ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) """ class test_DocTestRunner: def basics(): r""" Unit tests for the `DocTestRunner` class. DocTestRunner is used to run DocTest test cases, and to accumulate statistics. Here's a simple DocTest case we can use: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x) ... 12 ... >>> x//2 ... 6 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] The main DocTestRunner interface is the `run` method, which runs a given DocTest case in a given namespace (globs). It returns a tuple `(f,t)`, where `f` is the number of failed tests and `t` is the number of tried tests. >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=3) If any example produces incorrect output, then the test runner reports the failure and proceeds to the next example: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x) ... 14 ... >>> x//2 ... 6 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=True).run(test) ... # doctest: +ELLIPSIS Trying: x = 12 Expecting nothing ok Trying: print(x) Expecting: 14 ********************************************************************** File ..., line 4, in f Failed example: print(x) Expected: 14 Got: 12 Trying: x//2 Expecting: 6 ok TestResults(failed=1, attempted=3) """ def verbose_flag(): r""" The `verbose` flag makes the test runner generate more detailed output: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x) ... 12 ... >>> x//2 ... 6 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=True).run(test) Trying: x = 12 Expecting nothing ok Trying: print(x) Expecting: 12 ok Trying: x//2 Expecting: 6 ok TestResults(failed=0, attempted=3) If the `verbose` flag is unspecified, then the output will be verbose iff `-v` appears in sys.argv: >>> # Save the real sys.argv list. >>> old_argv = sys.argv >>> # If -v does not appear in sys.argv, then output isn't verbose. >>> sys.argv = ['test'] >>> doctest.DocTestRunner().run(test) TestResults(failed=0, attempted=3) >>> # If -v does appear in sys.argv, then output is verbose. >>> sys.argv = ['test', '-v'] >>> doctest.DocTestRunner().run(test) Trying: x = 12 Expecting nothing ok Trying: print(x) Expecting: 12 ok Trying: x//2 Expecting: 6 ok TestResults(failed=0, attempted=3) >>> # Restore sys.argv >>> sys.argv = old_argv In the remaining examples, the test runner's verbosity will be explicitly set, to ensure that the test behavior is consistent. """ def exceptions(): r""" Tests of `DocTestRunner`'s exception handling. An expected exception is specified with a traceback message. The lines between the first line and the type/value may be omitted or replaced with any other string: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x//0) ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=2) An example may not generate output before it raises an exception; if it does, then the traceback message will not be recognized as signaling an expected exception, so the example will be reported as an unexpected exception: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print('pre-exception output', x//0) ... pre-exception output ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) ... # doctest: +ELLIPSIS ********************************************************************** File ..., line 4, in f Failed example: print('pre-exception output', x//0) Exception raised: ... ZeroDivisionError: integer division or modulo by zero TestResults(failed=1, attempted=2) Exception messages may contain newlines: >>> def f(x): ... r''' ... >>> raise ValueError('multi\nline\nmessage') ... Traceback (most recent call last): ... ValueError: multi ... line ... message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=1) If an exception is expected, but an exception with the wrong type or message is raised, then it is reported as a failure: >>> def f(x): ... r''' ... >>> raise ValueError('message') ... Traceback (most recent call last): ... ValueError: wrong message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) ... # doctest: +ELLIPSIS ********************************************************************** File ..., line 3, in f Failed example: raise ValueError('message') Expected: Traceback (most recent call last): ValueError: wrong message Got: Traceback (most recent call last): ... ValueError: message TestResults(failed=1, attempted=1) However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the detail: >>> def f(x): ... r''' ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL ... Traceback (most recent call last): ... ValueError: wrong message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=1) IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting between Python versions. For example, in Python 2.x, the module path of the exception is not in the output, but this will fail under Python 3: >>> def f(x): ... r''' ... >>> from http.client import HTTPException ... >>> raise HTTPException('message') ... Traceback (most recent call last): ... HTTPException: message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) ... # doctest: +ELLIPSIS ********************************************************************** File ..., line 4, in f Failed example: raise HTTPException('message') Expected: Traceback (most recent call last): HTTPException: message Got: Traceback (most recent call last): ... http.client.HTTPException: message TestResults(failed=1, attempted=2) But in Python 3 the module path is included, and therefore a test must look like the following test to succeed in Python 3. But that test will fail under Python 2. >>> def f(x): ... r''' ... >>> from http.client import HTTPException ... >>> raise HTTPException('message') ... Traceback (most recent call last): ... http.client.HTTPException: message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=2) However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception (or its unexpected absence) will be ignored: >>> def f(x): ... r''' ... >>> from http.client import HTTPException ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL ... Traceback (most recent call last): ... HTTPException: message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=2) The module path will be completely ignored, so two different module paths will still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can be used when exceptions have changed module. >>> def f(x): ... r''' ... >>> from http.client import HTTPException ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL ... Traceback (most recent call last): ... foo.bar.HTTPException: message ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) TestResults(failed=0, attempted=2) But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type: >>> def f(x): ... r''' ... >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL ... Traceback (most recent call last): ... TypeError: wrong type ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) ... # doctest: +ELLIPSIS ********************************************************************** File ..., line 3, in f Failed example: raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL Expected: Traceback (most recent call last):
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_pyexpat.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pyexpat.py
# XXX TypeErrors on calling handlers, or on bad return values from a # handler, are obscure and unhelpful. from io import BytesIO import os import sys import sysconfig import unittest import traceback from xml.parsers import expat from xml.parsers.expat import errors from test.support import sortdict class SetAttributeTest(unittest.TestCase): def setUp(self): self.parser = expat.ParserCreate(namespace_separator='!') def test_buffer_text(self): self.assertIs(self.parser.buffer_text, False) for x in 0, 1, 2, 0: self.parser.buffer_text = x self.assertIs(self.parser.buffer_text, bool(x)) def test_namespace_prefixes(self): self.assertIs(self.parser.namespace_prefixes, False) for x in 0, 1, 2, 0: self.parser.namespace_prefixes = x self.assertIs(self.parser.namespace_prefixes, bool(x)) def test_ordered_attributes(self): self.assertIs(self.parser.ordered_attributes, False) for x in 0, 1, 2, 0: self.parser.ordered_attributes = x self.assertIs(self.parser.ordered_attributes, bool(x)) def test_specified_attributes(self): self.assertIs(self.parser.specified_attributes, False) for x in 0, 1, 2, 0: self.parser.specified_attributes = x self.assertIs(self.parser.specified_attributes, bool(x)) def test_invalid_attributes(self): with self.assertRaises(AttributeError): self.parser.returns_unicode = 1 with self.assertRaises(AttributeError): self.parser.returns_unicode # Issue #25019 self.assertRaises(TypeError, setattr, self.parser, range(0xF), 0) self.assertRaises(TypeError, self.parser.__setattr__, range(0xF), 0) self.assertRaises(TypeError, getattr, self.parser, range(0xF)) data = b'''\ <?xml version="1.0" encoding="iso-8859-1" standalone="no"?> <?xml-stylesheet href="stylesheet.css"?> <!-- comment data --> <!DOCTYPE quotations SYSTEM "quotations.dtd" [ <!ELEMENT root ANY> <!ATTLIST root attr1 CDATA #REQUIRED attr2 CDATA #IMPLIED> <!NOTATION notation SYSTEM "notation.jpeg"> <!ENTITY acirc "&#226;"> <!ENTITY external_entity SYSTEM "entity.file"> <!ENTITY unparsed_entity SYSTEM "entity.file" NDATA notation> %unparsed_entity; ]> <root attr1="value1" attr2="value2&#8000;"> <myns:subelement xmlns:myns="http://www.python.org/namespace"> Contents of subelements </myns:subelement> <sub2><![CDATA[contents of CDATA section]]></sub2> &external_entity; &skipped_entity; \xb5 </root> ''' # Produce UTF-8 output class ParseTest(unittest.TestCase): class Outputter: def __init__(self): self.out = [] def StartElementHandler(self, name, attrs): self.out.append('Start element: ' + repr(name) + ' ' + sortdict(attrs)) def EndElementHandler(self, name): self.out.append('End element: ' + repr(name)) def CharacterDataHandler(self, data): data = data.strip() if data: self.out.append('Character data: ' + repr(data)) def ProcessingInstructionHandler(self, target, data): self.out.append('PI: ' + repr(target) + ' ' + repr(data)) def StartNamespaceDeclHandler(self, prefix, uri): self.out.append('NS decl: ' + repr(prefix) + ' ' + repr(uri)) def EndNamespaceDeclHandler(self, prefix): self.out.append('End of NS decl: ' + repr(prefix)) def StartCdataSectionHandler(self): self.out.append('Start of CDATA section') def EndCdataSectionHandler(self): self.out.append('End of CDATA section') def CommentHandler(self, text): self.out.append('Comment: ' + repr(text)) def NotationDeclHandler(self, *args): name, base, sysid, pubid = args self.out.append('Notation declared: %s' %(args,)) def UnparsedEntityDeclHandler(self, *args): entityName, base, systemId, publicId, notationName = args self.out.append('Unparsed entity decl: %s' %(args,)) def NotStandaloneHandler(self): self.out.append('Not standalone') return 1 def ExternalEntityRefHandler(self, *args): context, base, sysId, pubId = args self.out.append('External entity ref: %s' %(args[1:],)) return 1 def StartDoctypeDeclHandler(self, *args): self.out.append(('Start doctype', args)) return 1 def EndDoctypeDeclHandler(self): self.out.append("End doctype") return 1 def EntityDeclHandler(self, *args): self.out.append(('Entity declaration', args)) return 1 def XmlDeclHandler(self, *args): self.out.append(('XML declaration', args)) return 1 def ElementDeclHandler(self, *args): self.out.append(('Element declaration', args)) return 1 def AttlistDeclHandler(self, *args): self.out.append(('Attribute list declaration', args)) return 1 def SkippedEntityHandler(self, *args): self.out.append(("Skipped entity", args)) return 1 def DefaultHandler(self, userData): pass def DefaultHandlerExpand(self, userData): pass handler_names = [ 'StartElementHandler', 'EndElementHandler', 'CharacterDataHandler', 'ProcessingInstructionHandler', 'UnparsedEntityDeclHandler', 'NotationDeclHandler', 'StartNamespaceDeclHandler', 'EndNamespaceDeclHandler', 'CommentHandler', 'StartCdataSectionHandler', 'EndCdataSectionHandler', 'DefaultHandler', 'DefaultHandlerExpand', 'NotStandaloneHandler', 'ExternalEntityRefHandler', 'StartDoctypeDeclHandler', 'EndDoctypeDeclHandler', 'EntityDeclHandler', 'XmlDeclHandler', 'ElementDeclHandler', 'AttlistDeclHandler', 'SkippedEntityHandler', ] def _hookup_callbacks(self, parser, handler): """ Set each of the callbacks defined on handler and named in self.handler_names on the given parser. """ for name in self.handler_names: setattr(parser, name, getattr(handler, name)) def _verify_parse_output(self, operations): expected_operations = [ ('XML declaration', ('1.0', 'iso-8859-1', 0)), 'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'', "Comment: ' comment data '", "Not standalone", ("Start doctype", ('quotations', 'quotations.dtd', None, 1)), ('Element declaration', ('root', (2, 0, None, ()))), ('Attribute list declaration', ('root', 'attr1', 'CDATA', None, 1)), ('Attribute list declaration', ('root', 'attr2', 'CDATA', None, 0)), "Notation declared: ('notation', None, 'notation.jpeg', None)", ('Entity declaration', ('acirc', 0, '\xe2', None, None, None, None)), ('Entity declaration', ('external_entity', 0, None, None, 'entity.file', None, None)), "Unparsed entity decl: ('unparsed_entity', None, 'entity.file', None, 'notation')", "Not standalone", "End doctype", "Start element: 'root' {'attr1': 'value1', 'attr2': 'value2\u1f40'}", "NS decl: 'myns' 'http://www.python.org/namespace'", "Start element: 'http://www.python.org/namespace!subelement' {}", "Character data: 'Contents of subelements'", "End element: 'http://www.python.org/namespace!subelement'", "End of NS decl: 'myns'", "Start element: 'sub2' {}", 'Start of CDATA section', "Character data: 'contents of CDATA section'", 'End of CDATA section', "End element: 'sub2'", "External entity ref: (None, 'entity.file', None)", ('Skipped entity', ('skipped_entity', 0)), "Character data: '\xb5'", "End element: 'root'", ] for operation, expected_operation in zip(operations, expected_operations): self.assertEqual(operation, expected_operation) def test_parse_bytes(self): out = self.Outputter() parser = expat.ParserCreate(namespace_separator='!') self._hookup_callbacks(parser, out) parser.Parse(data, 1) operations = out.out self._verify_parse_output(operations) # Issue #6697. self.assertRaises(AttributeError, getattr, parser, '\uD800') def test_parse_str(self): out = self.Outputter() parser = expat.ParserCreate(namespace_separator='!') self._hookup_callbacks(parser, out) parser.Parse(data.decode('iso-8859-1'), 1) operations = out.out self._verify_parse_output(operations) def test_parse_file(self): # Try parsing a file out = self.Outputter() parser = expat.ParserCreate(namespace_separator='!') self._hookup_callbacks(parser, out) file = BytesIO(data) parser.ParseFile(file) operations = out.out self._verify_parse_output(operations) def test_parse_again(self): parser = expat.ParserCreate() file = BytesIO(data) parser.ParseFile(file) # Issue 6676: ensure a meaningful exception is raised when attempting # to parse more than one XML document per xmlparser instance, # a limitation of the Expat library. with self.assertRaises(expat.error) as cm: parser.ParseFile(file) self.assertEqual(expat.ErrorString(cm.exception.code), expat.errors.XML_ERROR_FINISHED) class NamespaceSeparatorTest(unittest.TestCase): def test_legal(self): # Tests that make sure we get errors when the namespace_separator value # is illegal, and that we don't for good values: expat.ParserCreate() expat.ParserCreate(namespace_separator=None) expat.ParserCreate(namespace_separator=' ') def test_illegal(self): try: expat.ParserCreate(namespace_separator=42) self.fail() except TypeError as e: self.assertEqual(str(e), 'ParserCreate() argument 2 must be str or None, not int') try: expat.ParserCreate(namespace_separator='too long') self.fail() except ValueError as e: self.assertEqual(str(e), 'namespace_separator must be at most one character, omitted, or None') def test_zero_length(self): # ParserCreate() needs to accept a namespace_separator of zero length # to satisfy the requirements of RDF applications that are required # to simply glue together the namespace URI and the localname. Though # considered a wart of the RDF specifications, it needs to be supported. # # See XML-SIG mailing list thread starting with # http://mail.python.org/pipermail/xml-sig/2001-April/005202.html # expat.ParserCreate(namespace_separator='') # too short class InterningTest(unittest.TestCase): def test(self): # Test the interning machinery. p = expat.ParserCreate() L = [] def collector(name, *args): L.append(name) p.StartElementHandler = collector p.EndElementHandler = collector p.Parse(b"<e> <e/> <e></e> </e>", 1) tag = L[0] self.assertEqual(len(L), 6) for entry in L: # L should have the same string repeated over and over. self.assertTrue(tag is entry) def test_issue9402(self): # create an ExternalEntityParserCreate with buffer text class ExternalOutputter: def __init__(self, parser): self.parser = parser self.parser_result = None def ExternalEntityRefHandler(self, context, base, sysId, pubId): external_parser = self.parser.ExternalEntityParserCreate("") self.parser_result = external_parser.Parse(b"", 1) return 1 parser = expat.ParserCreate(namespace_separator='!') parser.buffer_text = 1 out = ExternalOutputter(parser) parser.ExternalEntityRefHandler = out.ExternalEntityRefHandler parser.Parse(data, 1) self.assertEqual(out.parser_result, 1) class BufferTextTest(unittest.TestCase): def setUp(self): self.stuff = [] self.parser = expat.ParserCreate() self.parser.buffer_text = 1 self.parser.CharacterDataHandler = self.CharacterDataHandler def check(self, expected, label): self.assertEqual(self.stuff, expected, "%s\nstuff = %r\nexpected = %r" % (label, self.stuff, map(str, expected))) def CharacterDataHandler(self, text): self.stuff.append(text) def StartElementHandler(self, name, attrs): self.stuff.append("<%s>" % name) bt = attrs.get("buffer-text") if bt == "yes": self.parser.buffer_text = 1 elif bt == "no": self.parser.buffer_text = 0 def EndElementHandler(self, name): self.stuff.append("</%s>" % name) def CommentHandler(self, data): self.stuff.append("<!--%s-->" % data) def setHandlers(self, handlers=[]): for name in handlers: setattr(self.parser, name, getattr(self, name)) def test_default_to_disabled(self): parser = expat.ParserCreate() self.assertFalse(parser.buffer_text) def test_buffering_enabled(self): # Make sure buffering is turned on self.assertTrue(self.parser.buffer_text) self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1) self.assertEqual(self.stuff, ['123'], "buffered text not properly collapsed") def test1(self): # XXX This test exposes more detail of Expat's text chunking than we # XXX like, but it tests what we need to concisely. self.setHandlers(["StartElementHandler"]) self.parser.Parse(b"<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", 1) self.assertEqual(self.stuff, ["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"], "buffering control not reacting as expected") def test2(self): self.parser.Parse(b"<a>1<b/>&lt;2&gt;<c/>&#32;\n&#x20;3</a>", 1) self.assertEqual(self.stuff, ["1<2> \n 3"], "buffered text not properly collapsed") def test3(self): self.setHandlers(["StartElementHandler"]) self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1) self.assertEqual(self.stuff, ["<a>", "1", "<b>", "2", "<c>", "3"], "buffered text not properly split") def test4(self): self.setHandlers(["StartElementHandler", "EndElementHandler"]) self.parser.CharacterDataHandler = None self.parser.Parse(b"<a>1<b/>2<c/>3</a>", 1) self.assertEqual(self.stuff, ["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"]) def test5(self): self.setHandlers(["StartElementHandler", "EndElementHandler"]) self.parser.Parse(b"<a>1<b></b>2<c/>3</a>", 1) self.assertEqual(self.stuff, ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"]) def test6(self): self.setHandlers(["CommentHandler", "EndElementHandler", "StartElementHandler"]) self.parser.Parse(b"<a>1<b/>2<c></c>345</a> ", 1) self.assertEqual(self.stuff, ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"], "buffered text not properly split") def test7(self): self.setHandlers(["CommentHandler", "EndElementHandler", "StartElementHandler"]) self.parser.Parse(b"<a>1<b/>2<c></c>3<!--abc-->4<!--def-->5</a> ", 1) self.assertEqual(self.stuff, ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "<!--abc-->", "4", "<!--def-->", "5", "</a>"], "buffered text not properly split") # Test handling of exception from callback: class HandlerExceptionTest(unittest.TestCase): def StartElementHandler(self, name, attrs): raise RuntimeError(name) def check_traceback_entry(self, entry, filename, funcname): self.assertEqual(os.path.basename(entry[0]), filename) self.assertEqual(entry[2], funcname) def test_exception(self): parser = expat.ParserCreate() parser.StartElementHandler = self.StartElementHandler try: parser.Parse(b"<a><b><c/></b></a>", 1) self.fail() except RuntimeError as e: self.assertEqual(e.args[0], 'a', "Expected RuntimeError for element 'a', but" + \ " found %r" % e.args[0]) # Check that the traceback contains the relevant line in pyexpat.c entries = traceback.extract_tb(e.__traceback__) self.assertEqual(len(entries), 3) self.check_traceback_entry(entries[0], "test_pyexpat.py", "test_exception") self.check_traceback_entry(entries[1], "pyexpat.c", "StartElement") self.check_traceback_entry(entries[2], "test_pyexpat.py", "StartElementHandler") if sysconfig.is_python_build(): self.assertIn('call_with_frame("StartElement"', entries[1][3]) # Test Current* members: class PositionTest(unittest.TestCase): def StartElementHandler(self, name, attrs): self.check_pos('s') def EndElementHandler(self, name): self.check_pos('e') def check_pos(self, event): pos = (event, self.parser.CurrentByteIndex, self.parser.CurrentLineNumber, self.parser.CurrentColumnNumber) self.assertTrue(self.upto < len(self.expected_list), 'too many parser events') expected = self.expected_list[self.upto] self.assertEqual(pos, expected, 'Expected position %s, got position %s' %(pos, expected)) self.upto += 1 def test(self): self.parser = expat.ParserCreate() self.parser.StartElementHandler = self.StartElementHandler self.parser.EndElementHandler = self.EndElementHandler self.upto = 0 self.expected_list = [('s', 0, 1, 0), ('s', 5, 2, 1), ('s', 11, 3, 2), ('e', 15, 3, 6), ('e', 17, 4, 1), ('e', 22, 5, 0)] xml = b'<a>\n <b>\n <c/>\n </b>\n</a>' self.parser.Parse(xml, 1) class sf1296433Test(unittest.TestCase): def test_parse_only_xml_data(self): # http://python.org/sf/1296433 # xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025) # this one doesn't crash #xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000) class SpecificException(Exception): pass def handler(text): raise SpecificException parser = expat.ParserCreate() parser.CharacterDataHandler = handler self.assertRaises(Exception, parser.Parse, xml.encode('iso8859')) class ChardataBufferTest(unittest.TestCase): """ test setting of chardata buffer size """ def test_1025_bytes(self): self.assertEqual(self.small_buffer_test(1025), 2) def test_1000_bytes(self): self.assertEqual(self.small_buffer_test(1000), 1) def test_wrong_size(self): parser = expat.ParserCreate() parser.buffer_text = 1 with self.assertRaises(ValueError): parser.buffer_size = -1 with self.assertRaises(ValueError): parser.buffer_size = 0 with self.assertRaises((ValueError, OverflowError)): parser.buffer_size = sys.maxsize + 1 with self.assertRaises(TypeError): parser.buffer_size = 512.0 def test_unchanged_size(self): xml1 = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * 512 xml2 = b'a'*512 + b'</s>' parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_size = 512 parser.buffer_text = 1 # Feed 512 bytes of character data: the handler should be called # once. self.n = 0 parser.Parse(xml1) self.assertEqual(self.n, 1) # Reassign to buffer_size, but assign the same size. parser.buffer_size = parser.buffer_size self.assertEqual(self.n, 1) # Try parsing rest of the document parser.Parse(xml2) self.assertEqual(self.n, 2) def test_disabling_buffer(self): xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>" + b'a' * 512 xml2 = b'b' * 1024 xml3 = b'c' * 1024 + b'</a>'; parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_text = 1 parser.buffer_size = 1024 self.assertEqual(parser.buffer_size, 1024) # Parse one chunk of XML self.n = 0 parser.Parse(xml1, 0) self.assertEqual(parser.buffer_size, 1024) self.assertEqual(self.n, 1) # Turn off buffering and parse the next chunk. parser.buffer_text = 0 self.assertFalse(parser.buffer_text) self.assertEqual(parser.buffer_size, 1024) for i in range(10): parser.Parse(xml2, 0) self.assertEqual(self.n, 11) parser.buffer_text = 1 self.assertTrue(parser.buffer_text) self.assertEqual(parser.buffer_size, 1024) parser.Parse(xml3, 1) self.assertEqual(self.n, 12) def counting_handler(self, text): self.n += 1 def small_buffer_test(self, buffer_len): xml = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * buffer_len + b'</s>' parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_size = 1024 parser.buffer_text = 1 self.n = 0 parser.Parse(xml) return self.n def test_change_size_1(self): xml1 = b"<?xml version='1.0' encoding='iso8859'?><a><s>" + b'a' * 1024 xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>' parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_text = 1 parser.buffer_size = 1024 self.assertEqual(parser.buffer_size, 1024) self.n = 0 parser.Parse(xml1, 0) parser.buffer_size *= 2 self.assertEqual(parser.buffer_size, 2048) parser.Parse(xml2, 1) self.assertEqual(self.n, 2) def test_change_size_2(self): xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>a<s>" + b'a' * 1023 xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>' parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_text = 1 parser.buffer_size = 2048 self.assertEqual(parser.buffer_size, 2048) self.n=0 parser.Parse(xml1, 0) parser.buffer_size = parser.buffer_size // 2 self.assertEqual(parser.buffer_size, 1024) parser.Parse(xml2, 1) self.assertEqual(self.n, 4) class MalformedInputTest(unittest.TestCase): def test1(self): xml = b"\0\r\n" parser = expat.ParserCreate() try: parser.Parse(xml, True) self.fail() except expat.ExpatError as e: self.assertEqual(str(e), 'unclosed token: line 2, column 0') def test2(self): # \xc2\x85 is UTF-8 encoded U+0085 (NEXT LINE) xml = b"<?xml version\xc2\x85='1.0'?>\r\n" parser = expat.ParserCreate() err_pattern = r'XML declaration not well-formed: line 1, column \d+' with self.assertRaisesRegex(expat.ExpatError, err_pattern): parser.Parse(xml, True) class ErrorMessageTest(unittest.TestCase): def test_codes(self): # verify mapping of errors.codes and errors.messages self.assertEqual(errors.XML_ERROR_SYNTAX, errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]]) def test_expaterror(self): xml = b'<' parser = expat.ParserCreate() try: parser.Parse(xml, True) self.fail() except expat.ExpatError as e: self.assertEqual(e.code, errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN]) class ForeignDTDTests(unittest.TestCase): """ Tests for the UseForeignDTD method of expat parser objects. """ def test_use_foreign_dtd(self): """ If UseForeignDTD is passed True and a document without an external entity reference is parsed, ExternalEntityRefHandler is first called with None for the public and system ids. """ handler_call_args = [] def resolve_entity(context, base, system_id, public_id): handler_call_args.append((public_id, system_id)) return 1 parser = expat.ParserCreate() parser.UseForeignDTD(True) parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.ExternalEntityRefHandler = resolve_entity parser.Parse(b"<?xml version='1.0'?><element/>") self.assertEqual(handler_call_args, [(None, None)]) # test UseForeignDTD() is equal to UseForeignDTD(True) handler_call_args[:] = [] parser = expat.ParserCreate() parser.UseForeignDTD() parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.ExternalEntityRefHandler = resolve_entity parser.Parse(b"<?xml version='1.0'?><element/>") self.assertEqual(handler_call_args, [(None, None)]) def test_ignore_use_foreign_dtd(self): """ If UseForeignDTD is passed True and a document with an external entity reference is parsed, ExternalEntityRefHandler is called with the public and system ids from the document. """ handler_call_args = [] def resolve_entity(context, base, system_id, public_id): handler_call_args.append((public_id, system_id)) return 1 parser = expat.ParserCreate() parser.UseForeignDTD(True) parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.ExternalEntityRefHandler = resolve_entity parser.Parse( b"<?xml version='1.0'?><!DOCTYPE foo PUBLIC 'bar' 'baz'><element/>") self.assertEqual(handler_call_args, [("bar", "baz")]) 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_sort.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sort.py
from test import support import random import unittest from functools import cmp_to_key verbose = support.verbose nerrors = 0 def check(tag, expected, raw, compare=None): global nerrors if verbose: print(" checking", tag) orig = raw[:] # save input in case of error if compare: raw.sort(key=cmp_to_key(compare)) else: raw.sort() if len(expected) != len(raw): print("error in", tag) print("length mismatch;", len(expected), len(raw)) print(expected) print(orig) print(raw) nerrors += 1 return for i, good in enumerate(expected): maybe = raw[i] if good is not maybe: print("error in", tag) print("out of order at index", i, good, maybe) print(expected) print(orig) print(raw) nerrors += 1 return class TestBase(unittest.TestCase): def testStressfully(self): # Try a variety of sizes at and around powers of 2, and at powers of 10. sizes = [0] for power in range(1, 10): n = 2 ** power sizes.extend(range(n-1, n+2)) sizes.extend([10, 100, 1000]) class Complains(object): maybe_complain = True def __init__(self, i): self.i = i def __lt__(self, other): if Complains.maybe_complain and random.random() < 0.001: if verbose: print(" complaining at", self, other) raise RuntimeError return self.i < other.i def __repr__(self): return "Complains(%d)" % self.i class Stable(object): def __init__(self, key, i): self.key = key self.index = i def __lt__(self, other): return self.key < other.key def __repr__(self): return "Stable(%d, %d)" % (self.key, self.index) for n in sizes: x = list(range(n)) if verbose: print("Testing size", n) s = x[:] check("identity", x, s) s = x[:] s.reverse() check("reversed", x, s) s = x[:] random.shuffle(s) check("random permutation", x, s) y = x[:] y.reverse() s = x[:] check("reversed via function", y, s, lambda a, b: (b>a)-(b<a)) if verbose: print(" Checking against an insane comparison function.") print(" If the implementation isn't careful, this may segfault.") s = x[:] s.sort(key=cmp_to_key(lambda a, b: int(random.random() * 3) - 1)) check("an insane function left some permutation", x, s) if len(x) >= 2: def bad_key(x): raise RuntimeError s = x[:] self.assertRaises(RuntimeError, s.sort, key=bad_key) x = [Complains(i) for i in x] s = x[:] random.shuffle(s) Complains.maybe_complain = True it_complained = False try: s.sort() except RuntimeError: it_complained = True if it_complained: Complains.maybe_complain = False check("exception during sort left some permutation", x, s) s = [Stable(random.randrange(10), i) for i in range(n)] augmented = [(e, e.index) for e in s] augmented.sort() # forced stable because ties broken by index x = [e for e, i in augmented] # a stable sort of s check("stability", x, s) #============================================================================== class TestBugs(unittest.TestCase): def test_bug453523(self): # bug 453523 -- list.sort() crasher. # If this fails, the most likely outcome is a core dump. # Mutations during a list sort should raise a ValueError. class C: def __lt__(self, other): if L and random.random() < 0.75: L.pop() else: L.append(3) return random.random() < 0.5 L = [C() for i in range(50)] self.assertRaises(ValueError, L.sort) def test_undetected_mutation(self): # Python 2.4a1 did not always detect mutation memorywaster = [] for i in range(20): def mutating_cmp(x, y): L.append(3) L.pop() return (x > y) - (x < y) L = [1,2] self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp)) def mutating_cmp(x, y): L.append(3) del L[:] return (x > y) - (x < y) self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp)) memorywaster = [memorywaster] #============================================================================== class TestDecorateSortUndecorate(unittest.TestCase): def test_decorated(self): data = 'The quick Brown fox Jumped over The lazy Dog'.split() copy = data[:] random.shuffle(data) data.sort(key=str.lower) def my_cmp(x, y): xlower, ylower = x.lower(), y.lower() return (xlower > ylower) - (xlower < ylower) copy.sort(key=cmp_to_key(my_cmp)) def test_baddecorator(self): data = 'The quick Brown fox Jumped over The lazy Dog'.split() self.assertRaises(TypeError, data.sort, key=lambda x,y: 0) def test_stability(self): data = [(random.randrange(100), i) for i in range(200)] copy = data[:] data.sort(key=lambda t: t[0]) # sort on the random first field copy.sort() # sort using both fields self.assertEqual(data, copy) # should get the same result def test_key_with_exception(self): # Verify that the wrapper has been removed data = list(range(-2, 2)) dup = data[:] self.assertRaises(ZeroDivisionError, data.sort, key=lambda x: 1/x) self.assertEqual(data, dup) def test_key_with_mutation(self): data = list(range(10)) def k(x): del data[:] data[:] = range(20) return x self.assertRaises(ValueError, data.sort, key=k) def test_key_with_mutating_del(self): data = list(range(10)) class SortKiller(object): def __init__(self, x): pass def __del__(self): del data[:] data[:] = range(20) def __lt__(self, other): return id(self) < id(other) self.assertRaises(ValueError, data.sort, key=SortKiller) def test_key_with_mutating_del_and_exception(self): data = list(range(10)) ## dup = data[:] class SortKiller(object): def __init__(self, x): if x > 2: raise RuntimeError def __del__(self): del data[:] data[:] = list(range(20)) self.assertRaises(RuntimeError, data.sort, key=SortKiller) ## major honking subtlety: we *can't* do: ## ## self.assertEqual(data, dup) ## ## because there is a reference to a SortKiller in the ## traceback and by the time it dies we're outside the call to ## .sort() and so the list protection gimmicks are out of ## date (this cost some brain cells to figure out...). def test_reverse(self): data = list(range(100)) random.shuffle(data) data.sort(reverse=True) self.assertEqual(data, list(range(99,-1,-1))) def test_reverse_stability(self): data = [(random.randrange(100), i) for i in range(200)] copy1 = data[:] copy2 = data[:] def my_cmp(x, y): x0, y0 = x[0], y[0] return (x0 > y0) - (x0 < y0) def my_cmp_reversed(x, y): x0, y0 = x[0], y[0] return (y0 > x0) - (y0 < x0) data.sort(key=cmp_to_key(my_cmp), reverse=True) copy1.sort(key=cmp_to_key(my_cmp_reversed)) self.assertEqual(data, copy1) copy2.sort(key=lambda x: x[0], reverse=True) self.assertEqual(data, copy2) #============================================================================== def check_against_PyObject_RichCompareBool(self, L): ## The idea here is to exploit the fact that unsafe_tuple_compare uses ## PyObject_RichCompareBool for the second elements of tuples. So we have, ## for (most) L, sorted(L) == [y[1] for y in sorted([(0,x) for x in L])] ## This will work as long as __eq__ => not __lt__ for all the objects in L, ## which holds for all the types used below. ## ## Testing this way ensures that the optimized implementation remains consistent ## with the naive implementation, even if changes are made to any of the ## richcompares. ## ## This function tests sorting for three lists (it randomly shuffles each one): ## 1. L ## 2. [(x,) for x in L] ## 3. [((x,),) for x in L] random.seed(0) random.shuffle(L) L_1 = L[:] L_2 = [(x,) for x in L] L_3 = [((x,),) for x in L] for L in [L_1, L_2, L_3]: optimized = sorted(L) reference = [y[1] for y in sorted([(0,x) for x in L])] for (opt, ref) in zip(optimized, reference): self.assertIs(opt, ref) #note: not assertEqual! We want to ensure *identical* behavior. class TestOptimizedCompares(unittest.TestCase): def test_safe_object_compare(self): heterogeneous_lists = [[0, 'foo'], [0.0, 'foo'], [('foo',), 'foo']] for L in heterogeneous_lists: self.assertRaises(TypeError, L.sort) self.assertRaises(TypeError, [(x,) for x in L].sort) self.assertRaises(TypeError, [((x,),) for x in L].sort) float_int_lists = [[1,1.1], [1<<70,1.1], [1.1,1], [1.1,1<<70]] for L in float_int_lists: check_against_PyObject_RichCompareBool(self, L) def test_unsafe_object_compare(self): # This test is by ppperry. It ensures that unsafe_object_compare is # verifying ms->key_richcompare == tp->richcompare before comparing. class WackyComparator(int): def __lt__(self, other): elem.__class__ = WackyList2 return int.__lt__(self, other) class WackyList1(list): pass class WackyList2(list): def __lt__(self, other): raise ValueError L = [WackyList1([WackyComparator(i), i]) for i in range(10)] elem = L[-1] with self.assertRaises(ValueError): L.sort() L = [WackyList1([WackyComparator(i), i]) for i in range(10)] elem = L[-1] with self.assertRaises(ValueError): [(x,) for x in L].sort() # The following test is also by ppperry. It ensures that # unsafe_object_compare handles Py_NotImplemented appropriately. class PointlessComparator: def __lt__(self, other): return NotImplemented L = [PointlessComparator(), PointlessComparator()] self.assertRaises(TypeError, L.sort) self.assertRaises(TypeError, [(x,) for x in L].sort) # The following tests go through various types that would trigger # ms->key_compare = unsafe_object_compare lists = [list(range(100)) + [(1<<70)], [str(x) for x in range(100)] + ['\uffff'], [bytes(x) for x in range(100)], [cmp_to_key(lambda x,y: x<y)(x) for x in range(100)]] for L in lists: check_against_PyObject_RichCompareBool(self, L) def test_unsafe_latin_compare(self): check_against_PyObject_RichCompareBool(self, [str(x) for x in range(100)]) def test_unsafe_long_compare(self): check_against_PyObject_RichCompareBool(self, [x for x in range(100)]) def test_unsafe_float_compare(self): check_against_PyObject_RichCompareBool(self, [float(x) for x in range(100)]) def test_unsafe_tuple_compare(self): # This test was suggested by Tim Peters. It verifies that the tuple # comparison respects the current tuple compare semantics, which do not # guarantee that x < x <=> (x,) < (x,) # # Note that we don't have to put anything in tuples here, because # the check function does a tuple test automatically. check_against_PyObject_RichCompareBool(self, [float('nan')]*100) check_against_PyObject_RichCompareBool(self, [float('nan') for _ in range(100)]) def test_not_all_tuples(self): self.assertRaises(TypeError, [(1.0, 1.0), (False, "A"), 6].sort) self.assertRaises(TypeError, [('a', 1), (1, 'a')].sort) self.assertRaises(TypeError, [(1, 'a'), ('a', 1)].sort) #============================================================================== 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_startfile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_startfile.py
# Ridiculously simple test of the os.startfile function for Windows. # # empty.vbs is an empty file (except for a comment), which does # nothing when run with cscript or wscript. # # A possible improvement would be to have empty.vbs do something that # we can detect here, to make sure that not only the os.startfile() # call succeeded, but also the script actually has run. import unittest from test import support import os import sys from os import path startfile = support.get_attribute(os, 'startfile') class TestCase(unittest.TestCase): def test_nonexisting(self): self.assertRaises(OSError, startfile, "nonexisting.vbs") def test_empty(self): # We need to make sure the child process starts in a directory # we're not about to delete. If we're running under -j, that # means the test harness provided directory isn't a safe option. # See http://bugs.python.org/issue15526 for more details with support.change_cwd(path.dirname(sys.executable)): empty = path.join(path.dirname(__file__), "empty.vbs") startfile(empty) startfile(empty, "open") 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_memoryio.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_memoryio.py
"""Unit tests for memory-based file-like objects. StringIO -- for unicode strings BytesIO -- for bytes """ import unittest from test import support import io import _pyio as pyio import pickle import sys class IntLike: def __init__(self, num): self._num = num def __index__(self): return self._num __int__ = __index__ class MemorySeekTestMixin: def testInit(self): buf = self.buftype("1234567890") bytesIo = self.ioclass(buf) def testRead(self): buf = self.buftype("1234567890") bytesIo = self.ioclass(buf) self.assertEqual(buf[:1], bytesIo.read(1)) self.assertEqual(buf[1:5], bytesIo.read(4)) self.assertEqual(buf[5:], bytesIo.read(900)) self.assertEqual(self.EOF, bytesIo.read()) def testReadNoArgs(self): buf = self.buftype("1234567890") bytesIo = self.ioclass(buf) self.assertEqual(buf, bytesIo.read()) self.assertEqual(self.EOF, bytesIo.read()) def testSeek(self): buf = self.buftype("1234567890") bytesIo = self.ioclass(buf) bytesIo.read(5) bytesIo.seek(0) self.assertEqual(buf, bytesIo.read()) bytesIo.seek(3) self.assertEqual(buf[3:], bytesIo.read()) self.assertRaises(TypeError, bytesIo.seek, 0.0) def testTell(self): buf = self.buftype("1234567890") bytesIo = self.ioclass(buf) self.assertEqual(0, bytesIo.tell()) bytesIo.seek(5) self.assertEqual(5, bytesIo.tell()) bytesIo.seek(10000) self.assertEqual(10000, bytesIo.tell()) class MemoryTestMixin: def test_detach(self): buf = self.ioclass() self.assertRaises(self.UnsupportedOperation, buf.detach) def write_ops(self, f, t): self.assertEqual(f.write(t("blah.")), 5) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(t("Hello.")), 6) self.assertEqual(f.tell(), 6) self.assertEqual(f.seek(5), 5) self.assertEqual(f.tell(), 5) self.assertEqual(f.write(t(" world\n\n\n")), 9) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(t("h")), 1) self.assertEqual(f.truncate(12), 12) self.assertEqual(f.tell(), 1) def test_write(self): buf = self.buftype("hello world\n") memio = self.ioclass(buf) self.write_ops(memio, self.buftype) self.assertEqual(memio.getvalue(), buf) memio = self.ioclass() self.write_ops(memio, self.buftype) self.assertEqual(memio.getvalue(), buf) self.assertRaises(TypeError, memio.write, None) memio.close() self.assertRaises(ValueError, memio.write, self.buftype("")) def test_writelines(self): buf = self.buftype("1234567890") memio = self.ioclass() self.assertEqual(memio.writelines([buf] * 100), None) self.assertEqual(memio.getvalue(), buf * 100) memio.writelines([]) self.assertEqual(memio.getvalue(), buf * 100) memio = self.ioclass() self.assertRaises(TypeError, memio.writelines, [buf] + [1]) self.assertEqual(memio.getvalue(), buf) self.assertRaises(TypeError, memio.writelines, None) memio.close() self.assertRaises(ValueError, memio.writelines, []) def test_writelines_error(self): memio = self.ioclass() def error_gen(): yield self.buftype('spam') raise KeyboardInterrupt self.assertRaises(KeyboardInterrupt, memio.writelines, error_gen()) def test_truncate(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertRaises(ValueError, memio.truncate, -1) self.assertRaises(ValueError, memio.truncate, IntLike(-1)) memio.seek(6) self.assertEqual(memio.truncate(IntLike(8)), 8) self.assertEqual(memio.getvalue(), buf[:8]) self.assertEqual(memio.truncate(), 6) self.assertEqual(memio.getvalue(), buf[:6]) self.assertEqual(memio.truncate(4), 4) self.assertEqual(memio.getvalue(), buf[:4]) self.assertEqual(memio.tell(), 6) memio.seek(0, 2) memio.write(buf) self.assertEqual(memio.getvalue(), buf[:4] + buf) pos = memio.tell() self.assertEqual(memio.truncate(None), pos) self.assertEqual(memio.tell(), pos) self.assertRaises(TypeError, memio.truncate, '0') memio.close() self.assertRaises(ValueError, memio.truncate, 0) self.assertRaises(ValueError, memio.truncate, IntLike(0)) def test_init(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.getvalue(), buf) memio = self.ioclass(None) self.assertEqual(memio.getvalue(), self.EOF) memio.__init__(buf * 2) self.assertEqual(memio.getvalue(), buf * 2) memio.__init__(buf) self.assertEqual(memio.getvalue(), buf) self.assertRaises(TypeError, memio.__init__, []) def test_read(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.read(0), self.EOF) self.assertEqual(memio.read(1), buf[:1]) self.assertEqual(memio.read(4), buf[1:5]) self.assertEqual(memio.read(900), buf[5:]) self.assertEqual(memio.read(), self.EOF) memio.seek(0) self.assertEqual(memio.read(IntLike(0)), self.EOF) self.assertEqual(memio.read(IntLike(1)), buf[:1]) self.assertEqual(memio.read(IntLike(4)), buf[1:5]) self.assertEqual(memio.read(IntLike(900)), buf[5:]) memio.seek(0) self.assertEqual(memio.read(), buf) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.tell(), 10) memio.seek(0) self.assertEqual(memio.read(-1), buf) memio.seek(0) self.assertEqual(memio.read(IntLike(-1)), buf) memio.seek(0) self.assertEqual(type(memio.read()), type(buf)) memio.seek(100) self.assertEqual(type(memio.read()), type(buf)) memio.seek(0) self.assertEqual(memio.read(None), buf) self.assertRaises(TypeError, memio.read, '') memio.seek(len(buf) + 1) self.assertEqual(memio.read(1), self.EOF) memio.seek(len(buf) + 1) self.assertEqual(memio.read(IntLike(1)), self.EOF) memio.seek(len(buf) + 1) self.assertEqual(memio.read(), self.EOF) memio.close() self.assertRaises(ValueError, memio.read) def test_readline(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 2) self.assertEqual(memio.readline(0), self.EOF) self.assertEqual(memio.readline(IntLike(0)), self.EOF) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), self.EOF) memio.seek(0) self.assertEqual(memio.readline(5), buf[:5]) self.assertEqual(memio.readline(5), buf[5:10]) self.assertEqual(memio.readline(5), buf[10:15]) memio.seek(0) self.assertEqual(memio.readline(IntLike(5)), buf[:5]) self.assertEqual(memio.readline(IntLike(5)), buf[5:10]) self.assertEqual(memio.readline(IntLike(5)), buf[10:15]) memio.seek(0) self.assertEqual(memio.readline(-1), buf) memio.seek(0) self.assertEqual(memio.readline(IntLike(-1)), buf) memio.seek(0) self.assertEqual(memio.readline(0), self.EOF) self.assertEqual(memio.readline(IntLike(0)), self.EOF) # Issue #24989: Buffer overread memio.seek(len(buf) * 2 + 1) self.assertEqual(memio.readline(), self.EOF) buf = self.buftype("1234567890\n") memio = self.ioclass((buf * 3)[:-1]) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf[:-1]) self.assertEqual(memio.readline(), self.EOF) memio.seek(0) self.assertEqual(type(memio.readline()), type(buf)) self.assertEqual(memio.readline(), buf) self.assertRaises(TypeError, memio.readline, '') memio.close() self.assertRaises(ValueError, memio.readline) def test_readlines(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 10) self.assertEqual(memio.readlines(), [buf] * 10) memio.seek(5) self.assertEqual(memio.readlines(), [buf[5:]] + [buf] * 9) memio.seek(0) self.assertEqual(memio.readlines(15), [buf] * 2) memio.seek(0) self.assertEqual(memio.readlines(-1), [buf] * 10) memio.seek(0) self.assertEqual(memio.readlines(0), [buf] * 10) memio.seek(0) self.assertEqual(type(memio.readlines()[0]), type(buf)) memio.seek(0) self.assertEqual(memio.readlines(None), [buf] * 10) self.assertRaises(TypeError, memio.readlines, '') # Issue #24989: Buffer overread memio.seek(len(buf) * 10 + 1) self.assertEqual(memio.readlines(), []) memio.close() self.assertRaises(ValueError, memio.readlines) def test_iterator(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 10) self.assertEqual(iter(memio), memio) self.assertTrue(hasattr(memio, '__iter__')) self.assertTrue(hasattr(memio, '__next__')) i = 0 for line in memio: self.assertEqual(line, buf) i += 1 self.assertEqual(i, 10) memio.seek(0) i = 0 for line in memio: self.assertEqual(line, buf) i += 1 self.assertEqual(i, 10) # Issue #24989: Buffer overread memio.seek(len(buf) * 10 + 1) self.assertEqual(list(memio), []) memio = self.ioclass(buf * 2) memio.close() self.assertRaises(ValueError, memio.__next__) def test_getvalue(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.getvalue(), buf) memio.read() self.assertEqual(memio.getvalue(), buf) self.assertEqual(type(memio.getvalue()), type(buf)) memio = self.ioclass(buf * 1000) self.assertEqual(memio.getvalue()[-3:], self.buftype("890")) memio = self.ioclass(buf) memio.close() self.assertRaises(ValueError, memio.getvalue) def test_seek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) memio.read(5) self.assertRaises(ValueError, memio.seek, -1) self.assertRaises(ValueError, memio.seek, 1, -1) self.assertRaises(ValueError, memio.seek, 1, 3) self.assertEqual(memio.seek(0), 0) self.assertEqual(memio.seek(0, 0), 0) self.assertEqual(memio.read(), buf) self.assertEqual(memio.seek(3), 3) self.assertEqual(memio.seek(0, 1), 3) self.assertEqual(memio.read(), buf[3:]) self.assertEqual(memio.seek(len(buf)), len(buf)) self.assertEqual(memio.read(), self.EOF) memio.seek(len(buf) + 1) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.seek(0, 2), len(buf)) self.assertEqual(memio.read(), self.EOF) memio.close() self.assertRaises(ValueError, memio.seek, 0) def test_overseek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.seek(len(buf) + 1), 11) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.tell(), 11) self.assertEqual(memio.getvalue(), buf) memio.write(self.EOF) self.assertEqual(memio.getvalue(), buf) memio.write(buf) self.assertEqual(memio.getvalue(), buf + self.buftype('\0') + buf) def test_tell(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.tell(), 0) memio.seek(5) self.assertEqual(memio.tell(), 5) memio.seek(10000) self.assertEqual(memio.tell(), 10000) memio.close() self.assertRaises(ValueError, memio.tell) def test_flush(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.flush(), None) def test_flags(self): memio = self.ioclass() self.assertEqual(memio.writable(), True) self.assertEqual(memio.readable(), True) self.assertEqual(memio.seekable(), True) self.assertEqual(memio.isatty(), False) self.assertEqual(memio.closed, False) memio.close() self.assertRaises(ValueError, memio.writable) self.assertRaises(ValueError, memio.readable) self.assertRaises(ValueError, memio.seekable) self.assertRaises(ValueError, memio.isatty) self.assertEqual(memio.closed, True) def test_subclassing(self): buf = self.buftype("1234567890") def test1(): class MemIO(self.ioclass): pass m = MemIO(buf) return m.getvalue() def test2(): class MemIO(self.ioclass): def __init__(me, a, b): self.ioclass.__init__(me, a) m = MemIO(buf, None) return m.getvalue() self.assertEqual(test1(), buf) self.assertEqual(test2(), buf) def test_instance_dict_leak(self): # Test case for issue #6242. # This will be caught by regrtest.py -R if this leak. for _ in range(100): memio = self.ioclass() memio.foo = 1 def test_pickling(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) memio.foo = 42 memio.seek(2) class PickleTestMemIO(self.ioclass): def __init__(me, initvalue, foo): self.ioclass.__init__(me, initvalue) me.foo = foo # __getnewargs__ is undefined on purpose. This checks that PEP 307 # is used to provide pickling support. # Pickle expects the class to be on the module level. Here we use a # little hack to allow the PickleTestMemIO class to derive from # self.ioclass without having to define all combinations explicitly on # the module-level. import __main__ PickleTestMemIO.__module__ = '__main__' PickleTestMemIO.__qualname__ = PickleTestMemIO.__name__ __main__.PickleTestMemIO = PickleTestMemIO submemio = PickleTestMemIO(buf, 80) submemio.seek(2) # We only support pickle protocol 2 and onward since we use extended # __reduce__ API of PEP 307 to provide pickling support. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): for obj in (memio, submemio): obj2 = pickle.loads(pickle.dumps(obj, protocol=proto)) self.assertEqual(obj.getvalue(), obj2.getvalue()) self.assertEqual(obj.__class__, obj2.__class__) self.assertEqual(obj.foo, obj2.foo) self.assertEqual(obj.tell(), obj2.tell()) obj2.close() self.assertRaises(ValueError, pickle.dumps, obj2, proto) del __main__.PickleTestMemIO class PyBytesIOTest(MemoryTestMixin, MemorySeekTestMixin, unittest.TestCase): # Test _pyio.BytesIO; class also inherited for testing C implementation UnsupportedOperation = pyio.UnsupportedOperation @staticmethod def buftype(s): return s.encode("ascii") ioclass = pyio.BytesIO EOF = b"" def test_getbuffer(self): memio = self.ioclass(b"1234567890") buf = memio.getbuffer() self.assertEqual(bytes(buf), b"1234567890") memio.seek(5) buf = memio.getbuffer() self.assertEqual(bytes(buf), b"1234567890") # Trying to change the size of the BytesIO while a buffer is exported # raises a BufferError. self.assertRaises(BufferError, memio.write, b'x' * 100) self.assertRaises(BufferError, memio.truncate) self.assertRaises(BufferError, memio.close) self.assertFalse(memio.closed) # Mutating the buffer updates the BytesIO buf[3:6] = b"abc" self.assertEqual(bytes(buf), b"123abc7890") self.assertEqual(memio.getvalue(), b"123abc7890") # After the buffer gets released, we can resize and close the BytesIO # again del buf support.gc_collect() memio.truncate() memio.close() self.assertRaises(ValueError, memio.getbuffer) def test_read1(self): buf = self.buftype("1234567890") self.assertEqual(self.ioclass(buf).read1(), buf) self.assertEqual(self.ioclass(buf).read1(-1), buf) def test_readinto(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) b = bytearray(b"hello") self.assertEqual(memio.readinto(b), 5) self.assertEqual(b, b"12345") self.assertEqual(memio.readinto(b), 5) self.assertEqual(b, b"67890") self.assertEqual(memio.readinto(b), 0) self.assertEqual(b, b"67890") b = bytearray(b"hello world") memio.seek(0) self.assertEqual(memio.readinto(b), 10) self.assertEqual(b, b"1234567890d") b = bytearray(b"") memio.seek(0) self.assertEqual(memio.readinto(b), 0) self.assertEqual(b, b"") self.assertRaises(TypeError, memio.readinto, '') import array a = array.array('b', b"hello world") memio = self.ioclass(buf) memio.readinto(a) self.assertEqual(a.tobytes(), b"1234567890d") memio.close() self.assertRaises(ValueError, memio.readinto, b) memio = self.ioclass(b"123") b = bytearray() memio.seek(42) memio.readinto(b) self.assertEqual(b, b"") def test_relative_seek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.seek(-1, 1), 0) self.assertEqual(memio.seek(3, 1), 3) self.assertEqual(memio.seek(-4, 1), 0) self.assertEqual(memio.seek(-1, 2), 9) self.assertEqual(memio.seek(1, 1), 10) self.assertEqual(memio.seek(1, 2), 11) memio.seek(-3, 2) self.assertEqual(memio.read(), buf[-3:]) memio.seek(0) memio.seek(1, 1) self.assertEqual(memio.read(), buf[1:]) def test_unicode(self): memio = self.ioclass() self.assertRaises(TypeError, self.ioclass, "1234567890") self.assertRaises(TypeError, memio.write, "1234567890") self.assertRaises(TypeError, memio.writelines, ["1234567890"]) def test_bytes_array(self): buf = b"1234567890" import array a = array.array('b', list(buf)) memio = self.ioclass(a) self.assertEqual(memio.getvalue(), buf) self.assertEqual(memio.write(a), 10) self.assertEqual(memio.getvalue(), buf) def test_issue5449(self): buf = self.buftype("1234567890") self.ioclass(initial_bytes=buf) self.assertRaises(TypeError, self.ioclass, buf, foo=None) class TextIOTestMixin: def test_newlines_property(self): memio = self.ioclass(newline=None) # The C StringIO decodes newlines in write() calls, but the Python # implementation only does when reading. This function forces them to # be decoded for testing. def force_decode(): memio.seek(0) memio.read() self.assertEqual(memio.newlines, None) memio.write("a\n") force_decode() self.assertEqual(memio.newlines, "\n") memio.write("b\r\n") force_decode() self.assertEqual(memio.newlines, ("\n", "\r\n")) memio.write("c\rd") force_decode() self.assertEqual(memio.newlines, ("\r", "\n", "\r\n")) def test_relative_seek(self): memio = self.ioclass() self.assertRaises(OSError, memio.seek, -1, 1) self.assertRaises(OSError, memio.seek, 3, 1) self.assertRaises(OSError, memio.seek, -3, 1) self.assertRaises(OSError, memio.seek, -1, 2) self.assertRaises(OSError, memio.seek, 1, 1) self.assertRaises(OSError, memio.seek, 1, 2) def test_textio_properties(self): memio = self.ioclass() # These are just dummy values but we nevertheless check them for fear # of unexpected breakage. self.assertIsNone(memio.encoding) self.assertIsNone(memio.errors) self.assertFalse(memio.line_buffering) def test_newline_default(self): memio = self.ioclass("a\nb\r\nc\rd") self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") memio = self.ioclass() self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) memio.seek(0) self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") def test_newline_none(self): # newline=None memio = self.ioclass("a\nb\r\nc\rd", newline=None) self.assertEqual(list(memio), ["a\n", "b\n", "c\n", "d"]) memio.seek(0) self.assertEqual(memio.read(1), "a") self.assertEqual(memio.read(2), "\nb") self.assertEqual(memio.read(2), "\nc") self.assertEqual(memio.read(1), "\n") self.assertEqual(memio.getvalue(), "a\nb\nc\nd") memio = self.ioclass(newline=None) self.assertEqual(2, memio.write("a\n")) self.assertEqual(3, memio.write("b\r\n")) self.assertEqual(3, memio.write("c\rd")) memio.seek(0) self.assertEqual(memio.read(), "a\nb\nc\nd") self.assertEqual(memio.getvalue(), "a\nb\nc\nd") memio = self.ioclass("a\r\nb", newline=None) self.assertEqual(memio.read(3), "a\nb") def test_newline_empty(self): # newline="" memio = self.ioclass("a\nb\r\nc\rd", newline="") self.assertEqual(list(memio), ["a\n", "b\r\n", "c\r", "d"]) memio.seek(0) self.assertEqual(memio.read(4), "a\nb\r") self.assertEqual(memio.read(2), "\nc") self.assertEqual(memio.read(1), "\r") self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") memio = self.ioclass(newline="") self.assertEqual(2, memio.write("a\n")) self.assertEqual(2, memio.write("b\r")) self.assertEqual(2, memio.write("\nc")) self.assertEqual(2, memio.write("\rd")) memio.seek(0) self.assertEqual(list(memio), ["a\n", "b\r\n", "c\r", "d"]) self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") def test_newline_lf(self): # newline="\n" memio = self.ioclass("a\nb\r\nc\rd", newline="\n") self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") memio = self.ioclass(newline="\n") self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) memio.seek(0) self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") def test_newline_cr(self): # newline="\r" memio = self.ioclass("a\nb\r\nc\rd", newline="\r") self.assertEqual(memio.read(), "a\rb\r\rc\rd") memio.seek(0) self.assertEqual(list(memio), ["a\r", "b\r", "\r", "c\r", "d"]) self.assertEqual(memio.getvalue(), "a\rb\r\rc\rd") memio = self.ioclass(newline="\r") self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) memio.seek(0) self.assertEqual(list(memio), ["a\r", "b\r", "\r", "c\r", "d"]) memio.seek(0) self.assertEqual(memio.readlines(), ["a\r", "b\r", "\r", "c\r", "d"]) self.assertEqual(memio.getvalue(), "a\rb\r\rc\rd") def test_newline_crlf(self): # newline="\r\n" memio = self.ioclass("a\nb\r\nc\rd", newline="\r\n") self.assertEqual(memio.read(), "a\r\nb\r\r\nc\rd") memio.seek(0) self.assertEqual(list(memio), ["a\r\n", "b\r\r\n", "c\rd"]) memio.seek(0) self.assertEqual(memio.readlines(), ["a\r\n", "b\r\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\r\nb\r\r\nc\rd") memio = self.ioclass(newline="\r\n") self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) memio.seek(0) self.assertEqual(list(memio), ["a\r\n", "b\r\r\n", "c\rd"]) self.assertEqual(memio.getvalue(), "a\r\nb\r\r\nc\rd") def test_issue5265(self): # StringIO can duplicate newlines in universal newlines mode memio = self.ioclass("a\r\nb\r\n", newline=None) self.assertEqual(memio.read(5), "a\nb\n") self.assertEqual(memio.getvalue(), "a\nb\n") def test_newline_argument(self): self.assertRaises(TypeError, self.ioclass, newline=b"\n") self.assertRaises(ValueError, self.ioclass, newline="error") # These should not raise an error for newline in (None, "", "\n", "\r", "\r\n"): self.ioclass(newline=newline) class PyStringIOTest(MemoryTestMixin, MemorySeekTestMixin, TextIOTestMixin, unittest.TestCase): buftype = str ioclass = pyio.StringIO UnsupportedOperation = pyio.UnsupportedOperation EOF = "" def test_lone_surrogates(self): # Issue #20424 memio = self.ioclass('\ud800') self.assertEqual(memio.read(), '\ud800') memio = self.ioclass() memio.write('\ud800') self.assertEqual(memio.getvalue(), '\ud800') class PyStringIOPickleTest(TextIOTestMixin, unittest.TestCase): """Test if pickle restores properly the internal state of StringIO. """ buftype = str UnsupportedOperation = pyio.UnsupportedOperation EOF = "" class ioclass(pyio.StringIO): def __new__(cls, *args, **kwargs): return pickle.loads(pickle.dumps(pyio.StringIO(*args, **kwargs))) def __init__(self, *args, **kwargs): pass class CBytesIOTest(PyBytesIOTest): ioclass = io.BytesIO UnsupportedOperation = io.UnsupportedOperation def test_getstate(self): memio = self.ioclass() state = memio.__getstate__() self.assertEqual(len(state), 3) bytearray(state[0]) # Check if state[0] supports the buffer interface. self.assertIsInstance(state[1], int) if state[2] is not None: self.assertIsInstance(state[2], dict) memio.close() self.assertRaises(ValueError, memio.__getstate__) def test_setstate(self): # This checks whether __setstate__ does proper input validation. memio = self.ioclass() memio.__setstate__((b"no error", 0, None)) memio.__setstate__((bytearray(b"no error"), 0, None)) memio.__setstate__((b"no error", 0, {'spam': 3})) self.assertRaises(ValueError, memio.__setstate__, (b"", -1, None)) self.assertRaises(TypeError, memio.__setstate__, ("unicode", 0, None)) self.assertRaises(TypeError, memio.__setstate__, (b"", 0.0, None)) self.assertRaises(TypeError, memio.__setstate__, (b"", 0, 0)) self.assertRaises(TypeError, memio.__setstate__, (b"len-test", 0)) self.assertRaises(TypeError, memio.__setstate__) self.assertRaises(TypeError, memio.__setstate__, 0) memio.close() self.assertRaises(ValueError, memio.__setstate__, (b"closed", 0, None)) check_sizeof = support.check_sizeof @support.cpython_only def test_sizeof(self): basesize = support.calcobjsize('P2n2Pn') check = self.check_sizeof self.assertEqual(object.__sizeof__(io.BytesIO()), basesize) check(io.BytesIO(), basesize ) n = 1000 # use a variable to prevent constant folding check(io.BytesIO(b'a' * n), basesize + sys.getsizeof(b'a' * n)) # Various tests of copy-on-write behaviour for BytesIO. def _test_cow_mutation(self, mutation): # Common code for all BytesIO copy-on-write mutation tests. imm = b' ' * 1024 old_rc = sys.getrefcount(imm) memio = self.ioclass(imm) self.assertEqual(sys.getrefcount(imm), old_rc + 1) mutation(memio) self.assertEqual(sys.getrefcount(imm), old_rc) @support.cpython_only def test_cow_truncate(self): # Ensure truncate causes a copy. def mutation(memio): memio.truncate(1) self._test_cow_mutation(mutation) @support.cpython_only def test_cow_write(self): # Ensure write that would not cause a resize still results in a copy. def mutation(memio): memio.seek(0) memio.write(b'foo') self._test_cow_mutation(mutation) @support.cpython_only def test_cow_setstate(self): # __setstate__ should cause buffer to be released. memio = self.ioclass(b'foooooo') state = memio.__getstate__() def mutation(memio): memio.__setstate__(state) self._test_cow_mutation(mutation) @support.cpython_only def test_cow_mutable(self): # BytesIO should accept only Bytes for copy-on-write sharing, since # arbitrary buffer-exporting objects like bytearray() aren't guaranteed # to be immutable. ba = bytearray(1024) old_rc = sys.getrefcount(ba) memio = self.ioclass(ba) self.assertEqual(sys.getrefcount(ba), old_rc) class CStringIOTest(PyStringIOTest): ioclass = io.StringIO UnsupportedOperation = io.UnsupportedOperation # XXX: For the Python version of io.StringIO, this is highly # dependent on the encoding used for the underlying buffer. def test_widechar(self): buf = self.buftype("\U0002030a\U00020347") memio = self.ioclass(buf) self.assertEqual(memio.getvalue(), buf) self.assertEqual(memio.write(buf), len(buf)) self.assertEqual(memio.tell(), len(buf)) self.assertEqual(memio.getvalue(), buf) self.assertEqual(memio.write(buf), len(buf)) self.assertEqual(memio.tell(), len(buf) * 2) self.assertEqual(memio.getvalue(), buf + buf) def test_getstate(self): memio = self.ioclass() state = memio.__getstate__() self.assertEqual(len(state), 4) self.assertIsInstance(state[0], str) self.assertIsInstance(state[1], str) self.assertIsInstance(state[2], int) if state[3] is not None: self.assertIsInstance(state[3], dict) memio.close() self.assertRaises(ValueError, memio.__getstate__) def test_setstate(self): # This checks whether __setstate__ does proper input validation. memio = self.ioclass() memio.__setstate__(("no error", "\n", 0, None)) memio.__setstate__(("no error", "", 0, {'spam': 3})) self.assertRaises(ValueError, memio.__setstate__, ("", "f", 0, None)) self.assertRaises(ValueError, memio.__setstate__, ("", "", -1, None)) self.assertRaises(TypeError, memio.__setstate__, (b"", "", 0, None)) self.assertRaises(TypeError, memio.__setstate__, ("", b"", 0, None)) self.assertRaises(TypeError, memio.__setstate__, ("", "", 0.0, None)) self.assertRaises(TypeError, memio.__setstate__, ("", "", 0, 0)) self.assertRaises(TypeError, memio.__setstate__, ("len-test", 0)) self.assertRaises(TypeError, memio.__setstate__) self.assertRaises(TypeError, memio.__setstate__, 0) memio.close() self.assertRaises(ValueError, memio.__setstate__, ("closed", "", 0, None)) class CStringIOPickleTest(PyStringIOPickleTest): UnsupportedOperation = io.UnsupportedOperation class ioclass(io.StringIO): def __new__(cls, *args, **kwargs): return pickle.loads(pickle.dumps(io.StringIO(*args, **kwargs))) def __init__(self, *args, **kwargs): 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/test_sndhdr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sndhdr.py
import sndhdr import pickle import unittest from test.support import findfile class TestFormats(unittest.TestCase): def test_data(self): for filename, expected in ( ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)), ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)), ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)), ('sndhdr.au', ('au', 44100, 2, 5.0, 16)), ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)), ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)), ('sndhdr.voc', ('voc', 0, 1, -1, 8)), ('sndhdr.wav', ('wav', 44100, 2, 5, 16)), ): filename = findfile(filename, subdir="sndhdrdata") what = sndhdr.what(filename) self.assertNotEqual(what, None, filename) self.assertSequenceEqual(what, expected) self.assertEqual(what.filetype, expected[0]) self.assertEqual(what.framerate, expected[1]) self.assertEqual(what.nchannels, expected[2]) self.assertEqual(what.nframes, expected[3]) self.assertEqual(what.sampwidth, expected[4]) def test_pickleable(self): filename = findfile('sndhdr.aifc', subdir="sndhdrdata") what = sndhdr.what(filename) for proto in range(pickle.HIGHEST_PROTOCOL + 1): dump = pickle.dumps(what, proto) self.assertEqual(pickle.loads(dump), what) 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_posixpath.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_posixpath.py
import os import posixpath import unittest import warnings from posixpath import realpath, abspath, dirname, basename from test import support, test_genericpath from test.support import FakePath from unittest import mock try: import posix except ImportError: posix = None # An absolute path to a temporary filename for testing. We can't rely on TESTFN # being an absolute path, so we need this. ABSTFN = abspath(support.TESTFN) def skip_if_ABSTFN_contains_backslash(test): """ On Windows, posixpath.abspath still returns paths with backslashes instead of posix forward slashes. If this is the case, several tests fail, so skip them. """ found_backslash = '\\' in ABSTFN msg = "ABSTFN is not a posix path - tests fail" return [test, unittest.skip(msg)(test)][found_backslash] def safe_rmdir(dirname): try: os.rmdir(dirname) except OSError: pass class PosixPathTest(unittest.TestCase): def setUp(self): self.tearDown() def tearDown(self): for suffix in ["", "1", "2"]: support.unlink(support.TESTFN + suffix) safe_rmdir(support.TESTFN + suffix) def test_join(self): self.assertEqual(posixpath.join("/foo", "bar", "/bar", "baz"), "/bar/baz") self.assertEqual(posixpath.join("/foo", "bar", "baz"), "/foo/bar/baz") self.assertEqual(posixpath.join("/foo/", "bar/", "baz/"), "/foo/bar/baz/") self.assertEqual(posixpath.join(b"/foo", b"bar", b"/bar", b"baz"), b"/bar/baz") self.assertEqual(posixpath.join(b"/foo", b"bar", b"baz"), b"/foo/bar/baz") self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"), b"/foo/bar/baz/") def test_split(self): self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar")) self.assertEqual(posixpath.split("/"), ("/", "")) self.assertEqual(posixpath.split("foo"), ("", "foo")) self.assertEqual(posixpath.split("////foo"), ("////", "foo")) self.assertEqual(posixpath.split("//foo//bar"), ("//foo", "bar")) self.assertEqual(posixpath.split(b"/foo/bar"), (b"/foo", b"bar")) self.assertEqual(posixpath.split(b"/"), (b"/", b"")) self.assertEqual(posixpath.split(b"foo"), (b"", b"foo")) self.assertEqual(posixpath.split(b"////foo"), (b"////", b"foo")) self.assertEqual(posixpath.split(b"//foo//bar"), (b"//foo", b"bar")) def splitextTest(self, path, filename, ext): self.assertEqual(posixpath.splitext(path), (filename, ext)) self.assertEqual(posixpath.splitext("/" + path), ("/" + filename, ext)) self.assertEqual(posixpath.splitext("abc/" + path), ("abc/" + filename, ext)) self.assertEqual(posixpath.splitext("abc.def/" + path), ("abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext("/abc.def/" + path), ("/abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(path + "/"), (filename + ext + "/", "")) path = bytes(path, "ASCII") filename = bytes(filename, "ASCII") ext = bytes(ext, "ASCII") self.assertEqual(posixpath.splitext(path), (filename, ext)) self.assertEqual(posixpath.splitext(b"/" + path), (b"/" + filename, ext)) self.assertEqual(posixpath.splitext(b"abc/" + path), (b"abc/" + filename, ext)) self.assertEqual(posixpath.splitext(b"abc.def/" + path), (b"abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(b"/abc.def/" + path), (b"/abc.def/" + filename, ext)) self.assertEqual(posixpath.splitext(path + b"/"), (filename + ext + b"/", b"")) def test_splitext(self): self.splitextTest("foo.bar", "foo", ".bar") self.splitextTest("foo.boo.bar", "foo.boo", ".bar") self.splitextTest("foo.boo.biff.bar", "foo.boo.biff", ".bar") self.splitextTest(".csh.rc", ".csh", ".rc") self.splitextTest("nodots", "nodots", "") self.splitextTest(".cshrc", ".cshrc", "") self.splitextTest("...manydots", "...manydots", "") self.splitextTest("...manydots.ext", "...manydots", ".ext") self.splitextTest(".", ".", "") self.splitextTest("..", "..", "") self.splitextTest("........", "........", "") self.splitextTest("", "", "") def test_isabs(self): self.assertIs(posixpath.isabs(""), False) self.assertIs(posixpath.isabs("/"), True) self.assertIs(posixpath.isabs("/foo"), True) self.assertIs(posixpath.isabs("/foo/bar"), True) self.assertIs(posixpath.isabs("foo/bar"), False) self.assertIs(posixpath.isabs(b""), False) self.assertIs(posixpath.isabs(b"/"), True) self.assertIs(posixpath.isabs(b"/foo"), True) self.assertIs(posixpath.isabs(b"/foo/bar"), True) self.assertIs(posixpath.isabs(b"foo/bar"), False) def test_basename(self): self.assertEqual(posixpath.basename("/foo/bar"), "bar") self.assertEqual(posixpath.basename("/"), "") self.assertEqual(posixpath.basename("foo"), "foo") self.assertEqual(posixpath.basename("////foo"), "foo") self.assertEqual(posixpath.basename("//foo//bar"), "bar") self.assertEqual(posixpath.basename(b"/foo/bar"), b"bar") self.assertEqual(posixpath.basename(b"/"), b"") self.assertEqual(posixpath.basename(b"foo"), b"foo") self.assertEqual(posixpath.basename(b"////foo"), b"foo") self.assertEqual(posixpath.basename(b"//foo//bar"), b"bar") def test_dirname(self): self.assertEqual(posixpath.dirname("/foo/bar"), "/foo") self.assertEqual(posixpath.dirname("/"), "/") self.assertEqual(posixpath.dirname("foo"), "") self.assertEqual(posixpath.dirname("////foo"), "////") self.assertEqual(posixpath.dirname("//foo//bar"), "//foo") self.assertEqual(posixpath.dirname(b"/foo/bar"), b"/foo") self.assertEqual(posixpath.dirname(b"/"), b"/") self.assertEqual(posixpath.dirname(b"foo"), b"") self.assertEqual(posixpath.dirname(b"////foo"), b"////") self.assertEqual(posixpath.dirname(b"//foo//bar"), b"//foo") def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), False) with open(support.TESTFN + "1", "wb") as f: f.write(b"foo") self.assertIs(posixpath.islink(support.TESTFN + "1"), False) if support.can_symlink(): os.symlink(support.TESTFN + "1", support.TESTFN + "2") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) os.remove(support.TESTFN + "1") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) self.assertIs(posixpath.exists(support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), True) def test_ismount(self): self.assertIs(posixpath.ismount("/"), True) self.assertIs(posixpath.ismount(b"/"), True) def test_ismount_non_existent(self): # Non-existent mountpoint. self.assertIs(posixpath.ismount(ABSTFN), False) try: os.mkdir(ABSTFN) self.assertIs(posixpath.ismount(ABSTFN), False) finally: safe_rmdir(ABSTFN) @unittest.skipUnless(support.can_symlink(), "Test requires symlink support") def test_ismount_symlinks(self): # Symlinks are never mountpoints. try: os.symlink("/", ABSTFN) self.assertIs(posixpath.ismount(ABSTFN), False) finally: os.unlink(ABSTFN) @unittest.skipIf(posix is None, "Test requires posix module") def test_ismount_different_device(self): # Simulate the path being on a different device from its parent by # mocking out st_dev. save_lstat = os.lstat def fake_lstat(path): st_ino = 0 st_dev = 0 if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0)) try: os.lstat = fake_lstat self.assertIs(posixpath.ismount(ABSTFN), True) finally: os.lstat = save_lstat @unittest.skipIf(posix is None, "Test requires posix module") def test_ismount_directory_not_readable(self): # issue #2466: Simulate ismount run on a directory that is not # readable, which used to return False. save_lstat = os.lstat def fake_lstat(path): st_ino = 0 st_dev = 0 if path.startswith(ABSTFN) and path != ABSTFN: # ismount tries to read something inside the ABSTFN directory; # simulate this being forbidden (no read permission). raise OSError("Fake [Errno 13] Permission denied") if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0)) try: os.lstat = fake_lstat self.assertIs(posixpath.ismount(ABSTFN), True) finally: os.lstat = save_lstat def test_expanduser(self): self.assertEqual(posixpath.expanduser("foo"), "foo") self.assertEqual(posixpath.expanduser(b"foo"), b"foo") def test_expanduser_home_envvar(self): with support.EnvironmentVarGuard() as env: env['HOME'] = '/home/victor' self.assertEqual(posixpath.expanduser("~"), "/home/victor") # expanduser() strips trailing slash env['HOME'] = '/home/victor/' self.assertEqual(posixpath.expanduser("~"), "/home/victor") for home in '/', '', '//', '///': with self.subTest(home=home): env['HOME'] = home self.assertEqual(posixpath.expanduser("~"), "/") self.assertEqual(posixpath.expanduser("~/"), "/") self.assertEqual(posixpath.expanduser("~/foo"), "/foo") def test_expanduser_pwd(self): pwd = support.import_module('pwd') self.assertIsInstance(posixpath.expanduser("~/"), str) self.assertIsInstance(posixpath.expanduser(b"~/"), bytes) # if home directory == root directory, this test makes no sense if posixpath.expanduser("~") != '/': self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") ) self.assertEqual( posixpath.expanduser(b"~") + b"/", posixpath.expanduser(b"~/") ) self.assertIsInstance(posixpath.expanduser("~root/"), str) self.assertIsInstance(posixpath.expanduser("~foo/"), str) self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes) self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes) with support.EnvironmentVarGuard() as env: # expanduser should fall back to using the password database del env['HOME'] home = pwd.getpwuid(os.getuid()).pw_dir # $HOME can end with a trailing /, so strip it (see #17809) home = home.rstrip("/") or '/' self.assertEqual(posixpath.expanduser("~"), home) # bpo-10496: If the HOME environment variable is not set and the # user (current identifier or name in the path) doesn't exist in # the password database (pwd.getuid() or pwd.getpwnam() fail), # expanduser() must return the path unchanged. with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError), \ mock.patch.object(pwd, 'getpwnam', side_effect=KeyError): for path in ('~', '~/.local', '~vstinner/'): self.assertEqual(posixpath.expanduser(path), path) def test_normpath(self): self.assertEqual(posixpath.normpath(""), ".") self.assertEqual(posixpath.normpath("/"), "/") self.assertEqual(posixpath.normpath("//"), "//") self.assertEqual(posixpath.normpath("///"), "/") self.assertEqual(posixpath.normpath("///foo/.//bar//"), "/foo/bar") self.assertEqual(posixpath.normpath("///foo/.//bar//.//..//.//baz"), "/foo/baz") self.assertEqual(posixpath.normpath("///..//./foo/.//bar"), "/foo/bar") self.assertEqual(posixpath.normpath(b""), b".") self.assertEqual(posixpath.normpath(b"/"), b"/") self.assertEqual(posixpath.normpath(b"//"), b"//") self.assertEqual(posixpath.normpath(b"///"), b"/") self.assertEqual(posixpath.normpath(b"///foo/.//bar//"), b"/foo/bar") self.assertEqual(posixpath.normpath(b"///foo/.//bar//.//..//.//baz"), b"/foo/baz") self.assertEqual(posixpath.normpath(b"///..//./foo/.//bar"), b"/foo/bar") @skip_if_ABSTFN_contains_backslash def test_realpath_curdir(self): self.assertEqual(realpath('.'), os.getcwd()) self.assertEqual(realpath('./.'), os.getcwd()) self.assertEqual(realpath('/'.join(['.'] * 100)), os.getcwd()) self.assertEqual(realpath(b'.'), os.getcwdb()) self.assertEqual(realpath(b'./.'), os.getcwdb()) self.assertEqual(realpath(b'/'.join([b'.'] * 100)), os.getcwdb()) @skip_if_ABSTFN_contains_backslash def test_realpath_pardir(self): self.assertEqual(realpath('..'), dirname(os.getcwd())) self.assertEqual(realpath('../..'), dirname(dirname(os.getcwd()))) self.assertEqual(realpath('/'.join(['..'] * 100)), '/') self.assertEqual(realpath(b'..'), dirname(os.getcwdb())) self.assertEqual(realpath(b'../..'), dirname(dirname(os.getcwdb()))) self.assertEqual(realpath(b'/'.join([b'..'] * 100)), b'/') @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_basic(self): # Basic operation. try: os.symlink(ABSTFN+"1", ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN+"1") finally: support.unlink(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_relative(self): try: os.symlink(posixpath.relpath(ABSTFN+"1"), ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN+"1") finally: support.unlink(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_symlink_loops(self): # Bug #930024, return the path unchanged if we get into an infinite # symlink loop. try: os.symlink(ABSTFN, ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN) os.symlink(ABSTFN+"1", ABSTFN+"2") os.symlink(ABSTFN+"2", ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2") self.assertEqual(realpath(ABSTFN+"1/x"), ABSTFN+"1/x") self.assertEqual(realpath(ABSTFN+"1/.."), dirname(ABSTFN)) self.assertEqual(realpath(ABSTFN+"1/../x"), dirname(ABSTFN) + "/x") os.symlink(ABSTFN+"x", ABSTFN+"y") self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "y"), ABSTFN + "y") self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "1"), ABSTFN + "1") os.symlink(basename(ABSTFN) + "a/b", ABSTFN+"a") self.assertEqual(realpath(ABSTFN+"a"), ABSTFN+"a/b") os.symlink("../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) + "c", ABSTFN+"c") self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c") # Test using relative path as well. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN)), ABSTFN) finally: support.unlink(ABSTFN) support.unlink(ABSTFN+"1") support.unlink(ABSTFN+"2") support.unlink(ABSTFN+"y") support.unlink(ABSTFN+"c") support.unlink(ABSTFN+"a") @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_repeated_indirect_symlinks(self): # Issue #6975. try: os.mkdir(ABSTFN) os.symlink('../' + basename(ABSTFN), ABSTFN + '/self') os.symlink('self/self/self', ABSTFN + '/link') self.assertEqual(realpath(ABSTFN + '/link'), ABSTFN) finally: support.unlink(ABSTFN + '/self') support.unlink(ABSTFN + '/link') safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_deep_recursion(self): depth = 10 try: os.mkdir(ABSTFN) for i in range(depth): os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1)) os.symlink('.', ABSTFN + '/0') self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN) # Test using relative path as well. with support.change_cwd(ABSTFN): self.assertEqual(realpath('%d' % depth), ABSTFN) finally: for i in range(depth + 1): support.unlink(ABSTFN + '/%d' % i) safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_parents(self): # We also need to resolve any symlinks in the parents of a relative # path passed to realpath. E.g.: current working directory is # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call # realpath("a"). This should return /usr/share/doc/a/. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/y") os.symlink(ABSTFN + "/y", ABSTFN + "/k") with support.change_cwd(ABSTFN + "/k"): self.assertEqual(realpath("a"), ABSTFN + "/y/a") finally: support.unlink(ABSTFN + "/k") safe_rmdir(ABSTFN + "/y") safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN) @unittest.skipUnless(hasattr(os, "symlink"), "Missing symlink implementation") @skip_if_ABSTFN_contains_backslash def test_realpath_resolve_first(self): # Bug #1213894: The first component of the path, if not absolute, # must be resolved too. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.symlink(ABSTFN, ABSTFN + "link") with support.change_cwd(dirname(ABSTFN)): base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k") finally: support.unlink(ABSTFN + "link") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN) def test_relpath(self): (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar") try: curdir = os.path.split(os.getcwd())[-1] self.assertRaises(ValueError, posixpath.relpath, "") self.assertEqual(posixpath.relpath("a"), "a") self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a") self.assertEqual(posixpath.relpath("a/b"), "a/b") self.assertEqual(posixpath.relpath("../a/b"), "../a/b") self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a") self.assertEqual(posixpath.relpath("a/b", "../c"), "../"+curdir+"/a/b") self.assertEqual(posixpath.relpath("a", "b/c"), "../../a") self.assertEqual(posixpath.relpath("a", "a"), ".") self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x/y/z"), '../../../foo/bar/bat') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/foo/bar"), 'bat') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/"), 'foo/bar/bat') self.assertEqual(posixpath.relpath("/", "/foo/bar/bat"), '../../..') self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x"), '../foo/bar/bat') self.assertEqual(posixpath.relpath("/x", "/foo/bar/bat"), '../../../x') self.assertEqual(posixpath.relpath("/", "/"), '.') self.assertEqual(posixpath.relpath("/a", "/a"), '.') self.assertEqual(posixpath.relpath("/a/b", "/a/b"), '.') finally: os.getcwd = real_getcwd def test_relpath_bytes(self): (real_getcwdb, os.getcwdb) = (os.getcwdb, lambda: br"/home/user/bar") try: curdir = os.path.split(os.getcwdb())[-1] self.assertRaises(ValueError, posixpath.relpath, b"") self.assertEqual(posixpath.relpath(b"a"), b"a") self.assertEqual(posixpath.relpath(posixpath.abspath(b"a")), b"a") self.assertEqual(posixpath.relpath(b"a/b"), b"a/b") self.assertEqual(posixpath.relpath(b"../a/b"), b"../a/b") self.assertEqual(posixpath.relpath(b"a", b"../b"), b"../"+curdir+b"/a") self.assertEqual(posixpath.relpath(b"a/b", b"../c"), b"../"+curdir+b"/a/b") self.assertEqual(posixpath.relpath(b"a", b"b/c"), b"../../a") self.assertEqual(posixpath.relpath(b"a", b"a"), b".") self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x/y/z"), b'../../../foo/bar/bat') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/foo/bar"), b'bat') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/"), b'foo/bar/bat') self.assertEqual(posixpath.relpath(b"/", b"/foo/bar/bat"), b'../../..') self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x"), b'../foo/bar/bat') self.assertEqual(posixpath.relpath(b"/x", b"/foo/bar/bat"), b'../../../x') self.assertEqual(posixpath.relpath(b"/", b"/"), b'.') self.assertEqual(posixpath.relpath(b"/a", b"/a"), b'.') self.assertEqual(posixpath.relpath(b"/a/b", b"/a/b"), b'.') self.assertRaises(TypeError, posixpath.relpath, b"bytes", "str") self.assertRaises(TypeError, posixpath.relpath, "str", b"bytes") finally: os.getcwdb = real_getcwdb def test_commonpath(self): def check(paths, expected): self.assertEqual(posixpath.commonpath(paths), expected) self.assertEqual(posixpath.commonpath([os.fsencode(p) for p in paths]), os.fsencode(expected)) def check_error(exc, paths): self.assertRaises(exc, posixpath.commonpath, paths) self.assertRaises(exc, posixpath.commonpath, [os.fsencode(p) for p in paths]) self.assertRaises(ValueError, posixpath.commonpath, []) check_error(ValueError, ['/usr', 'usr']) check_error(ValueError, ['usr', '/usr']) check(['/usr/local'], '/usr/local') check(['/usr/local', '/usr/local'], '/usr/local') check(['/usr/local/', '/usr/local'], '/usr/local') check(['/usr/local/', '/usr/local/'], '/usr/local') check(['/usr//local', '//usr/local'], '/usr/local') check(['/usr/./local', '/./usr/local'], '/usr/local') check(['/', '/dev'], '/') check(['/usr', '/dev'], '/') check(['/usr/lib/', '/usr/lib/python3'], '/usr/lib') check(['/usr/lib/', '/usr/lib64/'], '/usr') check(['/usr/lib', '/usr/lib64'], '/usr') check(['/usr/lib/', '/usr/lib64'], '/usr') check(['spam'], 'spam') check(['spam', 'spam'], 'spam') check(['spam', 'alot'], '') check(['and/jam', 'and/spam'], 'and') check(['and//jam', 'and/spam//'], 'and') check(['and/./jam', './and/spam'], 'and') check(['and/jam', 'and/spam', 'alot'], '') check(['and/jam', 'and/spam', 'and'], 'and') check([''], '') check(['', 'spam/alot'], '') check_error(ValueError, ['', '/spam/alot']) self.assertRaises(TypeError, posixpath.commonpath, [b'/usr/lib/', '/usr/lib/python3']) self.assertRaises(TypeError, posixpath.commonpath, [b'/usr/lib/', 'usr/lib/python3']) self.assertRaises(TypeError, posixpath.commonpath, [b'usr/lib/', '/usr/lib/python3']) self.assertRaises(TypeError, posixpath.commonpath, ['/usr/lib/', b'/usr/lib/python3']) self.assertRaises(TypeError, posixpath.commonpath, ['/usr/lib/', b'usr/lib/python3']) self.assertRaises(TypeError, posixpath.commonpath, ['usr/lib/', b'/usr/lib/python3']) class PosixCommonTest(test_genericpath.CommonTest, unittest.TestCase): pathmodule = posixpath attributes = ['relpath', 'samefile', 'sameopenfile', 'samestat'] class PathLikeTests(unittest.TestCase): path = posixpath def setUp(self): self.file_name = support.TESTFN.lower() self.file_path = FakePath(support.TESTFN) self.addCleanup(support.unlink, self.file_name) with open(self.file_name, 'xb', 0) as file: file.write(b"test_posixpath.PathLikeTests") def assertPathEqual(self, func): self.assertEqual(func(self.file_path), func(self.file_name)) def test_path_normcase(self): self.assertPathEqual(self.path.normcase) def test_path_isabs(self): self.assertPathEqual(self.path.isabs) def test_path_join(self): self.assertEqual(self.path.join('a', FakePath('b'), 'c'), self.path.join('a', 'b', 'c')) def test_path_split(self): self.assertPathEqual(self.path.split) def test_path_splitext(self): self.assertPathEqual(self.path.splitext) def test_path_splitdrive(self): self.assertPathEqual(self.path.splitdrive) def test_path_basename(self): self.assertPathEqual(self.path.basename) def test_path_dirname(self): self.assertPathEqual(self.path.dirname) def test_path_islink(self): self.assertPathEqual(self.path.islink) def test_path_lexists(self): self.assertPathEqual(self.path.lexists) def test_path_ismount(self): self.assertPathEqual(self.path.ismount) def test_path_expanduser(self): self.assertPathEqual(self.path.expanduser) def test_path_expandvars(self): self.assertPathEqual(self.path.expandvars) def test_path_normpath(self): self.assertPathEqual(self.path.normpath) def test_path_abspath(self): self.assertPathEqual(self.path.abspath) def test_path_realpath(self): self.assertPathEqual(self.path.realpath) def test_path_relpath(self): self.assertPathEqual(self.path.relpath) def test_path_commonpath(self): common_path = self.path.commonpath([self.file_path, self.file_name]) self.assertEqual(common_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/pydocfodder.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/pydocfodder.py
"""Something just to look at via pydoc.""" import types class A_classic: "A classic class." def A_method(self): "Method defined in A." def AB_method(self): "Method defined in A and B." def AC_method(self): "Method defined in A and C." def AD_method(self): "Method defined in A and D." def ABC_method(self): "Method defined in A, B and C." def ABD_method(self): "Method defined in A, B and D." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." class B_classic(A_classic): "A classic class, derived from A_classic." def AB_method(self): "Method defined in A and B." def ABC_method(self): "Method defined in A, B and C." def ABD_method(self): "Method defined in A, B and D." def ABCD_method(self): "Method defined in A, B, C and D." def B_method(self): "Method defined in B." def BC_method(self): "Method defined in B and C." def BD_method(self): "Method defined in B and D." def BCD_method(self): "Method defined in B, C and D." class C_classic(A_classic): "A classic class, derived from A_classic." def AC_method(self): "Method defined in A and C." def ABC_method(self): "Method defined in A, B and C." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." def BC_method(self): "Method defined in B and C." def BCD_method(self): "Method defined in B, C and D." def C_method(self): "Method defined in C." def CD_method(self): "Method defined in C and D." class D_classic(B_classic, C_classic): "A classic class, derived from B_classic and C_classic." def AD_method(self): "Method defined in A and D." def ABD_method(self): "Method defined in A, B and D." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." def BD_method(self): "Method defined in B and D." def BCD_method(self): "Method defined in B, C and D." def CD_method(self): "Method defined in C and D." def D_method(self): "Method defined in D." class A_new(object): "A new-style class." def A_method(self): "Method defined in A." def AB_method(self): "Method defined in A and B." def AC_method(self): "Method defined in A and C." def AD_method(self): "Method defined in A and D." def ABC_method(self): "Method defined in A, B and C." def ABD_method(self): "Method defined in A, B and D." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." def A_classmethod(cls, x): "A class method defined in A." A_classmethod = classmethod(A_classmethod) def A_staticmethod(): "A static method defined in A." A_staticmethod = staticmethod(A_staticmethod) def _getx(self): "A property getter function." def _setx(self, value): "A property setter function." def _delx(self): "A property deleter function." A_property = property(fdel=_delx, fget=_getx, fset=_setx, doc="A sample property defined in A.") A_int_alias = int class B_new(A_new): "A new-style class, derived from A_new." def AB_method(self): "Method defined in A and B." def ABC_method(self): "Method defined in A, B and C." def ABD_method(self): "Method defined in A, B and D." def ABCD_method(self): "Method defined in A, B, C and D." def B_method(self): "Method defined in B." def BC_method(self): "Method defined in B and C." def BD_method(self): "Method defined in B and D." def BCD_method(self): "Method defined in B, C and D." class C_new(A_new): "A new-style class, derived from A_new." def AC_method(self): "Method defined in A and C." def ABC_method(self): "Method defined in A, B and C." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." def BC_method(self): "Method defined in B and C." def BCD_method(self): "Method defined in B, C and D." def C_method(self): "Method defined in C." def CD_method(self): "Method defined in C and D." class D_new(B_new, C_new): """A new-style class, derived from B_new and C_new. """ def AD_method(self): "Method defined in A and D." def ABD_method(self): "Method defined in A, B and D." def ACD_method(self): "Method defined in A, C and D." def ABCD_method(self): "Method defined in A, B, C and D." def BD_method(self): "Method defined in B and D." def BCD_method(self): "Method defined in B, C and D." def CD_method(self): "Method defined in C and D." def D_method(self): "Method defined in D." class FunkyProperties(object): """From SF bug 472347, by Roeland Rengelink. Property getters etc may not be vanilla functions or methods, and this used to make GUI pydoc blow up. """ def __init__(self): self.desc = {'x':0} class get_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst): print('Get called', self, inst) return inst.desc[self.attr] class set_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst, val): print('Set called', self, inst, val) inst.desc[self.attr] = val class del_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst): print('Del called', self, inst) del inst.desc[self.attr] x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x') submodule = types.ModuleType(__name__ + '.submodule', """A submodule, which should appear in its parent's summary""")
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_devpoll.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_devpoll.py
# Test case for the select.devpoll() function # Initial tests are copied as is from "test_poll.py" import os import random import select import unittest from test.support import run_unittest, cpython_only if not hasattr(select, 'devpoll') : raise unittest.SkipTest('test works only on Solaris OS family') def find_ready_matching(ready, flag): match = [] for fd, mode in ready: if mode & flag: match.append(fd) return match class DevPollTests(unittest.TestCase): def test_devpoll1(self): # Basic functional test of poll object # Create a bunch of pipe and test that poll works with them. p = select.devpoll() NUM_PIPES = 12 MSG = b" This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_PIPES): rd, wr = os.pipe() p.register(rd) p.modify(rd, select.POLLIN) p.register(wr, select.POLLOUT) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd bufs = [] while writers: ready = p.poll() ready_writers = find_ready_matching(ready, select.POLLOUT) if not ready_writers: self.fail("no pipes ready for writing") wr = random.choice(ready_writers) os.write(wr, MSG) ready = p.poll() ready_readers = find_ready_matching(ready, select.POLLIN) if not ready_readers: self.fail("no pipes ready for reading") self.assertEqual([w2r[wr]], ready_readers) rd = ready_readers[0] buf = os.read(rd, MSG_LEN) self.assertEqual(len(buf), MSG_LEN) bufs.append(buf) os.close(r2w[rd]) ; os.close(rd) p.unregister(r2w[rd]) p.unregister(rd) writers.remove(r2w[rd]) self.assertEqual(bufs, [MSG] * NUM_PIPES) def test_timeout_overflow(self): pollster = select.devpoll() w, r = os.pipe() pollster.register(w) pollster.poll(-1) self.assertRaises(OverflowError, pollster.poll, -2) self.assertRaises(OverflowError, pollster.poll, -1 << 31) self.assertRaises(OverflowError, pollster.poll, -1 << 64) pollster.poll(0) pollster.poll(1) pollster.poll(1 << 30) self.assertRaises(OverflowError, pollster.poll, 1 << 31) self.assertRaises(OverflowError, pollster.poll, 1 << 63) self.assertRaises(OverflowError, pollster.poll, 1 << 64) def test_close(self): open_file = open(__file__, "rb") self.addCleanup(open_file.close) fd = open_file.fileno() devpoll = select.devpoll() # test fileno() method and closed attribute self.assertIsInstance(devpoll.fileno(), int) self.assertFalse(devpoll.closed) # test close() devpoll.close() self.assertTrue(devpoll.closed) self.assertRaises(ValueError, devpoll.fileno) # close() can be called more than once devpoll.close() # operations must fail with ValueError("I/O operation on closed ...") self.assertRaises(ValueError, devpoll.modify, fd, select.POLLIN) self.assertRaises(ValueError, devpoll.poll) self.assertRaises(ValueError, devpoll.register, fd, fd, select.POLLIN) self.assertRaises(ValueError, devpoll.unregister, fd) def test_fd_non_inheritable(self): devpoll = select.devpoll() self.addCleanup(devpoll.close) self.assertEqual(os.get_inheritable(devpoll.fileno()), False) def test_events_mask_overflow(self): pollster = select.devpoll() w, r = os.pipe() pollster.register(w) # Issue #17919 self.assertRaises(OverflowError, pollster.register, 0, -1) self.assertRaises(OverflowError, pollster.register, 0, 1 << 64) self.assertRaises(OverflowError, pollster.modify, 1, -1) self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64) @cpython_only def test_events_mask_overflow_c_limits(self): from _testcapi import USHRT_MAX pollster = select.devpoll() w, r = os.pipe() pollster.register(w) # Issue #17919 self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) def test_main(): run_unittest(DevPollTests) 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_largefile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_largefile.py
"""Test largefile support on system where this makes sense. """ import os import stat import sys import unittest from test.support import TESTFN, requires, unlink, bigmemtest import io # C implementation of io import _pyio as pyio # Python implementation of io # size of file to create (>2 GiB; 2 GiB == 2,147,483,648 bytes) size = 2_500_000_000 class LargeFileTest: """Test that each file function works as expected for large (i.e. > 2 GiB) files. """ def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return if current_size == 0: f.write(b'z') f.seek(0) f.seek(size) f.write(b'a') f.flush() self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1) @classmethod def tearDownClass(cls): with cls.open(TESTFN, 'wb'): pass if not os.stat(TESTFN)[stat.ST_SIZE] == 0: raise cls.failureException('File was not truncated by opening ' 'with mode "wb"') # _pyio.FileIO.readall() uses a temporary bytearray then casted to bytes, # so memuse=2 is needed @bigmemtest(size=size, memuse=2, dry_run=False) def test_large_read(self, _size): # bpo-24658: Test that a read greater than 2GB does not fail. with self.open(TESTFN, "rb") as f: self.assertEqual(len(f.read()), size + 1) self.assertEqual(f.tell(), size + 1) def test_osstat(self): self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1) def test_seek_read(self): with self.open(TESTFN, 'rb') as f: self.assertEqual(f.tell(), 0) self.assertEqual(f.read(1), b'z') self.assertEqual(f.tell(), 1) f.seek(0) self.assertEqual(f.tell(), 0) f.seek(0, 0) self.assertEqual(f.tell(), 0) f.seek(42) self.assertEqual(f.tell(), 42) f.seek(42, 0) self.assertEqual(f.tell(), 42) f.seek(42, 1) self.assertEqual(f.tell(), 84) f.seek(0, 1) self.assertEqual(f.tell(), 84) f.seek(0, 2) # seek from the end self.assertEqual(f.tell(), size + 1 + 0) f.seek(-10, 2) self.assertEqual(f.tell(), size + 1 - 10) f.seek(-size-1, 2) self.assertEqual(f.tell(), 0) f.seek(size) self.assertEqual(f.tell(), size) # the 'a' that was written at the end of file above self.assertEqual(f.read(1), b'a') f.seek(-size-1, 1) self.assertEqual(f.read(1), b'z') self.assertEqual(f.tell(), 1) def test_lseek(self): with self.open(TESTFN, 'rb') as f: self.assertEqual(os.lseek(f.fileno(), 0, 0), 0) self.assertEqual(os.lseek(f.fileno(), 42, 0), 42) self.assertEqual(os.lseek(f.fileno(), 42, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 2), size+1+0) self.assertEqual(os.lseek(f.fileno(), -10, 2), size+1-10) self.assertEqual(os.lseek(f.fileno(), -size-1, 2), 0) self.assertEqual(os.lseek(f.fileno(), size, 0), size) # the 'a' that was written at the end of file above self.assertEqual(f.read(1), b'a') def test_truncate(self): with self.open(TESTFN, 'r+b') as f: if not hasattr(f, 'truncate'): raise unittest.SkipTest("open().truncate() not available " "on this system") f.seek(0, 2) # else we've lost track of the true size self.assertEqual(f.tell(), size+1) # Cut it back via seek + truncate with no argument. newsize = size - 10 f.seek(newsize) f.truncate() self.assertEqual(f.tell(), newsize) # else pointer moved f.seek(0, 2) self.assertEqual(f.tell(), newsize) # else wasn't truncated # Ensure that truncate(smaller than true size) shrinks # the file. newsize -= 1 f.seek(42) f.truncate(newsize) self.assertEqual(f.tell(), 42) f.seek(0, 2) self.assertEqual(f.tell(), newsize) # XXX truncate(larger than true size) is ill-defined # across platform; cut it waaaaay back f.seek(0) f.truncate(1) self.assertEqual(f.tell(), 0) # else pointer moved f.seek(0) self.assertEqual(len(f.read()), 1) # else wasn't truncated def test_seekable(self): # Issue #5016; seekable() can return False when the current position # is negative when truncated to an int. for pos in (2**31-1, 2**31, 2**31+1): with self.open(TESTFN, 'rb') as f: f.seek(pos) self.assertTrue(f.seekable()) def setUpModule(): try: import signal # The default handler for SIGXFSZ is to abort the process. # By ignoring it, system calls exceeding the file size resource # limit will raise OSError instead of crashing the interpreter. signal.signal(signal.SIGXFSZ, signal.SIG_IGN) except (ImportError, AttributeError): pass # On Windows and Mac OSX this test consumes large resources; It # takes a long time to build the >2 GiB file and takes >2 GiB of disk # space therefore the resource must be enabled to run this test. # If not, nothing after this line stanza will be executed. if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(size)) else: # Only run if the current filesystem supports large files. # (Skip this test on Windows, since we now always support # large files.) f = open(TESTFN, 'wb', buffering=0) try: # 2**31 == 2147483648 f.seek(2147483649) # Seeking is not enough of a test: you must write and flush, too! f.write(b'x') f.flush() except (OSError, OverflowError): raise unittest.SkipTest("filesystem does not have " "largefile support") finally: f.close() unlink(TESTFN) class CLargeFileTest(LargeFileTest, unittest.TestCase): open = staticmethod(io.open) class PyLargeFileTest(LargeFileTest, unittest.TestCase): open = staticmethod(pyio.open) def tearDownModule(): unlink(TESTFN) 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_iterlen.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_iterlen.py
""" Test Iterator Length Transparency Some functions or methods which accept general iterable arguments have optional, more efficient code paths if they know how many items to expect. For instance, map(func, iterable), will pre-allocate the exact amount of space required whenever the iterable can report its length. The desired invariant is: len(it)==len(list(it)). A complication is that an iterable and iterator can be the same object. To maintain the invariant, an iterator needs to dynamically update its length. For instance, an iterable such as range(10) always reports its length as ten, but it=iter(range(10)) starts at ten, and then goes to nine after next(it). Having this capability means that map() can ignore the distinction between map(func, iterable) and map(func, iter(iterable)). When the iterable is immutable, the implementation can straight-forwardly report the original length minus the cumulative number of calls to next(). This is the case for tuples, range objects, and itertools.repeat(). Some containers become temporarily immutable during iteration. This includes dicts, sets, and collections.deque. Their implementation is equally simple though they need to permanently set their length to zero whenever there is an attempt to iterate after a length mutation. The situation slightly more involved whenever an object allows length mutation during iteration. Lists and sequence iterators are dynamically updatable. So, if a list is extended during iteration, the iterator will continue through the new items. If it shrinks to a point before the most recent iteration, then no further items are available and the length is reported at zero. Reversed objects can also be wrapped around mutable objects; however, any appends after the current position are ignored. Any other approach leads to confusion and possibly returning the same item more than once. The iterators not listed above, such as enumerate and the other itertools, are not length transparent because they have no way to distinguish between iterables that report static length and iterators whose length changes with each call (i.e. the difference between enumerate('abc') and enumerate(iter('abc')). """ import unittest from itertools import repeat from collections import deque from operator import length_hint n = 10 class TestInvariantWithoutMutations: def test_invariant(self): it = self.it for i in reversed(range(1, n+1)): self.assertEqual(length_hint(it), i) next(it) self.assertEqual(length_hint(it), 0) self.assertRaises(StopIteration, next, it) self.assertEqual(length_hint(it), 0) class TestTemporarilyImmutable(TestInvariantWithoutMutations): def test_immutable_during_iteration(self): # objects such as deques, sets, and dictionaries enforce # length immutability during iteration it = self.it self.assertEqual(length_hint(it), n) next(it) self.assertEqual(length_hint(it), n-1) self.mutate() self.assertRaises(RuntimeError, next, it) self.assertEqual(length_hint(it), 0) ## ------- Concrete Type Tests ------- class TestRepeat(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = repeat(None, n) class TestXrange(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = iter(range(n)) class TestXrangeCustomReversed(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = reversed(range(n)) class TestTuple(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = iter(tuple(range(n))) ## ------- Types that should not be mutated during iteration ------- class TestDeque(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = deque(range(n)) self.it = iter(d) self.mutate = d.pop class TestDequeReversed(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = deque(range(n)) self.it = reversed(d) self.mutate = d.pop class TestDictKeys(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = dict.fromkeys(range(n)) self.it = iter(d) self.mutate = d.popitem class TestDictItems(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = dict.fromkeys(range(n)) self.it = iter(d.items()) self.mutate = d.popitem class TestDictValues(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = dict.fromkeys(range(n)) self.it = iter(d.values()) self.mutate = d.popitem class TestSet(TestTemporarilyImmutable, unittest.TestCase): def setUp(self): d = set(range(n)) self.it = iter(d) self.mutate = d.pop ## ------- Types that can mutate during iteration ------- class TestList(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = iter(range(n)) def test_mutation(self): d = list(range(n)) it = iter(d) next(it) next(it) self.assertEqual(length_hint(it), n - 2) d.append(n) self.assertEqual(length_hint(it), n - 1) # grow with append d[1:] = [] self.assertEqual(length_hint(it), 0) self.assertEqual(list(it), []) d.extend(range(20)) self.assertEqual(length_hint(it), 0) class TestListReversed(TestInvariantWithoutMutations, unittest.TestCase): def setUp(self): self.it = reversed(range(n)) def test_mutation(self): d = list(range(n)) it = reversed(d) next(it) next(it) self.assertEqual(length_hint(it), n - 2) d.append(n) self.assertEqual(length_hint(it), n - 2) # ignore append d[1:] = [] self.assertEqual(length_hint(it), 0) self.assertEqual(list(it), []) # confirm invariant d.extend(range(20)) self.assertEqual(length_hint(it), 0) ## -- Check to make sure exceptions are not suppressed by __length_hint__() class BadLen(object): def __iter__(self): return iter(range(10)) def __len__(self): raise RuntimeError('hello') class BadLengthHint(object): def __iter__(self): return iter(range(10)) def __length_hint__(self): raise RuntimeError('hello') class NoneLengthHint(object): def __iter__(self): return iter(range(10)) def __length_hint__(self): return NotImplemented class TestLengthHintExceptions(unittest.TestCase): def test_issue1242657(self): self.assertRaises(RuntimeError, list, BadLen()) self.assertRaises(RuntimeError, list, BadLengthHint()) self.assertRaises(RuntimeError, [].extend, BadLen()) self.assertRaises(RuntimeError, [].extend, BadLengthHint()) b = bytearray(range(10)) self.assertRaises(RuntimeError, b.extend, BadLen()) self.assertRaises(RuntimeError, b.extend, BadLengthHint()) def test_invalid_hint(self): # Make sure an invalid result doesn't muck-up the works self.assertEqual(list(NoneLengthHint()), list(range(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_frame.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_frame.py
import re import types import unittest import weakref from test import support class ClearTest(unittest.TestCase): """ Tests for frame.clear(). """ def inner(self, x=5, **kwargs): 1/0 def outer(self, **kwargs): try: self.inner(**kwargs) except ZeroDivisionError as e: exc = e return exc def clear_traceback_frames(self, tb): """ Clear all frames in a traceback. """ while tb is not None: tb.tb_frame.clear() tb = tb.tb_next def test_clear_locals(self): class C: pass c = C() wr = weakref.ref(c) exc = self.outer(c=c) del c support.gc_collect() # A reference to c is held through the frames self.assertIsNot(None, wr()) self.clear_traceback_frames(exc.__traceback__) support.gc_collect() # The reference was released by .clear() self.assertIs(None, wr()) def test_clear_generator(self): endly = False def g(): nonlocal endly try: yield inner() finally: endly = True gen = g() next(gen) self.assertFalse(endly) # Clearing the frame closes the generator gen.gi_frame.clear() self.assertTrue(endly) def test_clear_executing(self): # Attempting to clear an executing frame is forbidden. try: 1/0 except ZeroDivisionError as e: f = e.__traceback__.tb_frame with self.assertRaises(RuntimeError): f.clear() with self.assertRaises(RuntimeError): f.f_back.clear() def test_clear_executing_generator(self): # Attempting to clear an executing generator frame is forbidden. endly = False def g(): nonlocal endly try: 1/0 except ZeroDivisionError as e: f = e.__traceback__.tb_frame with self.assertRaises(RuntimeError): f.clear() with self.assertRaises(RuntimeError): f.f_back.clear() yield f finally: endly = True gen = g() f = next(gen) self.assertFalse(endly) # Clearing the frame closes the generator f.clear() self.assertTrue(endly) @support.cpython_only def test_clear_refcycles(self): # .clear() doesn't leave any refcycle behind with support.disable_gc(): class C: pass c = C() wr = weakref.ref(c) exc = self.outer(c=c) del c self.assertIsNot(None, wr()) self.clear_traceback_frames(exc.__traceback__) self.assertIs(None, wr()) class FrameAttrsTest(unittest.TestCase): def make_frames(self): def outer(): x = 5 y = 6 def inner(): z = x + 2 1/0 t = 9 return inner() try: outer() except ZeroDivisionError as e: tb = e.__traceback__ frames = [] while tb: frames.append(tb.tb_frame) tb = tb.tb_next return frames def test_locals(self): f, outer, inner = self.make_frames() outer_locals = outer.f_locals self.assertIsInstance(outer_locals.pop('inner'), types.FunctionType) self.assertEqual(outer_locals, {'x': 5, 'y': 6}) inner_locals = inner.f_locals self.assertEqual(inner_locals, {'x': 5, 'z': 7}) def test_clear_locals(self): # Test f_locals after clear() (issue #21897) f, outer, inner = self.make_frames() outer.clear() inner.clear() self.assertEqual(outer.f_locals, {}) self.assertEqual(inner.f_locals, {}) def test_locals_clear_locals(self): # Test f_locals before and after clear() (to exercise caching) f, outer, inner = self.make_frames() outer.f_locals inner.f_locals outer.clear() inner.clear() self.assertEqual(outer.f_locals, {}) self.assertEqual(inner.f_locals, {}) def test_f_lineno_del_segfault(self): f, _, _ = self.make_frames() with self.assertRaises(AttributeError): del f.f_lineno class ReprTest(unittest.TestCase): """ Tests for repr(frame). """ def test_repr(self): def outer(): x = 5 y = 6 def inner(): z = x + 2 1/0 t = 9 return inner() offset = outer.__code__.co_firstlineno try: outer() except ZeroDivisionError as e: tb = e.__traceback__ frames = [] while tb: frames.append(tb.tb_frame) tb = tb.tb_next else: self.fail("should have raised") f_this, f_outer, f_inner = frames file_repr = re.escape(repr(__file__)) self.assertRegex(repr(f_this), r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code test_repr>$" % (file_repr, offset + 23)) self.assertRegex(repr(f_outer), r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code outer>$" % (file_repr, offset + 7)) self.assertRegex(repr(f_inner), r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code inner>$" % (file_repr, offset + 5)) 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/pyclbr_input.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/pyclbr_input.py
"""Test cases for test_pyclbr.py""" def f(): pass class Other(object): @classmethod def foo(c): pass def om(self): pass class B (object): def bm(self): pass class C (B): foo = Other().foo om = Other.om d = 10 # XXX: This causes test_pyclbr.py to fail, but only because the # introspection-based is_method() code in the test can't # distinguish between this and a genuine method function like m(). # The pyclbr.py module gets this right as it parses the text. # #f = f def m(self): pass @staticmethod def sm(self): pass @classmethod def cm(self): pass
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_sax.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sax.py
# regression test for SAX 2.0 # $Id$ from xml.sax import make_parser, ContentHandler, \ SAXException, SAXReaderNotAvailable, SAXParseException import unittest from unittest import mock try: make_parser() except SAXReaderNotAvailable: # don't try to test this module if we cannot create a parser raise unittest.SkipTest("no XML parsers available") from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \ XMLFilterBase, prepare_input_source from xml.sax.expatreader import create_parser from xml.sax.handler import feature_namespaces, feature_external_ges from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl from io import BytesIO, StringIO import codecs import gc import os.path import shutil from urllib.error import URLError from test import support from test.support import findfile, run_unittest, TESTFN TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata") TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata") try: TEST_XMLFILE.encode("utf-8") TEST_XMLFILE_OUT.encode("utf-8") except UnicodeEncodeError: raise unittest.SkipTest("filename is not encodable to utf8") supports_nonascii_filenames = True if not os.path.supports_unicode_filenames: try: support.TESTFN_UNICODE.encode(support.TESTFN_ENCODING) except (UnicodeError, TypeError): # Either the file system encoding is None, or the file name # cannot be encoded in the file system encoding. supports_nonascii_filenames = False requires_nonascii_filenames = unittest.skipUnless( supports_nonascii_filenames, 'Requires non-ascii filenames support') ns_uri = "http://www.python.org/xml-ns/saxtest/" class XmlTestBase(unittest.TestCase): def verify_empty_attrs(self, attrs): self.assertRaises(KeyError, attrs.getValue, "attr") self.assertRaises(KeyError, attrs.getValueByQName, "attr") self.assertRaises(KeyError, attrs.getNameByQName, "attr") self.assertRaises(KeyError, attrs.getQNameByName, "attr") self.assertRaises(KeyError, attrs.__getitem__, "attr") self.assertEqual(attrs.getLength(), 0) self.assertEqual(attrs.getNames(), []) self.assertEqual(attrs.getQNames(), []) self.assertEqual(len(attrs), 0) self.assertNotIn("attr", attrs) self.assertEqual(list(attrs.keys()), []) self.assertEqual(attrs.get("attrs"), None) self.assertEqual(attrs.get("attrs", 25), 25) self.assertEqual(list(attrs.items()), []) self.assertEqual(list(attrs.values()), []) def verify_empty_nsattrs(self, attrs): self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr")) self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr") self.assertRaises(KeyError, attrs.getNameByQName, "ns:attr") self.assertRaises(KeyError, attrs.getQNameByName, (ns_uri, "attr")) self.assertRaises(KeyError, attrs.__getitem__, (ns_uri, "attr")) self.assertEqual(attrs.getLength(), 0) self.assertEqual(attrs.getNames(), []) self.assertEqual(attrs.getQNames(), []) self.assertEqual(len(attrs), 0) self.assertNotIn((ns_uri, "attr"), attrs) self.assertEqual(list(attrs.keys()), []) self.assertEqual(attrs.get((ns_uri, "attr")), None) self.assertEqual(attrs.get((ns_uri, "attr"), 25), 25) self.assertEqual(list(attrs.items()), []) self.assertEqual(list(attrs.values()), []) def verify_attrs_wattr(self, attrs): self.assertEqual(attrs.getLength(), 1) self.assertEqual(attrs.getNames(), ["attr"]) self.assertEqual(attrs.getQNames(), ["attr"]) self.assertEqual(len(attrs), 1) self.assertIn("attr", attrs) self.assertEqual(list(attrs.keys()), ["attr"]) self.assertEqual(attrs.get("attr"), "val") self.assertEqual(attrs.get("attr", 25), "val") self.assertEqual(list(attrs.items()), [("attr", "val")]) self.assertEqual(list(attrs.values()), ["val"]) self.assertEqual(attrs.getValue("attr"), "val") self.assertEqual(attrs.getValueByQName("attr"), "val") self.assertEqual(attrs.getNameByQName("attr"), "attr") self.assertEqual(attrs["attr"], "val") self.assertEqual(attrs.getQNameByName("attr"), "attr") def xml_str(doc, encoding=None): if encoding is None: return doc return '<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc) def xml_bytes(doc, encoding, decl_encoding=...): if decl_encoding is ...: decl_encoding = encoding return xml_str(doc, decl_encoding).encode(encoding, 'xmlcharrefreplace') def make_xml_file(doc, encoding, decl_encoding=...): if decl_encoding is ...: decl_encoding = encoding with open(TESTFN, 'w', encoding=encoding, errors='xmlcharrefreplace') as f: f.write(xml_str(doc, decl_encoding)) class ParseTest(unittest.TestCase): data = '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>' def tearDown(self): support.unlink(TESTFN) def check_parse(self, f): from xml.sax import parse result = StringIO() parse(f, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) def test_parse_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') for encoding in encodings: self.check_parse(StringIO(xml_str(self.data, encoding))) make_xml_file(self.data, encoding) with open(TESTFN, 'r', encoding=encoding) as f: self.check_parse(f) self.check_parse(StringIO(self.data)) make_xml_file(self.data, encoding, None) with open(TESTFN, 'r', encoding=encoding) as f: self.check_parse(f) def test_parse_bytes(self): # UTF-8 is default encoding, US-ASCII is compatible with UTF-8, # UTF-16 is autodetected encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') for encoding in encodings: self.check_parse(BytesIO(xml_bytes(self.data, encoding))) make_xml_file(self.data, encoding) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, encoding, None))) make_xml_file(self.data, encoding, None) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # accept UTF-8 with BOM self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', 'utf-8'))) make_xml_file(self.data, 'utf-8-sig', 'utf-8') self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', None))) make_xml_file(self.data, 'utf-8-sig', None) self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # accept data with declared encoding self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1'))) make_xml_file(self.data, 'iso-8859-1') self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: self.check_parse(f) # fail on non-UTF-8 incompatible data without declared encoding with self.assertRaises(SAXException): self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1', None))) make_xml_file(self.data, 'iso-8859-1', None) with self.assertRaises(SAXException): self.check_parse(TESTFN) with open(TESTFN, 'rb') as f: with self.assertRaises(SAXException): self.check_parse(f) def test_parse_InputSource(self): # accept data without declared but with explicitly specified encoding make_xml_file(self.data, 'iso-8859-1', None) with open(TESTFN, 'rb') as f: input = InputSource() input.setByteStream(f) input.setEncoding('iso-8859-1') self.check_parse(input) def test_parse_close_source(self): builtin_open = open fileobj = None def mock_open(*args): nonlocal fileobj fileobj = builtin_open(*args) return fileobj with mock.patch('xml.sax.saxutils.open', side_effect=mock_open): make_xml_file(self.data, 'iso-8859-1', None) with self.assertRaises(SAXException): self.check_parse(TESTFN) self.assertTrue(fileobj.closed) def check_parseString(self, s): from xml.sax import parseString result = StringIO() parseString(s, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) def test_parseString_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') for encoding in encodings: self.check_parseString(xml_str(self.data, encoding)) self.check_parseString(self.data) def test_parseString_bytes(self): # UTF-8 is default encoding, US-ASCII is compatible with UTF-8, # UTF-16 is autodetected encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') for encoding in encodings: self.check_parseString(xml_bytes(self.data, encoding)) self.check_parseString(xml_bytes(self.data, encoding, None)) # accept UTF-8 with BOM self.check_parseString(xml_bytes(self.data, 'utf-8-sig', 'utf-8')) self.check_parseString(xml_bytes(self.data, 'utf-8-sig', None)) # accept data with declared encoding self.check_parseString(xml_bytes(self.data, 'iso-8859-1')) # fail on non-UTF-8 incompatible data without declared encoding with self.assertRaises(SAXException): self.check_parseString(xml_bytes(self.data, 'iso-8859-1', None)) class MakeParserTest(unittest.TestCase): def test_make_parser2(self): # Creating parsers several times in a row should succeed. # Testing this because there have been failures of this kind # before. from xml.sax import make_parser p = make_parser() from xml.sax import make_parser p = make_parser() from xml.sax import make_parser p = make_parser() from xml.sax import make_parser p = make_parser() from xml.sax import make_parser p = make_parser() from xml.sax import make_parser p = make_parser() # =========================================================================== # # saxutils tests # # =========================================================================== class SaxutilsTest(unittest.TestCase): # ===== escape def test_escape_basic(self): self.assertEqual(escape("Donald Duck & Co"), "Donald Duck &amp; Co") def test_escape_all(self): self.assertEqual(escape("<Donald Duck & Co>"), "&lt;Donald Duck &amp; Co&gt;") def test_escape_extra(self): self.assertEqual(escape("Hei på deg", {"å" : "&aring;"}), "Hei p&aring; deg") # ===== unescape def test_unescape_basic(self): self.assertEqual(unescape("Donald Duck &amp; Co"), "Donald Duck & Co") def test_unescape_all(self): self.assertEqual(unescape("&lt;Donald Duck &amp; Co&gt;"), "<Donald Duck & Co>") def test_unescape_extra(self): self.assertEqual(unescape("Hei på deg", {"å" : "&aring;"}), "Hei p&aring; deg") def test_unescape_amp_extra(self): self.assertEqual(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;") # ===== quoteattr def test_quoteattr_basic(self): self.assertEqual(quoteattr("Donald Duck & Co"), '"Donald Duck &amp; Co"') def test_single_quoteattr(self): self.assertEqual(quoteattr('Includes "double" quotes'), '\'Includes "double" quotes\'') def test_double_quoteattr(self): self.assertEqual(quoteattr("Includes 'single' quotes"), "\"Includes 'single' quotes\"") def test_single_double_quoteattr(self): self.assertEqual(quoteattr("Includes 'single' and \"double\" quotes"), "\"Includes 'single' and &quot;double&quot; quotes\"") # ===== make_parser def test_make_parser(self): # Creating a parser should succeed - it should fall back # to the expatreader p = make_parser(['xml.parsers.no_such_parser']) class PrepareInputSourceTest(unittest.TestCase): def setUp(self): self.file = support.TESTFN with open(self.file, "w") as tmp: tmp.write("This was read from a file.") def tearDown(self): support.unlink(self.file) def make_byte_stream(self): return BytesIO(b"This is a byte stream.") def make_character_stream(self): return StringIO("This is a character stream.") def checkContent(self, stream, content): self.assertIsNotNone(stream) self.assertEqual(stream.read(), content) stream.close() def test_character_stream(self): # If the source is an InputSource with a character stream, use it. src = InputSource(self.file) src.setCharacterStream(self.make_character_stream()) prep = prepare_input_source(src) self.assertIsNone(prep.getByteStream()) self.checkContent(prep.getCharacterStream(), "This is a character stream.") def test_byte_stream(self): # If the source is an InputSource that does not have a character # stream but does have a byte stream, use the byte stream. src = InputSource(self.file) src.setByteStream(self.make_byte_stream()) prep = prepare_input_source(src) self.assertIsNone(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This is a byte stream.") def test_system_id(self): # If the source is an InputSource that has neither a character # stream nor a byte stream, open the system ID. src = InputSource(self.file) prep = prepare_input_source(src) self.assertIsNone(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This was read from a file.") def test_string(self): # If the source is a string, use it as a system ID and open it. prep = prepare_input_source(self.file) self.assertIsNone(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This was read from a file.") def test_binary_file(self): # If the source is a binary file-like object, use it as a byte # stream. prep = prepare_input_source(self.make_byte_stream()) self.assertIsNone(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This is a byte stream.") def test_text_file(self): # If the source is a text file-like object, use it as a character # stream. prep = prepare_input_source(self.make_character_stream()) self.assertIsNone(prep.getByteStream()) self.checkContent(prep.getCharacterStream(), "This is a character stream.") # ===== XMLGenerator class XmlgenTest: def test_xmlgen_basic(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc></doc>")) def test_xmlgen_basic_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc/>")) def test_xmlgen_content(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.characters("huhei") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>huhei</doc>")) def test_xmlgen_content_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startElement("doc", {}) gen.characters("huhei") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>huhei</doc>")) def test_xmlgen_pi(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.processingInstruction("test", "data") gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<?test data?><doc></doc>")) def test_xmlgen_content_escape(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.characters("<huhei&") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>&lt;huhei&amp;</doc>")) def test_xmlgen_attr_escape(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {"a": '"'}) gen.startElement("e", {"a": "'"}) gen.endElement("e") gen.startElement("e", {"a": "'\""}) gen.endElement("e") gen.startElement("e", {"a": "\n\r\t"}) gen.endElement("e") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml( "<doc a='\"'><e a=\"'\"></e>" "<e a=\"'&quot;\"></e>" "<e a=\"&#10;&#13;&#9;\"></e></doc>")) def test_xmlgen_encoding(self): encodings = ('iso-8859-15', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'utf-32', 'utf-32be', 'utf-32le') for encoding in encodings: result = self.ioclass() gen = XMLGenerator(result, encoding=encoding) gen.startDocument() gen.startElement("doc", {"a": '\u20ac'}) gen.characters("\u20ac") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<doc a="\u20ac">\u20ac</doc>', encoding=encoding)) def test_xmlgen_unencodable(self): result = self.ioclass() gen = XMLGenerator(result, encoding='ascii') gen.startDocument() gen.startElement("doc", {"a": '\u20ac'}) gen.characters("\u20ac") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<doc a="&#8364;">&#8364;</doc>', encoding='ascii')) def test_xmlgen_ignorable(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.ignorableWhitespace(" ") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc> </doc>")) def test_xmlgen_ignorable_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startElement("doc", {}) gen.ignorableWhitespace(" ") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc> </doc>")) def test_xmlgen_encoding_bytes(self): encodings = ('iso-8859-15', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'utf-32', 'utf-32be', 'utf-32le') for encoding in encodings: result = self.ioclass() gen = XMLGenerator(result, encoding=encoding) gen.startDocument() gen.startElement("doc", {"a": '\u20ac'}) gen.characters("\u20ac".encode(encoding)) gen.ignorableWhitespace(" ".encode(encoding)) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<doc a="\u20ac">\u20ac </doc>', encoding=encoding)) def test_xmlgen_ns(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startPrefixMapping("ns1", ns_uri) gen.startElementNS((ns_uri, "doc"), "ns1:doc", {}) # add an unqualified name gen.startElementNS((None, "udoc"), None, {}) gen.endElementNS((None, "udoc"), None) gen.endElementNS((ns_uri, "doc"), "ns1:doc") gen.endPrefixMapping("ns1") gen.endDocument() self.assertEqual(result.getvalue(), self.xml( '<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' % ns_uri)) def test_xmlgen_ns_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startPrefixMapping("ns1", ns_uri) gen.startElementNS((ns_uri, "doc"), "ns1:doc", {}) # add an unqualified name gen.startElementNS((None, "udoc"), None, {}) gen.endElementNS((None, "udoc"), None) gen.endElementNS((ns_uri, "doc"), "ns1:doc") gen.endPrefixMapping("ns1") gen.endDocument() self.assertEqual(result.getvalue(), self.xml( '<ns1:doc xmlns:ns1="%s"><udoc/></ns1:doc>' % ns_uri)) def test_1463026_1(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) gen.endElementNS((None, 'a'), 'a') gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<a b="c"></a>')) def test_1463026_1_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) gen.endElementNS((None, 'a'), 'a') gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<a b="c"/>')) def test_1463026_2(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startPrefixMapping(None, 'qux') gen.startElementNS(('qux', 'a'), 'a', {}) gen.endElementNS(('qux', 'a'), 'a') gen.endPrefixMapping(None) gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<a xmlns="qux"></a>')) def test_1463026_2_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startPrefixMapping(None, 'qux') gen.startElementNS(('qux', 'a'), 'a', {}) gen.endElementNS(('qux', 'a'), 'a') gen.endPrefixMapping(None) gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<a xmlns="qux"/>')) def test_1463026_3(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startPrefixMapping('my', 'qux') gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) gen.endElementNS(('qux', 'a'), 'a') gen.endPrefixMapping('my') gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<my:a xmlns:my="qux" b="c"></my:a>')) def test_1463026_3_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) gen.startDocument() gen.startPrefixMapping('my', 'qux') gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) gen.endElementNS(('qux', 'a'), 'a') gen.endPrefixMapping('my') gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<my:a xmlns:my="qux" b="c"/>')) def test_5027_1(self): # The xml prefix (as in xml:lang below) is reserved and bound by # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator had # a bug whereby a KeyError is raised because this namespace is missing # from a dictionary. # # This test demonstrates the bug by parsing a document. test_xml = StringIO( '<?xml version="1.0"?>' '<a:g1 xmlns:a="http://example.com/ns">' '<a:g2 xml:lang="en">Hello</a:g2>' '</a:g1>') parser = make_parser() parser.setFeature(feature_namespaces, True) result = self.ioclass() gen = XMLGenerator(result) parser.setContentHandler(gen) parser.parse(test_xml) self.assertEqual(result.getvalue(), self.xml( '<a:g1 xmlns:a="http://example.com/ns">' '<a:g2 xml:lang="en">Hello</a:g2>' '</a:g1>')) def test_5027_2(self): # The xml prefix (as in xml:lang below) is reserved and bound by # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator had # a bug whereby a KeyError is raised because this namespace is missing # from a dictionary. # # This test demonstrates the bug by direct manipulation of the # XMLGenerator. result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startPrefixMapping('a', 'http://example.com/ns') gen.startElementNS(('http://example.com/ns', 'g1'), 'g1', {}) lang_attr = {('http://www.w3.org/XML/1998/namespace', 'lang'): 'en'} gen.startElementNS(('http://example.com/ns', 'g2'), 'g2', lang_attr) gen.characters('Hello') gen.endElementNS(('http://example.com/ns', 'g2'), 'g2') gen.endElementNS(('http://example.com/ns', 'g1'), 'g1') gen.endPrefixMapping('a') gen.endDocument() self.assertEqual(result.getvalue(), self.xml( '<a:g1 xmlns:a="http://example.com/ns">' '<a:g2 xml:lang="en">Hello</a:g2>' '</a:g1>')) def test_no_close_file(self): result = self.ioclass() def func(out): gen = XMLGenerator(out) gen.startDocument() gen.startElement("doc", {}) func(result) self.assertFalse(result.closed) def test_xmlgen_fragment(self): result = self.ioclass() gen = XMLGenerator(result) # Don't call gen.startDocument() gen.startElement("foo", {"a": "1.0"}) gen.characters("Hello") gen.endElement("foo") gen.startElement("bar", {"b": "2.0"}) gen.endElement("bar") # Don't call gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<foo a="1.0">Hello</foo><bar b="2.0"></bar>')[len(self.xml('')):]) class StringXmlgenTest(XmlgenTest, unittest.TestCase): ioclass = StringIO def xml(self, doc, encoding='iso-8859-1'): return '<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc) test_xmlgen_unencodable = None class BytesXmlgenTest(XmlgenTest, unittest.TestCase): ioclass = BytesIO def xml(self, doc, encoding='iso-8859-1'): return ('<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc)).encode(encoding, 'xmlcharrefreplace') class WriterXmlgenTest(BytesXmlgenTest): class ioclass(list): write = list.append closed = False def seekable(self): return True def tell(self): # return 0 at start and not 0 after start return len(self) def getvalue(self): return b''.join(self) class StreamWriterXmlgenTest(XmlgenTest, unittest.TestCase): def ioclass(self): raw = BytesIO() writer = codecs.getwriter('ascii')(raw, 'xmlcharrefreplace') writer.getvalue = raw.getvalue return writer def xml(self, doc, encoding='iso-8859-1'): return ('<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc)).encode('ascii', 'xmlcharrefreplace') class StreamReaderWriterXmlgenTest(XmlgenTest, unittest.TestCase): fname = support.TESTFN + '-codecs' def ioclass(self): writer = codecs.open(self.fname, 'w', encoding='ascii', errors='xmlcharrefreplace', buffering=0) def cleanup(): writer.close() support.unlink(self.fname) self.addCleanup(cleanup) def getvalue(): # Windows will not let use reopen without first closing writer.close() with open(writer.name, 'rb') as f: return f.read() writer.getvalue = getvalue return writer def xml(self, doc, encoding='iso-8859-1'): return ('<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc)).encode('ascii', 'xmlcharrefreplace') start = b'<?xml version="1.0" encoding="iso-8859-1"?>\n' class XMLFilterBaseTest(unittest.TestCase): def test_filter_basic(self): result = BytesIO() gen = XMLGenerator(result) filter = XMLFilterBase() filter.setContentHandler(gen) filter.startDocument() filter.startElement("doc", {}) filter.characters("content") filter.ignorableWhitespace(" ") filter.endElement("doc") filter.endDocument() self.assertEqual(result.getvalue(), start + b"<doc>content </doc>") # =========================================================================== # # expatreader tests # # =========================================================================== with open(TEST_XMLFILE_OUT, 'rb') as f: xml_test_out = f.read() class ExpatReaderTest(XmlTestBase): # ===== XMLReader support def test_expat_binary_file(self): parser = create_parser() result = BytesIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) with open(TEST_XMLFILE, 'rb') as f: parser.parse(f) self.assertEqual(result.getvalue(), xml_test_out) def test_expat_text_file(self): parser = create_parser() result = BytesIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) with open(TEST_XMLFILE, 'rt', encoding='iso-8859-1') as f: parser.parse(f) self.assertEqual(result.getvalue(), xml_test_out) @requires_nonascii_filenames def test_expat_binary_file_nonascii(self): fname = support.TESTFN_UNICODE shutil.copyfile(TEST_XMLFILE, fname) self.addCleanup(support.unlink, fname) parser = create_parser() result = BytesIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) parser.parse(open(fname, 'rb')) self.assertEqual(result.getvalue(), xml_test_out) def test_expat_binary_file_bytes_name(self): fname = os.fsencode(TEST_XMLFILE) parser = create_parser() result = BytesIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) with open(fname, 'rb') as f: parser.parse(f) self.assertEqual(result.getvalue(), xml_test_out) def test_expat_binary_file_int_name(self): parser = create_parser() result = BytesIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) with open(TEST_XMLFILE, 'rb') as f: with open(f.fileno(), 'rb', closefd=False) as f2: parser.parse(f2) self.assertEqual(result.getvalue(), xml_test_out) # ===== DTDHandler support class TestDTDHandler: def __init__(self): self._notations = [] self._entities = [] def notationDecl(self, name, publicId, systemId): self._notations.append((name, publicId, systemId))
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__osx_support.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test__osx_support.py
""" Test suite for _osx_support: shared OS X support functions. """ import os import platform import stat import sys import unittest import test.support import _osx_support @unittest.skipUnless(sys.platform.startswith("darwin"), "requires OS X") class Test_OSXSupport(unittest.TestCase): def setUp(self): self.maxDiff = None self.prog_name = 'bogus_program_xxxx' self.temp_path_dir = os.path.abspath(os.getcwd()) self.env = test.support.EnvironmentVarGuard() self.addCleanup(self.env.__exit__) for cv in ('CFLAGS', 'LDFLAGS', 'CPPFLAGS', 'BASECFLAGS', 'BLDSHARED', 'LDSHARED', 'CC', 'CXX', 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS', 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS'): if cv in self.env: self.env.unset(cv) def add_expected_saved_initial_values(self, config_vars, expected_vars): # Ensure that the initial values for all modified config vars # are also saved with modified keys. expected_vars.update(('_OSX_SUPPORT_INITIAL_'+ k, config_vars[k]) for k in config_vars if config_vars[k] != expected_vars[k]) def test__find_executable(self): if self.env['PATH']: self.env['PATH'] = self.env['PATH'] + ':' self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir) test.support.unlink(self.prog_name) self.assertIsNone(_osx_support._find_executable(self.prog_name)) self.addCleanup(test.support.unlink, self.prog_name) with open(self.prog_name, 'w') as f: f.write("#!/bin/sh\n/bin/echo OK\n") os.chmod(self.prog_name, stat.S_IRWXU) self.assertEqual(self.prog_name, _osx_support._find_executable(self.prog_name)) def test__read_output(self): if self.env['PATH']: self.env['PATH'] = self.env['PATH'] + ':' self.env['PATH'] = self.env['PATH'] + os.path.abspath(self.temp_path_dir) test.support.unlink(self.prog_name) self.addCleanup(test.support.unlink, self.prog_name) with open(self.prog_name, 'w') as f: f.write("#!/bin/sh\n/bin/echo ExpectedOutput\n") os.chmod(self.prog_name, stat.S_IRWXU) self.assertEqual('ExpectedOutput', _osx_support._read_output(self.prog_name)) def test__find_build_tool(self): out = _osx_support._find_build_tool('cc') self.assertTrue(os.path.isfile(out), 'cc not found - check xcode-select') def test__get_system_version(self): self.assertTrue(platform.mac_ver()[0].startswith( _osx_support._get_system_version())) def test__remove_original_values(self): config_vars = { 'CC': 'gcc-test -pthreads', } expected_vars = { 'CC': 'clang -pthreads', } cv = 'CC' newvalue = 'clang -pthreads' _osx_support._save_modified_value(config_vars, cv, newvalue) self.assertNotEqual(expected_vars, config_vars) _osx_support._remove_original_values(config_vars) self.assertEqual(expected_vars, config_vars) def test__save_modified_value(self): config_vars = { 'CC': 'gcc-test -pthreads', } expected_vars = { 'CC': 'clang -pthreads', } self.add_expected_saved_initial_values(config_vars, expected_vars) cv = 'CC' newvalue = 'clang -pthreads' _osx_support._save_modified_value(config_vars, cv, newvalue) self.assertEqual(expected_vars, config_vars) def test__save_modified_value_unchanged(self): config_vars = { 'CC': 'gcc-test -pthreads', } expected_vars = config_vars.copy() cv = 'CC' newvalue = 'gcc-test -pthreads' _osx_support._save_modified_value(config_vars, cv, newvalue) self.assertEqual(expected_vars, config_vars) def test__supports_universal_builds(self): import platform mac_ver_tuple = tuple(int(i) for i in platform.mac_ver()[0].split('.')[0:2]) self.assertEqual(mac_ver_tuple >= (10, 4), _osx_support._supports_universal_builds()) def test__find_appropriate_compiler(self): compilers = ( ('gcc-test', 'i686-apple-darwin11-llvm-gcc-4.2'), ('clang', 'clang version 3.1'), ) config_vars = { 'CC': 'gcc-test -pthreads', 'CXX': 'cc++-test', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-test -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-test -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } expected_vars = { 'CC': 'clang -pthreads', 'CXX': 'clang++', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'clang -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'clang -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } self.add_expected_saved_initial_values(config_vars, expected_vars) suffix = (':' + self.env['PATH']) if self.env['PATH'] else '' self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix for c_name, c_output in compilers: test.support.unlink(c_name) self.addCleanup(test.support.unlink, c_name) with open(c_name, 'w') as f: f.write("#!/bin/sh\n/bin/echo " + c_output) os.chmod(c_name, stat.S_IRWXU) self.assertEqual(expected_vars, _osx_support._find_appropriate_compiler( config_vars)) def test__remove_universal_flags(self): config_vars = { 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } expected_vars = { 'CFLAGS': '-fno-strict-aliasing -g -O3 ', 'LDFLAGS': ' -g', 'CPPFLAGS': '-I. ', 'BLDSHARED': 'gcc-4.0 -bundle -g', 'LDSHARED': 'gcc-4.0 -bundle -g', } self.add_expected_saved_initial_values(config_vars, expected_vars) self.assertEqual(expected_vars, _osx_support._remove_universal_flags( config_vars)) def test__remove_unsupported_archs(self): config_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } expected_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch i386 ', 'LDFLAGS': ' -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } self.add_expected_saved_initial_values(config_vars, expected_vars) suffix = (':' + self.env['PATH']) if self.env['PATH'] else '' self.env['PATH'] = os.path.abspath(self.temp_path_dir) + suffix c_name = 'clang' test.support.unlink(c_name) self.addCleanup(test.support.unlink, c_name) # exit status 255 means no PPC support in this compiler chain with open(c_name, 'w') as f: f.write("#!/bin/sh\nexit 255") os.chmod(c_name, stat.S_IRWXU) self.assertEqual(expected_vars, _osx_support._remove_unsupported_archs( config_vars)) def test__override_all_archs(self): self.env['ARCHFLAGS'] = '-arch x86_64' config_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.4u.sdk -g', } expected_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch x86_64', 'LDFLAGS': ' -g -arch x86_64', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.4u.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -g -arch x86_64', 'LDSHARED': 'gcc-4.0 -bundle -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk -g -arch x86_64', } self.add_expected_saved_initial_values(config_vars, expected_vars) self.assertEqual(expected_vars, _osx_support._override_all_archs( config_vars)) def test__check_for_unavailable_sdk(self): config_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.1.sdk', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. -isysroot /Developer/SDKs/MacOSX10.1.sdk', 'BLDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.1.sdk -g', } expected_vars = { 'CC': 'clang', 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ' ' ', 'LDFLAGS': '-arch ppc -arch i386 -g', 'CPPFLAGS': '-I. ', 'BLDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 -g', 'LDSHARED': 'gcc-4.0 -bundle -arch ppc -arch i386 ' ' -g', } self.add_expected_saved_initial_values(config_vars, expected_vars) self.assertEqual(expected_vars, _osx_support._check_for_unavailable_sdk( config_vars)) def test_get_platform_osx(self): # Note, get_platform_osx is currently tested more extensively # indirectly by test_sysconfig and test_distutils config_vars = { 'CFLAGS': '-fno-strict-aliasing -g -O3 -arch ppc -arch i386 ' '-isysroot /Developer/SDKs/MacOSX10.1.sdk', 'MACOSX_DEPLOYMENT_TARGET': '10.6', } result = _osx_support.get_platform_osx(config_vars, ' ', ' ', ' ') self.assertEqual(('macosx', '10.6', 'fat'), result) 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/pydoc_mod.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/pydoc_mod.py
"""This is a test module for test_pydoc""" __author__ = "Benjamin Peterson" __credits__ = "Nobody" __version__ = "1.2.3.4" __xyz__ = "X, Y and Z" class A: """Hello and goodbye""" def __init__(): """Wow, I have no function!""" pass class B(object): NO_MEANING: str = "eggs" pass class C(object): def say_no(self): return "no" def get_answer(self): """ Return say_no() """ return self.say_no() def is_it_true(self): """ Return self.get_answer() """ return self.get_answer() def doc_func(): """ This function solves all of the world's problems: hunger lack of Python war """ def nodoc_func(): pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false