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_ntpath.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ntpath.py
import ntpath import os import sys import unittest import warnings from test.support import TestFailed, FakePath from test import support, test_genericpath from tempfile import TemporaryFile try: import nt except ImportError: # Most tests can complete without the nt module, # but for those that require it we import here. nt = None def _norm(path): if isinstance(path, (bytes, str, os.PathLike)): return ntpath.normcase(os.fsdecode(path)) elif hasattr(path, "__iter__"): return tuple(ntpath.normcase(os.fsdecode(p)) for p in path) return path def tester(fn, wantResult): fn = fn.replace("\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult and _norm(wantResult) != _norm(gotResult): raise TestFailed("%s should return: %s but returned: %s" \ %(str(fn), str(wantResult), str(gotResult))) # then with bytes fn = fn.replace("('", "(b'") fn = fn.replace('("', '(b"') fn = fn.replace("['", "[b'") fn = fn.replace('["', '[b"') fn = fn.replace(", '", ", b'") fn = fn.replace(', "', ', b"') fn = os.fsencode(fn).decode('latin1') fn = fn.encode('ascii', 'backslashreplace').decode('ascii') with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) gotResult = eval(fn) if _norm(wantResult) != _norm(gotResult): raise TestFailed("%s should return: %s but returned: %s" \ %(str(fn), str(wantResult), repr(gotResult))) class NtpathTestCase(unittest.TestCase): def assertPathEqual(self, path1, path2): if path1 == path2 or _norm(path1) == _norm(path2): return self.assertEqual(path1, path2) def assertPathIn(self, path, pathset): self.assertIn(_norm(path), _norm(pathset)) class TestNtpath(NtpathTestCase): def test_splitext(self): tester('ntpath.splitext("foo.ext")', ('foo', '.ext')) tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext')) tester('ntpath.splitext(".ext")', ('.ext', '')) tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', '')) tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', '')) tester('ntpath.splitext("")', ('', '')) tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext')) tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext')) tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext')) tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d')) def test_splitdrive(self): tester('ntpath.splitdrive("c:\\foo\\bar")', ('c:', '\\foo\\bar')) tester('ntpath.splitdrive("c:/foo/bar")', ('c:', '/foo/bar')) tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar')) tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar')) tester('ntpath.splitdrive("\\\\\\conky\\mountpoint\\foo\\bar")', ('', '\\\\\\conky\\mountpoint\\foo\\bar')) tester('ntpath.splitdrive("///conky/mountpoint/foo/bar")', ('', '///conky/mountpoint/foo/bar')) tester('ntpath.splitdrive("\\\\conky\\\\mountpoint\\foo\\bar")', ('', '\\\\conky\\\\mountpoint\\foo\\bar')) tester('ntpath.splitdrive("//conky//mountpoint/foo/bar")', ('', '//conky//mountpoint/foo/bar')) # Issue #19911: UNC part containing U+0130 self.assertEqual(ntpath.splitdrive('//conky/MOUNTPOİNT/foo/bar'), ('//conky/MOUNTPOİNT', '/foo/bar')) def test_split(self): tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar')) tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint\\foo', 'bar')) tester('ntpath.split("c:\\")', ('c:\\', '')) tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint\\', '')) tester('ntpath.split("c:/")', ('c:/', '')) tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', '')) def test_isabs(self): tester('ntpath.isabs("c:\\")', 1) tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1) tester('ntpath.isabs("\\foo")', 1) tester('ntpath.isabs("\\foo\\bar")', 1) def test_commonprefix(self): tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])', "/home/swen") tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])', "\\home\\swen\\") tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])', "/home/swen/spam") def test_join(self): tester('ntpath.join("")', '') tester('ntpath.join("", "", "")', '') tester('ntpath.join("a")', 'a') tester('ntpath.join("/a")', '/a') tester('ntpath.join("\\a")', '\\a') tester('ntpath.join("a:")', 'a:') tester('ntpath.join("a:", "\\b")', 'a:\\b') tester('ntpath.join("a", "\\b")', '\\b') tester('ntpath.join("a", "b", "c")', 'a\\b\\c') tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c') tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c') tester('ntpath.join("a", "b", "\\c")', '\\c') tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep') tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b') tester("ntpath.join('', 'a')", 'a') tester("ntpath.join('', '', '', '', 'a')", 'a') tester("ntpath.join('a', '')", 'a\\') tester("ntpath.join('a', '', '', '', '')", 'a\\') tester("ntpath.join('a\\', '')", 'a\\') tester("ntpath.join('a\\', '', '', '', '')", 'a\\') tester("ntpath.join('a/', '')", 'a/') tester("ntpath.join('a/b', 'x/y')", 'a/b\\x/y') tester("ntpath.join('/a/b', 'x/y')", '/a/b\\x/y') tester("ntpath.join('/a/b/', 'x/y')", '/a/b/x/y') tester("ntpath.join('c:', 'x/y')", 'c:x/y') tester("ntpath.join('c:a/b', 'x/y')", 'c:a/b\\x/y') tester("ntpath.join('c:a/b/', 'x/y')", 'c:a/b/x/y') tester("ntpath.join('c:/', 'x/y')", 'c:/x/y') tester("ntpath.join('c:/a/b', 'x/y')", 'c:/a/b\\x/y') tester("ntpath.join('c:/a/b/', 'x/y')", 'c:/a/b/x/y') tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y') tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y') tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y') tester("ntpath.join('a/b', '/x/y')", '/x/y') tester("ntpath.join('/a/b', '/x/y')", '/x/y') tester("ntpath.join('c:', '/x/y')", 'c:/x/y') tester("ntpath.join('c:a/b', '/x/y')", 'c:/x/y') tester("ntpath.join('c:/', '/x/y')", 'c:/x/y') tester("ntpath.join('c:/a/b', '/x/y')", 'c:/x/y') tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y') tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y') tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y') tester("ntpath.join('c:', 'C:x/y')", 'C:x/y') tester("ntpath.join('c:a/b', 'C:x/y')", 'C:a/b\\x/y') tester("ntpath.join('c:/', 'C:x/y')", 'C:/x/y') tester("ntpath.join('c:/a/b', 'C:x/y')", 'C:/a/b\\x/y') for x in ('', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b', '//computer/share', '//computer/share/', '//computer/share/a/b'): for y in ('d:', 'd:x/y', 'd:/', 'd:/x/y', '//machine/common', '//machine/common/', '//machine/common/x/y'): tester("ntpath.join(%r, %r)" % (x, y), y) tester("ntpath.join('\\\\computer\\share\\', 'a', 'b')", '\\\\computer\\share\\a\\b') tester("ntpath.join('\\\\computer\\share', 'a', 'b')", '\\\\computer\\share\\a\\b') tester("ntpath.join('\\\\computer\\share', 'a\\b')", '\\\\computer\\share\\a\\b') tester("ntpath.join('//computer/share/', 'a', 'b')", '//computer/share/a\\b') tester("ntpath.join('//computer/share', 'a', 'b')", '//computer/share\\a\\b') tester("ntpath.join('//computer/share', 'a/b')", '//computer/share\\a/b') def test_normpath(self): tester("ntpath.normpath('A//////././//.//B')", r'A\B') tester("ntpath.normpath('A/./B')", r'A\B') tester("ntpath.normpath('A/foo/../B')", r'A\B') tester("ntpath.normpath('C:A//B')", r'C:A\B') tester("ntpath.normpath('D:A/./B')", r'D:A\B') tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B') tester("ntpath.normpath('C:///A//B')", r'C:\A\B') tester("ntpath.normpath('D:///A/./B')", r'D:\A\B') tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B') tester("ntpath.normpath('..')", r'..') tester("ntpath.normpath('.')", r'.') tester("ntpath.normpath('')", r'.') tester("ntpath.normpath('/')", '\\') tester("ntpath.normpath('c:/')", 'c:\\') tester("ntpath.normpath('/../.././..')", '\\') tester("ntpath.normpath('c:/../../..')", 'c:\\') tester("ntpath.normpath('../.././..')", r'..\..\..') tester("ntpath.normpath('K:../.././..')", r'K:..\..\..') tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL') tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z') def test_expandvars(self): with support.EnvironmentVarGuard() as env: env.clear() env["foo"] = "bar" env["{foo"] = "baz1" env["{foo}"] = "baz2" tester('ntpath.expandvars("foo")', "foo") tester('ntpath.expandvars("$foo bar")', "bar bar") tester('ntpath.expandvars("${foo}bar")', "barbar") tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") tester('ntpath.expandvars("$bar bar")', "$bar bar") tester('ntpath.expandvars("$?bar")', "$?bar") tester('ntpath.expandvars("$foo}bar")', "bar}bar") tester('ntpath.expandvars("${foo")', "${foo") tester('ntpath.expandvars("${{foo}}")', "baz1}") tester('ntpath.expandvars("$foo$foo")', "barbar") tester('ntpath.expandvars("$bar$bar")', "$bar$bar") tester('ntpath.expandvars("%foo% bar")', "bar bar") tester('ntpath.expandvars("%foo%bar")', "barbar") tester('ntpath.expandvars("%foo%%foo%")', "barbar") tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar") tester('ntpath.expandvars("%?bar%")', "%?bar%") tester('ntpath.expandvars("%foo%%bar")', "bar%bar") tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar") tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%") @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII') def test_expandvars_nonascii(self): def check(value, expected): tester('ntpath.expandvars(%r)' % value, expected) with support.EnvironmentVarGuard() as env: env.clear() nonascii = support.FS_NONASCII env['spam'] = nonascii env[nonascii] = 'ham' + nonascii check('$spam bar', '%s bar' % nonascii) check('$%s bar' % nonascii, '$%s bar' % nonascii) check('${spam}bar', '%sbar' % nonascii) check('${%s}bar' % nonascii, 'ham%sbar' % nonascii) check('$spam}bar', '%s}bar' % nonascii) check('$%s}bar' % nonascii, '$%s}bar' % nonascii) check('%spam% bar', '%s bar' % nonascii) check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii) check('%spam%bar', '%sbar' % nonascii) check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii) def test_expanduser(self): tester('ntpath.expanduser("test")', 'test') with support.EnvironmentVarGuard() as env: env.clear() tester('ntpath.expanduser("~test")', '~test') env['HOMEPATH'] = 'eric\\idle' env['HOMEDRIVE'] = 'C:\\' tester('ntpath.expanduser("~test")', 'C:\\eric\\test') tester('ntpath.expanduser("~")', 'C:\\eric\\idle') del env['HOMEDRIVE'] tester('ntpath.expanduser("~test")', 'eric\\test') tester('ntpath.expanduser("~")', 'eric\\idle') env.clear() env['USERPROFILE'] = 'C:\\eric\\idle' tester('ntpath.expanduser("~test")', 'C:\\eric\\test') tester('ntpath.expanduser("~")', 'C:\\eric\\idle') env.clear() env['HOME'] = 'C:\\idle\\eric' tester('ntpath.expanduser("~test")', 'C:\\idle\\test') tester('ntpath.expanduser("~")', 'C:\\idle\\eric') tester('ntpath.expanduser("~test\\foo\\bar")', 'C:\\idle\\test\\foo\\bar') tester('ntpath.expanduser("~test/foo/bar")', 'C:\\idle\\test/foo/bar') tester('ntpath.expanduser("~\\foo\\bar")', 'C:\\idle\\eric\\foo\\bar') tester('ntpath.expanduser("~/foo/bar")', 'C:\\idle\\eric/foo/bar') @unittest.skipUnless(nt, "abspath requires 'nt' module") def test_abspath(self): tester('ntpath.abspath("C:\\")', "C:\\") with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047 tester('ntpath.abspath("")', cwd_dir) tester('ntpath.abspath(" ")', cwd_dir + "\\ ") tester('ntpath.abspath("?")', cwd_dir + "\\?") drive, _ = ntpath.splitdrive(cwd_dir) tester('ntpath.abspath("/abc/")', drive + "\\abc") def test_relpath(self): tester('ntpath.relpath("a")', 'a') tester('ntpath.relpath(os.path.abspath("a"))', 'a') tester('ntpath.relpath("a/b")', 'a\\b') tester('ntpath.relpath("../a/b")', '..\\a\\b') with support.temp_cwd(support.TESTFN) as cwd_dir: currentdir = os.path.basename(cwd_dir) tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a') tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b') tester('ntpath.relpath("a", "b/c")', '..\\..\\a') tester('ntpath.relpath("c:/foo/bar/bat", "c:/x/y")', '..\\..\\foo\\bar\\bat') tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a') tester('ntpath.relpath("a", "a")', '.') tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat') tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat') tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat') tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..') tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat') tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x') tester('ntpath.relpath("/", "/")', '.') tester('ntpath.relpath("/a", "/a")', '.') tester('ntpath.relpath("/a/b", "/a/b")', '.') tester('ntpath.relpath("c:/foo", "C:/FOO")', '.') def test_commonpath(self): def check(paths, expected): tester(('ntpath.commonpath(%r)' % paths).replace('\\\\', '\\'), expected) def check_error(exc, paths): self.assertRaises(exc, ntpath.commonpath, paths) self.assertRaises(exc, ntpath.commonpath, [os.fsencode(p) for p in paths]) self.assertRaises(ValueError, ntpath.commonpath, []) check_error(ValueError, ['C:\\Program Files', 'Program Files']) check_error(ValueError, ['C:\\Program Files', 'C:Program Files']) check_error(ValueError, ['\\Program Files', 'Program Files']) check_error(ValueError, ['Program Files', 'C:\\Program Files']) check(['C:\\Program Files'], 'C:\\Program Files') check(['C:\\Program Files', 'C:\\Program Files'], 'C:\\Program Files') check(['C:\\Program Files\\', 'C:\\Program Files'], 'C:\\Program Files') check(['C:\\Program Files\\', 'C:\\Program Files\\'], 'C:\\Program Files') check(['C:\\\\Program Files', 'C:\\Program Files\\\\'], 'C:\\Program Files') check(['C:\\.\\Program Files', 'C:\\Program Files\\.'], 'C:\\Program Files') check(['C:\\', 'C:\\bin'], 'C:\\') check(['C:\\Program Files', 'C:\\bin'], 'C:\\') check(['C:\\Program Files', 'C:\\Program Files\\Bar'], 'C:\\Program Files') check(['C:\\Program Files\\Foo', 'C:\\Program Files\\Bar'], 'C:\\Program Files') check(['C:\\Program Files', 'C:\\Projects'], 'C:\\') check(['C:\\Program Files\\', 'C:\\Projects'], 'C:\\') check(['C:\\Program Files\\Foo', 'C:/Program Files/Bar'], 'C:\\Program Files') check(['C:\\Program Files\\Foo', 'c:/program files/bar'], 'C:\\Program Files') check(['c:/program files/bar', 'C:\\Program Files\\Foo'], 'c:\\program files') check_error(ValueError, ['C:\\Program Files', 'D:\\Program Files']) 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(['C:and\\jam', 'C:and\\spam'], 'C:and') check([''], '') check(['', 'spam\\alot'], '') check_error(ValueError, ['', '\\spam\\alot']) self.assertRaises(TypeError, ntpath.commonpath, [b'C:\\Program Files', 'C:\\Program Files\\Foo']) self.assertRaises(TypeError, ntpath.commonpath, [b'C:\\Program Files', 'Program Files\\Foo']) self.assertRaises(TypeError, ntpath.commonpath, [b'Program Files', 'C:\\Program Files\\Foo']) self.assertRaises(TypeError, ntpath.commonpath, ['C:\\Program Files', b'C:\\Program Files\\Foo']) self.assertRaises(TypeError, ntpath.commonpath, ['C:\\Program Files', b'Program Files\\Foo']) self.assertRaises(TypeError, ntpath.commonpath, ['Program Files', b'C:\\Program Files\\Foo']) def test_sameopenfile(self): with TemporaryFile() as tf1, TemporaryFile() as tf2: # Make sure the same file is really the same self.assertTrue(ntpath.sameopenfile(tf1.fileno(), tf1.fileno())) # Make sure different files are really different self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno())) # Make sure invalid values don't cause issues on win32 if sys.platform == "win32": with self.assertRaises(OSError): # Invalid file descriptors shouldn't display assert # dialogs (#4804) ntpath.sameopenfile(-1, -1) def test_ismount(self): self.assertTrue(ntpath.ismount("c:\\")) self.assertTrue(ntpath.ismount("C:\\")) self.assertTrue(ntpath.ismount("c:/")) self.assertTrue(ntpath.ismount("C:/")) self.assertTrue(ntpath.ismount("\\\\.\\c:\\")) self.assertTrue(ntpath.ismount("\\\\.\\C:\\")) self.assertTrue(ntpath.ismount(b"c:\\")) self.assertTrue(ntpath.ismount(b"C:\\")) self.assertTrue(ntpath.ismount(b"c:/")) self.assertTrue(ntpath.ismount(b"C:/")) self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\")) self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\")) with support.temp_dir() as d: self.assertFalse(ntpath.ismount(d)) if sys.platform == "win32": # # Make sure the current folder isn't the root folder # (or any other volume root). The drive-relative # locations below cannot then refer to mount points # drive, path = ntpath.splitdrive(sys.executable) with support.change_cwd(os.path.dirname(sys.executable)): self.assertFalse(ntpath.ismount(drive.lower())) self.assertFalse(ntpath.ismount(drive.upper())) self.assertTrue(ntpath.ismount("\\\\localhost\\c$")) self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\")) self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$")) self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\")) @unittest.skipUnless(nt, "OS helpers require 'nt' module") def test_nt_helpers(self): # Trivial validation that the helpers do not break, and support both # unicode and bytes (UTF-8) paths drive, path = ntpath.splitdrive(sys.executable) drive = drive.rstrip(ntpath.sep) + ntpath.sep self.assertEqual(drive, nt._getvolumepathname(sys.executable)) self.assertEqual(drive.encode(), nt._getvolumepathname(sys.executable.encode())) cap, free = nt._getdiskusage(sys.exec_prefix) self.assertGreater(cap, 0) self.assertGreater(free, 0) b_cap, b_free = nt._getdiskusage(sys.exec_prefix.encode()) # Free space may change, so only test the capacity is equal self.assertEqual(b_cap, cap) self.assertGreater(b_free, 0) for path in [sys.prefix, sys.executable]: final_path = nt._getfinalpathname(path) self.assertIsInstance(final_path, str) self.assertGreater(len(final_path), 0) b_final_path = nt._getfinalpathname(path.encode()) self.assertIsInstance(b_final_path, bytes) self.assertGreater(len(b_final_path), 0) class NtCommonTest(test_genericpath.CommonTest, unittest.TestCase): pathmodule = ntpath attributes = ['relpath'] class PathLikeTests(NtpathTestCase): path = ntpath 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_ntpath.PathLikeTests") def _check_function(self, func): self.assertPathEqual(func(self.file_path), func(self.file_name)) def test_path_normcase(self): self._check_function(self.path.normcase) def test_path_isabs(self): self._check_function(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._check_function(self.path.split) def test_path_splitext(self): self._check_function(self.path.splitext) def test_path_splitdrive(self): self._check_function(self.path.splitdrive) def test_path_basename(self): self._check_function(self.path.basename) def test_path_dirname(self): self._check_function(self.path.dirname) def test_path_islink(self): self._check_function(self.path.islink) def test_path_lexists(self): self._check_function(self.path.lexists) def test_path_ismount(self): self._check_function(self.path.ismount) def test_path_expanduser(self): self._check_function(self.path.expanduser) def test_path_expandvars(self): self._check_function(self.path.expandvars) def test_path_normpath(self): self._check_function(self.path.normpath) def test_path_abspath(self): self._check_function(self.path.abspath) def test_path_realpath(self): self._check_function(self.path.realpath) def test_path_relpath(self): self._check_function(self.path.relpath) def test_path_commonpath(self): common_path = self.path.commonpath([self.file_path, self.file_name]) self.assertPathEqual(common_path, self.file_name) def test_path_isdir(self): self._check_function(self.path.isdir) 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_symtable.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_symtable.py
""" Test the API of the symtable module. """ import symtable import unittest TEST_CODE = """ import sys glob = 42 class Mine: instance_var = 24 def a_method(p1, p2): pass def spam(a, b, *var, **kw): global bar bar = 47 x = 23 glob def internal(): return x return internal def foo(): pass def namespace_test(): pass def namespace_test(): pass """ def find_block(block, name): for ch in block.get_children(): if ch.get_name() == name: return ch class SymtableTest(unittest.TestCase): top = symtable.symtable(TEST_CODE, "?", "exec") # These correspond to scopes in TEST_CODE Mine = find_block(top, "Mine") a_method = find_block(Mine, "a_method") spam = find_block(top, "spam") internal = find_block(spam, "internal") foo = find_block(top, "foo") def test_type(self): self.assertEqual(self.top.get_type(), "module") self.assertEqual(self.Mine.get_type(), "class") self.assertEqual(self.a_method.get_type(), "function") self.assertEqual(self.spam.get_type(), "function") self.assertEqual(self.internal.get_type(), "function") def test_optimized(self): self.assertFalse(self.top.is_optimized()) self.assertFalse(self.top.has_exec()) self.assertTrue(self.spam.is_optimized()) def test_nested(self): self.assertFalse(self.top.is_nested()) self.assertFalse(self.Mine.is_nested()) self.assertFalse(self.spam.is_nested()) self.assertTrue(self.internal.is_nested()) def test_children(self): self.assertTrue(self.top.has_children()) self.assertTrue(self.Mine.has_children()) self.assertFalse(self.foo.has_children()) def test_lineno(self): self.assertEqual(self.top.get_lineno(), 0) self.assertEqual(self.spam.get_lineno(), 11) def test_function_info(self): func = self.spam self.assertEqual(sorted(func.get_parameters()), ["a", "b", "kw", "var"]) expected = ["a", "b", "internal", "kw", "var", "x"] self.assertEqual(sorted(func.get_locals()), expected) self.assertEqual(sorted(func.get_globals()), ["bar", "glob"]) self.assertEqual(self.internal.get_frees(), ("x",)) def test_globals(self): self.assertTrue(self.spam.lookup("glob").is_global()) self.assertFalse(self.spam.lookup("glob").is_declared_global()) self.assertTrue(self.spam.lookup("bar").is_global()) self.assertTrue(self.spam.lookup("bar").is_declared_global()) self.assertFalse(self.internal.lookup("x").is_global()) self.assertFalse(self.Mine.lookup("instance_var").is_global()) def test_local(self): self.assertTrue(self.spam.lookup("x").is_local()) self.assertFalse(self.internal.lookup("x").is_local()) def test_referenced(self): self.assertTrue(self.internal.lookup("x").is_referenced()) self.assertTrue(self.spam.lookup("internal").is_referenced()) self.assertFalse(self.spam.lookup("x").is_referenced()) def test_parameters(self): for sym in ("a", "var", "kw"): self.assertTrue(self.spam.lookup(sym).is_parameter()) self.assertFalse(self.spam.lookup("x").is_parameter()) def test_symbol_lookup(self): self.assertEqual(len(self.top.get_identifiers()), len(self.top.get_symbols())) self.assertRaises(KeyError, self.top.lookup, "not_here") def test_namespaces(self): self.assertTrue(self.top.lookup("Mine").is_namespace()) self.assertTrue(self.Mine.lookup("a_method").is_namespace()) self.assertTrue(self.top.lookup("spam").is_namespace()) self.assertTrue(self.spam.lookup("internal").is_namespace()) self.assertTrue(self.top.lookup("namespace_test").is_namespace()) self.assertFalse(self.spam.lookup("x").is_namespace()) self.assertTrue(self.top.lookup("spam").get_namespace() is self.spam) ns_test = self.top.lookup("namespace_test") self.assertEqual(len(ns_test.get_namespaces()), 2) self.assertRaises(ValueError, ns_test.get_namespace) def test_assigned(self): self.assertTrue(self.spam.lookup("x").is_assigned()) self.assertTrue(self.spam.lookup("bar").is_assigned()) self.assertTrue(self.top.lookup("spam").is_assigned()) self.assertTrue(self.Mine.lookup("a_method").is_assigned()) self.assertFalse(self.internal.lookup("x").is_assigned()) def test_annotated(self): st1 = symtable.symtable('def f():\n x: int\n', 'test', 'exec') st2 = st1.get_children()[0] self.assertTrue(st2.lookup('x').is_local()) self.assertTrue(st2.lookup('x').is_annotated()) self.assertFalse(st2.lookup('x').is_global()) st3 = symtable.symtable('def f():\n x = 1\n', 'test', 'exec') st4 = st3.get_children()[0] self.assertTrue(st4.lookup('x').is_local()) self.assertFalse(st4.lookup('x').is_annotated()) def test_imported(self): self.assertTrue(self.top.lookup("sys").is_imported()) def test_name(self): self.assertEqual(self.top.get_name(), "top") self.assertEqual(self.spam.get_name(), "spam") self.assertEqual(self.spam.lookup("x").get_name(), "x") self.assertEqual(self.Mine.get_name(), "Mine") def test_class_info(self): self.assertEqual(self.Mine.get_methods(), ('a_method',)) def test_filename_correct(self): ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. def checkfilename(brokencode, offset): try: symtable.symtable(brokencode, "spam", "exec") except SyntaxError as e: self.assertEqual(e.filename, "spam") self.assertEqual(e.lineno, 1) self.assertEqual(e.offset, offset) else: self.fail("no SyntaxError for %r" % (brokencode,)) checkfilename("def f(x): foo)(", 14) # parse-time checkfilename("def f(x): global x", 10) # symtable-build-time symtable.symtable("pass", b"spam", "exec") with self.assertWarns(DeprecationWarning), \ self.assertRaises(TypeError): symtable.symtable("pass", bytearray(b"spam"), "exec") with self.assertWarns(DeprecationWarning): symtable.symtable("pass", memoryview(b"spam"), "exec") with self.assertRaises(TypeError): symtable.symtable("pass", list(b"spam"), "exec") def test_eval(self): symbols = symtable.symtable("42", "?", "eval") def test_single(self): symbols = symtable.symtable("42", "?", "single") def test_exec(self): symbols = symtable.symtable("def f(x): return x", "?", "exec") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_generators.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_generators.py
import copy import gc import pickle import sys import unittest import warnings import weakref import inspect from test import support try: import _testcapi except ImportError: _testcapi = None # This tests to make sure that if a SIGINT arrives just before we send into a # yield from chain, the KeyboardInterrupt is raised in the innermost # generator (see bpo-30039). @unittest.skipUnless(_testcapi is not None and hasattr(_testcapi, "raise_SIGINT_then_send_None"), "needs _testcapi.raise_SIGINT_then_send_None") class SignalAndYieldFromTest(unittest.TestCase): def generator1(self): return (yield from self.generator2()) def generator2(self): try: yield except KeyboardInterrupt: return "PASSED" else: return "FAILED" def test_raise_and_yield_from(self): gen = self.generator1() gen.send(None) try: _testcapi.raise_SIGINT_then_send_None(gen) except BaseException as _exc: exc = _exc self.assertIs(type(exc), StopIteration) self.assertEqual(exc.value, "PASSED") class FinalizationTest(unittest.TestCase): def test_frame_resurrect(self): # A generator frame can be resurrected by a generator's finalization. def gen(): nonlocal frame try: yield finally: frame = sys._getframe() g = gen() wr = weakref.ref(g) next(g) del g support.gc_collect() self.assertIs(wr(), None) self.assertTrue(frame) del frame support.gc_collect() def test_refcycle(self): # A generator caught in a refcycle gets finalized anyway. old_garbage = gc.garbage[:] finalized = False def gen(): nonlocal finalized try: g = yield yield 1 finally: finalized = True g = gen() next(g) g.send(g) self.assertGreater(sys.getrefcount(g), 2) self.assertFalse(finalized) del g support.gc_collect() self.assertTrue(finalized) self.assertEqual(gc.garbage, old_garbage) def test_lambda_generator(self): # Issue #23192: Test that a lambda returning a generator behaves # like the equivalent function f = lambda: (yield 1) def g(): return (yield 1) # test 'yield from' f2 = lambda: (yield from g()) def g2(): return (yield from g()) f3 = lambda: (yield from f()) def g3(): return (yield from f()) for gen_fun in (f, g, f2, g2, f3, g3): gen = gen_fun() self.assertEqual(next(gen), 1) with self.assertRaises(StopIteration) as cm: gen.send(2) self.assertEqual(cm.exception.value, 2) class GeneratorTest(unittest.TestCase): def test_name(self): def func(): yield 1 # check generator names gen = func() self.assertEqual(gen.__name__, "func") self.assertEqual(gen.__qualname__, "GeneratorTest.test_name.<locals>.func") # modify generator names gen.__name__ = "name" gen.__qualname__ = "qualname" self.assertEqual(gen.__name__, "name") self.assertEqual(gen.__qualname__, "qualname") # generator names must be a string and cannot be deleted self.assertRaises(TypeError, setattr, gen, '__name__', 123) self.assertRaises(TypeError, setattr, gen, '__qualname__', 123) self.assertRaises(TypeError, delattr, gen, '__name__') self.assertRaises(TypeError, delattr, gen, '__qualname__') # modify names of the function creating the generator func.__qualname__ = "func_qualname" func.__name__ = "func_name" gen = func() self.assertEqual(gen.__name__, "func_name") self.assertEqual(gen.__qualname__, "func_qualname") # unnamed generator gen = (x for x in range(10)) self.assertEqual(gen.__name__, "<genexpr>") self.assertEqual(gen.__qualname__, "GeneratorTest.test_name.<locals>.<genexpr>") def test_copy(self): def f(): yield 1 g = f() with self.assertRaises(TypeError): copy.copy(g) def test_pickle(self): def f(): yield 1 g = f() for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises((TypeError, pickle.PicklingError)): pickle.dumps(g, proto) class ExceptionTest(unittest.TestCase): # Tests for the issue #23353: check that the currently handled exception # is correctly saved/restored in PyEval_EvalFrameEx(). def test_except_throw(self): def store_raise_exc_generator(): try: self.assertEqual(sys.exc_info()[0], None) yield except Exception as exc: # exception raised by gen.throw(exc) self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsNone(exc.__context__) yield # ensure that the exception is not lost self.assertEqual(sys.exc_info()[0], ValueError) yield # we should be able to raise back the ValueError raise make = store_raise_exc_generator() next(make) try: raise ValueError() except Exception as exc: try: make.throw(exc) except Exception: pass next(make) with self.assertRaises(ValueError) as cm: next(make) self.assertIsNone(cm.exception.__context__) self.assertEqual(sys.exc_info(), (None, None, None)) def test_except_next(self): def gen(): self.assertEqual(sys.exc_info()[0], ValueError) yield "done" g = gen() try: raise ValueError except Exception: self.assertEqual(next(g), "done") self.assertEqual(sys.exc_info(), (None, None, None)) def test_except_gen_except(self): def gen(): try: self.assertEqual(sys.exc_info()[0], None) yield # we are called from "except ValueError:", TypeError must # inherit ValueError in its context raise TypeError() except TypeError as exc: self.assertEqual(sys.exc_info()[0], TypeError) self.assertEqual(type(exc.__context__), ValueError) # here we are still called from the "except ValueError:" self.assertEqual(sys.exc_info()[0], ValueError) yield self.assertIsNone(sys.exc_info()[0]) yield "done" g = gen() next(g) try: raise ValueError except Exception: next(g) self.assertEqual(next(g), "done") self.assertEqual(sys.exc_info(), (None, None, None)) def test_except_throw_exception_context(self): def gen(): try: try: self.assertEqual(sys.exc_info()[0], None) yield except ValueError: # we are called from "except ValueError:" self.assertEqual(sys.exc_info()[0], ValueError) raise TypeError() except Exception as exc: self.assertEqual(sys.exc_info()[0], TypeError) self.assertEqual(type(exc.__context__), ValueError) # we are still called from "except ValueError:" self.assertEqual(sys.exc_info()[0], ValueError) yield self.assertIsNone(sys.exc_info()[0]) yield "done" g = gen() next(g) try: raise ValueError except Exception as exc: g.throw(exc) self.assertEqual(next(g), "done") self.assertEqual(sys.exc_info(), (None, None, None)) def test_stopiteration_error(self): # See also PEP 479. def gen(): raise StopIteration yield with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'): next(gen()) def test_tutorial_stopiteration(self): # Raise StopIteration" stops the generator too: def f(): yield 1 raise StopIteration yield 2 # never reached g = f() self.assertEqual(next(g), 1) with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'): next(g) def test_return_tuple(self): def g(): return (yield 1) gen = g() self.assertEqual(next(gen), 1) with self.assertRaises(StopIteration) as cm: gen.send((2,)) self.assertEqual(cm.exception.value, (2,)) def test_return_stopiteration(self): def g(): return (yield 1) gen = g() self.assertEqual(next(gen), 1) with self.assertRaises(StopIteration) as cm: gen.send(StopIteration(2)) self.assertIsInstance(cm.exception.value, StopIteration) self.assertEqual(cm.exception.value.value, 2) class YieldFromTests(unittest.TestCase): def test_generator_gi_yieldfrom(self): def a(): self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING) self.assertIsNone(gen_b.gi_yieldfrom) yield self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING) self.assertIsNone(gen_b.gi_yieldfrom) def b(): self.assertIsNone(gen_b.gi_yieldfrom) yield from a() self.assertIsNone(gen_b.gi_yieldfrom) yield self.assertIsNone(gen_b.gi_yieldfrom) gen_b = b() self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CREATED) self.assertIsNone(gen_b.gi_yieldfrom) gen_b.send(None) self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED) self.assertEqual(gen_b.gi_yieldfrom.gi_code.co_name, 'a') gen_b.send(None) self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED) self.assertIsNone(gen_b.gi_yieldfrom) [] = gen_b # Exhaust generator self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_CLOSED) self.assertIsNone(gen_b.gi_yieldfrom) tutorial_tests = """ Let's try a simple generator: >>> def f(): ... yield 1 ... yield 2 >>> for i in f(): ... print(i) 1 2 >>> g = f() >>> next(g) 1 >>> next(g) 2 "Falling off the end" stops the generator: >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g StopIteration "return" also stops the generator: >>> def f(): ... yield 1 ... return ... yield 2 # never reached ... >>> g = f() >>> next(g) 1 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in f StopIteration >>> next(g) # once stopped, can't be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration However, "return" and StopIteration are not exactly equivalent: >>> def g1(): ... try: ... return ... except: ... yield 1 ... >>> list(g1()) [] >>> def g2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(g2())) [42] This may be surprising at first: >>> def g3(): ... try: ... return ... finally: ... yield 1 ... >>> list(g3()) [1] Let's create an alternate range() function implemented as a generator: >>> def yrange(n): ... for i in range(n): ... yield i ... >>> list(yrange(5)) [0, 1, 2, 3, 4] Generators always return to the most recent caller: >>> def creator(): ... r = yrange(5) ... print("creator", next(r)) ... return r ... >>> def caller(): ... r = creator() ... for i in r: ... print("caller", i) ... >>> caller() creator 0 caller 1 caller 2 caller 3 caller 4 Generators can call other generators: >>> def zrange(n): ... for i in yrange(n): ... yield i ... >>> list(zrange(5)) [0, 1, 2, 3, 4] """ # The examples from PEP 255. pep_tests = """ Specification: Yield Restriction: A generator cannot be resumed while it is actively running: >>> def g(): ... i = next(me) ... yield i >>> me = g() >>> next(me) Traceback (most recent call last): ... File "<string>", line 2, in g ValueError: generator already executing Specification: Return Note that return isn't always equivalent to raising StopIteration: the difference lies in how enclosing try/except constructs are treated. For example, >>> def f1(): ... try: ... return ... except: ... yield 1 >>> print(list(f1())) [] because, as in any function, return simply exits, but >>> def f2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(f2())) [42] because StopIteration is captured by a bare "except", as is any exception. Specification: Generators and Exception Propagation >>> def f(): ... return 1//0 >>> def g(): ... yield f() # the zero division exception propagates ... yield 42 # and we'll never get here >>> k = g() >>> next(k) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g File "<stdin>", line 2, in f ZeroDivisionError: integer division or modulo by zero >>> next(k) # and the generator cannot be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>> Specification: Try/Except/Finally >>> def f(): ... try: ... yield 1 ... try: ... yield 2 ... 1//0 ... yield 3 # never get here ... except ZeroDivisionError: ... yield 4 ... yield 5 ... raise ... except: ... yield 6 ... yield 7 # the "raise" above stops this ... except: ... yield 8 ... yield 9 ... try: ... x = 12 ... finally: ... yield 10 ... yield 11 >>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] >>> Guido's binary tree example. >>> # A binary tree class. >>> class Tree: ... ... def __init__(self, label, left=None, right=None): ... self.label = label ... self.left = left ... self.right = right ... ... def __repr__(self, level=0, indent=" "): ... s = level*indent + repr(self.label) ... if self.left: ... s = s + "\\n" + self.left.__repr__(level+1, indent) ... if self.right: ... s = s + "\\n" + self.right.__repr__(level+1, indent) ... return s ... ... def __iter__(self): ... return inorder(self) >>> # Create a Tree from a list. >>> def tree(list): ... n = len(list) ... if n == 0: ... return [] ... i = n // 2 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:])) >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # A recursive generator that generates Tree labels in in-order. >>> def inorder(t): ... if t: ... for x in inorder(t.left): ... yield x ... yield t.label ... for x in inorder(t.right): ... yield x >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. >>> def inorder(node): ... stack = [] ... while node: ... while node.left: ... stack.append(node) ... node = node.left ... yield node.label ... while not node.right: ... try: ... node = stack.pop() ... except IndexError: ... return ... yield node.label ... node = node.right >>> # Exercise the non-recursive generator. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z """ # Examples from Iterator-List and Python-Dev and c.l.py. email_tests = """ The difference between yielding None and returning it. >>> def g(): ... for i in range(3): ... yield None ... yield None ... return >>> list(g()) [None, None, None, None] Ensure that explicitly raising StopIteration acts like any other exception in try/except, not like a return. >>> def g(): ... yield 1 ... try: ... raise StopIteration ... except: ... yield 2 ... yield 3 >>> list(g()) [1, 2, 3] Next one was posted to c.l.py. >>> def gcomb(x, k): ... "Generate all combinations of k elements from list x." ... ... if k > len(x): ... return ... if k == 0: ... yield [] ... else: ... first, rest = x[0], x[1:] ... # A combination does or doesn't contain first. ... # If it does, the remainder is a k-1 comb of rest. ... for c in gcomb(rest, k-1): ... c.insert(0, first) ... yield c ... # If it doesn't contain first, it's a k comb of rest. ... for c in gcomb(rest, k): ... yield c >>> seq = list(range(1, 5)) >>> for k in range(len(seq) + 2): ... print("%d-combs of %s:" % (k, seq)) ... for c in gcomb(seq, k): ... print(" ", c) 0-combs of [1, 2, 3, 4]: [] 1-combs of [1, 2, 3, 4]: [1] [2] [3] [4] 2-combs of [1, 2, 3, 4]: [1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4] 3-combs of [1, 2, 3, 4]: [1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4] 4-combs of [1, 2, 3, 4]: [1, 2, 3, 4] 5-combs of [1, 2, 3, 4]: From the Iterators list, about the types of these things. >>> def g(): ... yield 1 ... >>> type(g) <class 'function'> >>> i = g() >>> type(i) <class 'generator'> >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'] >>> from test.support import HAVE_DOCSTRINGS >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'Implement next(self).') Implement next(self). >>> iter(i) is i True >>> import types >>> isinstance(i, types.GeneratorType) True And more, added later. >>> i.gi_running 0 >>> type(i.gi_frame) <class 'frame'> >>> i.gi_running = 42 Traceback (most recent call last): ... AttributeError: readonly attribute >>> def g(): ... yield me.gi_running >>> me = g() >>> me.gi_running 0 >>> next(me) 1 >>> me.gi_running 0 A clever union-find implementation from c.l.py, due to David Eppstein. Sent: Friday, June 29, 2001 12:16 PM To: python-list@python.org Subject: Re: PEP 255: Simple Generators >>> class disjointSet: ... def __init__(self, name): ... self.name = name ... self.parent = None ... self.generator = self.generate() ... ... def generate(self): ... while not self.parent: ... yield self ... for x in self.parent.generator: ... yield x ... ... def find(self): ... return next(self.generator) ... ... def union(self, parent): ... if self.parent: ... raise ValueError("Sorry, I'm not a root!") ... self.parent = parent ... ... def __str__(self): ... return self.name >>> names = "ABCDEFGHIJKLM" >>> sets = [disjointSet(name) for name in names] >>> roots = sets[:] >>> import random >>> gen = random.Random(42) >>> while 1: ... for s in sets: ... print(" %s->%s" % (s, s.find()), end='') ... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) ... roots.remove(s1) ... s2 = gen.choice(roots) ... s1.union(s2) ... print("merged", s1, "into", s2) ... else: ... break A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M merged K into B A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged A into F A->F B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged E into F A->F B->B C->C D->D E->F F->F G->G H->H I->I J->J K->B L->L M->M merged D into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->M merged M into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->C merged J into B A->F B->B C->C D->C E->F F->F G->G H->H I->I J->B K->B L->L M->C merged B into C A->F B->C C->C D->C E->F F->F G->G H->H I->I J->C K->C L->L M->C merged F into G A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->L M->C merged L into C A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->C M->C merged G into I A->I B->C C->C D->C E->I F->I G->I H->H I->I J->C K->C L->C M->C merged I into H A->H B->C C->C D->C E->H F->H G->H H->H I->H J->C K->C L->C M->C merged C into H A->H B->H C->H D->H E->H F->H G->H H->H I->H J->H K->H L->H M->H """ # Emacs turd ' # Fun tests (for sufficiently warped notions of "fun"). fun_tests = """ Build up to a recursive Sieve of Eratosthenes generator. >>> def firstn(g, n): ... return [next(g) for i in range(n)] >>> def intsfrom(i): ... while 1: ... yield i ... i += 1 >>> firstn(intsfrom(5), 7) [5, 6, 7, 8, 9, 10, 11] >>> def exclude_multiples(n, ints): ... for i in ints: ... if i % n: ... yield i >>> firstn(exclude_multiples(3, intsfrom(1)), 6) [1, 2, 4, 5, 7, 8] >>> def sieve(ints): ... prime = next(ints) ... yield prime ... not_divisible_by_prime = exclude_multiples(prime, ints) ... for p in sieve(not_divisible_by_prime): ... yield p >>> primes = sieve(intsfrom(2)) >>> firstn(primes, 20) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71] Another famous problem: generate all integers of the form 2**i * 3**j * 5**k in increasing order, where i,j,k >= 0. Trickier than it may look at first! Try writing it without generators, and correctly, and without generating 3 internal results for each result output. >>> def times(n, g): ... for i in g: ... yield n * i >>> firstn(times(10, intsfrom(1)), 10) [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> def merge(g, h): ... ng = next(g) ... nh = next(h) ... while 1: ... if ng < nh: ... yield ng ... ng = next(g) ... elif ng > nh: ... yield nh ... nh = next(h) ... else: ... yield ng ... ng = next(g) ... nh = next(h) The following works, but is doing a whale of a lot of redundant work -- it's not clear how to get the internal uses of m235 to share a single generator. Note that me_times2 (etc) each need to see every element in the result sequence. So this is an example where lazy lists are more natural (you can look at the head of a lazy list any number of times). >>> def m235(): ... yield 1 ... me_times2 = times(2, m235()) ... me_times3 = times(3, m235()) ... me_times5 = times(5, m235()) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Don't print "too many" of these -- the implementation above is extremely inefficient: each call of m235() leads to 3 recursive calls, and in turn each of those 3 more, and so on, and so on, until we've descended enough levels to satisfy the print stmts. Very odd: when I printed 5 lines of results below, this managed to screw up Win98's malloc in "the usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting address space, and it *looked* like a very slow leak. >>> result = m235() >>> for i in range(3): ... print(firstn(result, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] Heh. Here's one way to get a shared list, complete with an excruciating namespace renaming trick. The *pretty* part is that the times() and merge() functions can be reused as-is, because they only assume their stream arguments are iterable -- a LazyList is the same as a generator to times(). >>> class LazyList: ... def __init__(self, g): ... self.sofar = [] ... self.fetch = g.__next__ ... ... def __getitem__(self, i): ... sofar, fetch = self.sofar, self.fetch ... while i >= len(sofar): ... sofar.append(fetch()) ... return sofar[i] >>> def m235(): ... yield 1 ... # Gack: m235 below actually refers to a LazyList. ... me_times2 = times(2, m235) ... me_times3 = times(3, m235) ... me_times5 = times(5, m235) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Print as many of these as you like -- *this* implementation is memory- efficient. >>> m235 = LazyList(m235()) >>> for i in range(5): ... print([m235[j] for j in range(15*i, 15*(i+1))]) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] Ye olde Fibonacci generator, LazyList style. >>> def fibgen(a, b): ... ... def sum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def tail(g): ... next(g) # throw first away ... for x in g: ... yield x ... ... yield a ... yield b ... for s in sum(iter(fib), ... tail(iter(fib))): ... yield s >>> fib = LazyList(fibgen(1, 2)) >>> firstn(iter(fib), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] Running after your tail with itertools.tee (new in version 2.4) The algorithms "m235" (Hamming) and Fibonacci presented above are both examples of a whole family of FP (functional programming) algorithms where a function produces and returns a list while the production algorithm suppose the list as already produced by recursively calling itself. For these algorithms to work, they must: - produce at least a first element without presupposing the existence of the rest of the list - produce their elements in a lazy manner To work efficiently, the beginning of the list must not be recomputed over and over again. This is ensured in most FP languages as a built-in feature. In python, we have to explicitly maintain a list of already computed results and abandon genuine recursivity. This is what had been attempted above with the LazyList class. One problem with that class is that it keeps a list of all of the generated results and therefore continually grows. This partially defeats the goal of the generator concept, viz. produce the results only as needed instead of producing them all and thereby wasting memory. Thanks to itertools.tee, it is now clear "how to get the internal uses of m235 to share a single generator". >>> from itertools import tee >>> def m235(): ... def _m235(): ... yield 1 ... for n in merge(times(2, m2), ... merge(times(3, m3), ... times(5, m5))): ... yield n ... m1 = _m235() ... m2, m3, m5, mRes = tee(m1, 4) ... return mRes >>> it = m235() >>> for i in range(5): ... print(firstn(it, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] The "tee" function does just what we want. It internally keeps a generated result for as long as it has not been "consumed" from all of the duplicated iterators, whereupon it is deleted. You can therefore print the hamming sequence during hours without increasing memory usage, or very little. The beauty of it is that recursive running-after-their-tail FP algorithms are quite straightforwardly expressed with this Python idiom. Ye olde Fibonacci generator, tee style. >>> def fib(): ... ... def _isum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def _fib(): ... yield 1 ... yield 2 ... next(fibTail) # throw first away ... for res in _isum(fibHead, fibTail): ... yield res ... ... realfib = _fib() ... fibHead, fibTail, fibRes = tee(realfib, 3) ... return fibRes >>> firstn(fib(), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] """ # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0 # hackery. syntax_tests = """ These are fine: >>> def f(): ... yield 1 ... return >>> def f(): ... try: ... yield 1 ... finally: ... pass >>> def f(): ... try: ... try: ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... pass ... finally: ... pass >>> def f(): ... try: ... try: ... yield 12 ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... try: ... x = 12 ... finally: ... yield 12 ... except: ... return >>> list(f()) [12, 666] >>> def f(): ... yield >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... yield >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... yield 1 >>> type(f()) <class 'generator'> >>> def f(): ... if "": ... yield None >>> type(f()) <class 'generator'> >>> def f(): ... return ... try: ... if x==4: ... pass ... elif 0: ... try: ... 1//0 ... except SyntaxError: ... pass ... else: ... if 0: ... while 12: ... x += 1 ... yield 2 # don't blink ... f(a, b, c, d, e) ... else: ... pass ... except: ... x = 1 ... return >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... def g(): ... yield 1 ... >>> type(f()) <class 'NoneType'> >>> def f(): ... if 0: ... class C: ... def __init__(self): ... yield 1 ... def f(self): ... yield 2 >>> type(f()) <class 'NoneType'> >>> def f(): ... if 0: ... return ... if 0: ... yield 2 >>> type(f()) <class 'generator'> This one caused a crash (see SF bug 567538): >>> def f(): ... for i in range(3): ... try: ... continue ... finally: ... yield i ... >>> g = f() >>> print(next(g)) 0 >>> print(next(g)) 1 >>> print(next(g)) 2 >>> print(next(g)) Traceback (most recent call last): StopIteration Test the gi_code attribute >>> def f(): ... yield 5 ... >>> g = f() >>> g.gi_code is f.__code__ True >>> next(g) 5 >>> next(g) Traceback (most recent call last): StopIteration >>> g.gi_code is f.__code__ True
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_time.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_time.py
from test import support import decimal import enum import locale import math import platform import sys import sysconfig import time import threading import unittest import warnings try: import _testcapi except ImportError: _testcapi = None # Max year is only limited by the size of C int. SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4 TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1 TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900 SEC_TO_US = 10 ** 6 US_TO_NS = 10 ** 3 MS_TO_NS = 10 ** 6 SEC_TO_NS = 10 ** 9 NS_TO_SEC = 10 ** 9 class _PyTime(enum.IntEnum): # Round towards minus infinity (-inf) ROUND_FLOOR = 0 # Round towards infinity (+inf) ROUND_CEILING = 1 # Round to nearest with ties going to nearest even integer ROUND_HALF_EVEN = 2 # Round away from zero ROUND_UP = 3 # Rounding modes supported by PyTime ROUNDING_MODES = ( # (PyTime rounding method, decimal rounding method) (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR), (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING), (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN), (_PyTime.ROUND_UP, decimal.ROUND_UP), ) class TimeTestCase(unittest.TestCase): def setUp(self): self.t = time.time() def test_data_attributes(self): time.altzone time.daylight time.timezone time.tzname def test_time(self): time.time() info = time.get_clock_info('time') self.assertFalse(info.monotonic) self.assertTrue(info.adjustable) def test_time_ns_type(self): def check_ns(sec, ns): self.assertIsInstance(ns, int) sec_ns = int(sec * 1e9) # tolerate a difference of 50 ms self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns)) check_ns(time.time(), time.time_ns()) check_ns(time.monotonic(), time.monotonic_ns()) check_ns(time.perf_counter(), time.perf_counter_ns()) check_ns(time.process_time(), time.process_time_ns()) if hasattr(time, 'thread_time'): check_ns(time.thread_time(), time.thread_time_ns()) if hasattr(time, 'clock_gettime'): check_ns(time.clock_gettime(time.CLOCK_REALTIME), time.clock_gettime_ns(time.CLOCK_REALTIME)) def test_clock(self): with self.assertWarns(DeprecationWarning): time.clock() with self.assertWarns(DeprecationWarning): info = time.get_clock_info('clock') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_clock_realtime(self): t = time.clock_gettime(time.CLOCK_REALTIME) self.assertIsInstance(t, float) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'), 'need time.CLOCK_MONOTONIC') def test_clock_monotonic(self): a = time.clock_gettime(time.CLOCK_MONOTONIC) b = time.clock_gettime(time.CLOCK_MONOTONIC) self.assertLessEqual(a, b) @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'), 'need time.pthread_getcpuclockid()') @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_pthread_getcpuclockid(self): clk_id = time.pthread_getcpuclockid(threading.get_ident()) self.assertTrue(type(clk_id) is int) self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) t1 = time.clock_gettime(clk_id) t2 = time.clock_gettime(clk_id) self.assertLessEqual(t1, t2) @unittest.skipUnless(hasattr(time, 'clock_getres'), 'need time.clock_getres()') def test_clock_getres(self): res = time.clock_getres(time.CLOCK_REALTIME) self.assertGreater(res, 0.0) self.assertLessEqual(res, 1.0) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime()') def test_clock_settime(self): t = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, t) except PermissionError: pass if hasattr(time, 'CLOCK_MONOTONIC'): self.assertRaises(OSError, time.clock_settime, time.CLOCK_MONOTONIC, 0) def test_conversions(self): self.assertEqual(time.ctime(self.t), time.asctime(time.localtime(self.t))) self.assertEqual(int(time.mktime(time.localtime(self.t))), int(self.t)) def test_sleep(self): self.assertRaises(ValueError, time.sleep, -2) self.assertRaises(ValueError, time.sleep, -1) time.sleep(1.2) def test_strftime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strftime(format, tt) except ValueError: self.fail('conversion specifier: %r failed.' % format) self.assertRaises(TypeError, time.strftime, b'%S', tt) # embedded null character self.assertRaises(ValueError, time.strftime, '%S\0', tt) def _bounds_checking(self, func): # Make sure that strftime() checks the bounds of the various parts # of the time tuple (0 is valid for *all* values). # The year field is tested by other test cases above # Check month [1, 12] + zero support func((1900, 0, 1, 0, 0, 0, 0, 1, -1)) func((1900, 12, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, -1, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 13, 1, 0, 0, 0, 0, 1, -1)) # Check day of month [1, 31] + zero support func((1900, 1, 0, 0, 0, 0, 0, 1, -1)) func((1900, 1, 31, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, -1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 32, 0, 0, 0, 0, 1, -1)) # Check hour [0, 23] func((1900, 1, 1, 23, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, -1, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 24, 0, 0, 0, 1, -1)) # Check minute [0, 59] func((1900, 1, 1, 0, 59, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, -1, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 60, 0, 0, 1, -1)) # Check second [0, 61] self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, -1, 0, 1, -1)) # C99 only requires allowing for one leap second, but Python's docs say # allow two leap seconds (0..61) func((1900, 1, 1, 0, 0, 60, 0, 1, -1)) func((1900, 1, 1, 0, 0, 61, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 62, 0, 1, -1)) # No check for upper-bound day of week; # value forced into range by a ``% 7`` calculation. # Start check at -2 since gettmarg() increments value before taking # modulo. self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)), func((1900, 1, 1, 0, 0, 0, +6, 1, -1))) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, -2, 1, -1)) # Check day of the year [1, 366] + zero support func((1900, 1, 1, 0, 0, 0, 0, 0, -1)) func((1900, 1, 1, 0, 0, 0, 0, 366, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, -1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, 367, -1)) def test_strftime_bounding_check(self): self._bounds_checking(lambda tup: time.strftime('', tup)) def test_strftime_format_check(self): # Test that strftime does not crash on invalid format strings # that may trigger a buffer overread. When not triggered, # strftime may succeed or raise ValueError depending on # the platform. for x in [ '', 'A', '%A', '%AA' ]: for y in range(0x0, 0x10): for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]: try: time.strftime(x * y + z) except ValueError: pass def test_default_values_for_zero(self): # Make sure that using all zeros uses the proper default # values. No test for daylight savings since strftime() does # not change output based on its value and no test for year # because systems vary in their support for year 0. expected = "2000 01 01 00 00 00 1 001" with support.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8) self.assertEqual(expected, result) def test_strptime(self): # Should be able to go round-trip from strftime to strptime without # raising an exception. tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = '%' + directive strf_output = time.strftime(format, tt) try: time.strptime(strf_output, format) except ValueError: self.fail("conversion specifier %r failed with '%s' input." % (format, strf_output)) def test_strptime_bytes(self): # Make sure only strings are accepted as arguments to strptime. self.assertRaises(TypeError, time.strptime, b'2009', "%Y") self.assertRaises(TypeError, time.strptime, '2009', b'%Y') def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see #17572) with self.assertRaises(ValueError) as e: time.strptime('', '%D') self.assertIs(e.exception.__suppress_context__, True) # additional check for IndexError branch (issue #19545) with self.assertRaises(ValueError) as e: time.strptime('19', '%Y %') self.assertIs(e.exception.__suppress_context__, True) def test_asctime(self): time.asctime(time.gmtime(self.t)) # Max year is only limited by the size of C int. for bigyear in TIME_MAXYEAR, TIME_MINYEAR: asc = time.asctime((bigyear, 6, 1) + (0,) * 6) self.assertEqual(asc[-len(str(bigyear)):], str(bigyear)) self.assertRaises(OverflowError, time.asctime, (TIME_MAXYEAR + 1,) + (0,) * 8) self.assertRaises(OverflowError, time.asctime, (TIME_MINYEAR - 1,) + (0,) * 8) self.assertRaises(TypeError, time.asctime, 0) self.assertRaises(TypeError, time.asctime, ()) self.assertRaises(TypeError, time.asctime, (0,) * 10) def test_asctime_bounding_check(self): self._bounds_checking(time.asctime) def test_ctime(self): t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973') t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000') for year in [-100, 100, 1000, 2000, 2050, 10000]: try: testval = time.mktime((year, 1, 10) + (0,)*6) except (ValueError, OverflowError): # If mktime fails, ctime will fail too. This may happen # on some platforms. pass else: self.assertEqual(time.ctime(testval)[20:], str(year)) @unittest.skipUnless(hasattr(time, "tzset"), "time module has no attribute tzset") def test_tzset(self): from os import environ # Epoch time of midnight Dec 25th 2002. Never DST in northern # hemisphere. xmas2002 = 1040774400.0 # These formats are correct for 2002, and possibly future years # This format is the 'standard' as documented at: # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html # They are also documented in the tzset(3) man page on most Unix # systems. eastern = 'EST+05EDT,M4.1.0,M10.5.0' victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0' utc='UTC+0' org_TZ = environ.get('TZ',None) try: # Make sure we can switch to UTC time and results are correct # Note that unknown timezones default to UTC. # Note that altzone is undefined in UTC, as there is no DST environ['TZ'] = eastern time.tzset() environ['TZ'] = utc time.tzset() self.assertEqual( time.gmtime(xmas2002), time.localtime(xmas2002) ) self.assertEqual(time.daylight, 0) self.assertEqual(time.timezone, 0) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) # Make sure we can switch to US/Eastern environ['TZ'] = eastern time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) self.assertEqual(time.tzname, ('EST', 'EDT')) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, 18000) self.assertEqual(time.altzone, 14400) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) self.assertEqual(len(time.tzname), 2) # Now go to the southern hemisphere. environ['TZ'] = victoria time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) # Issue #11886: Australian Eastern Standard Time (UTC+10) is called # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST" # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone), # on some operating systems (e.g. FreeBSD), which is wrong. See for # example this bug: # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0]) self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1])) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, -36000) self.assertEqual(time.altzone, -39600) self.assertEqual(time.localtime(xmas2002).tm_isdst, 1) finally: # Repair TZ environment variable in case any other tests # rely on it. if org_TZ is not None: environ['TZ'] = org_TZ elif 'TZ' in environ: del environ['TZ'] time.tzset() def test_insane_timestamps(self): # It's possible that some platform maps time_t to double, # and that this test will fail there. This test should # exempt such platforms (provided they return reasonable # results!). for func in time.ctime, time.gmtime, time.localtime: for unreasonable in -1e200, 1e200: self.assertRaises(OverflowError, func, unreasonable) def test_ctime_without_arg(self): # Not sure how to check the values, since the clock could tick # at any time. Make sure these are at least accepted and # don't raise errors. time.ctime() time.ctime(None) def test_gmtime_without_arg(self): gt0 = time.gmtime() gt1 = time.gmtime(None) t0 = time.mktime(gt0) t1 = time.mktime(gt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_localtime_without_arg(self): lt0 = time.localtime() lt1 = time.localtime(None) t0 = time.mktime(lt0) t1 = time.mktime(lt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_mktime(self): # Issue #1726687 for t in (-2, -1, 0, 1): if sys.platform.startswith('aix') and t == -1: # Issue #11188, #19748: mktime() returns -1 on error. On Linux, # the tm_wday field is used as a sentinel () to detect if -1 is # really an error or a valid timestamp. On AIX, tm_wday is # unchanged even on success and so cannot be used as a # sentinel. continue try: tt = time.localtime(t) except (OverflowError, OSError): pass else: self.assertEqual(time.mktime(tt), t) # Issue #13309: passing extreme values to mktime() or localtime() # borks the glibc's internal timezone data. @unittest.skipUnless(platform.libc_ver()[0] != 'glibc', "disabled because of a bug in glibc. Issue #13309") def test_mktime_error(self): # It may not be possible to reliably make mktime return error # on all platfom. This will make sure that no other exception # than OverflowError is raised for an extreme value. tt = time.gmtime(self.t) tzname = time.strftime('%Z', tt) self.assertNotEqual(tzname, 'LMT') try: time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1)) except OverflowError: pass self.assertEqual(time.strftime('%Z', tt), tzname) def test_monotonic(self): # monotonic() should not go backward times = [time.monotonic() for n in range(100)] t1 = times[0] for t2 in times[1:]: self.assertGreaterEqual(t2, t1, "times=%s" % times) t1 = t2 # monotonic() includes time elapsed during a sleep t1 = time.monotonic() time.sleep(0.5) t2 = time.monotonic() dt = t2 - t1 self.assertGreater(t2, t1) # bpo-20101: tolerate a difference of 50 ms because of bad timer # resolution on Windows self.assertTrue(0.450 <= dt) # monotonic() is a monotonic but non adjustable clock info = time.get_clock_info('monotonic') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_perf_counter(self): time.perf_counter() def test_process_time(self): # process_time() should not include time spend during a sleep start = time.process_time() time.sleep(0.100) stop = time.process_time() # use 20 ms because process_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('process_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_thread_time(self): if not hasattr(time, 'thread_time'): if sys.platform.startswith(('linux', 'win')): self.fail("time.thread_time() should be available on %r" % (sys.platform,)) else: self.skipTest("need time.thread_time") # thread_time() should not include time spend during a sleep start = time.thread_time() time.sleep(0.100) stop = time.thread_time() # use 20 ms because thread_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('thread_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime') def test_monotonic_settime(self): t1 = time.monotonic() realtime = time.clock_gettime(time.CLOCK_REALTIME) # jump backward with an offset of 1 hour try: time.clock_settime(time.CLOCK_REALTIME, realtime - 3600) except PermissionError as err: self.skipTest(err) t2 = time.monotonic() time.clock_settime(time.CLOCK_REALTIME, realtime) # monotonic must not be affected by system clock updates self.assertGreaterEqual(t2, t1) def test_localtime_failure(self): # Issue #13847: check for localtime() failure invalid_time_t = None for time_t in (-1, 2**30, 2**33, 2**60): try: time.localtime(time_t) except OverflowError: self.skipTest("need 64-bit time_t") except OSError: invalid_time_t = time_t break if invalid_time_t is None: self.skipTest("unable to find an invalid time_t value") self.assertRaises(OSError, time.localtime, invalid_time_t) self.assertRaises(OSError, time.ctime, invalid_time_t) # Issue #26669: check for localtime() failure self.assertRaises(ValueError, time.localtime, float("nan")) self.assertRaises(ValueError, time.ctime, float("nan")) def test_get_clock_info(self): clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time'] for name in clocks: if name == 'clock': with self.assertWarns(DeprecationWarning): info = time.get_clock_info('clock') else: info = time.get_clock_info(name) #self.assertIsInstance(info, dict) self.assertIsInstance(info.implementation, str) self.assertNotEqual(info.implementation, '') self.assertIsInstance(info.monotonic, bool) self.assertIsInstance(info.resolution, float) # 0.0 < resolution <= 1.0 self.assertGreater(info.resolution, 0.0) self.assertLessEqual(info.resolution, 1.0) self.assertIsInstance(info.adjustable, bool) self.assertRaises(ValueError, time.get_clock_info, 'xxx') class TestLocale(unittest.TestCase): def setUp(self): self.oldloc = locale.setlocale(locale.LC_ALL) def tearDown(self): locale.setlocale(locale.LC_ALL, self.oldloc) def test_bug_3061(self): try: tmp = locale.setlocale(locale.LC_ALL, "fr_FR") except locale.Error: self.skipTest('could not set locale.LC_ALL to fr_FR') # This should not cause an exception time.strftime("%B", (2009,2,1,0,0,0,0,0,0)) class _TestAsctimeYear: _format = '%d' def yearstr(self, y): return time.asctime((y,) + (0,) * 8).split()[-1] def test_large_year(self): # Check that it doesn't crash for year > 9999 self.assertEqual(self.yearstr(12345), '12345') self.assertEqual(self.yearstr(123456789), '123456789') class _TestStrftimeYear: # Issue 13305: For years < 1000, the value is not always # padded to 4 digits across platforms. The C standard # assumes year >= 1900, so it does not specify the number # of digits. if time.strftime('%Y', (1,) + (0,) * 8) == '0001': _format = '%04d' else: _format = '%d' def yearstr(self, y): return time.strftime('%Y', (y,) + (0,) * 8) def test_4dyear(self): # Check that we can return the zero padded value. if self._format == '%04d': self.test_year('%04d') else: def year4d(y): return time.strftime('%4Y', (y,) + (0,) * 8) self.test_year('%04d', func=year4d) def skip_if_not_supported(y): msg = "strftime() is limited to [1; 9999] with Visual Studio" # Check that it doesn't crash for year > 9999 try: time.strftime('%Y', (y,) + (0,) * 8) except ValueError: cond = False else: cond = True return unittest.skipUnless(cond, msg) @skip_if_not_supported(10000) def test_large_year(self): return super().test_large_year() @skip_if_not_supported(0) def test_negative(self): return super().test_negative() del skip_if_not_supported class _Test4dYear: _format = '%d' def test_year(self, fmt=None, func=None): fmt = fmt or self._format func = func or self.yearstr self.assertEqual(func(1), fmt % 1) self.assertEqual(func(68), fmt % 68) self.assertEqual(func(69), fmt % 69) self.assertEqual(func(99), fmt % 99) self.assertEqual(func(999), fmt % 999) self.assertEqual(func(9999), fmt % 9999) def test_large_year(self): self.assertEqual(self.yearstr(12345).lstrip('+'), '12345') self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789') self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR)) self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1) def test_negative(self): self.assertEqual(self.yearstr(-1), self._format % -1) self.assertEqual(self.yearstr(-1234), '-1234') self.assertEqual(self.yearstr(-123456), '-123456') self.assertEqual(self.yearstr(-123456789), str(-123456789)) self.assertEqual(self.yearstr(-1234567890), str(-1234567890)) self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR)) # Modules/timemodule.c checks for underflow self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1) with self.assertRaises(OverflowError): self.yearstr(-TIME_MAXYEAR - 1) class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase): pass class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase): pass class TestPytime(unittest.TestCase): @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_localtime_timezone(self): # Get the localtime and examine it for the offset and zone. lt = time.localtime() self.assertTrue(hasattr(lt, "tm_gmtoff")) self.assertTrue(hasattr(lt, "tm_zone")) # See if the offset and zone are similar to the module # attributes. if lt.tm_gmtoff is None: self.assertTrue(not hasattr(time, "timezone")) else: self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst]) if lt.tm_zone is None: self.assertTrue(not hasattr(time, "tzname")) else: self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst]) # Try and make UNIX times from the localtime and a 9-tuple # created from the localtime. Test to see that the times are # the same. t = time.mktime(lt); t9 = time.mktime(lt[:9]) self.assertEqual(t, t9) # Make localtimes from the UNIX times and compare them to # the original localtime, thus making a round trip. new_lt = time.localtime(t); new_lt9 = time.localtime(t9) self.assertEqual(new_lt, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt.tm_zone, lt.tm_zone) self.assertEqual(new_lt9, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt9.tm_zone, lt.tm_zone) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_strptime_timezone(self): t = time.strptime("UTC", "%Z") self.assertEqual(t.tm_zone, 'UTC') t = time.strptime("+0500", "%z") self.assertEqual(t.tm_gmtoff, 5 * 3600) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_short_times(self): import pickle # Load a short time structure using pickle. st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n." lt = pickle.loads(st) self.assertIs(lt.tm_gmtoff, None) self.assertIs(lt.tm_zone, None) @unittest.skipIf(_testcapi is None, 'need the _testcapi module') class CPyTimeTestCase: """ Base class to test the C _PyTime_t API. """ OVERFLOW_SECONDS = None def setUp(self): from _testcapi import SIZEOF_TIME_T bits = SIZEOF_TIME_T * 8 - 1 self.time_t_min = -2 ** bits self.time_t_max = 2 ** bits - 1 def time_t_filter(self, seconds): return (self.time_t_min <= seconds <= self.time_t_max) def _rounding_values(self, use_float): "Build timestamps used to test rounding." units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS] if use_float: # picoseconds are only tested to pytime_converter accepting floats units.append(1e-3) values = ( # small values 1, 2, 5, 7, 123, 456, 1234, # 10^k - 1 9, 99, 999, 9999, 99999, 999999, # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5 499, 500, 501, 1499, 1500, 1501, 2500, 3500, 4500, ) ns_timestamps = [0] for unit in units: for value in values: ns = value * unit ns_timestamps.extend((-ns, ns)) for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33): ns = (2 ** pow2) * SEC_TO_NS ns_timestamps.extend(( -ns-1, -ns, -ns+1, ns-1, ns, ns+1 )) for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX): ns_timestamps.append(seconds * SEC_TO_NS) if use_float: # numbers with an exact representation in IEEE 754 (base 2) for pow2 in (3, 7, 10, 15): ns = 2.0 ** (-pow2) ns_timestamps.extend((-ns, ns)) # seconds close to _PyTime_t type limit ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS ns_timestamps.extend((-ns, ns)) return ns_timestamps def _check_rounding(self, pytime_converter, expected_func, use_float, unit_to_sec, value_filter=None): def convert_values(ns_timestamps): if use_float: unit_to_ns = SEC_TO_NS / float(unit_to_sec) values = [ns / unit_to_ns for ns in ns_timestamps] else: unit_to_ns = SEC_TO_NS // unit_to_sec values = [ns // unit_to_ns for ns in ns_timestamps] if value_filter: values = filter(value_filter, values) # remove duplicates and sort return sorted(set(values)) # test rounding ns_timestamps = self._rounding_values(use_float) valid_values = convert_values(ns_timestamps) for time_rnd, decimal_rnd in ROUNDING_MODES : with decimal.localcontext() as context: context.rounding = decimal_rnd for value in valid_values: debug_info = {'value': value, 'rounding': decimal_rnd} try: result = pytime_converter(value, time_rnd) expected = expected_func(value) except Exception as exc: self.fail("Error on timestamp conversion: %s" % debug_info) self.assertEqual(result, expected, debug_info) # test overflow ns = self.OVERFLOW_SECONDS * SEC_TO_NS ns_timestamps = (-ns, ns) overflow_values = convert_values(ns_timestamps) for time_rnd, _ in ROUNDING_MODES : for value in overflow_values: debug_info = {'value': value, 'rounding': time_rnd} with self.assertRaises(OverflowError, msg=debug_info): pytime_converter(value, time_rnd) def check_int_rounding(self, pytime_converter, expected_func,
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_ast.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ast.py
import ast import dis import os import sys import unittest import weakref from textwrap import dedent from test import support def to_tuple(t): if t is None or isinstance(t, (str, int, complex)): return t elif isinstance(t, list): return [to_tuple(e) for e in t] result = [t.__class__.__name__] if hasattr(t, 'lineno') and hasattr(t, 'col_offset'): result.append((t.lineno, t.col_offset)) if t._fields is None: return tuple(result) for f in t._fields: result.append(to_tuple(getattr(t, f))) return tuple(result) # These tests are compiled through "exec" # There should be at least one test per statement exec_tests = [ # None "None", # Module docstring "'module docstring'", # FunctionDef "def f(): pass", # FunctionDef with docstring "def f(): 'function docstring'", # FunctionDef with arg "def f(a): pass", # FunctionDef with arg and default value "def f(a=0): pass", # FunctionDef with varargs "def f(*args): pass", # FunctionDef with kwargs "def f(**kwargs): pass", # FunctionDef with all kind of args and docstring "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'", # ClassDef "class C:pass", # ClassDef with docstring "class C: 'docstring for class C'", # ClassDef, new style class "class C(object): pass", # Return "def f():return 1", # Delete "del v", # Assign "v = 1", # AugAssign "v += 1", # For "for v in v:pass", # While "while v:pass", # If "if v:pass", # If-Elif "if a:\n pass\nelif b:\n pass", # If-Elif-Else "if a:\n pass\nelif b:\n pass\nelse:\n pass", # With "with x as y: pass", "with x as y, z as q: pass", # Raise "raise Exception('string')", # TryExcept "try:\n pass\nexcept Exception:\n pass", # TryFinally "try:\n pass\nfinally:\n pass", # Assert "assert v", # Import "import sys", # ImportFrom "from sys import v", # Global "global v", # Expr "1", # Pass, "pass", # Break "for v in v:break", # Continue "for v in v:continue", # for statements with naked tuples (see http://bugs.python.org/issue6704) "for a,b in c: pass", "[(a,b) for a,b in c]", "((a,b) for a,b in c)", "((a,b) for (a,b) in c)", # Multiline generator expression (test for .lineno & .col_offset) """( ( Aa , Bb ) for Aa , Bb in Cc )""", # dictcomp "{a : b for w in x for m in p if g}", # dictcomp with naked tuple "{a : b for v,w in x}", # setcomp "{r for l in x if g}", # setcomp with naked tuple "{r for l,m in x}", # AsyncFunctionDef "async def f():\n 'async function'\n await something()", # AsyncFor "async def f():\n async for e in i: 1\n else: 2", # AsyncWith "async def f():\n async with a as b: 1", # PEP 448: Additional Unpacking Generalizations "{**{1:2}, 2:3}", "{*{1, 2}, 3}", # Asynchronous comprehensions "async def f():\n [i async for b in c]", # Decorated FunctionDef "@deco1\n@deco2()\n@deco3(1)\ndef f(): pass", # Decorated AsyncFunctionDef "@deco1\n@deco2()\n@deco3(1)\nasync def f(): pass", # Decorated ClassDef "@deco1\n@deco2()\n@deco3(1)\nclass C: pass", # Decorator with generator argument "@deco(a for a in b)\ndef f(): pass", ] # These are compiled through "single" # because of overlap with "eval", it just tests what # can't be tested with "eval" single_tests = [ "1+2" ] # These are compiled through "eval" # It should test all expressions eval_tests = [ # None "None", # BoolOp "a and b", # BinOp "a + b", # UnaryOp "not v", # Lambda "lambda:None", # Dict "{ 1:2 }", # Empty dict "{}", # Set "{None,}", # Multiline dict (test for .lineno & .col_offset) """{ 1 : 2 }""", # ListComp "[a for b in c if d]", # GeneratorExp "(a for b in c if d)", # Yield - yield expressions can't work outside a function # # Compare "1 < 2 < 3", # Call "f(1,2,c=3,*d,**e)", # Num "10", # Str "'string'", # Attribute "a.b", # Subscript "a[b:c]", # Name "v", # List "[1,2,3]", # Empty list "[]", # Tuple "1,2,3", # Tuple "(1,2,3)", # Empty tuple "()", # Combination "a.b.c.d(a.b[1:2])", ] # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension # excepthandler, arguments, keywords, alias class AST_Tests(unittest.TestCase): def _assertTrueorder(self, ast_node, parent_pos): if not isinstance(ast_node, ast.AST) or ast_node._fields is None: return if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): node_pos = (ast_node.lineno, ast_node.col_offset) self.assertTrue(node_pos >= parent_pos) parent_pos = (ast_node.lineno, ast_node.col_offset) for name in ast_node._fields: value = getattr(ast_node, name) if isinstance(value, list): for child in value: self._assertTrueorder(child, parent_pos) elif value is not None: self._assertTrueorder(value, parent_pos) def test_AST_objects(self): x = ast.AST() self.assertEqual(x._fields, ()) x.foobar = 42 self.assertEqual(x.foobar, 42) self.assertEqual(x.__dict__["foobar"], 42) with self.assertRaises(AttributeError): x.vararg with self.assertRaises(TypeError): # "_ast.AST constructor takes 0 positional arguments" ast.AST(2) def test_AST_garbage_collection(self): class X: pass a = ast.AST() a.x = X() a.x.a = a ref = weakref.ref(a.x) del a support.gc_collect() self.assertIsNone(ref()) def test_snippets(self): for input, output, kind in ((exec_tests, exec_results, "exec"), (single_tests, single_results, "single"), (eval_tests, eval_results, "eval")): for i, o in zip(input, output): with self.subTest(action="parsing", input=i): ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) self.assertEqual(to_tuple(ast_tree), o) self._assertTrueorder(ast_tree, (0, 0)) with self.subTest(action="compiling", input=i, kind=kind): compile(ast_tree, "?", kind) def test_slice(self): slc = ast.parse("x[::]").body[0].value.slice self.assertIsNone(slc.upper) self.assertIsNone(slc.lower) self.assertIsNone(slc.step) def test_from_import(self): im = ast.parse("from . import y").body[0] self.assertIsNone(im.module) def test_non_interned_future_from_ast(self): mod = ast.parse("from __future__ import division") self.assertIsInstance(mod.body[0], ast.ImportFrom) mod.body[0].module = " __future__ ".strip() compile(mod, "<test>", "exec") def test_base_classes(self): self.assertTrue(issubclass(ast.For, ast.stmt)) self.assertTrue(issubclass(ast.Name, ast.expr)) self.assertTrue(issubclass(ast.stmt, ast.AST)) self.assertTrue(issubclass(ast.expr, ast.AST)) self.assertTrue(issubclass(ast.comprehension, ast.AST)) self.assertTrue(issubclass(ast.Gt, ast.AST)) def test_field_attr_existence(self): for name, item in ast.__dict__.items(): if isinstance(item, type) and name != 'AST' and name[0].isupper(): x = item() if isinstance(x, ast.AST): self.assertEqual(type(x._fields), tuple) def test_arguments(self): x = ast.arguments() self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs', 'kw_defaults', 'kwarg', 'defaults')) with self.assertRaises(AttributeError): x.vararg x = ast.arguments(*range(1, 7)) self.assertEqual(x.vararg, 2) def test_field_attr_writable(self): x = ast.Num() # We can assign to _fields x._fields = 666 self.assertEqual(x._fields, 666) def test_classattrs(self): x = ast.Num() self.assertEqual(x._fields, ('n',)) with self.assertRaises(AttributeError): x.n x = ast.Num(42) self.assertEqual(x.n, 42) with self.assertRaises(AttributeError): x.lineno with self.assertRaises(AttributeError): x.foobar x = ast.Num(lineno=2) self.assertEqual(x.lineno, 2) x = ast.Num(42, lineno=0) self.assertEqual(x.lineno, 0) self.assertEqual(x._fields, ('n',)) self.assertEqual(x.n, 42) self.assertRaises(TypeError, ast.Num, 1, 2) self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0) def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body) def test_nodeclasses(self): # Zero arguments constructor explicitly allowed x = ast.BinOp() self.assertEqual(x._fields, ('left', 'op', 'right')) # Random attribute allowed too x.foobarbaz = 5 self.assertEqual(x.foobarbaz, 5) n1 = ast.Num(1) n3 = ast.Num(3) addop = ast.Add() x = ast.BinOp(n1, addop, n3) self.assertEqual(x.left, n1) self.assertEqual(x.op, addop) self.assertEqual(x.right, n3) x = ast.BinOp(1, 2, 3) self.assertEqual(x.left, 1) self.assertEqual(x.op, 2) self.assertEqual(x.right, 3) x = ast.BinOp(1, 2, 3, lineno=0) self.assertEqual(x.left, 1) self.assertEqual(x.op, 2) self.assertEqual(x.right, 3) self.assertEqual(x.lineno, 0) # node raises exception when given too many arguments self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4) # node raises exception when given too many arguments self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0) # can set attributes through kwargs too x = ast.BinOp(left=1, op=2, right=3, lineno=0) self.assertEqual(x.left, 1) self.assertEqual(x.op, 2) self.assertEqual(x.right, 3) self.assertEqual(x.lineno, 0) # Random kwargs also allowed x = ast.BinOp(1, 2, 3, foobarbaz=42) self.assertEqual(x.foobarbaz, 42) def test_no_fields(self): # this used to fail because Sub._fields was None x = ast.Sub() self.assertEqual(x._fields, ()) def test_pickling(self): import pickle mods = [pickle] try: import cPickle mods.append(cPickle) except ImportError: pass protocols = [0, 1, 2] for mod in mods: for protocol in protocols: for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): ast2 = mod.loads(mod.dumps(ast, protocol)) self.assertEqual(to_tuple(ast2), to_tuple(ast)) def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", str(cm.exception)) def test_invalid_identitifer(self): m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))]) ast.fix_missing_locations(m) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("identifier must be of type str", str(cm.exception)) def test_empty_yield_from(self): # Issue 16546: yield from value is not optional. empty_yield_from = ast.parse("def f():\n yield from g()") empty_yield_from.body[0].body[0].value.value = None with self.assertRaises(ValueError) as cm: compile(empty_yield_from, "<test>", "exec") self.assertIn("field value is required", str(cm.exception)) @support.cpython_only def test_issue31592(self): # There shouldn't be an assertion failure in case of a bad # unicodedata.normalize(). import unicodedata def bad_normalize(*args): return None with support.swap_attr(unicodedata, 'normalize', bad_normalize): self.assertRaises(TypeError, ast.parse, '\u03D5') class ASTHelpers_Test(unittest.TestCase): def test_parse(self): a = ast.parse('foo(1 + 1)') b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST) self.assertEqual(ast.dump(a), ast.dump(b)) def test_parse_in_error(self): try: 1/0 except Exception: with self.assertRaises(SyntaxError) as e: ast.literal_eval(r"'\U'") self.assertIsNotNone(e.exception.__context__) def test_dump(self): node = ast.parse('spam(eggs, "and cheese")') self.assertEqual(ast.dump(node), "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), " "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], " "keywords=[]))])" ) self.assertEqual(ast.dump(node, annotate_fields=False), "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), " "Str('and cheese')], []))])" ) self.assertEqual(ast.dump(node, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), " "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), " "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, " "col_offset=11)], keywords=[], " "lineno=1, col_offset=0), lineno=1, col_offset=0)])" ) def test_dump_incomplete(self): node = ast.Raise(lineno=3, col_offset=4) self.assertEqual(ast.dump(node), "Raise()" ) self.assertEqual(ast.dump(node, include_attributes=True), "Raise(lineno=3, col_offset=4)" ) node = ast.Raise(exc=ast.Name(id='e', ctx=ast.Load()), lineno=3, col_offset=4) self.assertEqual(ast.dump(node), "Raise(exc=Name(id='e', ctx=Load()))" ) self.assertEqual(ast.dump(node, annotate_fields=False), "Raise(Name('e', Load()))" ) self.assertEqual(ast.dump(node, include_attributes=True), "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)" ) self.assertEqual(ast.dump(node, annotate_fields=False, include_attributes=True), "Raise(Name('e', Load()), lineno=3, col_offset=4)" ) node = ast.Raise(cause=ast.Name(id='e', ctx=ast.Load())) self.assertEqual(ast.dump(node), "Raise(cause=Name(id='e', ctx=Load()))" ) self.assertEqual(ast.dump(node, annotate_fields=False), "Raise(cause=Name('e', Load()))" ) def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Num(2), src.body.right) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' 'col_offset=0))' ) def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.assertEqual(ast.dump(src, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, " "col_offset=6)], keywords=[], " "lineno=1, col_offset=0), lineno=1, col_offset=0), " "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, " "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], " "keywords=[], lineno=1, " "col_offset=0), lineno=1, col_offset=0)])" ) def test_increment_lineno(self): src = ast.parse('1 + 1', mode='eval') self.assertEqual(ast.increment_lineno(src, n=3), src) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), ' 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, ' 'col_offset=0))' ) # issue10869: do not increment lineno of root twice src = ast.parse('1 + 1', mode='eval') self.assertEqual(ast.increment_lineno(src.body, n=3), src.body) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), ' 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, ' 'col_offset=0))' ) def test_iter_fields(self): node = ast.parse('foo()', mode='eval') d = dict(ast.iter_fields(node.body)) self.assertEqual(d.pop('func').id, 'foo') self.assertEqual(d, {'keywords': [], 'args': []}) def test_iter_child_nodes(self): node = ast.parse("spam(23, 42, eggs='leek')", mode='eval') self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4) iterator = ast.iter_child_nodes(node.body) self.assertEqual(next(iterator).id, 'spam') self.assertEqual(next(iterator).n, 23) self.assertEqual(next(iterator).n, 42) self.assertEqual(ast.dump(next(iterator)), "keyword(arg='eggs', value=Str(s='leek'))" ) def test_get_docstring(self): node = ast.parse('"""line one\n line two"""') self.assertEqual(ast.get_docstring(node), 'line one\nline two') node = ast.parse('class foo:\n """line one\n line two"""') self.assertEqual(ast.get_docstring(node.body[0]), 'line one\nline two') node = ast.parse('def foo():\n """line one\n line two"""') self.assertEqual(ast.get_docstring(node.body[0]), 'line one\nline two') node = ast.parse('async def foo():\n """spam\n ham"""') self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham') def test_get_docstring_none(self): self.assertIsNone(ast.get_docstring(ast.parse(''))) node = ast.parse('x = "not docstring"') self.assertIsNone(ast.get_docstring(node)) node = ast.parse('def foo():\n pass') self.assertIsNone(ast.get_docstring(node)) node = ast.parse('class foo:\n pass') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('class foo:\n x = "not docstring"') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('class foo:\n def bar(self): pass') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('def foo():\n pass') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('def foo():\n x = "not docstring"') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('async def foo():\n pass') self.assertIsNone(ast.get_docstring(node.body[0])) node = ast.parse('async def foo():\n x = "not docstring"') self.assertIsNone(ast.get_docstring(node.body[0])) def test_elif_stmt_start_position(self): node = ast.parse('if a:\n pass\nelif b:\n pass\n') elif_stmt = node.body[0].orelse[0] self.assertEqual(elif_stmt.lineno, 3) self.assertEqual(elif_stmt.col_offset, 0) def test_elif_stmt_start_position_with_else(self): node = ast.parse('if a:\n pass\nelif b:\n pass\nelse:\n pass\n') elif_stmt = node.body[0].orelse[0] self.assertEqual(elif_stmt.lineno, 3) self.assertEqual(elif_stmt.col_offset, 0) def test_literal_eval(self): self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3]) self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42}) self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None)) self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3}) self.assertEqual(ast.literal_eval('b"hi"'), b"hi") self.assertRaises(ValueError, ast.literal_eval, 'foo()') self.assertEqual(ast.literal_eval('6'), 6) self.assertEqual(ast.literal_eval('+6'), 6) self.assertEqual(ast.literal_eval('-6'), -6) self.assertEqual(ast.literal_eval('3.25'), 3.25) self.assertEqual(ast.literal_eval('+3.25'), 3.25) self.assertEqual(ast.literal_eval('-3.25'), -3.25) self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0') self.assertRaises(ValueError, ast.literal_eval, '++6') self.assertRaises(ValueError, ast.literal_eval, '+True') self.assertRaises(ValueError, ast.literal_eval, '2+3') def test_literal_eval_complex(self): # Issue #4907 self.assertEqual(ast.literal_eval('6j'), 6j) self.assertEqual(ast.literal_eval('-6j'), -6j) self.assertEqual(ast.literal_eval('6.75j'), 6.75j) self.assertEqual(ast.literal_eval('-6.75j'), -6.75j) self.assertEqual(ast.literal_eval('3+6j'), 3+6j) self.assertEqual(ast.literal_eval('-3+6j'), -3+6j) self.assertEqual(ast.literal_eval('3-6j'), 3-6j) self.assertEqual(ast.literal_eval('-3-6j'), -3-6j) self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j) self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j) self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j) self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j) self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j) self.assertRaises(ValueError, ast.literal_eval, '-6j+3') self.assertRaises(ValueError, ast.literal_eval, '-6j+3j') self.assertRaises(ValueError, ast.literal_eval, '3+-6j') self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)') self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)') def test_bad_integer(self): # issue13436: Bad error message with invalid numeric values body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=None, col_offset=None)] mod = ast.Module(body) with self.assertRaises(ValueError) as cm: compile(mod, 'test', 'exec') self.assertIn("invalid integer value: None", str(cm.exception)) def test_level_as_none(self): body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=0, col_offset=0)] mod = ast.Module(body) code = compile(mod, 'test', 'exec') ns = {} exec(code, ns) self.assertIn('sleep', ns) class ASTValidatorTests(unittest.TestCase): def mod(self, mod, msg=None, mode="exec", *, exc=ValueError): mod.lineno = mod.col_offset = 0 ast.fix_missing_locations(mod) with self.assertRaises(exc) as cm: compile(mod, "<test>", mode) if msg is not None: self.assertIn(msg, str(cm.exception)) def expr(self, node, msg=None, *, exc=ValueError): mod = ast.Module([ast.Expr(node)]) self.mod(mod, msg, exc=exc) def stmt(self, stmt, msg=None): mod = ast.Module([stmt]) self.mod(mod, msg) def test_module(self): m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))]) self.mod(m, "must have Load context", "single") m = ast.Expression(ast.Name("x", ast.Store())) self.mod(m, "must have Load context", "eval") def _check_arguments(self, fac, check): def arguments(args=None, vararg=None, kwonlyargs=None, kwarg=None, defaults=None, kw_defaults=None): if args is None: args = [] if kwonlyargs is None: kwonlyargs = [] if defaults is None: defaults = [] if kw_defaults is None: kw_defaults = [] args = ast.arguments(args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) return fac(args) args = [ast.arg("x", ast.Name("x", ast.Store()))] check(arguments(args=args), "must have Load context") check(arguments(kwonlyargs=args), "must have Load context") check(arguments(defaults=[ast.Num(3)]), "more positional defaults than args") check(arguments(kw_defaults=[ast.Num(4)]), "length of kwonlyargs is not the same as kw_defaults") args = [ast.arg("x", ast.Name("x", ast.Load()))] check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]), "must have Load context") args = [ast.arg("a", ast.Name("x", ast.Load())), ast.arg("b", ast.Name("y", ast.Load()))] check(arguments(kwonlyargs=args, kw_defaults=[None, ast.Name("x", ast.Store())]), "must have Load context") def test_funcdef(self): a = ast.arguments([], None, [], [], None, []) f = ast.FunctionDef("x", a, [], [], None) self.stmt(f, "empty body on FunctionDef") f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())], None) self.stmt(f, "must have Load context") f = ast.FunctionDef("x", a, [ast.Pass()], [], ast.Name("x", ast.Store())) self.stmt(f, "must have Load context") def fac(args): return ast.FunctionDef("x", args, [ast.Pass()], [], None) self._check_arguments(fac, self.stmt) def test_classdef(self): def cls(bases=None, keywords=None, body=None, decorator_list=None): if bases is None: bases = [] if keywords is None: keywords = [] if body is None: body = [ast.Pass()] if decorator_list is None: decorator_list = [] return ast.ClassDef("myclass", bases, keywords, body, decorator_list) self.stmt(cls(bases=[ast.Name("x", ast.Store())]), "must have Load context") self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]), "must have Load context") self.stmt(cls(body=[]), "empty body on ClassDef") self.stmt(cls(body=[None]), "None disallowed") self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]), "must have Load context") def test_delete(self): self.stmt(ast.Delete([]), "empty targets on Delete") self.stmt(ast.Delete([None]), "None disallowed") self.stmt(ast.Delete([ast.Name("x", ast.Load())]), "must have Del context") def test_assign(self): self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign") self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed") self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)), "must have Store context") self.stmt(ast.Assign([ast.Name("x", ast.Store())], ast.Name("y", ast.Store())), "must have Load context") def test_augassign(self): aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(), ast.Name("y", ast.Load())) self.stmt(aug, "must have Store context") aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(), ast.Name("y", ast.Store())) self.stmt(aug, "must have Load context") def test_for(self): x = ast.Name("x", ast.Store()) y = ast.Name("y", ast.Load()) p = ast.Pass() self.stmt(ast.For(x, y, [], []), "empty body on For") self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []), "must have Store context") self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []), "must have Load context") e = ast.Expr(ast.Name("x", ast.Store())) self.stmt(ast.For(x, y, [e], []), "must have Load context") self.stmt(ast.For(x, y, [p], [e]), "must have Load context") def test_while(self): self.stmt(ast.While(ast.Num(3), [], []), "empty body on While") self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []), "must have Load context") self.stmt(ast.While(ast.Num(3), [ast.Pass()], [ast.Expr(ast.Name("x", ast.Store()))]), "must have Load context") def test_if(self): self.stmt(ast.If(ast.Num(3), [], []), "empty body on If") i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], []) self.stmt(i, "must have Load context") i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], []) self.stmt(i, "must have Load context") i = ast.If(ast.Num(3), [ast.Pass()], [ast.Expr(ast.Name("x", ast.Store()))]) self.stmt(i, "must have Load context") def test_with(self): p = ast.Pass() self.stmt(ast.With([], [p]), "empty items on With") i = ast.withitem(ast.Num(3), None) self.stmt(ast.With([i], []), "empty body on With") i = ast.withitem(ast.Name("x", ast.Store()), None) self.stmt(ast.With([i], [p]), "must have Load context") i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load())) self.stmt(ast.With([i], [p]), "must have Store context") def test_raise(self): r = ast.Raise(None, ast.Num(3)) self.stmt(r, "Raise with cause but no exception") r = ast.Raise(ast.Name("x", ast.Store()), None) self.stmt(r, "must have Load context") r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store())) self.stmt(r, "must have Load context") def test_try(self): p = ast.Pass() t = ast.Try([], [], [], [p]) self.stmt(t, "empty body on Try") t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p]) self.stmt(t, "must have Load context") t = ast.Try([p], [], [], []) self.stmt(t, "Try has neither except handlers nor finalbody") t = ast.Try([p], [], [p], [p]) self.stmt(t, "Try has orelse but no except handlers") t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], []) self.stmt(t, "empty body on ExceptHandler") e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])] self.stmt(ast.Try([p], e, [], []), "must have Load context") e = [ast.ExceptHandler(None, "x", [p])] t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p]) self.stmt(t, "must have Load context") t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))]) self.stmt(t, "must have Load context") def test_assert(self): self.stmt(ast.Assert(ast.Name("x", ast.Store()), None), "must have Load context") assrt = ast.Assert(ast.Name("x", ast.Load()), ast.Name("y", ast.Store())) self.stmt(assrt, "must have Load context") def test_import(self): self.stmt(ast.Import([]), "empty names on Import") def test_importfrom(self): imp = ast.ImportFrom(None, [ast.alias("x", None)], -42) self.stmt(imp, "Negative ImportFrom level") self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom") def test_global(self): self.stmt(ast.Global([]), "empty names on Global") def test_nonlocal(self): self.stmt(ast.Nonlocal([]), "empty names on Nonlocal") def test_expr(self): e = ast.Expr(ast.Name("x", ast.Store())) self.stmt(e, "must have Load context") def test_boolop(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_py_compile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_py_compile.py
import functools import importlib.util import os import py_compile import shutil import stat import sys import tempfile import unittest from test import support def without_source_date_epoch(fxn): """Runs function with SOURCE_DATE_EPOCH unset.""" @functools.wraps(fxn) def wrapper(*args, **kwargs): with support.EnvironmentVarGuard() as env: env.unset('SOURCE_DATE_EPOCH') return fxn(*args, **kwargs) return wrapper def with_source_date_epoch(fxn): """Runs function with SOURCE_DATE_EPOCH set.""" @functools.wraps(fxn) def wrapper(*args, **kwargs): with support.EnvironmentVarGuard() as env: env['SOURCE_DATE_EPOCH'] = '123456789' return fxn(*args, **kwargs) return wrapper # Run tests with SOURCE_DATE_EPOCH set or unset explicitly. class SourceDateEpochTestMeta(type(unittest.TestCase)): def __new__(mcls, name, bases, dct, *, source_date_epoch): cls = super().__new__(mcls, name, bases, dct) for attr in dir(cls): if attr.startswith('test_'): meth = getattr(cls, attr) if source_date_epoch: wrapper = with_source_date_epoch(meth) else: wrapper = without_source_date_epoch(meth) setattr(cls, attr, wrapper) return cls class PyCompileTestsBase: def setUp(self): self.directory = tempfile.mkdtemp(dir=os.getcwd()) self.source_path = os.path.join(self.directory, '_test.py') self.pyc_path = self.source_path + 'c' self.cache_path = importlib.util.cache_from_source(self.source_path) self.cwd_drive = os.path.splitdrive(os.getcwd())[0] # In these tests we compute relative paths. When using Windows, the # current working directory path and the 'self.source_path' might be # on different drives. Therefore we need to switch to the drive where # the temporary source file lives. drive = os.path.splitdrive(self.source_path)[0] if drive: os.chdir(drive) with open(self.source_path, 'w') as file: file.write('x = 123\n') def tearDown(self): shutil.rmtree(self.directory) if self.cwd_drive: os.chdir(self.cwd_drive) def test_absolute_path(self): py_compile.compile(self.source_path, self.pyc_path) self.assertTrue(os.path.exists(self.pyc_path)) self.assertFalse(os.path.exists(self.cache_path)) def test_do_not_overwrite_symlinks(self): # In the face of a cfile argument being a symlink, bail out. # Issue #17222 try: os.symlink(self.pyc_path + '.actual', self.pyc_path) except (NotImplementedError, OSError): self.skipTest('need to be able to create a symlink for a file') else: assert os.path.islink(self.pyc_path) with self.assertRaises(FileExistsError): py_compile.compile(self.source_path, self.pyc_path) @unittest.skipIf(not os.path.exists(os.devnull) or os.path.isfile(os.devnull), 'requires os.devnull and for it to be a non-regular file') def test_do_not_overwrite_nonregular_files(self): # In the face of a cfile argument being a non-regular file, bail out. # Issue #17222 with self.assertRaises(FileExistsError): py_compile.compile(self.source_path, os.devnull) def test_cache_path(self): py_compile.compile(self.source_path) self.assertTrue(os.path.exists(self.cache_path)) def test_cwd(self): with support.change_cwd(self.directory): py_compile.compile(os.path.basename(self.source_path), os.path.basename(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path)) self.assertFalse(os.path.exists(self.cache_path)) def test_relative_path(self): py_compile.compile(os.path.relpath(self.source_path), os.path.relpath(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path)) self.assertFalse(os.path.exists(self.cache_path)) @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, 'non-root user required') @unittest.skipIf(os.name == 'nt', 'cannot control directory permissions on Windows') def test_exceptions_propagate(self): # Make sure that exceptions raised thanks to issues with writing # bytecode. # http://bugs.python.org/issue17244 mode = os.stat(self.directory) os.chmod(self.directory, stat.S_IREAD) try: with self.assertRaises(IOError): py_compile.compile(self.source_path, self.pyc_path) finally: os.chmod(self.directory, mode.st_mode) def test_bad_coding(self): bad_coding = os.path.join(os.path.dirname(__file__), 'bad_coding2.py') with support.captured_stderr(): self.assertIsNone(py_compile.compile(bad_coding, doraise=False)) self.assertFalse(os.path.exists( importlib.util.cache_from_source(bad_coding))) def test_source_date_epoch(self): py_compile.compile(self.source_path, self.pyc_path) self.assertTrue(os.path.exists(self.pyc_path)) self.assertFalse(os.path.exists(self.cache_path)) with open(self.pyc_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) if os.environ.get('SOURCE_DATE_EPOCH'): expected_flags = 0b11 else: expected_flags = 0b00 self.assertEqual(flags, expected_flags) @unittest.skipIf(sys.flags.optimize > 0, 'test does not work with -O') def test_double_dot_no_clobber(self): # http://bugs.python.org/issue22966 # py_compile foo.bar.py -> __pycache__/foo.cpython-34.pyc weird_path = os.path.join(self.directory, 'foo.bar.py') cache_path = importlib.util.cache_from_source(weird_path) pyc_path = weird_path + 'c' head, tail = os.path.split(cache_path) penultimate_tail = os.path.basename(head) self.assertEqual( os.path.join(penultimate_tail, tail), os.path.join( '__pycache__', 'foo.bar.{}.pyc'.format(sys.implementation.cache_tag))) with open(weird_path, 'w') as file: file.write('x = 123\n') py_compile.compile(weird_path) self.assertTrue(os.path.exists(cache_path)) self.assertFalse(os.path.exists(pyc_path)) def test_optimization_path(self): # Specifying optimized bytecode should lead to a path reflecting that. self.assertIn('opt-2', py_compile.compile(self.source_path, optimize=2)) def test_invalidation_mode(self): py_compile.compile( self.source_path, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH, ) with open(self.cache_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) self.assertEqual(flags, 0b11) py_compile.compile( self.source_path, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH, ) with open(self.cache_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) self.assertEqual(flags, 0b1) class PyCompileTestsWithSourceEpoch(PyCompileTestsBase, unittest.TestCase, metaclass=SourceDateEpochTestMeta, source_date_epoch=True): pass class PyCompileTestsWithoutSourceEpoch(PyCompileTestsBase, 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_ioctl.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ioctl.py
import array import unittest from test.support import import_module, get_attribute import os, struct fcntl = import_module('fcntl') termios = import_module('termios') get_attribute(termios, 'TIOCGPGRP') #Can't run tests without this feature try: tty = open("/dev/tty", "rb") except OSError: raise unittest.SkipTest("Unable to open /dev/tty") else: # Skip if another process is in foreground r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") tty.close() rpgrp = struct.unpack("i", r)[0] if rpgrp not in (os.getpgrp(), os.getsid(0)): raise unittest.SkipTest("Neither the process group nor the session " "are attached to /dev/tty") del tty, r, rpgrp try: import pty except ImportError: pty = None class IoctlTests(unittest.TestCase): def test_ioctl(self): # If this process has been put into the background, TIOCGPGRP returns # the session ID instead of the process group id. ids = (os.getpgrp(), os.getsid(0)) with open("/dev/tty", "rb") as tty: r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") rpgrp = struct.unpack("i", r)[0] self.assertIn(rpgrp, ids) def _check_ioctl_mutate_len(self, nbytes=None): buf = array.array('i') intsize = buf.itemsize ids = (os.getpgrp(), os.getsid(0)) # A fill value unlikely to be in `ids` fill = -12345 if nbytes is not None: # Extend the buffer so that it is exactly `nbytes` bytes long buf.extend([fill] * (nbytes // intsize)) self.assertEqual(len(buf) * intsize, nbytes) # sanity check else: buf.append(fill) with open("/dev/tty", "rb") as tty: r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) rpgrp = buf[0] self.assertEqual(r, 0) self.assertIn(rpgrp, ids) def test_ioctl_mutate(self): self._check_ioctl_mutate_len() def test_ioctl_mutate_1024(self): # Issue #9758: a mutable buffer of exactly 1024 bytes wouldn't be # copied back after the system call. self._check_ioctl_mutate_len(1024) def test_ioctl_mutate_2048(self): # Test with a larger buffer, just for the record. self._check_ioctl_mutate_len(2048) def test_ioctl_signed_unsigned_code_param(self): if not pty: raise unittest.SkipTest('pty module required') mfd, sfd = pty.openpty() try: if termios.TIOCSWINSZ < 0: set_winsz_opcode_maybe_neg = termios.TIOCSWINSZ set_winsz_opcode_pos = termios.TIOCSWINSZ & 0xffffffff else: set_winsz_opcode_pos = termios.TIOCSWINSZ set_winsz_opcode_maybe_neg, = struct.unpack("i", struct.pack("I", termios.TIOCSWINSZ)) our_winsz = struct.pack("HHHH",80,25,0,0) # test both with a positive and potentially negative ioctl code new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_pos, our_winsz) new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, our_winsz) finally: os.close(mfd) os.close(sfd) 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_functions.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_unicode_file_functions.py
# Test the Unicode versions of normal file functions # open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir import os import sys import unittest import warnings from unicodedata import normalize from test import support filenames = [ '1_abc', '2_ascii', '3_Gr\xfc\xdf-Gott', '4_\u0393\u03b5\u03b9\u03ac-\u03c3\u03b1\u03c2', '5_\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435', '6_\u306b\u307d\u3093', '7_\u05d4\u05e9\u05e7\u05e6\u05e5\u05e1', '8_\u66e8\u66e9\u66eb', '9_\u66e8\u05e9\u3093\u0434\u0393\xdf', # Specific code points: fn, NFC(fn) and NFKC(fn) all different '10_\u1fee\u1ffd', ] # Mac OS X decomposes Unicode names, using Normal Form D. # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html # "However, most volume formats do not follow the exact specification for # these normal forms. For example, HFS Plus uses a variant of Normal Form D # in which U+2000 through U+2FFF, U+F900 through U+FAFF, and U+2F800 through # U+2FAFF are not decomposed." if sys.platform != 'darwin': filenames.extend([ # Specific code points: NFC(fn), NFD(fn), NFKC(fn) and NFKD(fn) all different '11_\u0385\u03d3\u03d4', '12_\u00a8\u0301\u03d2\u0301\u03d2\u0308', # == NFD('\u0385\u03d3\u03d4') '13_\u0020\u0308\u0301\u038e\u03ab', # == NFKC('\u0385\u03d3\u03d4') '14_\u1e9b\u1fc1\u1fcd\u1fce\u1fcf\u1fdd\u1fde\u1fdf\u1fed', # Specific code points: fn, NFC(fn) and NFKC(fn) all different '15_\u1fee\u1ffd\ufad1', '16_\u2000\u2000\u2000A', '17_\u2001\u2001\u2001A', '18_\u2003\u2003\u2003A', # == NFC('\u2001\u2001\u2001A') '19_\u0020\u0020\u0020A', # '\u0020' == ' ' == NFKC('\u2000') == # NFKC('\u2001') == NFKC('\u2003') ]) # Is it Unicode-friendly? if not os.path.supports_unicode_filenames: fsencoding = sys.getfilesystemencoding() try: for name in filenames: name.encode(fsencoding) except UnicodeEncodeError: raise unittest.SkipTest("only NT+ and systems with " "Unicode-friendly filesystem encoding") class UnicodeFileTests(unittest.TestCase): files = set(filenames) normal_form = None def setUp(self): try: os.mkdir(support.TESTFN) except FileExistsError: pass self.addCleanup(support.rmtree, support.TESTFN) files = set() for name in self.files: name = os.path.join(support.TESTFN, self.norm(name)) with open(name, 'wb') as f: f.write((name+'\n').encode("utf-8")) os.stat(name) files.add(name) self.files = files def norm(self, s): if self.normal_form: return normalize(self.normal_form, s) return s def _apply_failure(self, fn, filename, expected_exception=FileNotFoundError, check_filename=True): with self.assertRaises(expected_exception) as c: fn(filename) exc_filename = c.exception.filename if check_filename: self.assertEqual(exc_filename, filename, "Function '%s(%a) failed " "with bad filename in the exception: %a" % (fn.__name__, filename, exc_filename)) def test_failures(self): # Pass non-existing Unicode filenames all over the place. for name in self.files: name = "not_" + name self._apply_failure(open, name) self._apply_failure(os.stat, name) self._apply_failure(os.chdir, name) self._apply_failure(os.rmdir, name) self._apply_failure(os.remove, name) self._apply_failure(os.listdir, name) if sys.platform == 'win32': # Windows is lunatic. Issue #13366. _listdir_failure = NotADirectoryError, FileNotFoundError else: _listdir_failure = NotADirectoryError def test_open(self): for name in self.files: f = open(name, 'wb') f.write((name+'\n').encode("utf-8")) f.close() os.stat(name) self._apply_failure(os.listdir, name, self._listdir_failure) # Skip the test on darwin, because darwin does normalize the filename to # NFD (a variant of Unicode NFD form). Normalize the filename to NFC, NFKC, # NFKD in Python is useless, because darwin will normalize it later and so # open(), os.stat(), etc. don't raise any exception. @unittest.skipIf(sys.platform == 'darwin', 'irrelevant test on Mac OS X') def test_normalize(self): files = set(self.files) others = set() for nf in set(['NFC', 'NFD', 'NFKC', 'NFKD']): others |= set(normalize(nf, file) for file in files) others -= files for name in others: self._apply_failure(open, name) self._apply_failure(os.stat, name) self._apply_failure(os.chdir, name) self._apply_failure(os.rmdir, name) self._apply_failure(os.remove, name) self._apply_failure(os.listdir, name) # Skip the test on darwin, because darwin uses a normalization different # than Python NFD normalization: filenames are different even if we use # Python NFD normalization. @unittest.skipIf(sys.platform == 'darwin', 'irrelevant test on Mac OS X') def test_listdir(self): sf0 = set(self.files) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) f1 = os.listdir(support.TESTFN.encode(sys.getfilesystemencoding())) f2 = os.listdir(support.TESTFN) sf2 = set(os.path.join(support.TESTFN, f) for f in f2) self.assertEqual(sf0, sf2, "%a != %a" % (sf0, sf2)) self.assertEqual(len(f1), len(f2)) def test_rename(self): for name in self.files: os.rename(name, "tmp") os.rename("tmp", name) def test_directory(self): dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb') filename = '\xdf-\u66e8\u66e9\u66eb' with support.temp_cwd(dirname): with open(filename, 'wb') as f: f.write((filename + '\n').encode("utf-8")) os.access(filename,os.R_OK) os.remove(filename) class UnicodeNFCFileTests(UnicodeFileTests): normal_form = 'NFC' class UnicodeNFDFileTests(UnicodeFileTests): normal_form = 'NFD' class UnicodeNFKCFileTests(UnicodeFileTests): normal_form = 'NFKC' class UnicodeNFKDFileTests(UnicodeFileTests): normal_form = 'NFKD' def test_main(): support.run_unittest( UnicodeFileTests, UnicodeNFCFileTests, UnicodeNFDFileTests, UnicodeNFKCFileTests, UnicodeNFKDFileTests, ) 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_abstract_numbers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_abstract_numbers.py
"""Unit tests for numbers.py.""" import math import operator import unittest from numbers import Complex, Real, Rational, Integral class TestNumbers(unittest.TestCase): def test_int(self): self.assertTrue(issubclass(int, Integral)) self.assertTrue(issubclass(int, Complex)) self.assertEqual(7, int(7).real) self.assertEqual(0, int(7).imag) self.assertEqual(7, int(7).conjugate()) self.assertEqual(-7, int(-7).conjugate()) self.assertEqual(7, int(7).numerator) self.assertEqual(1, int(7).denominator) def test_float(self): self.assertFalse(issubclass(float, Rational)) self.assertTrue(issubclass(float, Real)) self.assertEqual(7.3, float(7.3).real) self.assertEqual(0, float(7.3).imag) self.assertEqual(7.3, float(7.3).conjugate()) self.assertEqual(-7.3, float(-7.3).conjugate()) def test_complex(self): self.assertFalse(issubclass(complex, Real)) self.assertTrue(issubclass(complex, Complex)) c1, c2 = complex(3, 2), complex(4,1) # XXX: This is not ideal, but see the comment in math_trunc(). self.assertRaises(TypeError, math.trunc, c1) self.assertRaises(TypeError, operator.mod, c1, c2) self.assertRaises(TypeError, divmod, c1, c2) self.assertRaises(TypeError, operator.floordiv, c1, c2) self.assertRaises(TypeError, float, c1) self.assertRaises(TypeError, int, c1) 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_clinic.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
# Argument Clinic # Copyright 2012-2013 by Larry Hastings. # Licensed to the PSF under a contributor agreement. from test import support from unittest import TestCase import collections import inspect import os.path import sys import unittest clinic_path = os.path.join(os.path.dirname(__file__), '..', '..', 'Tools', 'clinic') clinic_path = os.path.normpath(clinic_path) if not os.path.exists(clinic_path): raise unittest.SkipTest(f'{clinic_path!r} path does not exist') sys.path.append(clinic_path) try: import clinic from clinic import DSLParser finally: del sys.path[-1] class FakeConverter: def __init__(self, name, args): self.name = name self.args = args class FakeConverterFactory: def __init__(self, name): self.name = name def __call__(self, name, default, **kwargs): return FakeConverter(self.name, kwargs) class FakeConvertersDict: def __init__(self): self.used_converters = {} def get(self, name, default): return self.used_converters.setdefault(name, FakeConverterFactory(name)) c = clinic.Clinic(language='C', filename = "file") class FakeClinic: def __init__(self): self.converters = FakeConvertersDict() self.legacy_converters = FakeConvertersDict() self.language = clinic.CLanguage(None) self.filename = None self.destination_buffers = {} self.block_parser = clinic.BlockParser('', self.language) self.modules = collections.OrderedDict() self.classes = collections.OrderedDict() clinic.clinic = self self.name = "FakeClinic" self.line_prefix = self.line_suffix = '' self.destinations = {} self.add_destination("block", "buffer") self.add_destination("file", "buffer") self.add_destination("suppress", "suppress") d = self.destinations.get self.field_destinations = collections.OrderedDict(( ('docstring_prototype', d('suppress')), ('docstring_definition', d('block')), ('methoddef_define', d('block')), ('impl_prototype', d('block')), ('parser_prototype', d('suppress')), ('parser_definition', d('block')), ('impl_definition', d('block')), )) def get_destination(self, name): d = self.destinations.get(name) if not d: sys.exit("Destination does not exist: " + repr(name)) return d def add_destination(self, name, type, *args): if name in self.destinations: sys.exit("Destination already exists: " + repr(name)) self.destinations[name] = clinic.Destination(name, type, self, *args) def is_directive(self, name): return name == "module" def directive(self, name, args): self.called_directives[name] = args _module_and_class = clinic.Clinic._module_and_class class ClinicWholeFileTest(TestCase): def test_eol(self): # regression test: # clinic's block parser didn't recognize # the "end line" for the block if it # didn't end in "\n" (as in, the last) # byte of the file was '/'. # so it would spit out an end line for you. # and since you really already had one, # the last line of the block got corrupted. c = clinic.Clinic(clinic.CLanguage(None), filename="file") raw = "/*[clinic]\nfoo\n[clinic]*/" cooked = c.parse(raw).splitlines() end_line = cooked[2].rstrip() # this test is redundant, it's just here explicitly to catch # the regression test so we don't forget what it looked like self.assertNotEqual(end_line, "[clinic]*/[clinic]*/") self.assertEqual(end_line, "[clinic]*/") class ClinicGroupPermuterTest(TestCase): def _test(self, l, m, r, output): computed = clinic.permute_optional_groups(l, m, r) self.assertEqual(output, computed) def test_range(self): self._test([['start']], ['stop'], [['step']], ( ('stop',), ('start', 'stop',), ('start', 'stop', 'step',), )) def test_add_window(self): self._test([['x', 'y']], ['ch'], [['attr']], ( ('ch',), ('ch', 'attr'), ('x', 'y', 'ch',), ('x', 'y', 'ch', 'attr'), )) def test_ludicrous(self): self._test([['a1', 'a2', 'a3'], ['b1', 'b2']], ['c1'], [['d1', 'd2'], ['e1', 'e2', 'e3']], ( ('c1',), ('b1', 'b2', 'c1'), ('b1', 'b2', 'c1', 'd1', 'd2'), ('a1', 'a2', 'a3', 'b1', 'b2', 'c1'), ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2'), ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2', 'e1', 'e2', 'e3'), )) def test_right_only(self): self._test([], [], [['a'],['b'],['c']], ( (), ('a',), ('a', 'b'), ('a', 'b', 'c') )) def test_have_left_options_but_required_is_empty(self): def fn(): clinic.permute_optional_groups(['a'], [], []) self.assertRaises(AssertionError, fn) class ClinicLinearFormatTest(TestCase): def _test(self, input, output, **kwargs): computed = clinic.linear_format(input, **kwargs) self.assertEqual(output, computed) def test_empty_strings(self): self._test('', '') def test_solo_newline(self): self._test('\n', '\n') def test_no_substitution(self): self._test(""" abc """, """ abc """) def test_empty_substitution(self): self._test(""" abc {name} def """, """ abc def """, name='') def test_single_line_substitution(self): self._test(""" abc {name} def """, """ abc GARGLE def """, name='GARGLE') def test_multiline_substitution(self): self._test(""" abc {name} def """, """ abc bingle bungle def """, name='bingle\nbungle\n') class InertParser: def __init__(self, clinic): pass def parse(self, block): pass class CopyParser: def __init__(self, clinic): pass def parse(self, block): block.output = block.input class ClinicBlockParserTest(TestCase): def _test(self, input, output): language = clinic.CLanguage(None) blocks = list(clinic.BlockParser(input, language)) writer = clinic.BlockPrinter(language) for block in blocks: writer.print_block(block) output = writer.f.getvalue() assert output == input, "output != input!\n\noutput " + repr(output) + "\n\n input " + repr(input) def round_trip(self, input): return self._test(input, input) def test_round_trip_1(self): self.round_trip(""" verbatim text here lah dee dah """) def test_round_trip_2(self): self.round_trip(""" verbatim text here lah dee dah /*[inert] abc [inert]*/ def /*[inert checksum: 7b18d017f89f61cf17d47f92749ea6930a3f1deb]*/ xyz """) def _test_clinic(self, input, output): language = clinic.CLanguage(None) c = clinic.Clinic(language, filename="file") c.parsers['inert'] = InertParser(c) c.parsers['copy'] = CopyParser(c) computed = c.parse(input) self.assertEqual(output, computed) def test_clinic_1(self): self._test_clinic(""" verbatim text here lah dee dah /*[copy input] def [copy start generated code]*/ abc /*[copy end generated code: output=03cfd743661f0797 input=7b18d017f89f61cf]*/ xyz """, """ verbatim text here lah dee dah /*[copy input] def [copy start generated code]*/ def /*[copy end generated code: output=7b18d017f89f61cf input=7b18d017f89f61cf]*/ xyz """) class ClinicParserTest(TestCase): def test_trivial(self): parser = DSLParser(FakeClinic()) block = clinic.Block("module os\nos.access") parser.parse(block) module, function = block.signatures self.assertEqual("access", function.name) self.assertEqual("os", module.name) def test_ignore_line(self): block = self.parse("#\nmodule os\nos.access") module, function = block.signatures self.assertEqual("access", function.name) self.assertEqual("os", module.name) def test_param(self): function = self.parse_function("module os\nos.access\n path: int") self.assertEqual("access", function.name) self.assertEqual(2, len(function.parameters)) p = function.parameters['path'] self.assertEqual('path', p.name) self.assertIsInstance(p.converter, clinic.int_converter) def test_param_default(self): function = self.parse_function("module os\nos.access\n follow_symlinks: bool = True") p = function.parameters['follow_symlinks'] self.assertEqual(True, p.default) def test_param_with_continuations(self): function = self.parse_function("module os\nos.access\n follow_symlinks: \\\n bool \\\n =\\\n True") p = function.parameters['follow_symlinks'] self.assertEqual(True, p.default) def test_param_default_expression(self): function = self.parse_function("module os\nos.access\n follow_symlinks: int(c_default='MAXSIZE') = sys.maxsize") p = function.parameters['follow_symlinks'] self.assertEqual(sys.maxsize, p.default) self.assertEqual("MAXSIZE", p.converter.c_default) s = self.parse_function_should_fail("module os\nos.access\n follow_symlinks: int = sys.maxsize") self.assertEqual(s, "Error on line 0:\nWhen you specify a named constant ('sys.maxsize') as your default value,\nyou MUST specify a valid c_default.\n") def test_param_no_docstring(self): function = self.parse_function(""" module os os.access follow_symlinks: bool = True something_else: str = ''""") p = function.parameters['follow_symlinks'] self.assertEqual(3, len(function.parameters)) self.assertIsInstance(function.parameters['something_else'].converter, clinic.str_converter) def test_param_default_parameters_out_of_order(self): s = self.parse_function_should_fail(""" module os os.access follow_symlinks: bool = True something_else: str""") self.assertEqual(s, """Error on line 0: Can't have a parameter without a default ('something_else') after a parameter with a default! """) def disabled_test_converter_arguments(self): function = self.parse_function("module os\nos.access\n path: path_t(allow_fd=1)") p = function.parameters['path'] self.assertEqual(1, p.converter.args['allow_fd']) def test_function_docstring(self): function = self.parse_function(""" module os os.stat as os_stat_fn path: str Path to be examined Perform a stat system call on the given path.""") self.assertEqual(""" stat($module, /, path) -- Perform a stat system call on the given path. path Path to be examined """.strip(), function.docstring) def test_explicit_parameters_in_docstring(self): function = self.parse_function(""" module foo foo.bar x: int Documentation for x. y: int This is the documentation for foo. Okay, we're done here. """) self.assertEqual(""" bar($module, /, x, y) -- This is the documentation for foo. x Documentation for x. Okay, we're done here. """.strip(), function.docstring) def test_parser_regression_special_character_in_parameter_column_of_docstring_first_line(self): function = self.parse_function(""" module os os.stat path: str This/used to break Clinic! """) self.assertEqual("stat($module, /, path)\n--\n\nThis/used to break Clinic!", function.docstring) def test_c_name(self): function = self.parse_function("module os\nos.stat as os_stat_fn") self.assertEqual("os_stat_fn", function.c_basename) def test_return_converter(self): function = self.parse_function("module os\nos.stat -> int") self.assertIsInstance(function.return_converter, clinic.int_return_converter) def test_star(self): function = self.parse_function("module os\nos.access\n *\n follow_symlinks: bool = True") p = function.parameters['follow_symlinks'] self.assertEqual(inspect.Parameter.KEYWORD_ONLY, p.kind) self.assertEqual(0, p.group) def test_group(self): function = self.parse_function("module window\nwindow.border\n [\n ls : int\n ]\n /\n") p = function.parameters['ls'] self.assertEqual(1, p.group) def test_left_group(self): function = self.parse_function(""" module curses curses.addch [ y: int Y-coordinate. x: int X-coordinate. ] ch: char Character to add. [ attr: long Attributes for the character. ] / """) for name, group in ( ('y', -1), ('x', -1), ('ch', 0), ('attr', 1), ): p = function.parameters[name] self.assertEqual(p.group, group) self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) self.assertEqual(function.docstring.strip(), """ addch([y, x,] ch, [attr]) y Y-coordinate. x X-coordinate. ch Character to add. attr Attributes for the character. """.strip()) def test_nested_groups(self): function = self.parse_function(""" module curses curses.imaginary [ [ y1: int Y-coordinate. y2: int Y-coordinate. ] x1: int X-coordinate. x2: int X-coordinate. ] ch: char Character to add. [ attr1: long Attributes for the character. attr2: long Attributes for the character. attr3: long Attributes for the character. [ attr4: long Attributes for the character. attr5: long Attributes for the character. attr6: long Attributes for the character. ] ] / """) for name, group in ( ('y1', -2), ('y2', -2), ('x1', -1), ('x2', -1), ('ch', 0), ('attr1', 1), ('attr2', 1), ('attr3', 1), ('attr4', 2), ('attr5', 2), ('attr6', 2), ): p = function.parameters[name] self.assertEqual(p.group, group) self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) self.assertEqual(function.docstring.strip(), """ imaginary([[y1, y2,] x1, x2,] ch, [attr1, attr2, attr3, [attr4, attr5, attr6]]) y1 Y-coordinate. y2 Y-coordinate. x1 X-coordinate. x2 X-coordinate. ch Character to add. attr1 Attributes for the character. attr2 Attributes for the character. attr3 Attributes for the character. attr4 Attributes for the character. attr5 Attributes for the character. attr6 Attributes for the character. """.strip()) def parse_function_should_fail(self, s): with support.captured_stdout() as stdout: with self.assertRaises(SystemExit): self.parse_function(s) return stdout.getvalue() def test_disallowed_grouping__two_top_groups_on_left(self): s = self.parse_function_should_fail(""" module foo foo.two_top_groups_on_left [ group1 : int ] [ group2 : int ] param: int """) self.assertEqual(s, ('Error on line 0:\n' 'Function two_top_groups_on_left has an unsupported group configuration. (Unexpected state 2.b)\n')) def test_disallowed_grouping__two_top_groups_on_right(self): self.parse_function_should_fail(""" module foo foo.two_top_groups_on_right param: int [ group1 : int ] [ group2 : int ] """) def test_disallowed_grouping__parameter_after_group_on_right(self): self.parse_function_should_fail(""" module foo foo.parameter_after_group_on_right param: int [ [ group1 : int ] group2 : int ] """) def test_disallowed_grouping__group_after_parameter_on_left(self): self.parse_function_should_fail(""" module foo foo.group_after_parameter_on_left [ group2 : int [ group1 : int ] ] param: int """) def test_disallowed_grouping__empty_group_on_left(self): self.parse_function_should_fail(""" module foo foo.empty_group [ [ ] group2 : int ] param: int """) def test_disallowed_grouping__empty_group_on_right(self): self.parse_function_should_fail(""" module foo foo.empty_group param: int [ [ ] group2 : int ] """) def test_no_parameters(self): function = self.parse_function(""" module foo foo.bar Docstring """) self.assertEqual("bar($module, /)\n--\n\nDocstring", function.docstring) self.assertEqual(1, len(function.parameters)) # self! def test_init_with_no_parameters(self): function = self.parse_function(""" module foo class foo.Bar "unused" "notneeded" foo.Bar.__init__ Docstring """, signatures_in_block=3, function_index=2) # self is not in the signature self.assertEqual("Bar()\n--\n\nDocstring", function.docstring) # but it *is* a parameter self.assertEqual(1, len(function.parameters)) def test_illegal_module_line(self): self.parse_function_should_fail(""" module foo foo.bar => int / """) def test_illegal_c_basename(self): self.parse_function_should_fail(""" module foo foo.bar as 935 / """) def test_single_star(self): self.parse_function_should_fail(""" module foo foo.bar * * """) def test_parameters_required_after_star_without_initial_parameters_or_docstring(self): self.parse_function_should_fail(""" module foo foo.bar * """) def test_parameters_required_after_star_without_initial_parameters_with_docstring(self): self.parse_function_should_fail(""" module foo foo.bar * Docstring here. """) def test_parameters_required_after_star_with_initial_parameters_without_docstring(self): self.parse_function_should_fail(""" module foo foo.bar this: int * """) def test_parameters_required_after_star_with_initial_parameters_and_docstring(self): self.parse_function_should_fail(""" module foo foo.bar this: int * Docstring. """) def test_single_slash(self): self.parse_function_should_fail(""" module foo foo.bar / / """) def test_mix_star_and_slash(self): self.parse_function_should_fail(""" module foo foo.bar x: int y: int * z: int / """) def test_parameters_not_permitted_after_slash_for_now(self): self.parse_function_should_fail(""" module foo foo.bar / x: int """) def test_function_not_at_column_0(self): function = self.parse_function(""" module foo foo.bar x: int Nested docstring here, goeth. * y: str Not at column 0! """) self.assertEqual(""" bar($module, /, x, *, y) -- Not at column 0! x Nested docstring here, goeth. """.strip(), function.docstring) def test_directive(self): c = FakeClinic() parser = DSLParser(c) parser.flag = False parser.directives['setflag'] = lambda : setattr(parser, 'flag', True) block = clinic.Block("setflag") parser.parse(block) self.assertTrue(parser.flag) def test_legacy_converters(self): block = self.parse('module os\nos.access\n path: "s"') module, function = block.signatures self.assertIsInstance((function.parameters['path']).converter, clinic.str_converter) def parse(self, text): c = FakeClinic() parser = DSLParser(c) block = clinic.Block(text) parser.parse(block) return block def parse_function(self, text, signatures_in_block=2, function_index=1): block = self.parse(text) s = block.signatures self.assertEqual(len(s), signatures_in_block) assert isinstance(s[0], clinic.Module) assert isinstance(s[function_index], clinic.Function) return s[function_index] def test_scaffolding(self): # test repr on special values self.assertEqual(repr(clinic.unspecified), '<Unspecified>') self.assertEqual(repr(clinic.NULL), '<Null>') # test that fail fails with support.captured_stdout() as stdout: with self.assertRaises(SystemExit): clinic.fail('The igloos are melting!', filename='clown.txt', line_number=69) self.assertEqual(stdout.getvalue(), 'Error in file "clown.txt" on line 69:\nThe igloos are melting!\n') class ClinicExternalTest(TestCase): maxDiff = None def test_external(self): source = support.findfile('clinic.test') with open(source, 'r', encoding='utf-8') as f: original = f.read() with support.temp_dir() as testdir: testfile = os.path.join(testdir, 'clinic.test.c') with open(testfile, 'w', encoding='utf-8') as f: f.write(original) clinic.parse_file(testfile, force=True) with open(testfile, 'r', encoding='utf-8') as f: result = f.read() self.assertEqual(result, original) 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_range.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_range.py
# Python test set -- built-in functions import unittest import sys import pickle import itertools # pure Python implementations (3 args only), for comparison def pyrange(start, stop, step): if (start - stop) // step < 0: # replace stop with next element in the sequence of integers # that are congruent to start modulo step. stop += (start - stop) % step while start != stop: yield start start += step def pyrange_reversed(start, stop, step): stop += (start - stop) % step return pyrange(stop - step, start - step, -step) class RangeTest(unittest.TestCase): def assert_iterators_equal(self, xs, ys, test_id, limit=None): # check that an iterator xs matches the expected results ys, # up to a given limit. if limit is not None: xs = itertools.islice(xs, limit) ys = itertools.islice(ys, limit) sentinel = object() pairs = itertools.zip_longest(xs, ys, fillvalue=sentinel) for i, (x, y) in enumerate(pairs): if x == y: continue elif x == sentinel: self.fail('{}: iterator ended unexpectedly ' 'at position {}; expected {}'.format(test_id, i, y)) elif y == sentinel: self.fail('{}: unexpected excess element {} at ' 'position {}'.format(test_id, x, i)) else: self.fail('{}: wrong element at position {}; ' 'expected {}, got {}'.format(test_id, i, y, x)) def test_range(self): self.assertEqual(list(range(3)), [0, 1, 2]) self.assertEqual(list(range(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(range(0)), []) self.assertEqual(list(range(-3)), []) self.assertEqual(list(range(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) a = 10 b = 100 c = 50 self.assertEqual(list(range(a, a+2)), [a, a+1]) self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(range(a, b, c)) self.assertIn(a, seq) self.assertNotIn(b, seq) self.assertEqual(len(seq), 2) seq = list(range(b, a, -c)) self.assertIn(b, seq) self.assertNotIn(a, seq) self.assertEqual(len(seq), 2) seq = list(range(-a, -b, -c)) self.assertIn(-a, seq) self.assertNotIn(-b, seq) self.assertEqual(len(seq), 2) self.assertRaises(TypeError, range) self.assertRaises(TypeError, range, 1, 2, 3, 4) self.assertRaises(ValueError, range, 1, 2, 0) self.assertRaises(TypeError, range, 0.0, 2, 1) self.assertRaises(TypeError, range, 1, 2.0, 1) self.assertRaises(TypeError, range, 1, 2, 1.0) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, 42, "spam") self.assertEqual(len(range(0, sys.maxsize, sys.maxsize-1)), 2) r = range(-sys.maxsize, sys.maxsize, 2) self.assertEqual(len(r), sys.maxsize) def test_large_operands(self): x = range(10**20, 10**20+10, 3) self.assertEqual(len(x), 4) self.assertEqual(len(list(x)), 4) x = range(10**20+10, 10**20, 3) self.assertEqual(len(x), 0) self.assertEqual(len(list(x)), 0) self.assertFalse(x) x = range(10**20, 10**20+10, -3) self.assertEqual(len(x), 0) self.assertEqual(len(list(x)), 0) self.assertFalse(x) x = range(10**20+10, 10**20, -3) self.assertEqual(len(x), 4) self.assertEqual(len(list(x)), 4) self.assertTrue(x) # Now test range() with longs for x in [range(-2**100), range(0, -2**100), range(0, 2**100, -1)]: self.assertEqual(list(x), []) self.assertFalse(x) a = int(10 * sys.maxsize) b = int(100 * sys.maxsize) c = int(50 * sys.maxsize) self.assertEqual(list(range(a, a+2)), [a, a+1]) self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(range(a, b, c)) self.assertIn(a, seq) self.assertNotIn(b, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], a) self.assertEqual(seq[-1], a+c) seq = list(range(b, a, -c)) self.assertIn(b, seq) self.assertNotIn(a, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], b) self.assertEqual(seq[-1], b-c) seq = list(range(-a, -b, -c)) self.assertIn(-a, seq) self.assertNotIn(-b, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], -a) self.assertEqual(seq[-1], -a-c) def test_large_range(self): # Check long ranges (len > sys.maxsize) # len() is expected to fail due to limitations of the __len__ protocol def _range_len(x): try: length = len(x) except OverflowError: step = x[1] - x[0] length = 1 + ((x[-1] - x[0]) // step) return length a = -sys.maxsize b = sys.maxsize expected_len = b - a x = range(a, b) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+idx) self.assertEqual(x[idx:idx+1][0], a+idx) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = 0 b = 2 * sys.maxsize expected_len = b - a x = range(a, b) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+idx) self.assertEqual(x[idx:idx+1][0], a+idx) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = 0 b = sys.maxsize**10 c = 2*sys.maxsize expected_len = 1 + (b - a) // c x = range(a, b, c) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+(idx*c)) self.assertEqual(x[idx:idx+1][0], a+(idx*c)) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = sys.maxsize**10 b = 0 c = -2*sys.maxsize expected_len = 1 + (b - a) // c x = range(a, b, c) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+(idx*c)) self.assertEqual(x[idx:idx+1][0], a+(idx*c)) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] def test_invalid_invocation(self): self.assertRaises(TypeError, range) self.assertRaises(TypeError, range, 1, 2, 3, 4) self.assertRaises(ValueError, range, 1, 2, 0) a = int(10 * sys.maxsize) self.assertRaises(ValueError, range, a, a + 1, int(0)) self.assertRaises(TypeError, range, 1., 1., 1.) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, 42, "spam") # Exercise various combinations of bad arguments, to check # refcounting logic self.assertRaises(TypeError, range, 0.0) self.assertRaises(TypeError, range, 0, 0.0) self.assertRaises(TypeError, range, 0.0, 0) self.assertRaises(TypeError, range, 0.0, 0.0) self.assertRaises(TypeError, range, 0, 0, 1.0) self.assertRaises(TypeError, range, 0, 0.0, 1) self.assertRaises(TypeError, range, 0, 0.0, 1.0) self.assertRaises(TypeError, range, 0.0, 0, 1) self.assertRaises(TypeError, range, 0.0, 0, 1.0) self.assertRaises(TypeError, range, 0.0, 0.0, 1) self.assertRaises(TypeError, range, 0.0, 0.0, 1.0) def test_index(self): u = range(2) self.assertEqual(u.index(0), 0) self.assertEqual(u.index(1), 1) self.assertRaises(ValueError, u.index, 2) u = range(-2, 3) self.assertEqual(u.count(0), 1) self.assertEqual(u.index(0), 2) self.assertRaises(TypeError, u.index) class BadExc(Exception): pass class BadCmp: def __eq__(self, other): if other == 2: raise BadExc() return False a = range(4) self.assertRaises(BadExc, a.index, BadCmp()) a = range(-2, 3) self.assertEqual(a.index(0), 2) self.assertEqual(range(1, 10, 3).index(4), 1) self.assertEqual(range(1, -10, -3).index(-5), 2) self.assertEqual(range(10**20).index(1), 1) self.assertEqual(range(10**20).index(10**20 - 1), 10**20 - 1) self.assertRaises(ValueError, range(1, 2**100, 2).index, 2**87) self.assertEqual(range(1, 2**100, 2).index(2**87+1), 2**86) class AlwaysEqual(object): def __eq__(self, other): return True always_equal = AlwaysEqual() self.assertEqual(range(10).index(always_equal), 0) def test_user_index_method(self): bignum = 2*sys.maxsize smallnum = 42 # User-defined class with an __index__ method class I: def __init__(self, n): self.n = int(n) def __index__(self): return self.n self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum]) self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum]) # User-defined class with a failing __index__ method class IX: def __index__(self): raise RuntimeError self.assertRaises(RuntimeError, range, IX()) # User-defined class with an invalid __index__ method class IN: def __index__(self): return "not a number" self.assertRaises(TypeError, range, IN()) # Test use of user-defined classes in slice indices. self.assertEqual(range(10)[:I(5)], range(5)) with self.assertRaises(RuntimeError): range(0, 10)[:IX()] with self.assertRaises(TypeError): range(0, 10)[:IN()] def test_count(self): self.assertEqual(range(3).count(-1), 0) self.assertEqual(range(3).count(0), 1) self.assertEqual(range(3).count(1), 1) self.assertEqual(range(3).count(2), 1) self.assertEqual(range(3).count(3), 0) self.assertIs(type(range(3).count(-1)), int) self.assertIs(type(range(3).count(1)), int) self.assertEqual(range(10**20).count(1), 1) self.assertEqual(range(10**20).count(10**20), 0) self.assertEqual(range(3).index(1), 1) self.assertEqual(range(1, 2**100, 2).count(2**87), 0) self.assertEqual(range(1, 2**100, 2).count(2**87+1), 1) class AlwaysEqual(object): def __eq__(self, other): return True always_equal = AlwaysEqual() self.assertEqual(range(10).count(always_equal), 10) self.assertEqual(len(range(sys.maxsize, sys.maxsize+10)), 10) def test_repr(self): self.assertEqual(repr(range(1)), 'range(0, 1)') self.assertEqual(repr(range(1, 2)), 'range(1, 2)') self.assertEqual(repr(range(1, 2, 3)), 'range(1, 2, 3)') def test_pickling(self): testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1), (13, 21, 3), (-2, 2, 2), (2**65, 2**65+2)] for proto in range(pickle.HIGHEST_PROTOCOL + 1): for t in testcases: with self.subTest(proto=proto, test=t): r = range(*t) self.assertEqual(list(pickle.loads(pickle.dumps(r, proto))), list(r)) def test_iterator_pickling(self): testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1), (13, 21, 3), (-2, 2, 2), (2**65, 2**65+2)] for proto in range(pickle.HIGHEST_PROTOCOL + 1): for t in testcases: it = itorg = iter(range(*t)) data = list(range(*t)) d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(list(it), data) it = pickle.loads(d) try: next(it) except StopIteration: continue d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(list(it), data[1:]) def test_exhausted_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): r = range(2**65, 2**65+2) i = iter(r) while True: r = next(i) if r == 2**65+1: break d = pickle.dumps(i, proto) i2 = pickle.loads(d) self.assertEqual(list(i), []) self.assertEqual(list(i2), []) def test_large_exhausted_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): r = range(20) i = iter(r) while True: r = next(i) if r == 19: break d = pickle.dumps(i, proto) i2 = pickle.loads(d) self.assertEqual(list(i), []) self.assertEqual(list(i2), []) def test_odd_bug(self): # This used to raise a "SystemError: NULL result without error" # because the range validation step was eating the exception # before NULL was returned. with self.assertRaises(TypeError): range([], 1, -1) def test_types(self): # Non-integer objects *equal* to any of the range's items are supposed # to be contained in the range. self.assertIn(1.0, range(3)) self.assertIn(True, range(3)) self.assertIn(1+0j, range(3)) class C1: def __eq__(self, other): return True self.assertIn(C1(), range(3)) # Objects are never coerced into other types for comparison. class C2: def __int__(self): return 1 def __index__(self): return 1 self.assertNotIn(C2(), range(3)) # ..except if explicitly told so. self.assertIn(int(C2()), range(3)) # Check that the range.__contains__ optimization is only # used for ints, not for instances of subclasses of int. class C3(int): def __eq__(self, other): return True self.assertIn(C3(11), range(10)) self.assertIn(C3(11), list(range(10))) def test_strided_limits(self): r = range(0, 101, 2) self.assertIn(0, r) self.assertNotIn(1, r) self.assertIn(2, r) self.assertNotIn(99, r) self.assertIn(100, r) self.assertNotIn(101, r) r = range(0, -20, -1) self.assertIn(0, r) self.assertIn(-1, r) self.assertIn(-19, r) self.assertNotIn(-20, r) r = range(0, -20, -2) self.assertIn(-18, r) self.assertNotIn(-19, r) self.assertNotIn(-20, r) def test_empty(self): r = range(0) self.assertNotIn(0, r) self.assertNotIn(1, r) r = range(0, -10) self.assertNotIn(0, r) self.assertNotIn(-1, r) self.assertNotIn(1, r) def test_range_iterators(self): # exercise 'fast' iterators, that use a rangeiterobject internally. # see issue 7298 limits = [base + jiggle for M in (2**32, 2**64) for base in (-M, -M//2, 0, M//2, M) for jiggle in (-2, -1, 0, 1, 2)] test_ranges = [(start, end, step) for start in limits for end in limits for step in (-2**63, -2**31, -2, -1, 1, 2)] for start, end, step in test_ranges: iter1 = range(start, end, step) iter2 = pyrange(start, end, step) test_id = "range({}, {}, {})".format(start, end, step) # check first 100 entries self.assert_iterators_equal(iter1, iter2, test_id, limit=100) iter1 = reversed(range(start, end, step)) iter2 = pyrange_reversed(start, end, step) test_id = "reversed(range({}, {}, {}))".format(start, end, step) self.assert_iterators_equal(iter1, iter2, test_id, limit=100) def test_range_iterators_invocation(self): # verify range iterators instances cannot be created by # calling their type rangeiter_type = type(iter(range(0))) self.assertRaises(TypeError, rangeiter_type, 1, 3, 1) long_rangeiter_type = type(iter(range(1 << 1000))) self.assertRaises(TypeError, long_rangeiter_type, 1, 3, 1) def test_slice(self): def check(start, stop, step=None): i = slice(start, stop, step) self.assertEqual(list(r[i]), list(r)[i]) self.assertEqual(len(r[i]), len(list(r)[i])) for r in [range(10), range(0), range(1, 9, 3), range(8, 0, -3), range(sys.maxsize+1, sys.maxsize+10), ]: check(0, 2) check(0, 20) check(1, 2) check(20, 30) check(-30, -20) check(-1, 100, 2) check(0, -1) check(-1, -3, -1) def test_contains(self): r = range(10) self.assertIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(9, -1, -1) self.assertIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(0, 10, 2) self.assertIn(0, r) self.assertNotIn(1, r) self.assertNotIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(9, -1, -2) self.assertNotIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) def test_reverse_iteration(self): for r in [range(10), range(0), range(1, 9, 3), range(8, 0, -3), range(sys.maxsize+1, sys.maxsize+10), ]: self.assertEqual(list(reversed(r)), list(r)[::-1]) def test_issue11845(self): r = range(*slice(1, 18, 2).indices(20)) values = {None, 0, 1, -1, 2, -2, 5, -5, 19, -19, 20, -20, 21, -21, 30, -30, 99, -99} for i in values: for j in values: for k in values - {0}: r[i:j:k] def test_comparison(self): test_ranges = [range(0), range(0, -1), range(1, 1, 3), range(1), range(5, 6), range(5, 6, 2), range(5, 7, 2), range(2), range(0, 4, 2), range(0, 5, 2), range(0, 6, 2)] test_tuples = list(map(tuple, test_ranges)) # Check that equality of ranges matches equality of the corresponding # tuples for each pair from the test lists above. ranges_eq = [a == b for a in test_ranges for b in test_ranges] tuples_eq = [a == b for a in test_tuples for b in test_tuples] self.assertEqual(ranges_eq, tuples_eq) # Check that != correctly gives the logical negation of == ranges_ne = [a != b for a in test_ranges for b in test_ranges] self.assertEqual(ranges_ne, [not x for x in ranges_eq]) # Equal ranges should have equal hashes. for a in test_ranges: for b in test_ranges: if a == b: self.assertEqual(hash(a), hash(b)) # Ranges are unequal to other types (even sequence types) self.assertIs(range(0) == (), False) self.assertIs(() == range(0), False) self.assertIs(range(2) == [0, 1], False) # Huge integers aren't a problem. self.assertEqual(range(0, 2**100 - 1, 2), range(0, 2**100, 2)) self.assertEqual(hash(range(0, 2**100 - 1, 2)), hash(range(0, 2**100, 2))) self.assertNotEqual(range(0, 2**100, 2), range(0, 2**100 + 1, 2)) self.assertEqual(range(2**200, 2**201 - 2**99, 2**100), range(2**200, 2**201, 2**100)) self.assertEqual(hash(range(2**200, 2**201 - 2**99, 2**100)), hash(range(2**200, 2**201, 2**100))) self.assertNotEqual(range(2**200, 2**201, 2**100), range(2**200, 2**201 + 1, 2**100)) # Order comparisons are not implemented for ranges. with self.assertRaises(TypeError): range(0) < range(0) with self.assertRaises(TypeError): range(0) > range(0) with self.assertRaises(TypeError): range(0) <= range(0) with self.assertRaises(TypeError): range(0) >= range(0) def test_attributes(self): # test the start, stop and step attributes of range objects self.assert_attrs(range(0), 0, 0, 1) self.assert_attrs(range(10), 0, 10, 1) self.assert_attrs(range(-10), 0, -10, 1) self.assert_attrs(range(0, 10, 1), 0, 10, 1) self.assert_attrs(range(0, 10, 3), 0, 10, 3) self.assert_attrs(range(10, 0, -1), 10, 0, -1) self.assert_attrs(range(10, 0, -3), 10, 0, -3) def assert_attrs(self, rangeobj, start, stop, step): self.assertEqual(rangeobj.start, start) self.assertEqual(rangeobj.stop, stop) self.assertEqual(rangeobj.step, step) with self.assertRaises(AttributeError): rangeobj.start = 0 with self.assertRaises(AttributeError): rangeobj.stop = 10 with self.assertRaises(AttributeError): rangeobj.step = 1 with self.assertRaises(AttributeError): del rangeobj.start with self.assertRaises(AttributeError): del rangeobj.stop with self.assertRaises(AttributeError): del rangeobj.step 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_runpy.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_runpy.py
# Test the runpy module import unittest import os import os.path import sys import re import tempfile import importlib, importlib.machinery, importlib.util import py_compile import warnings from test.support import ( forget, make_legacy_pyc, unload, verbose, no_tracing, create_empty_file, temp_dir) from test.support.script_helper import ( make_pkg, make_script, make_zip_pkg, make_zip_script) import runpy from runpy import _run_code, _run_module_code, run_module, run_path # Note: This module can't safely test _run_module_as_main as it # runs its tests in the current process, which would mess with the # real __main__ module (usually test.regrtest) # See test_cmd_line_script for a test that executes that code path # Set up the test code and expected results example_source = """\ # Check basic code execution result = ['Top level assignment'] def f(): result.append('Lower level reference') f() del f # Check the sys module import sys run_argv0 = sys.argv[0] run_name_in_sys_modules = __name__ in sys.modules module_in_sys_modules = (run_name_in_sys_modules and globals() is sys.modules[__name__].__dict__) # Check nested operation import runpy nested = runpy._run_module_code('x=1\\n', mod_name='<run>') """ implicit_namespace = { "__name__": None, "__file__": None, "__cached__": None, "__package__": None, "__doc__": None, "__spec__": None } example_namespace = { "sys": sys, "runpy": runpy, "result": ["Top level assignment", "Lower level reference"], "run_argv0": sys.argv[0], "run_name_in_sys_modules": False, "module_in_sys_modules": False, "nested": dict(implicit_namespace, x=1, __name__="<run>", __loader__=None), } example_namespace.update(implicit_namespace) class CodeExecutionMixin: # Issue #15230 (run_path not handling run_name correctly) highlighted a # problem with the way arguments were being passed from higher level APIs # down to lower level code. This mixin makes it easier to ensure full # testing occurs at those upper layers as well, not just at the utility # layer # Figuring out the loader details in advance is hard to do, so we skip # checking the full details of loader and loader_state CHECKED_SPEC_ATTRIBUTES = ["name", "parent", "origin", "cached", "has_location", "submodule_search_locations"] def assertNamespaceMatches(self, result_ns, expected_ns): """Check two namespaces match. Ignores any unspecified interpreter created names """ # Avoid side effects result_ns = result_ns.copy() expected_ns = expected_ns.copy() # Impls are permitted to add extra names, so filter them out for k in list(result_ns): if k.startswith("__") and k.endswith("__"): if k not in expected_ns: result_ns.pop(k) if k not in expected_ns["nested"]: result_ns["nested"].pop(k) # Spec equality includes the loader, so we take the spec out of the # result namespace and check that separately result_spec = result_ns.pop("__spec__") expected_spec = expected_ns.pop("__spec__") if expected_spec is None: self.assertIsNone(result_spec) else: # If an expected loader is set, we just check we got the right # type, rather than checking for full equality if expected_spec.loader is not None: self.assertEqual(type(result_spec.loader), type(expected_spec.loader)) for attr in self.CHECKED_SPEC_ATTRIBUTES: k = "__spec__." + attr actual = (k, getattr(result_spec, attr)) expected = (k, getattr(expected_spec, attr)) self.assertEqual(actual, expected) # For the rest, we still don't use direct dict comparison on the # namespace, as the diffs are too hard to debug if anything breaks self.assertEqual(set(result_ns), set(expected_ns)) for k in result_ns: actual = (k, result_ns[k]) expected = (k, expected_ns[k]) self.assertEqual(actual, expected) def check_code_execution(self, create_namespace, expected_namespace): """Check that an interface runs the example code correctly First argument is a callable accepting the initial globals and using them to create the actual namespace Second argument is the expected result """ sentinel = object() expected_ns = expected_namespace.copy() run_name = expected_ns["__name__"] saved_argv0 = sys.argv[0] saved_mod = sys.modules.get(run_name, sentinel) # Check without initial globals result_ns = create_namespace(None) self.assertNamespaceMatches(result_ns, expected_ns) self.assertIs(sys.argv[0], saved_argv0) self.assertIs(sys.modules.get(run_name, sentinel), saved_mod) # And then with initial globals initial_ns = {"sentinel": sentinel} expected_ns["sentinel"] = sentinel result_ns = create_namespace(initial_ns) self.assertIsNot(result_ns, initial_ns) self.assertNamespaceMatches(result_ns, expected_ns) self.assertIs(sys.argv[0], saved_argv0) self.assertIs(sys.modules.get(run_name, sentinel), saved_mod) class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy._run_code and runpy._run_module_code""" def test_run_code(self): expected_ns = example_namespace.copy() expected_ns.update({ "__loader__": None, }) def create_ns(init_globals): return _run_code(example_source, {}, init_globals) self.check_code_execution(create_ns, expected_ns) def test_run_module_code(self): mod_name = "<Nonsense>" mod_fname = "Some other nonsense" mod_loader = "Now you're just being silly" mod_package = '' # Treat as a top level module mod_spec = importlib.machinery.ModuleSpec(mod_name, origin=mod_fname, loader=mod_loader) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__loader__": mod_loader, "__package__": mod_package, "__spec__": mod_spec, "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return _run_module_code(example_source, init_globals, mod_name, mod_spec) self.check_code_execution(create_ns, expected_ns) # TODO: Use self.addCleanup to get rid of a lot of try-finally blocks class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy.run_module""" def expect_import_error(self, mod_name): try: run_module(mod_name) except ImportError: pass else: self.fail("Expected import error for " + mod_name) def test_invalid_names(self): # Builtin module self.expect_import_error("sys") # Non-existent modules self.expect_import_error("sys.imp.eric") self.expect_import_error("os.path.half") self.expect_import_error("a.bee") # Relative names not allowed self.expect_import_error(".howard") self.expect_import_error("..eaten") self.expect_import_error(".test_runpy") self.expect_import_error(".unittest") # Package without __main__.py self.expect_import_error("multiprocessing") def test_library_module(self): self.assertEqual(run_module("runpy")["__name__"], "runpy") def _add_pkg_dir(self, pkg_dir, namespace=False): os.mkdir(pkg_dir) if namespace: return None pkg_fname = os.path.join(pkg_dir, "__init__.py") create_empty_file(pkg_fname) return pkg_fname def _make_pkg(self, source, depth, mod_base="runpy_test", *, namespace=False, parent_namespaces=False): # Enforce a couple of internal sanity checks on test cases if (namespace or parent_namespaces) and not depth: raise RuntimeError("Can't mark top level module as a " "namespace package") pkg_name = "__runpy_pkg__" test_fname = mod_base+os.extsep+"py" pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp()) if verbose > 1: print(" Package tree in:", sub_dir) sys.path.insert(0, pkg_dir) if verbose > 1: print(" Updated sys.path:", sys.path[0]) if depth: namespace_flags = [parent_namespaces] * depth namespace_flags[-1] = namespace for namespace_flag in namespace_flags: sub_dir = os.path.join(sub_dir, pkg_name) pkg_fname = self._add_pkg_dir(sub_dir, namespace_flag) if verbose > 1: print(" Next level in:", sub_dir) if verbose > 1: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) mod_file = open(mod_fname, "w") mod_file.write(source) mod_file.close() if verbose > 1: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + mod_base mod_spec = importlib.util.spec_from_file_location(mod_name, mod_fname) return pkg_dir, mod_fname, mod_name, mod_spec def _del_pkg(self, top): for entry in list(sys.modules): if entry.startswith("__runpy_pkg__"): del sys.modules[entry] if verbose > 1: print(" Removed sys.modules entries") del sys.path[0] if verbose > 1: print(" Removed sys.path entry") for root, dirs, files in os.walk(top, topdown=False): for name in files: try: os.remove(os.path.join(root, name)) except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up try: os.rmdir(top) if verbose > 1: print(" Removed package tree") except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up def _fix_ns_for_legacy_pyc(self, ns, alter_sys): char_to_add = "c" ns["__file__"] += char_to_add ns["__cached__"] = ns["__file__"] spec = ns["__spec__"] new_spec = importlib.util.spec_from_file_location(spec.name, ns["__file__"]) ns["__spec__"] = new_spec if alter_sys: ns["run_argv0"] += char_to_add def _check_module(self, depth, alter_sys=False, *, namespace=False, parent_namespaces=False): pkg_dir, mod_fname, mod_name, mod_spec = ( self._make_pkg(example_source, depth, namespace=namespace, parent_namespaces=parent_namespaces)) forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__cached__": mod_spec.cached, "__package__": mod_name.rpartition(".")[0], "__spec__": mod_spec, }) if alter_sys: expected_ns.update({ "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return run_module(mod_name, init_globals, alter_sys=alter_sys) try: if verbose > 1: print("Running from source:", mod_name) self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) if not sys.dont_write_bytecode: make_legacy_pyc(mod_fname) unload(mod_name) # In case loader caches paths importlib.invalidate_caches() if verbose > 1: print("Running from compiled:", mod_name) self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir) if verbose > 1: print("Module executed successfully") def _check_package(self, depth, alter_sys=False, *, namespace=False, parent_namespaces=False): pkg_dir, mod_fname, mod_name, mod_spec = ( self._make_pkg(example_source, depth, "__main__", namespace=namespace, parent_namespaces=parent_namespaces)) pkg_name = mod_name.rpartition(".")[0] forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__cached__": importlib.util.cache_from_source(mod_fname), "__package__": pkg_name, "__spec__": mod_spec, }) if alter_sys: expected_ns.update({ "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return run_module(pkg_name, init_globals, alter_sys=alter_sys) try: if verbose > 1: print("Running from source:", pkg_name) self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) if not sys.dont_write_bytecode: make_legacy_pyc(mod_fname) unload(mod_name) # In case loader caches paths if verbose > 1: print("Running from compiled:", pkg_name) importlib.invalidate_caches() self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir) if verbose > 1: print("Package executed successfully") def _add_relative_modules(self, base_dir, source, depth): if depth <= 1: raise ValueError("Relative module test needs depth > 1") pkg_name = "__runpy_pkg__" module_dir = base_dir for i in range(depth): parent_dir = module_dir module_dir = os.path.join(module_dir, pkg_name) # Add sibling module sibling_fname = os.path.join(module_dir, "sibling.py") create_empty_file(sibling_fname) if verbose > 1: print(" Added sibling module:", sibling_fname) # Add nephew module uncle_dir = os.path.join(parent_dir, "uncle") self._add_pkg_dir(uncle_dir) if verbose > 1: print(" Added uncle package:", uncle_dir) cousin_dir = os.path.join(uncle_dir, "cousin") self._add_pkg_dir(cousin_dir) if verbose > 1: print(" Added cousin package:", cousin_dir) nephew_fname = os.path.join(cousin_dir, "nephew.py") create_empty_file(nephew_fname) if verbose > 1: print(" Added nephew module:", nephew_fname) def _check_relative_imports(self, depth, run_name=None): contents = r"""\ from __future__ import absolute_import from . import sibling from ..uncle.cousin import nephew """ pkg_dir, mod_fname, mod_name, mod_spec = ( self._make_pkg(contents, depth)) if run_name is None: expected_name = mod_name else: expected_name = run_name try: self._add_relative_modules(pkg_dir, contents, depth) pkg_name = mod_name.rpartition('.')[0] if verbose > 1: print("Running from source:", mod_name) d1 = run_module(mod_name, run_name=run_name) # Read from source self.assertEqual(d1["__name__"], expected_name) self.assertEqual(d1["__package__"], pkg_name) self.assertIn("sibling", d1) self.assertIn("nephew", d1) del d1 # Ensure __loader__ entry doesn't keep file open importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) if not sys.dont_write_bytecode: make_legacy_pyc(mod_fname) unload(mod_name) # In case the loader caches paths if verbose > 1: print("Running from compiled:", mod_name) importlib.invalidate_caches() d2 = run_module(mod_name, run_name=run_name) # Read from bytecode self.assertEqual(d2["__name__"], expected_name) self.assertEqual(d2["__package__"], pkg_name) self.assertIn("sibling", d2) self.assertIn("nephew", d2) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir) if verbose > 1: print("Module executed successfully") def test_run_module(self): for depth in range(4): if verbose > 1: print("Testing package depth:", depth) self._check_module(depth) def test_run_module_in_namespace_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_module(depth, namespace=True, parent_namespaces=True) def test_run_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth) def test_run_package_init_exceptions(self): # These were previously wrapped in an ImportError; see Issue 14285 result = self._make_pkg("", 1, "__main__") pkg_dir, _, mod_name, _ = result mod_name = mod_name.replace(".__main__", "") self.addCleanup(self._del_pkg, pkg_dir) init = os.path.join(pkg_dir, "__runpy_pkg__", "__init__.py") exceptions = (ImportError, AttributeError, TypeError, ValueError) for exception in exceptions: name = exception.__name__ with self.subTest(name): source = "raise {0}('{0} in __init__.py.')".format(name) with open(init, "wt", encoding="ascii") as mod_file: mod_file.write(source) try: run_module(mod_name) except exception as err: self.assertNotIn("finding spec", format(err)) else: self.fail("Nothing raised; expected {}".format(name)) try: run_module(mod_name + ".submodule") except exception as err: self.assertNotIn("finding spec", format(err)) else: self.fail("Nothing raised; expected {}".format(name)) def test_submodule_imported_warning(self): pkg_dir, _, mod_name, _ = self._make_pkg("", 1) try: __import__(mod_name) with self.assertWarnsRegex(RuntimeWarning, r"found in sys\.modules"): run_module(mod_name) finally: self._del_pkg(pkg_dir) def test_package_imported_no_warning(self): pkg_dir, _, mod_name, _ = self._make_pkg("", 1, "__main__") self.addCleanup(self._del_pkg, pkg_dir) package = mod_name.replace(".__main__", "") # No warning should occur if we only imported the parent package __import__(package) self.assertIn(package, sys.modules) with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) run_module(package) # But the warning should occur if we imported the __main__ submodule __import__(mod_name) with self.assertWarnsRegex(RuntimeWarning, r"found in sys\.modules"): run_module(package) def test_run_package_in_namespace_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth, parent_namespaces=True) def test_run_namespace_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth, namespace=True) def test_run_namespace_package_in_namespace_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth, namespace=True, parent_namespaces=True) def test_run_module_alter_sys(self): for depth in range(4): if verbose > 1: print("Testing package depth:", depth) self._check_module(depth, alter_sys=True) def test_run_package_alter_sys(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth, alter_sys=True) def test_explicit_relative_import(self): for depth in range(2, 5): if verbose > 1: print("Testing relative imports at depth:", depth) self._check_relative_imports(depth) def test_main_relative_import(self): for depth in range(2, 5): if verbose > 1: print("Testing main relative imports at depth:", depth) self._check_relative_imports(depth, "__main__") def test_run_name(self): depth = 1 run_name = "And now for something completely different" pkg_dir, mod_fname, mod_name, mod_spec = ( self._make_pkg(example_source, depth)) forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": run_name, "__file__": mod_fname, "__cached__": importlib.util.cache_from_source(mod_fname), "__package__": mod_name.rpartition(".")[0], "__spec__": mod_spec, }) def create_ns(init_globals): return run_module(mod_name, init_globals, run_name) try: self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir) def test_pkgutil_walk_packages(self): # This is a dodgy hack to use the test_runpy infrastructure to test # issue #15343. Issue #15348 declares this is indeed a dodgy hack ;) import pkgutil max_depth = 4 base_name = "__runpy_pkg__" package_suffixes = ["uncle", "uncle.cousin"] module_suffixes = ["uncle.cousin.nephew", base_name + ".sibling"] expected_packages = set() expected_modules = set() for depth in range(1, max_depth): pkg_name = ".".join([base_name] * depth) expected_packages.add(pkg_name) for name in package_suffixes: expected_packages.add(pkg_name + "." + name) for name in module_suffixes: expected_modules.add(pkg_name + "." + name) pkg_name = ".".join([base_name] * max_depth) expected_packages.add(pkg_name) expected_modules.add(pkg_name + ".runpy_test") pkg_dir, mod_fname, mod_name, mod_spec = ( self._make_pkg("", max_depth)) self.addCleanup(self._del_pkg, pkg_dir) for depth in range(2, max_depth+1): self._add_relative_modules(pkg_dir, "", depth) for moduleinfo in pkgutil.walk_packages([pkg_dir]): self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) self.assertIsInstance(moduleinfo.module_finder, importlib.machinery.FileFinder) if moduleinfo.ispkg: expected_packages.remove(moduleinfo.name) else: expected_modules.remove(moduleinfo.name) self.assertEqual(len(expected_packages), 0, expected_packages) self.assertEqual(len(expected_modules), 0, expected_modules) class RunPathTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy.run_path""" def _make_test_script(self, script_dir, script_basename, source=None, omit_suffix=False): if source is None: source = example_source return make_script(script_dir, script_basename, source, omit_suffix) def _check_script(self, script_name, expected_name, expected_file, expected_argv0, mod_name=None, expect_spec=True, check_loader=True): # First check is without run_name def create_ns(init_globals): return run_path(script_name, init_globals) expected_ns = example_namespace.copy() if mod_name is None: spec_name = expected_name else: spec_name = mod_name if expect_spec: mod_spec = importlib.util.spec_from_file_location(spec_name, expected_file) mod_cached = mod_spec.cached if not check_loader: mod_spec.loader = None else: mod_spec = mod_cached = None expected_ns.update({ "__name__": expected_name, "__file__": expected_file, "__cached__": mod_cached, "__package__": "", "__spec__": mod_spec, "run_argv0": expected_argv0, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) self.check_code_execution(create_ns, expected_ns) # Second check makes sure run_name works in all cases run_name = "prove.issue15230.is.fixed" def create_ns(init_globals): return run_path(script_name, init_globals, run_name) if expect_spec and mod_name is None: mod_spec = importlib.util.spec_from_file_location(run_name, expected_file) if not check_loader: mod_spec.loader = None expected_ns["__spec__"] = mod_spec expected_ns["__name__"] = run_name expected_ns["__package__"] = run_name.rpartition(".")[0] self.check_code_execution(create_ns, expected_ns) def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegex(ImportError, msg, run_path, script_name) def test_basic_script(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_name, "<run_path>", script_name, script_name, expect_spec=False) def test_basic_script_no_suffix(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name, omit_suffix=True) self._check_script(script_name, "<run_path>", script_name, script_name, expect_spec=False) def test_script_compiled(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) self._check_script(compiled_name, "<run_path>", compiled_name, compiled_name, expect_spec=False) def test_directory(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_dir, "<run_path>", script_name, script_dir, mod_name=mod_name) def test_directory_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) if not sys.dont_write_bytecode: legacy_pyc = make_legacy_pyc(script_name) self._check_script(script_dir, "<run_path>", legacy_pyc, script_dir, mod_name=mod_name) def test_directory_error(self): with temp_dir() as script_dir: mod_name = 'not_main' script_name = self._make_test_script(script_dir, mod_name) msg = "can't find '__main__' module in %r" % script_dir self._check_import_error(script_dir, msg) def test_zipfile(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) self._check_script(zip_name, "<run_path>", fname, zip_name, mod_name=mod_name, check_loader=False) def test_zipfile_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, "<run_path>", fname, zip_name, mod_name=mod_name, check_loader=False) def test_zipfile_error(self): with temp_dir() as script_dir: mod_name = 'not_main' script_name = self._make_test_script(script_dir, mod_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) msg = "can't find '__main__' module in %r" % zip_name self._check_import_error(zip_name, msg) @no_tracing def test_main_recursion_error(self): with temp_dir() as script_dir, temp_dir() as dummy_dir: mod_name = '__main__' source = ("import runpy\n" "runpy.run_path(%r)\n") % dummy_dir script_name = self._make_test_script(script_dir, mod_name, source) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) msg = "recursion depth exceeded" self.assertRaisesRegex(RecursionError, msg, run_path, zip_name) def test_encoding(self): with temp_dir() as script_dir: filename = os.path.join(script_dir, 'script.py') with open(filename, 'w', encoding='latin1') as f: f.write(""" #coding:latin1 s = "non-ASCII: h\xe9" """) result = run_path(filename) self.assertEqual(result['s'], "non-ASCII: h\xe9") 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_yield_from.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_yield_from.py
# -*- coding: utf-8 -*- """ Test suite for PEP 380 implementation adapted from original tests written by Greg Ewing see <http://www.cosc.canterbury.ac.nz/greg.ewing/python/yield-from/YieldFrom-Python3.1.2-rev5.zip> """ import unittest import inspect from test.support import captured_stderr, disable_gc, gc_collect class TestPEP380Operation(unittest.TestCase): """ Test semantics. """ def test_delegation_of_initial_next_to_subgenerator(self): """ Test delegation of initial next() call to subgenerator """ trace = [] def g1(): trace.append("Starting g1") yield from g2() trace.append("Finishing g1") def g2(): trace.append("Starting g2") yield 42 trace.append("Finishing g2") for x in g1(): trace.append("Yielded %s" % (x,)) self.assertEqual(trace,[ "Starting g1", "Starting g2", "Yielded 42", "Finishing g2", "Finishing g1", ]) def test_raising_exception_in_initial_next_call(self): """ Test raising exception in initial next() call """ trace = [] def g1(): try: trace.append("Starting g1") yield from g2() finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") raise ValueError("spanish inquisition occurred") finally: trace.append("Finishing g2") try: for x in g1(): trace.append("Yielded %s" % (x,)) except ValueError as e: self.assertEqual(e.args[0], "spanish inquisition occurred") else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Starting g1", "Starting g2", "Finishing g2", "Finishing g1", ]) def test_delegation_of_next_call_to_subgenerator(self): """ Test delegation of next() call to subgenerator """ trace = [] def g1(): trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" trace.append("Finishing g1") def g2(): trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" trace.append("Finishing g2") for x in g1(): trace.append("Yielded %s" % (x,)) self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Yielded g2 more spam", "Finishing g2", "Yielded g1 eggs", "Finishing g1", ]) def test_raising_exception_in_delegated_next_call(self): """ Test raising exception in delegated next() call """ trace = [] def g1(): try: trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") yield "g2 spam" raise ValueError("hovercraft is full of eels") yield "g2 more spam" finally: trace.append("Finishing g2") try: for x in g1(): trace.append("Yielded %s" % (x,)) except ValueError as e: self.assertEqual(e.args[0], "hovercraft is full of eels") else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Finishing g2", "Finishing g1", ]) def test_delegation_of_send(self): """ Test delegation of send() """ trace = [] def g1(): trace.append("Starting g1") x = yield "g1 ham" trace.append("g1 received %s" % (x,)) yield from g2() x = yield "g1 eggs" trace.append("g1 received %s" % (x,)) trace.append("Finishing g1") def g2(): trace.append("Starting g2") x = yield "g2 spam" trace.append("g2 received %s" % (x,)) x = yield "g2 more spam" trace.append("g2 received %s" % (x,)) trace.append("Finishing g2") g = g1() y = next(g) x = 1 try: while 1: y = g.send(x) trace.append("Yielded %s" % (y,)) x += 1 except StopIteration: pass self.assertEqual(trace,[ "Starting g1", "g1 received 1", "Starting g2", "Yielded g2 spam", "g2 received 2", "Yielded g2 more spam", "g2 received 3", "Finishing g2", "Yielded g1 eggs", "g1 received 4", "Finishing g1", ]) def test_handling_exception_while_delegating_send(self): """ Test handling exception while delegating 'send' """ trace = [] def g1(): trace.append("Starting g1") x = yield "g1 ham" trace.append("g1 received %s" % (x,)) yield from g2() x = yield "g1 eggs" trace.append("g1 received %s" % (x,)) trace.append("Finishing g1") def g2(): trace.append("Starting g2") x = yield "g2 spam" trace.append("g2 received %s" % (x,)) raise ValueError("hovercraft is full of eels") x = yield "g2 more spam" trace.append("g2 received %s" % (x,)) trace.append("Finishing g2") def run(): g = g1() y = next(g) x = 1 try: while 1: y = g.send(x) trace.append("Yielded %s" % (y,)) x += 1 except StopIteration: trace.append("StopIteration") self.assertRaises(ValueError,run) self.assertEqual(trace,[ "Starting g1", "g1 received 1", "Starting g2", "Yielded g2 spam", "g2 received 2", ]) def test_delegating_close(self): """ Test delegating 'close' """ trace = [] def g1(): try: trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" finally: trace.append("Finishing g2") g = g1() for i in range(2): x = next(g) trace.append("Yielded %s" % (x,)) g.close() self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Finishing g2", "Finishing g1" ]) def test_handing_exception_while_delegating_close(self): """ Test handling exception while delegating 'close' """ trace = [] def g1(): try: trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" finally: trace.append("Finishing g2") raise ValueError("nybbles have exploded with delight") try: g = g1() for i in range(2): x = next(g) trace.append("Yielded %s" % (x,)) g.close() except ValueError as e: self.assertEqual(e.args[0], "nybbles have exploded with delight") self.assertIsInstance(e.__context__, GeneratorExit) else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Finishing g2", "Finishing g1", ]) def test_delegating_throw(self): """ Test delegating 'throw' """ trace = [] def g1(): try: trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" finally: trace.append("Finishing g2") try: g = g1() for i in range(2): x = next(g) trace.append("Yielded %s" % (x,)) e = ValueError("tomato ejected") g.throw(e) except ValueError as e: self.assertEqual(e.args[0], "tomato ejected") else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Finishing g2", "Finishing g1", ]) def test_value_attribute_of_StopIteration_exception(self): """ Test 'value' attribute of StopIteration exception """ trace = [] def pex(e): trace.append("%s: %s" % (e.__class__.__name__, e)) trace.append("value = %s" % (e.value,)) e = StopIteration() pex(e) e = StopIteration("spam") pex(e) e.value = "eggs" pex(e) self.assertEqual(trace,[ "StopIteration: ", "value = None", "StopIteration: spam", "value = spam", "StopIteration: spam", "value = eggs", ]) def test_exception_value_crash(self): # There used to be a refcount error when the return value # stored in the StopIteration has a refcount of 1. def g1(): yield from g2() def g2(): yield "g2" return [42] self.assertEqual(list(g1()), ["g2"]) def test_generator_return_value(self): """ Test generator return value """ trace = [] def g1(): trace.append("Starting g1") yield "g1 ham" ret = yield from g2() trace.append("g2 returned %r" % (ret,)) for v in 1, (2,), StopIteration(3): ret = yield from g2(v) trace.append("g2 returned %r" % (ret,)) yield "g1 eggs" trace.append("Finishing g1") def g2(v = None): trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" trace.append("Finishing g2") if v: return v for x in g1(): trace.append("Yielded %s" % (x,)) self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Yielded g2 more spam", "Finishing g2", "g2 returned None", "Starting g2", "Yielded g2 spam", "Yielded g2 more spam", "Finishing g2", "g2 returned 1", "Starting g2", "Yielded g2 spam", "Yielded g2 more spam", "Finishing g2", "g2 returned (2,)", "Starting g2", "Yielded g2 spam", "Yielded g2 more spam", "Finishing g2", "g2 returned StopIteration(3)", "Yielded g1 eggs", "Finishing g1", ]) def test_delegation_of_next_to_non_generator(self): """ Test delegation of next() to non-generator """ trace = [] def g(): yield from range(3) for x in g(): trace.append("Yielded %s" % (x,)) self.assertEqual(trace,[ "Yielded 0", "Yielded 1", "Yielded 2", ]) def test_conversion_of_sendNone_to_next(self): """ Test conversion of send(None) to next() """ trace = [] def g(): yield from range(3) gi = g() for x in range(3): y = gi.send(None) trace.append("Yielded: %s" % (y,)) self.assertEqual(trace,[ "Yielded: 0", "Yielded: 1", "Yielded: 2", ]) def test_delegation_of_close_to_non_generator(self): """ Test delegation of close() to non-generator """ trace = [] def g(): try: trace.append("starting g") yield from range(3) trace.append("g should not be here") finally: trace.append("finishing g") gi = g() next(gi) with captured_stderr() as output: gi.close() self.assertEqual(output.getvalue(), '') self.assertEqual(trace,[ "starting g", "finishing g", ]) def test_delegating_throw_to_non_generator(self): """ Test delegating 'throw' to non-generator """ trace = [] def g(): try: trace.append("Starting g") yield from range(10) finally: trace.append("Finishing g") try: gi = g() for i in range(5): x = next(gi) trace.append("Yielded %s" % (x,)) e = ValueError("tomato ejected") gi.throw(e) except ValueError as e: self.assertEqual(e.args[0],"tomato ejected") else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Starting g", "Yielded 0", "Yielded 1", "Yielded 2", "Yielded 3", "Yielded 4", "Finishing g", ]) def test_attempting_to_send_to_non_generator(self): """ Test attempting to send to non-generator """ trace = [] def g(): try: trace.append("starting g") yield from range(3) trace.append("g should not be here") finally: trace.append("finishing g") try: gi = g() next(gi) for x in range(3): y = gi.send(42) trace.append("Should not have yielded: %s" % (y,)) except AttributeError as e: self.assertIn("send", e.args[0]) else: self.fail("was able to send into non-generator") self.assertEqual(trace,[ "starting g", "finishing g", ]) def test_broken_getattr_handling(self): """ Test subiterator with a broken getattr implementation """ class Broken: def __iter__(self): return self def __next__(self): return 1 def __getattr__(self, attr): 1/0 def g(): yield from Broken() with self.assertRaises(ZeroDivisionError): gi = g() self.assertEqual(next(gi), 1) gi.send(1) with self.assertRaises(ZeroDivisionError): gi = g() self.assertEqual(next(gi), 1) gi.throw(AttributeError) with captured_stderr() as output: gi = g() self.assertEqual(next(gi), 1) gi.close() self.assertIn('ZeroDivisionError', output.getvalue()) def test_exception_in_initial_next_call(self): """ Test exception in initial next() call """ trace = [] def g1(): trace.append("g1 about to yield from g2") yield from g2() trace.append("g1 should not be here") def g2(): yield 1/0 def run(): gi = g1() next(gi) self.assertRaises(ZeroDivisionError,run) self.assertEqual(trace,[ "g1 about to yield from g2" ]) def test_attempted_yield_from_loop(self): """ Test attempted yield-from loop """ trace = [] def g1(): trace.append("g1: starting") yield "y1" trace.append("g1: about to yield from g2") yield from g2() trace.append("g1 should not be here") def g2(): trace.append("g2: starting") yield "y2" trace.append("g2: about to yield from g1") yield from gi trace.append("g2 should not be here") try: gi = g1() for y in gi: trace.append("Yielded: %s" % (y,)) except ValueError as e: self.assertEqual(e.args[0],"generator already executing") else: self.fail("subgenerator didn't raise ValueError") self.assertEqual(trace,[ "g1: starting", "Yielded: y1", "g1: about to yield from g2", "g2: starting", "Yielded: y2", "g2: about to yield from g1", ]) def test_returning_value_from_delegated_throw(self): """ Test returning value from delegated 'throw' """ trace = [] def g1(): try: trace.append("Starting g1") yield "g1 ham" yield from g2() yield "g1 eggs" finally: trace.append("Finishing g1") def g2(): try: trace.append("Starting g2") yield "g2 spam" yield "g2 more spam" except LunchError: trace.append("Caught LunchError in g2") yield "g2 lunch saved" yield "g2 yet more spam" class LunchError(Exception): pass g = g1() for i in range(2): x = next(g) trace.append("Yielded %s" % (x,)) e = LunchError("tomato ejected") g.throw(e) for x in g: trace.append("Yielded %s" % (x,)) self.assertEqual(trace,[ "Starting g1", "Yielded g1 ham", "Starting g2", "Yielded g2 spam", "Caught LunchError in g2", "Yielded g2 yet more spam", "Yielded g1 eggs", "Finishing g1", ]) def test_next_and_return_with_value(self): """ Test next and return with value """ trace = [] def f(r): gi = g(r) next(gi) try: trace.append("f resuming g") next(gi) trace.append("f SHOULD NOT BE HERE") except StopIteration as e: trace.append("f caught %r" % (e,)) def g(r): trace.append("g starting") yield trace.append("g returning %r" % (r,)) return r f(None) f(1) f((2,)) f(StopIteration(3)) self.assertEqual(trace,[ "g starting", "f resuming g", "g returning None", "f caught StopIteration()", "g starting", "f resuming g", "g returning 1", "f caught StopIteration(1)", "g starting", "f resuming g", "g returning (2,)", "f caught StopIteration((2,))", "g starting", "f resuming g", "g returning StopIteration(3)", "f caught StopIteration(StopIteration(3))", ]) def test_send_and_return_with_value(self): """ Test send and return with value """ trace = [] def f(r): gi = g(r) next(gi) try: trace.append("f sending spam to g") gi.send("spam") trace.append("f SHOULD NOT BE HERE") except StopIteration as e: trace.append("f caught %r" % (e,)) def g(r): trace.append("g starting") x = yield trace.append("g received %r" % (x,)) trace.append("g returning %r" % (r,)) return r f(None) f(1) f((2,)) f(StopIteration(3)) self.assertEqual(trace, [ "g starting", "f sending spam to g", "g received 'spam'", "g returning None", "f caught StopIteration()", "g starting", "f sending spam to g", "g received 'spam'", "g returning 1", 'f caught StopIteration(1)', 'g starting', 'f sending spam to g', "g received 'spam'", 'g returning (2,)', 'f caught StopIteration((2,))', 'g starting', 'f sending spam to g', "g received 'spam'", 'g returning StopIteration(3)', 'f caught StopIteration(StopIteration(3))' ]) def test_catching_exception_from_subgen_and_returning(self): """ Test catching an exception thrown into a subgenerator and returning a value """ def inner(): try: yield 1 except ValueError: trace.append("inner caught ValueError") return value def outer(): v = yield from inner() trace.append("inner returned %r to outer" % (v,)) yield v for value in 2, (2,), StopIteration(2): trace = [] g = outer() trace.append(next(g)) trace.append(repr(g.throw(ValueError))) self.assertEqual(trace, [ 1, "inner caught ValueError", "inner returned %r to outer" % (value,), repr(value), ]) def test_throwing_GeneratorExit_into_subgen_that_returns(self): """ Test throwing GeneratorExit into a subgenerator that catches it and returns normally. """ trace = [] def f(): try: trace.append("Enter f") yield trace.append("Exit f") except GeneratorExit: return def g(): trace.append("Enter g") yield from f() trace.append("Exit g") try: gi = g() next(gi) gi.throw(GeneratorExit) except GeneratorExit: pass else: self.fail("subgenerator failed to raise GeneratorExit") self.assertEqual(trace,[ "Enter g", "Enter f", ]) def test_throwing_GeneratorExit_into_subgenerator_that_yields(self): """ Test throwing GeneratorExit into a subgenerator that catches it and yields. """ trace = [] def f(): try: trace.append("Enter f") yield trace.append("Exit f") except GeneratorExit: yield def g(): trace.append("Enter g") yield from f() trace.append("Exit g") try: gi = g() next(gi) gi.throw(GeneratorExit) except RuntimeError as e: self.assertEqual(e.args[0], "generator ignored GeneratorExit") else: self.fail("subgenerator failed to raise GeneratorExit") self.assertEqual(trace,[ "Enter g", "Enter f", ]) def test_throwing_GeneratorExit_into_subgen_that_raises(self): """ Test throwing GeneratorExit into a subgenerator that catches it and raises a different exception. """ trace = [] def f(): try: trace.append("Enter f") yield trace.append("Exit f") except GeneratorExit: raise ValueError("Vorpal bunny encountered") def g(): trace.append("Enter g") yield from f() trace.append("Exit g") try: gi = g() next(gi) gi.throw(GeneratorExit) except ValueError as e: self.assertEqual(e.args[0], "Vorpal bunny encountered") self.assertIsInstance(e.__context__, GeneratorExit) else: self.fail("subgenerator failed to raise ValueError") self.assertEqual(trace,[ "Enter g", "Enter f", ]) def test_yield_from_empty(self): def g(): yield from () self.assertRaises(StopIteration, next, g()) def test_delegating_generators_claim_to_be_running(self): # Check with basic iteration def one(): yield 0 yield from two() yield 3 def two(): yield 1 try: yield from g1 except ValueError: pass yield 2 g1 = one() self.assertEqual(list(g1), [0, 1, 2, 3]) # Check with send g1 = one() res = [next(g1)] try: while True: res.append(g1.send(42)) except StopIteration: pass self.assertEqual(res, [0, 1, 2, 3]) # Check with throw class MyErr(Exception): pass def one(): try: yield 0 except MyErr: pass yield from two() try: yield 3 except MyErr: pass def two(): try: yield 1 except MyErr: pass try: yield from g1 except ValueError: pass try: yield 2 except MyErr: pass g1 = one() res = [next(g1)] try: while True: res.append(g1.throw(MyErr)) except StopIteration: pass # Check with close class MyIt(object): def __iter__(self): return self def __next__(self): return 42 def close(self_): self.assertTrue(g1.gi_running) self.assertRaises(ValueError, next, g1) def one(): yield from MyIt() g1 = one() next(g1) g1.close() def test_delegator_is_visible_to_debugger(self): def call_stack(): return [f[3] for f in inspect.stack()] def gen(): yield call_stack() yield call_stack() yield call_stack() def spam(g): yield from g def eggs(g): yield from g for stack in spam(gen()): self.assertTrue('spam' in stack) for stack in spam(eggs(gen())): self.assertTrue('spam' in stack and 'eggs' in stack) def test_custom_iterator_return(self): # See issue #15568 class MyIter: def __iter__(self): return self def __next__(self): raise StopIteration(42) def gen(): nonlocal ret ret = yield from MyIter() ret = None list(gen()) self.assertEqual(ret, 42) def test_close_with_cleared_frame(self): # See issue #17669. # # Create a stack of generators: outer() delegating to inner() # delegating to innermost(). The key point is that the instance of # inner is created first: this ensures that its frame appears before # the instance of outer in the GC linked list. # # At the gc.collect call: # - frame_clear is called on the inner_gen frame. # - gen_dealloc is called on the outer_gen generator (the only # reference is in the frame's locals). # - gen_close is called on the outer_gen generator. # - gen_close_iter is called to close the inner_gen generator, which # in turn calls gen_close, and gen_yf. # # Previously, gen_yf would crash since inner_gen's frame had been # cleared (and in particular f_stacktop was NULL). def innermost(): yield def inner(): outer_gen = yield yield from innermost() def outer(): inner_gen = yield yield from inner_gen with disable_gc(): inner_gen = inner() outer_gen = outer() outer_gen.send(None) outer_gen.send(inner_gen) outer_gen.send(outer_gen) del outer_gen del inner_gen gc_collect() def test_send_tuple_with_custom_generator(self): # See issue #21209. class MyGen: def __iter__(self): return self def __next__(self): return 42 def send(self, what): nonlocal v v = what return None def outer(): v = yield from MyGen() g = outer() next(g) v = None g.send((1, 2, 3, 4)) self.assertEqual(v, (1, 2, 3, 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_smtplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_smtplib.py
import asyncore import base64 import email.mime.text from email.message import EmailMessage from email.base64mime import body_encode as encode_base64 import email.utils import hmac import socket import smtpd import smtplib import io import re import sys import time import select import errno import textwrap import threading import unittest from test import support, mock_socket from test.support import HOST, HOSTv4, HOSTv6 from unittest.mock import Mock if sys.platform == 'darwin': # select.poll returns a select.POLLHUP at the end of the tests # on darwin, so just ignore it def handle_expt(self): pass smtpd.SMTPChannel.handle_expt = handle_expt def server(evt, buf, serv): serv.listen() evt.set() try: conn, addr = serv.accept() except socket.timeout: pass else: n = 500 while buf and n > 0: r, w, e = select.select([], [conn], []) if w: sent = conn.send(buf) buf = buf[sent:] n -= 1 conn.close() finally: serv.close() evt.set() class GeneralTests(unittest.TestCase): def setUp(self): smtplib.socket = mock_socket self.port = 25 def tearDown(self): smtplib.socket = socket # This method is no longer used but is retained for backward compatibility, # so test to make sure it still works. def testQuoteData(self): teststr = "abc\n.jkl\rfoo\r\n..blue" expected = "abc\r\n..jkl\r\nfoo\r\n...blue" self.assertEqual(expected, smtplib.quotedata(teststr)) def testBasic1(self): mock_socket.reply_with(b"220 Hola mundo") # connects smtp = smtplib.SMTP(HOST, self.port) smtp.close() def testSourceAddress(self): mock_socket.reply_with(b"220 Hola mundo") # connects smtp = smtplib.SMTP(HOST, self.port, source_address=('127.0.0.1',19876)) self.assertEqual(smtp.source_address, ('127.0.0.1', 19876)) smtp.close() def testBasic2(self): mock_socket.reply_with(b"220 Hola mundo") # connects, include port in host name smtp = smtplib.SMTP("%s:%s" % (HOST, self.port)) smtp.close() def testLocalHostName(self): mock_socket.reply_with(b"220 Hola mundo") # check that supplied local_hostname is used smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost") self.assertEqual(smtp.local_hostname, "testhost") smtp.close() def testTimeoutDefault(self): mock_socket.reply_with(b"220 Hola mundo") self.assertIsNone(mock_socket.getdefaulttimeout()) mock_socket.setdefaulttimeout(30) self.assertEqual(mock_socket.getdefaulttimeout(), 30) try: smtp = smtplib.SMTP(HOST, self.port) finally: mock_socket.setdefaulttimeout(None) self.assertEqual(smtp.sock.gettimeout(), 30) smtp.close() def testTimeoutNone(self): mock_socket.reply_with(b"220 Hola mundo") self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: smtp = smtplib.SMTP(HOST, self.port, timeout=None) finally: socket.setdefaulttimeout(None) self.assertIsNone(smtp.sock.gettimeout()) smtp.close() def testTimeoutValue(self): mock_socket.reply_with(b"220 Hola mundo") smtp = smtplib.SMTP(HOST, self.port, timeout=30) self.assertEqual(smtp.sock.gettimeout(), 30) smtp.close() def test_debuglevel(self): mock_socket.reply_with(b"220 Hello world") smtp = smtplib.SMTP() smtp.set_debuglevel(1) with support.captured_stderr() as stderr: smtp.connect(HOST, self.port) smtp.close() expected = re.compile(r"^connect:", re.MULTILINE) self.assertRegex(stderr.getvalue(), expected) def test_debuglevel_2(self): mock_socket.reply_with(b"220 Hello world") smtp = smtplib.SMTP() smtp.set_debuglevel(2) with support.captured_stderr() as stderr: smtp.connect(HOST, self.port) smtp.close() expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ", re.MULTILINE) self.assertRegex(stderr.getvalue(), expected) # Test server thread using the specified SMTP server class def debugging_server(serv, serv_evt, client_evt): serv_evt.set() try: if hasattr(select, 'poll'): poll_fun = asyncore.poll2 else: poll_fun = asyncore.poll n = 1000 while asyncore.socket_map and n > 0: poll_fun(0.01, asyncore.socket_map) # when the client conversation is finished, it will # set client_evt, and it's then ok to kill the server if client_evt.is_set(): serv.close() break n -= 1 except socket.timeout: pass finally: if not client_evt.is_set(): # allow some time for the client to read the result time.sleep(0.5) serv.close() asyncore.close_all() serv_evt.set() MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n' MSG_END = '------------ END MESSAGE ------------\n' # NOTE: Some SMTP objects in the tests below are created with a non-default # local_hostname argument to the constructor, since (on some systems) the FQDN # lookup caused by the default local_hostname sometimes takes so long that the # test server times out, causing the test to fail. # Test behavior of smtpd.DebuggingServer class DebuggingServerTests(unittest.TestCase): maxDiff = None def setUp(self): self.real_getfqdn = socket.getfqdn socket.getfqdn = mock_socket.getfqdn # temporarily replace sys.stdout to capture DebuggingServer output self.old_stdout = sys.stdout self.output = io.StringIO() sys.stdout = self.output self.serv_evt = threading.Event() self.client_evt = threading.Event() # Capture SMTPChannel debug output self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM smtpd.DEBUGSTREAM = io.StringIO() # Pick a random unused port by passing 0 for the port number self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1), decode_data=True) # Keep a note of what server host and port were assigned self.host, self.port = self.serv.socket.getsockname()[:2] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() # wait until server thread has assigned a port number self.serv_evt.wait() self.serv_evt.clear() def tearDown(self): socket.getfqdn = self.real_getfqdn # indicate that the client is finished self.client_evt.set() # wait for the server thread to terminate self.serv_evt.wait() self.thread.join() # restore sys.stdout sys.stdout = self.old_stdout # restore DEBUGSTREAM smtpd.DEBUGSTREAM.close() smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM def get_output_without_xpeer(self): test_output = self.output.getvalue() return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2', test_output, flags=re.MULTILINE|re.DOTALL) def testBasic(self): # connect smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.quit() def testSourceAddress(self): # connect src_port = support.find_unused_port() try: smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost', timeout=3, source_address=(self.host, src_port)) self.assertEqual(smtp.source_address, (self.host, src_port)) self.assertEqual(smtp.local_hostname, 'localhost') smtp.quit() except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to source port %d" % src_port) raise def testNOOP(self): smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'OK') self.assertEqual(smtp.noop(), expected) smtp.quit() def testRSET(self): smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'OK') self.assertEqual(smtp.rset(), expected) smtp.quit() def testELHO(self): # EHLO isn't implemented in DebuggingServer smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (250, b'\nSIZE 33554432\nHELP') self.assertEqual(smtp.ehlo(), expected) smtp.quit() def testEXPNNotImplemented(self): # EXPN isn't implemented in DebuggingServer smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (502, b'EXPN not implemented') smtp.putcmd('EXPN') self.assertEqual(smtp.getreply(), expected) smtp.quit() def testVRFY(self): smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) expected = (252, b'Cannot VRFY user, but will accept message ' + \ b'and attempt delivery') self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected) self.assertEqual(smtp.verify('nobody@nowhere.com'), expected) smtp.quit() def testSecondHELO(self): # check that a second HELO returns a message that it's a duplicate # (this behavior is specific to smtpd.SMTPChannel) smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.helo() expected = (503, b'Duplicate HELO/EHLO') self.assertEqual(smtp.helo(), expected) smtp.quit() def testHELP(self): smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \ b'RCPT DATA RSET NOOP QUIT VRFY') smtp.quit() def testSend(self): # connect and send mail m = 'A test message' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('John', 'Sally', m) # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor # in asyncore. This sleep might help, but should really be fixed # properly by using an Event variable. time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END) self.assertEqual(self.output.getvalue(), mexpect) def testSendBinary(self): m = b'A test message' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('John', 'Sally', m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END) self.assertEqual(self.output.getvalue(), mexpect) def testSendNeedingDotQuote(self): # Issue 12283 m = '.A test\n.mes.sage.' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('John', 'Sally', m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END) self.assertEqual(self.output.getvalue(), mexpect) def testSendNullSender(self): m = 'A test message' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.sendmail('<>', 'Sally', m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END) self.assertEqual(self.output.getvalue(), mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: <>$", re.MULTILINE) self.assertRegex(debugout, sender) def testSendMessage(self): m = email.mime.text.MIMEText('A test message') smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m, from_addr='John', to_addrs='Sally') # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() # Remove the X-Peer header that DebuggingServer adds as figuring out # exactly what IP address format is put there is not easy (and # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is # not always the same as socket.gethostbyname(HOST). :( test_output = self.get_output_without_xpeer() del m['X-Peer'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) def testSendMessageWithAddresses(self): m = email.mime.text.MIMEText('A test message') m['From'] = 'foo@bar.com' m['To'] = 'John' m['CC'] = 'Sally, Fred' m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() # make sure the Bcc header is still in the message. self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" ' '<warped@silly.walks.com>') self.client_evt.set() self.serv_evt.wait() self.output.flush() # Remove the X-Peer header that DebuggingServer adds. test_output = self.get_output_without_xpeer() del m['X-Peer'] # The Bcc header should not be transmitted. del m['Bcc'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: foo@bar.com$", re.MULTILINE) self.assertRegex(debugout, sender) for addr in ('John', 'Sally', 'Fred', 'root@localhost', 'warped@silly.walks.com'): to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE) self.assertRegex(debugout, to_addr) def testSendMessageWithSomeAddresses(self): # Make sure nothing breaks if not all of the three 'to' headers exist m = email.mime.text.MIMEText('A test message') m['From'] = 'foo@bar.com' m['To'] = 'John, Dinsdale' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() # Remove the X-Peer header that DebuggingServer adds. test_output = self.get_output_without_xpeer() del m['X-Peer'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: foo@bar.com$", re.MULTILINE) self.assertRegex(debugout, sender) for addr in ('John', 'Dinsdale'): to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE) self.assertRegex(debugout, to_addr) def testSendMessageWithSpecifiedAddresses(self): # Make sure addresses specified in call override those in message. m = email.mime.text.MIMEText('A test message') m['From'] = 'foo@bar.com' m['To'] = 'John, Dinsdale' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net') # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() # Remove the X-Peer header that DebuggingServer adds. test_output = self.get_output_without_xpeer() del m['X-Peer'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: joe@example.com$", re.MULTILINE) self.assertRegex(debugout, sender) for addr in ('John', 'Dinsdale'): to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE) self.assertNotRegex(debugout, to_addr) recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE) self.assertRegex(debugout, recip) def testSendMessageWithMultipleFrom(self): # Sender overrides To m = email.mime.text.MIMEText('A test message') m['From'] = 'Bernard, Bianca' m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com' m['To'] = 'John, Dinsdale' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() # Remove the X-Peer header that DebuggingServer adds. test_output = self.get_output_without_xpeer() del m['X-Peer'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE) self.assertRegex(debugout, sender) for addr in ('John', 'Dinsdale'): to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE) self.assertRegex(debugout, to_addr) def testSendMessageResent(self): m = email.mime.text.MIMEText('A test message') m['From'] = 'foo@bar.com' m['To'] = 'John' m['CC'] = 'Sally, Fred' m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>' m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000' m['Resent-From'] = 'holy@grail.net' m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff' m['Resent-Bcc'] = 'doe@losthope.net' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) smtp.send_message(m) # XXX (see comment in testSend) time.sleep(0.01) smtp.quit() self.client_evt.set() self.serv_evt.wait() self.output.flush() # The Resent-Bcc headers are deleted before serialization. del m['Bcc'] del m['Resent-Bcc'] # Remove the X-Peer header that DebuggingServer adds. test_output = self.get_output_without_xpeer() del m['X-Peer'] mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END) self.assertEqual(test_output, mexpect) debugout = smtpd.DEBUGSTREAM.getvalue() sender = re.compile("^sender: holy@grail.net$", re.MULTILINE) self.assertRegex(debugout, sender) for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'): to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr), re.MULTILINE) self.assertRegex(debugout, to_addr) def testSendMessageMultipleResentRaises(self): m = email.mime.text.MIMEText('A test message') m['From'] = 'foo@bar.com' m['To'] = 'John' m['CC'] = 'Sally, Fred' m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>' m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000' m['Resent-From'] = 'holy@grail.net' m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff' m['Resent-Bcc'] = 'doe@losthope.net' m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000' m['Resent-To'] = 'holy@grail.net' m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff' smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3) with self.assertRaises(ValueError): smtp.send_message(m) smtp.close() class NonConnectingTests(unittest.TestCase): def testNotConnected(self): # Test various operations on an unconnected SMTP object that # should raise exceptions (at present the attempt in SMTP.send # to reference the nonexistent 'sock' attribute of the SMTP object # causes an AttributeError) smtp = smtplib.SMTP() self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo) self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, 'test msg') def testNonnumericPort(self): # check that non-numeric port raises OSError self.assertRaises(OSError, smtplib.SMTP, "localhost", "bogus") self.assertRaises(OSError, smtplib.SMTP, "localhost:bogus") class DefaultArgumentsTests(unittest.TestCase): def setUp(self): self.msg = EmailMessage() self.msg['From'] = 'Páolo <főo@bar.com>' self.smtp = smtplib.SMTP() self.smtp.ehlo = Mock(return_value=(200, 'OK')) self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock() def testSendMessage(self): expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME') self.smtp.send_message(self.msg) self.smtp.send_message(self.msg) self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3], expected_mail_options) self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3], expected_mail_options) def testSendMessageWithMailOptions(self): mail_options = ['STARTTLS'] expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME') self.smtp.send_message(self.msg, None, None, mail_options) self.assertEqual(mail_options, ['STARTTLS']) self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3], expected_mail_options) # test response of client to a non-successful HELO message class BadHELOServerTests(unittest.TestCase): def setUp(self): smtplib.socket = mock_socket mock_socket.reply_with(b"199 no hello for you!") self.old_stdout = sys.stdout self.output = io.StringIO() sys.stdout = self.output self.port = 25 def tearDown(self): smtplib.socket = socket sys.stdout = self.old_stdout def testFailingHELO(self): self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP, HOST, self.port, 'localhost', 3) class TooLongLineTests(unittest.TestCase): respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n' def setUp(self): self.old_stdout = sys.stdout self.output = io.StringIO() sys.stdout = self.output self.evt = threading.Event() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(15) self.port = support.bind_port(self.sock) servargs = (self.evt, self.respdata, self.sock) thread = threading.Thread(target=server, args=servargs) thread.start() self.addCleanup(thread.join) self.evt.wait() self.evt.clear() def tearDown(self): self.evt.wait() sys.stdout = self.old_stdout def testLineTooLong(self): self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP, HOST, self.port, 'localhost', 3) sim_users = {'Mr.A@somewhere.com':'John A', 'Ms.B@xn--fo-fka.com':'Sally B', 'Mrs.C@somewhereesle.com':'Ruth C', } sim_auth = ('Mr.A@somewhere.com', 'somepassword') sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn' 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=') sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'], 'list-2':['Ms.B@xn--fo-fka.com',], } # Simulated SMTP channel & server class ResponseException(Exception): pass class SimSMTPChannel(smtpd.SMTPChannel): quit_response = None mail_response = None rcpt_response = None data_response = None rcpt_count = 0 rset_count = 0 disconnect = 0 AUTH = 99 # Add protocol state to enable auth testing. authenticated_user = None def __init__(self, extra_features, *args, **kw): self._extrafeatures = ''.join( [ "250-{0}\r\n".format(x) for x in extra_features ]) super(SimSMTPChannel, self).__init__(*args, **kw) # AUTH related stuff. It would be nice if support for this were in smtpd. def found_terminator(self): if self.smtp_state == self.AUTH: line = self._emptystring.join(self.received_lines) print('Data:', repr(line), file=smtpd.DEBUGSTREAM) self.received_lines = [] try: self.auth_object(line) except ResponseException as e: self.smtp_state = self.COMMAND self.push('%s %s' % (e.smtp_code, e.smtp_error)) return super().found_terminator() def smtp_AUTH(self, arg): if not self.seen_greeting: self.push('503 Error: send EHLO first') return if not self.extended_smtp or 'AUTH' not in self._extrafeatures: self.push('500 Error: command "AUTH" not recognized') return if self.authenticated_user is not None: self.push( '503 Bad sequence of commands: already authenticated') return args = arg.split() if len(args) not in [1, 2]: self.push('501 Syntax: AUTH <mechanism> [initial-response]') return auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_') try: self.auth_object = getattr(self, auth_object_name) except AttributeError: self.push('504 Command parameter not implemented: unsupported ' ' authentication mechanism {!r}'.format(auth_object_name)) return self.smtp_state = self.AUTH self.auth_object(args[1] if len(args) == 2 else None) def _authenticated(self, user, valid): if valid: self.authenticated_user = user self.push('235 Authentication Succeeded') else: self.push('535 Authentication credentials invalid') self.smtp_state = self.COMMAND def _decode_base64(self, string): return base64.decodebytes(string.encode('ascii')).decode('utf-8') def _auth_plain(self, arg=None): if arg is None: self.push('334 ') else: logpass = self._decode_base64(arg) try: *_, user, password = logpass.split('\0') except ValueError as e: self.push('535 Splitting response {!r} into user and password' ' failed: {}'.format(logpass, e)) return self._authenticated(user, password == sim_auth[1]) def _auth_login(self, arg=None): if arg is None: # base64 encoded 'Username:' self.push('334 VXNlcm5hbWU6') elif not hasattr(self, '_auth_login_user'): self._auth_login_user = self._decode_base64(arg) # base64 encoded 'Password:' self.push('334 UGFzc3dvcmQ6') else: password = self._decode_base64(arg) self._authenticated(self._auth_login_user, password == sim_auth[1]) del self._auth_login_user def _auth_cram_md5(self, arg=None): if arg is None: self.push('334 {}'.format(sim_cram_md5_challenge)) else: logpass = self._decode_base64(arg) try: user, hashed_pass = logpass.split() except ValueError as e: self.push('535 Splitting response {!r} into user and password ' 'failed: {}'.format(logpass, e)) return False valid_hashed_pass = hmac.HMAC( sim_auth[1].encode('ascii'), self._decode_base64(sim_cram_md5_challenge).encode('ascii'), 'md5').hexdigest() self._authenticated(user, hashed_pass == valid_hashed_pass) # end AUTH related stuff. def smtp_EHLO(self, arg): resp = ('250-testhost\r\n' '250-EXPN\r\n' '250-SIZE 20000000\r\n' '250-STARTTLS\r\n' '250-DELIVERBY\r\n') resp = resp + self._extrafeatures + '250 HELP' self.push(resp) self.seen_greeting = arg self.extended_smtp = True def smtp_VRFY(self, arg): # For max compatibility smtplib should be sending the raw address. if arg in sim_users: self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg))) else: self.push('550 No such user: %s' % arg) def smtp_EXPN(self, arg): list_name = arg.lower() if list_name in sim_lists: user_list = sim_lists[list_name] for n, user_email in enumerate(user_list): quoted_addr = smtplib.quoteaddr(user_email) if n < len(user_list) - 1: self.push('250-%s %s' % (sim_users[user_email], quoted_addr)) else: self.push('250 %s %s' % (sim_users[user_email], quoted_addr)) else: self.push('550 No access for you!') def smtp_QUIT(self, arg): if self.quit_response is None: super(SimSMTPChannel, self).smtp_QUIT(arg) else: self.push(self.quit_response) self.close_when_done() def smtp_MAIL(self, arg): if self.mail_response is None: super().smtp_MAIL(arg) else: self.push(self.mail_response) if self.disconnect: self.close_when_done() def smtp_RCPT(self, arg): if self.rcpt_response is None: super().smtp_RCPT(arg) return self.rcpt_count += 1 self.push(self.rcpt_response[self.rcpt_count-1]) def smtp_RSET(self, arg): self.rset_count += 1 super().smtp_RSET(arg) def smtp_DATA(self, arg): if self.data_response is None: super().smtp_DATA(arg) else: self.push(self.data_response) def handle_error(self): raise class SimSMTPServer(smtpd.SMTPServer): channel_class = SimSMTPChannel def __init__(self, *args, **kw): self._extra_features = [] self._addresses = {} smtpd.SMTPServer.__init__(self, *args, **kw) def handle_accepted(self, conn, addr): self._SMTPchannel = self.channel_class( self._extra_features, self, conn, addr, decode_data=self._decode_data) def process_message(self, peer, mailfrom, rcpttos, data): self._addresses['from'] = mailfrom self._addresses['tos'] = rcpttos def add_feature(self, feature): self._extra_features.append(feature) def handle_error(self): raise # Test various SMTP & ESMTP commands/behaviors that require a simulated server # (i.e., something with more features than DebuggingServer) class SMTPSimTests(unittest.TestCase): def setUp(self): self.real_getfqdn = socket.getfqdn socket.getfqdn = mock_socket.getfqdn self.serv_evt = threading.Event() self.client_evt = threading.Event() # Pick a random unused port by passing 0 for the port number
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/tf_inherit_check.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/tf_inherit_check.py
# Helper script for test_tempfile.py. argv[2] is the number of a file # descriptor which should _not_ be open. Check this by attempting to # write to it -- if we succeed, something is wrong. import sys import os from test.support import SuppressCrashReport with SuppressCrashReport(): verbose = (sys.argv[1] == 'v') try: fd = int(sys.argv[2]) try: os.write(fd, b"blat") except OSError: # Success -- could not write to fd. sys.exit(0) else: if verbose: sys.stderr.write("fd %d is open in child" % fd) sys.exit(1) except Exception: if verbose: raise sys.exit(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_logging.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
# Copyright 2001-2017 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Test harness for the logging module. Run all tests. Copyright (C) 2001-2017 Vinay Sajip. All Rights Reserved. """ import logging import logging.handlers import logging.config import codecs import configparser import datetime import pathlib import pickle import io import gc import json import os import queue import random import re import signal import socket import struct import sys import tempfile from test.support.script_helper import assert_python_ok, assert_python_failure from test import support import textwrap import threading import time import unittest import warnings import weakref import asyncore from http.server import HTTPServer, BaseHTTPRequestHandler import smtpd from urllib.parse import urlparse, parse_qs from socketserver import (ThreadingUDPServer, DatagramRequestHandler, ThreadingTCPServer, StreamRequestHandler) try: import win32evtlog, win32evtlogutil, pywintypes except ImportError: win32evtlog = win32evtlogutil = pywintypes = None try: import zlib except ImportError: pass class BaseTest(unittest.TestCase): """Base class for logging tests.""" log_format = "%(name)s -> %(levelname)s: %(message)s" expected_log_pat = r"^([\w.]+) -> (\w+): (\d+)$" message_num = 0 def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" self._threading_key = support.threading_setup() logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers()) def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelToName.clear() logging._levelToName.update(self.saved_level_to_name) logging._nameToLevel.clear() logging._nameToLevel.update(self.saved_name_to_level) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list manager = logging.getLogger().manager manager.disable = 0 loggerDict = manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) logger_states = self.logger_states for name in self.logger_states: if logger_states[name] is not None: self.saved_loggers[name].disabled = logger_states[name] finally: logging._releaseLock() self.doCleanups() support.threading_cleanup(*self._threading_key) def assert_log_lines(self, expected_values, stream=None, pat=None): """Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.""" stream = stream or self.stream pat = re.compile(pat or self.expected_log_pat) actual_lines = stream.getvalue().splitlines() self.assertEqual(len(actual_lines), len(expected_values)) for actual, expected in zip(actual_lines, expected_values): match = pat.search(actual) if not match: self.fail("Log line does not match expected pattern:\n" + actual) self.assertEqual(tuple(match.groups()), expected) s = stream.read() if s: self.fail("Remaining output at end of log stream:\n" + s) def next_message(self): """Generate a message consisting solely of an auto-incrementing integer.""" self.message_num += 1 return "%d" % self.message_num class BuiltinLevelsTest(BaseTest): """Test builtin levels and their inheritance.""" def test_flat(self): # Logging levels in a flat logger namespace. m = self.next_message ERR = logging.getLogger("ERR") ERR.setLevel(logging.ERROR) INF = logging.LoggerAdapter(logging.getLogger("INF"), {}) INF.setLevel(logging.INFO) DEB = logging.getLogger("DEB") DEB.setLevel(logging.DEBUG) # These should log. ERR.log(logging.CRITICAL, m()) ERR.error(m()) INF.log(logging.CRITICAL, m()) INF.error(m()) INF.warning(m()) INF.info(m()) DEB.log(logging.CRITICAL, m()) DEB.error(m()) DEB.warning(m()) DEB.info(m()) DEB.debug(m()) # These should not log. ERR.warning(m()) ERR.info(m()) ERR.debug(m()) INF.debug(m()) self.assert_log_lines([ ('ERR', 'CRITICAL', '1'), ('ERR', 'ERROR', '2'), ('INF', 'CRITICAL', '3'), ('INF', 'ERROR', '4'), ('INF', 'WARNING', '5'), ('INF', 'INFO', '6'), ('DEB', 'CRITICAL', '7'), ('DEB', 'ERROR', '8'), ('DEB', 'WARNING', '9'), ('DEB', 'INFO', '10'), ('DEB', 'DEBUG', '11'), ]) def test_nested_explicit(self): # Logging levels in a nested namespace, all explicitly set. m = self.next_message INF = logging.getLogger("INF") INF.setLevel(logging.INFO) INF_ERR = logging.getLogger("INF.ERR") INF_ERR.setLevel(logging.ERROR) # These should log. INF_ERR.log(logging.CRITICAL, m()) INF_ERR.error(m()) # These should not log. INF_ERR.warning(m()) INF_ERR.info(m()) INF_ERR.debug(m()) self.assert_log_lines([ ('INF.ERR', 'CRITICAL', '1'), ('INF.ERR', 'ERROR', '2'), ]) def test_nested_inherited(self): # Logging levels in a nested namespace, inherited from parent loggers. m = self.next_message INF = logging.getLogger("INF") INF.setLevel(logging.INFO) INF_ERR = logging.getLogger("INF.ERR") INF_ERR.setLevel(logging.ERROR) INF_UNDEF = logging.getLogger("INF.UNDEF") INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF") UNDEF = logging.getLogger("UNDEF") # These should log. INF_UNDEF.log(logging.CRITICAL, m()) INF_UNDEF.error(m()) INF_UNDEF.warning(m()) INF_UNDEF.info(m()) INF_ERR_UNDEF.log(logging.CRITICAL, m()) INF_ERR_UNDEF.error(m()) # These should not log. INF_UNDEF.debug(m()) INF_ERR_UNDEF.warning(m()) INF_ERR_UNDEF.info(m()) INF_ERR_UNDEF.debug(m()) self.assert_log_lines([ ('INF.UNDEF', 'CRITICAL', '1'), ('INF.UNDEF', 'ERROR', '2'), ('INF.UNDEF', 'WARNING', '3'), ('INF.UNDEF', 'INFO', '4'), ('INF.ERR.UNDEF', 'CRITICAL', '5'), ('INF.ERR.UNDEF', 'ERROR', '6'), ]) def test_nested_with_virtual_parent(self): # Logging levels when some parent does not exist yet. m = self.next_message INF = logging.getLogger("INF") GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF") CHILD = logging.getLogger("INF.BADPARENT") INF.setLevel(logging.INFO) # These should log. GRANDCHILD.log(logging.FATAL, m()) GRANDCHILD.info(m()) CHILD.log(logging.FATAL, m()) CHILD.info(m()) # These should not log. GRANDCHILD.debug(m()) CHILD.debug(m()) self.assert_log_lines([ ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'), ('INF.BADPARENT.UNDEF', 'INFO', '2'), ('INF.BADPARENT', 'CRITICAL', '3'), ('INF.BADPARENT', 'INFO', '4'), ]) def test_regression_22386(self): """See issue #22386 for more information.""" self.assertEqual(logging.getLevelName('INFO'), logging.INFO) self.assertEqual(logging.getLevelName(logging.INFO), 'INFO') def test_regression_29220(self): """See issue #29220 for more information.""" logging.addLevelName(logging.INFO, '') self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') self.assertEqual(logging.getLevelName(logging.INFO), '') def test_issue27935(self): fatal = logging.getLevelName('FATAL') self.assertEqual(fatal, logging.FATAL) def test_regression_29220(self): """See issue #29220 for more information.""" logging.addLevelName(logging.INFO, '') self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') self.assertEqual(logging.getLevelName(logging.INFO), '') self.assertEqual(logging.getLevelName(logging.NOTSET), 'NOTSET') self.assertEqual(logging.getLevelName('NOTSET'), logging.NOTSET) class BasicFilterTest(BaseTest): """Test the bundled Filter class.""" def test_filter(self): # Only messages satisfying the specified criteria pass through the # filter. filter_ = logging.Filter("spam.eggs") handler = self.root_logger.handlers[0] try: handler.addFilter(filter_) spam = logging.getLogger("spam") spam_eggs = logging.getLogger("spam.eggs") spam_eggs_fish = logging.getLogger("spam.eggs.fish") spam_bakedbeans = logging.getLogger("spam.bakedbeans") spam.info(self.next_message()) spam_eggs.info(self.next_message()) # Good. spam_eggs_fish.info(self.next_message()) # Good. spam_bakedbeans.info(self.next_message()) self.assert_log_lines([ ('spam.eggs', 'INFO', '2'), ('spam.eggs.fish', 'INFO', '3'), ]) finally: handler.removeFilter(filter_) def test_callable_filter(self): # Only messages satisfying the specified criteria pass through the # filter. def filterfunc(record): parts = record.name.split('.') prefix = '.'.join(parts[:2]) return prefix == 'spam.eggs' handler = self.root_logger.handlers[0] try: handler.addFilter(filterfunc) spam = logging.getLogger("spam") spam_eggs = logging.getLogger("spam.eggs") spam_eggs_fish = logging.getLogger("spam.eggs.fish") spam_bakedbeans = logging.getLogger("spam.bakedbeans") spam.info(self.next_message()) spam_eggs.info(self.next_message()) # Good. spam_eggs_fish.info(self.next_message()) # Good. spam_bakedbeans.info(self.next_message()) self.assert_log_lines([ ('spam.eggs', 'INFO', '2'), ('spam.eggs.fish', 'INFO', '3'), ]) finally: handler.removeFilter(filterfunc) def test_empty_filter(self): f = logging.Filter() r = logging.makeLogRecord({'name': 'spam.eggs'}) self.assertTrue(f.filter(r)) # # First, we define our levels. There can be as many as you want - the only # limitations are that they should be integers, the lowest should be > 0 and # larger values mean less information being logged. If you need specific # level values which do not fit into these limitations, you can use a # mapping dictionary to convert between your application levels and the # logging system. # SILENT = 120 TACITURN = 119 TERSE = 118 EFFUSIVE = 117 SOCIABLE = 116 VERBOSE = 115 TALKATIVE = 114 GARRULOUS = 113 CHATTERBOX = 112 BORING = 111 LEVEL_RANGE = range(BORING, SILENT + 1) # # Next, we define names for our levels. You don't need to do this - in which # case the system will use "Level n" to denote the text for the level. # my_logging_levels = { SILENT : 'Silent', TACITURN : 'Taciturn', TERSE : 'Terse', EFFUSIVE : 'Effusive', SOCIABLE : 'Sociable', VERBOSE : 'Verbose', TALKATIVE : 'Talkative', GARRULOUS : 'Garrulous', CHATTERBOX : 'Chatterbox', BORING : 'Boring', } class GarrulousFilter(logging.Filter): """A filter which blocks garrulous messages.""" def filter(self, record): return record.levelno != GARRULOUS class VerySpecificFilter(logging.Filter): """A filter which blocks sociable and taciturn messages.""" def filter(self, record): return record.levelno not in [SOCIABLE, TACITURN] class CustomLevelsAndFiltersTest(BaseTest): """Test various filtering possibilities with custom logging levels.""" # Skip the logger name group. expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" def setUp(self): BaseTest.setUp(self) for k, v in my_logging_levels.items(): logging.addLevelName(k, v) def log_at_all_levels(self, logger): for lvl in LEVEL_RANGE: logger.log(lvl, self.next_message()) def test_logger_filter(self): # Filter at logger level. self.root_logger.setLevel(VERBOSE) # Levels >= 'Verbose' are good. self.log_at_all_levels(self.root_logger) self.assert_log_lines([ ('Verbose', '5'), ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ]) def test_handler_filter(self): # Filter at handler level. self.root_logger.handlers[0].setLevel(SOCIABLE) try: # Levels >= 'Sociable' are good. self.log_at_all_levels(self.root_logger) self.assert_log_lines([ ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ]) finally: self.root_logger.handlers[0].setLevel(logging.NOTSET) def test_specific_filters(self): # Set a specific filter object on the handler, and then add another # filter object on the logger itself. handler = self.root_logger.handlers[0] specific_filter = None garr = GarrulousFilter() handler.addFilter(garr) try: self.log_at_all_levels(self.root_logger) first_lines = [ # Notice how 'Garrulous' is missing ('Boring', '1'), ('Chatterbox', '2'), ('Talkative', '4'), ('Verbose', '5'), ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ] self.assert_log_lines(first_lines) specific_filter = VerySpecificFilter() self.root_logger.addFilter(specific_filter) self.log_at_all_levels(self.root_logger) self.assert_log_lines(first_lines + [ # Not only 'Garrulous' is still missing, but also 'Sociable' # and 'Taciturn' ('Boring', '11'), ('Chatterbox', '12'), ('Talkative', '14'), ('Verbose', '15'), ('Effusive', '17'), ('Terse', '18'), ('Silent', '20'), ]) finally: if specific_filter: self.root_logger.removeFilter(specific_filter) handler.removeFilter(garr) class HandlerTest(BaseTest): def test_name(self): h = logging.Handler() h.name = 'generic' self.assertEqual(h.name, 'generic') h.name = 'anothergeneric' self.assertEqual(h.name, 'anothergeneric') self.assertRaises(NotImplementedError, h.emit, None) def test_builtin_handlers(self): # We can't actually *use* too many handlers in the tests, # but we can try instantiating them with various options if sys.platform in ('linux', 'darwin'): for existing in (True, False): fd, fn = tempfile.mkstemp() os.close(fd) if not existing: os.unlink(fn) h = logging.handlers.WatchedFileHandler(fn, delay=True) if existing: dev, ino = h.dev, h.ino self.assertEqual(dev, -1) self.assertEqual(ino, -1) r = logging.makeLogRecord({'msg': 'Test'}) h.handle(r) # Now remove the file. os.unlink(fn) self.assertFalse(os.path.exists(fn)) # The next call should recreate the file. h.handle(r) self.assertTrue(os.path.exists(fn)) else: self.assertEqual(h.dev, -1) self.assertEqual(h.ino, -1) h.close() if existing: os.unlink(fn) if sys.platform == 'darwin': sockname = '/var/run/syslog' else: sockname = '/dev/log' try: h = logging.handlers.SysLogHandler(sockname) self.assertEqual(h.facility, h.LOG_USER) self.assertTrue(h.unixsocket) h.close() except OSError: # syslogd might not be available pass for method in ('GET', 'POST', 'PUT'): if method == 'PUT': self.assertRaises(ValueError, logging.handlers.HTTPHandler, 'localhost', '/log', method) else: h = logging.handlers.HTTPHandler('localhost', '/log', method) h.close() h = logging.handlers.BufferingHandler(0) r = logging.makeLogRecord({}) self.assertTrue(h.shouldFlush(r)) h.close() h = logging.handlers.BufferingHandler(1) self.assertFalse(h.shouldFlush(r)) h.close() def test_path_objects(self): """ Test that Path objects are accepted as filename arguments to handlers. See Issue #27493. """ fd, fn = tempfile.mkstemp() os.close(fd) os.unlink(fn) pfn = pathlib.Path(fn) cases = ( (logging.FileHandler, (pfn, 'w')), (logging.handlers.RotatingFileHandler, (pfn, 'a')), (logging.handlers.TimedRotatingFileHandler, (pfn, 'h')), ) if sys.platform in ('linux', 'darwin'): cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),) for cls, args in cases: h = cls(*args) self.assertTrue(os.path.exists(fn)) h.close() os.unlink(fn) @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Windows.') def test_race(self): # Issue #14632 refers. def remove_loop(fname, tries): for _ in range(tries): try: os.unlink(fname) self.deletion_time = time.time() except OSError: pass time.sleep(0.004 * random.randint(0, 4)) del_count = 500 log_count = 500 self.handle_time = None self.deletion_time = None for delay in (False, True): fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') os.close(fd) remover = threading.Thread(target=remove_loop, args=(fn, del_count)) remover.daemon = True remover.start() h = logging.handlers.WatchedFileHandler(fn, delay=delay) f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s') h.setFormatter(f) try: for _ in range(log_count): time.sleep(0.005) r = logging.makeLogRecord({'msg': 'testing' }) try: self.handle_time = time.time() h.handle(r) except Exception: print('Deleted at %s, ' 'opened at %s' % (self.deletion_time, self.handle_time)) raise finally: remover.join() h.close() if os.path.exists(fn): os.unlink(fn) # The implementation relies on os.register_at_fork existing, but we test # based on os.fork existing because that is what users and this test use. # This helps ensure that when fork exists (the important concept) that the # register_at_fork mechanism is also present and used. @unittest.skipIf(not hasattr(os, 'fork'), 'Test requires os.fork().') def test_post_fork_child_no_deadlock(self): """Ensure child logging locks are not held; bpo-6721 & bpo-36533.""" class _OurHandler(logging.Handler): def __init__(self): super().__init__() self.sub_handler = logging.StreamHandler( stream=open('/dev/null', 'wt')) def emit(self, record): self.sub_handler.acquire() try: self.sub_handler.emit(record) finally: self.sub_handler.release() self.assertEqual(len(logging._handlers), 0) refed_h = _OurHandler() self.addCleanup(refed_h.sub_handler.stream.close) refed_h.name = 'because we need at least one for this test' self.assertGreater(len(logging._handlers), 0) self.assertGreater(len(logging._at_fork_reinit_lock_weakset), 1) test_logger = logging.getLogger('test_post_fork_child_no_deadlock') test_logger.addHandler(refed_h) test_logger.setLevel(logging.DEBUG) locks_held__ready_to_fork = threading.Event() fork_happened__release_locks_and_end_thread = threading.Event() def lock_holder_thread_fn(): logging._acquireLock() try: refed_h.acquire() try: # Tell the main thread to do the fork. locks_held__ready_to_fork.set() # If the deadlock bug exists, the fork will happen # without dealing with the locks we hold, deadlocking # the child. # Wait for a successful fork or an unreasonable amount of # time before releasing our locks. To avoid a timing based # test we'd need communication from os.fork() as to when it # has actually happened. Given this is a regression test # for a fixed issue, potentially less reliably detecting # regression via timing is acceptable for simplicity. # The test will always take at least this long. :( fork_happened__release_locks_and_end_thread.wait(0.5) finally: refed_h.release() finally: logging._releaseLock() lock_holder_thread = threading.Thread( target=lock_holder_thread_fn, name='test_post_fork_child_no_deadlock lock holder') lock_holder_thread.start() locks_held__ready_to_fork.wait() pid = os.fork() if pid == 0: # Child. try: test_logger.info(r'Child process did not deadlock. \o/') finally: os._exit(0) else: # Parent. test_logger.info(r'Parent process returned from fork. \o/') fork_happened__release_locks_and_end_thread.set() lock_holder_thread.join() start_time = time.monotonic() while True: test_logger.debug('Waiting for child process.') waited_pid, status = os.waitpid(pid, os.WNOHANG) if waited_pid == pid: break # child process exited. if time.monotonic() - start_time > 7: break # so long? implies child deadlock. time.sleep(0.05) test_logger.debug('Done waiting.') if waited_pid != pid: os.kill(pid, signal.SIGKILL) waited_pid, status = os.waitpid(pid, 0) self.fail("child process deadlocked.") self.assertEqual(status, 0, msg="child process error") class BadStream(object): def write(self, data): raise RuntimeError('deliberate mistake') class TestStreamHandler(logging.StreamHandler): def handleError(self, record): self.error_record = record class StreamWithIntName(object): level = logging.NOTSET name = 2 class StreamHandlerTest(BaseTest): def test_error_handling(self): h = TestStreamHandler(BadStream()) r = logging.makeLogRecord({}) old_raise = logging.raiseExceptions try: h.handle(r) self.assertIs(h.error_record, r) h = logging.StreamHandler(BadStream()) with support.captured_stderr() as stderr: h.handle(r) msg = '\nRuntimeError: deliberate mistake\n' self.assertIn(msg, stderr.getvalue()) logging.raiseExceptions = False with support.captured_stderr() as stderr: h.handle(r) self.assertEqual('', stderr.getvalue()) finally: logging.raiseExceptions = old_raise def test_stream_setting(self): """ Test setting the handler's stream """ h = logging.StreamHandler() stream = io.StringIO() old = h.setStream(stream) self.assertIs(old, sys.stderr) actual = h.setStream(old) self.assertIs(actual, stream) # test that setting to existing value returns None actual = h.setStream(old) self.assertIsNone(actual) def test_can_represent_stream_with_int_name(self): h = logging.StreamHandler(StreamWithIntName()) self.assertEqual(repr(h), '<StreamHandler 2 (NOTSET)>') # -- The following section could be moved into a server_helper.py module # -- if it proves to be of wider utility than just test_logging class TestSMTPServer(smtpd.SMTPServer): """ This class implements a test SMTP server. :param addr: A (host, port) tuple which the server listens on. You can specify a port value of zero: the server's *port* attribute will hold the actual port number used, which can be used in client connections. :param handler: A callable which will be called to process incoming messages. The handler will be passed the client address tuple, who the message is from, a list of recipients and the message data. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`. :param sockmap: A dictionary which will be used to hold :class:`asyncore.dispatcher` instances used by :func:`asyncore.loop`. This avoids changing the :mod:`asyncore` module's global state. """ def __init__(self, addr, handler, poll_interval, sockmap): smtpd.SMTPServer.__init__(self, addr, None, map=sockmap, decode_data=True) self.port = self.socket.getsockname()[1] self._handler = handler self._thread = None self.poll_interval = poll_interval def process_message(self, peer, mailfrom, rcpttos, data): """ Delegates to the handler passed in to the server's constructor. Typically, this will be a test case method. :param peer: The client (host, port) tuple. :param mailfrom: The address of the sender. :param rcpttos: The addresses of the recipients. :param data: The message. """ self._handler(peer, mailfrom, rcpttos, data) def start(self): """ Start the server running on a separate daemon thread. """ self._thread = t = threading.Thread(target=self.serve_forever, args=(self.poll_interval,)) t.setDaemon(True) t.start() def serve_forever(self, poll_interval): """ Run the :mod:`asyncore` loop until normal termination conditions arise. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`. """ asyncore.loop(poll_interval, map=self._map) def stop(self, timeout=None): """ Stop the thread by closing the server instance. Wait for the server thread to terminate. :param timeout: How long to wait for the server thread to terminate. """ self.close() support.join_thread(self._thread, timeout) self._thread = None asyncore.close_all(map=self._map, ignore_all=True) class ControlMixin(object): """ This mixin is used to start a server on a separate thread, and shut it down programmatically. Request handling is simplified - instead of needing to derive a suitable RequestHandler subclass, you just provide a callable which will be passed each received request to be processed. :param handler: A handler callable which will be called with a
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___future__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test___future__.py
import unittest import __future__ GOOD_SERIALS = ("alpha", "beta", "candidate", "final") features = __future__.all_feature_names class FutureTest(unittest.TestCase): def test_names(self): # Verify that all_feature_names appears correct. given_feature_names = features[:] for name in dir(__future__): obj = getattr(__future__, name, None) if obj is not None and isinstance(obj, __future__._Feature): self.assertTrue( name in given_feature_names, "%r should have been in all_feature_names" % name ) given_feature_names.remove(name) self.assertEqual(len(given_feature_names), 0, "all_feature_names has too much: %r" % given_feature_names) def test_attributes(self): for feature in features: value = getattr(__future__, feature) optional = value.getOptionalRelease() mandatory = value.getMandatoryRelease() a = self.assertTrue e = self.assertEqual def check(t, name): a(isinstance(t, tuple), "%s isn't tuple" % name) e(len(t), 5, "%s isn't 5-tuple" % name) (major, minor, micro, level, serial) = t a(isinstance(major, int), "%s major isn't int" % name) a(isinstance(minor, int), "%s minor isn't int" % name) a(isinstance(micro, int), "%s micro isn't int" % name) a(isinstance(level, str), "%s level isn't string" % name) a(level in GOOD_SERIALS, "%s level string has unknown value" % name) a(isinstance(serial, int), "%s serial isn't int" % name) check(optional, "optional") if mandatory is not None: check(mandatory, "mandatory") a(optional < mandatory, "optional not less than mandatory, and mandatory not None") a(hasattr(value, "compiler_flag"), "feature is missing a .compiler_flag attr") # Make sure the compile accepts the flag. compile("", "<test>", "exec", value.compiler_flag) a(isinstance(getattr(value, "compiler_flag"), int), ".compiler_flag isn't int") 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_ossaudiodev.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ossaudiodev.py
from test import support support.requires('audio') from test.support import findfile ossaudiodev = support.import_module('ossaudiodev') import errno import sys import sunau import time import audioop import unittest # Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a # fairly recent addition to OSS. try: from ossaudiodev import AFMT_S16_NE except ImportError: if sys.byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE def read_sound_file(path): with open(path, 'rb') as fp: au = sunau.open(fp) rate = au.getframerate() nchannels = au.getnchannels() encoding = au._encoding fp.seek(0) data = fp.read() if encoding != sunau.AUDIO_FILE_ENCODING_MULAW_8: raise RuntimeError("Expect .au file with 8-bit mu-law samples") # Convert the data to 16-bit signed. data = audioop.ulaw2lin(data, 2) return (data, rate, 16, nchannels) class OSSAudioDevTests(unittest.TestCase): def play_sound_file(self, data, rate, ssize, nchannels): try: dsp = ossaudiodev.open('w') except OSError as msg: if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise unittest.SkipTest(msg) raise # at least check that these methods can be invoked dsp.bufsize() dsp.obufcount() dsp.obuffree() dsp.getptr() dsp.fileno() # Make sure the read-only attributes work. self.assertFalse(dsp.closed) self.assertEqual(dsp.name, "/dev/dsp") self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode) # And make sure they're really read-only. for attr in ('closed', 'name', 'mode'): try: setattr(dsp, attr, 42) except (TypeError, AttributeError): pass else: self.fail("dsp.%s not read-only" % attr) # Compute expected running time of sound sample (in seconds). expected_time = float(len(data)) / (ssize/8) / nchannels / rate # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.monotonic() dsp.write(data) dsp.close() t2 = time.monotonic() elapsed_time = t2 - t1 percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100 self.assertTrue(percent_diff <= 10.0, "elapsed time (%s) > 10%% off of expected time (%s)" % (elapsed_time, expected_time)) def set_parameters(self, dsp): # Two configurations for testing: # config1 (8-bit, mono, 8 kHz) should work on even the most # ancient and crufty sound card, but maybe not on special- # purpose high-end hardware # config2 (16-bit, stereo, 44.1kHz) should work on all but the # most ancient and crufty hardware config1 = (ossaudiodev.AFMT_U8, 1, 8000) config2 = (AFMT_S16_NE, 2, 44100) for config in [config1, config2]: (fmt, channels, rate) = config if (dsp.setfmt(fmt) == fmt and dsp.channels(channels) == channels and dsp.speed(rate) == rate): break else: raise RuntimeError("unable to set audio sampling parameters: " "you must have really weird audio hardware") # setparameters() should be able to set this configuration in # either strict or non-strict mode. result = dsp.setparameters(fmt, channels, rate, False) self.assertEqual(result, (fmt, channels, rate), "setparameters%r: returned %r" % (config, result)) result = dsp.setparameters(fmt, channels, rate, True) self.assertEqual(result, (fmt, channels, rate), "setparameters%r: returned %r" % (config, result)) def set_bad_parameters(self, dsp): # Now try some configurations that are presumably bogus: eg. 300 # channels currently exceeds even Hollywood's ambitions, and # negative sampling rate is utter nonsense. setparameters() should # accept these in non-strict mode, returning something other than # was requested, but should barf in strict mode. fmt = AFMT_S16_NE rate = 44100 channels = 2 for config in [(fmt, 300, rate), # ridiculous nchannels (fmt, -5, rate), # impossible nchannels (fmt, channels, -50), # impossible rate ]: (fmt, channels, rate) = config result = dsp.setparameters(fmt, channels, rate, False) self.assertNotEqual(result, config, "unexpectedly got requested configuration") try: result = dsp.setparameters(fmt, channels, rate, True) except ossaudiodev.OSSAudioError as err: pass else: self.fail("expected OSSAudioError") def test_playback(self): sound_info = read_sound_file(findfile('audiotest.au')) self.play_sound_file(*sound_info) def test_set_parameters(self): dsp = ossaudiodev.open("w") try: self.set_parameters(dsp) # Disabled because it fails under Linux 2.6 with ALSA's OSS # emulation layer. #self.set_bad_parameters(dsp) finally: dsp.close() self.assertTrue(dsp.closed) def test_mixer_methods(self): # Issue #8139: ossaudiodev didn't initialize its types properly, # therefore some methods were unavailable. with ossaudiodev.openmixer() as mixer: self.assertGreaterEqual(mixer.fileno(), 0) def test_with(self): with ossaudiodev.open('w') as dsp: pass self.assertTrue(dsp.closed) def test_on_closed(self): dsp = ossaudiodev.open('w') dsp.close() self.assertRaises(ValueError, dsp.fileno) self.assertRaises(ValueError, dsp.read, 1) self.assertRaises(ValueError, dsp.write, b'x') self.assertRaises(ValueError, dsp.writeall, b'x') self.assertRaises(ValueError, dsp.bufsize) self.assertRaises(ValueError, dsp.obufcount) self.assertRaises(ValueError, dsp.obufcount) self.assertRaises(ValueError, dsp.obuffree) self.assertRaises(ValueError, dsp.getptr) mixer = ossaudiodev.openmixer() mixer.close() self.assertRaises(ValueError, mixer.fileno) def test_main(): try: dsp = ossaudiodev.open('w') except (ossaudiodev.error, OSError) as msg: if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise unittest.SkipTest(msg) raise dsp.close() support.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_xmlrpc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xmlrpc.py
import base64 import datetime import decimal import sys import time import unittest from unittest import mock import xmlrpc.client as xmlrpclib import xmlrpc.server import http.client import http, http.server import socket import threading import re import io import contextlib from test import support try: import gzip except ImportError: gzip = None alist = [{'astring': 'foo@bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, 'ashortlong': 2, 'anotherlist': ['.zyx.41'], 'abase64': xmlrpclib.Binary(b"my dog has fleas"), 'b64bytes': b"my dog has fleas", 'b64bytearray': bytearray(b"my dog has fleas"), 'boolean': False, 'unicode': '\u4000\u6000\u8000', 'ukey\u4000': 'regular value', 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), 'datetime2': xmlrpclib.DateTime( (2005, 2, 10, 11, 41, 23, 0, 1, -1)), 'datetime3': xmlrpclib.DateTime( datetime.datetime(2005, 2, 10, 11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): def test_dump_load(self): dump = xmlrpclib.dumps((alist,)) load = xmlrpclib.loads(dump) self.assertEqual(alist, load[0][0]) def test_dump_bare_datetime(self): # This checks that an unwrapped datetime.date object can be handled # by the marshalling code. This can't be done via test_dump_load() # since with use_builtin_types set to 1 the unmarshaller would create # datetime objects for the 'datetime[123]' keys as well dt = datetime.datetime(2005, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_datetime_before_1900(self): # same as before but with a date before 1900 dt = datetime.datetime(1, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_bug_1164912 (self): d = xmlrpclib.DateTime() ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,), methodresponse=True)) self.assertIsInstance(new_d.value, str) # Check that the output of dumps() is still an 8-bit string s = xmlrpclib.dumps((new_d,), methodresponse=True) self.assertIsInstance(s, str) def test_newstyle_class(self): class T(object): pass t = T() t.x = 100 t.y = "Hello" ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,))) self.assertEqual(t2, t.__dict__) def test_dump_big_long(self): self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,)) def test_dump_bad_dict(self): self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},)) def test_dump_recursive_seq(self): l = [1,2,3] t = [3,4,5,l] l.append(t) self.assertRaises(TypeError, xmlrpclib.dumps, (l,)) def test_dump_recursive_dict(self): d = {'1':1, '2':1} t = {'3':3, 'd':d} d['t'] = t self.assertRaises(TypeError, xmlrpclib.dumps, (d,)) def test_dump_big_int(self): if sys.maxsize > 2**31-1: self.assertRaises(OverflowError, xmlrpclib.dumps, (int(2**34),)) xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,)) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_int(xmlrpclib.MAXINT, dummy_write) m.dump_int(xmlrpclib.MININT, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write) def test_dump_double(self): xmlrpclib.dumps((float(2 ** 34),)) xmlrpclib.dumps((float(xmlrpclib.MAXINT), float(xmlrpclib.MININT))) xmlrpclib.dumps((float(xmlrpclib.MAXINT + 42), float(xmlrpclib.MININT - 42))) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_double(xmlrpclib.MAXINT, dummy_write) m.dump_double(xmlrpclib.MININT, dummy_write) m.dump_double(xmlrpclib.MAXINT + 42, dummy_write) m.dump_double(xmlrpclib.MININT - 42, dummy_write) def test_dump_none(self): value = alist + [None] arg1 = (alist + [None],) strg = xmlrpclib.dumps(arg1, allow_none=True) self.assertEqual(value, xmlrpclib.loads(strg)[0][0]) self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,)) def test_dump_encoding(self): value = {'key\u20ac\xa4': 'value\u20ac\xa4'} strg = xmlrpclib.dumps((value,), encoding='iso-8859-15') strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodresponse=True) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) methodname = 'method\u20ac\xa4' strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodname=methodname) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) self.assertEqual(xmlrpclib.loads(strg)[1], methodname) def test_dump_bytes(self): sample = b"my dog has fleas" self.assertEqual(sample, xmlrpclib.Binary(sample)) for type_ in bytes, bytearray, xmlrpclib.Binary: value = type_(sample) s = xmlrpclib.dumps((value,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), bytes) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), xmlrpclib.Binary) self.assertIsNone(m) def test_loads_unsupported(self): ResponseError = xmlrpclib.ResponseError data = '<params><param><value><spam/></value></param></params>' self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><array>' '<value><spam/></value>' '</array></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><struct>' '<member><name>a</name><value><spam/></value></member>' '<member><name>b</name><value><spam/></value></member>' '</struct></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) def check_loads(self, s, value, **kwargs): dump = '<params><param><value>%s</value></param></params>' % s result, m = xmlrpclib.loads(dump, **kwargs) (newvalue,) = result self.assertEqual(newvalue, value) self.assertIs(type(newvalue), type(value)) self.assertIsNone(m) def test_load_standard_types(self): check = self.check_loads check('string', 'string') check('<string>string</string>', 'string') check('<string>𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string</string>', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string') check('<int>2056183947</int>', 2056183947) check('<int>-2056183947</int>', -2056183947) check('<i4>2056183947</i4>', 2056183947) check('<double>46093.78125</double>', 46093.78125) check('<boolean>0</boolean>', False) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', xmlrpclib.Binary(b'\x00byte string\xff')) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', b'\x00byte string\xff', use_builtin_types=True) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', xmlrpclib.DateTime('20050210T11:41:23')) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', datetime.datetime(2005, 2, 10, 11, 41, 23), use_builtin_types=True) check('<array><data>' '<value><int>1</int></value><value><int>2</int></value>' '</data></array>', [1, 2]) check('<struct>' '<member><name>b</name><value><int>2</int></value></member>' '<member><name>a</name><value><int>1</int></value></member>' '</struct>', {'a': 1, 'b': 2}) def test_load_extension_types(self): check = self.check_loads check('<nil/>', None) check('<ex:nil/>', None) check('<i1>205</i1>', 205) check('<i2>20561</i2>', 20561) check('<i8>9876543210</i8>', 9876543210) check('<biginteger>98765432100123456789</biginteger>', 98765432100123456789) check('<float>93.78125</float>', 93.78125) check('<bigdecimal>9876543210.0123456789</bigdecimal>', decimal.Decimal('9876543210.0123456789')) def test_get_host_info(self): # see bug #3613, this raised a TypeError transp = xmlrpc.client.Transport() self.assertEqual(transp.get_host_info("user@host.tld"), ('host.tld', [('Authorization', 'Basic dXNlcg==')], {})) def test_ssl_presence(self): try: import ssl except ImportError: has_ssl = False else: has_ssl = True try: xmlrpc.client.ServerProxy('https://localhost:9999').bad_function() except NotImplementedError: self.assertFalse(has_ssl, "xmlrpc client's error with SSL support") except OSError: self.assertTrue(has_ssl) def test_keepalive_disconnect(self): class RequestHandler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" handled = False def do_POST(self): length = int(self.headers.get("Content-Length")) self.rfile.read(length) if self.handled: self.close_connection = True return response = xmlrpclib.dumps((5,), methodresponse=True) response = response.encode() self.send_response(http.HTTPStatus.OK) self.send_header("Content-Length", len(response)) self.end_headers() self.wfile.write(response) self.handled = True self.close_connection = False def log_message(self, format, *args): # don't clobber sys.stderr pass def run_server(): server.socket.settimeout(float(1)) # Don't hang if client fails server.handle_request() # First request and attempt at second server.handle_request() # Retried second request server = http.server.HTTPServer((support.HOST, 0), RequestHandler) self.addCleanup(server.server_close) thread = threading.Thread(target=run_server) thread.start() self.addCleanup(thread.join) url = "http://{}:{}/".format(*server.server_address) with xmlrpclib.ServerProxy(url) as p: self.assertEqual(p.method(), 5) self.assertEqual(p.method(), 5) class SimpleXMLRPCDispatcherTestCase(unittest.TestCase): class DispatchExc(Exception): """Raised inside the dispatched functions when checking for chained exceptions""" def test_call_registered_func(self): """Calls explicitly registered function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_params = 1, 2, 3 def dispatched_func(*params): raise self.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(dispatched_func) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_instance_func(self): """Calls a registered instance attribute as a function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_params = 1, 2, 3 class DispatchedClass: def dispatched_func(self, *params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(DispatchedClass()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_dispatch_func(self): """Calls the registered instance's `_dispatch` function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_method = 'method' exp_params = 1, 2, 3 class TestInstance: def _dispatch(self, method, params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc( method, params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(TestInstance()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch(exp_method, exp_params) self.assertEqual(exc_ctx.exception.args, (exp_method, exp_params)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_registered_func_is_none(self): """Calls explicitly registered function which is None""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(None, name='method') with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_instance_has_no_func(self): """Attempts to call nonexistent function on a registered instance""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(object()) with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_cannot_locate_func(self): """Calls a function that the dispatcher cannot locate""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) class HelperTestCase(unittest.TestCase): def test_escape(self): self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b") self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b") self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b") class FaultTestCase(unittest.TestCase): def test_repr(self): f = xmlrpclib.Fault(42, 'Test Fault') self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>") self.assertEqual(repr(f), str(f)) def test_dump_fault(self): f = xmlrpclib.Fault(42, 'Test Fault') s = xmlrpclib.dumps((f,)) (newf,), m = xmlrpclib.loads(s) self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'}) self.assertEqual(m, None) s = xmlrpclib.Marshaller().dumps(f) self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s) def test_dotted_attribute(self): # this will raise AttributeError because code don't want us to use # private methods self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) class DateTimeTestCase(unittest.TestCase): def test_default(self): with mock.patch('time.localtime') as localtime_mock: time_struct = time.struct_time( [2013, 7, 15, 0, 24, 49, 0, 196, 0]) localtime_mock.return_value = time_struct localtime = time.localtime() t = xmlrpclib.DateTime() self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", localtime)) def test_time(self): d = 1181399930.036952 t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) def test_time_tuple(self): d = (2007,6,9,10,38,50,5,160,0) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070609T10:38:50') def test_time_struct(self): d = time.localtime(1181399930.036952) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d)) def test_datetime_datetime(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070102T03:04:05') def test_repr(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) val ="<DateTime '20070102T03:04:05' at %#x>" % id(t) self.assertEqual(repr(t), val) def test_decode(self): d = ' 20070908T07:11:13 ' t1 = xmlrpclib.DateTime() t1.decode(d) tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13)) self.assertEqual(t1, tref) t2 = xmlrpclib._datetime(d) self.assertEqual(t2, tref) def test_comparison(self): now = datetime.datetime.now() dtime = xmlrpclib.DateTime(now.timetuple()) # datetime vs. DateTime self.assertTrue(dtime == now) self.assertTrue(now == dtime) then = now + datetime.timedelta(seconds=4) self.assertTrue(then >= dtime) self.assertTrue(dtime < then) # str vs. DateTime dstr = now.strftime("%Y%m%dT%H:%M:%S") self.assertTrue(dtime == dstr) self.assertTrue(dstr == dtime) dtime_then = xmlrpclib.DateTime(then.timetuple()) self.assertTrue(dtime_then >= dstr) self.assertTrue(dstr < dtime_then) # some other types dbytes = dstr.encode('ascii') dtuple = now.timetuple() with self.assertRaises(TypeError): dtime == 1970 with self.assertRaises(TypeError): dtime != dbytes with self.assertRaises(TypeError): dtime == bytearray(dbytes) with self.assertRaises(TypeError): dtime != dtuple with self.assertRaises(TypeError): dtime < float(1970) with self.assertRaises(TypeError): dtime > dbytes with self.assertRaises(TypeError): dtime <= bytearray(dbytes) with self.assertRaises(TypeError): dtime >= dtuple class BinaryTestCase(unittest.TestCase): # XXX What should str(Binary(b"\xff")) return? I'm chosing "\xff" # for now (i.e. interpreting the binary data as Latin-1-encoded # text). But this feels very unsatisfactory. Perhaps we should # only define repr(), and return r"Binary(b'\xff')" instead? def test_default(self): t = xmlrpclib.Binary() self.assertEqual(str(t), '') def test_string(self): d = b'\x01\x02\x03abc123\xff\xfe' t = xmlrpclib.Binary(d) self.assertEqual(str(t), str(d, "latin-1")) def test_decode(self): d = b'\x01\x02\x03abc123\xff\xfe' de = base64.encodebytes(d) t1 = xmlrpclib.Binary() t1.decode(de) self.assertEqual(str(t1), str(d, "latin-1")) t2 = xmlrpclib._binary(de) self.assertEqual(str(t2), str(d, "latin-1")) ADDR = PORT = URL = None # The evt is set twice. First when the server is ready to serve. # Second when the server has been shutdown. The user must clear # the event after it has been set the first time to catch the second set. def http_server(evt, numrequests, requestHandler=None, encoding=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' class Fixture: @staticmethod def getData(): return '42' class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer): def get_request(self): # Ensure the socket is always non-blocking. On Linux, socket # attributes are not inherited like they are on *BSD and Windows. s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler serv = MyXMLRPCServer(("localhost", 0), requestHandler, encoding=encoding, logRequests=False, bind_and_activate=False) try: serv.server_bind() global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() #connect to IP address directly. This avoids socket.create_connection() #trying to connect to "localhost" using all address families, which #causes slowdown e.g. on vista which supports AF_INET6. The server listens #on AF_INET only. URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() serv.register_introspection_functions() serv.register_multicall_functions() serv.register_function(pow) serv.register_function(lambda x: x, 'têšt') @serv.register_function def my_function(): '''This is my function''' return True @serv.register_function(name='add') def _(x, y): return x + y testInstance = TestInstanceClass() serv.register_instance(testInstance, allow_dotted_names=True) evt.set() # handle up to 'numrequests' requests while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() def http_multi_server(evt, numrequests, requestHandler=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' def my_function(): '''This is my function''' return True class MyXMLRPCServer(xmlrpc.server.MultiPathXMLRPCServer): def get_request(self): # Ensure the socket is always non-blocking. On Linux, socket # attributes are not inherited like they are on *BSD and Windows. s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler class MyRequestHandler(requestHandler): rpc_paths = [] class BrokenDispatcher: def _marshaled_dispatch(self, data, dispatch_method=None, path=None): raise RuntimeError("broken dispatcher") serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler, logRequests=False, bind_and_activate=False) serv.socket.settimeout(3) serv.server_bind() try: global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() #connect to IP address directly. This avoids socket.create_connection() #trying to connect to "localhost" using all address families, which #causes slowdown e.g. on vista which supports AF_INET6. The server listens #on AF_INET only. URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() paths = ["/foo", "/foo/bar"] for path in paths: d = serv.add_dispatcher(path, xmlrpc.server.SimpleXMLRPCDispatcher()) d.register_introspection_functions() d.register_multicall_functions() serv.get_dispatcher(paths[0]).register_function(pow) serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add') serv.add_dispatcher("/is/broken", BrokenDispatcher()) evt.set() # handle up to 'numrequests' requests while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() # This function prevents errors like: # <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error> def is_unavailable_exception(e): '''Returns True if the given ProtocolError is the product of a server-side exception caused by the 'temporarily unavailable' response sometimes given by operations on non-blocking sockets.''' # sometimes we get a -1 error code and/or empty headers try: if e.errcode == -1 or e.headers is None: return True exc_mess = e.headers.get('X-exception') except AttributeError: # Ignore OSErrors here. exc_mess = str(e) if exc_mess and 'temporarily unavailable' in exc_mess.lower(): return True def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request because # the server created in setUp blocks expecting one to come in. if not condition: return lambda func: func def decorator(func): def make_request_and_skip(self): try: xmlrpclib.ServerProxy(URL).my_function() except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): raise raise unittest.SkipTest(reason) return make_request_and_skip return decorator class BaseServerTestCase(unittest.TestCase): requestHandler = None request_count = 1 threadFunc = staticmethod(http_server) def setUp(self): # enable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True self.evt = threading.Event() # start server thread to handle requests serv_args = (self.evt, self.request_count, self.requestHandler) thread = threading.Thread(target=self.threadFunc, args=serv_args) thread.start() self.addCleanup(thread.join) # wait for the server to be ready self.evt.wait() self.evt.clear() def tearDown(self): # wait on the server thread to terminate self.evt.wait() # disable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False class SimpleServerTestCase(BaseServerTestCase): def test_simple1(self): try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii(self): start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t' end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n' try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_client_encoding(self): start_string = '\u20ac' end_string = '\xa4' try: p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15') self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket unavailable errors. if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii_methodname(self): try: p = xmlrpclib.ServerProxy(URL, encoding='ascii') self.assertEqual(p.têšt(42), 42) except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket unavailable errors. if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_404(self): # send POST with http.client, it should return 404 header and # 'Not Found' message. conn = http.client.HTTPConnection(ADDR, PORT) conn.request('POST', '/this-is-not-valid') response = conn.getresponse() conn.close() self.assertEqual(response.status, 404) self.assertEqual(response.reason, 'Not Found') def test_introspection1(self): expected_methods = set(['pow', 'div', 'my_function', 'add', 'têšt', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall', 'Fixture']) try: p = xmlrpclib.ServerProxy(URL) meth = p.system.listMethods() self.assertEqual(set(meth), expected_methods) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection2(self): try: # test _methodHelp() p = xmlrpclib.ServerProxy(URL) divhelp = p.system.methodHelp('div') self.assertEqual(divhelp, 'This is the div function')
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_jp.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecmaps_jp.py
# # test_codecmaps_jp.py # Codec mapping tests for Japanese encodings # from test import multibytecodec_support import unittest class TestCP932Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'cp932' mapfileurl = 'http://www.pythontest.net/unicode/CP932.TXT' supmaps = [ (b'\x80', '\u0080'), (b'\xa0', '\uf8f0'), (b'\xfd', '\uf8f1'), (b'\xfe', '\uf8f2'), (b'\xff', '\uf8f3'), ] for i in range(0xa1, 0xe0): supmaps.append((bytes([i]), chr(i+0xfec0))) class TestEUCJPCOMPATMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'euc_jp' mapfilename = 'EUC-JP.TXT' mapfileurl = 'http://www.pythontest.net/unicode/EUC-JP.TXT' class TestSJISCOMPATMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'shift_jis' mapfilename = 'SHIFTJIS.TXT' mapfileurl = 'http://www.pythontest.net/unicode/SHIFTJIS.TXT' pass_enctest = [ (b'\x81_', '\\'), ] pass_dectest = [ (b'\\', '\xa5'), (b'~', '\u203e'), (b'\x81_', '\\'), ] class TestEUCJISX0213Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'euc_jisx0213' mapfilename = 'EUC-JISX0213.TXT' mapfileurl = 'http://www.pythontest.net/unicode/EUC-JISX0213.TXT' class TestSJISX0213Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'shift_jisx0213' mapfilename = 'SHIFT_JISX0213.TXT' mapfileurl = 'http://www.pythontest.net/unicode/SHIFT_JISX0213.TXT' 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_minidom.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_minidom.py
# test for xml.dom.minidom import copy import pickle from test import support import unittest import xml.dom.minidom from xml.dom.minidom import parse, Node, Document, parseString from xml.dom.minidom import getDOMImplementation tstfile = support.findfile("test.xml", subdir="xmltestdata") sample = ("<?xml version='1.0' encoding='us-ascii'?>\n" "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'" " 'http://xml.python.org/system' [\n" " <!ELEMENT e EMPTY>\n" " <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n" "]><doc attr='value'> text\n" "<?pi sample?> <!-- comment --> <e/> </doc>") # The tests of DocumentType importing use these helpers to construct # the documents to work with, since not all DOM builders actually # create the DocumentType nodes. def create_doc_without_doctype(doctype=None): return getDOMImplementation().createDocument(None, "doc", doctype) def create_nonempty_doctype(): doctype = getDOMImplementation().createDocumentType("doc", None, None) doctype.entities._seq = [] doctype.notations._seq = [] notation = xml.dom.minidom.Notation("my-notation", None, "http://xml.python.org/notations/my") doctype.notations._seq.append(notation) entity = xml.dom.minidom.Entity("my-entity", None, "http://xml.python.org/entities/my", "my-notation") entity.version = "1.0" entity.encoding = "utf-8" entity.actualEncoding = "us-ascii" doctype.entities._seq.append(entity) return doctype def create_doc_with_doctype(): doctype = create_nonempty_doctype() doc = create_doc_without_doctype(doctype) doctype.entities.item(0).ownerDocument = doc doctype.notations.item(0).ownerDocument = doc return doc class MinidomTest(unittest.TestCase): def confirm(self, test, testname = "Test"): self.assertTrue(test, testname) def checkWholeText(self, node, s): t = node.wholeText self.confirm(t == s, "looking for %r, found %r" % (s, t)) def testDocumentAsyncAttr(self): doc = Document() self.assertFalse(doc.async_) self.assertFalse(Document.async_) def testParseFromBinaryFile(self): with open(tstfile, 'rb') as file: dom = parse(file) dom.unlink() self.confirm(isinstance(dom, Document)) def testParseFromTextFile(self): with open(tstfile, 'r', encoding='iso-8859-1') as file: dom = parse(file) dom.unlink() self.confirm(isinstance(dom, Document)) def testGetElementsByTagName(self): dom = parse(tstfile) self.confirm(dom.getElementsByTagName("LI") == \ dom.documentElement.getElementsByTagName("LI")) dom.unlink() def testInsertBefore(self): dom = parseString("<doc><foo/></doc>") root = dom.documentElement elem = root.childNodes[0] nelem = dom.createElement("element") root.insertBefore(nelem, elem) self.confirm(len(root.childNodes) == 2 and root.childNodes.length == 2 and root.childNodes[0] is nelem and root.childNodes.item(0) is nelem and root.childNodes[1] is elem and root.childNodes.item(1) is elem and root.firstChild is nelem and root.lastChild is elem and root.toxml() == "<doc><element/><foo/></doc>" , "testInsertBefore -- node properly placed in tree") nelem = dom.createElement("element") root.insertBefore(nelem, None) self.confirm(len(root.childNodes) == 3 and root.childNodes.length == 3 and root.childNodes[1] is elem and root.childNodes.item(1) is elem and root.childNodes[2] is nelem and root.childNodes.item(2) is nelem and root.lastChild is nelem and nelem.previousSibling is elem and root.toxml() == "<doc><element/><foo/><element/></doc>" , "testInsertBefore -- node properly placed in tree") nelem2 = dom.createElement("bar") root.insertBefore(nelem2, nelem) self.confirm(len(root.childNodes) == 4 and root.childNodes.length == 4 and root.childNodes[2] is nelem2 and root.childNodes.item(2) is nelem2 and root.childNodes[3] is nelem and root.childNodes.item(3) is nelem and nelem2.nextSibling is nelem and nelem.previousSibling is nelem2 and root.toxml() == "<doc><element/><foo/><bar/><element/></doc>" , "testInsertBefore -- node properly placed in tree") dom.unlink() def _create_fragment_test_nodes(self): dom = parseString("<doc/>") orig = dom.createTextNode("original") c1 = dom.createTextNode("foo") c2 = dom.createTextNode("bar") c3 = dom.createTextNode("bat") dom.documentElement.appendChild(orig) frag = dom.createDocumentFragment() frag.appendChild(c1) frag.appendChild(c2) frag.appendChild(c3) return dom, orig, c1, c2, c3, frag def testInsertBeforeFragment(self): dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes() dom.documentElement.insertBefore(frag, None) self.confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3), "insertBefore(<fragment>, None)") frag.unlink() dom.unlink() dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes() dom.documentElement.insertBefore(frag, orig) self.confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3, orig), "insertBefore(<fragment>, orig)") frag.unlink() dom.unlink() def testAppendChild(self): dom = parse(tstfile) dom.documentElement.appendChild(dom.createComment("Hello")) self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment") self.confirm(dom.documentElement.childNodes[-1].data == "Hello") dom.unlink() def testAppendChildFragment(self): dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes() dom.documentElement.appendChild(frag) self.confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3), "appendChild(<fragment>)") frag.unlink() dom.unlink() def testReplaceChildFragment(self): dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes() dom.documentElement.replaceChild(frag, orig) orig.unlink() self.confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3), "replaceChild(<fragment>)") frag.unlink() dom.unlink() def testLegalChildren(self): dom = Document() elem = dom.createElement('element') text = dom.createTextNode('text') self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text) dom.appendChild(elem) self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text, elem) self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text, elem) nodemap = elem.attributes self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem, text) self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS, text) elem.appendChild(text) dom.unlink() def testNamedNodeMapSetItem(self): dom = Document() elem = dom.createElement('element') attrs = elem.attributes attrs["foo"] = "bar" a = attrs.item(0) self.confirm(a.ownerDocument is dom, "NamedNodeMap.__setitem__() sets ownerDocument") self.confirm(a.ownerElement is elem, "NamedNodeMap.__setitem__() sets ownerElement") self.confirm(a.value == "bar", "NamedNodeMap.__setitem__() sets value") self.confirm(a.nodeValue == "bar", "NamedNodeMap.__setitem__() sets nodeValue") elem.unlink() dom.unlink() def testNonZero(self): dom = parse(tstfile) self.confirm(dom)# should not be zero dom.appendChild(dom.createComment("foo")) self.confirm(not dom.childNodes[-1].childNodes) dom.unlink() def testUnlink(self): dom = parse(tstfile) self.assertTrue(dom.childNodes) dom.unlink() self.assertFalse(dom.childNodes) def testContext(self): with parse(tstfile) as dom: self.assertTrue(dom.childNodes) self.assertFalse(dom.childNodes) def testElement(self): dom = Document() dom.appendChild(dom.createElement("abc")) self.confirm(dom.documentElement) dom.unlink() def testAAA(self): dom = parseString("<abc/>") el = dom.documentElement el.setAttribute("spam", "jam2") self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA") a = el.getAttributeNode("spam") self.confirm(a.ownerDocument is dom, "setAttribute() sets ownerDocument") self.confirm(a.ownerElement is dom.documentElement, "setAttribute() sets ownerElement") dom.unlink() def testAAB(self): dom = parseString("<abc/>") el = dom.documentElement el.setAttribute("spam", "jam") el.setAttribute("spam", "jam2") self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB") dom.unlink() def testAddAttr(self): dom = Document() child = dom.appendChild(dom.createElement("abc")) child.setAttribute("def", "ghi") self.confirm(child.getAttribute("def") == "ghi") self.confirm(child.attributes["def"].value == "ghi") child.setAttribute("jkl", "mno") self.confirm(child.getAttribute("jkl") == "mno") self.confirm(child.attributes["jkl"].value == "mno") self.confirm(len(child.attributes) == 2) child.setAttribute("def", "newval") self.confirm(child.getAttribute("def") == "newval") self.confirm(child.attributes["def"].value == "newval") self.confirm(len(child.attributes) == 2) dom.unlink() def testDeleteAttr(self): dom = Document() child = dom.appendChild(dom.createElement("abc")) self.confirm(len(child.attributes) == 0) child.setAttribute("def", "ghi") self.confirm(len(child.attributes) == 1) del child.attributes["def"] self.confirm(len(child.attributes) == 0) dom.unlink() def testRemoveAttr(self): dom = Document() child = dom.appendChild(dom.createElement("abc")) child.setAttribute("def", "ghi") self.confirm(len(child.attributes) == 1) self.assertRaises(xml.dom.NotFoundErr, child.removeAttribute, "foo") child.removeAttribute("def") self.confirm(len(child.attributes) == 0) dom.unlink() def testRemoveAttrNS(self): dom = Document() child = dom.appendChild( dom.createElementNS("http://www.python.org", "python:abc")) child.setAttributeNS("http://www.w3.org", "xmlns:python", "http://www.python.org") child.setAttributeNS("http://www.python.org", "python:abcattr", "foo") self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNS, "foo", "http://www.python.org") self.confirm(len(child.attributes) == 2) child.removeAttributeNS("http://www.python.org", "abcattr") self.confirm(len(child.attributes) == 1) dom.unlink() def testRemoveAttributeNode(self): dom = Document() child = dom.appendChild(dom.createElement("foo")) child.setAttribute("spam", "jam") self.confirm(len(child.attributes) == 1) node = child.getAttributeNode("spam") self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNode, None) child.removeAttributeNode(node) self.confirm(len(child.attributes) == 0 and child.getAttributeNode("spam") is None) dom2 = Document() child2 = dom2.appendChild(dom2.createElement("foo")) node2 = child2.getAttributeNode("spam") self.assertRaises(xml.dom.NotFoundErr, child2.removeAttributeNode, node2) dom.unlink() def testHasAttribute(self): dom = Document() child = dom.appendChild(dom.createElement("foo")) child.setAttribute("spam", "jam") self.confirm(child.hasAttribute("spam")) def testChangeAttr(self): dom = parseString("<abc/>") el = dom.documentElement el.setAttribute("spam", "jam") self.confirm(len(el.attributes) == 1) el.setAttribute("spam", "bam") # Set this attribute to be an ID and make sure that doesn't change # when changing the value: el.setIdAttribute("spam") self.confirm(len(el.attributes) == 1 and el.attributes["spam"].value == "bam" and el.attributes["spam"].nodeValue == "bam" and el.getAttribute("spam") == "bam" and el.getAttributeNode("spam").isId) el.attributes["spam"] = "ham" self.confirm(len(el.attributes) == 1 and el.attributes["spam"].value == "ham" and el.attributes["spam"].nodeValue == "ham" and el.getAttribute("spam") == "ham" and el.attributes["spam"].isId) el.setAttribute("spam2", "bam") self.confirm(len(el.attributes) == 2 and el.attributes["spam"].value == "ham" and el.attributes["spam"].nodeValue == "ham" and el.getAttribute("spam") == "ham" and el.attributes["spam2"].value == "bam" and el.attributes["spam2"].nodeValue == "bam" and el.getAttribute("spam2") == "bam") el.attributes["spam2"] = "bam2" self.confirm(len(el.attributes) == 2 and el.attributes["spam"].value == "ham" and el.attributes["spam"].nodeValue == "ham" and el.getAttribute("spam") == "ham" and el.attributes["spam2"].value == "bam2" and el.attributes["spam2"].nodeValue == "bam2" and el.getAttribute("spam2") == "bam2") dom.unlink() def testGetAttrList(self): pass def testGetAttrValues(self): pass def testGetAttrLength(self): pass def testGetAttribute(self): dom = Document() child = dom.appendChild( dom.createElementNS("http://www.python.org", "python:abc")) self.assertEqual(child.getAttribute('missing'), '') def testGetAttributeNS(self): dom = Document() child = dom.appendChild( dom.createElementNS("http://www.python.org", "python:abc")) child.setAttributeNS("http://www.w3.org", "xmlns:python", "http://www.python.org") self.assertEqual(child.getAttributeNS("http://www.w3.org", "python"), 'http://www.python.org') self.assertEqual(child.getAttributeNS("http://www.w3.org", "other"), '') child2 = child.appendChild(dom.createElement('abc')) self.assertEqual(child2.getAttributeNS("http://www.python.org", "missing"), '') def testGetAttributeNode(self): pass def testGetElementsByTagNameNS(self): d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'> <minidom:myelem/> </foo>""" dom = parseString(d) elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom", "myelem") self.confirm(len(elems) == 1 and elems[0].namespaceURI == "http://pyxml.sf.net/minidom" and elems[0].localName == "myelem" and elems[0].prefix == "minidom" and elems[0].tagName == "minidom:myelem" and elems[0].nodeName == "minidom:myelem") dom.unlink() def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri, lname): nodelist = doc.getElementsByTagNameNS(nsuri, lname) self.confirm(len(nodelist) == 0) def testGetEmptyNodeListFromElementsByTagNameNS(self): doc = parseString('<doc/>') self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, 'http://xml.python.org/namespaces/a', 'localname') self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, '*', 'splat') self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, 'http://xml.python.org/namespaces/a', '*') doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>') self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, "http://xml.python.org/splat", "not-there") self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, "*", "not-there") self.get_empty_nodelist_from_elements_by_tagName_ns_helper( doc, "http://somewhere.else.net/not-there", "e") def testElementReprAndStr(self): dom = Document() el = dom.appendChild(dom.createElement("abc")) string1 = repr(el) string2 = str(el) self.confirm(string1 == string2) dom.unlink() def testElementReprAndStrUnicode(self): dom = Document() el = dom.appendChild(dom.createElement("abc")) string1 = repr(el) string2 = str(el) self.confirm(string1 == string2) dom.unlink() def testElementReprAndStrUnicodeNS(self): dom = Document() el = dom.appendChild( dom.createElementNS("http://www.slashdot.org", "slash:abc")) string1 = repr(el) string2 = str(el) self.confirm(string1 == string2) self.confirm("slash:abc" in string1) dom.unlink() def testAttributeRepr(self): dom = Document() el = dom.appendChild(dom.createElement("abc")) node = el.setAttribute("abc", "def") self.confirm(str(node) == repr(node)) dom.unlink() def testTextNodeRepr(self): pass def testWriteXML(self): str = '<?xml version="1.0" ?><a b="c"/>' dom = parseString(str) domstr = dom.toxml() dom.unlink() self.confirm(str == domstr) def testAltNewline(self): str = '<?xml version="1.0" ?>\n<a b="c"/>\n' dom = parseString(str) domstr = dom.toprettyxml(newl="\r\n") dom.unlink() self.confirm(domstr == str.replace("\n", "\r\n")) def test_toprettyxml_with_text_nodes(self): # see issue #4147, text nodes are not indented decl = '<?xml version="1.0" ?>\n' self.assertEqual(parseString('<B>A</B>').toprettyxml(), decl + '<B>A</B>\n') self.assertEqual(parseString('<C>A<B>A</B></C>').toprettyxml(), decl + '<C>\n\tA\n\t<B>A</B>\n</C>\n') self.assertEqual(parseString('<C><B>A</B>A</C>').toprettyxml(), decl + '<C>\n\t<B>A</B>\n\tA\n</C>\n') self.assertEqual(parseString('<C><B>A</B><B>A</B></C>').toprettyxml(), decl + '<C>\n\t<B>A</B>\n\t<B>A</B>\n</C>\n') self.assertEqual(parseString('<C><B>A</B>A<B>A</B></C>').toprettyxml(), decl + '<C>\n\t<B>A</B>\n\tA\n\t<B>A</B>\n</C>\n') def test_toprettyxml_with_adjacent_text_nodes(self): # see issue #4147, adjacent text nodes are indented normally dom = Document() elem = dom.createElement('elem') elem.appendChild(dom.createTextNode('TEXT')) elem.appendChild(dom.createTextNode('TEXT')) dom.appendChild(elem) decl = '<?xml version="1.0" ?>\n' self.assertEqual(dom.toprettyxml(), decl + '<elem>\n\tTEXT\n\tTEXT\n</elem>\n') def test_toprettyxml_preserves_content_of_text_node(self): # see issue #4147 for str in ('<B>A</B>', '<A><B>C</B></A>'): dom = parseString(str) dom2 = parseString(dom.toprettyxml()) self.assertEqual( dom.getElementsByTagName('B')[0].childNodes[0].toxml(), dom2.getElementsByTagName('B')[0].childNodes[0].toxml()) def testProcessingInstruction(self): dom = parseString('<e><?mypi \t\n data \t\n ?></e>') pi = dom.documentElement.firstChild self.confirm(pi.target == "mypi" and pi.data == "data \t\n " and pi.nodeName == "mypi" and pi.nodeType == Node.PROCESSING_INSTRUCTION_NODE and pi.attributes is None and not pi.hasChildNodes() and len(pi.childNodes) == 0 and pi.firstChild is None and pi.lastChild is None and pi.localName is None and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE) def testProcessingInstructionRepr(self): pass def testTextRepr(self): pass def testWriteText(self): pass def testDocumentElement(self): pass def testTooManyDocumentElements(self): doc = parseString("<doc/>") elem = doc.createElement("extra") # Should raise an exception when adding an extra document element. self.assertRaises(xml.dom.HierarchyRequestErr, doc.appendChild, elem) elem.unlink() doc.unlink() def testCreateElementNS(self): pass def testCreateAttributeNS(self): pass def testParse(self): pass def testParseString(self): pass def testComment(self): pass def testAttrListItem(self): pass def testAttrListItems(self): pass def testAttrListItemNS(self): pass def testAttrListKeys(self): pass def testAttrListKeysNS(self): pass def testRemoveNamedItem(self): doc = parseString("<doc a=''/>") e = doc.documentElement attrs = e.attributes a1 = e.getAttributeNode("a") a2 = attrs.removeNamedItem("a") self.confirm(a1.isSameNode(a2)) self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItem, "a") def testRemoveNamedItemNS(self): doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>") e = doc.documentElement attrs = e.attributes a1 = e.getAttributeNodeNS("http://xml.python.org/", "b") a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b") self.confirm(a1.isSameNode(a2)) self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS, "http://xml.python.org/", "b") def testAttrListValues(self): pass def testAttrListLength(self): pass def testAttrList__getitem__(self): pass def testAttrList__setitem__(self): pass def testSetAttrValueandNodeValue(self): pass def testParseElement(self): pass def testParseAttributes(self): pass def testParseElementNamespaces(self): pass def testParseAttributeNamespaces(self): pass def testParseProcessingInstructions(self): pass def testChildNodes(self): pass def testFirstChild(self): pass def testHasChildNodes(self): dom = parseString("<doc><foo/></doc>") doc = dom.documentElement self.assertTrue(doc.hasChildNodes()) dom2 = parseString("<doc/>") doc2 = dom2.documentElement self.assertFalse(doc2.hasChildNodes()) def _testCloneElementCopiesAttributes(self, e1, e2, test): attrs1 = e1.attributes attrs2 = e2.attributes keys1 = list(attrs1.keys()) keys2 = list(attrs2.keys()) keys1.sort() keys2.sort() self.confirm(keys1 == keys2, "clone of element has same attribute keys") for i in range(len(keys1)): a1 = attrs1.item(i) a2 = attrs2.item(i) self.confirm(a1 is not a2 and a1.value == a2.value and a1.nodeValue == a2.nodeValue and a1.namespaceURI == a2.namespaceURI and a1.localName == a2.localName , "clone of attribute node has proper attribute values") self.confirm(a2.ownerElement is e2, "clone of attribute node correctly owned") def _setupCloneElement(self, deep): dom = parseString("<doc attr='value'><foo/></doc>") root = dom.documentElement clone = root.cloneNode(deep) self._testCloneElementCopiesAttributes( root, clone, "testCloneElement" + (deep and "Deep" or "Shallow")) # mutilate the original so shared data is detected root.tagName = root.nodeName = "MODIFIED" root.setAttribute("attr", "NEW VALUE") root.setAttribute("added", "VALUE") return dom, clone def testCloneElementShallow(self): dom, clone = self._setupCloneElement(0) self.confirm(len(clone.childNodes) == 0 and clone.childNodes.length == 0 and clone.parentNode is None and clone.toxml() == '<doc attr="value"/>' , "testCloneElementShallow") dom.unlink() def testCloneElementDeep(self): dom, clone = self._setupCloneElement(1) self.confirm(len(clone.childNodes) == 1 and clone.childNodes.length == 1 and clone.parentNode is None and clone.toxml() == '<doc attr="value"><foo/></doc>' , "testCloneElementDeep") dom.unlink() def testCloneDocumentShallow(self): doc = parseString("<?xml version='1.0'?>\n" "<!-- comment -->" "<!DOCTYPE doc [\n" "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n" "]>\n" "<doc attr='value'/>") doc2 = doc.cloneNode(0) self.confirm(doc2 is None, "testCloneDocumentShallow:" " shallow cloning of documents makes no sense!") def testCloneDocumentDeep(self): doc = parseString("<?xml version='1.0'?>\n" "<!-- comment -->" "<!DOCTYPE doc [\n" "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n" "]>\n" "<doc attr='value'/>") doc2 = doc.cloneNode(1) self.confirm(not (doc.isSameNode(doc2) or doc2.isSameNode(doc)), "testCloneDocumentDeep: document objects not distinct") self.confirm(len(doc.childNodes) == len(doc2.childNodes), "testCloneDocumentDeep: wrong number of Document children") self.confirm(doc2.documentElement.nodeType == Node.ELEMENT_NODE, "testCloneDocumentDeep: documentElement not an ELEMENT_NODE") self.confirm(doc2.documentElement.ownerDocument.isSameNode(doc2), "testCloneDocumentDeep: documentElement owner is not new document") self.confirm(not doc.documentElement.isSameNode(doc2.documentElement), "testCloneDocumentDeep: documentElement should not be shared") if doc.doctype is not None: # check the doctype iff the original DOM maintained it self.confirm(doc2.doctype.nodeType == Node.DOCUMENT_TYPE_NODE, "testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE") self.confirm(doc2.doctype.ownerDocument.isSameNode(doc2)) self.confirm(not doc.doctype.isSameNode(doc2.doctype)) def testCloneDocumentTypeDeepOk(self): doctype = create_nonempty_doctype() clone = doctype.cloneNode(1) self.confirm(clone is not None and clone.nodeName == doctype.nodeName and clone.name == doctype.name and clone.publicId == doctype.publicId and clone.systemId == doctype.systemId and len(clone.entities) == len(doctype.entities) and clone.entities.item(len(clone.entities)) is None and len(clone.notations) == len(doctype.notations) and clone.notations.item(len(clone.notations)) is None and len(clone.childNodes) == 0) for i in range(len(doctype.entities)): se = doctype.entities.item(i) ce = clone.entities.item(i) self.confirm((not se.isSameNode(ce)) and (not ce.isSameNode(se)) and ce.nodeName == se.nodeName and ce.notationName == se.notationName and ce.publicId == se.publicId and ce.systemId == se.systemId and ce.encoding == se.encoding and ce.actualEncoding == se.actualEncoding and ce.version == se.version) for i in range(len(doctype.notations)): sn = doctype.notations.item(i) cn = clone.notations.item(i) self.confirm((not sn.isSameNode(cn)) and (not cn.isSameNode(sn)) and cn.nodeName == sn.nodeName and cn.publicId == sn.publicId and cn.systemId == sn.systemId) def testCloneDocumentTypeDeepNotOk(self): doc = create_doc_with_doctype() clone = doc.doctype.cloneNode(1) self.confirm(clone is None, "testCloneDocumentTypeDeepNotOk") def testCloneDocumentTypeShallowOk(self): doctype = create_nonempty_doctype() clone = doctype.cloneNode(0) self.confirm(clone is not None and clone.nodeName == doctype.nodeName and clone.name == doctype.name and clone.publicId == doctype.publicId and clone.systemId == doctype.systemId and len(clone.entities) == 0 and clone.entities.item(0) is None and len(clone.notations) == 0 and clone.notations.item(0) is None and len(clone.childNodes) == 0) def testCloneDocumentTypeShallowNotOk(self): doc = create_doc_with_doctype() clone = doc.doctype.cloneNode(0) self.confirm(clone is None, "testCloneDocumentTypeShallowNotOk") def check_import_document(self, deep, testName): doc1 = parseString("<doc/>") doc2 = parseString("<doc/>") self.assertRaises(xml.dom.NotSupportedErr, doc1.importNode, doc2, deep) def testImportDocumentShallow(self): self.check_import_document(0, "testImportDocumentShallow") def testImportDocumentDeep(self): self.check_import_document(1, "testImportDocumentDeep") def testImportDocumentTypeShallow(self): src = create_doc_with_doctype() target = create_doc_without_doctype() self.assertRaises(xml.dom.NotSupportedErr, target.importNode, src.doctype, 0) def testImportDocumentTypeDeep(self): src = create_doc_with_doctype() target = create_doc_without_doctype() self.assertRaises(xml.dom.NotSupportedErr, target.importNode, src.doctype, 1) # Testing attribute clones uses a helper, and should always be deep, # even if the argument to cloneNode is false. def check_clone_attribute(self, deep, testName): doc = parseString("<doc attr='value'/>") attr = doc.documentElement.getAttributeNode("attr") self.assertNotEqual(attr, None) clone = attr.cloneNode(deep) self.confirm(not clone.isSameNode(attr)) self.confirm(not attr.isSameNode(clone)) self.confirm(clone.ownerElement is None, testName + ": ownerElement should be None") self.confirm(clone.ownerDocument.isSameNode(attr.ownerDocument), testName + ": ownerDocument does not match") self.confirm(clone.specified, testName + ": cloned attribute must have specified == True") def testCloneAttributeShallow(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_httpservers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httpservers.py
"""Unittests for the various HTTPServer modules. Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>, Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest. """ from http.server import BaseHTTPRequestHandler, HTTPServer, \ SimpleHTTPRequestHandler, CGIHTTPRequestHandler from http import server, HTTPStatus import os import sys import re import base64 import ntpath import shutil import email.message import email.utils import html import http.client import urllib.parse import tempfile import time import datetime import threading from unittest import mock from io import BytesIO import unittest from test import support class NoLogRequestHandler: def log_message(self, *args): # don't write log messages to stderr pass def read(self, n=None): return '' class TestServerThread(threading.Thread): def __init__(self, test_object, request_handler): threading.Thread.__init__(self) self.request_handler = request_handler self.test_object = test_object def run(self): self.server = HTTPServer(('localhost', 0), self.request_handler) self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname() self.test_object.server_started.set() self.test_object = None try: self.server.serve_forever(0.05) finally: self.server.server_close() def stop(self): self.server.shutdown() self.join() class BaseTestCase(unittest.TestCase): def setUp(self): self._threads = support.threading_setup() os.environ = support.EnvironmentVarGuard() self.server_started = threading.Event() self.thread = TestServerThread(self, self.request_handler) self.thread.start() self.server_started.wait() def tearDown(self): self.thread.stop() self.thread = None os.environ.__exit__() support.threading_cleanup(*self._threads) def request(self, uri, method='GET', body=None, headers={}): self.connection = http.client.HTTPConnection(self.HOST, self.PORT) self.connection.request(method, uri, body, headers) return self.connection.getresponse() class BaseHTTPServerTestCase(BaseTestCase): class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' default_request_version = 'HTTP/1.1' def do_TEST(self): self.send_response(HTTPStatus.NO_CONTENT) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'close') self.end_headers() def do_KEEP(self): self.send_response(HTTPStatus.NO_CONTENT) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'keep-alive') self.end_headers() def do_KEYERROR(self): self.send_error(999) def do_NOTFOUND(self): self.send_error(HTTPStatus.NOT_FOUND) def do_EXPLAINERROR(self): self.send_error(999, "Short Message", "This is a long \n explanation") def do_CUSTOM(self): self.send_response(999) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'close') self.end_headers() def do_LATINONEHEADER(self): self.send_response(999) self.send_header('X-Special', 'Dängerous Mind') self.send_header('Connection', 'close') self.end_headers() body = self.headers['x-special-incoming'].encode('utf-8') self.wfile.write(body) def do_SEND_ERROR(self): self.send_error(int(self.path[1:])) def do_HEAD(self): self.send_error(int(self.path[1:])) def setUp(self): BaseTestCase.setUp(self) self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() def test_command(self): self.con.request('GET', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_request_line_trimming(self): self.con._http_vsn_str = 'HTTP/1.1\n' self.con.putrequest('XYZBOGUS', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_version_bogus(self): self.con._http_vsn_str = 'FUBAR' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_digits(self): self.con._http_vsn_str = 'HTTP/9.9.9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_none_get(self): self.con._http_vsn_str = '' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_version_none(self): # Test that a valid method is rejected when not HTTP/1.x self.con._http_vsn_str = '' self.con.putrequest('CUSTOM', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_invalid(self): self.con._http_vsn = 99 self.con._http_vsn_str = 'HTTP/9.9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED) def test_send_blank(self): self.con._http_vsn_str = '' self.con.putrequest('', '') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_header_close(self): self.con.putrequest('GET', '/') self.con.putheader('Connection', 'close') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_header_keep_alive(self): self.con._http_vsn_str = 'HTTP/1.1' self.con.putrequest('GET', '/') self.con.putheader('Connection', 'keep-alive') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_handler(self): self.con.request('TEST', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NO_CONTENT) def test_return_header_keep_alive(self): self.con.request('KEEP', '/') res = self.con.getresponse() self.assertEqual(res.getheader('Connection'), 'keep-alive') self.con.request('TEST', '/') self.addCleanup(self.con.close) def test_internal_key_error(self): self.con.request('KEYERROR', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) def test_return_custom_status(self): self.con.request('CUSTOM', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) def test_return_explain_error(self): self.con.request('EXPLAINERROR', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) self.assertTrue(int(res.getheader('Content-Length'))) def test_latin1_header(self): self.con.request('LATINONEHEADER', '/', headers={ 'X-Special-Incoming': 'Ärger mit Unicode' }) res = self.con.getresponse() self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind') self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8')) def test_error_content_length(self): # Issue #16088: standard error responses should have a content-length self.con.request('NOTFOUND', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_FOUND) data = res.read() self.assertEqual(int(res.getheader('Content-Length')), len(data)) def test_send_error(self): allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT) for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED, HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT, HTTPStatus.SWITCHING_PROTOCOLS): self.con.request('SEND_ERROR', '/{}'.format(code)) res = self.con.getresponse() self.assertEqual(code, res.status) self.assertEqual(None, res.getheader('Content-Length')) self.assertEqual(None, res.getheader('Content-Type')) if code not in allow_transfer_encoding_codes: self.assertEqual(None, res.getheader('Transfer-Encoding')) data = res.read() self.assertEqual(b'', data) def test_head_via_send_error(self): allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT) for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT, HTTPStatus.SWITCHING_PROTOCOLS): self.con.request('HEAD', '/{}'.format(code)) res = self.con.getresponse() self.assertEqual(code, res.status) if code == HTTPStatus.OK: self.assertTrue(int(res.getheader('Content-Length')) > 0) self.assertIn('text/html', res.getheader('Content-Type')) else: self.assertEqual(None, res.getheader('Content-Length')) self.assertEqual(None, res.getheader('Content-Type')) if code not in allow_transfer_encoding_codes: self.assertEqual(None, res.getheader('Transfer-Encoding')) data = res.read() self.assertEqual(b'', data) class RequestHandlerLoggingTestCase(BaseTestCase): class request_handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' default_request_version = 'HTTP/1.1' def do_GET(self): self.send_response(HTTPStatus.OK) self.end_headers() def do_ERROR(self): self.send_error(HTTPStatus.NOT_FOUND, 'File not found') def test_get(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() with support.captured_stderr() as err: self.con.request('GET', '/') self.con.getresponse() self.assertTrue( err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n')) def test_err(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() with support.captured_stderr() as err: self.con.request('ERROR', '/') self.con.getresponse() lines = err.getvalue().split('\n') self.assertTrue(lines[0].endswith('code 404, message File not found')) self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -')) class SimpleHTTPServerTestCase(BaseTestCase): class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler): pass def setUp(self): BaseTestCase.setUp(self) self.cwd = os.getcwd() basetempdir = tempfile.gettempdir() os.chdir(basetempdir) self.data = b'We are the knights who say Ni!' self.tempdir = tempfile.mkdtemp(dir=basetempdir) self.tempdir_name = os.path.basename(self.tempdir) self.base_url = '/' + self.tempdir_name tempname = os.path.join(self.tempdir, 'test') with open(tempname, 'wb') as temp: temp.write(self.data) temp.flush() mtime = os.stat(tempname).st_mtime # compute last modification datetime for browser cache tests last_modif = datetime.datetime.fromtimestamp(mtime, datetime.timezone.utc) self.last_modif_datetime = last_modif.replace(microsecond=0) self.last_modif_header = email.utils.formatdate( last_modif.timestamp(), usegmt=True) def tearDown(self): try: os.chdir(self.cwd) try: shutil.rmtree(self.tempdir) except: pass finally: BaseTestCase.tearDown(self) def check_status_and_reason(self, response, status, data=None): def close_conn(): """Don't close reader yet so we can check if there was leftover buffered input""" nonlocal reader reader = response.fp response.fp = None reader = None response._close_conn = close_conn body = response.read() self.assertTrue(response) self.assertEqual(response.status, status) self.assertIsNotNone(response.reason) if data: self.assertEqual(data, body) # Ensure the server has not set up a persistent connection, and has # not sent any extra data self.assertEqual(response.version, 10) self.assertEqual(response.msg.get("Connection", "close"), "close") self.assertEqual(reader.read(30), b'', 'Connection should be closed') reader.close() return body @unittest.skipIf(sys.platform == 'darwin', 'undecodable name cannot always be decoded on macOS') @unittest.skipIf(sys.platform == 'win32', 'undecodable name cannot be decoded on win32') @unittest.skipUnless(support.TESTFN_UNDECODABLE, 'need support.TESTFN_UNDECODABLE') def test_undecodable_filename(self): enc = sys.getfilesystemencoding() filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt' with open(os.path.join(self.tempdir, filename), 'wb') as f: f.write(support.TESTFN_UNDECODABLE) response = self.request(self.base_url + '/') if sys.platform == 'darwin': # On Mac OS the HFS+ filesystem replaces bytes that aren't valid # UTF-8 into a percent-encoded value. for name in os.listdir(self.tempdir): if name != 'test': # Ignore a filename created in setUp(). filename = name break body = self.check_status_and_reason(response, HTTPStatus.OK) quotedname = urllib.parse.quote(filename, errors='surrogatepass') self.assertIn(('href="%s"' % quotedname) .encode(enc, 'surrogateescape'), body) self.assertIn(('>%s<' % html.escape(filename, quote=False)) .encode(enc, 'surrogateescape'), body) response = self.request(self.base_url + '/' + quotedname) self.check_status_and_reason(response, HTTPStatus.OK, data=support.TESTFN_UNDECODABLE) def test_get(self): #constructs the path relative to the root directory of the HTTPServer response = self.request(self.base_url + '/test') self.check_status_and_reason(response, HTTPStatus.OK, data=self.data) # check for trailing "/" which should return 404. See Issue17324 response = self.request(self.base_url + '/test/') self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) response = self.request(self.base_url + '/') self.check_status_and_reason(response, HTTPStatus.OK) response = self.request(self.base_url) self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) response = self.request(self.base_url + '/?hi=2') self.check_status_and_reason(response, HTTPStatus.OK) response = self.request(self.base_url + '?hi=1') self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) self.assertEqual(response.getheader("Location"), self.base_url + "/?hi=1") response = self.request('/ThisDoesNotExist') self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) response = self.request('/' + 'ThisDoesNotExist' + '/') self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) data = b"Dummy index file\r\n" with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f: f.write(data) response = self.request(self.base_url + '/') self.check_status_and_reason(response, HTTPStatus.OK, data) # chmod() doesn't work as expected on Windows, and filesystem # permissions are ignored by root on Unix. if os.name == 'posix' and os.geteuid() != 0: os.chmod(self.tempdir, 0) try: response = self.request(self.base_url + '/') self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) finally: os.chmod(self.tempdir, 0o755) def test_head(self): response = self.request( self.base_url + '/test', method='HEAD') self.check_status_and_reason(response, HTTPStatus.OK) self.assertEqual(response.getheader('content-length'), str(len(self.data))) self.assertEqual(response.getheader('content-type'), 'application/octet-stream') def test_browser_cache(self): """Check that when a request to /test is sent with the request header If-Modified-Since set to date of last modification, the server returns status code 304, not 200 """ headers = email.message.Message() headers['If-Modified-Since'] = self.last_modif_header response = self.request(self.base_url + '/test', headers=headers) self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED) # one hour after last modification : must return 304 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1) headers = email.message.Message() headers['If-Modified-Since'] = email.utils.format_datetime(new_dt, usegmt=True) response = self.request(self.base_url + '/test', headers=headers) self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED) def test_browser_cache_file_changed(self): # with If-Modified-Since earlier than Last-Modified, must return 200 dt = self.last_modif_datetime # build datetime object : 365 days before last modification old_dt = dt - datetime.timedelta(days=365) headers = email.message.Message() headers['If-Modified-Since'] = email.utils.format_datetime(old_dt, usegmt=True) response = self.request(self.base_url + '/test', headers=headers) self.check_status_and_reason(response, HTTPStatus.OK) def test_browser_cache_with_If_None_Match_header(self): # if If-None-Match header is present, ignore If-Modified-Since headers = email.message.Message() headers['If-Modified-Since'] = self.last_modif_header headers['If-None-Match'] = "*" response = self.request(self.base_url + '/test', headers=headers) self.check_status_and_reason(response, HTTPStatus.OK) def test_invalid_requests(self): response = self.request('/', method='FOO') self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) # requests must be case sensitive,so this should fail too response = self.request('/', method='custom') self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) response = self.request('/', method='GETs') self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) def test_last_modified(self): """Checks that the datetime returned in Last-Modified response header is the actual datetime of last modification, rounded to the second """ response = self.request(self.base_url + '/test') self.check_status_and_reason(response, HTTPStatus.OK, data=self.data) last_modif_header = response.headers['Last-modified'] self.assertEqual(last_modif_header, self.last_modif_header) def test_path_without_leading_slash(self): response = self.request(self.tempdir_name + '/test') self.check_status_and_reason(response, HTTPStatus.OK, data=self.data) response = self.request(self.tempdir_name + '/test/') self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) response = self.request(self.tempdir_name + '/') self.check_status_and_reason(response, HTTPStatus.OK) response = self.request(self.tempdir_name) self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) response = self.request(self.tempdir_name + '/?hi=2') self.check_status_and_reason(response, HTTPStatus.OK) response = self.request(self.tempdir_name + '?hi=1') self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) self.assertEqual(response.getheader("Location"), self.tempdir_name + "/?hi=1") def test_html_escape_filename(self): filename = '<test&>.txt' fullpath = os.path.join(self.tempdir, filename) try: open(fullpath, 'w').close() except OSError: raise unittest.SkipTest('Can not create file %s on current file ' 'system' % filename) try: response = self.request(self.base_url + '/') body = self.check_status_and_reason(response, HTTPStatus.OK) enc = response.headers.get_content_charset() finally: os.unlink(fullpath) # avoid affecting test_undecodable_filename self.assertIsNotNone(enc) html_text = '>%s<' % html.escape(filename, quote=False) self.assertIn(html_text.encode(enc), body) cgi_file1 = """\ #!%s print("Content-type: text/html") print() print("Hello World") """ cgi_file2 = """\ #!%s import cgi print("Content-type: text/html") print() form = cgi.FieldStorage() print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"), form.getfirst("bacon"))) """ cgi_file4 = """\ #!%s import os print("Content-type: text/html") print() print(os.environ["%s"]) """ @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, "This test can't be run reliably as root (issue #13308).") class CGIHTTPServerTestCase(BaseTestCase): class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler): pass linesep = os.linesep.encode('ascii') def setUp(self): BaseTestCase.setUp(self) self.cwd = os.getcwd() self.parent_dir = tempfile.mkdtemp() self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin') self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir') os.mkdir(self.cgi_dir) os.mkdir(self.cgi_child_dir) self.nocgi_path = None self.file1_path = None self.file2_path = None self.file3_path = None self.file4_path = None # The shebang line should be pure ASCII: use symlink if possible. # See issue #7668. if support.can_symlink(): self.pythonexe = os.path.join(self.parent_dir, 'python') os.symlink(sys.executable, self.pythonexe) else: self.pythonexe = sys.executable try: # The python executable path is written as the first line of the # CGI Python script. The encoding cookie cannot be used, and so the # path should be encodable to the default script encoding (utf-8) self.pythonexe.encode('utf-8') except UnicodeEncodeError: self.tearDown() self.skipTest("Python executable path is not encodable to utf-8") self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py') with open(self.nocgi_path, 'w') as fp: fp.write(cgi_file1 % self.pythonexe) os.chmod(self.nocgi_path, 0o777) self.file1_path = os.path.join(self.cgi_dir, 'file1.py') with open(self.file1_path, 'w', encoding='utf-8') as file1: file1.write(cgi_file1 % self.pythonexe) os.chmod(self.file1_path, 0o777) self.file2_path = os.path.join(self.cgi_dir, 'file2.py') with open(self.file2_path, 'w', encoding='utf-8') as file2: file2.write(cgi_file2 % self.pythonexe) os.chmod(self.file2_path, 0o777) self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py') with open(self.file3_path, 'w', encoding='utf-8') as file3: file3.write(cgi_file1 % self.pythonexe) os.chmod(self.file3_path, 0o777) self.file4_path = os.path.join(self.cgi_dir, 'file4.py') with open(self.file4_path, 'w', encoding='utf-8') as file4: file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING')) os.chmod(self.file4_path, 0o777) os.chdir(self.parent_dir) def tearDown(self): try: os.chdir(self.cwd) if self.pythonexe != sys.executable: os.remove(self.pythonexe) if self.nocgi_path: os.remove(self.nocgi_path) if self.file1_path: os.remove(self.file1_path) if self.file2_path: os.remove(self.file2_path) if self.file3_path: os.remove(self.file3_path) if self.file4_path: os.remove(self.file4_path) os.rmdir(self.cgi_child_dir) os.rmdir(self.cgi_dir) os.rmdir(self.parent_dir) finally: BaseTestCase.tearDown(self) def test_url_collapse_path(self): # verify tail is the last portion and head is the rest on proper urls test_vectors = { '': '//', '..': IndexError, '/.//..': IndexError, '/': '//', '//': '//', '/\\': '//\\', '/.//': '//', 'cgi-bin/file1.py': '/cgi-bin/file1.py', '/cgi-bin/file1.py': '/cgi-bin/file1.py', 'a': '//a', '/a': '//a', '//a': '//a', './a': '//a', './C:/': '/C:/', '/a/b': '/a/b', '/a/b/': '/a/b/', '/a/b/.': '/a/b/', '/a/b/c/..': '/a/b/', '/a/b/c/../d': '/a/b/d', '/a/b/c/../d/e/../f': '/a/b/d/f', '/a/b/c/../d/e/../../f': '/a/b/f', '/a/b/c/../d/e/.././././..//f': '/a/b/f', '../a/b/c/../d/e/.././././..//f': IndexError, '/a/b/c/../d/e/../../../f': '/a/f', '/a/b/c/../d/e/../../../../f': '//f', '/a/b/c/../d/e/../../../../../f': IndexError, '/a/b/c/../d/e/../../../../f/..': '//', '/a/b/c/../d/e/../../../../f/../.': '//', } for path, expected in test_vectors.items(): if isinstance(expected, type) and issubclass(expected, Exception): self.assertRaises(expected, server._url_collapse_path, path) else: actual = server._url_collapse_path(path) self.assertEqual(expected, actual, msg='path = %r\nGot: %r\nWanted: %r' % (path, actual, expected)) def test_headers_and_content(self): res = self.request('/cgi-bin/file1.py') self.assertEqual( (res.read(), res.getheader('Content-type'), res.status), (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK)) def test_issue19435(self): res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh') self.assertEqual(res.status, HTTPStatus.NOT_FOUND) def test_post(self): params = urllib.parse.urlencode( {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456}) headers = {'Content-type' : 'application/x-www-form-urlencoded'} res = self.request('/cgi-bin/file2.py', 'POST', params, headers) self.assertEqual(res.read(), b'1, python, 123456' + self.linesep) def test_invaliduri(self): res = self.request('/cgi-bin/invalid') res.read() self.assertEqual(res.status, HTTPStatus.NOT_FOUND) def test_authorization(self): headers = {b'Authorization' : b'Basic ' + base64.b64encode(b'username:pass')} res = self.request('/cgi-bin/file1.py', 'GET', headers=headers) self.assertEqual( (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) def test_no_leading_slash(self): # http://bugs.python.org/issue2254 res = self.request('cgi-bin/file1.py') self.assertEqual( (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) def test_os_environ_is_not_altered(self): signature = "Test CGI Server" os.environ['SERVER_SOFTWARE'] = signature res = self.request('/cgi-bin/file1.py') self.assertEqual( (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) self.assertEqual(os.environ['SERVER_SOFTWARE'], signature) def test_urlquote_decoding_in_cgi_check(self): res = self.request('/cgi-bin%2ffile1.py') self.assertEqual( (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) def test_nested_cgi_path_issue21323(self): res = self.request('/cgi-bin/child-dir/file3.py') self.assertEqual( (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) def test_query_with_multiple_question_mark(self): res = self.request('/cgi-bin/file4.py?a=b?c=d') self.assertEqual( (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) def test_query_with_continuous_slashes(self): res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//') self.assertEqual( (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep, 'text/html', HTTPStatus.OK), (res.read(), res.getheader('Content-type'), res.status)) class SocketlessRequestHandler(SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): request = mock.Mock() request.makefile.return_value = BytesIO() super().__init__(request, None, None) self.get_called = False self.protocol_version = "HTTP/1.1" def do_GET(self): self.get_called = True self.send_response(HTTPStatus.OK) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(b'<html><body>Data</body></html>\r\n') def log_message(self, format, *args): pass class RejectingSocketlessRequestHandler(SocketlessRequestHandler): def handle_expect_100(self): self.send_error(HTTPStatus.EXPECTATION_FAILED) return False class AuditableBytesIO: def __init__(self): self.datas = [] def write(self, data): self.datas.append(data) def getData(self): return b''.join(self.datas) @property def numWrites(self): return len(self.datas) class BaseHTTPRequestHandlerTestCase(unittest.TestCase): """Test the functionality of the BaseHTTPServer. Test the support for the Expect 100-continue header. """ HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK') def setUp (self): self.handler = SocketlessRequestHandler() def send_typical_request(self, message): input = BytesIO(message) output = BytesIO() self.handler.rfile = input self.handler.wfile = output self.handler.handle_one_request() output.seek(0) return output.readlines() def verify_get_called(self): self.assertTrue(self.handler.get_called) def verify_expected_headers(self, headers): for fieldName in b'Server: ', b'Date: ', b'Content-Type: ': self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
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_zlib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_zlib.py
import unittest from test import support import binascii import pickle import random import sys from test.support import bigmemtest, _1G, _4G zlib = support.import_module('zlib') requires_Compress_copy = unittest.skipUnless( hasattr(zlib.compressobj(), "copy"), 'requires Compress.copy()') requires_Decompress_copy = unittest.skipUnless( hasattr(zlib.decompressobj(), "copy"), 'requires Decompress.copy()') class VersionTestCase(unittest.TestCase): def test_library_version(self): # Test that the major version of the actual library in use matches the # major version that we were compiled against. We can't guarantee that # the minor versions will match (even on the machine on which the module # was compiled), and the API is stable between minor versions, so # testing only the major versions avoids spurious failures. self.assertEqual(zlib.ZLIB_RUNTIME_VERSION[0], zlib.ZLIB_VERSION[0]) class ChecksumTestCase(unittest.TestCase): # checksum test cases def test_crc32start(self): self.assertEqual(zlib.crc32(b""), zlib.crc32(b"", 0)) self.assertTrue(zlib.crc32(b"abc", 0xffffffff)) def test_crc32empty(self): self.assertEqual(zlib.crc32(b"", 0), 0) self.assertEqual(zlib.crc32(b"", 1), 1) self.assertEqual(zlib.crc32(b"", 432), 432) def test_adler32start(self): self.assertEqual(zlib.adler32(b""), zlib.adler32(b"", 1)) self.assertTrue(zlib.adler32(b"abc", 0xffffffff)) def test_adler32empty(self): self.assertEqual(zlib.adler32(b"", 0), 0) self.assertEqual(zlib.adler32(b"", 1), 1) self.assertEqual(zlib.adler32(b"", 432), 432) def test_penguins(self): self.assertEqual(zlib.crc32(b"penguin", 0), 0x0e5c1a120) self.assertEqual(zlib.crc32(b"penguin", 1), 0x43b6aa94) self.assertEqual(zlib.adler32(b"penguin", 0), 0x0bcf02f6) self.assertEqual(zlib.adler32(b"penguin", 1), 0x0bd602f7) self.assertEqual(zlib.crc32(b"penguin"), zlib.crc32(b"penguin", 0)) self.assertEqual(zlib.adler32(b"penguin"),zlib.adler32(b"penguin",1)) def test_crc32_adler32_unsigned(self): foo = b'abcdefghijklmnop' # explicitly test signed behavior self.assertEqual(zlib.crc32(foo), 2486878355) self.assertEqual(zlib.crc32(b'spam'), 1138425661) self.assertEqual(zlib.adler32(foo+foo), 3573550353) self.assertEqual(zlib.adler32(b'spam'), 72286642) def test_same_as_binascii_crc32(self): foo = b'abcdefghijklmnop' crc = 2486878355 self.assertEqual(binascii.crc32(foo), crc) self.assertEqual(zlib.crc32(foo), crc) self.assertEqual(binascii.crc32(b'spam'), zlib.crc32(b'spam')) # Issue #10276 - check that inputs >=4 GiB are handled correctly. class ChecksumBigBufferTestCase(unittest.TestCase): @bigmemtest(size=_4G + 4, memuse=1, dry_run=False) def test_big_buffer(self, size): data = b"nyan" * (_1G + 1) self.assertEqual(zlib.crc32(data), 1044521549) self.assertEqual(zlib.adler32(data), 2256789997) class ExceptionTestCase(unittest.TestCase): # make sure we generate some expected errors def test_badlevel(self): # specifying compression level out of range causes an error # (but -1 is Z_DEFAULT_COMPRESSION and apparently the zlib # accepts 0 too) self.assertRaises(zlib.error, zlib.compress, b'ERROR', 10) def test_badargs(self): self.assertRaises(TypeError, zlib.adler32) self.assertRaises(TypeError, zlib.crc32) self.assertRaises(TypeError, zlib.compress) self.assertRaises(TypeError, zlib.decompress) for arg in (42, None, '', 'abc', (), []): self.assertRaises(TypeError, zlib.adler32, arg) self.assertRaises(TypeError, zlib.crc32, arg) self.assertRaises(TypeError, zlib.compress, arg) self.assertRaises(TypeError, zlib.decompress, arg) def test_badcompressobj(self): # verify failure on building compress object with bad params self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, 0) # specifying total bits too large causes an error self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, zlib.MAX_WBITS + 1) def test_baddecompressobj(self): # verify failure on building decompress object with bad params self.assertRaises(ValueError, zlib.decompressobj, -1) def test_decompressobj_badflush(self): # verify failure on calling decompressobj.flush with bad params self.assertRaises(ValueError, zlib.decompressobj().flush, 0) self.assertRaises(ValueError, zlib.decompressobj().flush, -1) @support.cpython_only def test_overflow(self): with self.assertRaisesRegex(OverflowError, 'int too large'): zlib.decompress(b'', 15, sys.maxsize + 1) with self.assertRaisesRegex(OverflowError, 'int too large'): zlib.decompressobj().decompress(b'', sys.maxsize + 1) with self.assertRaisesRegex(OverflowError, 'int too large'): zlib.decompressobj().flush(sys.maxsize + 1) class BaseCompressTestCase(object): def check_big_compress_buffer(self, size, compress_func): _1M = 1024 * 1024 # Generate 10 MiB worth of random, and expand it by repeating it. # The assumption is that zlib's memory is not big enough to exploit # such spread out redundancy. data = b''.join([random.getrandbits(8 * _1M).to_bytes(_1M, 'little') for i in range(10)]) data = data * (size // len(data) + 1) try: compress_func(data) finally: # Release memory data = None def check_big_decompress_buffer(self, size, decompress_func): data = b'x' * size try: compressed = zlib.compress(data, 1) finally: # Release memory data = None data = decompress_func(compressed) # Sanity check try: self.assertEqual(len(data), size) self.assertEqual(len(data.strip(b'x')), 0) finally: data = None class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) self.assertEqual(zlib.decompress(x), HAMLET_SCENE) def test_keywords(self): x = zlib.compress(HAMLET_SCENE, level=3) self.assertEqual(zlib.decompress(x), HAMLET_SCENE) with self.assertRaises(TypeError): zlib.compress(data=HAMLET_SCENE, level=3) self.assertEqual(zlib.decompress(x, wbits=zlib.MAX_WBITS, bufsize=zlib.DEF_BUF_SIZE), HAMLET_SCENE) def test_speech128(self): # compress more data data = HAMLET_SCENE * 128 x = zlib.compress(data) self.assertEqual(zlib.compress(bytearray(data)), x) for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) def test_incomplete_stream(self): # A useful error message is given x = zlib.compress(HAMLET_SCENE) self.assertRaisesRegex(zlib.error, "Error -5 while decompressing data: incomplete or truncated stream", zlib.decompress, x[:-1]) # Memory use of the following functions takes into account overallocation @bigmemtest(size=_1G + 1024 * 1024, memuse=3) def test_big_compress_buffer(self, size): compress = lambda s: zlib.compress(s, 1) self.check_big_compress_buffer(size, compress) @bigmemtest(size=_1G + 1024 * 1024, memuse=2) def test_big_decompress_buffer(self, size): self.check_big_decompress_buffer(size, zlib.decompress) @bigmemtest(size=_4G, memuse=1) def test_large_bufsize(self, size): # Test decompress(bufsize) parameter greater than the internal limit data = HAMLET_SCENE * 10 compressed = zlib.compress(data, 1) self.assertEqual(zlib.decompress(compressed, 15, size), data) def test_custom_bufsize(self): data = HAMLET_SCENE * 10 compressed = zlib.compress(data, 1) self.assertEqual(zlib.decompress(compressed, 15, CustomInt()), data) @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform') @bigmemtest(size=_4G + 100, memuse=4) def test_64bit_compress(self, size): data = b'x' * size try: comp = zlib.compress(data, 0) self.assertEqual(zlib.decompress(comp), data) finally: comp = data = None class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects datasrc = HAMLET_SCENE * 128 datazip = zlib.compress(datasrc) # should compress both bytes and bytearray data for data in (datasrc, bytearray(datasrc)): co = zlib.compressobj() x1 = co.compress(data) x2 = co.flush() self.assertRaises(zlib.error, co.flush) # second flush should not work self.assertEqual(x1 + x2, datazip) for v1, v2 in ((x1, x2), (bytearray(x1), bytearray(x2))): dco = zlib.decompressobj() y1 = dco.decompress(v1 + v2) y2 = dco.flush() self.assertEqual(data, y1 + y2) self.assertIsInstance(dco.unconsumed_tail, bytes) self.assertIsInstance(dco.unused_data, bytes) def test_keywords(self): level = 2 method = zlib.DEFLATED wbits = -12 memLevel = 9 strategy = zlib.Z_FILTERED co = zlib.compressobj(level=level, method=method, wbits=wbits, memLevel=memLevel, strategy=strategy, zdict=b"") do = zlib.decompressobj(wbits=wbits, zdict=b"") with self.assertRaises(TypeError): co.compress(data=HAMLET_SCENE) with self.assertRaises(TypeError): do.decompress(data=zlib.compress(HAMLET_SCENE)) x = co.compress(HAMLET_SCENE) + co.flush() y = do.decompress(x, max_length=len(HAMLET_SCENE)) + do.flush() self.assertEqual(HAMLET_SCENE, y) def test_compressoptions(self): # specify lots of options to compressobj() level = 2 method = zlib.DEFLATED wbits = -12 memLevel = 9 strategy = zlib.Z_FILTERED co = zlib.compressobj(level, method, wbits, memLevel, strategy) x1 = co.compress(HAMLET_SCENE) x2 = co.flush() dco = zlib.decompressobj(wbits) y1 = dco.decompress(x1 + x2) y2 = dco.flush() self.assertEqual(HAMLET_SCENE, y1 + y2) def test_compressincremental(self): # compress object in steps, decompress object as one-shot data = HAMLET_SCENE * 128 co = zlib.compressobj() bufs = [] for i in range(0, len(data), 256): bufs.append(co.compress(data[i:i+256])) bufs.append(co.flush()) combuf = b''.join(bufs) dco = zlib.decompressobj() y1 = dco.decompress(b''.join(bufs)) y2 = dco.flush() self.assertEqual(data, y1 + y2) def test_decompinc(self, flush=False, source=None, cx=256, dcx=64): # compress object in steps, decompress object in steps source = source or HAMLET_SCENE data = source * 128 co = zlib.compressobj() bufs = [] for i in range(0, len(data), cx): bufs.append(co.compress(data[i:i+cx])) bufs.append(co.flush()) combuf = b''.join(bufs) decombuf = zlib.decompress(combuf) # Test type of return value self.assertIsInstance(decombuf, bytes) self.assertEqual(data, decombuf) dco = zlib.decompressobj() bufs = [] for i in range(0, len(combuf), dcx): bufs.append(dco.decompress(combuf[i:i+dcx])) self.assertEqual(b'', dco.unconsumed_tail, ######## "(A) uct should be b'': not %d long" % len(dco.unconsumed_tail)) self.assertEqual(b'', dco.unused_data) if flush: bufs.append(dco.flush()) else: while True: chunk = dco.decompress(b'') if chunk: bufs.append(chunk) else: break self.assertEqual(b'', dco.unconsumed_tail, ######## "(B) uct should be b'': not %d long" % len(dco.unconsumed_tail)) self.assertEqual(b'', dco.unused_data) self.assertEqual(data, b''.join(bufs)) # Failure means: "decompressobj with init options failed" def test_decompincflush(self): self.test_decompinc(flush=True) def test_decompimax(self, source=None, cx=256, dcx=64): # compress in steps, decompress in length-restricted steps source = source or HAMLET_SCENE # Check a decompression object with max_length specified data = source * 128 co = zlib.compressobj() bufs = [] for i in range(0, len(data), cx): bufs.append(co.compress(data[i:i+cx])) bufs.append(co.flush()) combuf = b''.join(bufs) self.assertEqual(data, zlib.decompress(combuf), 'compressed data failure') dco = zlib.decompressobj() bufs = [] cb = combuf while cb: #max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, dcx) self.assertFalse(len(chunk) > dcx, 'chunk too big (%d>%d)' % (len(chunk), dcx)) bufs.append(chunk) cb = dco.unconsumed_tail bufs.append(dco.flush()) self.assertEqual(data, b''.join(bufs), 'Wrong data retrieved') def test_decompressmaxlen(self, flush=False): # Check a decompression object with max_length specified data = HAMLET_SCENE * 128 co = zlib.compressobj() bufs = [] for i in range(0, len(data), 256): bufs.append(co.compress(data[i:i+256])) bufs.append(co.flush()) combuf = b''.join(bufs) self.assertEqual(data, zlib.decompress(combuf), 'compressed data failure') dco = zlib.decompressobj() bufs = [] cb = combuf while cb: max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, max_length) self.assertFalse(len(chunk) > max_length, 'chunk too big (%d>%d)' % (len(chunk),max_length)) bufs.append(chunk) cb = dco.unconsumed_tail if flush: bufs.append(dco.flush()) else: while chunk: chunk = dco.decompress(b'', max_length) self.assertFalse(len(chunk) > max_length, 'chunk too big (%d>%d)' % (len(chunk),max_length)) bufs.append(chunk) self.assertEqual(data, b''.join(bufs), 'Wrong data retrieved') def test_decompressmaxlenflush(self): self.test_decompressmaxlen(flush=True) def test_maxlenmisc(self): # Misc tests of max_length dco = zlib.decompressobj() self.assertRaises(ValueError, dco.decompress, b"", -1) self.assertEqual(b'', dco.unconsumed_tail) def test_maxlen_large(self): # Sizes up to sys.maxsize should be accepted, although zlib is # internally limited to expressing sizes with unsigned int data = HAMLET_SCENE * 10 self.assertGreater(len(data), zlib.DEF_BUF_SIZE) compressed = zlib.compress(data, 1) dco = zlib.decompressobj() self.assertEqual(dco.decompress(compressed, sys.maxsize), data) def test_maxlen_custom(self): data = HAMLET_SCENE * 10 compressed = zlib.compress(data, 1) dco = zlib.decompressobj() self.assertEqual(dco.decompress(compressed, CustomInt()), data[:100]) def test_clear_unconsumed_tail(self): # Issue #12050: calling decompress() without providing max_length # should clear the unconsumed_tail attribute. cdata = b"x\x9cKLJ\x06\x00\x02M\x01" # "abc" dco = zlib.decompressobj() ddata = dco.decompress(cdata, 1) ddata += dco.decompress(dco.unconsumed_tail) self.assertEqual(dco.unconsumed_tail, b"") def test_flushes(self): # Test flush() with the various options, using all the # different levels in order to provide more variations. sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH', 'Z_PARTIAL_FLUSH'] ver = tuple(int(v) for v in zlib.ZLIB_RUNTIME_VERSION.split('.')) # Z_BLOCK has a known failure prior to 1.2.5.3 if ver >= (1, 2, 5, 3): sync_opt.append('Z_BLOCK') sync_opt = [getattr(zlib, opt) for opt in sync_opt if hasattr(zlib, opt)] data = HAMLET_SCENE * 8 for sync in sync_opt: for level in range(10): try: obj = zlib.compressobj( level ) a = obj.compress( data[:3000] ) b = obj.flush( sync ) c = obj.compress( data[3000:] ) d = obj.flush() except: print("Error for flush mode={}, level={}" .format(sync, level)) raise self.assertEqual(zlib.decompress(b''.join([a,b,c,d])), data, ("Decompress failed: flush " "mode=%i, level=%i") % (sync, level)) del obj @unittest.skipUnless(hasattr(zlib, 'Z_SYNC_FLUSH'), 'requires zlib.Z_SYNC_FLUSH') def test_odd_flush(self): # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1 import random # Testing on 17K of "random" data # Create compressor and decompressor objects co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) dco = zlib.decompressobj() # Try 17K of data # generate random data stream try: # In 2.3 and later, WichmannHill is the RNG of the bug report gen = random.WichmannHill() except AttributeError: try: # 2.2 called it Random gen = random.Random() except AttributeError: # others might simply have a single RNG gen = random gen.seed(1) data = genblock(1, 17 * 1024, generator=gen) # compress, sync-flush, and decompress first = co.compress(data) second = co.flush(zlib.Z_SYNC_FLUSH) expanded = dco.decompress(first + second) # if decompressed data is different from the input data, choke. self.assertEqual(expanded, data, "17K random source doesn't match") def test_empty_flush(self): # Test that calling .flush() on unused objects works. # (Bug #1083110 -- calling .flush() on decompress objects # caused a core dump.) co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) self.assertTrue(co.flush()) # Returns a zlib header dco = zlib.decompressobj() self.assertEqual(dco.flush(), b"") # Returns nothing def test_dictionary(self): h = HAMLET_SCENE # Build a simulated dictionary out of the words in HAMLET. words = h.split() random.shuffle(words) zdict = b''.join(words) # Use it to compress HAMLET. co = zlib.compressobj(zdict=zdict) cd = co.compress(h) + co.flush() # Verify that it will decompress with the dictionary. dco = zlib.decompressobj(zdict=zdict) self.assertEqual(dco.decompress(cd) + dco.flush(), h) # Verify that it fails when not given the dictionary. dco = zlib.decompressobj() self.assertRaises(zlib.error, dco.decompress, cd) def test_dictionary_streaming(self): # This simulates the reuse of a compressor object for compressing # several separate data streams. co = zlib.compressobj(zdict=HAMLET_SCENE) do = zlib.decompressobj(zdict=HAMLET_SCENE) piece = HAMLET_SCENE[1000:1500] d0 = co.compress(piece) + co.flush(zlib.Z_SYNC_FLUSH) d1 = co.compress(piece[100:]) + co.flush(zlib.Z_SYNC_FLUSH) d2 = co.compress(piece[:-100]) + co.flush(zlib.Z_SYNC_FLUSH) self.assertEqual(do.decompress(d0), piece) self.assertEqual(do.decompress(d1), piece[100:]) self.assertEqual(do.decompress(d2), piece[:-100]) def test_decompress_incomplete_stream(self): # This is 'foo', deflated x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # For the record self.assertEqual(zlib.decompress(x), b'foo') self.assertRaises(zlib.error, zlib.decompress, x[:-5]) # Omitting the stream end works with decompressor objects # (see issue #8672). dco = zlib.decompressobj() y = dco.decompress(x[:-5]) y += dco.flush() self.assertEqual(y, b'foo') def test_decompress_eof(self): x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo' dco = zlib.decompressobj() self.assertFalse(dco.eof) dco.decompress(x[:-5]) self.assertFalse(dco.eof) dco.decompress(x[-5:]) self.assertTrue(dco.eof) dco.flush() self.assertTrue(dco.eof) def test_decompress_eof_incomplete_stream(self): x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo' dco = zlib.decompressobj() self.assertFalse(dco.eof) dco.decompress(x[:-5]) self.assertFalse(dco.eof) dco.flush() self.assertFalse(dco.eof) def test_decompress_unused_data(self): # Repeated calls to decompress() after EOF should accumulate data in # dco.unused_data, instead of just storing the arg to the last call. source = b'abcdefghijklmnopqrstuvwxyz' remainder = b'0123456789' y = zlib.compress(source) x = y + remainder for maxlen in 0, 1000: for step in 1, 2, len(y), len(x): dco = zlib.decompressobj() data = b'' for i in range(0, len(x), step): if i < len(y): self.assertEqual(dco.unused_data, b'') if maxlen == 0: data += dco.decompress(x[i : i + step]) self.assertEqual(dco.unconsumed_tail, b'') else: data += dco.decompress( dco.unconsumed_tail + x[i : i + step], maxlen) data += dco.flush() self.assertTrue(dco.eof) self.assertEqual(data, source) self.assertEqual(dco.unconsumed_tail, b'') self.assertEqual(dco.unused_data, remainder) # issue27164 def test_decompress_raw_with_dictionary(self): zdict = b'abcdefghijklmnopqrstuvwxyz' co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=zdict) comp = co.compress(zdict) + co.flush() dco = zlib.decompressobj(wbits=-zlib.MAX_WBITS, zdict=zdict) uncomp = dco.decompress(comp) + dco.flush() self.assertEqual(zdict, uncomp) def test_flush_with_freed_input(self): # Issue #16411: decompressor accesses input to last decompress() call # in flush(), even if this object has been freed in the meanwhile. input1 = b'abcdefghijklmnopqrstuvwxyz' input2 = b'QWERTYUIOPASDFGHJKLZXCVBNM' data = zlib.compress(input1) dco = zlib.decompressobj() dco.decompress(data, 1) del data data = zlib.compress(input2) self.assertEqual(dco.flush(), input1[1:]) @bigmemtest(size=_4G, memuse=1) def test_flush_large_length(self, size): # Test flush(length) parameter greater than internal limit UINT_MAX input = HAMLET_SCENE * 10 data = zlib.compress(input, 1) dco = zlib.decompressobj() dco.decompress(data, 1) self.assertEqual(dco.flush(size), input[1:]) def test_flush_custom_length(self): input = HAMLET_SCENE * 10 data = zlib.compress(input, 1) dco = zlib.decompressobj() dco.decompress(data, 1) self.assertEqual(dco.flush(CustomInt()), input[1:]) @requires_Compress_copy def test_compresscopy(self): # Test copying a compression object data0 = HAMLET_SCENE data1 = bytes(str(HAMLET_SCENE, "ascii").swapcase(), "ascii") c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) bufs0 = [] bufs0.append(c0.compress(data0)) c1 = c0.copy() bufs1 = bufs0[:] bufs0.append(c0.compress(data0)) bufs0.append(c0.flush()) s0 = b''.join(bufs0) bufs1.append(c1.compress(data1)) bufs1.append(c1.flush()) s1 = b''.join(bufs1) self.assertEqual(zlib.decompress(s0),data0+data0) self.assertEqual(zlib.decompress(s1),data0+data1) @requires_Compress_copy def test_badcompresscopy(self): # Test copying a compression object in an inconsistent state c = zlib.compressobj() c.compress(HAMLET_SCENE) c.flush() self.assertRaises(ValueError, c.copy) @requires_Decompress_copy def test_decompresscopy(self): # Test copying a decompression object data = HAMLET_SCENE comp = zlib.compress(data) # Test type of return value self.assertIsInstance(comp, bytes) d0 = zlib.decompressobj() bufs0 = [] bufs0.append(d0.decompress(comp[:32])) d1 = d0.copy() bufs1 = bufs0[:] bufs0.append(d0.decompress(comp[32:])) s0 = b''.join(bufs0) bufs1.append(d1.decompress(comp[32:])) s1 = b''.join(bufs1) self.assertEqual(s0,s1) self.assertEqual(s0,data) @requires_Decompress_copy def test_baddecompresscopy(self): # Test copying a compression object in an inconsistent state data = zlib.compress(HAMLET_SCENE) d = zlib.decompressobj() d.decompress(data) d.flush() self.assertRaises(ValueError, d.copy) def test_compresspickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises((TypeError, pickle.PicklingError)): pickle.dumps(zlib.compressobj(zlib.Z_BEST_COMPRESSION), proto) def test_decompresspickle(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises((TypeError, pickle.PicklingError)): pickle.dumps(zlib.decompressobj(), proto) # Memory use of the following functions takes into account overallocation @bigmemtest(size=_1G + 1024 * 1024, memuse=3) def test_big_compress_buffer(self, size): c = zlib.compressobj(1) compress = lambda s: c.compress(s) + c.flush() self.check_big_compress_buffer(size, compress) @bigmemtest(size=_1G + 1024 * 1024, memuse=2) def test_big_decompress_buffer(self, size): d = zlib.decompressobj() decompress = lambda s: d.decompress(s) + d.flush() self.check_big_decompress_buffer(size, decompress) @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform') @bigmemtest(size=_4G + 100, memuse=4) def test_64bit_compress(self, size): data = b'x' * size co = zlib.compressobj(0) do = zlib.decompressobj() try: comp = co.compress(data) + co.flush() uncomp = do.decompress(comp) + do.flush() self.assertEqual(uncomp, data) finally: comp = uncomp = data = None @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform') @bigmemtest(size=_4G + 100, memuse=3) def test_large_unused_data(self, size): data = b'abcdefghijklmnop' unused = b'x' * size comp = zlib.compress(data) + unused do = zlib.decompressobj() try: uncomp = do.decompress(comp) + do.flush() self.assertEqual(unused, do.unused_data) self.assertEqual(uncomp, data) finally: unused = comp = do = None @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform') @bigmemtest(size=_4G + 100, memuse=5) def test_large_unconsumed_tail(self, size): data = b'x' * size do = zlib.decompressobj() try: comp = zlib.compress(data, 0) uncomp = do.decompress(comp, 1) + do.flush() self.assertEqual(uncomp, data) self.assertEqual(do.unconsumed_tail, b'') finally: comp = uncomp = data = None def test_wbits(self): # wbits=0 only supported since zlib v1.2.3.5 # Register "1.2.3" as "1.2.3.0" # or "1.2.0-linux","1.2.0.f","1.2.0.f-linux" v = zlib.ZLIB_RUNTIME_VERSION.split('-', 1)[0].split('.') if len(v) < 4: v.append('0') elif not v[-1].isnumeric(): v[-1] = '0' v = tuple(map(int, v)) supports_wbits_0 = v >= (1, 2, 3, 5) co = zlib.compressobj(level=1, wbits=15) zlib15 = co.compress(HAMLET_SCENE) + co.flush() self.assertEqual(zlib.decompress(zlib15, 15), HAMLET_SCENE) if supports_wbits_0: self.assertEqual(zlib.decompress(zlib15, 0), HAMLET_SCENE) self.assertEqual(zlib.decompress(zlib15, 32 + 15), HAMLET_SCENE) with self.assertRaisesRegex(zlib.error, 'invalid window size'): zlib.decompress(zlib15, 14) dco = zlib.decompressobj(wbits=32 + 15) self.assertEqual(dco.decompress(zlib15), HAMLET_SCENE) dco = zlib.decompressobj(wbits=14) with self.assertRaisesRegex(zlib.error, 'invalid window size'): dco.decompress(zlib15) co = zlib.compressobj(level=1, wbits=9) zlib9 = co.compress(HAMLET_SCENE) + co.flush() self.assertEqual(zlib.decompress(zlib9, 9), HAMLET_SCENE) self.assertEqual(zlib.decompress(zlib9, 15), HAMLET_SCENE) if supports_wbits_0: self.assertEqual(zlib.decompress(zlib9, 0), HAMLET_SCENE) self.assertEqual(zlib.decompress(zlib9, 32 + 9), HAMLET_SCENE) dco = zlib.decompressobj(wbits=32 + 9) self.assertEqual(dco.decompress(zlib9), HAMLET_SCENE) co = zlib.compressobj(level=1, wbits=-15) deflate15 = co.compress(HAMLET_SCENE) + co.flush() self.assertEqual(zlib.decompress(deflate15, -15), HAMLET_SCENE) dco = zlib.decompressobj(wbits=-15) self.assertEqual(dco.decompress(deflate15), HAMLET_SCENE) co = zlib.compressobj(level=1, wbits=-9) deflate9 = co.compress(HAMLET_SCENE) + co.flush() self.assertEqual(zlib.decompress(deflate9, -9), HAMLET_SCENE) self.assertEqual(zlib.decompress(deflate9, -15), HAMLET_SCENE) dco = zlib.decompressobj(wbits=-9) self.assertEqual(dco.decompress(deflate9), HAMLET_SCENE) co = zlib.compressobj(level=1, wbits=16 + 15) gzip = co.compress(HAMLET_SCENE) + co.flush() self.assertEqual(zlib.decompress(gzip, 16 + 15), HAMLET_SCENE) self.assertEqual(zlib.decompress(gzip, 32 + 15), HAMLET_SCENE) dco = zlib.decompressobj(32 + 15) self.assertEqual(dco.decompress(gzip), HAMLET_SCENE) def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: generator.seed(seed) randint = generator.randint if length < step or step < 2: step = length blocks = bytes() for i in range(0, length, step): blocks += bytes(randint(0, 255) for x in range(step)) return blocks def choose_lines(source, number, seed=None, generator=random): """Return a list of number lines randomly chosen from the source""" if seed is not None: generator.seed(seed) sources = source.split('\n')
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_heapq.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_heapq.py
"""Unittests for heapq.""" import random import unittest from test import support from unittest import TestCase, skipUnless from operator import itemgetter py_heapq = support.import_fresh_module('heapq', blocked=['_heapq']) c_heapq = support.import_fresh_module('heapq', fresh=['_heapq']) # _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when # _heapq is imported, so check them there func_names = ['heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace', '_heappop_max', '_heapreplace_max', '_heapify_max'] class TestModules(TestCase): def test_py_functions(self): for fname in func_names: self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq') @skipUnless(c_heapq, 'requires _heapq') def test_c_functions(self): for fname in func_names: self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq') class TestHeap: def test_push_pop(self): # 1) Push 256 random numbers and pop them off, verifying all's OK. heap = [] data = [] self.check_invariant(heap) for i in range(256): item = random.random() data.append(item) self.module.heappush(heap, item) self.check_invariant(heap) results = [] while heap: item = self.module.heappop(heap) self.check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() self.assertEqual(data_sorted, results) # 2) Check that the invariant holds for a sorted array self.check_invariant(results) self.assertRaises(TypeError, self.module.heappush, []) try: self.assertRaises(TypeError, self.module.heappush, None, None) self.assertRaises(TypeError, self.module.heappop, None) except AttributeError: pass def check_invariant(self, heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 self.assertTrue(heap[parentpos] <= item) def test_heapify(self): for size in list(range(30)) + [20000]: heap = [random.random() for dummy in range(size)] self.module.heapify(heap) self.check_invariant(heap) self.assertRaises(TypeError, self.module.heapify, None) def test_naive_nbest(self): data = [random.randrange(2000) for i in range(1000)] heap = [] for item in data: self.module.heappush(heap, item) if len(heap) > 10: self.module.heappop(heap) heap.sort() self.assertEqual(heap, sorted(data)[-10:]) def heapiter(self, heap): # An iterator returning a heap's elements, smallest-first. try: while 1: yield self.module.heappop(heap) except IndexError: pass def test_nbest(self): # Less-naive "N-best" algorithm, much faster (if len(data) is big # enough <wink>) than sorting all of data. However, if we had a max # heap instead of a min heap, it could go faster still via # heapify'ing all of data (linear time), then doing 10 heappops # (10 log-time steps). data = [random.randrange(2000) for i in range(1000)] heap = data[:10] self.module.heapify(heap) for item in data[10:]: if item > heap[0]: # this gets rarer the longer we run self.module.heapreplace(heap, item) self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:]) self.assertRaises(TypeError, self.module.heapreplace, None) self.assertRaises(TypeError, self.module.heapreplace, None, None) self.assertRaises(IndexError, self.module.heapreplace, [], None) def test_nbest_with_pushpop(self): data = [random.randrange(2000) for i in range(1000)] heap = data[:10] self.module.heapify(heap) for item in data[10:]: self.module.heappushpop(heap, item) self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:]) self.assertEqual(self.module.heappushpop([], 'x'), 'x') def test_heappushpop(self): h = [] x = self.module.heappushpop(h, 10) self.assertEqual((h, x), ([], 10)) h = [10] x = self.module.heappushpop(h, 10.0) self.assertEqual((h, x), ([10], 10.0)) self.assertEqual(type(h[0]), int) self.assertEqual(type(x), float) h = [10]; x = self.module.heappushpop(h, 9) self.assertEqual((h, x), ([10], 9)) h = [10]; x = self.module.heappushpop(h, 11) self.assertEqual((h, x), ([11], 10)) def test_heapsort(self): # Exercise everything with repeated heapsort checks for trial in range(100): size = random.randrange(50) data = [random.randrange(25) for i in range(size)] if trial & 1: # Half of the time, use heapify heap = data[:] self.module.heapify(heap) else: # The rest of the time, use heappush heap = [] for item in data: self.module.heappush(heap, item) heap_sorted = [self.module.heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) def test_merge(self): inputs = [] for i in range(random.randrange(25)): row = [] for j in range(random.randrange(100)): tup = random.choice('ABC'), random.randrange(-500, 500) row.append(tup) inputs.append(row) for key in [None, itemgetter(0), itemgetter(1), itemgetter(1, 0)]: for reverse in [False, True]: seqs = [] for seq in inputs: seqs.append(sorted(seq, key=key, reverse=reverse)) self.assertEqual(sorted(chain(*inputs), key=key, reverse=reverse), list(self.module.merge(*seqs, key=key, reverse=reverse))) self.assertEqual(list(self.module.merge()), []) def test_merge_does_not_suppress_index_error(self): # Issue 19018: Heapq.merge suppresses IndexError from user generator def iterable(): s = list(range(10)) for i in range(20): yield s[i] # IndexError when i > 10 with self.assertRaises(IndexError): list(self.module.merge(iterable(), iterable())) def test_merge_stability(self): class Int(int): pass inputs = [[], [], [], []] for i in range(20000): stream = random.randrange(4) x = random.randrange(500) obj = Int(x) obj.pair = (x, stream) inputs[stream].append(obj) for stream in inputs: stream.sort() result = [i.pair for i in self.module.merge(*inputs)] self.assertEqual(result, sorted(result)) def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): self.assertEqual(list(self.module.nsmallest(n, data)), sorted(data)[:n]) self.assertEqual(list(self.module.nsmallest(n, data, key=f)), sorted(data, key=f)[:n]) def test_nlargest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): self.assertEqual(list(self.module.nlargest(n, data)), sorted(data, reverse=True)[:n]) self.assertEqual(list(self.module.nlargest(n, data, key=f)), sorted(data, key=f, reverse=True)[:n]) def test_comparison_operator(self): # Issue 3051: Make sure heapq works with both __lt__ # For python 3.0, __le__ alone is not enough def hsort(data, comp): data = [comp(x) for x in data] self.module.heapify(data) return [self.module.heappop(data).x for i in range(len(data))] class LT: def __init__(self, x): self.x = x def __lt__(self, other): return self.x > other.x class LE: def __init__(self, x): self.x = x def __le__(self, other): return self.x >= other.x data = [random.random() for i in range(100)] target = sorted(data, reverse=True) self.assertEqual(hsort(data, LT), target) self.assertRaises(TypeError, data, LE) class TestHeapPython(TestHeap, TestCase): module = py_heapq @skipUnless(c_heapq, 'requires _heapq') class TestHeapC(TestHeap, TestCase): module = c_heapq #============================================================================== class LenOnly: "Dummy sequence class defining __len__ but not __getitem__." def __len__(self): return 10 class GetOnly: "Dummy sequence class defining __getitem__ but not __len__." def __getitem__(self, ndx): return 10 class CmpErr: "Dummy element that always raises an error during comparison" def __eq__(self, other): raise ZeroDivisionError __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__ def R(seqn): 'Regular generator' for i in seqn: yield i class G: 'Sequence using __getitem__' def __init__(self, seqn): self.seqn = seqn def __getitem__(self, i): return self.seqn[i] class I: 'Sequence using iterator protocol' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class Ig: 'Sequence using iterator protocol defined with a generator' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): for val in self.seqn: yield val class X: 'Missing __getitem__ and __iter__' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self class E: 'Test propagation of exceptions' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def __next__(self): 3 // 0 class S: 'Test immediate stop' def __init__(self, seqn): pass def __iter__(self): return self def __next__(self): raise StopIteration from itertools import chain def L(seqn): 'Test multiple tiers of iterators' return chain(map(lambda x:x, R(Ig(G(seqn))))) class SideEffectLT: def __init__(self, value, heap): self.value = value self.heap = heap def __lt__(self, other): self.heap[:] = [] return self.value < other.value class TestErrorHandling: def test_non_sequence(self): for f in (self.module.heapify, self.module.heappop): self.assertRaises((TypeError, AttributeError), f, 10) for f in (self.module.heappush, self.module.heapreplace, self.module.nlargest, self.module.nsmallest): self.assertRaises((TypeError, AttributeError), f, 10, 10) def test_len_only(self): for f in (self.module.heapify, self.module.heappop): self.assertRaises((TypeError, AttributeError), f, LenOnly()) for f in (self.module.heappush, self.module.heapreplace): self.assertRaises((TypeError, AttributeError), f, LenOnly(), 10) for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 2, LenOnly()) def test_get_only(self): for f in (self.module.heapify, self.module.heappop): self.assertRaises(TypeError, f, GetOnly()) for f in (self.module.heappush, self.module.heapreplace): self.assertRaises(TypeError, f, GetOnly(), 10) for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(TypeError, f, 2, GetOnly()) def test_get_only(self): seq = [CmpErr(), CmpErr(), CmpErr()] for f in (self.module.heapify, self.module.heappop): self.assertRaises(ZeroDivisionError, f, seq) for f in (self.module.heappush, self.module.heapreplace): self.assertRaises(ZeroDivisionError, f, seq, 10) for f in (self.module.nlargest, self.module.nsmallest): self.assertRaises(ZeroDivisionError, f, 2, seq) def test_arg_parsing(self): for f in (self.module.heapify, self.module.heappop, self.module.heappush, self.module.heapreplace, self.module.nlargest, self.module.nsmallest): self.assertRaises((TypeError, AttributeError), f, 10) def test_iterable_args(self): for f in (self.module.nlargest, self.module.nsmallest): for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)): for g in (G, I, Ig, L, R): self.assertEqual(list(f(2, g(s))), list(f(2,s))) self.assertEqual(list(f(2, S(s))), []) self.assertRaises(TypeError, f, 2, X(s)) self.assertRaises(TypeError, f, 2, N(s)) self.assertRaises(ZeroDivisionError, f, 2, E(s)) # Issue #17278: the heap may change size while it's being walked. def test_heappush_mutating_heap(self): heap = [] heap.extend(SideEffectLT(i, heap) for i in range(200)) # Python version raises IndexError, C version RuntimeError with self.assertRaises((IndexError, RuntimeError)): self.module.heappush(heap, SideEffectLT(5, heap)) def test_heappop_mutating_heap(self): heap = [] heap.extend(SideEffectLT(i, heap) for i in range(200)) # Python version raises IndexError, C version RuntimeError with self.assertRaises((IndexError, RuntimeError)): self.module.heappop(heap) def test_comparison_operator_modifiying_heap(self): # See bpo-39421: Strong references need to be taken # when comparing objects as they can alter the heap class EvilClass(int): def __lt__(self, o): heap.clear() return NotImplemented heap = [] self.module.heappush(heap, EvilClass(0)) self.assertRaises(IndexError, self.module.heappushpop, heap, 1) def test_comparison_operator_modifiying_heap_two_heaps(self): class h(int): def __lt__(self, o): list2.clear() return NotImplemented class g(int): def __lt__(self, o): list1.clear() return NotImplemented list1, list2 = [], [] self.module.heappush(list1, h(0)) self.module.heappush(list2, g(0)) self.assertRaises((IndexError, RuntimeError), self.module.heappush, list1, g(1)) self.assertRaises((IndexError, RuntimeError), self.module.heappush, list2, h(1)) class TestErrorHandlingPython(TestErrorHandling, TestCase): module = py_heapq @skipUnless(c_heapq, 'requires _heapq') class TestErrorHandlingC(TestErrorHandling, TestCase): module = c_heapq 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_decimal.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py
# Copyright (c) 2004 Python Software Foundation. # All rights reserved. # Written by Eric Price <eprice at tjhsst.edu> # and Facundo Batista <facundo at taniquetil.com.ar> # and Raymond Hettinger <python at rcn.com> # and Aahz (aahz at pobox.com) # and Tim Peters """ These are the test cases for the Decimal module. There are two groups of tests, Arithmetic and Behaviour. The former test the Decimal arithmetic using the tests provided by Mike Cowlishaw. The latter test the pythonic behaviour according to PEP 327. Cowlishaw's tests can be downloaded from: http://speleotrove.com/decimal/dectest.zip This test module can be called from command line with one parameter (Arithmetic or Behaviour) to test each part, or without parameter to test both parts. If you're working through IDLE, you can import this test module and call test_main() with the corresponding argument. """ import math import os, sys import operator import warnings import pickle, copy import unittest import numbers import locale from test.support import (run_unittest, run_doctest, is_resource_enabled, requires_IEEE_754, requires_docstrings) from test.support import (import_fresh_module, TestFailed, run_with_locale, cpython_only) import random import inspect import threading C = import_fresh_module('decimal', fresh=['_decimal']) P = import_fresh_module('decimal', blocked=['_decimal']) orig_sys_decimal = sys.modules['decimal'] # fractions module must import the correct decimal module. cfractions = import_fresh_module('fractions', fresh=['fractions']) sys.modules['decimal'] = P pfractions = import_fresh_module('fractions', fresh=['fractions']) sys.modules['decimal'] = C fractions = {C:cfractions, P:pfractions} sys.modules['decimal'] = orig_sys_decimal # Useful Test Constant Signals = { C: tuple(C.getcontext().flags.keys()) if C else None, P: tuple(P.getcontext().flags.keys()) } # Signals ordered with respect to precedence: when an operation # produces multiple signals, signals occurring later in the list # should be handled before those occurring earlier in the list. OrderedSignals = { C: [C.Clamped, C.Rounded, C.Inexact, C.Subnormal, C.Underflow, C.Overflow, C.DivisionByZero, C.InvalidOperation, C.FloatOperation] if C else None, P: [P.Clamped, P.Rounded, P.Inexact, P.Subnormal, P.Underflow, P.Overflow, P.DivisionByZero, P.InvalidOperation, P.FloatOperation] } def assert_signals(cls, context, attr, expected): d = getattr(context, attr) cls.assertTrue(all(d[s] if s in expected else not d[s] for s in d)) ROUND_UP = P.ROUND_UP ROUND_DOWN = P.ROUND_DOWN ROUND_CEILING = P.ROUND_CEILING ROUND_FLOOR = P.ROUND_FLOOR ROUND_HALF_UP = P.ROUND_HALF_UP ROUND_HALF_DOWN = P.ROUND_HALF_DOWN ROUND_HALF_EVEN = P.ROUND_HALF_EVEN ROUND_05UP = P.ROUND_05UP RoundingModes = [ ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_05UP ] # Tests are built around these assumed context defaults. # test_main() restores the original context. ORIGINAL_CONTEXT = { C: C.getcontext().copy() if C else None, P: P.getcontext().copy() } def init(m): if not m: return DefaultTestContext = m.Context( prec=9, rounding=ROUND_HALF_EVEN, traps=dict.fromkeys(Signals[m], 0) ) m.setcontext(DefaultTestContext) TESTDATADIR = 'decimaltestdata' if __name__ == '__main__': file = sys.argv[0] else: file = __file__ testdir = os.path.dirname(file) or os.curdir directory = testdir + os.sep + TESTDATADIR + os.sep skip_expected = not os.path.isdir(directory) # Make sure it actually raises errors when not expected and caught in flags # Slower, since it runs some things several times. EXTENDEDERRORTEST = False # Test extra functionality in the C version (-DEXTRA_FUNCTIONALITY). EXTRA_FUNCTIONALITY = True if hasattr(C, 'DecClamped') else False requires_extra_functionality = unittest.skipUnless( EXTRA_FUNCTIONALITY, "test requires build with -DEXTRA_FUNCTIONALITY") skip_if_extra_functionality = unittest.skipIf( EXTRA_FUNCTIONALITY, "test requires regular build") class IBMTestCases(unittest.TestCase): """Class which tests the Decimal class against the IBM test cases.""" def setUp(self): self.context = self.decimal.Context() self.readcontext = self.decimal.Context() self.ignore_list = ['#'] # List of individual .decTest test ids that correspond to tests that # we're skipping for one reason or another. self.skipped_test_ids = set([ # Skip implementation-specific scaleb tests. 'scbx164', 'scbx165', # For some operations (currently exp, ln, log10, power), the decNumber # reference implementation imposes additional restrictions on the context # and operands. These restrictions are not part of the specification; # however, the effect of these restrictions does show up in some of the # testcases. We skip testcases that violate these restrictions, since # Decimal behaves differently from decNumber for these testcases so these # testcases would otherwise fail. 'expx901', 'expx902', 'expx903', 'expx905', 'lnx901', 'lnx902', 'lnx903', 'lnx905', 'logx901', 'logx902', 'logx903', 'logx905', 'powx1183', 'powx1184', 'powx4001', 'powx4002', 'powx4003', 'powx4005', 'powx4008', 'powx4010', 'powx4012', 'powx4014', ]) if self.decimal == C: # status has additional Subnormal, Underflow self.skipped_test_ids.add('pwsx803') self.skipped_test_ids.add('pwsx805') # Correct rounding (skipped for decNumber, too) self.skipped_test_ids.add('powx4302') self.skipped_test_ids.add('powx4303') self.skipped_test_ids.add('powx4342') self.skipped_test_ids.add('powx4343') # http://bugs.python.org/issue7049 self.skipped_test_ids.add('pwmx325') self.skipped_test_ids.add('pwmx326') # Map test directives to setter functions. self.ChangeDict = {'precision' : self.change_precision, 'rounding' : self.change_rounding_method, 'maxexponent' : self.change_max_exponent, 'minexponent' : self.change_min_exponent, 'clamp' : self.change_clamp} # Name adapter to be able to change the Decimal and Context # interface without changing the test files from Cowlishaw. self.NameAdapter = {'and':'logical_and', 'apply':'_apply', 'class':'number_class', 'comparesig':'compare_signal', 'comparetotal':'compare_total', 'comparetotmag':'compare_total_mag', 'copy':'copy_decimal', 'copyabs':'copy_abs', 'copynegate':'copy_negate', 'copysign':'copy_sign', 'divideint':'divide_int', 'invert':'logical_invert', 'iscanonical':'is_canonical', 'isfinite':'is_finite', 'isinfinite':'is_infinite', 'isnan':'is_nan', 'isnormal':'is_normal', 'isqnan':'is_qnan', 'issigned':'is_signed', 'issnan':'is_snan', 'issubnormal':'is_subnormal', 'iszero':'is_zero', 'maxmag':'max_mag', 'minmag':'min_mag', 'nextminus':'next_minus', 'nextplus':'next_plus', 'nexttoward':'next_toward', 'or':'logical_or', 'reduce':'normalize', 'remaindernear':'remainder_near', 'samequantum':'same_quantum', 'squareroot':'sqrt', 'toeng':'to_eng_string', 'tointegral':'to_integral_value', 'tointegralx':'to_integral_exact', 'tosci':'to_sci_string', 'xor':'logical_xor'} # Map test-case names to roundings. self.RoundingDict = {'ceiling' : ROUND_CEILING, 'down' : ROUND_DOWN, 'floor' : ROUND_FLOOR, 'half_down' : ROUND_HALF_DOWN, 'half_even' : ROUND_HALF_EVEN, 'half_up' : ROUND_HALF_UP, 'up' : ROUND_UP, '05up' : ROUND_05UP} # Map the test cases' error names to the actual errors. self.ErrorNames = {'clamped' : self.decimal.Clamped, 'conversion_syntax' : self.decimal.InvalidOperation, 'division_by_zero' : self.decimal.DivisionByZero, 'division_impossible' : self.decimal.InvalidOperation, 'division_undefined' : self.decimal.InvalidOperation, 'inexact' : self.decimal.Inexact, 'invalid_context' : self.decimal.InvalidOperation, 'invalid_operation' : self.decimal.InvalidOperation, 'overflow' : self.decimal.Overflow, 'rounded' : self.decimal.Rounded, 'subnormal' : self.decimal.Subnormal, 'underflow' : self.decimal.Underflow} # The following functions return True/False rather than a # Decimal instance. self.LogicalFunctions = ('is_canonical', 'is_finite', 'is_infinite', 'is_nan', 'is_normal', 'is_qnan', 'is_signed', 'is_snan', 'is_subnormal', 'is_zero', 'same_quantum') def read_unlimited(self, v, context): """Work around the limitations of the 32-bit _decimal version. The guaranteed maximum values for prec, Emax etc. are 425000000, but higher values usually work, except for rare corner cases. In particular, all of the IBM tests pass with maximum values of 1070000000.""" if self.decimal == C and self.decimal.MAX_EMAX == 425000000: self.readcontext._unsafe_setprec(1070000000) self.readcontext._unsafe_setemax(1070000000) self.readcontext._unsafe_setemin(-1070000000) return self.readcontext.create_decimal(v) else: return self.decimal.Decimal(v, context) def eval_file(self, file): global skip_expected if skip_expected: raise unittest.SkipTest with open(file) as f: for line in f: line = line.replace('\r\n', '').replace('\n', '') #print line try: t = self.eval_line(line) except self.decimal.DecimalException as exception: #Exception raised where there shouldn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) def eval_line(self, s): if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'): s = (s.split('->')[0] + '->' + s.split('->')[1].split('--')[0]).strip() else: s = s.split('--')[0].strip() for ignore in self.ignore_list: if s.find(ignore) >= 0: #print s.split()[0], 'NotImplemented--', ignore return if not s: return elif ':' in s: return self.eval_directive(s) else: return self.eval_equation(s) def eval_directive(self, s): funct, value = (x.strip().lower() for x in s.split(':')) if funct == 'rounding': value = self.RoundingDict[value] else: try: value = int(value) except ValueError: pass funct = self.ChangeDict.get(funct, (lambda *args: None)) funct(value) def eval_equation(self, s): if not TEST_ALL and random.random() < 0.90: return self.context.clear_flags() try: Sides = s.split('->') L = Sides[0].strip().split() id = L[0] if DEBUG: print("Test ", id, end=" ") funct = L[1].lower() valstemp = L[2:] L = Sides[1].strip().split() ans = L[0] exceptions = L[1:] except (TypeError, AttributeError, IndexError): raise self.decimal.InvalidOperation def FixQuotes(val): val = val.replace("''", 'SingleQuote').replace('""', 'DoubleQuote') val = val.replace("'", '').replace('"', '') val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"') return val if id in self.skipped_test_ids: return fname = self.NameAdapter.get(funct, funct) if fname == 'rescale': return funct = getattr(self.context, fname) vals = [] conglomerate = '' quote = 0 theirexceptions = [self.ErrorNames[x.lower()] for x in exceptions] for exception in Signals[self.decimal]: self.context.traps[exception] = 1 #Catch these bugs... for exception in theirexceptions: self.context.traps[exception] = 0 for i, val in enumerate(valstemp): if val.count("'") % 2 == 1: quote = 1 - quote if quote: conglomerate = conglomerate + ' ' + val continue else: val = conglomerate + val conglomerate = '' v = FixQuotes(val) if fname in ('to_sci_string', 'to_eng_string'): if EXTENDEDERRORTEST: for error in theirexceptions: self.context.traps[error] = 1 try: funct(self.context.create_decimal(v)) except error: pass except Signals[self.decimal] as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 v = self.context.create_decimal(v) else: v = self.read_unlimited(v, self.context) vals.append(v) ans = FixQuotes(ans) if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'): for error in theirexceptions: self.context.traps[error] = 1 try: funct(*vals) except error: pass except Signals[self.decimal] as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 # as above, but add traps cumulatively, to check precedence ordered_errors = [e for e in OrderedSignals[self.decimal] if e in theirexceptions] for error in ordered_errors: self.context.traps[error] = 1 try: funct(*vals) except error: pass except Signals[self.decimal] as e: self.fail("Raised %s in %s; expected %s" % (type(e), s, error)) else: self.fail("Did not raise %s in %s" % (error, s)) # reset traps for error in ordered_errors: self.context.traps[error] = 0 if DEBUG: print("--", self.context) try: result = str(funct(*vals)) if fname in self.LogicalFunctions: result = str(int(eval(result))) # 'True', 'False' -> '1', '0' except Signals[self.decimal] as error: self.fail("Raised %s in %s" % (error, s)) except: #Catch any error long enough to state the test case. print("ERROR:", s) raise myexceptions = self.getexceptions() myexceptions.sort(key=repr) theirexceptions.sort(key=repr) self.assertEqual(result, ans, 'Incorrect answer for ' + s + ' -- got ' + result) self.assertEqual(myexceptions, theirexceptions, 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) def getexceptions(self): return [e for e in Signals[self.decimal] if self.context.flags[e]] def change_precision(self, prec): if self.decimal == C and self.decimal.MAX_PREC == 425000000: self.context._unsafe_setprec(prec) else: self.context.prec = prec def change_rounding_method(self, rounding): self.context.rounding = rounding def change_min_exponent(self, exp): if self.decimal == C and self.decimal.MAX_PREC == 425000000: self.context._unsafe_setemin(exp) else: self.context.Emin = exp def change_max_exponent(self, exp): if self.decimal == C and self.decimal.MAX_PREC == 425000000: self.context._unsafe_setemax(exp) else: self.context.Emax = exp def change_clamp(self, clamp): self.context.clamp = clamp class CIBMTestCases(IBMTestCases): decimal = C class PyIBMTestCases(IBMTestCases): decimal = P # The following classes test the behaviour of Decimal according to PEP 327 class ExplicitConstructionTest(unittest.TestCase): '''Unit tests for Explicit Construction cases of Decimal.''' def test_explicit_empty(self): Decimal = self.decimal.Decimal self.assertEqual(Decimal(), Decimal("0")) def test_explicit_from_None(self): Decimal = self.decimal.Decimal self.assertRaises(TypeError, Decimal, None) def test_explicit_from_int(self): Decimal = self.decimal.Decimal #positive d = Decimal(45) self.assertEqual(str(d), '45') #very large positive d = Decimal(500000123) self.assertEqual(str(d), '500000123') #negative d = Decimal(-45) self.assertEqual(str(d), '-45') #zero d = Decimal(0) self.assertEqual(str(d), '0') # single word longs for n in range(0, 32): for sign in (-1, 1): for x in range(-5, 5): i = sign * (2**n + x) d = Decimal(i) self.assertEqual(str(d), str(i)) def test_explicit_from_string(self): Decimal = self.decimal.Decimal InvalidOperation = self.decimal.InvalidOperation localcontext = self.decimal.localcontext #empty self.assertEqual(str(Decimal('')), 'NaN') #int self.assertEqual(str(Decimal('45')), '45') #float self.assertEqual(str(Decimal('45.34')), '45.34') #engineer notation self.assertEqual(str(Decimal('45e2')), '4.5E+3') #just not a number self.assertEqual(str(Decimal('ugly')), 'NaN') #leading and trailing whitespace permitted self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4') self.assertEqual(str(Decimal(' -7.89')), '-7.89') self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679') # underscores self.assertEqual(str(Decimal('1_3.3e4_0')), '1.33E+41') self.assertEqual(str(Decimal('1_0_0_0')), '1000') # unicode whitespace for lead in ["", ' ', '\u00a0', '\u205f']: for trail in ["", ' ', '\u00a0', '\u205f']: self.assertEqual(str(Decimal(lead + '9.311E+28' + trail)), '9.311E+28') with localcontext() as c: c.traps[InvalidOperation] = True # Invalid string self.assertRaises(InvalidOperation, Decimal, "xyz") # Two arguments max self.assertRaises(TypeError, Decimal, "1234", "x", "y") # space within the numeric part self.assertRaises(InvalidOperation, Decimal, "1\u00a02\u00a03") self.assertRaises(InvalidOperation, Decimal, "\u00a01\u00a02\u00a0") # unicode whitespace self.assertRaises(InvalidOperation, Decimal, "\u00a0") self.assertRaises(InvalidOperation, Decimal, "\u00a0\u00a0") # embedded NUL self.assertRaises(InvalidOperation, Decimal, "12\u00003") # underscores don't prevent errors self.assertRaises(InvalidOperation, Decimal, "1_2_\u00003") @cpython_only def test_from_legacy_strings(self): import _testcapi Decimal = self.decimal.Decimal context = self.decimal.Context() s = _testcapi.unicode_legacy_string('9.999999') self.assertEqual(str(Decimal(s)), '9.999999') self.assertEqual(str(context.create_decimal(s)), '9.999999') def test_explicit_from_tuples(self): Decimal = self.decimal.Decimal #zero d = Decimal( (0, (0,), 0) ) self.assertEqual(str(d), '0') #int d = Decimal( (1, (4, 5), 0) ) self.assertEqual(str(d), '-45') #float d = Decimal( (0, (4, 5, 3, 4), -2) ) self.assertEqual(str(d), '45.34') #weird d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) self.assertEqual(str(d), '-4.34913534E-17') #inf d = Decimal( (0, (), "F") ) self.assertEqual(str(d), 'Infinity') #wrong number of items self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) ) #bad sign self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) ) self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) ) self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2)) #bad exp self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') ) self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) ) self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') ) #bad coefficients self.assertRaises(ValueError, Decimal, (1, "xyz", 2) ) self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) ) self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) ) self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) ) self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) ) def test_explicit_from_list(self): Decimal = self.decimal.Decimal d = Decimal([0, [0], 0]) self.assertEqual(str(d), '0') d = Decimal([1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25]) self.assertEqual(str(d), '-4.34913534E-17') d = Decimal([1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25]) self.assertEqual(str(d), '-4.34913534E-17') d = Decimal((1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25)) self.assertEqual(str(d), '-4.34913534E-17') def test_explicit_from_bool(self): Decimal = self.decimal.Decimal self.assertIs(bool(Decimal(0)), False) self.assertIs(bool(Decimal(1)), True) self.assertEqual(Decimal(False), Decimal(0)) self.assertEqual(Decimal(True), Decimal(1)) def test_explicit_from_Decimal(self): Decimal = self.decimal.Decimal #positive d = Decimal(45) e = Decimal(d) self.assertEqual(str(e), '45') #very large positive d = Decimal(500000123) e = Decimal(d) self.assertEqual(str(e), '500000123') #negative d = Decimal(-45) e = Decimal(d) self.assertEqual(str(e), '-45') #zero d = Decimal(0) e = Decimal(d) self.assertEqual(str(e), '0') @requires_IEEE_754 def test_explicit_from_float(self): Decimal = self.decimal.Decimal r = Decimal(0.1) self.assertEqual(type(r), Decimal) self.assertEqual(str(r), '0.1000000000000000055511151231257827021181583404541015625') self.assertTrue(Decimal(float('nan')).is_qnan()) self.assertTrue(Decimal(float('inf')).is_infinite()) self.assertTrue(Decimal(float('-inf')).is_infinite()) self.assertEqual(str(Decimal(float('nan'))), str(Decimal('NaN'))) self.assertEqual(str(Decimal(float('inf'))), str(Decimal('Infinity'))) self.assertEqual(str(Decimal(float('-inf'))), str(Decimal('-Infinity'))) self.assertEqual(str(Decimal(float('-0.0'))), str(Decimal('-0'))) for i in range(200): x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) self.assertEqual(x, float(Decimal(x))) # roundtrip def test_explicit_context_create_decimal(self): Decimal = self.decimal.Decimal InvalidOperation = self.decimal.InvalidOperation Rounded = self.decimal.Rounded nc = copy.copy(self.decimal.getcontext()) nc.prec = 3 # empty d = Decimal() self.assertEqual(str(d), '0') d = nc.create_decimal() self.assertEqual(str(d), '0') # from None self.assertRaises(TypeError, nc.create_decimal, None) # from int d = nc.create_decimal(456) self.assertIsInstance(d, Decimal) self.assertEqual(nc.create_decimal(45678), nc.create_decimal('457E+2')) # from string d = Decimal('456789') self.assertEqual(str(d), '456789') d = nc.create_decimal('456789') self.assertEqual(str(d), '4.57E+5') # leading and trailing whitespace should result in a NaN; # spaces are already checked in Cowlishaw's test-suite, so # here we just check that a trailing newline results in a NaN self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN') # from tuples d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) self.assertEqual(str(d), '-4.34913534E-17') d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) self.assertEqual(str(d), '-4.35E-17') # from Decimal prevdec = Decimal(500000123) d = Decimal(prevdec) self.assertEqual(str(d), '500000123') d = nc.create_decimal(prevdec) self.assertEqual(str(d), '5.00E+8') # more integers nc.prec = 28 nc.traps[InvalidOperation] = True for v in [-2**63-1, -2**63, -2**31-1, -2**31, 0, 2**31-1, 2**31, 2**63-1, 2**63]: d = nc.create_decimal(v) self.assertTrue(isinstance(d, Decimal)) self.assertEqual(int(d), v) nc.prec = 3 nc.traps[Rounded] = True self.assertRaises(Rounded, nc.create_decimal, 1234) # from string nc.prec = 28 self.assertEqual(str(nc.create_decimal('0E-017')), '0E-17') self.assertEqual(str(nc.create_decimal('45')), '45') self.assertEqual(str(nc.create_decimal('-Inf')), '-Infinity') self.assertEqual(str(nc.create_decimal('NaN123')), 'NaN123') # invalid arguments self.assertRaises(InvalidOperation, nc.create_decimal, "xyz") self.assertRaises(ValueError, nc.create_decimal, (1, "xyz", -25)) self.assertRaises(TypeError, nc.create_decimal, "1234", "5678") # no whitespace and underscore stripping is done with this method self.assertRaises(InvalidOperation, nc.create_decimal, " 1234") self.assertRaises(InvalidOperation, nc.create_decimal, "12_34") # too many NaN payload digits nc.prec = 3 self.assertRaises(InvalidOperation, nc.create_decimal, 'NaN12345') self.assertRaises(InvalidOperation, nc.create_decimal, Decimal('NaN12345')) nc.traps[InvalidOperation] = False self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN') self.assertTrue(nc.flags[InvalidOperation]) nc.flags[InvalidOperation] = False self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN') self.assertTrue(nc.flags[InvalidOperation]) def test_explicit_context_create_from_float(self): Decimal = self.decimal.Decimal nc = self.decimal.Context() r = nc.create_decimal(0.1) self.assertEqual(type(r), Decimal) self.assertEqual(str(r), '0.1000000000000000055511151231') self.assertTrue(nc.create_decimal(float('nan')).is_qnan()) self.assertTrue(nc.create_decimal(float('inf')).is_infinite()) self.assertTrue(nc.create_decimal(float('-inf')).is_infinite()) self.assertEqual(str(nc.create_decimal(float('nan'))), str(nc.create_decimal('NaN'))) self.assertEqual(str(nc.create_decimal(float('inf'))), str(nc.create_decimal('Infinity'))) self.assertEqual(str(nc.create_decimal(float('-inf'))), str(nc.create_decimal('-Infinity'))) self.assertEqual(str(nc.create_decimal(float('-0.0'))), str(nc.create_decimal('-0'))) nc.prec = 100 for i in range(200): x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) self.assertEqual(x, float(nc.create_decimal(x))) # roundtrip def test_unicode_digits(self): Decimal = self.decimal.Decimal test_values = { '\uff11': '1', '\u0660.\u0660\u0663\u0667\u0662e-\u0663' : '0.0000372', '-nan\u0c68\u0c6a\u0c66\u0c66' : '-NaN2400', } for input, expected in test_values.items(): self.assertEqual(str(Decimal(input)), expected) class CExplicitConstructionTest(ExplicitConstructionTest): decimal = C class PyExplicitConstructionTest(ExplicitConstructionTest): decimal = P class ImplicitConstructionTest(unittest.TestCase): '''Unit tests for Implicit Construction cases of Decimal.''' def test_implicit_from_None(self): Decimal = self.decimal.Decimal self.assertRaises(TypeError, eval, 'Decimal(5) + None', locals()) def test_implicit_from_int(self): Decimal = self.decimal.Decimal #normal self.assertEqual(str(Decimal(5) + 45), '50') #exceeding precision self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000)) def test_implicit_from_string(self): Decimal = self.decimal.Decimal self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', locals()) def test_implicit_from_float(self): Decimal = self.decimal.Decimal self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', locals()) def test_implicit_from_Decimal(self): Decimal = self.decimal.Decimal self.assertEqual(Decimal(5) + Decimal(45), Decimal(50)) def test_rop(self): Decimal = self.decimal.Decimal # Allow other classes to be trained to interact with Decimals class E: def __divmod__(self, other): return 'divmod ' + str(other) def __rdivmod__(self, other): return str(other) + ' rdivmod'
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_textwrap.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_textwrap.py
# # Test suite for the textwrap module. # # Original tests written by Greg Ward <gward@python.net>. # Converted to PyUnit by Peter Hansen <peter@engcorp.com>. # Currently maintained by Greg Ward. # # $Id$ # import unittest from textwrap import TextWrapper, wrap, fill, dedent, indent, shorten class BaseTestCase(unittest.TestCase): '''Parent class with utility methods for textwrap tests.''' def show(self, textin): if isinstance(textin, list): result = [] for i in range(len(textin)): result.append(" %d: %r" % (i, textin[i])) result = "\n".join(result) if result else " no lines" elif isinstance(textin, str): result = " %s\n" % repr(textin) return result def check(self, result, expect): self.assertEqual(result, expect, 'expected:\n%s\nbut got:\n%s' % ( self.show(expect), self.show(result))) def check_wrap(self, text, width, expect, **kwargs): result = wrap(text, width, **kwargs) self.check(result, expect) def check_split(self, text, expect): result = self.wrapper._split(text) self.assertEqual(result, expect, "\nexpected %r\n" "but got %r" % (expect, result)) class WrapTestCase(BaseTestCase): def setUp(self): self.wrapper = TextWrapper(width=45) def test_simple(self): # Simple case: just words, spaces, and a bit of punctuation text = "Hello there, how are you this fine day? I'm glad to hear it!" self.check_wrap(text, 12, ["Hello there,", "how are you", "this fine", "day? I'm", "glad to hear", "it!"]) self.check_wrap(text, 42, ["Hello there, how are you this fine day?", "I'm glad to hear it!"]) self.check_wrap(text, 80, [text]) def test_empty_string(self): # Check that wrapping the empty string returns an empty list. self.check_wrap("", 6, []) self.check_wrap("", 6, [], drop_whitespace=False) def test_empty_string_with_initial_indent(self): # Check that the empty string is not indented. self.check_wrap("", 6, [], initial_indent="++") self.check_wrap("", 6, [], initial_indent="++", drop_whitespace=False) def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = ["This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!"] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, '\n'.join(expect)) text = "\tTest\tdefault\t\ttabsize." expect = [" Test default tabsize."] self.check_wrap(text, 80, expect) text = "\tTest\tcustom\t\ttabsize." expect = [" Test custom tabsize."] self.check_wrap(text, 80, expect, tabsize=4) def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) # SF #847346: ensure that fix_sentence_endings=True does the # right thing even on input short enough that it doesn't need to # be wrapped. text = "A short line. Note the single space." expect = ["A short line. Note the single space."] self.check(wrapper.wrap(text), expect) # Test some of the hairy end cases that _fix_sentence_endings() # is supposed to handle (the easy stuff is tested in # test_whitespace() above). text = "Well, Doctor? What do you think?" expect = ["Well, Doctor? What do you think?"] self.check(wrapper.wrap(text), expect) text = "Well, Doctor?\nWhat do you think?" self.check(wrapper.wrap(text), expect) text = 'I say, chaps! Anyone for "tennis?"\nHmmph!' expect = ['I say, chaps! Anyone for "tennis?" Hmmph!'] self.check(wrapper.wrap(text), expect) wrapper.width = 20 expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!'] self.check(wrapper.wrap(text), expect) text = 'And she said, "Go to hell!"\nCan you believe that?' expect = ['And she said, "Go to', 'hell!" Can you', 'believe that?'] self.check(wrapper.wrap(text), expect) wrapper.width = 60 expect = ['And she said, "Go to hell!" Can you believe that?'] self.check(wrapper.wrap(text), expect) text = 'File stdio.h is nice.' expect = ['File stdio.h is nice.'] self.check(wrapper.wrap(text), expect) def test_wrap_short(self): # Wrapping to make short lines longer text = "This is a\nshort paragraph." self.check_wrap(text, 20, ["This is a short", "paragraph."]) self.check_wrap(text, 40, ["This is a short paragraph."]) def test_wrap_short_1line(self): # Test endcases text = "This is a short line." self.check_wrap(text, 30, ["This is a short line."]) self.check_wrap(text, 30, ["(1) This is a short line."], initial_indent="(1) ") def test_hyphenated(self): # Test breaking hyphenated words text = ("this-is-a-useful-feature-for-" "reformatting-posts-from-tim-peters'ly") self.check_wrap(text, 40, ["this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly"]) self.check_wrap(text, 41, ["this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly"]) self.check_wrap(text, 42, ["this-is-a-useful-feature-for-reformatting-", "posts-from-tim-peters'ly"]) # The test tests current behavior but is not testing parts of the API. expect = ("this-|is-|a-|useful-|feature-|for-|" "reformatting-|posts-|from-|tim-|peters'ly").split('|') self.check_wrap(text, 1, expect, break_long_words=False) self.check_split(text, expect) self.check_split('e-mail', ['e-mail']) self.check_split('Jelly-O', ['Jelly-O']) # The test tests current behavior but is not testing parts of the API. self.check_split('half-a-crown', 'half-|a-|crown'.split('|')) def test_hyphenated_numbers(self): # Test that hyphenated numbers (eg. dates) are not broken like words. text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n" "released on 1994-02-15.") self.check_wrap(text, 30, ['Python 1.0.0 was released on', '1994-01-26. Python 1.0.1 was', 'released on 1994-02-15.']) self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.', 'Python 1.0.1 was released on 1994-02-15.']) self.check_wrap(text, 1, text.split(), break_long_words=False) text = "I do all my shopping at 7-11." self.check_wrap(text, 25, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 27, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 29, ["I do all my shopping at 7-11."]) self.check_wrap(text, 1, text.split(), break_long_words=False) def test_em_dash(self): # Test text with em-dashes text = "Em-dashes should be written -- thus." self.check_wrap(text, 25, ["Em-dashes should be", "written -- thus."]) # Probe the boundaries of the properly written em-dash, # ie. " -- ". self.check_wrap(text, 29, ["Em-dashes should be written", "-- thus."]) expect = ["Em-dashes should be written --", "thus."] self.check_wrap(text, 30, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 36, ["Em-dashes should be written -- thus."]) # The improperly written em-dash is handled too, because # it's adjacent to non-whitespace on both sides. text = "You can also do--this or even---this." expect = ["You can also do", "--this or even", "---this."] self.check_wrap(text, 15, expect) self.check_wrap(text, 16, expect) expect = ["You can also do--", "this or even---", "this."] self.check_wrap(text, 17, expect) self.check_wrap(text, 19, expect) expect = ["You can also do--this or even", "---this."] self.check_wrap(text, 29, expect) self.check_wrap(text, 31, expect) expect = ["You can also do--this or even---", "this."] self.check_wrap(text, 32, expect) self.check_wrap(text, 35, expect) # All of the above behaviour could be deduced by probing the # _split() method. text = "Here's an -- em-dash and--here's another---and another!" expect = ["Here's", " ", "an", " ", "--", " ", "em-", "dash", " ", "and", "--", "here's", " ", "another", "---", "and", " ", "another!"] self.check_split(text, expect) text = "and then--bam!--he was gone" expect = ["and", " ", "then", "--", "bam!", "--", "he", " ", "was", " ", "gone"] self.check_split(text, expect) def test_unix_options (self): # Test that Unix-style command-line options are wrapped correctly. # Both Optik (OptionParser) and Docutils rely on this behaviour! text = "You should use the -n option, or --dry-run in its long form." self.check_wrap(text, 20, ["You should use the", "-n option, or --dry-", "run in its long", "form."]) self.check_wrap(text, 21, ["You should use the -n", "option, or --dry-run", "in its long form."]) expect = ["You should use the -n option, or", "--dry-run in its long form."] self.check_wrap(text, 32, expect) self.check_wrap(text, 34, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 38, expect) expect = ["You should use the -n option, or --dry-", "run in its long form."] self.check_wrap(text, 39, expect) self.check_wrap(text, 41, expect) expect = ["You should use the -n option, or --dry-run", "in its long form."] self.check_wrap(text, 42, expect) # Again, all of the above can be deduced from _split(). text = "the -n option, or --dry-run or --dryrun" expect = ["the", " ", "-n", " ", "option,", " ", "or", " ", "--dry-", "run", " ", "or", " ", "--dryrun"] self.check_split(text, expect) def test_funky_hyphens (self): # Screwy edge cases cooked up by David Goodger. All reported # in SF bug #596434. self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"]) self.check_split("what the--", ["what", " ", "the--"]) self.check_split("what the--.", ["what", " ", "the--."]) self.check_split("--text--.", ["--text--."]) # When I first read bug #596434, this is what I thought David # was talking about. I was wrong; these have always worked # fine. The real problem is tested in test_funky_parens() # below... self.check_split("--option", ["--option"]) self.check_split("--option-opt", ["--option-", "opt"]) self.check_split("foo --option-opt bar", ["foo", " ", "--option-", "opt", " ", "bar"]) def test_punct_hyphens(self): # Oh bother, SF #965425 found another problem with hyphens -- # hyphenated words in single quotes weren't handled correctly. # In fact, the bug is that *any* punctuation around a hyphenated # word was handled incorrectly, except for a leading "--", which # was special-cased for Optik and Docutils. So test a variety # of styles of punctuation around a hyphenated word. # (Actually this is based on an Optik bug report, #813077). self.check_split("the 'wibble-wobble' widget", ['the', ' ', "'wibble-", "wobble'", ' ', 'widget']) self.check_split('the "wibble-wobble" widget', ['the', ' ', '"wibble-', 'wobble"', ' ', 'widget']) self.check_split("the (wibble-wobble) widget", ['the', ' ', "(wibble-", "wobble)", ' ', 'widget']) self.check_split("the ['wibble-wobble'] widget", ['the', ' ', "['wibble-", "wobble']", ' ', 'widget']) # The test tests current behavior but is not testing parts of the API. self.check_split("what-d'you-call-it.", "what-d'you-|call-|it.".split('|')) def test_funky_parens (self): # Second part of SF bug #596434: long option strings inside # parentheses. self.check_split("foo (--option) bar", ["foo", " ", "(--option)", " ", "bar"]) # Related stuff -- make sure parens work in simpler contexts. self.check_split("foo (bar) baz", ["foo", " ", "(bar)", " ", "baz"]) self.check_split("blah (ding dong), wubba", ["blah", " ", "(ding", " ", "dong),", " ", "wubba"]) def test_drop_whitespace_false(self): # Check that drop_whitespace=False preserves whitespace. # SF patch #1581073 text = " This is a sentence with much whitespace." self.check_wrap(text, 10, [" This is a", " ", "sentence ", "with ", "much white", "space."], drop_whitespace=False) def test_drop_whitespace_false_whitespace_only(self): # Check that drop_whitespace=False preserves a whitespace-only string. self.check_wrap(" ", 6, [" "], drop_whitespace=False) def test_drop_whitespace_false_whitespace_only_with_indent(self): # Check that a whitespace-only string gets indented (when # drop_whitespace is False). self.check_wrap(" ", 6, [" "], drop_whitespace=False, initial_indent=" ") def test_drop_whitespace_whitespace_only(self): # Check drop_whitespace on a whitespace-only string. self.check_wrap(" ", 6, []) def test_drop_whitespace_leading_whitespace(self): # Check that drop_whitespace does not drop leading whitespace (if # followed by non-whitespace). # SF bug #622849 reported inconsistent handling of leading # whitespace; let's test that a bit, shall we? text = " This is a sentence with leading whitespace." self.check_wrap(text, 50, [" This is a sentence with leading whitespace."]) self.check_wrap(text, 30, [" This is a sentence with", "leading whitespace."]) def test_drop_whitespace_whitespace_line(self): # Check that drop_whitespace skips the whole line if a non-leading # line consists only of whitespace. text = "abcd efgh" # Include the result for drop_whitespace=False for comparison. self.check_wrap(text, 6, ["abcd", " ", "efgh"], drop_whitespace=False) self.check_wrap(text, 6, ["abcd", "efgh"]) def test_drop_whitespace_whitespace_only_with_indent(self): # Check that initial_indent is not applied to a whitespace-only # string. This checks a special case of the fact that dropping # whitespace occurs before indenting. self.check_wrap(" ", 6, [], initial_indent="++") def test_drop_whitespace_whitespace_indent(self): # Check that drop_whitespace does not drop whitespace indents. # This checks a special case of the fact that dropping whitespace # occurs before indenting. self.check_wrap("abcd efgh", 6, [" abcd", " efgh"], initial_indent=" ", subsequent_indent=" ") def test_split(self): # Ensure that the standard _split() method works as advertised # in the comments text = "Hello there -- you goof-ball, use the -b option!" result = self.wrapper._split(text) self.check(result, ["Hello", " ", "there", " ", "--", " ", "you", " ", "goof-", "ball,", " ", "use", " ", "the", " ", "-b", " ", "option!"]) def test_break_on_hyphens(self): # Ensure that the break_on_hyphens attributes work text = "yaba daba-doo" self.check_wrap(text, 10, ["yaba daba-", "doo"], break_on_hyphens=True) self.check_wrap(text, 10, ["yaba", "daba-doo"], break_on_hyphens=False) def test_bad_width(self): # Ensure that width <= 0 is caught. text = "Whatever, it doesn't matter." self.assertRaises(ValueError, wrap, text, 0) self.assertRaises(ValueError, wrap, text, -1) def test_no_split_at_umlaut(self): text = "Die Empf\xe4nger-Auswahl" self.check_wrap(text, 13, ["Die", "Empf\xe4nger-", "Auswahl"]) def test_umlaut_followed_by_dash(self): text = "aa \xe4\xe4-\xe4\xe4" self.check_wrap(text, 7, ["aa \xe4\xe4-", "\xe4\xe4"]) def test_non_breaking_space(self): text = 'This is a sentence with non-breaking\N{NO-BREAK SPACE}space.' self.check_wrap(text, 20, ['This is a sentence', 'with non-', 'breaking\N{NO-BREAK SPACE}space.'], break_on_hyphens=True) self.check_wrap(text, 20, ['This is a sentence', 'with', 'non-breaking\N{NO-BREAK SPACE}space.'], break_on_hyphens=False) def test_narrow_non_breaking_space(self): text = ('This is a sentence with non-breaking' '\N{NARROW NO-BREAK SPACE}space.') self.check_wrap(text, 20, ['This is a sentence', 'with non-', 'breaking\N{NARROW NO-BREAK SPACE}space.'], break_on_hyphens=True) self.check_wrap(text, 20, ['This is a sentence', 'with', 'non-breaking\N{NARROW NO-BREAK SPACE}space.'], break_on_hyphens=False) class MaxLinesTestCase(BaseTestCase): text = "Hello there, how are you this fine day? I'm glad to hear it!" def test_simple(self): self.check_wrap(self.text, 12, ["Hello [...]"], max_lines=0) self.check_wrap(self.text, 12, ["Hello [...]"], max_lines=1) self.check_wrap(self.text, 12, ["Hello there,", "how [...]"], max_lines=2) self.check_wrap(self.text, 13, ["Hello there,", "how are [...]"], max_lines=2) self.check_wrap(self.text, 80, [self.text], max_lines=1) self.check_wrap(self.text, 12, ["Hello there,", "how are you", "this fine", "day? I'm", "glad to hear", "it!"], max_lines=6) def test_spaces(self): # strip spaces before placeholder self.check_wrap(self.text, 12, ["Hello there,", "how are you", "this fine", "day? [...]"], max_lines=4) # placeholder at the start of line self.check_wrap(self.text, 6, ["Hello", "[...]"], max_lines=2) # final spaces self.check_wrap(self.text + ' ' * 10, 12, ["Hello there,", "how are you", "this fine", "day? I'm", "glad to hear", "it!"], max_lines=6) def test_placeholder(self): self.check_wrap(self.text, 12, ["Hello..."], max_lines=1, placeholder='...') self.check_wrap(self.text, 12, ["Hello there,", "how are..."], max_lines=2, placeholder='...') # long placeholder and indentation with self.assertRaises(ValueError): wrap(self.text, 16, initial_indent=' ', max_lines=1, placeholder=' [truncated]...') with self.assertRaises(ValueError): wrap(self.text, 16, subsequent_indent=' ', max_lines=2, placeholder=' [truncated]...') self.check_wrap(self.text, 16, [" Hello there,", " [truncated]..."], max_lines=2, initial_indent=' ', subsequent_indent=' ', placeholder=' [truncated]...') self.check_wrap(self.text, 16, [" [truncated]..."], max_lines=1, initial_indent=' ', subsequent_indent=' ', placeholder=' [truncated]...') self.check_wrap(self.text, 80, [self.text], placeholder='.' * 1000) def test_placeholder_backtrack(self): # Test special case when max_lines insufficient, but what # would be last wrapped line so long the placeholder cannot # be added there without violence. So, textwrap backtracks, # adding placeholder to the penultimate line. text = 'Good grief Python features are advancing quickly!' self.check_wrap(text, 12, ['Good grief', 'Python*****'], max_lines=3, placeholder='*****') class LongWordTestCase (BaseTestCase): def setUp(self): self.wrapper = TextWrapper() self.text = '''\ Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? ''' def test_break_long(self): # Wrap text with long words and lots of punctuation self.check_wrap(self.text, 30, ['Did you say "supercalifragilis', 'ticexpialidocious?" How *do*', 'you spell that odd word,', 'anyways?']) self.check_wrap(self.text, 50, ['Did you say "supercalifragilisticexpialidocious?"', 'How *do* you spell that odd word, anyways?']) # SF bug 797650. Prevent an infinite loop by making sure that at # least one character gets split off on every pass. self.check_wrap('-'*10+'hello', 10, ['----------', ' h', ' e', ' l', ' l', ' o'], subsequent_indent = ' '*15) # bug 1146. Prevent a long word to be wrongly wrapped when the # preceding word is exactly one character shorter than the width self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', 'ialidocious?', '" How *do*', 'you spell', 'that odd', 'word,', 'anyways?']) def test_nobreak_long(self): # Test with break_long_words disabled self.wrapper.break_long_words = 0 self.wrapper.width = 30 expect = ['Did you say', '"supercalifragilisticexpialidocious?"', 'How *do* you spell that odd', 'word, anyways?' ] result = self.wrapper.wrap(self.text) self.check(result, expect) # Same thing with kwargs passed to standalone wrap() function. result = wrap(self.text, width=30, break_long_words=0) self.check(result, expect) def test_max_lines_long(self): self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', '[...]'], max_lines=4) class IndentTestCases(BaseTestCase): # called before each test method def setUp(self): self.text = '''\ This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' def test_fill(self): # Test the fill() method expect = '''\ This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' result = fill(self.text, 40) self.check(result, expect) def test_initial_indent(self): # Test initial_indent parameter expect = [" This paragraph will be filled,", "first without any indentation, and then", "with some (including a hanging indent)."] result = wrap(self.text, 40, initial_indent=" ") self.check(result, expect) expect = "\n".join(expect) result = fill(self.text, 40, initial_indent=" ") self.check(result, expect) def test_subsequent_indent(self): # Test subsequent_indent parameter expect = '''\ * This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' result = fill(self.text, 40, initial_indent=" * ", subsequent_indent=" ") self.check(result, expect) # Despite the similar names, DedentTestCase is *not* the inverse # of IndentTestCase! class DedentTestCase(unittest.TestCase): def assertUnchanged(self, text): """assert that dedent() has no effect on 'text'""" self.assertEqual(text, dedent(text)) def test_dedent_nomargin(self): # No lines indented. text = "Hello there.\nHow are you?\nOh good, I'm glad." self.assertUnchanged(text) # Similar, with a blank line. text = "Hello there.\n\nBoo!" self.assertUnchanged(text) # Some lines indented, but overall margin is still zero. text = "Hello there.\n This is indented." self.assertUnchanged(text) # Again, add a blank line. text = "Hello there.\n\n Boo!\n" self.assertUnchanged(text) def test_dedent_even(self): # All lines indented by two spaces. text = " Hello there.\n How are ya?\n Oh good." expect = "Hello there.\nHow are ya?\nOh good." self.assertEqual(expect, dedent(text)) # Same, with blank lines. text = " Hello there.\n\n How are ya?\n Oh good.\n" expect = "Hello there.\n\nHow are ya?\nOh good.\n" self.assertEqual(expect, dedent(text)) # Now indent one of the blank lines. text = " Hello there.\n \n How are ya?\n Oh good.\n" expect = "Hello there.\n\nHow are ya?\nOh good.\n" self.assertEqual(expect, dedent(text)) def test_dedent_uneven(self): # Lines indented unevenly. text = '''\ def foo(): while 1: return foo ''' expect = '''\ def foo(): while 1: return foo ''' self.assertEqual(expect, dedent(text)) # Uneven indentation with a blank line. text = " Foo\n Bar\n\n Baz\n" expect = "Foo\n Bar\n\n Baz\n" self.assertEqual(expect, dedent(text)) # Uneven indentation with a whitespace-only line. text = " Foo\n Bar\n \n Baz\n" expect = "Foo\n Bar\n\n Baz\n" self.assertEqual(expect, dedent(text)) def test_dedent_declining(self): # Uneven indentation with declining indent level. text = " Foo\n Bar\n" # 5 spaces, then 4 expect = " Foo\nBar\n" self.assertEqual(expect, dedent(text)) # Declining indent level with blank line. text = " Foo\n\n Bar\n" # 5 spaces, blank, then 4 expect = " Foo\n\nBar\n" self.assertEqual(expect, dedent(text)) # Declining indent level with whitespace only line. text = " Foo\n \n Bar\n" # 5 spaces, then 4, then 4 expect = " Foo\n\nBar\n" self.assertEqual(expect, dedent(text)) # dedent() should not mangle internal tabs def test_dedent_preserve_internal_tabs(self): text = " hello\tthere\n how are\tyou?" expect = "hello\tthere\nhow are\tyou?" self.assertEqual(expect, dedent(text)) # make sure that it preserves tabs when it's not making any # changes at all self.assertEqual(expect, dedent(expect)) # dedent() should not mangle tabs in the margin (i.e. # tabs and spaces both count as margin, but are *not* # considered equivalent) def test_dedent_preserve_margin_tabs(self): text = " hello there\n\thow are you?" self.assertUnchanged(text) # same effect even if we have 8 spaces text = " hello there\n\thow are you?" self.assertUnchanged(text) # dedent() only removes whitespace that can be uniformly removed! text = "\thello there\n\thow are you?" expect = "hello there\nhow are you?" self.assertEqual(expect, dedent(text)) text = " \thello there\n \thow are you?" self.assertEqual(expect, dedent(text)) text = " \t hello there\n \t how are you?" self.assertEqual(expect, dedent(text)) text = " \thello there\n \t how are you?" expect = "hello there\n how are you?" self.assertEqual(expect, dedent(text)) # test margin is smaller than smallest indent text = " \thello there\n \thow are you?\n \tI'm fine, thanks" expect = " \thello there\n \thow are you?\n\tI'm fine, thanks" self.assertEqual(expect, dedent(text)) # Test textwrap.indent class IndentTestCase(unittest.TestCase): # The examples used for tests. If any of these change, the expected # results in the various test cases must also be updated. # The roundtrip cases are separate, because textwrap.dedent doesn't # handle Windows line endings ROUNDTRIP_CASES = ( # Basic test case "Hi.\nThis is a test.\nTesting.", # Include a blank line "Hi.\nThis is a test.\n\nTesting.", # Include leading and trailing blank lines "\nHi.\nThis is a test.\nTesting.\n", ) CASES = ROUNDTRIP_CASES + ( # Use Windows line endings "Hi.\r\nThis is a test.\r\nTesting.\r\n", # Pathological case "\nHi.\r\nThis is a test.\n\r\nTesting.\r\n\n", )
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_genericclass.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_genericclass.py
import unittest from test import support class TestMROEntry(unittest.TestCase): def test_mro_entry_signature(self): tested = [] class B: ... class C: def __mro_entries__(self, *args, **kwargs): tested.extend([args, kwargs]) return (C,) c = C() self.assertEqual(tested, []) class D(B, c): ... self.assertEqual(tested[0], ((B, c),)) self.assertEqual(tested[1], {}) def test_mro_entry(self): tested = [] class A: ... class B: ... class C: def __mro_entries__(self, bases): tested.append(bases) return (self.__class__,) c = C() self.assertEqual(tested, []) class D(A, c, B): ... self.assertEqual(tested[-1], (A, c, B)) self.assertEqual(D.__bases__, (A, C, B)) self.assertEqual(D.__orig_bases__, (A, c, B)) self.assertEqual(D.__mro__, (D, A, C, B, object)) d = D() class E(d): ... self.assertEqual(tested[-1], (d,)) self.assertEqual(E.__bases__, (D,)) def test_mro_entry_none(self): tested = [] class A: ... class B: ... class C: def __mro_entries__(self, bases): tested.append(bases) return () c = C() self.assertEqual(tested, []) class D(A, c, B): ... self.assertEqual(tested[-1], (A, c, B)) self.assertEqual(D.__bases__, (A, B)) self.assertEqual(D.__orig_bases__, (A, c, B)) self.assertEqual(D.__mro__, (D, A, B, object)) class E(c): ... self.assertEqual(tested[-1], (c,)) self.assertEqual(E.__bases__, (object,)) self.assertEqual(E.__orig_bases__, (c,)) self.assertEqual(E.__mro__, (E, object)) def test_mro_entry_with_builtins(self): tested = [] class A: ... class C: def __mro_entries__(self, bases): tested.append(bases) return (dict,) c = C() self.assertEqual(tested, []) class D(A, c): ... self.assertEqual(tested[-1], (A, c)) self.assertEqual(D.__bases__, (A, dict)) self.assertEqual(D.__orig_bases__, (A, c)) self.assertEqual(D.__mro__, (D, A, dict, object)) def test_mro_entry_with_builtins_2(self): tested = [] class C: def __mro_entries__(self, bases): tested.append(bases) return (C,) c = C() self.assertEqual(tested, []) class D(c, dict): ... self.assertEqual(tested[-1], (c, dict)) self.assertEqual(D.__bases__, (C, dict)) self.assertEqual(D.__orig_bases__, (c, dict)) self.assertEqual(D.__mro__, (D, C, dict, object)) def test_mro_entry_errors(self): class C_too_many: def __mro_entries__(self, bases, something, other): return () c = C_too_many() with self.assertRaises(TypeError): class D(c): ... class C_too_few: def __mro_entries__(self): return () d = C_too_few() with self.assertRaises(TypeError): class D(d): ... def test_mro_entry_errors_2(self): class C_not_callable: __mro_entries__ = "Surprise!" c = C_not_callable() with self.assertRaises(TypeError): class D(c): ... class C_not_tuple: def __mro_entries__(self): return object c = C_not_tuple() with self.assertRaises(TypeError): class D(c): ... def test_mro_entry_metaclass(self): meta_args = [] class Meta(type): def __new__(mcls, name, bases, ns): meta_args.extend([mcls, name, bases, ns]) return super().__new__(mcls, name, bases, ns) class A: ... class C: def __mro_entries__(self, bases): return (A,) c = C() class D(c, metaclass=Meta): x = 1 self.assertEqual(meta_args[0], Meta) self.assertEqual(meta_args[1], 'D') self.assertEqual(meta_args[2], (A,)) self.assertEqual(meta_args[3]['x'], 1) self.assertEqual(D.__bases__, (A,)) self.assertEqual(D.__orig_bases__, (c,)) self.assertEqual(D.__mro__, (D, A, object)) self.assertEqual(D.__class__, Meta) def test_mro_entry_type_call(self): # Substitution should _not_ happen in direct type call class C: def __mro_entries__(self, bases): return () c = C() with self.assertRaisesRegex(TypeError, "MRO entry resolution; " "use types.new_class()"): type('Bad', (c,), {}) class TestClassGetitem(unittest.TestCase): def test_class_getitem(self): getitem_args = [] class C: def __class_getitem__(*args, **kwargs): getitem_args.extend([args, kwargs]) return None C[int, str] self.assertEqual(getitem_args[0], (C, (int, str))) self.assertEqual(getitem_args[1], {}) def test_class_getitem_format(self): class C: def __class_getitem__(cls, item): return f'C[{item.__name__}]' self.assertEqual(C[int], 'C[int]') self.assertEqual(C[C], 'C[C]') def test_class_getitem_inheritance(self): class C: def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' class D(C): ... self.assertEqual(D[int], 'D[int]') self.assertEqual(D[D], 'D[D]') def test_class_getitem_inheritance_2(self): class C: def __class_getitem__(cls, item): return 'Should not see this' class D(C): def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' self.assertEqual(D[int], 'D[int]') self.assertEqual(D[D], 'D[D]') def test_class_getitem_classmethod(self): class C: @classmethod def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' class D(C): ... self.assertEqual(D[int], 'D[int]') self.assertEqual(D[D], 'D[D]') def test_class_getitem_patched(self): class C: def __init_subclass__(cls): def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' cls.__class_getitem__ = classmethod(__class_getitem__) class D(C): ... self.assertEqual(D[int], 'D[int]') self.assertEqual(D[D], 'D[D]') def test_class_getitem_with_builtins(self): class A(dict): called_with = None def __class_getitem__(cls, item): cls.called_with = item class B(A): pass self.assertIs(B.called_with, None) B[int] self.assertIs(B.called_with, int) def test_class_getitem_errors(self): class C_too_few: def __class_getitem__(cls): return None with self.assertRaises(TypeError): C_too_few[int] class C_too_many: def __class_getitem__(cls, one, two): return None with self.assertRaises(TypeError): C_too_many[int] def test_class_getitem_errors_2(self): class C: def __class_getitem__(cls, item): return None with self.assertRaises(TypeError): C()[int] class E: ... e = E() e.__class_getitem__ = lambda cls, item: 'This will not work' with self.assertRaises(TypeError): e[int] class C_not_callable: __class_getitem__ = "Surprise!" with self.assertRaises(TypeError): C_not_callable[int] def test_class_getitem_metaclass(self): class Meta(type): def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' self.assertEqual(Meta[int], 'Meta[int]') def test_class_getitem_with_metaclass(self): class Meta(type): pass class C(metaclass=Meta): def __class_getitem__(cls, item): return f'{cls.__name__}[{item.__name__}]' self.assertEqual(C[int], 'C[int]') def test_class_getitem_metaclass_first(self): class Meta(type): def __getitem__(cls, item): return 'from metaclass' class C(metaclass=Meta): def __class_getitem__(cls, item): return 'from __class_getitem__' self.assertEqual(C[int], 'from metaclass') @support.cpython_only class CAPITest(unittest.TestCase): def test_c_class(self): from _testcapi import Generic, GenericAlias self.assertIsInstance(Generic.__class_getitem__(int), GenericAlias) IntGeneric = Generic[int] self.assertIs(type(IntGeneric), GenericAlias) self.assertEqual(IntGeneric.__mro_entries__(()), (int,)) class C(IntGeneric): pass self.assertEqual(C.__bases__, (int,)) self.assertEqual(C.__orig_bases__, (IntGeneric,)) self.assertEqual(C.__mro__, (C, int, object)) 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_datetime.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_datetime.py
import unittest import sys from test.support import import_fresh_module, run_unittest TESTS = 'test.datetimetester' try: pure_tests = import_fresh_module(TESTS, fresh=['datetime', '_strptime'], blocked=['_datetime']) fast_tests = import_fresh_module(TESTS, fresh=['datetime', '_datetime', '_strptime']) finally: # XXX: import_fresh_module() is supposed to leave sys.module cache untouched, # XXX: but it does not, so we have to cleanup ourselves. for modname in ['datetime', '_datetime', '_strptime']: sys.modules.pop(modname, None) test_modules = [pure_tests, fast_tests] test_suffixes = ["_Pure", "_Fast"] # XXX(gb) First run all the _Pure tests, then all the _Fast tests. You might # not believe this, but in spite of all the sys.modules trickery running a _Pure # test last will leave a mix of pure and native datetime stuff lying around. all_test_classes = [] for module, suffix in zip(test_modules, test_suffixes): test_classes = [] for name, cls in module.__dict__.items(): if not isinstance(cls, type): continue if issubclass(cls, unittest.TestCase): test_classes.append(cls) elif issubclass(cls, unittest.TestSuite): suit = cls() test_classes.extend(type(test) for test in suit) test_classes = sorted(set(test_classes), key=lambda cls: cls.__qualname__) for cls in test_classes: cls.__name__ += suffix cls.__qualname__ += suffix @classmethod def setUpClass(cls_, module=module): cls_._save_sys_modules = sys.modules.copy() sys.modules[TESTS] = module sys.modules['datetime'] = module.datetime_module sys.modules['_strptime'] = module._strptime @classmethod def tearDownClass(cls_): sys.modules.clear() sys.modules.update(cls_._save_sys_modules) cls.setUpClass = setUpClass cls.tearDownClass = tearDownClass all_test_classes.extend(test_classes) def test_main(): run_unittest(*all_test_classes) 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_format.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_format.py
from test.support import verbose, TestFailed import locale import sys import test.support as support import unittest maxsize = support.MAX_Py_ssize_t # test string formatting operator (I am not sure if this is being tested # elsewhere but, surely, some of the given cases are *not* tested because # they crash python) # test on bytes object as well def testformat(formatstr, args, output=None, limit=None, overflowok=False): if verbose: if output: print("{!a} % {!a} =? {!a} ...".format(formatstr, args, output), end=' ') else: print("{!a} % {!a} works? ...".format(formatstr, args), end=' ') try: result = formatstr % args except OverflowError: if not overflowok: raise if verbose: print('overflow (this is fine)') else: if output and limit is None and result != output: if verbose: print('no') raise AssertionError("%r %% %r == %r != %r" % (formatstr, args, result, output)) # when 'limit' is specified, it determines how many characters # must match exactly; lengths must always match. # ex: limit=5, '12345678' matches '12345___' # (mainly for floating point format tests for which an exact match # can't be guaranteed due to rounding and representation errors) elif output and limit is not None and ( len(result)!=len(output) or result[:limit]!=output[:limit]): if verbose: print('no') print("%s %% %s == %s != %s" % \ (repr(formatstr), repr(args), repr(result), repr(output))) else: if verbose: print('yes') def testcommon(formatstr, args, output=None, limit=None, overflowok=False): # if formatstr is a str, test str, bytes, and bytearray; # otherwise, test bytes and bytearry if isinstance(formatstr, str): testformat(formatstr, args, output, limit, overflowok) b_format = formatstr.encode('ascii') else: b_format = formatstr ba_format = bytearray(b_format) b_args = [] if not isinstance(args, tuple): args = (args, ) b_args = tuple(args) if output is None: b_output = ba_output = None else: if isinstance(output, str): b_output = output.encode('ascii') else: b_output = output ba_output = bytearray(b_output) testformat(b_format, b_args, b_output, limit, overflowok) testformat(ba_format, b_args, ba_output, limit, overflowok) def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception as exc: if str(exc) == excmsg: if verbose: print("yes") else: if verbose: print('no') print('Unexpected ', exception, ':', repr(str(exc))) except: if verbose: print('no') print('Unexpected exception') raise else: raise TestFailed('did not get expected exception: %s' % excmsg) def test_exc_common(formatstr, args, exception, excmsg): # test str and bytes test_exc(formatstr, args, exception, excmsg) test_exc(formatstr.encode('ascii'), args, exception, excmsg) class FormatTest(unittest.TestCase): def test_common_format(self): # test the format identifiers that work the same across # str, bytes, and bytearrays (integer, float, oct, hex) testcommon("%%", (), "%") testcommon("%.1d", (1,), "1") testcommon("%.*d", (sys.maxsize,1), overflowok=True) # expect overflow testcommon("%.100d", (1,), '00000000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '00000001', overflowok=True) testcommon("%#.117x", (1,), '0x00000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '0000000000000000000000000001', overflowok=True) testcommon("%#.118x", (1,), '0x00000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '00000000000000000000000000001', overflowok=True) testcommon("%f", (1.0,), "1.000000") # these are trying to test the limits of the internal magic-number-length # formatting buffer, if that number changes then these tests are less # effective testcommon("%#.*g", (109, -1.e+49/3.)) testcommon("%#.*g", (110, -1.e+49/3.)) testcommon("%#.*g", (110, -1.e+100/3.)) # test some ridiculously large precision, expect overflow testcommon('%12.*f', (123456, 1.0)) # check for internal overflow validation on length of precision # these tests should no longer cause overflow in Python # 2.7/3.1 and later. testcommon("%#.*g", (110, -1.e+100/3.)) testcommon("%#.*G", (110, -1.e+100/3.)) testcommon("%#.*f", (110, -1.e+100/3.)) testcommon("%#.*F", (110, -1.e+100/3.)) # Formatting of integers. Overflow is not ok testcommon("%x", 10, "a") testcommon("%x", 100000000000, "174876e800") testcommon("%o", 10, "12") testcommon("%o", 100000000000, "1351035564000") testcommon("%d", 10, "10") testcommon("%d", 100000000000, "100000000000") big = 123456789012345678901234567890 testcommon("%d", big, "123456789012345678901234567890") testcommon("%d", -big, "-123456789012345678901234567890") testcommon("%5d", -big, "-123456789012345678901234567890") testcommon("%31d", -big, "-123456789012345678901234567890") testcommon("%32d", -big, " -123456789012345678901234567890") testcommon("%-32d", -big, "-123456789012345678901234567890 ") testcommon("%032d", -big, "-0123456789012345678901234567890") testcommon("%-032d", -big, "-123456789012345678901234567890 ") testcommon("%034d", -big, "-000123456789012345678901234567890") testcommon("%034d", big, "0000123456789012345678901234567890") testcommon("%0+34d", big, "+000123456789012345678901234567890") testcommon("%+34d", big, " +123456789012345678901234567890") testcommon("%34d", big, " 123456789012345678901234567890") testcommon("%.2d", big, "123456789012345678901234567890") testcommon("%.30d", big, "123456789012345678901234567890") testcommon("%.31d", big, "0123456789012345678901234567890") testcommon("%32.31d", big, " 0123456789012345678901234567890") testcommon("%d", float(big), "123456________________________", 6) big = 0x1234567890abcdef12345 # 21 hex digits testcommon("%x", big, "1234567890abcdef12345") testcommon("%x", -big, "-1234567890abcdef12345") testcommon("%5x", -big, "-1234567890abcdef12345") testcommon("%22x", -big, "-1234567890abcdef12345") testcommon("%23x", -big, " -1234567890abcdef12345") testcommon("%-23x", -big, "-1234567890abcdef12345 ") testcommon("%023x", -big, "-01234567890abcdef12345") testcommon("%-023x", -big, "-1234567890abcdef12345 ") testcommon("%025x", -big, "-0001234567890abcdef12345") testcommon("%025x", big, "00001234567890abcdef12345") testcommon("%0+25x", big, "+0001234567890abcdef12345") testcommon("%+25x", big, " +1234567890abcdef12345") testcommon("%25x", big, " 1234567890abcdef12345") testcommon("%.2x", big, "1234567890abcdef12345") testcommon("%.21x", big, "1234567890abcdef12345") testcommon("%.22x", big, "01234567890abcdef12345") testcommon("%23.22x", big, " 01234567890abcdef12345") testcommon("%-23.22x", big, "01234567890abcdef12345 ") testcommon("%X", big, "1234567890ABCDEF12345") testcommon("%#X", big, "0X1234567890ABCDEF12345") testcommon("%#x", big, "0x1234567890abcdef12345") testcommon("%#x", -big, "-0x1234567890abcdef12345") testcommon("%#27x", big, " 0x1234567890abcdef12345") testcommon("%#-27x", big, "0x1234567890abcdef12345 ") testcommon("%#027x", big, "0x00001234567890abcdef12345") testcommon("%#.23x", big, "0x001234567890abcdef12345") testcommon("%#.23x", -big, "-0x001234567890abcdef12345") testcommon("%#27.23x", big, " 0x001234567890abcdef12345") testcommon("%#-27.23x", big, "0x001234567890abcdef12345 ") testcommon("%#027.23x", big, "0x00001234567890abcdef12345") testcommon("%#+.23x", big, "+0x001234567890abcdef12345") testcommon("%# .23x", big, " 0x001234567890abcdef12345") testcommon("%#+.23X", big, "+0X001234567890ABCDEF12345") # next one gets two leading zeroes from precision, and another from the # 0 flag and the width testcommon("%#+027.23X", big, "+0X0001234567890ABCDEF12345") testcommon("%# 027.23X", big, " 0X0001234567890ABCDEF12345") # same, except no 0 flag testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345") testcommon("%#-+27.23x", big, "+0x001234567890abcdef12345 ") testcommon("%#- 27.23x", big, " 0x001234567890abcdef12345 ") big = 0o12345670123456701234567012345670 # 32 octal digits testcommon("%o", big, "12345670123456701234567012345670") testcommon("%o", -big, "-12345670123456701234567012345670") testcommon("%5o", -big, "-12345670123456701234567012345670") testcommon("%33o", -big, "-12345670123456701234567012345670") testcommon("%34o", -big, " -12345670123456701234567012345670") testcommon("%-34o", -big, "-12345670123456701234567012345670 ") testcommon("%034o", -big, "-012345670123456701234567012345670") testcommon("%-034o", -big, "-12345670123456701234567012345670 ") testcommon("%036o", -big, "-00012345670123456701234567012345670") testcommon("%036o", big, "000012345670123456701234567012345670") testcommon("%0+36o", big, "+00012345670123456701234567012345670") testcommon("%+36o", big, " +12345670123456701234567012345670") testcommon("%36o", big, " 12345670123456701234567012345670") testcommon("%.2o", big, "12345670123456701234567012345670") testcommon("%.32o", big, "12345670123456701234567012345670") testcommon("%.33o", big, "012345670123456701234567012345670") testcommon("%34.33o", big, " 012345670123456701234567012345670") testcommon("%-34.33o", big, "012345670123456701234567012345670 ") testcommon("%o", big, "12345670123456701234567012345670") testcommon("%#o", big, "0o12345670123456701234567012345670") testcommon("%#o", -big, "-0o12345670123456701234567012345670") testcommon("%#38o", big, " 0o12345670123456701234567012345670") testcommon("%#-38o", big, "0o12345670123456701234567012345670 ") testcommon("%#038o", big, "0o000012345670123456701234567012345670") testcommon("%#.34o", big, "0o0012345670123456701234567012345670") testcommon("%#.34o", -big, "-0o0012345670123456701234567012345670") testcommon("%#38.34o", big, " 0o0012345670123456701234567012345670") testcommon("%#-38.34o", big, "0o0012345670123456701234567012345670 ") testcommon("%#038.34o", big, "0o000012345670123456701234567012345670") testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670") testcommon("%# .34o", big, " 0o0012345670123456701234567012345670") testcommon("%#+38.34o", big, " +0o0012345670123456701234567012345670") testcommon("%#-+38.34o", big, "+0o0012345670123456701234567012345670 ") testcommon("%#- 38.34o", big, " 0o0012345670123456701234567012345670 ") testcommon("%#+038.34o", big, "+0o00012345670123456701234567012345670") testcommon("%# 038.34o", big, " 0o00012345670123456701234567012345670") # next one gets one leading zero from precision testcommon("%.33o", big, "012345670123456701234567012345670") # base marker added in spite of leading zero (different to Python 2) testcommon("%#.33o", big, "0o012345670123456701234567012345670") # reduce precision, and base marker is always added testcommon("%#.32o", big, "0o12345670123456701234567012345670") # one leading zero from precision, plus two from "0" flag & width testcommon("%035.33o", big, "00012345670123456701234567012345670") # base marker shouldn't change the size testcommon("%0#35.33o", big, "0o012345670123456701234567012345670") # Some small ints, in both Python int and flavors). testcommon("%d", 42, "42") testcommon("%d", -42, "-42") testcommon("%d", 42.0, "42") testcommon("%#x", 1, "0x1") testcommon("%#X", 1, "0X1") testcommon("%#o", 1, "0o1") testcommon("%#o", 0, "0o0") testcommon("%o", 0, "0") testcommon("%d", 0, "0") testcommon("%#x", 0, "0x0") testcommon("%#X", 0, "0X0") testcommon("%x", 0x42, "42") testcommon("%x", -0x42, "-42") testcommon("%o", 0o42, "42") testcommon("%o", -0o42, "-42") # alternate float formatting testcommon('%g', 1.1, '1.1') testcommon('%#g', 1.1, '1.10000') if verbose: print('Testing exceptions') test_exc_common('%', (), ValueError, "incomplete format") test_exc_common('% %s', 1, ValueError, "unsupported format character '%' (0x25) at index 2") test_exc_common('%d', '1', TypeError, "%d format: a number is required, not str") test_exc_common('%d', b'1', TypeError, "%d format: a number is required, not bytes") test_exc_common('%x', '1', TypeError, "%x format: an integer is required, not str") test_exc_common('%x', 3.14, TypeError, "%x format: an integer is required, not float") def test_str_format(self): testformat("%r", "\u0378", "'\\u0378'") # non printable testformat("%a", "\u0378", "'\\u0378'") # non printable testformat("%r", "\u0374", "'\u0374'") # printable testformat("%a", "\u0374", "'\\u0374'") # printable # Test exception for unknown format characters, etc. if verbose: print('Testing exceptions') test_exc('abc %b', 1, ValueError, "unsupported format character 'b' (0x62) at index 5") #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, # "unsupported format character '?' (0x3000) at index 5") test_exc('%g', '1', TypeError, "must be real number, not str") test_exc('no format', '1', TypeError, "not all arguments converted during string formatting") test_exc('%c', -1, OverflowError, "%c arg not in range(0x110000)") test_exc('%c', sys.maxunicode+1, OverflowError, "%c arg not in range(0x110000)") #test_exc('%c', 2**128, OverflowError, "%c arg not in range(0x110000)") test_exc('%c', 3.14, TypeError, "%c requires int or char") test_exc('%c', 'ab', TypeError, "%c requires int or char") test_exc('%c', b'x', TypeError, "%c requires int or char") if maxsize == 2**31-1: # crashes 2.2.1 and earlier: try: "%*d"%(maxsize, -127) except MemoryError: pass else: raise TestFailed('"%*d"%(maxsize, -127) should fail') def test_bytes_and_bytearray_format(self): # %c will insert a single byte, either from an int in range(256), or # from a bytes argument of length 1, not from a str. testcommon(b"%c", 7, b"\x07") testcommon(b"%c", b"Z", b"Z") testcommon(b"%c", bytearray(b"Z"), b"Z") testcommon(b"%5c", 65, b" A") testcommon(b"%-5c", 65, b"A ") # %b will insert a series of bytes, either from a type that supports # the Py_buffer protocol, or something that has a __bytes__ method class FakeBytes(object): def __bytes__(self): return b'123' fb = FakeBytes() testcommon(b"%b", b"abc", b"abc") testcommon(b"%b", bytearray(b"def"), b"def") testcommon(b"%b", fb, b"123") testcommon(b"%b", memoryview(b"abc"), b"abc") # # %s is an alias for %b -- should only be used for Py2/3 code testcommon(b"%s", b"abc", b"abc") testcommon(b"%s", bytearray(b"def"), b"def") testcommon(b"%s", fb, b"123") testcommon(b"%s", memoryview(b"abc"), b"abc") # %a will give the equivalent of # repr(some_obj).encode('ascii', 'backslashreplace') testcommon(b"%a", 3.14, b"3.14") testcommon(b"%a", b"ghi", b"b'ghi'") testcommon(b"%a", "jkl", b"'jkl'") testcommon(b"%a", "\u0544", b"'\\u0544'") # %r is an alias for %a testcommon(b"%r", 3.14, b"3.14") testcommon(b"%r", b"ghi", b"b'ghi'") testcommon(b"%r", "jkl", b"'jkl'") testcommon(b"%r", "\u0544", b"'\\u0544'") # Test exception for unknown format characters, etc. if verbose: print('Testing exceptions') test_exc(b'%g', '1', TypeError, "float argument required, not str") test_exc(b'%g', b'1', TypeError, "float argument required, not bytes") test_exc(b'no format', 7, TypeError, "not all arguments converted during bytes formatting") test_exc(b'no format', b'1', TypeError, "not all arguments converted during bytes formatting") test_exc(b'no format', bytearray(b'1'), TypeError, "not all arguments converted during bytes formatting") test_exc(b"%c", -1, OverflowError, "%c arg not in range(256)") test_exc(b"%c", 256, OverflowError, "%c arg not in range(256)") test_exc(b"%c", 2**128, OverflowError, "%c arg not in range(256)") test_exc(b"%c", b"Za", TypeError, "%c requires an integer in range(256) or a single byte") test_exc(b"%c", "Y", TypeError, "%c requires an integer in range(256) or a single byte") test_exc(b"%c", 3.14, TypeError, "%c requires an integer in range(256) or a single byte") test_exc(b"%b", "Xc", TypeError, "%b requires a bytes-like object, " "or an object that implements __bytes__, not 'str'") test_exc(b"%s", "Wd", TypeError, "%b requires a bytes-like object, " "or an object that implements __bytes__, not 'str'") if maxsize == 2**31-1: # crashes 2.2.1 and earlier: try: "%*d"%(maxsize, -127) except MemoryError: pass else: raise TestFailed('"%*d"%(maxsize, -127) should fail') def test_nul(self): # test the null character testcommon("a\0b", (), 'a\0b') testcommon("a%cb", (0,), 'a\0b') testformat("a%sb", ('c\0d',), 'ac\0db') testcommon(b"a%sb", (b'c\0d',), b'ac\0db') def test_non_ascii(self): testformat("\u20ac=%f", (1.0,), "\u20ac=1.000000") self.assertEqual(format("abc", "\u2007<5"), "abc\u2007\u2007") self.assertEqual(format(123, "\u2007<5"), "123\u2007\u2007") self.assertEqual(format(12.3, "\u2007<6"), "12.3\u2007\u2007") self.assertEqual(format(0j, "\u2007<4"), "0j\u2007\u2007") self.assertEqual(format(1+2j, "\u2007<8"), "(1+2j)\u2007\u2007") self.assertEqual(format("abc", "\u2007>5"), "\u2007\u2007abc") self.assertEqual(format(123, "\u2007>5"), "\u2007\u2007123") self.assertEqual(format(12.3, "\u2007>6"), "\u2007\u200712.3") self.assertEqual(format(1+2j, "\u2007>8"), "\u2007\u2007(1+2j)") self.assertEqual(format(0j, "\u2007>4"), "\u2007\u20070j") self.assertEqual(format("abc", "\u2007^5"), "\u2007abc\u2007") self.assertEqual(format(123, "\u2007^5"), "\u2007123\u2007") self.assertEqual(format(12.3, "\u2007^6"), "\u200712.3\u2007") self.assertEqual(format(1+2j, "\u2007^8"), "\u2007(1+2j)\u2007") self.assertEqual(format(0j, "\u2007^4"), "\u20070j\u2007") def test_locale(self): try: oldloc = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, '') except locale.Error as err: self.skipTest("Cannot set locale: {}".format(err)) try: localeconv = locale.localeconv() sep = localeconv['thousands_sep'] point = localeconv['decimal_point'] text = format(123456789, "n") self.assertIn(sep, text) self.assertEqual(text.replace(sep, ''), '123456789') text = format(1234.5, "n") self.assertIn(sep, text) self.assertIn(point, text) self.assertEqual(text.replace(sep, ''), '1234' + point + '5') finally: locale.setlocale(locale.LC_ALL, oldloc) @support.cpython_only def test_optimisations(self): text = "abcde" # 5 characters self.assertIs("%s" % text, text) self.assertIs("%.5s" % text, text) self.assertIs("%.10s" % text, text) self.assertIs("%1s" % text, text) self.assertIs("%5s" % text, text) self.assertIs("{0}".format(text), text) self.assertIs("{0:s}".format(text), text) self.assertIs("{0:.5s}".format(text), text) self.assertIs("{0:.10s}".format(text), text) self.assertIs("{0:1s}".format(text), text) self.assertIs("{0:5s}".format(text), text) self.assertIs(text % (), text) self.assertIs(text.format(), text) def test_precision(self): f = 1.2 self.assertEqual(format(f, ".0f"), "1") self.assertEqual(format(f, ".3f"), "1.200") with self.assertRaises(ValueError) as cm: format(f, ".%sf" % (sys.maxsize + 1)) c = complex(f) self.assertEqual(format(c, ".0f"), "1+0j") self.assertEqual(format(c, ".3f"), "1.200+0.000j") with self.assertRaises(ValueError) as cm: format(c, ".%sf" % (sys.maxsize + 1)) @support.cpython_only def test_precision_c_limits(self): from _testcapi import INT_MAX f = 1.2 with self.assertRaises(ValueError) as cm: format(f, ".%sf" % (INT_MAX + 1)) c = complex(f) with self.assertRaises(ValueError) as cm: format(c, ".%sf" % (INT_MAX + 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/ann_module2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ann_module2.py
""" Some correct syntax for variable annotation here. More examples are in test_grammar and test_parser. """ from typing import no_type_check, ClassVar i: int = 1 j: int x: float = i/10 def f(): class C: ... return C() f().new_attr: object = object() class C: def __init__(self, x: int) -> None: self.x = x c = C(5) c.new_attr: int = 10 __annotations__ = {} @no_type_check class NTC: def meth(self, param: complex) -> None: ... class CV: var: ClassVar['CV'] CV.var = CV()
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_idle.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_idle.py
import unittest from test.support import import_module # Skip test_idle if _tkinter wasn't built, if tkinter is missing, # if tcl/tk is not the 8.5+ needed for ttk widgets, # or if idlelib is missing (not installed). tk = import_module('tkinter') # Also imports _tkinter. if tk.TkVersion < 8.5: raise unittest.SkipTest("IDLE requires tk 8.5 or later.") idlelib = import_module('idlelib') # Before importing and executing more of idlelib, # tell IDLE to avoid changing the environment. idlelib.testing = True # Unittest.main and test.libregrtest.runtest.runtest_inner # call load_tests, when present here, to discover tests to run. from idlelib.idle_test import load_tests if __name__ == '__main__': tk.NoDefaultRoot() unittest.main(exit=False) tk._support_default_root = 1 tk._default_root = None
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_mailbox.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_mailbox.py
import os import sys import time import stat import socket import email import email.message import re import io import tempfile from test import support import unittest import textwrap import mailbox import glob class TestBase: all_mailbox_types = (mailbox.Message, mailbox.MaildirMessage, mailbox.mboxMessage, mailbox.MHMessage, mailbox.BabylMessage, mailbox.MMDFMessage) def _check_sample(self, msg): # Inspect a mailbox.Message representation of the sample message self.assertIsInstance(msg, email.message.Message) self.assertIsInstance(msg, mailbox.Message) for key, value in _sample_headers.items(): self.assertIn(value, msg.get_all(key)) self.assertTrue(msg.is_multipart()) self.assertEqual(len(msg.get_payload()), len(_sample_payloads)) for i, payload in enumerate(_sample_payloads): part = msg.get_payload(i) self.assertIsInstance(part, email.message.Message) self.assertNotIsInstance(part, mailbox.Message) self.assertEqual(part.get_payload(), payload) def _delete_recursively(self, target): # Delete a file or delete a directory recursively if os.path.isdir(target): support.rmtree(target) elif os.path.exists(target): support.unlink(target) class TestMailbox(TestBase): maxDiff = None _factory = None # Overridden by subclasses to reuse tests _template = 'From: foo\n\n%s\n' def setUp(self): self._path = support.TESTFN self._delete_recursively(self._path) self._box = self._factory(self._path) def tearDown(self): self._box.close() self._delete_recursively(self._path) def test_add(self): # Add copies of a sample message keys = [] keys.append(self._box.add(self._template % 0)) self.assertEqual(len(self._box), 1) keys.append(self._box.add(mailbox.Message(_sample_message))) self.assertEqual(len(self._box), 2) keys.append(self._box.add(email.message_from_string(_sample_message))) self.assertEqual(len(self._box), 3) keys.append(self._box.add(io.BytesIO(_bytes_sample_message))) self.assertEqual(len(self._box), 4) keys.append(self._box.add(_sample_message)) self.assertEqual(len(self._box), 5) keys.append(self._box.add(_bytes_sample_message)) self.assertEqual(len(self._box), 6) with self.assertWarns(DeprecationWarning): keys.append(self._box.add( io.TextIOWrapper(io.BytesIO(_bytes_sample_message)))) self.assertEqual(len(self._box), 7) self.assertEqual(self._box.get_string(keys[0]), self._template % 0) for i in (1, 2, 3, 4, 5, 6): self._check_sample(self._box[keys[i]]) _nonascii_msg = textwrap.dedent("""\ From: foo Subject: Falinaptár házhozszállítással. Már rendeltél? 0 """) def test_add_invalid_8bit_bytes_header(self): key = self._box.add(self._nonascii_msg.encode('latin-1')) self.assertEqual(len(self._box), 1) self.assertEqual(self._box.get_bytes(key), self._nonascii_msg.encode('latin-1')) def test_invalid_nonascii_header_as_string(self): subj = self._nonascii_msg.splitlines()[1] key = self._box.add(subj.encode('latin-1')) self.assertEqual(self._box.get_string(key), 'Subject: =?unknown-8bit?b?RmFsaW5hcHThciBo4Xpob3pzeuFsbO104XNz' 'YWwuIE3hciByZW5kZWx06Ww/?=\n\n') def test_add_nonascii_string_header_raises(self): with self.assertRaisesRegex(ValueError, "ASCII-only"): self._box.add(self._nonascii_msg) self._box.flush() self.assertEqual(len(self._box), 0) self.assertMailboxEmpty() def test_add_that_raises_leaves_mailbox_empty(self): def raiser(*args, **kw): raise Exception("a fake error") support.patch(self, email.generator.BytesGenerator, 'flatten', raiser) with self.assertRaises(Exception): self._box.add(email.message_from_string("From: Alphöso")) self.assertEqual(len(self._box), 0) self._box.close() self.assertMailboxEmpty() _non_latin_bin_msg = textwrap.dedent("""\ From: foo@bar.com To: báz Subject: Maintenant je vous présente mon collègue, le pouf célèbre \tJean de Baddie Mime-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit Да, они летят. """).encode('utf-8') def test_add_8bit_body(self): key = self._box.add(self._non_latin_bin_msg) self.assertEqual(self._box.get_bytes(key), self._non_latin_bin_msg) with self._box.get_file(key) as f: self.assertEqual(f.read(), self._non_latin_bin_msg.replace(b'\n', os.linesep.encode())) self.assertEqual(self._box[key].get_payload(), "Да, они летят.\n") def test_add_binary_file(self): with tempfile.TemporaryFile('wb+') as f: f.write(_bytes_sample_message) f.seek(0) key = self._box.add(f) self.assertEqual(self._box.get_bytes(key).split(b'\n'), _bytes_sample_message.split(b'\n')) def test_add_binary_nonascii_file(self): with tempfile.TemporaryFile('wb+') as f: f.write(self._non_latin_bin_msg) f.seek(0) key = self._box.add(f) self.assertEqual(self._box.get_bytes(key).split(b'\n'), self._non_latin_bin_msg.split(b'\n')) def test_add_text_file_warns(self): with tempfile.TemporaryFile('w+') as f: f.write(_sample_message) f.seek(0) with self.assertWarns(DeprecationWarning): key = self._box.add(f) self.assertEqual(self._box.get_bytes(key).split(b'\n'), _bytes_sample_message.split(b'\n')) def test_add_StringIO_warns(self): with self.assertWarns(DeprecationWarning): key = self._box.add(io.StringIO(self._template % "0")) self.assertEqual(self._box.get_string(key), self._template % "0") def test_add_nonascii_StringIO_raises(self): with self.assertWarns(DeprecationWarning): with self.assertRaisesRegex(ValueError, "ASCII-only"): self._box.add(io.StringIO(self._nonascii_msg)) self.assertEqual(len(self._box), 0) self._box.close() self.assertMailboxEmpty() def test_remove(self): # Remove messages using remove() self._test_remove_or_delitem(self._box.remove) def test_delitem(self): # Remove messages using __delitem__() self._test_remove_or_delitem(self._box.__delitem__) def _test_remove_or_delitem(self, method): # (Used by test_remove() and test_delitem().) key0 = self._box.add(self._template % 0) key1 = self._box.add(self._template % 1) self.assertEqual(len(self._box), 2) method(key0) self.assertEqual(len(self._box), 1) self.assertRaises(KeyError, lambda: self._box[key0]) self.assertRaises(KeyError, lambda: method(key0)) self.assertEqual(self._box.get_string(key1), self._template % 1) key2 = self._box.add(self._template % 2) self.assertEqual(len(self._box), 2) method(key2) self.assertEqual(len(self._box), 1) self.assertRaises(KeyError, lambda: self._box[key2]) self.assertRaises(KeyError, lambda: method(key2)) self.assertEqual(self._box.get_string(key1), self._template % 1) method(key1) self.assertEqual(len(self._box), 0) self.assertRaises(KeyError, lambda: self._box[key1]) self.assertRaises(KeyError, lambda: method(key1)) def test_discard(self, repetitions=10): # Discard messages key0 = self._box.add(self._template % 0) key1 = self._box.add(self._template % 1) self.assertEqual(len(self._box), 2) self._box.discard(key0) self.assertEqual(len(self._box), 1) self.assertRaises(KeyError, lambda: self._box[key0]) self._box.discard(key0) self.assertEqual(len(self._box), 1) self.assertRaises(KeyError, lambda: self._box[key0]) def test_get(self): # Retrieve messages using get() key0 = self._box.add(self._template % 0) msg = self._box.get(key0) self.assertEqual(msg['from'], 'foo') self.assertEqual(msg.get_payload(), '0\n') self.assertIsNone(self._box.get('foo')) self.assertIs(self._box.get('foo', False), False) self._box.close() self._box = self._factory(self._path) key1 = self._box.add(self._template % 1) msg = self._box.get(key1) self.assertEqual(msg['from'], 'foo') self.assertEqual(msg.get_payload(), '1\n') def test_getitem(self): # Retrieve message using __getitem__() key0 = self._box.add(self._template % 0) msg = self._box[key0] self.assertEqual(msg['from'], 'foo') self.assertEqual(msg.get_payload(), '0\n') self.assertRaises(KeyError, lambda: self._box['foo']) self._box.discard(key0) self.assertRaises(KeyError, lambda: self._box[key0]) def test_get_message(self): # Get Message representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) msg0 = self._box.get_message(key0) self.assertIsInstance(msg0, mailbox.Message) self.assertEqual(msg0['from'], 'foo') self.assertEqual(msg0.get_payload(), '0\n') self._check_sample(self._box.get_message(key1)) def test_get_bytes(self): # Get bytes representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) self.assertEqual(self._box.get_bytes(key0), (self._template % 0).encode('ascii')) self.assertEqual(self._box.get_bytes(key1), _bytes_sample_message) def test_get_string(self): # Get string representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) self.assertEqual(self._box.get_string(key0), self._template % 0) self.assertEqual(self._box.get_string(key1).split('\n'), _sample_message.split('\n')) def test_get_file(self): # Get file representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) with self._box.get_file(key0) as file: data0 = file.read() with self._box.get_file(key1) as file: data1 = file.read() self.assertEqual(data0.decode('ascii').replace(os.linesep, '\n'), self._template % 0) self.assertEqual(data1.decode('ascii').replace(os.linesep, '\n'), _sample_message) def test_get_file_can_be_closed_twice(self): # Issue 11700 key = self._box.add(_sample_message) f = self._box.get_file(key) f.close() f.close() def test_iterkeys(self): # Get keys using iterkeys() self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False) def test_keys(self): # Get keys using keys() self._check_iteration(self._box.keys, do_keys=True, do_values=False) def test_itervalues(self): # Get values using itervalues() self._check_iteration(self._box.itervalues, do_keys=False, do_values=True) def test_iter(self): # Get values using __iter__() self._check_iteration(self._box.__iter__, do_keys=False, do_values=True) def test_values(self): # Get values using values() self._check_iteration(self._box.values, do_keys=False, do_values=True) def test_iteritems(self): # Get keys and values using iteritems() self._check_iteration(self._box.iteritems, do_keys=True, do_values=True) def test_items(self): # Get keys and values using items() self._check_iteration(self._box.items, do_keys=True, do_values=True) def _check_iteration(self, method, do_keys, do_values, repetitions=10): for value in method(): self.fail("Not empty") keys, values = [], [] for i in range(repetitions): keys.append(self._box.add(self._template % i)) values.append(self._template % i) if do_keys and not do_values: returned_keys = list(method()) elif do_values and not do_keys: returned_values = list(method()) else: returned_keys, returned_values = [], [] for key, value in method(): returned_keys.append(key) returned_values.append(value) if do_keys: self.assertEqual(len(keys), len(returned_keys)) self.assertEqual(set(keys), set(returned_keys)) if do_values: count = 0 for value in returned_values: self.assertEqual(value['from'], 'foo') self.assertLess(int(value.get_payload()), repetitions) count += 1 self.assertEqual(len(values), count) def test_contains(self): # Check existence of keys using __contains__() self.assertNotIn('foo', self._box) key0 = self._box.add(self._template % 0) self.assertIn(key0, self._box) self.assertNotIn('foo', self._box) key1 = self._box.add(self._template % 1) self.assertIn(key1, self._box) self.assertIn(key0, self._box) self.assertNotIn('foo', self._box) self._box.remove(key0) self.assertNotIn(key0, self._box) self.assertIn(key1, self._box) self.assertNotIn('foo', self._box) self._box.remove(key1) self.assertNotIn(key1, self._box) self.assertNotIn(key0, self._box) self.assertNotIn('foo', self._box) def test_len(self, repetitions=10): # Get message count keys = [] for i in range(repetitions): self.assertEqual(len(self._box), i) keys.append(self._box.add(self._template % i)) self.assertEqual(len(self._box), i + 1) for i in range(repetitions): self.assertEqual(len(self._box), repetitions - i) self._box.remove(keys[i]) self.assertEqual(len(self._box), repetitions - i - 1) def test_set_item(self): # Modify messages using __setitem__() key0 = self._box.add(self._template % 'original 0') self.assertEqual(self._box.get_string(key0), self._template % 'original 0') key1 = self._box.add(self._template % 'original 1') self.assertEqual(self._box.get_string(key1), self._template % 'original 1') self._box[key0] = self._template % 'changed 0' self.assertEqual(self._box.get_string(key0), self._template % 'changed 0') self._box[key1] = self._template % 'changed 1' self.assertEqual(self._box.get_string(key1), self._template % 'changed 1') self._box[key0] = _sample_message self._check_sample(self._box[key0]) self._box[key1] = self._box[key0] self._check_sample(self._box[key1]) self._box[key0] = self._template % 'original 0' self.assertEqual(self._box.get_string(key0), self._template % 'original 0') self._check_sample(self._box[key1]) self.assertRaises(KeyError, lambda: self._box.__setitem__('foo', 'bar')) self.assertRaises(KeyError, lambda: self._box['foo']) self.assertEqual(len(self._box), 2) def test_clear(self, iterations=10): # Remove all messages using clear() keys = [] for i in range(iterations): self._box.add(self._template % i) for i, key in enumerate(keys): self.assertEqual(self._box.get_string(key), self._template % i) self._box.clear() self.assertEqual(len(self._box), 0) for i, key in enumerate(keys): self.assertRaises(KeyError, lambda: self._box.get_string(key)) def test_pop(self): # Get and remove a message using pop() key0 = self._box.add(self._template % 0) self.assertIn(key0, self._box) key1 = self._box.add(self._template % 1) self.assertIn(key1, self._box) self.assertEqual(self._box.pop(key0).get_payload(), '0\n') self.assertNotIn(key0, self._box) self.assertIn(key1, self._box) key2 = self._box.add(self._template % 2) self.assertIn(key2, self._box) self.assertEqual(self._box.pop(key2).get_payload(), '2\n') self.assertNotIn(key2, self._box) self.assertIn(key1, self._box) self.assertEqual(self._box.pop(key1).get_payload(), '1\n') self.assertNotIn(key1, self._box) self.assertEqual(len(self._box), 0) def test_popitem(self, iterations=10): # Get and remove an arbitrary (key, message) using popitem() keys = [] for i in range(10): keys.append(self._box.add(self._template % i)) seen = [] for i in range(10): key, msg = self._box.popitem() self.assertIn(key, keys) self.assertNotIn(key, seen) seen.append(key) self.assertEqual(int(msg.get_payload()), keys.index(key)) self.assertEqual(len(self._box), 0) for key in keys: self.assertRaises(KeyError, lambda: self._box[key]) def test_update(self): # Modify multiple messages using update() key0 = self._box.add(self._template % 'original 0') key1 = self._box.add(self._template % 'original 1') key2 = self._box.add(self._template % 'original 2') self._box.update({key0: self._template % 'changed 0', key2: _sample_message}) self.assertEqual(len(self._box), 3) self.assertEqual(self._box.get_string(key0), self._template % 'changed 0') self.assertEqual(self._box.get_string(key1), self._template % 'original 1') self._check_sample(self._box[key2]) self._box.update([(key2, self._template % 'changed 2'), (key1, self._template % 'changed 1'), (key0, self._template % 'original 0')]) self.assertEqual(len(self._box), 3) self.assertEqual(self._box.get_string(key0), self._template % 'original 0') self.assertEqual(self._box.get_string(key1), self._template % 'changed 1') self.assertEqual(self._box.get_string(key2), self._template % 'changed 2') self.assertRaises(KeyError, lambda: self._box.update({'foo': 'bar', key0: self._template % "changed 0"})) self.assertEqual(len(self._box), 3) self.assertEqual(self._box.get_string(key0), self._template % "changed 0") self.assertEqual(self._box.get_string(key1), self._template % "changed 1") self.assertEqual(self._box.get_string(key2), self._template % "changed 2") def test_flush(self): # Write changes to disk self._test_flush_or_close(self._box.flush, True) def test_popitem_and_flush_twice(self): # See #15036. self._box.add(self._template % 0) self._box.add(self._template % 1) self._box.flush() self._box.popitem() self._box.flush() self._box.popitem() self._box.flush() def test_lock_unlock(self): # Lock and unlock the mailbox self.assertFalse(os.path.exists(self._get_lock_path())) self._box.lock() self.assertTrue(os.path.exists(self._get_lock_path())) self._box.unlock() self.assertFalse(os.path.exists(self._get_lock_path())) def test_close(self): # Close mailbox and flush changes to disk self._test_flush_or_close(self._box.close, False) def _test_flush_or_close(self, method, should_call_close): contents = [self._template % i for i in range(3)] self._box.add(contents[0]) self._box.add(contents[1]) self._box.add(contents[2]) oldbox = self._box method() if should_call_close: self._box.close() self._box = self._factory(self._path) keys = self._box.keys() self.assertEqual(len(keys), 3) for key in keys: self.assertIn(self._box.get_string(key), contents) oldbox.close() def test_dump_message(self): # Write message representations to disk for input in (email.message_from_string(_sample_message), _sample_message, io.BytesIO(_bytes_sample_message)): output = io.BytesIO() self._box._dump_message(input, output) self.assertEqual(output.getvalue(), _bytes_sample_message.replace(b'\n', os.linesep.encode())) output = io.BytesIO() self.assertRaises(TypeError, lambda: self._box._dump_message(None, output)) def _get_lock_path(self): # Return the path of the dot lock file. May be overridden. return self._path + '.lock' class TestMailboxSuperclass(TestBase, unittest.TestCase): def test_notimplemented(self): # Test that all Mailbox methods raise NotImplementedException. box = mailbox.Mailbox('path') self.assertRaises(NotImplementedError, lambda: box.add('')) self.assertRaises(NotImplementedError, lambda: box.remove('')) self.assertRaises(NotImplementedError, lambda: box.__delitem__('')) self.assertRaises(NotImplementedError, lambda: box.discard('')) self.assertRaises(NotImplementedError, lambda: box.__setitem__('', '')) self.assertRaises(NotImplementedError, lambda: box.iterkeys()) self.assertRaises(NotImplementedError, lambda: box.keys()) self.assertRaises(NotImplementedError, lambda: box.itervalues().__next__()) self.assertRaises(NotImplementedError, lambda: box.__iter__().__next__()) self.assertRaises(NotImplementedError, lambda: box.values()) self.assertRaises(NotImplementedError, lambda: box.iteritems().__next__()) self.assertRaises(NotImplementedError, lambda: box.items()) self.assertRaises(NotImplementedError, lambda: box.get('')) self.assertRaises(NotImplementedError, lambda: box.__getitem__('')) self.assertRaises(NotImplementedError, lambda: box.get_message('')) self.assertRaises(NotImplementedError, lambda: box.get_string('')) self.assertRaises(NotImplementedError, lambda: box.get_bytes('')) self.assertRaises(NotImplementedError, lambda: box.get_file('')) self.assertRaises(NotImplementedError, lambda: '' in box) self.assertRaises(NotImplementedError, lambda: box.__contains__('')) self.assertRaises(NotImplementedError, lambda: box.__len__()) self.assertRaises(NotImplementedError, lambda: box.clear()) self.assertRaises(NotImplementedError, lambda: box.pop('')) self.assertRaises(NotImplementedError, lambda: box.popitem()) self.assertRaises(NotImplementedError, lambda: box.update((('', ''),))) self.assertRaises(NotImplementedError, lambda: box.flush()) self.assertRaises(NotImplementedError, lambda: box.lock()) self.assertRaises(NotImplementedError, lambda: box.unlock()) self.assertRaises(NotImplementedError, lambda: box.close()) class TestMaildir(TestMailbox, unittest.TestCase): _factory = lambda self, path, factory=None: mailbox.Maildir(path, factory) def setUp(self): TestMailbox.setUp(self) if (os.name == 'nt') or (sys.platform == 'cygwin'): self._box.colon = '!' def assertMailboxEmpty(self): self.assertEqual(os.listdir(os.path.join(self._path, 'tmp')), []) def test_add_MM(self): # Add a MaildirMessage instance msg = mailbox.MaildirMessage(self._template % 0) msg.set_subdir('cur') msg.set_info('foo') key = self._box.add(msg) self.assertTrue(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' % (key, self._box.colon)))) def test_get_MM(self): # Get a MaildirMessage instance msg = mailbox.MaildirMessage(self._template % 0) msg.set_subdir('cur') msg.set_flags('RF') key = self._box.add(msg) msg_returned = self._box.get_message(key) self.assertIsInstance(msg_returned, mailbox.MaildirMessage) self.assertEqual(msg_returned.get_subdir(), 'cur') self.assertEqual(msg_returned.get_flags(), 'FR') def test_set_MM(self): # Set with a MaildirMessage instance msg0 = mailbox.MaildirMessage(self._template % 0) msg0.set_flags('TP') key = self._box.add(msg0) msg_returned = self._box.get_message(key) self.assertEqual(msg_returned.get_subdir(), 'new') self.assertEqual(msg_returned.get_flags(), 'PT') msg1 = mailbox.MaildirMessage(self._template % 1) self._box[key] = msg1 msg_returned = self._box.get_message(key) self.assertEqual(msg_returned.get_subdir(), 'new') self.assertEqual(msg_returned.get_flags(), '') self.assertEqual(msg_returned.get_payload(), '1\n') msg2 = mailbox.MaildirMessage(self._template % 2) msg2.set_info('2,S') self._box[key] = msg2 self._box[key] = self._template % 3 msg_returned = self._box.get_message(key) self.assertEqual(msg_returned.get_subdir(), 'new') self.assertEqual(msg_returned.get_flags(), 'S') self.assertEqual(msg_returned.get_payload(), '3\n') def test_consistent_factory(self): # Add a message. msg = mailbox.MaildirMessage(self._template % 0) msg.set_subdir('cur') msg.set_flags('RF') key = self._box.add(msg) # Create new mailbox with class FakeMessage(mailbox.MaildirMessage): pass box = mailbox.Maildir(self._path, factory=FakeMessage) box.colon = self._box.colon msg2 = box.get_message(key) self.assertIsInstance(msg2, FakeMessage) def test_initialize_new(self): # Initialize a non-existent mailbox self.tearDown() self._box = mailbox.Maildir(self._path) self._check_basics() self._delete_recursively(self._path) self._box = self._factory(self._path, factory=None) self._check_basics() def test_initialize_existing(self): # Initialize an existing mailbox self.tearDown() for subdir in '', 'tmp', 'new', 'cur': os.mkdir(os.path.normpath(os.path.join(self._path, subdir))) self._box = mailbox.Maildir(self._path) self._check_basics() def _check_basics(self, factory=None): # (Used by test_open_new() and test_open_existing().) self.assertEqual(self._box._path, os.path.abspath(self._path)) self.assertEqual(self._box._factory, factory) for subdir in '', 'tmp', 'new', 'cur': path = os.path.join(self._path, subdir) mode = os.stat(path)[stat.ST_MODE] self.assertTrue(stat.S_ISDIR(mode), "Not a directory: '%s'" % path) def test_list_folders(self): # List folders self._box.add_folder('one') self._box.add_folder('two') self._box.add_folder('three') self.assertEqual(len(self._box.list_folders()), 3) self.assertEqual(set(self._box.list_folders()), set(('one', 'two', 'three'))) def test_get_folder(self): # Open folders self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') self.assertTrue(os.path.isdir(os.path.join(self._path, '.foo.bar'))) folder1 = self._box.get_folder('foo.bar') self.assertEqual(folder1.get_string(folder1.keys()[0]), self._template % 'bar') def test_add_and_remove_folders(self): # Delete folders self._box.add_folder('one') self._box.add_folder('two') self.assertEqual(len(self._box.list_folders()), 2) self.assertEqual(set(self._box.list_folders()), set(('one', 'two'))) self._box.remove_folder('one') self.assertEqual(len(self._box.list_folders()), 1) self.assertEqual(set(self._box.list_folders()), set(('two',))) self._box.add_folder('three') self.assertEqual(len(self._box.list_folders()), 2) self.assertEqual(set(self._box.list_folders()), set(('two', 'three'))) self._box.remove_folder('three') self.assertEqual(len(self._box.list_folders()), 1) self.assertEqual(set(self._box.list_folders()), set(('two',))) self._box.remove_folder('two') self.assertEqual(len(self._box.list_folders()), 0) self.assertEqual(self._box.list_folders(), []) def test_clean(self): # Remove old files from 'tmp' foo_path = os.path.join(self._path, 'tmp', 'foo') bar_path = os.path.join(self._path, 'tmp', 'bar') with open(foo_path, 'w') as f: f.write("@") with open(bar_path, 'w') as f: f.write("@") self._box.clean() self.assertTrue(os.path.exists(foo_path)) self.assertTrue(os.path.exists(bar_path)) foo_stat = os.stat(foo_path) os.utime(foo_path, (time.time() - 129600 - 2, foo_stat.st_mtime)) self._box.clean() self.assertFalse(os.path.exists(foo_path)) self.assertTrue(os.path.exists(bar_path)) def test_create_tmp(self, repetitions=10): # Create files in tmp directory hostname = socket.gethostname() if '/' in hostname: hostname = hostname.replace('/', r'\057') if ':' in hostname: hostname = hostname.replace(':', r'\072') pid = os.getpid() pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)" r"Q(?P<Q>\d+)\.(?P<host>[^:/]*)") previous_groups = None for x in range(repetitions): tmp_file = self._box._create_tmp() head, tail = os.path.split(tmp_file.name) self.assertEqual(head, os.path.abspath(os.path.join(self._path, "tmp")), "File in wrong location: '%s'" % head) match = pattern.match(tail) self.assertIsNotNone(match, "Invalid file name: '%s'" % tail) groups = match.groups() if previous_groups is not None: self.assertGreaterEqual(int(groups[0]), int(previous_groups[0]), "Non-monotonic seconds: '%s' before '%s'" % (previous_groups[0], groups[0])) if int(groups[0]) == int(previous_groups[0]): self.assertGreaterEqual(int(groups[1]), int(previous_groups[1]), "Non-monotonic milliseconds: '%s' before '%s'" % (previous_groups[1], groups[1])) self.assertEqual(int(groups[2]), pid, "Process ID mismatch: '%s' should be '%s'" % (groups[2], pid)) self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1, "Non-sequential counter: '%s' before '%s'" % (previous_groups[3], groups[3])) self.assertEqual(groups[4], hostname, "Host name mismatch: '%s' should be '%s'" % (groups[4], hostname)) previous_groups = groups tmp_file.write(_bytes_sample_message) tmp_file.seek(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/curses_tests.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/curses_tests.py
#!/usr/bin/env python3 # # $Id: ncurses.py 36559 2004-07-18 05:56:09Z tim_one $ # # Interactive test suite for the curses module. # This script displays various things and the user should verify whether # they display correctly. # import curses from curses import textpad def test_textpad(stdscr, insert_mode=False): ncols, nlines = 8, 3 uly, ulx = 3, 2 if insert_mode: mode = 'insert mode' else: mode = 'overwrite mode' stdscr.addstr(uly-3, ulx, "Use Ctrl-G to end editing (%s)." % mode) stdscr.addstr(uly-2, ulx, "Be sure to try typing in the lower-right corner.") win = curses.newwin(nlines, ncols, uly, ulx) textpad.rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols) stdscr.refresh() box = textpad.Textbox(win, insert_mode) contents = box.edit() stdscr.addstr(uly+ncols+2, 0, "Text entered in the box\n") stdscr.addstr(repr(contents)) stdscr.addstr('\n') stdscr.addstr('Press any key') stdscr.getch() for i in range(3): stdscr.move(uly+ncols+2 + i, 0) stdscr.clrtoeol() def main(stdscr): stdscr.clear() test_textpad(stdscr, False) test_textpad(stdscr, True) if __name__ == '__main__': curses.wrapper(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_numeric_tower.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_numeric_tower.py
# test interactions between int, float, Decimal and Fraction import unittest import random import math import sys import operator from decimal import Decimal as D from fractions import Fraction as F # Constants related to the hash implementation; hash(x) is based # on the reduction of x modulo the prime _PyHASH_MODULUS. _PyHASH_MODULUS = sys.hash_info.modulus _PyHASH_INF = sys.hash_info.inf class HashTest(unittest.TestCase): def check_equal_hash(self, x, y): # check both that x and y are equal and that their hashes are equal self.assertEqual(hash(x), hash(y), "got different hashes for {!r} and {!r}".format(x, y)) self.assertEqual(x, y) def test_bools(self): self.check_equal_hash(False, 0) self.check_equal_hash(True, 1) def test_integers(self): # check that equal values hash equal # exact integers for i in range(-1000, 1000): self.check_equal_hash(i, float(i)) self.check_equal_hash(i, D(i)) self.check_equal_hash(i, F(i)) # the current hash is based on reduction modulo 2**n-1 for some # n, so pay special attention to numbers of the form 2**n and 2**n-1. for i in range(100): n = 2**i - 1 if n == int(float(n)): self.check_equal_hash(n, float(n)) self.check_equal_hash(-n, -float(n)) self.check_equal_hash(n, D(n)) self.check_equal_hash(n, F(n)) self.check_equal_hash(-n, D(-n)) self.check_equal_hash(-n, F(-n)) n = 2**i self.check_equal_hash(n, float(n)) self.check_equal_hash(-n, -float(n)) self.check_equal_hash(n, D(n)) self.check_equal_hash(n, F(n)) self.check_equal_hash(-n, D(-n)) self.check_equal_hash(-n, F(-n)) # random values of various sizes for _ in range(1000): e = random.randrange(300) n = random.randrange(-10**e, 10**e) self.check_equal_hash(n, D(n)) self.check_equal_hash(n, F(n)) if n == int(float(n)): self.check_equal_hash(n, float(n)) def test_binary_floats(self): # check that floats hash equal to corresponding Fractions and Decimals # floats that are distinct but numerically equal should hash the same self.check_equal_hash(0.0, -0.0) # zeros self.check_equal_hash(0.0, D(0)) self.check_equal_hash(-0.0, D(0)) self.check_equal_hash(-0.0, D('-0.0')) self.check_equal_hash(0.0, F(0)) # infinities and nans self.check_equal_hash(float('inf'), D('inf')) self.check_equal_hash(float('-inf'), D('-inf')) for _ in range(1000): x = random.random() * math.exp(random.random()*200.0 - 100.0) self.check_equal_hash(x, D.from_float(x)) self.check_equal_hash(x, F.from_float(x)) def test_complex(self): # complex numbers with zero imaginary part should hash equal to # the corresponding float test_values = [0.0, -0.0, 1.0, -1.0, 0.40625, -5136.5, float('inf'), float('-inf')] for zero in -0.0, 0.0: for value in test_values: self.check_equal_hash(value, complex(value, zero)) def test_decimals(self): # check that Decimal instances that have different representations # but equal values give the same hash zeros = ['0', '-0', '0.0', '-0.0e10', '000e-10'] for zero in zeros: self.check_equal_hash(D(zero), D(0)) self.check_equal_hash(D('1.00'), D(1)) self.check_equal_hash(D('1.00000'), D(1)) self.check_equal_hash(D('-1.00'), D(-1)) self.check_equal_hash(D('-1.00000'), D(-1)) self.check_equal_hash(D('123e2'), D(12300)) self.check_equal_hash(D('1230e1'), D(12300)) self.check_equal_hash(D('12300'), D(12300)) self.check_equal_hash(D('12300.0'), D(12300)) self.check_equal_hash(D('12300.00'), D(12300)) self.check_equal_hash(D('12300.000'), D(12300)) def test_fractions(self): # check special case for fractions where either the numerator # or the denominator is a multiple of _PyHASH_MODULUS self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF) self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF) self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0) self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0) def test_hash_normalization(self): # Test for a bug encountered while changing long_hash. # # Given objects x and y, it should be possible for y's # __hash__ method to return hash(x) in order to ensure that # hash(x) == hash(y). But hash(x) is not exactly equal to the # result of x.__hash__(): there's some internal normalization # to make sure that the result fits in a C long, and is not # equal to the invalid hash value -1. This internal # normalization must therefore not change the result of # hash(x) for any x. class HalibutProxy: def __hash__(self): return hash('halibut') def __eq__(self, other): return other == 'halibut' x = {'halibut', HalibutProxy()} self.assertEqual(len(x), 1) class ComparisonTest(unittest.TestCase): def test_mixed_comparisons(self): # ordered list of distinct test values of various types: # int, float, Fraction, Decimal test_values = [ float('-inf'), D('-1e425000000'), -1e308, F(-22, 7), -3.14, -2, 0.0, 1e-320, True, F('1.2'), D('1.3'), float('1.4'), F(275807, 195025), D('1.414213562373095048801688724'), F(114243, 80782), F(473596569, 84615), 7e200, D('infinity'), ] for i, first in enumerate(test_values): for second in test_values[i+1:]: self.assertLess(first, second) self.assertLessEqual(first, second) self.assertGreater(second, first) self.assertGreaterEqual(second, first) def test_complex(self): # comparisons with complex are special: equality and inequality # comparisons should always succeed, but order comparisons should # raise TypeError. z = 1.0 + 0j w = -3.14 + 2.7j for v in 1, 1.0, F(1), D(1), complex(1): self.assertEqual(z, v) self.assertEqual(v, z) for v in 2, 2.0, F(2), D(2), complex(2): self.assertNotEqual(z, v) self.assertNotEqual(v, z) self.assertNotEqual(w, v) self.assertNotEqual(v, w) for v in (1, 1.0, F(1), D(1), complex(1), 2, 2.0, F(2), D(2), complex(2), w): for op in operator.le, operator.lt, operator.ge, operator.gt: self.assertRaises(TypeError, op, z, v) self.assertRaises(TypeError, op, v, z) 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_tcl.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tcl.py
import unittest import re import subprocess import sys import os from test import support # Skip this test if the _tkinter module wasn't built. _tkinter = support.import_module('_tkinter') import tkinter from tkinter import Tcl from _tkinter import TclError try: from _testcapi import INT_MAX, PY_SSIZE_T_MAX except ImportError: INT_MAX = PY_SSIZE_T_MAX = sys.maxsize tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) _tk_patchlevel = None def get_tk_patchlevel(): global _tk_patchlevel if _tk_patchlevel is None: tcl = Tcl() patchlevel = tcl.call('info', 'patchlevel') m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel) major, minor, releaselevel, serial = m.groups() major, minor, serial = int(major), int(minor), int(serial) releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel] if releaselevel == 'final': _tk_patchlevel = major, minor, serial, releaselevel, 0 else: _tk_patchlevel = major, minor, 0, releaselevel, serial return _tk_patchlevel class TkinterTest(unittest.TestCase): def testFlattenLen(self): # flatten(<object with no length>) self.assertRaises(TypeError, _tkinter._flatten, True) class TclTest(unittest.TestCase): def setUp(self): self.interp = Tcl() self.wantobjects = self.interp.tk.wantobjects() def testEval(self): tcl = self.interp tcl.eval('set a 1') self.assertEqual(tcl.eval('set a'),'1') def test_eval_null_in_result(self): tcl = self.interp self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b') def testEvalException(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'set a') def testEvalException2(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'this is wrong') def testCall(self): tcl = self.interp tcl.call('set','a','1') self.assertEqual(tcl.call('set','a'),'1') def testCallException(self): tcl = self.interp self.assertRaises(TclError,tcl.call,'set','a') def testCallException2(self): tcl = self.interp self.assertRaises(TclError,tcl.call,'this','is','wrong') def testSetVar(self): tcl = self.interp tcl.setvar('a','1') self.assertEqual(tcl.eval('set a'),'1') def testSetVarArray(self): tcl = self.interp tcl.setvar('a(1)','1') self.assertEqual(tcl.eval('set a(1)'),'1') def testGetVar(self): tcl = self.interp tcl.eval('set a 1') self.assertEqual(tcl.getvar('a'),'1') def testGetVarArray(self): tcl = self.interp tcl.eval('set a(1) 1') self.assertEqual(tcl.getvar('a(1)'),'1') def testGetVarException(self): tcl = self.interp self.assertRaises(TclError,tcl.getvar,'a') def testGetVarArrayException(self): tcl = self.interp self.assertRaises(TclError,tcl.getvar,'a(1)') def testUnsetVar(self): tcl = self.interp tcl.setvar('a',1) self.assertEqual(tcl.eval('info exists a'),'1') tcl.unsetvar('a') self.assertEqual(tcl.eval('info exists a'),'0') def testUnsetVarArray(self): tcl = self.interp tcl.setvar('a(1)',1) tcl.setvar('a(2)',2) self.assertEqual(tcl.eval('info exists a(1)'),'1') self.assertEqual(tcl.eval('info exists a(2)'),'1') tcl.unsetvar('a(1)') self.assertEqual(tcl.eval('info exists a(1)'),'0') self.assertEqual(tcl.eval('info exists a(2)'),'1') def testUnsetVarException(self): tcl = self.interp self.assertRaises(TclError,tcl.unsetvar,'a') def get_integers(self): integers = (0, 1, -1, 2**31-1, -2**31, 2**31, -2**31-1, 2**63-1, -2**63) # bignum was added in Tcl 8.5, but its support is able only since 8.5.8 if (get_tk_patchlevel() >= (8, 6, 0, 'final') or (8, 5, 8) <= get_tk_patchlevel() < (8, 6)): integers += (2**63, -2**63-1, 2**1000, -2**1000) return integers def test_getint(self): tcl = self.interp.tk for i in self.get_integers(): self.assertEqual(tcl.getint(' %d ' % i), i) if tcl_version >= (8, 5): self.assertEqual(tcl.getint(' %#o ' % i), i) self.assertEqual(tcl.getint((' %#o ' % i).replace('o', '')), i) self.assertEqual(tcl.getint(' %#x ' % i), i) if tcl_version < (8, 5): # bignum was added in Tcl 8.5 self.assertRaises(TclError, tcl.getint, str(2**1000)) self.assertEqual(tcl.getint(42), 42) self.assertRaises(TypeError, tcl.getint) self.assertRaises(TypeError, tcl.getint, '42', '10') self.assertRaises(TypeError, tcl.getint, b'42') self.assertRaises(TypeError, tcl.getint, 42.0) self.assertRaises(TclError, tcl.getint, 'a') self.assertRaises((TypeError, ValueError, TclError), tcl.getint, '42\0') self.assertRaises((UnicodeEncodeError, ValueError, TclError), tcl.getint, '42\ud800') def test_getdouble(self): tcl = self.interp.tk self.assertEqual(tcl.getdouble(' 42 '), 42.0) self.assertEqual(tcl.getdouble(' 42.5 '), 42.5) self.assertEqual(tcl.getdouble(42.5), 42.5) self.assertEqual(tcl.getdouble(42), 42.0) self.assertRaises(TypeError, tcl.getdouble) self.assertRaises(TypeError, tcl.getdouble, '42.5', '10') self.assertRaises(TypeError, tcl.getdouble, b'42.5') self.assertRaises(TclError, tcl.getdouble, 'a') self.assertRaises((TypeError, ValueError, TclError), tcl.getdouble, '42.5\0') self.assertRaises((UnicodeEncodeError, ValueError, TclError), tcl.getdouble, '42.5\ud800') def test_getboolean(self): tcl = self.interp.tk self.assertIs(tcl.getboolean('on'), True) self.assertIs(tcl.getboolean('1'), True) self.assertIs(tcl.getboolean(42), True) self.assertIs(tcl.getboolean(0), False) self.assertRaises(TypeError, tcl.getboolean) self.assertRaises(TypeError, tcl.getboolean, 'on', '1') self.assertRaises(TypeError, tcl.getboolean, b'on') self.assertRaises(TypeError, tcl.getboolean, 1.0) self.assertRaises(TclError, tcl.getboolean, 'a') self.assertRaises((TypeError, ValueError, TclError), tcl.getboolean, 'on\0') self.assertRaises((UnicodeEncodeError, ValueError, TclError), tcl.getboolean, 'on\ud800') def testEvalFile(self): tcl = self.interp with open(support.TESTFN, 'w') as f: self.addCleanup(support.unlink, support.TESTFN) f.write("""set a 1 set b 2 set c [ expr $a + $b ] """) tcl.evalfile(support.TESTFN) self.assertEqual(tcl.eval('set a'),'1') self.assertEqual(tcl.eval('set b'),'2') self.assertEqual(tcl.eval('set c'),'3') def test_evalfile_null_in_result(self): tcl = self.interp with open(support.TESTFN, 'w') as f: self.addCleanup(support.unlink, support.TESTFN) f.write(""" set a "a\0b" set b "a\\0b" """) tcl.evalfile(support.TESTFN) self.assertEqual(tcl.eval('set a'), 'a\x00b') self.assertEqual(tcl.eval('set b'), 'a\x00b') def testEvalFileException(self): tcl = self.interp filename = "doesnotexists" try: os.remove(filename) except Exception as e: pass self.assertRaises(TclError,tcl.evalfile,filename) def testPackageRequireException(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'package require DNE') @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows') def testLoadWithUNC(self): # Build a UNC path from the regular path. # Something like # \\%COMPUTERNAME%\c$\python27\python.exe fullname = os.path.abspath(sys.executable) if fullname[1] != ':': raise unittest.SkipTest('Absolute path should have drive part') unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], fullname[0], fullname[3:]) if not os.path.exists(unc_name): raise unittest.SkipTest('Cannot connect to UNC Path') with support.EnvironmentVarGuard() as env: env.unset("TCL_LIBRARY") stdout = subprocess.check_output( [unc_name, '-c', 'import tkinter; print(tkinter)']) self.assertIn(b'tkinter', stdout) def test_exprstring(self): tcl = self.interp tcl.call('set', 'a', 3) tcl.call('set', 'b', 6) def check(expr, expected): result = tcl.exprstring(expr) self.assertEqual(result, expected) self.assertIsInstance(result, str) self.assertRaises(TypeError, tcl.exprstring) self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6') self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6') self.assertRaises(TclError, tcl.exprstring, 'spam') check('', '0') check('8.2 + 6', '14.2') check('3.1 + $a', '6.1') check('2 + "$a.$b"', '5.6') check('4*[llength "6 2"]', '8') check('{word one} < "word $a"', '0') check('4*2 < 7', '0') check('hypot($a, 4)', '5.0') check('5 / 4', '1') check('5 / 4.0', '1.25') check('5 / ( [string length "abcd"] + 0.0 )', '1.25') check('20.0/5.0', '4.0') check('"0x03" > "2"', '1') check('[string length "a\xbd\u20ac"]', '3') check(r'[string length "a\xbd\u20ac"]', '3') check('"abc"', 'abc') check('"a\xbd\u20ac"', 'a\xbd\u20ac') check(r'"a\xbd\u20ac"', 'a\xbd\u20ac') check(r'"a\0b"', 'a\x00b') if tcl_version >= (8, 5): # bignum was added in Tcl 8.5 check('2**64', str(2**64)) def test_exprdouble(self): tcl = self.interp tcl.call('set', 'a', 3) tcl.call('set', 'b', 6) def check(expr, expected): result = tcl.exprdouble(expr) self.assertEqual(result, expected) self.assertIsInstance(result, float) self.assertRaises(TypeError, tcl.exprdouble) self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6') self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6') self.assertRaises(TclError, tcl.exprdouble, 'spam') check('', 0.0) check('8.2 + 6', 14.2) check('3.1 + $a', 6.1) check('2 + "$a.$b"', 5.6) check('4*[llength "6 2"]', 8.0) check('{word one} < "word $a"', 0.0) check('4*2 < 7', 0.0) check('hypot($a, 4)', 5.0) check('5 / 4', 1.0) check('5 / 4.0', 1.25) check('5 / ( [string length "abcd"] + 0.0 )', 1.25) check('20.0/5.0', 4.0) check('"0x03" > "2"', 1.0) check('[string length "a\xbd\u20ac"]', 3.0) check(r'[string length "a\xbd\u20ac"]', 3.0) self.assertRaises(TclError, tcl.exprdouble, '"abc"') if tcl_version >= (8, 5): # bignum was added in Tcl 8.5 check('2**64', float(2**64)) def test_exprlong(self): tcl = self.interp tcl.call('set', 'a', 3) tcl.call('set', 'b', 6) def check(expr, expected): result = tcl.exprlong(expr) self.assertEqual(result, expected) self.assertIsInstance(result, int) self.assertRaises(TypeError, tcl.exprlong) self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6') self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6') self.assertRaises(TclError, tcl.exprlong, 'spam') check('', 0) check('8.2 + 6', 14) check('3.1 + $a', 6) check('2 + "$a.$b"', 5) check('4*[llength "6 2"]', 8) check('{word one} < "word $a"', 0) check('4*2 < 7', 0) check('hypot($a, 4)', 5) check('5 / 4', 1) check('5 / 4.0', 1) check('5 / ( [string length "abcd"] + 0.0 )', 1) check('20.0/5.0', 4) check('"0x03" > "2"', 1) check('[string length "a\xbd\u20ac"]', 3) check(r'[string length "a\xbd\u20ac"]', 3) self.assertRaises(TclError, tcl.exprlong, '"abc"') if tcl_version >= (8, 5): # bignum was added in Tcl 8.5 self.assertRaises(TclError, tcl.exprlong, '2**64') def test_exprboolean(self): tcl = self.interp tcl.call('set', 'a', 3) tcl.call('set', 'b', 6) def check(expr, expected): result = tcl.exprboolean(expr) self.assertEqual(result, expected) self.assertIsInstance(result, int) self.assertNotIsInstance(result, bool) self.assertRaises(TypeError, tcl.exprboolean) self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6') self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6') self.assertRaises(TclError, tcl.exprboolean, 'spam') check('', False) for value in ('0', 'false', 'no', 'off'): check(value, False) check('"%s"' % value, False) check('{%s}' % value, False) for value in ('1', 'true', 'yes', 'on'): check(value, True) check('"%s"' % value, True) check('{%s}' % value, True) check('8.2 + 6', True) check('3.1 + $a', True) check('2 + "$a.$b"', True) check('4*[llength "6 2"]', True) check('{word one} < "word $a"', False) check('4*2 < 7', False) check('hypot($a, 4)', True) check('5 / 4', True) check('5 / 4.0', True) check('5 / ( [string length "abcd"] + 0.0 )', True) check('20.0/5.0', True) check('"0x03" > "2"', True) check('[string length "a\xbd\u20ac"]', True) check(r'[string length "a\xbd\u20ac"]', True) self.assertRaises(TclError, tcl.exprboolean, '"abc"') if tcl_version >= (8, 5): # bignum was added in Tcl 8.5 check('2**64', True) @unittest.skipUnless(tcl_version >= (8, 5), 'requires Tcl version >= 8.5') def test_booleans(self): tcl = self.interp def check(expr, expected): result = tcl.call('expr', expr) if tcl.wantobjects(): self.assertEqual(result, expected) self.assertIsInstance(result, int) else: self.assertIn(result, (expr, str(int(expected)))) self.assertIsInstance(result, str) check('true', True) check('yes', True) check('on', True) check('false', False) check('no', False) check('off', False) check('1 < 2', True) check('1 > 2', False) def test_expr_bignum(self): tcl = self.interp for i in self.get_integers(): result = tcl.call('expr', str(i)) if self.wantobjects: self.assertEqual(result, i) self.assertIsInstance(result, int) else: self.assertEqual(result, str(i)) self.assertIsInstance(result, str) if tcl_version < (8, 5): # bignum was added in Tcl 8.5 self.assertRaises(TclError, tcl.call, 'expr', str(2**1000)) def test_passing_values(self): def passValue(value): return self.interp.call('set', '_', value) self.assertEqual(passValue(True), True if self.wantobjects else '1') self.assertEqual(passValue(False), False if self.wantobjects else '0') self.assertEqual(passValue('string'), 'string') self.assertEqual(passValue('string\u20ac'), 'string\u20ac') self.assertEqual(passValue('string\U0001f4bb'), 'string\U0001f4bb') self.assertEqual(passValue('str\x00ing'), 'str\x00ing') self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd') self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac') self.assertEqual(passValue('str\x00ing\U0001f4bb'), 'str\x00ing\U0001f4bb') self.assertEqual(passValue(b'str\x00ing'), b'str\x00ing' if self.wantobjects else 'str\x00ing') self.assertEqual(passValue(b'str\xc0\x80ing'), b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing') self.assertEqual(passValue(b'str\xbding'), b'str\xbding' if self.wantobjects else 'str\xbding') for i in self.get_integers(): self.assertEqual(passValue(i), i if self.wantobjects else str(i)) if tcl_version < (8, 5): # bignum was added in Tcl 8.5 self.assertEqual(passValue(2**1000), str(2**1000)) for f in (0.0, 1.0, -1.0, 1/3, sys.float_info.min, sys.float_info.max, -sys.float_info.min, -sys.float_info.max): if self.wantobjects: self.assertEqual(passValue(f), f) else: self.assertEqual(float(passValue(f)), f) if self.wantobjects: f = passValue(float('nan')) self.assertNotEqual(f, f) self.assertEqual(passValue(float('inf')), float('inf')) self.assertEqual(passValue(-float('inf')), -float('inf')) else: self.assertEqual(float(passValue(float('inf'))), float('inf')) self.assertEqual(float(passValue(-float('inf'))), -float('inf')) # XXX NaN representation can be not parsable by float() self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4') self.assertEqual(passValue(['a', ['b', 'c']]), ('a', ('b', 'c')) if self.wantobjects else 'a {b c}') def test_user_command(self): result = None def testfunc(arg): nonlocal result result = arg return arg self.interp.createcommand('testfunc', testfunc) self.addCleanup(self.interp.tk.deletecommand, 'testfunc') def check(value, expected=None, *, eq=self.assertEqual): if expected is None: expected = value nonlocal result result = None r = self.interp.call('testfunc', value) self.assertIsInstance(result, str) eq(result, expected) self.assertIsInstance(r, str) eq(r, expected) def float_eq(actual, expected): self.assertAlmostEqual(float(actual), expected, delta=abs(expected) * 1e-10) check(True, '1') check(False, '0') check('string') check('string\xbd') check('string\u20ac') check('string\U0001f4bb') check('') check(b'string', 'string') check(b'string\xe2\x82\xac', 'string\xe2\x82\xac') check(b'string\xbd', 'string\xbd') check(b'', '') check('str\x00ing') check('str\x00ing\xbd') check('str\x00ing\u20ac') check(b'str\x00ing', 'str\x00ing') check(b'str\xc0\x80ing', 'str\xc0\x80ing') check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac') for i in self.get_integers(): check(i, str(i)) if tcl_version < (8, 5): # bignum was added in Tcl 8.5 check(2**1000, str(2**1000)) for f in (0.0, 1.0, -1.0): check(f, repr(f)) for f in (1/3.0, sys.float_info.min, sys.float_info.max, -sys.float_info.min, -sys.float_info.max): check(f, eq=float_eq) check(float('inf'), eq=float_eq) check(-float('inf'), eq=float_eq) # XXX NaN representation can be not parsable by float() check((), '') check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}') check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}') def test_splitlist(self): splitlist = self.interp.tk.splitlist call = self.interp.tk.call self.assertRaises(TypeError, splitlist) self.assertRaises(TypeError, splitlist, 'a', 'b') self.assertRaises(TypeError, splitlist, 2) testcases = [ ('2', ('2',)), ('', ()), ('{}', ('',)), ('""', ('',)), ('a\n b\t\r c\n ', ('a', 'b', 'c')), (b'a\n b\t\r c\n ', ('a', 'b', 'c')), ('a \u20ac', ('a', '\u20ac')), ('a \U0001f4bb', ('a', '\U0001f4bb')), (b'a \xe2\x82\xac', ('a', '\u20ac')), (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')), ('a {b c}', ('a', 'b c')), (r'a b\ c', ('a', 'b c')), (('a', 'b c'), ('a', 'b c')), ('a 2', ('a', '2')), (('a', 2), ('a', 2)), ('a 3.4', ('a', '3.4')), (('a', 3.4), ('a', 3.4)), ((), ()), ([], ()), (['a', ['b', 'c']], ('a', ['b', 'c'])), (call('list', 1, '2', (3.4,)), (1, '2', (3.4,)) if self.wantobjects else ('1', '2', '3.4')), ] tk_patchlevel = get_tk_patchlevel() if tcl_version >= (8, 5): if not self.wantobjects or tk_patchlevel < (8, 5, 5): # Before 8.5.5 dicts were converted to lists through string expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4') else: expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,)) testcases += [ (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)), expected), ] dbg_info = ('want objects? %s, Tcl version: %s, Tk patchlevel: %s' % (self.wantobjects, tcl_version, tk_patchlevel)) for arg, res in testcases: self.assertEqual(splitlist(arg), res, 'arg=%a, %s' % (arg, dbg_info)) self.assertRaises(TclError, splitlist, '{') def test_split(self): split = self.interp.tk.split call = self.interp.tk.call self.assertRaises(TypeError, split) self.assertRaises(TypeError, split, 'a', 'b') self.assertRaises(TypeError, split, 2) testcases = [ ('2', '2'), ('', ''), ('{}', ''), ('""', ''), ('{', '{'), ('a\n b\t\r c\n ', ('a', 'b', 'c')), (b'a\n b\t\r c\n ', ('a', 'b', 'c')), ('a \u20ac', ('a', '\u20ac')), (b'a \xe2\x82\xac', ('a', '\u20ac')), (b'a\xc0\x80b', 'a\x00b'), (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')), (b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'), ('a {b c}', ('a', ('b', 'c'))), (r'a b\ c', ('a', ('b', 'c'))), (('a', b'b c'), ('a', ('b', 'c'))), (('a', 'b c'), ('a', ('b', 'c'))), ('a 2', ('a', '2')), (('a', 2), ('a', 2)), ('a 3.4', ('a', '3.4')), (('a', 3.4), ('a', 3.4)), (('a', (2, 3.4)), ('a', (2, 3.4))), ((), ()), ([], ()), (['a', 'b c'], ('a', ('b', 'c'))), (['a', ['b', 'c']], ('a', ('b', 'c'))), (call('list', 1, '2', (3.4,)), (1, '2', (3.4,)) if self.wantobjects else ('1', '2', '3.4')), ] if tcl_version >= (8, 5): if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5): # Before 8.5.5 dicts were converted to lists through string expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4') else: expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,)) testcases += [ (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)), expected), ] for arg, res in testcases: self.assertEqual(split(arg), res, msg=arg) def test_splitdict(self): splitdict = tkinter._splitdict tcl = self.interp.tk arg = '-a {1 2 3} -something foo status {}' self.assertEqual(splitdict(tcl, arg, False), {'-a': '1 2 3', '-something': 'foo', 'status': ''}) self.assertEqual(splitdict(tcl, arg), {'a': '1 2 3', 'something': 'foo', 'status': ''}) arg = ('-a', (1, 2, 3), '-something', 'foo', 'status', '{}') self.assertEqual(splitdict(tcl, arg, False), {'-a': (1, 2, 3), '-something': 'foo', 'status': '{}'}) self.assertEqual(splitdict(tcl, arg), {'a': (1, 2, 3), 'something': 'foo', 'status': '{}'}) self.assertRaises(RuntimeError, splitdict, tcl, '-a b -c ') self.assertRaises(RuntimeError, splitdict, tcl, ('-a', 'b', '-c')) arg = tcl.call('list', '-a', (1, 2, 3), '-something', 'foo', 'status', ()) self.assertEqual(splitdict(tcl, arg), {'a': (1, 2, 3) if self.wantobjects else '1 2 3', 'something': 'foo', 'status': ''}) if tcl_version >= (8, 5): arg = tcl.call('dict', 'create', '-a', (1, 2, 3), '-something', 'foo', 'status', ()) if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5): # Before 8.5.5 dicts were converted to lists through string expected = {'a': '1 2 3', 'something': 'foo', 'status': ''} else: expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''} self.assertEqual(splitdict(tcl, arg), expected) def test_join(self): join = tkinter._join tcl = self.interp.tk def unpack(s): return tcl.call('lindex', s, 0) def check(value): self.assertEqual(unpack(join([value])), value) self.assertEqual(unpack(join([value, 0])), value) self.assertEqual(unpack(unpack(join([[value]]))), value) self.assertEqual(unpack(unpack(join([[value, 0]]))), value) self.assertEqual(unpack(unpack(join([[value], 0]))), value) self.assertEqual(unpack(unpack(join([[value, 0], 0]))), value) check('') check('spam') check('sp am') check('sp\tam') check('sp\nam') check(' \t\n') check('{spam}') check('{sp am}') check('"spam"') check('"sp am"') check('{"spam"}') check('"{spam}"') check('sp\\am') check('"sp\\am"') check('"{}" "{}"') check('"\\') check('"{') check('"}') check('\n\\') check('\n{') check('\n}') check('\\\n') check('{\n') check('}\n') def test_new_tcl_obj(self): self.assertRaises(TypeError, _tkinter.Tcl_Obj) class BigmemTclTest(unittest.TestCase): def setUp(self): self.interp = Tcl() @support.cpython_only @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") @support.bigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False) def test_huge_string_call(self, size): value = ' ' * size self.assertRaises(OverflowError, self.interp.call, 'string', 'index', value, 0) @support.cpython_only @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") @support.bigmemtest(size=INT_MAX + 1, memuse=2, dry_run=False) def test_huge_string_builtins(self, size): tk = self.interp.tk value = '1' + ' ' * size self.assertRaises(OverflowError, tk.getint, value) self.assertRaises(OverflowError, tk.getdouble, value) self.assertRaises(OverflowError, tk.getboolean, value) self.assertRaises(OverflowError, tk.eval, value) self.assertRaises(OverflowError, tk.evalfile, value) self.assertRaises(OverflowError, tk.record, value) self.assertRaises(OverflowError, tk.adderrorinfo, value) self.assertRaises(OverflowError, tk.setvar, value, 'x', 'a') self.assertRaises(OverflowError, tk.setvar, 'x', value, 'a') self.assertRaises(OverflowError, tk.unsetvar, value) self.assertRaises(OverflowError, tk.unsetvar, 'x', value) self.assertRaises(OverflowError, tk.adderrorinfo, value) self.assertRaises(OverflowError, tk.exprstring, value) self.assertRaises(OverflowError, tk.exprlong, value) self.assertRaises(OverflowError, tk.exprboolean, value) self.assertRaises(OverflowError, tk.splitlist, value) self.assertRaises(OverflowError, tk.split, value) self.assertRaises(OverflowError, tk.createcommand, value, max) self.assertRaises(OverflowError, tk.deletecommand, value) @support.cpython_only @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") @support.bigmemtest(size=INT_MAX + 1, memuse=6, dry_run=False) def test_huge_string_builtins2(self, size): # These commands require larger memory for possible error messages tk = self.interp.tk value = '1' + ' ' * size self.assertRaises(OverflowError, tk.evalfile, value) self.assertRaises(OverflowError, tk.unsetvar, value) self.assertRaises(OverflowError, tk.unsetvar, 'x', value) def setUpModule(): if support.verbose: tcl = Tcl() print('patchlevel =', tcl.call('info', 'patchlevel')) def test_main(): support.run_unittest(TclTest, TkinterTest, BigmemTclTest) 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/string_tests.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/string_tests.py
""" Common tests shared by test_unicode, test_userstring and test_bytes. """ import unittest, string, sys, struct from test import support from collections import UserList class Sequence: def __init__(self, seq='wxyz'): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] class BadSeq1(Sequence): def __init__(self): self.seq = [7, 'hello', 123] def __str__(self): return '{0} {1} {2}'.format(*self.seq) class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] def __len__(self): return 8 class BaseTest: # These tests are for buffers of values (bytes) and not # specific to character interpretation, used for bytes objects # and various string implementations # The type to be tested # Change in subclasses to change the behaviour of fixtesttype() type2test = None # Whether the "contained items" of the container are integers in # range(0, 256) (i.e. bytes, bytearray) or strings of length 1 # (str) contains_bytes = False # All tests pass their arguments to the testing methods # as str objects. fixtesttype() can be used to propagate # these arguments to the appropriate type def fixtype(self, obj): if isinstance(obj, str): return self.__class__.type2test(obj) elif isinstance(obj, list): return [self.fixtype(x) for x in obj] elif isinstance(obj, tuple): return tuple([self.fixtype(x) for x in obj]) elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) for (key, value) in obj.items() ]) else: return obj def test_fixtype(self): self.assertIs(type(self.fixtype("123")), self.type2test) # check that obj.method(*args) returns result def checkequal(self, result, obj, methodname, *args, **kwargs): result = self.fixtype(result) obj = self.fixtype(obj) args = self.fixtype(args) kwargs = {k: self.fixtype(v) for k,v in kwargs.items()} realresult = getattr(obj, methodname)(*args, **kwargs) self.assertEqual( result, realresult ) # if the original is returned make sure that # this doesn't happen with subclasses if obj is realresult: try: class subtype(self.__class__.type2test): pass except TypeError: pass # Skip this if we can't subclass else: obj = subtype(obj) realresult = getattr(obj, methodname)(*args) self.assertIsNot(obj, realresult) # check that obj.method(*args) raises exc def checkraises(self, exc, obj, methodname, *args): obj = self.fixtype(obj) args = self.fixtype(args) with self.assertRaises(exc) as cm: getattr(obj, methodname)(*args) self.assertNotEqual(str(cm.exception), '') # call obj.method(*args) without any checks def checkcall(self, obj, methodname, *args): obj = self.fixtype(obj) args = self.fixtype(args) getattr(obj, methodname)(*args) def test_count(self): self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(3, 'aaa', 'count', 'a') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(0, 'aaa', 'count', 'b') self.checkequal(2, 'aaa', 'count', 'a', 1) self.checkequal(0, 'aaa', 'count', 'a', 10) self.checkequal(1, 'aaa', 'count', 'a', -1) self.checkequal(3, 'aaa', 'count', 'a', -10) self.checkequal(1, 'aaa', 'count', 'a', 0, 1) self.checkequal(3, 'aaa', 'count', 'a', 0, 10) self.checkequal(2, 'aaa', 'count', 'a', 0, -1) self.checkequal(0, 'aaa', 'count', 'a', 0, -10) self.checkequal(3, 'aaa', 'count', '', 1) self.checkequal(1, 'aaa', 'count', '', 3) self.checkequal(0, 'aaa', 'count', '', 10) self.checkequal(2, 'aaa', 'count', '', -1) self.checkequal(4, 'aaa', 'count', '', -10) self.checkequal(1, '', 'count', '') self.checkequal(0, '', 'count', '', 1, 1) self.checkequal(0, '', 'count', '', sys.maxsize, 0) self.checkequal(0, '', 'count', 'xx') self.checkequal(0, '', 'count', 'xx', 1, 1) self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0) self.checkraises(TypeError, 'hello', 'count') if self.contains_bytes: self.checkequal(0, 'hello', 'count', 42) else: self.checkraises(TypeError, 'hello', 'count', 42) # For a variety of combinations, # verify that str.count() matches an equivalent function # replacing all occurrences and then differencing the string lengths charset = ['', 'a', 'b'] digits = 7 base = len(charset) teststrings = set() for i in range(base ** digits): entry = [] for j in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) teststrings = [self.fixtype(ts) for ts in teststrings] for i in teststrings: n = len(i) for j in teststrings: r1 = i.count(j) if j: r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))), len(j)) else: r2, rem = len(i)+1, 0 if rem or r1 != r2: self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i)) self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i)) def test_find(self): self.checkequal(0, 'abcdefghiabc', 'find', 'abc') self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1) self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4) self.checkequal(0, 'abc', 'find', '', 0) self.checkequal(3, 'abc', 'find', '', 3) self.checkequal(-1, 'abc', 'find', '', 4) # to check the ability to pass None as defaults self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a') self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4) self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6) self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None) self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6) self.checkraises(TypeError, 'hello', 'find') if self.contains_bytes: self.checkequal(-1, 'hello', 'find', 42) else: self.checkraises(TypeError, 'hello', 'find', 42) self.checkequal(0, '', 'find', '') self.checkequal(-1, '', 'find', '', 1, 1) self.checkequal(-1, '', 'find', '', sys.maxsize, 0) self.checkequal(-1, '', 'find', 'xx') self.checkequal(-1, '', 'find', 'xx', 1, 1) self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0) # issue 7458 self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0) # For a variety of combinations, # verify that str.find() matches __contains__ # and that the found substring is really at that location charset = ['', 'a', 'b', 'c'] digits = 5 base = len(charset) teststrings = set() for i in range(base ** digits): entry = [] for j in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) teststrings = [self.fixtype(ts) for ts in teststrings] for i in teststrings: for j in teststrings: loc = i.find(j) r1 = (loc != -1) r2 = j in i self.assertEqual(r1, r2) if loc != -1: self.assertEqual(i[loc:loc+len(j)], j) def test_rfind(self): self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc') self.checkequal(12, 'abcdefghiabc', 'rfind', '') self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd') self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz') self.checkequal(3, 'abc', 'rfind', '', 0) self.checkequal(3, 'abc', 'rfind', '', 3) self.checkequal(-1, 'abc', 'rfind', '', 4) # to check the ability to pass None as defaults self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a') self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4) self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6) self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None) self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6) self.checkraises(TypeError, 'hello', 'rfind') if self.contains_bytes: self.checkequal(-1, 'hello', 'rfind', 42) else: self.checkraises(TypeError, 'hello', 'rfind', 42) # For a variety of combinations, # verify that str.rfind() matches __contains__ # and that the found substring is really at that location charset = ['', 'a', 'b', 'c'] digits = 5 base = len(charset) teststrings = set() for i in range(base ** digits): entry = [] for j in range(digits): i, m = divmod(i, base) entry.append(charset[m]) teststrings.add(''.join(entry)) teststrings = [self.fixtype(ts) for ts in teststrings] for i in teststrings: for j in teststrings: loc = i.rfind(j) r1 = (loc != -1) r2 = j in i self.assertEqual(r1, r2) if loc != -1: self.assertEqual(i[loc:loc+len(j)], j) # issue 7458 self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0) # issue #15534 self.checkequal(0, '<......\u043c...', "rfind", "<") def test_index(self): self.checkequal(0, 'abcdefghiabc', 'index', '') self.checkequal(3, 'abcdefghiabc', 'index', 'def') self.checkequal(0, 'abcdefghiabc', 'index', 'abc') self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1) self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib') self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1) self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8) self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1) # to check the ability to pass None as defaults self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a') self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4) self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6) self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None) self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6) self.checkraises(TypeError, 'hello', 'index') if self.contains_bytes: self.checkraises(ValueError, 'hello', 'index', 42) else: self.checkraises(TypeError, 'hello', 'index', 42) def test_rindex(self): self.checkequal(12, 'abcdefghiabc', 'rindex', '') self.checkequal(3, 'abcdefghiabc', 'rindex', 'def') self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc') self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1) self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib') self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1) self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1) self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8) self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1) # to check the ability to pass None as defaults self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a') self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4) self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6) self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None) self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6) self.checkraises(TypeError, 'hello', 'rindex') if self.contains_bytes: self.checkraises(ValueError, 'hello', 'rindex', 42) else: self.checkraises(TypeError, 'hello', 'rindex', 42) def test_lower(self): self.checkequal('hello', 'HeLLo', 'lower') self.checkequal('hello', 'hello', 'lower') self.checkraises(TypeError, 'hello', 'lower', 42) def test_upper(self): self.checkequal('HELLO', 'HeLLo', 'upper') self.checkequal('HELLO', 'HELLO', 'upper') self.checkraises(TypeError, 'hello', 'upper', 42) def test_expandtabs(self): self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4) self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs') self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 8) self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4) self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4) # check keyword args self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', tabsize=8) self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', tabsize=4) self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1) self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42) # This test is only valid when sizeof(int) == sizeof(void*) == 4. if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4: self.checkraises(OverflowError, '\ta\n\tb', 'expandtabs', sys.maxsize) def test_split(self): # by a char self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|') self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0) self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1) self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', sys.maxsize-2) self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0) self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2) self.checkequal(['abcd'], 'abcd', 'split', '|') self.checkequal([''], '', 'split', '|') self.checkequal(['endcase ', ''], 'endcase |', 'split', '|') self.checkequal(['', ' startcase'], '| startcase', 'split', '|') self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|') self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2) self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|') self.checkequal(['a']*15 +['a|a|a|a|a'], ('a|'*20)[:-1], 'split', '|', 15) # by string self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//') self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1) self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', sys.maxsize-10) self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0) self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2) self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test') self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test') self.checkequal(['', ' bothcase ', ''], 'test bothcase test', 'split', 'test') self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb') self.checkequal(['', ''], 'aaa', 'split', 'aaa') self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0) self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba') self.checkequal(['aaaa'], 'aaaa', 'split', 'aab') self.checkequal([''], '', 'split', 'aaa') self.checkequal(['aa'], 'aa', 'split', 'aaa') self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb') self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb') self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH') self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19) self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4], 'split', 'BLAH', 18) # with keyword args self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', sep='|') self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', maxsplit=1) self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', sep='|', maxsplit=1) self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', maxsplit=1, sep='|') self.checkequal(['a', 'b c d'], 'a b c d', 'split', maxsplit=1) # argument type self.checkraises(TypeError, 'hello', 'split', 42, 42, 42) # null case self.checkraises(ValueError, 'hello', 'split', '') self.checkraises(ValueError, 'hello', 'split', '', 0) def test_rsplit(self): # by a char self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|') self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1) self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4) self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', sys.maxsize-100) self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0) self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2) self.checkequal(['abcd'], 'abcd', 'rsplit', '|') self.checkequal([''], '', 'rsplit', '|') self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|') self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|') self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|') self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2) self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|') self.checkequal(['a|a|a|a|a']+['a']*15, ('a|'*20)[:-1], 'rsplit', '|', 15) # by string self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//') self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1) self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4) self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', sys.maxsize-5) self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0) self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2) self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test') self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test') self.checkequal(['', ' bothcase ', ''], 'test bothcase test', 'rsplit', 'test') self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb') self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa') self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0) self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba') self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab') self.checkequal([''], '', 'rsplit', 'aaa') self.checkequal(['aa'], 'aa', 'rsplit', 'aaa') self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb') self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb') self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH') self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19) self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 18) # with keyword args self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', sep='|') self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', maxsplit=1) self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', sep='|', maxsplit=1) self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', maxsplit=1, sep='|') self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', maxsplit=1) # argument type self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42) # null case self.checkraises(ValueError, 'hello', 'rsplit', '') self.checkraises(ValueError, 'hello', 'rsplit', '', 0) def test_replace(self): EQ = self.checkequal # Operations on the empty string EQ("", "", "replace", "", "") EQ("A", "", "replace", "", "A") EQ("", "", "replace", "A", "") EQ("", "", "replace", "A", "A") EQ("", "", "replace", "", "", 100) EQ("", "", "replace", "", "", sys.maxsize) # interleave (from=="", 'to' gets inserted everywhere) EQ("A", "A", "replace", "", "") EQ("*A*", "A", "replace", "", "*") EQ("*1A*1", "A", "replace", "", "*1") EQ("*-#A*-#", "A", "replace", "", "*-#") EQ("*-A*-A*-", "AA", "replace", "", "*-") EQ("*-A*-A*-", "AA", "replace", "", "*-", -1) EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize) EQ("*-A*-A*-", "AA", "replace", "", "*-", 4) EQ("*-A*-A*-", "AA", "replace", "", "*-", 3) EQ("*-A*-A", "AA", "replace", "", "*-", 2) EQ("*-AA", "AA", "replace", "", "*-", 1) EQ("AA", "AA", "replace", "", "*-", 0) # single character deletion (from=="A", to=="") EQ("", "A", "replace", "A", "") EQ("", "AAA", "replace", "A", "") EQ("", "AAA", "replace", "A", "", -1) EQ("", "AAA", "replace", "A", "", sys.maxsize) EQ("", "AAA", "replace", "A", "", 4) EQ("", "AAA", "replace", "A", "", 3) EQ("A", "AAA", "replace", "A", "", 2) EQ("AA", "AAA", "replace", "A", "", 1) EQ("AAA", "AAA", "replace", "A", "", 0) EQ("", "AAAAAAAAAA", "replace", "A", "") EQ("BCD", "ABACADA", "replace", "A", "") EQ("BCD", "ABACADA", "replace", "A", "", -1) EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize) EQ("BCD", "ABACADA", "replace", "A", "", 5) EQ("BCD", "ABACADA", "replace", "A", "", 4) EQ("BCDA", "ABACADA", "replace", "A", "", 3) EQ("BCADA", "ABACADA", "replace", "A", "", 2) EQ("BACADA", "ABACADA", "replace", "A", "", 1) EQ("ABACADA", "ABACADA", "replace", "A", "", 0) EQ("BCD", "ABCAD", "replace", "A", "") EQ("BCD", "ABCADAA", "replace", "A", "") EQ("BCD", "BCD", "replace", "A", "") EQ("*************", "*************", "replace", "A", "") EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999) # substring deletion (from=="the", to=="") EQ("", "the", "replace", "the", "") EQ("ater", "theater", "replace", "the", "") EQ("", "thethe", "replace", "the", "") EQ("", "thethethethe", "replace", "the", "") EQ("aaaa", "theatheatheathea", "replace", "the", "") EQ("that", "that", "replace", "the", "") EQ("thaet", "thaet", "replace", "the", "") EQ("here and re", "here and there", "replace", "the", "") EQ("here and re and re", "here and there and there", "replace", "the", "", sys.maxsize) EQ("here and re and re", "here and there and there", "replace", "the", "", -1) EQ("here and re and re", "here and there and there", "replace", "the", "", 3) EQ("here and re and re", "here and there and there", "replace", "the", "", 2) EQ("here and re and there", "here and there and there", "replace", "the", "", 1) EQ("here and there and there", "here and there and there", "replace", "the", "", 0) EQ("here and re and re", "here and there and there", "replace", "the", "") EQ("abc", "abc", "replace", "the", "") EQ("abcdefg", "abcdefg", "replace", "the", "") # substring deletion (from=="bob", to=="") EQ("bob", "bbobob", "replace", "bob", "") EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "") EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "") EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "") # single character replace in place (len(from)==len(to)==1) EQ("Who goes there?", "Who goes there?", "replace", "o", "o") EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O") EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize) EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1) EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3) EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2) EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1) EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0) EQ("Who goes there?", "Who goes there?", "replace", "a", "q") EQ("who goes there?", "Who goes there?", "replace", "W", "w") EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w") EQ("Who goes there!", "Who goes there?", "replace", "?", "!") EQ("Who goes there!!", "Who goes there??", "replace", "?", "!") EQ("Who goes there?", "Who goes there?", "replace", ".", "!") # substring replace in place (len(from)==len(to) > 1) EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**") EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize) EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1) EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4) EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3) EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2) EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1) EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0) EQ("cobob", "bobob", "replace", "bob", "cob") EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob") EQ("bobob", "bobob", "replace", "bot", "bot") # replace single character (len(from)==1, len(to)>1) EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK") EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1) EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize) EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2) EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1) EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0) EQ("A----B----C----", "A.B.C.", "replace", ".", "----") # issue #15534 EQ('...\u043c......&lt;', '...\u043c......<', "replace", "<", "&lt;") EQ("Reykjavik", "Reykjavik", "replace", "q", "KK") # replace substring (len(from)>1, len(to)!=len(from)) EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam", "replace", "spam", "ham") EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam", "replace", "spam", "ham", sys.maxsize) EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam", "replace", "spam", "ham", -1) EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam", "replace", "spam", "ham", 4) EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam", "replace", "spam", "ham", 3) EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam", "replace", "spam", "ham", 2) EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam", "replace", "spam", "ham", 1) EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam", "replace", "spam", "ham", 0) EQ("bobob", "bobobob", "replace", "bobob", "bob") EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob") EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby") self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1) self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '') self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4) self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0) self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@') self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@') self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2) self.checkequal('-a-b-c-', 'abc', 'replace', '', '-') self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3) self.checkequal('abc', 'abc', 'replace', '', '-', 0) self.checkequal('', '', 'replace', '', '') self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0) self.checkequal('abc', 'abc', 'replace', 'xy', '--') # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with # MemoryError due to empty result (platform malloc issue when requesting # 0 bytes). self.checkequal('', '123', 'replace', '123', '') self.checkequal('', '123123', 'replace', '123', '') self.checkequal('x', '123x123', 'replace', '123', '') self.checkraises(TypeError, 'hello', 'replace') self.checkraises(TypeError, 'hello', 'replace', 42) self.checkraises(TypeError, 'hello', 'replace', 42, 'h') self.checkraises(TypeError, 'hello', 'replace', 'h', 42) @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4, 'only applies to 32-bit platforms') def test_replace_overflow(self): # Check for overflow checking on 32 bit machines A2_16 = "A" * (2**16) self.checkraises(OverflowError, A2_16, "replace", "", A2_16) self.checkraises(OverflowError, A2_16, "replace", "A", A2_16) self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16) def test_capitalize(self): self.checkequal(' hello ', ' hello ', 'capitalize') self.checkequal('Hello ', 'Hello ','capitalize') self.checkequal('Hello ', 'hello ','capitalize') self.checkequal('Aaaa', 'aaaa', 'capitalize') self.checkequal('Aaaa', 'AaAa', 'capitalize') self.checkraises(TypeError, 'hello', 'capitalize', 42) def test_additional_split(self): self.checkequal(['this', 'is', 'the', 'split', 'function'], 'this is the split function', 'split') # by whitespace self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split') self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1) self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3) self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
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_doctest2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py
"""A module to test whether doctest recognizes some 2.2 features, like static and class methods. >>> print('yup') # 1 yup We include some (random) encoded (utf-8) text in the text surrounding the example. It should be ignored: ЉЊЈЁЂ """ import sys import unittest from test import support if sys.flags.optimize >= 2: raise unittest.SkipTest("Cannot test docstrings with -O2") class C(object): """Class C. >>> print(C()) # 2 42 We include some (random) encoded (utf-8) text in the text surrounding the example. It should be ignored: ЉЊЈЁЂ """ def __init__(self): """C.__init__. >>> print(C()) # 3 42 """ def __str__(self): """ >>> print(C()) # 4 42 """ return "42" class D(object): """A nested D class. >>> print("In D!") # 5 In D! """ def nested(self): """ >>> print(3) # 6 3 """ def getx(self): """ >>> c = C() # 7 >>> c.x = 12 # 8 >>> print(c.x) # 9 -12 """ return -self._x def setx(self, value): """ >>> c = C() # 10 >>> c.x = 12 # 11 >>> print(c.x) # 12 -12 """ self._x = value x = property(getx, setx, doc="""\ >>> c = C() # 13 >>> c.x = 12 # 14 >>> print(c.x) # 15 -12 """) @staticmethod def statm(): """ A static method. >>> print(C.statm()) # 16 666 >>> print(C().statm()) # 17 666 """ return 666 @classmethod def clsm(cls, val): """ A class method. >>> print(C.clsm(22)) # 18 22 >>> print(C().clsm(23)) # 19 23 """ return val def test_main(): from test import test_doctest2 EXPECTED = 19 f, t = support.run_doctest(test_doctest2) if t != EXPECTED: raise support.TestFailed("expected %d tests to run, not %d" % (EXPECTED, t)) # Pollute the namespace with a bunch of imported functions and classes, # to make sure they don't get tested. from doctest import * 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_platform.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_platform.py
from unittest import mock import os import platform import subprocess import sys import sysconfig import tempfile import unittest import warnings from test import support class PlatformTest(unittest.TestCase): def test_architecture(self): res = platform.architecture() @support.skip_unless_symlink def test_architecture_via_symlink(self): # issue3762 if sys.platform == "win32" and not os.path.exists(sys.executable): # App symlink appears to not exist, but we want the # real executable here anyway import _winapi real = _winapi.GetModuleFileName(0) else: real = os.path.realpath(sys.executable) link = os.path.abspath(support.TESTFN) os.symlink(real, link) # On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at # so we add the directory to the path, PYTHONHOME and PYTHONPATH. env = None if sys.platform == "win32": env = {k.upper(): os.environ[k] for k in os.environ} env["PATH"] = "{};{}".format( os.path.dirname(real), env.get("PATH", "")) env["PYTHONHOME"] = os.path.dirname(real) if sysconfig.is_python_build(True): env["PYTHONPATH"] = os.path.dirname(os.__file__) def get(python, env=None): cmd = [python, '-c', 'import platform; print(platform.architecture())'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) r = p.communicate() if p.returncode: print(repr(r[0])) print(repr(r[1]), file=sys.stderr) self.fail('unexpected return code: {0} (0x{0:08X})' .format(p.returncode)) return r try: self.assertEqual(get(sys.executable), get(link, env=env)) finally: os.remove(link) def test_platform(self): for aliased in (False, True): for terse in (False, True): res = platform.platform(aliased, terse) def test_system(self): res = platform.system() def test_node(self): res = platform.node() def test_release(self): res = platform.release() def test_version(self): res = platform.version() def test_machine(self): res = platform.machine() def test_processor(self): res = platform.processor() def setUp(self): self.save_version = sys.version self.save_git = sys._git self.save_platform = sys.platform def tearDown(self): sys.version = self.save_version sys._git = self.save_git sys.platform = self.save_platform def test_sys_version(self): # Old test. for input, output in ( ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]', ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')), ('IronPython 1.0.60816 on .NET 2.0.50727.42', ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')), ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42', ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')), ('2.4.3 (truncation, date, t) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')), ('2.4.3 (truncation, date, ) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')), ('2.4.3 (truncation, date,) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')), ('2.4.3 (truncation, date) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')), ('2.4.3 (truncation, d) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')), ('2.4.3 (truncation, ) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')), ('2.4.3 (truncation,) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')), ('2.4.3 (truncation) \n[GCC]', ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')), ): # branch and revision are not "parsed", but fetched # from sys._git. Ignore them (name, version, branch, revision, buildno, builddate, compiler) \ = platform._sys_version(input) self.assertEqual( (name, version, '', '', buildno, builddate, compiler), output) # Tests for python_implementation(), python_version(), python_branch(), # python_revision(), python_build(), and python_compiler(). sys_versions = { ("2.6.1 (r261:67515, Dec 6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]", ('CPython', 'tags/r261', '67515'), self.save_platform) : ("CPython", "2.6.1", "tags/r261", "67515", ('r261:67515', 'Dec 6 2008 15:26:00'), 'GCC 4.0.1 (Apple Computer, Inc. build 5370)'), ("IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053", None, "cli") : ("IronPython", "2.0.0", "", "", ("", ""), ".NET 2.0.50727.3053"), ("2.6.1 (IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.1433)", None, "cli") : ("IronPython", "2.6.1", "", "", ("", ""), ".NET 2.0.50727.1433"), ("2.7.4 (IronPython 2.7.4 (2.7.0.40) on Mono 4.0.30319.1 (32-bit))", None, "cli") : ("IronPython", "2.7.4", "", "", ("", ""), "Mono 4.0.30319.1 (32-bit)"), ("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]", ('Jython', 'trunk', '6107'), "java1.5.0_16") : ("Jython", "2.5.0", "trunk", "6107", ('trunk:6107', 'Mar 26 2009'), "java1.5.0_16"), ("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]", ('PyPy', 'trunk', '63378'), self.save_platform) : ("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'), "") } for (version_tag, scm, sys_platform), info in \ sys_versions.items(): sys.version = version_tag if scm is None: if hasattr(sys, "_git"): del sys._git else: sys._git = scm if sys_platform is not None: sys.platform = sys_platform self.assertEqual(platform.python_implementation(), info[0]) self.assertEqual(platform.python_version(), info[1]) self.assertEqual(platform.python_branch(), info[2]) self.assertEqual(platform.python_revision(), info[3]) self.assertEqual(platform.python_build(), info[4]) self.assertEqual(platform.python_compiler(), info[5]) def test_system_alias(self): res = platform.system_alias( platform.system(), platform.release(), platform.version(), ) def test_uname(self): res = platform.uname() self.assertTrue(any(res)) self.assertEqual(res[0], res.system) self.assertEqual(res[1], res.node) self.assertEqual(res[2], res.release) self.assertEqual(res[3], res.version) self.assertEqual(res[4], res.machine) self.assertEqual(res[5], res.processor) @unittest.skipUnless(sys.platform.startswith('win'), "windows only test") def test_uname_win32_ARCHITEW6432(self): # Issue 7860: make sure we get architecture from the correct variable # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be # using it, per # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx try: with support.EnvironmentVarGuard() as environ: if 'PROCESSOR_ARCHITEW6432' in environ: del environ['PROCESSOR_ARCHITEW6432'] environ['PROCESSOR_ARCHITECTURE'] = 'foo' platform._uname_cache = None system, node, release, version, machine, processor = platform.uname() self.assertEqual(machine, 'foo') environ['PROCESSOR_ARCHITEW6432'] = 'bar' platform._uname_cache = None system, node, release, version, machine, processor = platform.uname() self.assertEqual(machine, 'bar') finally: platform._uname_cache = None def test_java_ver(self): res = platform.java_ver() if sys.platform == 'java': self.assertTrue(all(res)) def test_win32_ver(self): res = platform.win32_ver() def test_mac_ver(self): res = platform.mac_ver() if platform.uname().system == 'Darwin': # We're on a MacOSX system, check that # the right version information is returned fd = os.popen('sw_vers', 'r') real_ver = None for ln in fd: if ln.startswith('ProductVersion:'): real_ver = ln.strip().split()[-1] break fd.close() self.assertFalse(real_ver is None) result_list = res[0].split('.') expect_list = real_ver.split('.') len_diff = len(result_list) - len(expect_list) # On Snow Leopard, sw_vers reports 10.6.0 as 10.6 if len_diff > 0: expect_list.extend(['0'] * len_diff) self.assertEqual(result_list, expect_list) # res[1] claims to contain # (version, dev_stage, non_release_version) # That information is no longer available self.assertEqual(res[1], ('', '', '')) if sys.byteorder == 'little': self.assertIn(res[2], ('i386', 'x86_64')) else: self.assertEqual(res[2], 'PowerPC') @unittest.skipUnless(sys.platform == 'darwin', "OSX only test") def test_mac_ver_with_fork(self): # Issue7895: platform.mac_ver() crashes when using fork without exec # # This test checks that the fix for that issue works. # pid = os.fork() if pid == 0: # child info = platform.mac_ver() os._exit(0) else: # parent cpid, sts = os.waitpid(pid, 0) self.assertEqual(cpid, pid) self.assertEqual(sts, 0) def test_dist(self): with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', r'dist\(\) and linux_distribution\(\) ' 'functions are deprecated .*', DeprecationWarning, ) res = platform.dist() def test_libc_ver(self): if os.path.isdir(sys.executable) and \ os.path.exists(sys.executable+'.exe'): # Cygwin horror executable = sys.executable + '.exe' elif sys.platform == "win32" and not os.path.exists(sys.executable): # App symlink appears to not exist, but we want the # real executable here anyway import _winapi executable = _winapi.GetModuleFileName(0) else: executable = sys.executable res = platform.libc_ver(executable) self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, 'wb') as f: f.write(b'x'*(16384-10)) f.write(b'GLIBC_1.23.4\0GLIBC_1.9\0GLIBC_1.21\0') self.assertEqual(platform.libc_ver(support.TESTFN), ('glibc', '1.23.4')) @support.cpython_only def test__comparable_version(self): from platform import _comparable_version as V self.assertEqual(V('1.2.3'), V('1.2.3')) self.assertLess(V('1.2.3'), V('1.2.10')) self.assertEqual(V('1.2.3.4'), V('1_2-3+4')) self.assertLess(V('1.2spam'), V('1.2dev')) self.assertLess(V('1.2dev'), V('1.2alpha')) self.assertLess(V('1.2dev'), V('1.2a')) self.assertLess(V('1.2alpha'), V('1.2beta')) self.assertLess(V('1.2a'), V('1.2b')) self.assertLess(V('1.2beta'), V('1.2c')) self.assertLess(V('1.2b'), V('1.2c')) self.assertLess(V('1.2c'), V('1.2RC')) self.assertLess(V('1.2c'), V('1.2rc')) self.assertLess(V('1.2RC'), V('1.2.0')) self.assertLess(V('1.2rc'), V('1.2.0')) self.assertLess(V('1.2.0'), V('1.2pl')) self.assertLess(V('1.2.0'), V('1.2p')) self.assertLess(V('1.5.1'), V('1.5.2b2')) self.assertLess(V('3.10a'), V('161')) self.assertEqual(V('8.02'), V('8.02')) self.assertLess(V('3.4j'), V('1996.07.12')) self.assertLess(V('3.1.1.6'), V('3.2.pl0')) self.assertLess(V('2g6'), V('11g')) self.assertLess(V('0.9'), V('2.2')) self.assertLess(V('1.2'), V('1.2.1')) self.assertLess(V('1.1'), V('1.2.2')) self.assertLess(V('1.1'), V('1.2')) self.assertLess(V('1.2.1'), V('1.2.2')) self.assertLess(V('1.2'), V('1.2.2')) self.assertLess(V('0.4'), V('0.4.0')) self.assertLess(V('1.13++'), V('5.5.kw')) self.assertLess(V('0.960923'), V('2.2beta29')) def test_parse_release_file(self): for input, output in ( # Examples of release file contents: ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')), ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')), ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')), ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')), ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')), ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')), ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')), ('CentOS release 4', ('CentOS', '4', None)), ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')), ('', ('', '', '')), # If there's nothing there. ): self.assertEqual(platform._parse_release_file(input), output) def test_popen(self): mswindows = (sys.platform == "win32") if mswindows: command = '"{}" -c "print(\'Hello\')"'.format(sys.executable) else: command = "'{}' -c 'print(\"Hello\")'".format(sys.executable) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) with platform.popen(command) as stdout: hello = stdout.read().strip() stdout.close() self.assertEqual(hello, "Hello") data = 'plop' if mswindows: command = '"{}" -c "import sys; data=sys.stdin.read(); exit(len(data))"' else: command = "'{}' -c 'import sys; data=sys.stdin.read(); exit(len(data))'" command = command.format(sys.executable) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) with platform.popen(command, 'w') as stdin: stdout = stdin.write(data) ret = stdin.close() self.assertIsNotNone(ret) if os.name == 'nt': returncode = ret else: returncode = ret >> 8 self.assertEqual(returncode, len(data)) def test_linux_distribution_encoding(self): # Issue #17429 with tempfile.TemporaryDirectory() as tempdir: filename = os.path.join(tempdir, 'fedora-release') with open(filename, 'w', encoding='utf-8') as f: f.write('Fedora release 19 (Schr\xf6dinger\u2019s Cat)\n') with mock.patch('platform._UNIXCONFDIR', tempdir): with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', r'dist\(\) and linux_distribution\(\) ' 'functions are deprecated .*', DeprecationWarning, ) distname, version, distid = platform.linux_distribution() self.assertEqual(distname, 'Fedora') self.assertEqual(version, '19') self.assertEqual(distid, 'Schr\xf6dinger\u2019s Cat') class DeprecationTest(unittest.TestCase): def test_dist_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: platform.dist() self.assertEqual(str(cm.warning), 'dist() and linux_distribution() functions are ' 'deprecated in Python 3.5') def test_linux_distribution_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: platform.linux_distribution() self.assertEqual(str(cm.warning), 'dist() and linux_distribution() functions are ' 'deprecated in Python 3.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/test_bytes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bytes.py
"""Unit tests for the bytes and bytearray types. XXX This is a mess. Common tests should be unified with string_tests.py (and the latter should be modernized). """ import array import os import re import sys import copy import functools import pickle import tempfile import unittest import test.support import test.string_tests import test.list_tests from test.support import bigaddrspacetest, MAX_Py_ssize_t if sys.flags.bytes_warning: def check_bytes_warnings(func): @functools.wraps(func) def wrapper(*args, **kw): with test.support.check_warnings(('', BytesWarning)): return func(*args, **kw) return wrapper else: # no-op def check_bytes_warnings(func): return func class Indexable: def __init__(self, value=0): self.value = value def __index__(self): return self.value class BaseBytesTest: def test_basics(self): b = self.type2test() self.assertEqual(type(b), self.type2test) self.assertEqual(b.__class__, self.type2test) def test_copy(self): a = self.type2test(b"abcd") for copy_method in (copy.copy, copy.deepcopy): b = copy_method(a) self.assertEqual(a, b) self.assertEqual(type(a), type(b)) def test_empty_sequence(self): b = self.type2test() self.assertEqual(len(b), 0) self.assertRaises(IndexError, lambda: b[0]) self.assertRaises(IndexError, lambda: b[1]) self.assertRaises(IndexError, lambda: b[sys.maxsize]) self.assertRaises(IndexError, lambda: b[sys.maxsize+1]) self.assertRaises(IndexError, lambda: b[10**100]) self.assertRaises(IndexError, lambda: b[-1]) self.assertRaises(IndexError, lambda: b[-2]) self.assertRaises(IndexError, lambda: b[-sys.maxsize]) self.assertRaises(IndexError, lambda: b[-sys.maxsize-1]) self.assertRaises(IndexError, lambda: b[-sys.maxsize-2]) self.assertRaises(IndexError, lambda: b[-10**100]) def test_from_iterable(self): b = self.type2test(range(256)) self.assertEqual(len(b), 256) self.assertEqual(list(b), list(range(256))) # Non-sequence iterable. b = self.type2test({42}) self.assertEqual(b, b"*") b = self.type2test({43, 45}) self.assertIn(tuple(b), {(43, 45), (45, 43)}) # Iterator that has a __length_hint__. b = self.type2test(iter(range(256))) self.assertEqual(len(b), 256) self.assertEqual(list(b), list(range(256))) # Iterator that doesn't have a __length_hint__. b = self.type2test(i for i in range(256) if i % 2) self.assertEqual(len(b), 128) self.assertEqual(list(b), list(range(256))[1::2]) # Sequence without __iter__. class S: def __getitem__(self, i): return (1, 2, 3)[i] b = self.type2test(S()) self.assertEqual(b, b"\x01\x02\x03") def test_from_tuple(self): # There is a special case for tuples. b = self.type2test(tuple(range(256))) self.assertEqual(len(b), 256) self.assertEqual(list(b), list(range(256))) b = self.type2test((1, 2, 3)) self.assertEqual(b, b"\x01\x02\x03") def test_from_list(self): # There is a special case for lists. b = self.type2test(list(range(256))) self.assertEqual(len(b), 256) self.assertEqual(list(b), list(range(256))) b = self.type2test([1, 2, 3]) self.assertEqual(b, b"\x01\x02\x03") def test_from_mutating_list(self): # Issue #34973: Crash in bytes constructor with mutating list. class X: def __index__(self): a.clear() return 42 a = [X(), X()] self.assertEqual(bytes(a), b'*') class Y: def __index__(self): if len(a) < 1000: a.append(self) return 42 a = [Y()] self.assertEqual(bytes(a), b'*' * 1000) # should not crash def test_from_index(self): b = self.type2test([Indexable(), Indexable(1), Indexable(254), Indexable(255)]) self.assertEqual(list(b), [0, 1, 254, 255]) self.assertRaises(ValueError, self.type2test, [Indexable(-1)]) self.assertRaises(ValueError, self.type2test, [Indexable(256)]) def test_from_buffer(self): a = self.type2test(array.array('B', [1, 2, 3])) self.assertEqual(a, b"\x01\x02\x03") a = self.type2test(b"\x01\x02\x03") self.assertEqual(a, b"\x01\x02\x03") # Issues #29159 and #34974. # Fallback when __index__ raises a TypeError class B(bytes): def __index__(self): raise TypeError self.assertEqual(self.type2test(B(b"foobar")), b"foobar") def test_from_ssize(self): self.assertEqual(self.type2test(0), b'') self.assertEqual(self.type2test(1), b'\x00') self.assertEqual(self.type2test(5), b'\x00\x00\x00\x00\x00') self.assertRaises(ValueError, self.type2test, -1) self.assertEqual(self.type2test('0', 'ascii'), b'0') self.assertEqual(self.type2test(b'0'), b'0') self.assertRaises(OverflowError, self.type2test, sys.maxsize + 1) def test_constructor_type_errors(self): self.assertRaises(TypeError, self.type2test, 0.0) class C: pass self.assertRaises(TypeError, self.type2test, ["0"]) self.assertRaises(TypeError, self.type2test, [0.0]) self.assertRaises(TypeError, self.type2test, [None]) self.assertRaises(TypeError, self.type2test, [C()]) self.assertRaises(TypeError, self.type2test, 0, 'ascii') self.assertRaises(TypeError, self.type2test, b'', 'ascii') self.assertRaises(TypeError, self.type2test, 0, errors='ignore') self.assertRaises(TypeError, self.type2test, b'', errors='ignore') self.assertRaises(TypeError, self.type2test, '') self.assertRaises(TypeError, self.type2test, '', errors='ignore') self.assertRaises(TypeError, self.type2test, '', b'ascii') self.assertRaises(TypeError, self.type2test, '', 'ascii', b'ignore') def test_constructor_value_errors(self): self.assertRaises(ValueError, self.type2test, [-1]) self.assertRaises(ValueError, self.type2test, [-sys.maxsize]) self.assertRaises(ValueError, self.type2test, [-sys.maxsize-1]) self.assertRaises(ValueError, self.type2test, [-sys.maxsize-2]) self.assertRaises(ValueError, self.type2test, [-10**100]) self.assertRaises(ValueError, self.type2test, [256]) self.assertRaises(ValueError, self.type2test, [257]) self.assertRaises(ValueError, self.type2test, [sys.maxsize]) self.assertRaises(ValueError, self.type2test, [sys.maxsize+1]) self.assertRaises(ValueError, self.type2test, [10**100]) @bigaddrspacetest def test_constructor_overflow(self): size = MAX_Py_ssize_t self.assertRaises((OverflowError, MemoryError), self.type2test, size) try: # Should either pass or raise an error (e.g. on debug builds with # additional malloc() overhead), but shouldn't crash. bytearray(size - 4) except (OverflowError, MemoryError): pass def test_constructor_exceptions(self): # Issue #34974: bytes and bytearray constructors replace unexpected # exceptions. class BadInt: def __index__(self): 1/0 self.assertRaises(ZeroDivisionError, self.type2test, BadInt()) self.assertRaises(ZeroDivisionError, self.type2test, [BadInt()]) class BadIterable: def __iter__(self): 1/0 self.assertRaises(ZeroDivisionError, self.type2test, BadIterable()) def test_compare(self): b1 = self.type2test([1, 2, 3]) b2 = self.type2test([1, 2, 3]) b3 = self.type2test([1, 3]) self.assertEqual(b1, b2) self.assertTrue(b2 != b3) self.assertTrue(b1 <= b2) self.assertTrue(b1 <= b3) self.assertTrue(b1 < b3) self.assertTrue(b1 >= b2) self.assertTrue(b3 >= b2) self.assertTrue(b3 > b2) self.assertFalse(b1 != b2) self.assertFalse(b2 == b3) self.assertFalse(b1 > b2) self.assertFalse(b1 > b3) self.assertFalse(b1 >= b3) self.assertFalse(b1 < b2) self.assertFalse(b3 < b2) self.assertFalse(b3 <= b2) @check_bytes_warnings def test_compare_to_str(self): # Byte comparisons with unicode should always fail! # Test this for all expected byte orders and Unicode character # sizes. self.assertEqual(self.type2test(b"\0a\0b\0c") == "abc", False) self.assertEqual(self.type2test(b"\0\0\0a\0\0\0b\0\0\0c") == "abc", False) self.assertEqual(self.type2test(b"a\0b\0c\0") == "abc", False) self.assertEqual(self.type2test(b"a\0\0\0b\0\0\0c\0\0\0") == "abc", False) self.assertEqual(self.type2test() == str(), False) self.assertEqual(self.type2test() != str(), True) def test_reversed(self): input = list(map(ord, "Hello")) b = self.type2test(input) output = list(reversed(b)) input.reverse() self.assertEqual(output, input) def test_getslice(self): def by(s): return self.type2test(map(ord, s)) b = by("Hello, world") self.assertEqual(b[:5], by("Hello")) self.assertEqual(b[1:5], by("ello")) self.assertEqual(b[5:7], by(", ")) self.assertEqual(b[7:], by("world")) self.assertEqual(b[7:12], by("world")) self.assertEqual(b[7:100], by("world")) self.assertEqual(b[:-7], by("Hello")) self.assertEqual(b[-11:-7], by("ello")) self.assertEqual(b[-7:-5], by(", ")) self.assertEqual(b[-5:], by("world")) self.assertEqual(b[-5:12], by("world")) self.assertEqual(b[-5:100], by("world")) self.assertEqual(b[-100:5], by("Hello")) def test_extended_getslice(self): # Test extended slicing by comparing with list slicing. L = list(range(255)) b = self.type2test(L) indices = (0, None, 1, 3, 19, 100, sys.maxsize, -1, -2, -31, -100) for start in indices: for stop in indices: # Skip step 0 (invalid) for step in indices[1:]: self.assertEqual(b[start:stop:step], self.type2test(L[start:stop:step])) def test_encoding(self): sample = "Hello world\n\u1234\u5678\u9abc" for enc in ("utf-8", "utf-16"): b = self.type2test(sample, enc) self.assertEqual(b, self.type2test(sample.encode(enc))) self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin-1") b = self.type2test(sample, "latin-1", "ignore") self.assertEqual(b, self.type2test(sample[:-3], "utf-8")) def test_decode(self): sample = "Hello world\n\u1234\u5678\u9abc" for enc in ("utf-8", "utf-16"): b = self.type2test(sample, enc) self.assertEqual(b.decode(enc), sample) sample = "Hello world\n\x80\x81\xfe\xff" b = self.type2test(sample, "latin-1") self.assertRaises(UnicodeDecodeError, b.decode, "utf-8") self.assertEqual(b.decode("utf-8", "ignore"), "Hello world\n") self.assertEqual(b.decode(errors="ignore", encoding="utf-8"), "Hello world\n") # Default encoding is utf-8 self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603') def test_from_int(self): b = self.type2test(0) self.assertEqual(b, self.type2test()) b = self.type2test(10) self.assertEqual(b, self.type2test([0]*10)) b = self.type2test(10000) self.assertEqual(b, self.type2test([0]*10000)) def test_concat(self): b1 = self.type2test(b"abc") b2 = self.type2test(b"def") self.assertEqual(b1 + b2, b"abcdef") self.assertEqual(b1 + bytes(b"def"), b"abcdef") self.assertEqual(bytes(b"def") + b1, b"defabc") self.assertRaises(TypeError, lambda: b1 + "def") self.assertRaises(TypeError, lambda: "abc" + b2) def test_repeat(self): for b in b"abc", self.type2test(b"abc"): self.assertEqual(b * 3, b"abcabcabc") self.assertEqual(b * 0, b"") self.assertEqual(b * -1, b"") self.assertRaises(TypeError, lambda: b * 3.14) self.assertRaises(TypeError, lambda: 3.14 * b) # XXX Shouldn't bytes and bytearray agree on what to raise? with self.assertRaises((OverflowError, MemoryError)): c = b * sys.maxsize with self.assertRaises((OverflowError, MemoryError)): b *= sys.maxsize def test_repeat_1char(self): self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100)) def test_contains(self): b = self.type2test(b"abc") self.assertIn(ord('a'), b) self.assertIn(int(ord('a')), b) self.assertNotIn(200, b) self.assertRaises(ValueError, lambda: 300 in b) self.assertRaises(ValueError, lambda: -1 in b) self.assertRaises(ValueError, lambda: sys.maxsize+1 in b) self.assertRaises(TypeError, lambda: None in b) self.assertRaises(TypeError, lambda: float(ord('a')) in b) self.assertRaises(TypeError, lambda: "a" in b) for f in bytes, bytearray: self.assertIn(f(b""), b) self.assertIn(f(b"a"), b) self.assertIn(f(b"b"), b) self.assertIn(f(b"c"), b) self.assertIn(f(b"ab"), b) self.assertIn(f(b"bc"), b) self.assertIn(f(b"abc"), b) self.assertNotIn(f(b"ac"), b) self.assertNotIn(f(b"d"), b) self.assertNotIn(f(b"dab"), b) self.assertNotIn(f(b"abd"), b) def test_fromhex(self): self.assertRaises(TypeError, self.type2test.fromhex) self.assertRaises(TypeError, self.type2test.fromhex, 1) self.assertEqual(self.type2test.fromhex(''), self.type2test()) b = bytearray([0x1a, 0x2b, 0x30]) self.assertEqual(self.type2test.fromhex('1a2B30'), b) self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b) # check that ASCII whitespace is ignored self.assertEqual(self.type2test.fromhex(' 1A\n2B\t30\v'), b) for c in "\x09\x0A\x0B\x0C\x0D\x20": self.assertEqual(self.type2test.fromhex(c), self.type2test()) for c in "\x1C\x1D\x1E\x1F\x85\xa0\u2000\u2002\u2028": self.assertRaises(ValueError, self.type2test.fromhex, c) self.assertEqual(self.type2test.fromhex('0000'), b'\0\0') self.assertRaises(TypeError, self.type2test.fromhex, b'1B') self.assertRaises(ValueError, self.type2test.fromhex, 'a') self.assertRaises(ValueError, self.type2test.fromhex, 'rt') self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd') self.assertRaises(ValueError, self.type2test.fromhex, '\x00') self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34') for data, pos in ( # invalid first hexadecimal character ('12 x4 56', 3), # invalid second hexadecimal character ('12 3x 56', 4), # two invalid hexadecimal characters ('12 xy 56', 3), # test non-ASCII string ('12 3\xff 56', 4), ): with self.assertRaises(ValueError) as cm: self.type2test.fromhex(data) self.assertIn('at position %s' % pos, str(cm.exception)) def test_hex(self): self.assertRaises(TypeError, self.type2test.hex) self.assertRaises(TypeError, self.type2test.hex, 1) self.assertEqual(self.type2test(b"").hex(), "") self.assertEqual(bytearray([0x1a, 0x2b, 0x30]).hex(), '1a2b30') self.assertEqual(self.type2test(b"\x1a\x2b\x30").hex(), '1a2b30') self.assertEqual(memoryview(b"\x1a\x2b\x30").hex(), '1a2b30') def test_join(self): self.assertEqual(self.type2test(b"").join([]), b"") self.assertEqual(self.type2test(b"").join([b""]), b"") for lst in [[b"abc"], [b"a", b"bc"], [b"ab", b"c"], [b"a", b"b", b"c"]]: lst = list(map(self.type2test, lst)) self.assertEqual(self.type2test(b"").join(lst), b"abc") self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc") self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc") dot_join = self.type2test(b".:").join self.assertEqual(dot_join([b"ab", b"cd"]), b"ab.:cd") self.assertEqual(dot_join([memoryview(b"ab"), b"cd"]), b"ab.:cd") self.assertEqual(dot_join([b"ab", memoryview(b"cd")]), b"ab.:cd") self.assertEqual(dot_join([bytearray(b"ab"), b"cd"]), b"ab.:cd") self.assertEqual(dot_join([b"ab", bytearray(b"cd")]), b"ab.:cd") # Stress it with many items seq = [b"abc"] * 1000 expected = b"abc" + b".:abc" * 999 self.assertEqual(dot_join(seq), expected) self.assertRaises(TypeError, self.type2test(b" ").join, None) # Error handling and cleanup when some item in the middle of the # sequence has the wrong type. with self.assertRaises(TypeError): dot_join([bytearray(b"ab"), "cd", b"ef"]) with self.assertRaises(TypeError): dot_join([memoryview(b"ab"), "cd", b"ef"]) def test_count(self): b = self.type2test(b'mississippi') i = 105 p = 112 w = 119 self.assertEqual(b.count(b'i'), 4) self.assertEqual(b.count(b'ss'), 2) self.assertEqual(b.count(b'w'), 0) self.assertEqual(b.count(i), 4) self.assertEqual(b.count(w), 0) self.assertEqual(b.count(b'i', 6), 2) self.assertEqual(b.count(b'p', 6), 2) self.assertEqual(b.count(b'i', 1, 3), 1) self.assertEqual(b.count(b'p', 7, 9), 1) self.assertEqual(b.count(i, 6), 2) self.assertEqual(b.count(p, 6), 2) self.assertEqual(b.count(i, 1, 3), 1) self.assertEqual(b.count(p, 7, 9), 1) def test_startswith(self): b = self.type2test(b'hello') self.assertFalse(self.type2test().startswith(b"anything")) self.assertTrue(b.startswith(b"hello")) self.assertTrue(b.startswith(b"hel")) self.assertTrue(b.startswith(b"h")) self.assertFalse(b.startswith(b"hellow")) self.assertFalse(b.startswith(b"ha")) with self.assertRaises(TypeError) as cm: b.startswith([b'h']) exc = str(cm.exception) self.assertIn('bytes', exc) self.assertIn('tuple', exc) def test_endswith(self): b = self.type2test(b'hello') self.assertFalse(bytearray().endswith(b"anything")) self.assertTrue(b.endswith(b"hello")) self.assertTrue(b.endswith(b"llo")) self.assertTrue(b.endswith(b"o")) self.assertFalse(b.endswith(b"whello")) self.assertFalse(b.endswith(b"no")) with self.assertRaises(TypeError) as cm: b.endswith([b'o']) exc = str(cm.exception) self.assertIn('bytes', exc) self.assertIn('tuple', exc) def test_find(self): b = self.type2test(b'mississippi') i = 105 w = 119 self.assertEqual(b.find(b'ss'), 2) self.assertEqual(b.find(b'w'), -1) self.assertEqual(b.find(b'mississippian'), -1) self.assertEqual(b.find(i), 1) self.assertEqual(b.find(w), -1) self.assertEqual(b.find(b'ss', 3), 5) self.assertEqual(b.find(b'ss', 1, 7), 2) self.assertEqual(b.find(b'ss', 1, 3), -1) self.assertEqual(b.find(i, 6), 7) self.assertEqual(b.find(i, 1, 3), 1) self.assertEqual(b.find(w, 1, 3), -1) for index in (-1, 256, sys.maxsize + 1): self.assertRaisesRegex( ValueError, r'byte must be in range\(0, 256\)', b.find, index) def test_rfind(self): b = self.type2test(b'mississippi') i = 105 w = 119 self.assertEqual(b.rfind(b'ss'), 5) self.assertEqual(b.rfind(b'w'), -1) self.assertEqual(b.rfind(b'mississippian'), -1) self.assertEqual(b.rfind(i), 10) self.assertEqual(b.rfind(w), -1) self.assertEqual(b.rfind(b'ss', 3), 5) self.assertEqual(b.rfind(b'ss', 0, 6), 2) self.assertEqual(b.rfind(i, 1, 3), 1) self.assertEqual(b.rfind(i, 3, 9), 7) self.assertEqual(b.rfind(w, 1, 3), -1) def test_index(self): b = self.type2test(b'mississippi') i = 105 w = 119 self.assertEqual(b.index(b'ss'), 2) self.assertRaises(ValueError, b.index, b'w') self.assertRaises(ValueError, b.index, b'mississippian') self.assertEqual(b.index(i), 1) self.assertRaises(ValueError, b.index, w) self.assertEqual(b.index(b'ss', 3), 5) self.assertEqual(b.index(b'ss', 1, 7), 2) self.assertRaises(ValueError, b.index, b'ss', 1, 3) self.assertEqual(b.index(i, 6), 7) self.assertEqual(b.index(i, 1, 3), 1) self.assertRaises(ValueError, b.index, w, 1, 3) def test_rindex(self): b = self.type2test(b'mississippi') i = 105 w = 119 self.assertEqual(b.rindex(b'ss'), 5) self.assertRaises(ValueError, b.rindex, b'w') self.assertRaises(ValueError, b.rindex, b'mississippian') self.assertEqual(b.rindex(i), 10) self.assertRaises(ValueError, b.rindex, w) self.assertEqual(b.rindex(b'ss', 3), 5) self.assertEqual(b.rindex(b'ss', 0, 6), 2) self.assertEqual(b.rindex(i, 1, 3), 1) self.assertEqual(b.rindex(i, 3, 9), 7) self.assertRaises(ValueError, b.rindex, w, 1, 3) def test_mod(self): b = self.type2test(b'hello, %b!') orig = b b = b % b'world' self.assertEqual(b, b'hello, world!') self.assertEqual(orig, b'hello, %b!') self.assertFalse(b is orig) b = self.type2test(b'%s / 100 = %d%%') a = b % (b'seventy-nine', 79) self.assertEqual(a, b'seventy-nine / 100 = 79%') self.assertIs(type(a), self.type2test) # issue 29714 b = self.type2test(b'hello,\x00%b!') b = b % b'world' self.assertEqual(b, b'hello,\x00world!') self.assertIs(type(b), self.type2test) def test_imod(self): b = self.type2test(b'hello, %b!') orig = b b %= b'world' self.assertEqual(b, b'hello, world!') self.assertEqual(orig, b'hello, %b!') self.assertFalse(b is orig) b = self.type2test(b'%s / 100 = %d%%') b %= (b'seventy-nine', 79) self.assertEqual(b, b'seventy-nine / 100 = 79%') self.assertIs(type(b), self.type2test) # issue 29714 b = self.type2test(b'hello,\x00%b!') b %= b'world' self.assertEqual(b, b'hello,\x00world!') self.assertIs(type(b), self.type2test) def test_rmod(self): with self.assertRaises(TypeError): object() % self.type2test(b'abc') self.assertIs(self.type2test(b'abc').__rmod__('%r'), NotImplemented) def test_replace(self): b = self.type2test(b'mississippi') self.assertEqual(b.replace(b'i', b'a'), b'massassappa') self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi') def test_replace_int_error(self): self.assertRaises(TypeError, self.type2test(b'a b').replace, 32, b'') def test_split_string_error(self): self.assertRaises(TypeError, self.type2test(b'a b').split, ' ') self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ') def test_split_int_error(self): self.assertRaises(TypeError, self.type2test(b'a b').split, 32) self.assertRaises(TypeError, self.type2test(b'a b').rsplit, 32) def test_split_unicodewhitespace(self): for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'): b = self.type2test(b) self.assertEqual(b.split(), [b]) b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F") self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f']) def test_rsplit_unicodewhitespace(self): b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F") self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f']) def test_partition(self): b = self.type2test(b'mississippi') self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi')) self.assertEqual(b.partition(b'w'), (b'mississippi', b'', b'')) def test_rpartition(self): b = self.type2test(b'mississippi') self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi')) self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b'')) self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi')) def test_partition_string_error(self): self.assertRaises(TypeError, self.type2test(b'a b').partition, ' ') self.assertRaises(TypeError, self.type2test(b'a b').rpartition, ' ') def test_partition_int_error(self): self.assertRaises(TypeError, self.type2test(b'a b').partition, 32) self.assertRaises(TypeError, self.type2test(b'a b').rpartition, 32) def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0": b = self.type2test(b) ps = pickle.dumps(b, proto) q = pickle.loads(ps) self.assertEqual(b, q) def test_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0": it = itorg = iter(self.type2test(b)) data = list(self.type2test(b)) d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(list(it), data) it = pickle.loads(d) if not b: continue next(it) d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(list(it), data[1:]) def test_strip_bytearray(self): self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b') self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc') self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab') def test_strip_string_error(self): self.assertRaises(TypeError, self.type2test(b'abc').strip, 'ac') self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'ac') self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'ac') def test_strip_int_error(self): self.assertRaises(TypeError, self.type2test(b' abc ').strip, 32) self.assertRaises(TypeError, self.type2test(b' abc ').lstrip, 32) self.assertRaises(TypeError, self.type2test(b' abc ').rstrip, 32) def test_center(self): # Fill character can be either bytes or bytearray (issue 12380) b = self.type2test(b'abc') for fill_type in (bytes, bytearray): self.assertEqual(b.center(7, fill_type(b'-')), self.type2test(b'--abc--')) def test_ljust(self): # Fill character can be either bytes or bytearray (issue 12380) b = self.type2test(b'abc') for fill_type in (bytes, bytearray): self.assertEqual(b.ljust(7, fill_type(b'-')), self.type2test(b'abc----')) def test_rjust(self): # Fill character can be either bytes or bytearray (issue 12380) b = self.type2test(b'abc') for fill_type in (bytes, bytearray): self.assertEqual(b.rjust(7, fill_type(b'-')), self.type2test(b'----abc')) def test_xjust_int_error(self): self.assertRaises(TypeError, self.type2test(b'abc').center, 7, 32) self.assertRaises(TypeError, self.type2test(b'abc').ljust, 7, 32) self.assertRaises(TypeError, self.type2test(b'abc').rjust, 7, 32) def test_ord(self): b = self.type2test(b'\0A\x7f\x80\xff') self.assertEqual([ord(b[i:i+1]) for i in range(len(b))], [0, 65, 127, 128, 255]) def test_maketrans(self): transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable) transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374xyz' self.assertEqual(self.type2test.maketrans(b'\375\376\377', b'xyz'), transtable) self.assertRaises(ValueError, self.type2test.maketrans, b'abc', b'xyzq') self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def') def test_none_arguments(self): # issue 11828 b = self.type2test(b'hello') l = self.type2test(b'l') h = self.type2test(b'h') x = self.type2test(b'x') o = self.type2test(b'o') self.assertEqual(2, b.find(l, None)) self.assertEqual(3, b.find(l, -2, None)) self.assertEqual(2, b.find(l, None, -2)) self.assertEqual(0, b.find(h, None, None)) self.assertEqual(3, b.rfind(l, None)) self.assertEqual(3, b.rfind(l, -2, None)) self.assertEqual(2, b.rfind(l, None, -2)) self.assertEqual(0, b.rfind(h, None, None)) self.assertEqual(2, b.index(l, None)) self.assertEqual(3, b.index(l, -2, None)) self.assertEqual(2, b.index(l, None, -2)) self.assertEqual(0, b.index(h, None, None)) self.assertEqual(3, b.rindex(l, None)) self.assertEqual(3, b.rindex(l, -2, None)) self.assertEqual(2, b.rindex(l, None, -2)) self.assertEqual(0, b.rindex(h, None, None)) self.assertEqual(2, b.count(l, None)) self.assertEqual(1, b.count(l, -2, None)) self.assertEqual(1, b.count(l, None, -2)) self.assertEqual(0, b.count(x, None, None)) self.assertEqual(True, b.endswith(o, None)) self.assertEqual(True, b.endswith(o, -2, None)) self.assertEqual(True, b.endswith(l, None, -2)) self.assertEqual(False, b.endswith(x, None, None)) self.assertEqual(True, b.startswith(h, None)) self.assertEqual(True, b.startswith(l, -2, None)) self.assertEqual(True, b.startswith(h, None, -2)) self.assertEqual(False, b.startswith(x, None, None)) def test_integer_arguments_out_of_byte_range(self): b = self.type2test(b'hello') for method in (b.count, b.find, b.index, b.rfind, b.rindex): self.assertRaises(ValueError, method, -1) self.assertRaises(ValueError, method, 256)
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_traceback.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_traceback.py
"""Test cases for traceback module""" from collections import namedtuple from io import StringIO import linecache import sys import unittest import re from test import support from test.support import TESTFN, Error, captured_output, unlink, cpython_only from test.support.script_helper import assert_python_ok import textwrap import traceback test_code = namedtuple('code', ['co_filename', 'co_name']) test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals']) test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next']) class TracebackCases(unittest.TestCase): # For now, a very minimal set of tests. I want to be sure that # formatting of SyntaxErrors works based on changes for 2.1. def get_exception_format(self, func, exc): try: func() except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError("call did not raise exception") def syntax_error_with_caret(self): compile("def fact(x):\n\treturn x!\n", "?", "exec") def syntax_error_with_caret_2(self): compile("1 +\n", "?", "exec") def syntax_error_bad_indentation(self): compile("def spam():\n print(1)\n print(2)", "?", "exec") def syntax_error_with_caret_non_ascii(self): compile('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', "?", "exec") def syntax_error_bad_indentation2(self): compile(" print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) self.assertEqual(len(err), 4) self.assertTrue(err[1].strip() == "return x!") self.assertIn("^", err[2]) # third line has caret self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) self.assertIn("^", err[2]) # third line has caret self.assertEqual(err[2].count('\n'), 1) # and no additional newline self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_non_ascii, SyntaxError) self.assertIn("^", err[2]) # third line has caret self.assertEqual(err[2].count('\n'), 1) # and no additional newline self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place def test_nocaret(self): exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) err = traceback.format_exception_only(SyntaxError, exc) self.assertEqual(len(err), 3) self.assertEqual(err[1].strip(), "bad syntax") def test_bad_indentation(self): err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") self.assertIn("^", err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) err = self.get_exception_format(self.syntax_error_bad_indentation2, IndentationError) self.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") self.assertIn("^", err[2]) self.assertEqual(err[1].find("p"), err[2].find("^")) def test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) def test_format_exception_only_bad__str__(self): class X(Exception): def __str__(self): 1/0 err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '<unprintable %s object>' % X.__name__ if X.__module__ in ('__main__', 'builtins'): str_name = X.__qualname__ else: str_name = '.'.join([X.__module__, X.__qualname__]) self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) def test_encoded_file(self): # Test that tracebacks are correctly printed for encoded source files: # - correct line number (Issue2384) # - respect file encoding (Issue3975) import tempfile, sys, subprocess, os # The spawned subprocess has its stdout redirected to a PIPE, and its # encoding may be different from the current interpreter, on Windows # at least. process = subprocess.Popen([sys.executable, "-c", "import sys; print(sys.stdout.encoding)"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() output_encoding = str(stdout, 'ascii').splitlines()[0] def do_test(firstlines, message, charset, lineno): # Raise the message in a subprocess, and catch the output try: with open(TESTFN, "w", encoding=charset) as output: output.write("""{0}if 1: import traceback; raise RuntimeError('{1}') """.format(firstlines, message)) process = subprocess.Popen([sys.executable, TESTFN], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() stdout = stdout.decode(output_encoding).splitlines() finally: unlink(TESTFN) # The source lines are encoded with the 'backslashreplace' handler encoded_message = message.encode(output_encoding, 'backslashreplace') # and we just decoded them with the output_encoding. message_ascii = encoded_message.decode(output_encoding) err_line = "raise RuntimeError('{0}')".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii) self.assertIn(("line %s" % lineno), stdout[1], "Invalid line number: {0!r} instead of {1}".format( stdout[1], lineno)) self.assertTrue(stdout[2].endswith(err_line), "Invalid traceback line: {0!r} instead of {1!r}".format( stdout[2], err_line)) self.assertTrue(stdout[3] == err_msg, "Invalid error message: {0!r} instead of {1!r}".format( stdout[3], err_msg)) do_test("", "foo", "ascii", 3) for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): if charset == "ascii": text = "foo" elif charset == "GBK": text = "\u4E02\u5100" else: text = "h\xe9 ho" do_test("# coding: {0}\n".format(charset), text, charset, 4) do_test("#!shebang\n# coding: {0}\n".format(charset), text, charset, 5) do_test(" \t\f\n# coding: {0}\n".format(charset), text, charset, 5) # Issue #18960: coding spec should have no effect do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5) @support.requires_type_collecting def test_print_traceback_at_exit(self): # Issue #22599: Ensure that it is possible to use the traceback module # to display an exception at Python exit code = textwrap.dedent(""" import sys import traceback class PrintExceptionAtExit(object): def __init__(self): try: x = 1 / 0 except Exception: self.exc_info = sys.exc_info() # self.exc_info[1] (traceback) contains frames: # explicitly clear the reference to self in the current # frame to break a reference cycle self = None def __del__(self): traceback.print_exception(*self.exc_info) # Keep a reference in the module namespace to call the destructor # when the module is unloaded obj = PrintExceptionAtExit() """) rc, stdout, stderr = assert_python_ok('-c', code) expected = [b'Traceback (most recent call last):', b' File "<string>", line 8, in __init__', b'ZeroDivisionError: division by zero'] self.assertEqual(stderr.splitlines(), expected) def test_print_exception(self): output = StringIO() traceback.print_exception( Exception, Exception("projector"), None, file=output ) self.assertEqual(output.getvalue(), "Exception: projector\n") class TracebackFormatTests(unittest.TestCase): def some_exception(self): raise KeyError('blah') @cpython_only def check_traceback_format(self, cleanup_func=None): from _testcapi import traceback_print try: self.some_exception() except KeyError: type_, value, tb = sys.exc_info() if cleanup_func is not None: # Clear the inner frames, not this one cleanup_func(tb.tb_next) traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() # Call all _tb and _exc functions with captured_output("stderr") as tbstderr: traceback.print_tb(tb) tbfile = StringIO() traceback.print_tb(tb, file=tbfile) with captured_output("stderr") as excstderr: traceback.print_exc() excfmt = traceback.format_exc() excfile = StringIO() traceback.print_exc(file=excfile) else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Now verify the _tb func output self.assertEqual(tbstderr.getvalue(), tbfile.getvalue()) # Now verify the _exc func output self.assertEqual(excstderr.getvalue(), excfile.getvalue()) self.assertEqual(excfmt, excfile.getvalue()) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 5) banner = tb_lines[0] location, source_line = tb_lines[-2:] self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise')) def test_traceback_format(self): self.check_traceback_format() def test_traceback_format_with_cleared_frames(self): # Check that traceback formatting also works with a clear()ed frame def cleanup_tb(tb): tb.tb_frame.clear() self.check_traceback_format(cleanup_tb) def test_stack_format(self): # Verify _stack functions. Note we have to use _getframe(1) to # compare them without this frame appearing in the output with captured_output("stderr") as ststderr: traceback.print_stack(sys._getframe(1)) stfile = StringIO() traceback.print_stack(sys._getframe(1), file=stfile) self.assertEqual(ststderr.getvalue(), stfile.getvalue()) stfmt = traceback.format_stack(sys._getframe(1)) self.assertEqual(ststderr.getvalue(), "".join(stfmt)) def test_print_stack(self): def prn(): traceback.print_stack() with captured_output("stderr") as stderr: prn() lineno = prn.__code__.co_firstlineno self.assertEqual(stderr.getvalue().splitlines()[-4:], [ ' File "%s", line %d, in test_print_stack' % (__file__, lineno+3), ' prn()', ' File "%s", line %d, in prn' % (__file__, lineno+1), ' traceback.print_stack()', ]) # issue 26823 - Shrink recursive tracebacks def _check_recursive_traceback_display(self, render_exc): # Always show full diffs when this test fails # Note that rearranging things may require adjusting # the relative line numbers in the expected tracebacks self.maxDiff = None # Check hitting the recursion limit def f(): f() with captured_output("stderr") as stderr_f: try: f() except RecursionError as exc: render_exc() else: self.fail("no recursion occurred") lineno_f = f.__code__.co_firstlineno result_f = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_f+5}, in _check_recursive_traceback_display\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' f' File "{__file__}", line {lineno_f+1}, in f\n' ' f()\n' # XXX: The following line changes depending on whether the tests # are run through the interactive interpreter or with -m # It also varies depending on the platform (stack size) # Fortunately, we don't care about exactness here, so we use regex r' \[Previous line repeated (\d+) more times\]' '\n' 'RecursionError: maximum recursion depth exceeded\n' ) expected = result_f.splitlines() actual = stderr_f.getvalue().splitlines() # Check the output text matches expectations # 2nd last line contains the repetition count self.assertEqual(actual[:-2], expected[:-2]) self.assertRegex(actual[-2], expected[-2]) # last line can have additional text appended self.assertIn(expected[-1], actual[-1]) # Check the recursion count is roughly as expected rec_limit = sys.getrecursionlimit() self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit-60, rec_limit)) # Check a known (limited) number of recursive invocations def g(count=10): if count: return g(count-1) raise ValueError with captured_output("stderr") as stderr_g: try: g() except ValueError as exc: render_exc() else: self.fail("no value error was raised") lineno_g = g.__code__.co_firstlineno result_g = ( f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' ' [Previous line repeated 7 more times]\n' f' File "{__file__}", line {lineno_g+3}, in g\n' ' raise ValueError\n' 'ValueError\n' ) tb_line = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_g+7}, in _check_recursive_traceback_display\n' ' g()\n' ) expected = (tb_line + result_g).splitlines() actual = stderr_g.getvalue().splitlines() self.assertEqual(actual, expected) # Check 2 different repetitive sections def h(count=10): if count: return h(count-1) g() with captured_output("stderr") as stderr_h: try: h() except ValueError as exc: render_exc() else: self.fail("no value error was raised") lineno_h = h.__code__.co_firstlineno result_h = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_h+7}, in _check_recursive_traceback_display\n' ' h()\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' f' File "{__file__}", line {lineno_h+2}, in h\n' ' return h(count-1)\n' ' [Previous line repeated 7 more times]\n' f' File "{__file__}", line {lineno_h+3}, in h\n' ' g()\n' ) expected = (result_h + result_g).splitlines() actual = stderr_h.getvalue().splitlines() self.assertEqual(actual, expected) # Check the boundary conditions. First, test just below the cutoff. with captured_output("stderr") as stderr_g: try: g(traceback._RECURSIVE_CUTOFF) except ValueError as exc: render_exc() else: self.fail("no error raised") result_g = ( f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+3}, in g\n' ' raise ValueError\n' 'ValueError\n' ) tb_line = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_g+71}, in _check_recursive_traceback_display\n' ' g(traceback._RECURSIVE_CUTOFF)\n' ) expected = (tb_line + result_g).splitlines() actual = stderr_g.getvalue().splitlines() self.assertEqual(actual, expected) # Second, test just above the cutoff. with captured_output("stderr") as stderr_g: try: g(traceback._RECURSIVE_CUTOFF + 1) except ValueError as exc: render_exc() else: self.fail("no error raised") result_g = ( f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' f' File "{__file__}", line {lineno_g+2}, in g\n' ' return g(count-1)\n' ' [Previous line repeated 1 more time]\n' f' File "{__file__}", line {lineno_g+3}, in g\n' ' raise ValueError\n' 'ValueError\n' ) tb_line = ( 'Traceback (most recent call last):\n' f' File "{__file__}", line {lineno_g+99}, in _check_recursive_traceback_display\n' ' g(traceback._RECURSIVE_CUTOFF + 1)\n' ) expected = (tb_line + result_g).splitlines() actual = stderr_g.getvalue().splitlines() self.assertEqual(actual, expected) def test_recursive_traceback_python(self): self._check_recursive_traceback_display(traceback.print_exc) @cpython_only def test_recursive_traceback_cpython_internal(self): from _testcapi import exception_print def render_exc(): exc_type, exc_value, exc_tb = sys.exc_info() exception_print(exc_value) self._check_recursive_traceback_display(render_exc) def test_format_stack(self): def fmt(): return traceback.format_stack() result = fmt() lineno = fmt.__code__.co_firstlineno self.assertEqual(result[-2:], [ ' File "%s", line %d, in test_format_stack\n' ' result = fmt()\n' % (__file__, lineno+2), ' File "%s", line %d, in fmt\n' ' return traceback.format_stack()\n' % (__file__, lineno+1), ]) @cpython_only def test_unhashable(self): from _testcapi import exception_print class UnhashableException(Exception): def __eq__(self, other): return True ex1 = UnhashableException('ex1') ex2 = UnhashableException('ex2') try: raise ex2 from ex1 except UnhashableException: try: raise ex1 except UnhashableException: exc_type, exc_val, exc_tb = sys.exc_info() with captured_output("stderr") as stderr_f: exception_print(exc_val) tb = stderr_f.getvalue().strip().splitlines() self.assertEqual(11, len(tb)) self.assertEqual(context_message.strip(), tb[5]) self.assertIn('UnhashableException: ex2', tb[3]) self.assertIn('UnhashableException: ex1', tb[10]) cause_message = ( "\nThe above exception was the direct cause " "of the following exception:\n\n") context_message = ( "\nDuring handling of the above exception, " "another exception occurred:\n\n") boundaries = re.compile( '(%s|%s)' % (re.escape(cause_message), re.escape(context_message))) class BaseExceptionReportingTests: def get_exception(self, exception_or_callable): if isinstance(exception_or_callable, Exception): return exception_or_callable try: exception_or_callable() except Exception as e: return e def zero_div(self): 1/0 # In zero_div def check_zero_div(self, msg): lines = msg.splitlines() self.assertTrue(lines[-3].startswith(' File')) self.assertIn('1/0 # In zero_div', lines[-2]) self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1]) def test_simple(self): try: 1/0 # Marker except ZeroDivisionError as _: e = _ lines = self.get_report(e).splitlines() self.assertEqual(len(lines), 4) self.assertTrue(lines[0].startswith('Traceback')) self.assertTrue(lines[1].startswith(' File')) self.assertIn('1/0 # Marker', lines[2]) self.assertTrue(lines[3].startswith('ZeroDivisionError')) def test_cause(self): def inner_raise(): try: self.zero_div() except ZeroDivisionError as e: raise KeyError from e def outer_raise(): inner_raise() # Marker blocks = boundaries.split(self.get_report(outer_raise)) self.assertEqual(len(blocks), 3) self.assertEqual(blocks[1], cause_message) self.check_zero_div(blocks[0]) self.assertIn('inner_raise() # Marker', blocks[2]) def test_context(self): def inner_raise(): try: self.zero_div() except ZeroDivisionError: raise KeyError def outer_raise(): inner_raise() # Marker blocks = boundaries.split(self.get_report(outer_raise)) self.assertEqual(len(blocks), 3) self.assertEqual(blocks[1], context_message) self.check_zero_div(blocks[0]) self.assertIn('inner_raise() # Marker', blocks[2]) def test_context_suppression(self): try: try: raise Exception except: raise ZeroDivisionError from None except ZeroDivisionError as _: e = _ lines = self.get_report(e).splitlines() self.assertEqual(len(lines), 4) self.assertTrue(lines[0].startswith('Traceback')) self.assertTrue(lines[1].startswith(' File')) self.assertIn('ZeroDivisionError from None', lines[2]) self.assertTrue(lines[3].startswith('ZeroDivisionError')) def test_cause_and_context(self): # When both a cause and a context are set, only the cause should be # displayed and the context should be muted. def inner_raise(): try: self.zero_div() except ZeroDivisionError as _e: e = _e try: xyzzy except NameError: raise KeyError from e def outer_raise(): inner_raise() # Marker blocks = boundaries.split(self.get_report(outer_raise)) self.assertEqual(len(blocks), 3) self.assertEqual(blocks[1], cause_message) self.check_zero_div(blocks[0]) self.assertIn('inner_raise() # Marker', blocks[2]) def test_cause_recursive(self): def inner_raise(): try: try: self.zero_div() except ZeroDivisionError as e: z = e raise KeyError from e except KeyError as e: raise z from e def outer_raise(): inner_raise() # Marker blocks = boundaries.split(self.get_report(outer_raise)) self.assertEqual(len(blocks), 3) self.assertEqual(blocks[1], cause_message) # The first block is the KeyError raised from the ZeroDivisionError self.assertIn('raise KeyError from e', blocks[0]) self.assertNotIn('1/0', blocks[0]) # The second block (apart from the boundary) is the ZeroDivisionError # re-raised from the KeyError self.assertIn('inner_raise() # Marker', blocks[2]) self.check_zero_div(blocks[2]) def test_syntax_error_offset_at_eol(self): # See #10186. def e(): raise SyntaxError('', ('', 0, 5, 'hello')) msg = self.get_report(e).splitlines() self.assertEqual(msg[-2], " ^") def e(): exec("x = 5 | 4 |") msg = self.get_report(e).splitlines() self.assertEqual(msg[-2], ' ^') def test_message_none(self): # A message that looks like "None" should not be treated specially err = self.get_report(Exception(None)) self.assertIn('Exception: None\n', err) err = self.get_report(Exception('None')) self.assertIn('Exception: None\n', err) err = self.get_report(Exception()) self.assertIn('Exception\n', err) err = self.get_report(Exception('')) self.assertIn('Exception\n', err) class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): # # This checks reporting through the 'traceback' module, with both # format_exception() and print_exception(). # def get_report(self, e): e = self.get_exception(e) s = ''.join( traceback.format_exception(type(e), e, e.__traceback__)) with captured_output("stderr") as sio: traceback.print_exception(type(e), e, e.__traceback__) self.assertEqual(sio.getvalue(), s) return s class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): # # This checks built-in reporting by the interpreter. # @cpython_only def get_report(self, e): from _testcapi import exception_print e = self.get_exception(e) with captured_output("stderr") as s: exception_print(e) return s.getvalue() class LimitTests(unittest.TestCase): ''' Tests for limit argument. It's enough to test extact_tb, extract_stack and format_exception ''' def last_raises1(self): raise Exception('Last raised') def last_raises2(self): self.last_raises1() def last_raises3(self): self.last_raises2() def last_raises4(self): self.last_raises3() def last_raises5(self): self.last_raises4() def last_returns_frame1(self): return sys._getframe() def last_returns_frame2(self): return self.last_returns_frame1() def last_returns_frame3(self): return self.last_returns_frame2() def last_returns_frame4(self): return self.last_returns_frame3() def last_returns_frame5(self): return self.last_returns_frame4() def test_extract_stack(self): frame = self.last_returns_frame5() def extract(**kwargs): return traceback.extract_stack(frame, **kwargs) def assertEqualExcept(actual, expected, ignore): self.assertEqual(actual[:ignore], expected[:ignore]) self.assertEqual(actual[ignore+1:], expected[ignore+1:]) self.assertEqual(len(actual), len(expected)) with support.swap_attr(sys, 'tracebacklimit', 1000): nolim = extract() self.assertGreater(len(nolim), 5) self.assertEqual(extract(limit=2), nolim[-2:]) assertEqualExcept(extract(limit=100), nolim[-100:], -5-1) self.assertEqual(extract(limit=-2), nolim[:2]) assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1) self.assertEqual(extract(limit=0), []) del sys.tracebacklimit assertEqualExcept(extract(), nolim, -5-1) sys.tracebacklimit = 2 self.assertEqual(extract(), nolim[-2:]) self.assertEqual(extract(limit=3), nolim[-3:]) self.assertEqual(extract(limit=-3), nolim[:3]) sys.tracebacklimit = 0 self.assertEqual(extract(), []) sys.tracebacklimit = -1 self.assertEqual(extract(), []) def test_extract_tb(self): try: self.last_raises5() except Exception: exc_type, exc_value, tb = sys.exc_info() def extract(**kwargs): return traceback.extract_tb(tb, **kwargs) with support.swap_attr(sys, 'tracebacklimit', 1000): nolim = extract() self.assertEqual(len(nolim), 5+1) self.assertEqual(extract(limit=2), nolim[:2]) self.assertEqual(extract(limit=10), nolim) self.assertEqual(extract(limit=-2), nolim[-2:]) self.assertEqual(extract(limit=-10), nolim) self.assertEqual(extract(limit=0), []) del sys.tracebacklimit self.assertEqual(extract(), nolim) sys.tracebacklimit = 2 self.assertEqual(extract(), nolim[:2]) self.assertEqual(extract(limit=3), nolim[:3]) self.assertEqual(extract(limit=-3), nolim[-3:]) sys.tracebacklimit = 0 self.assertEqual(extract(), []) sys.tracebacklimit = -1 self.assertEqual(extract(), []) def test_format_exception(self): try: self.last_raises5() except Exception: exc_type, exc_value, tb = sys.exc_info() # [1:-1] to exclude "Traceback (...)" header and # exception type and value def extract(**kwargs): return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1] with support.swap_attr(sys, 'tracebacklimit', 1000): nolim = extract() self.assertEqual(len(nolim), 5+1) self.assertEqual(extract(limit=2), nolim[:2]) self.assertEqual(extract(limit=10), nolim) self.assertEqual(extract(limit=-2), nolim[-2:]) self.assertEqual(extract(limit=-10), nolim) self.assertEqual(extract(limit=0), []) del sys.tracebacklimit self.assertEqual(extract(), nolim) sys.tracebacklimit = 2 self.assertEqual(extract(), nolim[:2]) self.assertEqual(extract(limit=3), nolim[:3]) self.assertEqual(extract(limit=-3), nolim[-3:]) sys.tracebacklimit = 0 self.assertEqual(extract(), []) sys.tracebacklimit = -1 self.assertEqual(extract(), []) class MiscTracebackCases(unittest.TestCase): # # Check non-printing functions in traceback module # def test_clear(self): def outer(): middle() def middle(): inner() def inner(): i = 1 1/0 try: outer() except: type_, value, tb = sys.exc_info() # Initial assertion: there's one local in the inner frame. inner_frame = tb.tb_next.tb_next.tb_next.tb_frame self.assertEqual(len(inner_frame.f_locals), 1) # Clear traceback frames traceback.clear_frames(tb) # Local variable dict should now be empty.
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_grammar.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_grammar.py
# Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. from test.support import check_syntax_error import inspect import unittest import sys # testing import * from sys import * # different import patterns to check that __annotations__ does not interfere # with import machinery import test.ann_module as ann_module import typing from collections import ChainMap from test import ann_module2 import test # These are shared with test_tokenize and other test modules. # # Note: since several test cases filter out floats by looking for "e" and ".", # don't add hexadecimal literals that contain "e" or "E". VALID_UNDERSCORE_LITERALS = [ '0_0_0', '4_2', '1_0000_0000', '0b1001_0100', '0xffff_ffff', '0o5_7_7', '1_00_00.5', '1_00_00.5e5', '1_00_00e5_1', '1e1_0', '.1_4', '.1_4e1', '0b_0', '0x_f', '0o_5', '1_00_00j', '1_00_00.5j', '1_00_00e5_1j', '.1_4j', '(1_2.5+3_3j)', '(.5_6j)', ] INVALID_UNDERSCORE_LITERALS = [ # Trailing underscores: '0_', '42_', '1.4j_', '0x_', '0b1_', '0xf_', '0o5_', '0 if 1_Else 1', # Underscores in the base selector: '0_b0', '0_xf', '0_o5', # Old-style octal, still disallowed: '0_7', '09_99', # Multiple consecutive underscores: '4_______2', '0.1__4', '0.1__4j', '0b1001__0100', '0xffff__ffff', '0x___', '0o5__77', '1e1__0', '1e1__0j', # Underscore right before a dot: '1_.4', '1_.4j', # Underscore right after a dot: '1._4', '1._4j', '._5', '._5j', # Underscore right after a sign: '1.0e+_1', '1.0e+_1j', # Underscore right before j: '1.4_j', '1.4e5_j', # Underscore right before e: '1_e1', '1.4_e1', '1.4_e1j', # Underscore right after e: '1e_1', '1.4e_1', '1.4e_1j', # Complex cases with parens: '(1+1.5_j_)', '(1+1.5_j)', ] class TokenTests(unittest.TestCase): def test_backslash(self): # Backslash means line continuation: x = 1 \ + 1 self.assertEqual(x, 2, 'backslash for line continuation') # Backslash does not means continuation in comments :\ x = 0 self.assertEqual(x, 0, 'backslash ending comment') def test_plain_integers(self): self.assertEqual(type(000), type(0)) self.assertEqual(0xff, 255) self.assertEqual(0o377, 255) self.assertEqual(2147483647, 0o17777777777) self.assertEqual(0b1001, 9) # "0x" is not a valid literal self.assertRaises(SyntaxError, eval, "0x") from sys import maxsize if maxsize == 2147483647: self.assertEqual(-2147483647-1, -0o20000000000) # XXX -2147483648 self.assertTrue(0o37777777777 > 0) self.assertTrue(0xffffffff > 0) self.assertTrue(0b1111111111111111111111111111111 > 0) for s in ('2147483648', '0o40000000000', '0x100000000', '0b10000000000000000000000000000000'): try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) elif maxsize == 9223372036854775807: self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000) self.assertTrue(0o1777777777777777777777 > 0) self.assertTrue(0xffffffffffffffff > 0) self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0) for s in '9223372036854775808', '0o2000000000000000000000', \ '0x10000000000000000', \ '0b100000000000000000000000000000000000000000000000000000000000000': try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) else: self.fail('Weird maxsize value %r' % maxsize) def test_long_integers(self): x = 0 x = 0xffffffffffffffff x = 0Xffffffffffffffff x = 0o77777777777777777 x = 0O77777777777777777 x = 123456789012345678901234567890 x = 0b100000000000000000000000000000000000000000000000000000000000000000000 x = 0B111111111111111111111111111111111111111111111111111111111111111111111 def test_floats(self): x = 3.14 x = 314. x = 0.314 # XXX x = 000.314 x = .314 x = 3e14 x = 3E14 x = 3e-14 x = 3e+14 x = 3.e14 x = .3e14 x = 3.1e4 def test_float_exponent_tokenization(self): # See issue 21642. self.assertEqual(1 if 1else 0, 1) self.assertEqual(1 if 0else 0, 0) self.assertRaises(SyntaxError, eval, "0 if 1Else 0") def test_underscore_literals(self): for lit in VALID_UNDERSCORE_LITERALS: self.assertEqual(eval(lit), eval(lit.replace('_', ''))) for lit in INVALID_UNDERSCORE_LITERALS: self.assertRaises(SyntaxError, eval, lit) # Sanity check: no literal begins with an underscore self.assertRaises(NameError, eval, "_0") def test_string_literals(self): x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' self.assertTrue(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' self.assertTrue(len(x) == 24 and x == y) x = """ The "quick" brown fox jumps over the 'lazy' dog. """ y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' self.assertEqual(x, y) y = ''' The "quick" brown fox jumps over the 'lazy' dog. ''' self.assertEqual(x, y) y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ " self.assertEqual(x, y) y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ ' self.assertEqual(x, y) def test_ellipsis(self): x = ... self.assertTrue(x is Ellipsis) self.assertRaises(SyntaxError, eval, ".. .") def test_eof_error(self): samples = ("def foo(", "\ndef foo(", "def foo(\n") for s in samples: with self.assertRaises(SyntaxError) as cm: compile(s, "<test>", "exec") self.assertIn("unexpected EOF", str(cm.exception)) var_annot_global: int # a global annotated is necessary for test_var_annot # custom namespace for testing __annotations__ class CNS: def __init__(self): self._dct = {} def __setitem__(self, item, value): self._dct[item.lower()] = value def __getitem__(self, item): return self._dct[item] class GrammarTests(unittest.TestCase): # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE # XXX can't test in a script -- this rule is only used when interactive # file_input: (NEWLINE | stmt)* ENDMARKER # Being tested as this very moment this very module # expr_input: testlist NEWLINE # XXX Hard to test -- used only in calls to input() def test_eval_input(self): # testlist ENDMARKER x = eval('1, 0 or 1') def test_var_annot_basics(self): # all these should be allowed var1: int = 5 var2: [int, str] my_lst = [42] def one(): return 1 int.new_attr: int [list][0]: type my_lst[one()-1]: int = 5 self.assertEqual(my_lst, [5]) def test_var_annot_syntax_errors(self): # parser pass check_syntax_error(self, "def f: int") check_syntax_error(self, "x: int: str") check_syntax_error(self, "def f():\n" " nonlocal x: int\n") # AST pass check_syntax_error(self, "[x, 0]: int\n") check_syntax_error(self, "f(): int\n") check_syntax_error(self, "(x,): int") check_syntax_error(self, "def f():\n" " (x, y): int = (1, 2)\n") # symtable pass check_syntax_error(self, "def f():\n" " x: int\n" " global x\n") check_syntax_error(self, "def f():\n" " global x\n" " x: int\n") def test_var_annot_basic_semantics(self): # execution order with self.assertRaises(ZeroDivisionError): no_name[does_not_exist]: no_name_again = 1/0 with self.assertRaises(NameError): no_name[does_not_exist]: 1/0 = 0 global var_annot_global # function semantics def f(): st: str = "Hello" a.b: int = (1, 2) return st self.assertEqual(f.__annotations__, {}) def f_OK(): x: 1/0 f_OK() def fbad(): x: int print(x) with self.assertRaises(UnboundLocalError): fbad() def f2bad(): (no_such_global): int print(no_such_global) try: f2bad() except Exception as e: self.assertIs(type(e), NameError) # class semantics class C: __foo: int s: str = "attr" z = 2 def __init__(self, x): self.x: int = x self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str}) with self.assertRaises(NameError): class CBad: no_such_name_defined.attr: int = 0 with self.assertRaises(NameError): class Cbad2(C): x: int x.y: list = [] def test_var_annot_metaclass_semantics(self): class CMeta(type): @classmethod def __prepare__(metacls, name, bases, **kwds): return {'__annotations__': CNS()} class CC(metaclass=CMeta): XX: 'ANNOT' self.assertEqual(CC.__annotations__['xx'], 'ANNOT') def test_var_annot_module_semantics(self): with self.assertRaises(AttributeError): print(test.__annotations__) self.assertEqual(ann_module.__annotations__, {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]}) self.assertEqual(ann_module.M.__annotations__, {'123': 123, 'o': type}) self.assertEqual(ann_module2.__annotations__, {}) def test_var_annot_in_module(self): # check that functions fail the same way when executed # outside of module where they were defined from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann with self.assertRaises(NameError): f_bad_ann() with self.assertRaises(NameError): g_bad_ann() with self.assertRaises(NameError): D_bad_ann(5) def test_var_annot_simple_exec(self): gns = {}; lns= {} exec("'docstring'\n" "__annotations__[1] = 2\n" "x: int = 5\n", gns, lns) self.assertEqual(lns["__annotations__"], {1: 2, 'x': int}) with self.assertRaises(KeyError): gns['__annotations__'] def test_var_annot_custom_maps(self): # tests with custom locals() and __annotations__ ns = {'__annotations__': CNS()} exec('X: int; Z: str = "Z"; (w): complex = 1j', ns) self.assertEqual(ns['__annotations__']['x'], int) self.assertEqual(ns['__annotations__']['z'], str) with self.assertRaises(KeyError): ns['__annotations__']['w'] nonloc_ns = {} class CNS2: def __init__(self): self._dct = {} def __setitem__(self, item, value): nonlocal nonloc_ns self._dct[item] = value nonloc_ns[item] = value def __getitem__(self, item): return self._dct[item] exec('x: int = 1', {}, CNS2()) self.assertEqual(nonloc_ns['__annotations__']['x'], int) def test_var_annot_refleak(self): # complex case: custom locals plus custom __annotations__ # this was causing refleak cns = CNS() nonloc_ns = {'__annotations__': cns} class CNS2: def __init__(self): self._dct = {'__annotations__': cns} def __setitem__(self, item, value): nonlocal nonloc_ns self._dct[item] = value nonloc_ns[item] = value def __getitem__(self, item): return self._dct[item] exec('X: str', {}, CNS2()) self.assertEqual(nonloc_ns['__annotations__']['x'], str) def test_funcdef(self): ### [decorators] 'def' NAME parameters ['->' test] ':' suite ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE ### decorators: decorator+ ### parameters: '(' [typedargslist] ')' ### typedargslist: ((tfpdef ['=' test] ',')* ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) ### tfpdef: NAME [':' test] ### varargslist: ((vfpdef ['=' test] ',')* ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) ### vfpdef: NAME def f1(): pass f1() f1(*()) f1(*(), **{}) def f2(one_argument): pass def f3(two, arguments): pass self.assertEqual(f2.__code__.co_varnames, ('one_argument',)) self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments')) def a1(one_arg,): pass def a2(two, args,): pass def v0(*rest): pass def v1(a, *rest): pass def v2(a, b, *rest): pass f1() f2(1) f2(1,) f3(1, 2) f3(1, 2,) v0() v0(1) v0(1,) v0(1,2) v0(1,2,3,4,5,6,7,8,9,0) v1(1) v1(1,) v1(1,2) v1(1,2,3) v1(1,2,3,4,5,6,7,8,9,0) v2(1,2) v2(1,2,3) v2(1,2,3,4) v2(1,2,3,4,5,6,7,8,9,0) def d01(a=1): pass d01() d01(1) d01(*(1,)) d01(*[] or [2]) d01(*() or (), *{} and (), **() or {}) d01(**{'a':2}) d01(**{'a':2} or {}) def d11(a, b=1): pass d11(1) d11(1, 2) d11(1, **{'b':2}) def d21(a, b, c=1): pass d21(1, 2) d21(1, 2, 3) d21(*(1, 2, 3)) d21(1, *(2, 3)) d21(1, 2, *(3,)) d21(1, 2, **{'c':3}) def d02(a=1, b=2): pass d02() d02(1) d02(1, 2) d02(*(1, 2)) d02(1, *(2,)) d02(1, **{'b':2}) d02(**{'a': 1, 'b': 2}) def d12(a, b=1, c=2): pass d12(1) d12(1, 2) d12(1, 2, 3) def d22(a, b, c=1, d=2): pass d22(1, 2) d22(1, 2, 3) d22(1, 2, 3, 4) def d01v(a=1, *rest): pass d01v() d01v(1) d01v(1, 2) d01v(*(1, 2, 3, 4)) d01v(*(1,)) d01v(**{'a':2}) def d11v(a, b=1, *rest): pass d11v(1) d11v(1, 2) d11v(1, 2, 3) def d21v(a, b, c=1, *rest): pass d21v(1, 2) d21v(1, 2, 3) d21v(1, 2, 3, 4) d21v(*(1, 2, 3, 4)) d21v(1, 2, **{'c': 3}) def d02v(a=1, b=2, *rest): pass d02v() d02v(1) d02v(1, 2) d02v(1, 2, 3) d02v(1, *(2, 3, 4)) d02v(**{'a': 1, 'b': 2}) def d12v(a, b=1, c=2, *rest): pass d12v(1) d12v(1, 2) d12v(1, 2, 3) d12v(1, 2, 3, 4) d12v(*(1, 2, 3, 4)) d12v(1, 2, *(3, 4, 5)) d12v(1, *(2,), **{'c': 3}) def d22v(a, b, c=1, d=2, *rest): pass d22v(1, 2) d22v(1, 2, 3) d22v(1, 2, 3, 4) d22v(1, 2, 3, 4, 5) d22v(*(1, 2, 3, 4)) d22v(1, 2, *(3, 4, 5)) d22v(1, *(2, 3), **{'d': 4}) # keyword argument type tests try: str('x', **{b'foo':1 }) except TypeError: pass else: self.fail('Bytes should not work as keyword argument names') # keyword only argument tests def pos0key1(*, key): return key pos0key1(key=100) def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 pos2key2(1, 2, k1=100) pos2key2(1, 2, k1=100, k2=200) pos2key2(1, 2, k2=100, k1=200) def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) self.assertRaises(SyntaxError, eval, "def f(*): pass") self.assertRaises(SyntaxError, eval, "def f(*,): pass") self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass") # keyword arguments after *arglist def f(*args, **kwargs): return args, kwargs self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), {'x':2, 'y':5})) self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {})) self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}), ((), {'eggs':'scrambled', 'spam':'fried'})) self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}), ((), {'eggs':'scrambled', 'spam':'fried'})) # Check ast errors in *args and *kwargs check_syntax_error(self, "f(*g(1=2))") check_syntax_error(self, "f(**g(1=2))") # argument annotation tests def f(x) -> list: pass self.assertEqual(f.__annotations__, {'return': list}) def f(x: int): pass self.assertEqual(f.__annotations__, {'x': int}) def f(*x: str): pass self.assertEqual(f.__annotations__, {'x': str}) def f(**x: float): pass self.assertEqual(f.__annotations__, {'x': float}) def f(x, y: 1+2): pass self.assertEqual(f.__annotations__, {'y': 3}) def f(a, b: 1, c: 2, d): pass self.assertEqual(f.__annotations__, {'b': 1, 'c': 2}) def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass self.assertEqual(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6}) def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10, **k: 11) -> 12: pass self.assertEqual(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, 'k': 11, 'return': 12}) # Check for issue #20625 -- annotations mangling class Spam: def f(self, *, __kw: 1): pass class Ham(Spam): pass self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1}) self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1}) # Check for SF Bug #1697248 - mixing decorators and a return annotation def null(x): return x @null def f(x) -> list: pass self.assertEqual(f.__annotations__, {'return': list}) # test closures with a variety of opargs closure = 1 def f(): return closure def f(x=1): return closure def f(*, k=1): return closure def f() -> int: return closure # Check trailing commas are permitted in funcdef argument list def f(a,): pass def f(*args,): pass def f(**kwds,): pass def f(a, *args,): pass def f(a, **kwds,): pass def f(*args, b,): pass def f(*, b,): pass def f(*args, **kwds,): pass def f(a, *args, b,): pass def f(a, *, b,): pass def f(a, *args, **kwds,): pass def f(*args, b, **kwds,): pass def f(*, b, **kwds,): pass def f(a, *args, b, **kwds,): pass def f(a, *, b, **kwds,): pass def test_lambdef(self): ### lambdef: 'lambda' [varargslist] ':' test l1 = lambda : 0 self.assertEqual(l1(), 0) l2 = lambda : a[d] # XXX just testing the expression l3 = lambda : [2 < x for x in [-1, 3, 0]] self.assertEqual(l3(), [0, 1, 0]) l4 = lambda x = lambda y = lambda z=1 : z : y() : x() self.assertEqual(l4(), 1) l5 = lambda x, y, z=2: x + y + z self.assertEqual(l5(1, 2), 5) self.assertEqual(l5(1, 2, 3), 6) check_syntax_error(self, "lambda x: x = 2") check_syntax_error(self, "lambda (None,): None") l6 = lambda x, y, *, k=20: x+y+k self.assertEqual(l6(1,2), 1+2+20) self.assertEqual(l6(1,2,k=10), 1+2+10) # check that trailing commas are permitted l10 = lambda a,: 0 l11 = lambda *args,: 0 l12 = lambda **kwds,: 0 l13 = lambda a, *args,: 0 l14 = lambda a, **kwds,: 0 l15 = lambda *args, b,: 0 l16 = lambda *, b,: 0 l17 = lambda *args, **kwds,: 0 l18 = lambda a, *args, b,: 0 l19 = lambda a, *, b,: 0 l20 = lambda a, *args, **kwds,: 0 l21 = lambda *args, b, **kwds,: 0 l22 = lambda *, b, **kwds,: 0 l23 = lambda a, *args, b, **kwds,: 0 l24 = lambda a, *, b, **kwds,: 0 ### stmt: simple_stmt | compound_stmt # Tested below def test_simple_stmt(self): ### simple_stmt: small_stmt (';' small_stmt)* [';'] x = 1; pass; del x def foo(): # verify statements that end with semi-colons x = 1; pass; del x; foo() ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt # Tested below def test_expr_stmt(self): # (exprlist '=')* exprlist 1 1, 2, 3 x = 1 x = 1, 2, 3 x = y = z = 1, 2, 3 x, y, z = 1, 2, 3 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) check_syntax_error(self, "x + 1 = 1") check_syntax_error(self, "a + 1 = b + 2") # Check the heuristic for print & exec covers significant cases # As well as placing some limits on false positives def test_former_statements_refer_to_builtins(self): keywords = "print", "exec" # Cases where we want the custom error cases = [ "{} foo", "{} {{1:foo}}", "if 1: {} foo", "if 1: {} {{1:foo}}", "if 1:\n {} foo", "if 1:\n {} {{1:foo}}", ] for keyword in keywords: custom_msg = "call to '{}'".format(keyword) for case in cases: source = case.format(keyword) with self.subTest(source=source): with self.assertRaisesRegex(SyntaxError, custom_msg): exec(source) source = source.replace("foo", "(foo.)") with self.subTest(source=source): with self.assertRaisesRegex(SyntaxError, "invalid syntax"): exec(source) def test_del_stmt(self): # 'del' exprlist abc = [1,2,3] x, y, z = abc xyz = x, y, z del abc del x, y, (z, xyz) def test_pass_stmt(self): # 'pass' pass # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt # Tested below def test_break_stmt(self): # 'break' while 1: break def test_continue_stmt(self): # 'continue' i = 1 while i: i = 0; continue msg = "" while not msg: msg = "ok" try: continue msg = "continue failed to continue inside try" except: msg = "continue inside try called except block" if msg != "ok": self.fail(msg) msg = "" while not msg: msg = "finally block not called" try: continue finally: msg = "ok" if msg != "ok": self.fail(msg) def test_break_continue_loop(self): # This test warrants an explanation. It is a test specifically for SF bugs # #463359 and #462937. The bug is that a 'break' statement executed or # exception raised inside a try/except inside a loop, *after* a continue # statement has been executed in that loop, will cause the wrong number of # arguments to be popped off the stack and the instruction pointer reset to # a very small number (usually 0.) Because of this, the following test # *must* written as a function, and the tracking vars *must* be function # arguments with default values. Otherwise, the test will loop and loop. def test_inner(extra_burning_oil = 1, count=0): big_hippo = 2 while big_hippo: count += 1 try: if extra_burning_oil and big_hippo == 1: extra_burning_oil -= 1 break big_hippo -= 1 continue except: raise if count > 2 or big_hippo != 1: self.fail("continue then break in try/except in loop broken!") test_inner() def test_return(self): # 'return' [testlist] def g1(): return def g2(): return 1 g1() x = g2() check_syntax_error(self, "class foo:return 1") def test_break_in_finally(self): count = 0 while count < 2: count += 1 try: pass finally: break self.assertEqual(count, 1) count = 0 while count < 2: count += 1 try: continue finally: break self.assertEqual(count, 1) count = 0 while count < 2: count += 1 try: 1/0 finally: break self.assertEqual(count, 1) for count in [0, 1]: self.assertEqual(count, 0) try: pass finally: break self.assertEqual(count, 0) for count in [0, 1]: self.assertEqual(count, 0) try: continue finally: break self.assertEqual(count, 0) for count in [0, 1]: self.assertEqual(count, 0) try: 1/0 finally: break self.assertEqual(count, 0) def test_return_in_finally(self): def g1(): try: pass finally: return 1 self.assertEqual(g1(), 1) def g2(): try: return 2 finally: return 3 self.assertEqual(g2(), 3) def g3(): try: 1/0 finally: return 4 self.assertEqual(g3(), 4) def test_yield(self): # Allowed as standalone statement def g(): yield 1 def g(): yield from () # Allowed as RHS of assignment def g(): x = yield 1 def g(): x = yield from () # Ordinary yield accepts implicit tuples def g(): yield 1, 1 def g(): x = yield 1, 1 # 'yield from' does not check_syntax_error(self, "def g(): yield from (), 1") check_syntax_error(self, "def g(): x = yield from (), 1") # Requires parentheses as subexpression def g(): 1, (yield 1) def g(): 1, (yield from ()) check_syntax_error(self, "def g(): 1, yield 1") check_syntax_error(self, "def g(): 1, yield from ()") # Requires parentheses as call argument def g(): f((yield 1)) def g(): f((yield 1), 1) def g(): f((yield from ())) def g(): f((yield from ()), 1) check_syntax_error(self, "def g(): f(yield 1)") check_syntax_error(self, "def g(): f(yield 1, 1)") check_syntax_error(self, "def g(): f(yield from ())") check_syntax_error(self, "def g(): f(yield from (), 1)") # Not allowed at top level check_syntax_error(self, "yield") check_syntax_error(self, "yield from") # Not allowed at class scope check_syntax_error(self, "class foo:yield 1") check_syntax_error(self, "class foo:yield from ()") # Check annotation refleak on SyntaxError check_syntax_error(self, "def g(a:(yield)): pass") def test_yield_in_comprehensions(self): # Check yield in comprehensions def g(): [x for x in [(yield 1)]] def g(): [x for x in [(yield from ())]] def check(code, warntext): with self.assertWarnsRegex(DeprecationWarning, warntext): compile(code, '<test string>', 'exec') import warnings with warnings.catch_warnings(): warnings.filterwarnings('error', category=DeprecationWarning) with self.assertRaisesRegex(SyntaxError, warntext): compile(code, '<test string>', 'exec') check("def g(): [(yield x) for x in ()]", "'yield' inside list comprehension") check("def g(): [x for x in () if not (yield x)]", "'yield' inside list comprehension") check("def g(): [y for x in () for y in [(yield x)]]", "'yield' inside list comprehension") check("def g(): {(yield x) for x in ()}", "'yield' inside set comprehension") check("def g(): {(yield x): x for x in ()}", "'yield' inside dict comprehension") check("def g(): {x: (yield x) for x in ()}", "'yield' inside dict comprehension") check("def g(): ((yield x) for x in ())", "'yield' inside generator expression") check("def g(): [(yield from x) for x in ()]", "'yield' inside list comprehension") check("class C: [(yield x) for x in ()]", "'yield' inside list comprehension") check("[(yield x) for x in ()]", "'yield' inside list comprehension") def test_raise(self): # 'raise' test [',' test] try: raise RuntimeError('just testing') except RuntimeError: pass try: raise KeyboardInterrupt except KeyboardInterrupt: pass def test_import(self): # 'import' dotted_as_names import sys import time, sys # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) from time import time from time import (time) # not testable inside a function, but already done at top of the module # from sys import * from sys import path, argv from sys import (path, argv) from sys import (path, argv,) def test_global(self): # 'global' NAME (',' NAME)* global a global a, b global one, two, three, four, five, six, seven, eight, nine, ten def test_nonlocal(self): # 'nonlocal' NAME (',' NAME)* x = 0 y = 0 def f(): nonlocal x nonlocal x, y def test_assert(self): # assertTruestmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x assert 1, lambda x:x+1 try: assert True except AssertionError as e: self.fail("'assert True' should not have raised an AssertionError") try: assert True, 'this should always pass' except AssertionError as e: self.fail("'assert True, msg' should not have " "raised an AssertionError") # these tests fail if python is run with -O, so check __debug__ @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") def testAssert2(self): try: assert 0, "msg" except AssertionError as e: self.assertEqual(e.args[0], "msg") else:
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_setcomps.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_setcomps.py
doctests = """ ########### Tests mostly copied from test_listcomps.py ############ Test simple loop with conditional >>> sum({i*i for i in range(100) if i&1 == 1}) 166650 Test simple case >>> {2*y + x + 1 for x in (0,) for y in (1,)} {3} Test simple nesting >>> list(sorted({(i,j) for i in range(3) for j in range(4)})) [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)] Test nesting with the inner expression dependent on the outer >>> list(sorted({(i,j) for i in range(4) for j in range(i)})) [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] Make sure the induction variable is not exposed >>> i = 20 >>> sum({i*i for i in range(100)}) 328350 >>> i 20 Verify that syntax error's are raised for setcomps used as lvalues >>> {y for y in (1,2)} = 10 # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... SyntaxError: ... >>> {y for y in (1,2)} += 10 # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... SyntaxError: ... Make a nested set comprehension that acts like set(range()) >>> def srange(n): ... return {i for i in range(n)} >>> list(sorted(srange(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Same again, only as a lambda expression instead of a function definition >>> lrange = lambda n: {i for i in range(n)} >>> list(sorted(lrange(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Generators can call other generators: >>> def grange(n): ... for x in {i for i in range(n)}: ... yield x >>> list(sorted(grange(5))) [0, 1, 2, 3, 4] Make sure that None is a valid return value >>> {None for i in range(10)} {None} ########### Tests for various scoping corner cases ############ Return lambdas that use the iteration variable as a default argument >>> items = {(lambda i=i: i) for i in range(5)} >>> {x() for x in items} == set(range(5)) True Same again, only this time as a closure variable >>> items = {(lambda: i) for i in range(5)} >>> {x() for x in items} {4} Another way to test that the iteration variable is local to the list comp >>> items = {(lambda: i) for i in range(5)} >>> i = 20 >>> {x() for x in items} {4} And confirm that a closure can jump over the list comp scope >>> items = {(lambda: y) for i in range(5)} >>> y = 2 >>> {x() for x in items} {2} We also repeat each of the above scoping tests inside a function >>> def test_func(): ... items = {(lambda i=i: i) for i in range(5)} ... return {x() for x in items} >>> test_func() == set(range(5)) True >>> def test_func(): ... items = {(lambda: i) for i in range(5)} ... return {x() for x in items} >>> test_func() {4} >>> def test_func(): ... items = {(lambda: i) for i in range(5)} ... i = 20 ... return {x() for x in items} >>> test_func() {4} >>> def test_func(): ... items = {(lambda: y) for i in range(5)} ... y = 2 ... return {x() for x in items} >>> test_func() {2} """ __test__ = {'doctests' : doctests} def test_main(verbose=None): import sys from test import support from test import test_setcomps support.run_doctest(test_setcomps, verbose) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in range(len(counts)): support.run_doctest(test_setcomps, verbose) gc.collect() counts[i] = sys.gettotalrefcount() print(counts) if __name__ == "__main__": test_main(verbose=True)
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_kr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_kr.py
# # test_codecencodings_kr.py # Codec encoding tests for ROK encodings. # from test import multibytecodec_support import unittest class Test_CP949(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'cp949' tstring = multibytecodec_support.load_teststring('cp949') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\uc894"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\uc894\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\uc894"), ) class Test_EUCKR(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'euc_kr' tstring = multibytecodec_support.load_teststring('euc_kr') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", 'abc\ufffd\ufffd\uc894'), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\uc894\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\uc894"), # composed make-up sequence errors (b"\xa4\xd4", "strict", None), (b"\xa4\xd4\xa4", "strict", None), (b"\xa4\xd4\xa4\xb6", "strict", None), (b"\xa4\xd4\xa4\xb6\xa4", "strict", None), (b"\xa4\xd4\xa4\xb6\xa4\xd0", "strict", None), (b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4", "strict", None), (b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4", "strict", "\uc4d4"), (b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4x", "strict", "\uc4d4x"), (b"a\xa4\xd4\xa4\xb6\xa4", "replace", 'a\ufffd'), (b"\xa4\xd4\xa3\xb6\xa4\xd0\xa4\xd4", "strict", None), (b"\xa4\xd4\xa4\xb6\xa3\xd0\xa4\xd4", "strict", None), (b"\xa4\xd4\xa4\xb6\xa4\xd0\xa3\xd4", "strict", None), (b"\xa4\xd4\xa4\xff\xa4\xd0\xa4\xd4", "replace", '\ufffd\u6e21\ufffd\u3160\ufffd'), (b"\xa4\xd4\xa4\xb6\xa4\xff\xa4\xd4", "replace", '\ufffd\u6e21\ub544\ufffd\ufffd'), (b"\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xff", "replace", '\ufffd\u6e21\ub544\u572d\ufffd'), (b"\xa4\xd4\xff\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4", "replace", '\ufffd\ufffd\ufffd\uc4d4'), (b"\xc1\xc4", "strict", "\uc894"), ) class Test_JOHAB(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'johab' tstring = multibytecodec_support.load_teststring('johab') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\ucd27"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\ucd27\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\ucd27"), (b"\xD8abc", "replace", "\uFFFDabc"), (b"\xD8\xFFabc", "replace", "\uFFFD\uFFFDabc"), (b"\x84bxy", "replace", "\uFFFDbxy"), (b"\x8CBxy", "replace", "\uFFFDBxy"), ) 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_typechecks.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typechecks.py
"""Unit tests for __instancecheck__ and __subclasscheck__.""" import unittest class ABC(type): def __instancecheck__(cls, inst): """Implement isinstance(inst, cls).""" return any(cls.__subclasscheck__(c) for c in {type(inst), inst.__class__}) def __subclasscheck__(cls, sub): """Implement issubclass(sub, cls).""" candidates = cls.__dict__.get("__subclass__", set()) | {cls} return any(c in candidates for c in sub.mro()) class Integer(metaclass=ABC): __subclass__ = {int} class SubInt(Integer): pass class TypeChecksTest(unittest.TestCase): def testIsSubclassInternal(self): self.assertEqual(Integer.__subclasscheck__(int), True) self.assertEqual(Integer.__subclasscheck__(float), False) def testIsSubclassBuiltin(self): self.assertEqual(issubclass(int, Integer), True) self.assertEqual(issubclass(int, (Integer,)), True) self.assertEqual(issubclass(float, Integer), False) self.assertEqual(issubclass(float, (Integer,)), False) def testIsInstanceBuiltin(self): self.assertEqual(isinstance(42, Integer), True) self.assertEqual(isinstance(42, (Integer,)), True) self.assertEqual(isinstance(3.14, Integer), False) self.assertEqual(isinstance(3.14, (Integer,)), False) def testIsInstanceActual(self): self.assertEqual(isinstance(Integer(), Integer), True) self.assertEqual(isinstance(Integer(), (Integer,)), True) def testIsSubclassActual(self): self.assertEqual(issubclass(Integer, Integer), True) self.assertEqual(issubclass(Integer, (Integer,)), True) def testSubclassBehavior(self): self.assertEqual(issubclass(SubInt, Integer), True) self.assertEqual(issubclass(SubInt, (Integer,)), True) self.assertEqual(issubclass(SubInt, SubInt), True) self.assertEqual(issubclass(SubInt, (SubInt,)), True) self.assertEqual(issubclass(Integer, SubInt), False) self.assertEqual(issubclass(Integer, (SubInt,)), False) self.assertEqual(issubclass(int, SubInt), False) self.assertEqual(issubclass(int, (SubInt,)), False) self.assertEqual(isinstance(SubInt(), Integer), True) self.assertEqual(isinstance(SubInt(), (Integer,)), True) self.assertEqual(isinstance(SubInt(), SubInt), True) self.assertEqual(isinstance(SubInt(), (SubInt,)), True) self.assertEqual(isinstance(42, SubInt), False) self.assertEqual(isinstance(42, (SubInt,)), False) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_stat.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_stat.py
import unittest import os import sys from test.support import TESTFN, import_fresh_module c_stat = import_fresh_module('stat', fresh=['_stat']) py_stat = import_fresh_module('stat', blocked=['_stat']) class TestFilemode: statmod = None file_flags = {'SF_APPEND', 'SF_ARCHIVED', 'SF_IMMUTABLE', 'SF_NOUNLINK', 'SF_SNAPSHOT', 'UF_APPEND', 'UF_COMPRESSED', 'UF_HIDDEN', 'UF_IMMUTABLE', 'UF_NODUMP', 'UF_NOUNLINK', 'UF_OPAQUE'} formats = {'S_IFBLK', 'S_IFCHR', 'S_IFDIR', 'S_IFIFO', 'S_IFLNK', 'S_IFREG', 'S_IFSOCK', 'S_IFDOOR', 'S_IFPORT', 'S_IFWHT'} format_funcs = {'S_ISBLK', 'S_ISCHR', 'S_ISDIR', 'S_ISFIFO', 'S_ISLNK', 'S_ISREG', 'S_ISSOCK', 'S_ISDOOR', 'S_ISPORT', 'S_ISWHT'} stat_struct = { 'ST_MODE': 0, 'ST_INO': 1, 'ST_DEV': 2, 'ST_NLINK': 3, 'ST_UID': 4, 'ST_GID': 5, 'ST_SIZE': 6, 'ST_ATIME': 7, 'ST_MTIME': 8, 'ST_CTIME': 9} # permission bit value are defined by POSIX permission_bits = { 'S_ISUID': 0o4000, 'S_ISGID': 0o2000, 'S_ENFMT': 0o2000, 'S_ISVTX': 0o1000, 'S_IRWXU': 0o700, 'S_IRUSR': 0o400, 'S_IREAD': 0o400, 'S_IWUSR': 0o200, 'S_IWRITE': 0o200, 'S_IXUSR': 0o100, 'S_IEXEC': 0o100, 'S_IRWXG': 0o070, 'S_IRGRP': 0o040, 'S_IWGRP': 0o020, 'S_IXGRP': 0o010, 'S_IRWXO': 0o007, 'S_IROTH': 0o004, 'S_IWOTH': 0o002, 'S_IXOTH': 0o001} # defined by the Windows API documentation file_attributes = { 'FILE_ATTRIBUTE_ARCHIVE': 32, 'FILE_ATTRIBUTE_COMPRESSED': 2048, 'FILE_ATTRIBUTE_DEVICE': 64, 'FILE_ATTRIBUTE_DIRECTORY': 16, 'FILE_ATTRIBUTE_ENCRYPTED': 16384, 'FILE_ATTRIBUTE_HIDDEN': 2, 'FILE_ATTRIBUTE_INTEGRITY_STREAM': 32768, 'FILE_ATTRIBUTE_NORMAL': 128, 'FILE_ATTRIBUTE_NOT_CONTENT_INDEXED': 8192, 'FILE_ATTRIBUTE_NO_SCRUB_DATA': 131072, 'FILE_ATTRIBUTE_OFFLINE': 4096, 'FILE_ATTRIBUTE_READONLY': 1, 'FILE_ATTRIBUTE_REPARSE_POINT': 1024, 'FILE_ATTRIBUTE_SPARSE_FILE': 512, 'FILE_ATTRIBUTE_SYSTEM': 4, 'FILE_ATTRIBUTE_TEMPORARY': 256, 'FILE_ATTRIBUTE_VIRTUAL': 65536} def setUp(self): try: os.remove(TESTFN) except OSError: try: os.rmdir(TESTFN) except OSError: pass tearDown = setUp def get_mode(self, fname=TESTFN, lstat=True): if lstat: st_mode = os.lstat(fname).st_mode else: st_mode = os.stat(fname).st_mode modestr = self.statmod.filemode(st_mode) return st_mode, modestr def assertS_IS(self, name, mode): # test format, lstrip is for S_IFIFO fmt = getattr(self.statmod, "S_IF" + name.lstrip("F")) self.assertEqual(self.statmod.S_IFMT(mode), fmt) # test that just one function returns true testname = "S_IS" + name for funcname in self.format_funcs: func = getattr(self.statmod, funcname, None) if func is None: if funcname == testname: raise ValueError(funcname) continue if funcname == testname: self.assertTrue(func(mode)) else: self.assertFalse(func(mode)) def test_mode(self): with open(TESTFN, 'w'): pass if os.name == 'posix': os.chmod(TESTFN, 0o700) st_mode, modestr = self.get_mode() self.assertEqual(modestr, '-rwx------') self.assertS_IS("REG", st_mode) self.assertEqual(self.statmod.S_IMODE(st_mode), self.statmod.S_IRWXU) os.chmod(TESTFN, 0o070) st_mode, modestr = self.get_mode() self.assertEqual(modestr, '----rwx---') self.assertS_IS("REG", st_mode) self.assertEqual(self.statmod.S_IMODE(st_mode), self.statmod.S_IRWXG) os.chmod(TESTFN, 0o007) st_mode, modestr = self.get_mode() self.assertEqual(modestr, '-------rwx') self.assertS_IS("REG", st_mode) self.assertEqual(self.statmod.S_IMODE(st_mode), self.statmod.S_IRWXO) os.chmod(TESTFN, 0o444) st_mode, modestr = self.get_mode() self.assertS_IS("REG", st_mode) self.assertEqual(modestr, '-r--r--r--') self.assertEqual(self.statmod.S_IMODE(st_mode), 0o444) else: os.chmod(TESTFN, 0o700) st_mode, modestr = self.get_mode() self.assertEqual(modestr[:3], '-rw') self.assertS_IS("REG", st_mode) self.assertEqual(self.statmod.S_IFMT(st_mode), self.statmod.S_IFREG) def test_directory(self): os.mkdir(TESTFN) os.chmod(TESTFN, 0o700) st_mode, modestr = self.get_mode() self.assertS_IS("DIR", st_mode) if os.name == 'posix': self.assertEqual(modestr, 'drwx------') else: self.assertEqual(modestr[0], 'd') @unittest.skipUnless(hasattr(os, 'symlink'), 'os.symlink not available') def test_link(self): try: os.symlink(os.getcwd(), TESTFN) except (OSError, NotImplementedError) as err: raise unittest.SkipTest(str(err)) else: st_mode, modestr = self.get_mode() self.assertEqual(modestr[0], 'l') self.assertS_IS("LNK", st_mode) @unittest.skipUnless(hasattr(os, 'mkfifo'), 'os.mkfifo not available') def test_fifo(self): try: os.mkfifo(TESTFN, 0o700) except PermissionError as e: self.skipTest('os.mkfifo(): %s' % e) st_mode, modestr = self.get_mode() self.assertEqual(modestr, 'prwx------') self.assertS_IS("FIFO", st_mode) @unittest.skipUnless(os.name == 'posix', 'requires Posix') def test_devices(self): if os.path.exists(os.devnull): st_mode, modestr = self.get_mode(os.devnull, lstat=False) self.assertEqual(modestr[0], 'c') self.assertS_IS("CHR", st_mode) # Linux block devices, BSD has no block devices anymore for blockdev in ("/dev/sda", "/dev/hda"): if os.path.exists(blockdev): st_mode, modestr = self.get_mode(blockdev, lstat=False) self.assertEqual(modestr[0], 'b') self.assertS_IS("BLK", st_mode) break def test_module_attributes(self): for key, value in self.stat_struct.items(): modvalue = getattr(self.statmod, key) self.assertEqual(value, modvalue, key) for key, value in self.permission_bits.items(): modvalue = getattr(self.statmod, key) self.assertEqual(value, modvalue, key) for key in self.file_flags: modvalue = getattr(self.statmod, key) self.assertIsInstance(modvalue, int) for key in self.formats: modvalue = getattr(self.statmod, key) self.assertIsInstance(modvalue, int) for key in self.format_funcs: func = getattr(self.statmod, key) self.assertTrue(callable(func)) self.assertEqual(func(0), 0) @unittest.skipUnless(sys.platform == "win32", "FILE_ATTRIBUTE_* constants are Win32 specific") def test_file_attribute_constants(self): for key, value in sorted(self.file_attributes.items()): self.assertTrue(hasattr(self.statmod, key), key) modvalue = getattr(self.statmod, key) self.assertEqual(value, modvalue, key) class TestFilemodeCStat(TestFilemode, unittest.TestCase): statmod = c_stat class TestFilemodePyStat(TestFilemode, unittest.TestCase): statmod = py_stat 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_getargs2.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_getargs2.py
import unittest import math import string import sys from test import support # Skip this test if the _testcapi module isn't available. _testcapi = support.import_module('_testcapi') from _testcapi import getargs_keywords, getargs_keyword_only # > How about the following counterproposal. This also changes some of # > the other format codes to be a little more regular. # > # > Code C type Range check # > # > b unsigned char 0..UCHAR_MAX # > h signed short SHRT_MIN..SHRT_MAX # > B unsigned char none ** # > H unsigned short none ** # > k * unsigned long none # > I * unsigned int 0..UINT_MAX # # # > i int INT_MIN..INT_MAX # > l long LONG_MIN..LONG_MAX # # > K * unsigned long long none # > L long long LLONG_MIN..LLONG_MAX # # > Notes: # > # > * New format codes. # > # > ** Changed from previous "range-and-a-half" to "none"; the # > range-and-a-half checking wasn't particularly useful. # # Plus a C API or two, e.g. PyLong_AsUnsignedLongMask() -> # unsigned long and PyLong_AsUnsignedLongLongMask() -> unsigned # long long (if that exists). LARGE = 0x7FFFFFFF VERY_LARGE = 0xFF0000121212121212121242 from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \ INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, \ SHRT_MIN, SHRT_MAX, FLT_MIN, FLT_MAX, DBL_MIN, DBL_MAX DBL_MAX_EXP = sys.float_info.max_exp INF = float('inf') NAN = float('nan') # fake, they are not defined in Python's header files LLONG_MAX = 2**63-1 LLONG_MIN = -2**63 ULLONG_MAX = 2**64-1 class Int: def __int__(self): return 99 class IntSubclass(int): def __int__(self): return 99 class BadInt: def __int__(self): return 1.0 class BadInt2: def __int__(self): return True class BadInt3(int): def __int__(self): return True class Float: def __float__(self): return 4.25 class FloatSubclass(float): pass class FloatSubclass2(float): def __float__(self): return 4.25 class BadFloat: def __float__(self): return 687 class BadFloat2: def __float__(self): return FloatSubclass(4.25) class BadFloat3(float): def __float__(self): return FloatSubclass(4.25) class Complex: def __complex__(self): return 4.25+0.5j class ComplexSubclass(complex): pass class ComplexSubclass2(complex): def __complex__(self): return 4.25+0.5j class BadComplex: def __complex__(self): return 1.25 class BadComplex2: def __complex__(self): return ComplexSubclass(4.25+0.5j) class BadComplex3(complex): def __complex__(self): return ComplexSubclass(4.25+0.5j) class TupleSubclass(tuple): pass class DictSubclass(dict): pass class Unsigned_TestCase(unittest.TestCase): def test_b(self): from _testcapi import getargs_b # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX) self.assertRaises(TypeError, getargs_b, 3.14) self.assertEqual(99, getargs_b(Int())) self.assertEqual(0, getargs_b(IntSubclass())) self.assertRaises(TypeError, getargs_b, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_b(BadInt2())) self.assertEqual(0, getargs_b(BadInt3())) self.assertRaises(OverflowError, getargs_b, -1) self.assertEqual(0, getargs_b(0)) self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX)) self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1) self.assertEqual(42, getargs_b(42)) self.assertRaises(OverflowError, getargs_b, VERY_LARGE) def test_B(self): from _testcapi import getargs_B # B returns 'unsigned char', no range checking self.assertRaises(TypeError, getargs_B, 3.14) self.assertEqual(99, getargs_B(Int())) self.assertEqual(0, getargs_B(IntSubclass())) self.assertRaises(TypeError, getargs_B, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_B(BadInt2())) self.assertEqual(0, getargs_B(BadInt3())) self.assertEqual(UCHAR_MAX, getargs_B(-1)) self.assertEqual(0, getargs_B(0)) self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX)) self.assertEqual(0, getargs_B(UCHAR_MAX+1)) self.assertEqual(42, getargs_B(42)) self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) def test_H(self): from _testcapi import getargs_H # H returns 'unsigned short', no range checking self.assertRaises(TypeError, getargs_H, 3.14) self.assertEqual(99, getargs_H(Int())) self.assertEqual(0, getargs_H(IntSubclass())) self.assertRaises(TypeError, getargs_H, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_H(BadInt2())) self.assertEqual(0, getargs_H(BadInt3())) self.assertEqual(USHRT_MAX, getargs_H(-1)) self.assertEqual(0, getargs_H(0)) self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX)) self.assertEqual(0, getargs_H(USHRT_MAX+1)) self.assertEqual(42, getargs_H(42)) self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE)) def test_I(self): from _testcapi import getargs_I # I returns 'unsigned int', no range checking self.assertRaises(TypeError, getargs_I, 3.14) self.assertEqual(99, getargs_I(Int())) self.assertEqual(0, getargs_I(IntSubclass())) self.assertRaises(TypeError, getargs_I, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_I(BadInt2())) self.assertEqual(0, getargs_I(BadInt3())) self.assertEqual(UINT_MAX, getargs_I(-1)) self.assertEqual(0, getargs_I(0)) self.assertEqual(UINT_MAX, getargs_I(UINT_MAX)) self.assertEqual(0, getargs_I(UINT_MAX+1)) self.assertEqual(42, getargs_I(42)) self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE)) def test_k(self): from _testcapi import getargs_k # k returns 'unsigned long', no range checking # it does not accept float, or instances with __int__ self.assertRaises(TypeError, getargs_k, 3.14) self.assertRaises(TypeError, getargs_k, Int()) self.assertEqual(0, getargs_k(IntSubclass())) self.assertRaises(TypeError, getargs_k, BadInt()) self.assertRaises(TypeError, getargs_k, BadInt2()) self.assertEqual(0, getargs_k(BadInt3())) self.assertEqual(ULONG_MAX, getargs_k(-1)) self.assertEqual(0, getargs_k(0)) self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX)) self.assertEqual(0, getargs_k(ULONG_MAX+1)) self.assertEqual(42, getargs_k(42)) self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE)) class Signed_TestCase(unittest.TestCase): def test_h(self): from _testcapi import getargs_h # h returns 'short', and does range checking (SHRT_MIN ... SHRT_MAX) self.assertRaises(TypeError, getargs_h, 3.14) self.assertEqual(99, getargs_h(Int())) self.assertEqual(0, getargs_h(IntSubclass())) self.assertRaises(TypeError, getargs_h, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_h(BadInt2())) self.assertEqual(0, getargs_h(BadInt3())) self.assertRaises(OverflowError, getargs_h, SHRT_MIN-1) self.assertEqual(SHRT_MIN, getargs_h(SHRT_MIN)) self.assertEqual(SHRT_MAX, getargs_h(SHRT_MAX)) self.assertRaises(OverflowError, getargs_h, SHRT_MAX+1) self.assertEqual(42, getargs_h(42)) self.assertRaises(OverflowError, getargs_h, VERY_LARGE) def test_i(self): from _testcapi import getargs_i # i returns 'int', and does range checking (INT_MIN ... INT_MAX) self.assertRaises(TypeError, getargs_i, 3.14) self.assertEqual(99, getargs_i(Int())) self.assertEqual(0, getargs_i(IntSubclass())) self.assertRaises(TypeError, getargs_i, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_i(BadInt2())) self.assertEqual(0, getargs_i(BadInt3())) self.assertRaises(OverflowError, getargs_i, INT_MIN-1) self.assertEqual(INT_MIN, getargs_i(INT_MIN)) self.assertEqual(INT_MAX, getargs_i(INT_MAX)) self.assertRaises(OverflowError, getargs_i, INT_MAX+1) self.assertEqual(42, getargs_i(42)) self.assertRaises(OverflowError, getargs_i, VERY_LARGE) def test_l(self): from _testcapi import getargs_l # l returns 'long', and does range checking (LONG_MIN ... LONG_MAX) self.assertRaises(TypeError, getargs_l, 3.14) self.assertEqual(99, getargs_l(Int())) self.assertEqual(0, getargs_l(IntSubclass())) self.assertRaises(TypeError, getargs_l, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_l(BadInt2())) self.assertEqual(0, getargs_l(BadInt3())) self.assertRaises(OverflowError, getargs_l, LONG_MIN-1) self.assertEqual(LONG_MIN, getargs_l(LONG_MIN)) self.assertEqual(LONG_MAX, getargs_l(LONG_MAX)) self.assertRaises(OverflowError, getargs_l, LONG_MAX+1) self.assertEqual(42, getargs_l(42)) self.assertRaises(OverflowError, getargs_l, VERY_LARGE) def test_n(self): from _testcapi import getargs_n # n returns 'Py_ssize_t', and does range checking # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX) self.assertRaises(TypeError, getargs_n, 3.14) self.assertRaises(TypeError, getargs_n, Int()) self.assertEqual(0, getargs_n(IntSubclass())) self.assertRaises(TypeError, getargs_n, BadInt()) self.assertRaises(TypeError, getargs_n, BadInt2()) self.assertEqual(0, getargs_n(BadInt3())) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1) self.assertEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN)) self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX)) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1) self.assertEqual(42, getargs_n(42)) self.assertRaises(OverflowError, getargs_n, VERY_LARGE) class LongLong_TestCase(unittest.TestCase): def test_L(self): from _testcapi import getargs_L # L returns 'long long', and does range checking (LLONG_MIN # ... LLONG_MAX) self.assertRaises(TypeError, getargs_L, 3.14) self.assertRaises(TypeError, getargs_L, "Hello") self.assertEqual(99, getargs_L(Int())) self.assertEqual(0, getargs_L(IntSubclass())) self.assertRaises(TypeError, getargs_L, BadInt()) with self.assertWarns(DeprecationWarning): self.assertEqual(1, getargs_L(BadInt2())) self.assertEqual(0, getargs_L(BadInt3())) self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1) self.assertEqual(LLONG_MIN, getargs_L(LLONG_MIN)) self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX)) self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1) self.assertEqual(42, getargs_L(42)) self.assertRaises(OverflowError, getargs_L, VERY_LARGE) def test_K(self): from _testcapi import getargs_K # K return 'unsigned long long', no range checking self.assertRaises(TypeError, getargs_K, 3.14) self.assertRaises(TypeError, getargs_K, Int()) self.assertEqual(0, getargs_K(IntSubclass())) self.assertRaises(TypeError, getargs_K, BadInt()) self.assertRaises(TypeError, getargs_K, BadInt2()) self.assertEqual(0, getargs_K(BadInt3())) self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX)) self.assertEqual(0, getargs_K(0)) self.assertEqual(0, getargs_K(ULLONG_MAX+1)) self.assertEqual(42, getargs_K(42)) self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE)) class Float_TestCase(unittest.TestCase): def assertEqualWithSign(self, actual, expected): self.assertEqual(actual, expected) self.assertEqual(math.copysign(1, actual), math.copysign(1, expected)) def test_f(self): from _testcapi import getargs_f self.assertEqual(getargs_f(4.25), 4.25) self.assertEqual(getargs_f(4), 4.0) self.assertRaises(TypeError, getargs_f, 4.25+0j) self.assertEqual(getargs_f(Float()), 4.25) self.assertEqual(getargs_f(FloatSubclass(7.5)), 7.5) self.assertEqual(getargs_f(FloatSubclass2(7.5)), 7.5) self.assertRaises(TypeError, getargs_f, BadFloat()) with self.assertWarns(DeprecationWarning): self.assertEqual(getargs_f(BadFloat2()), 4.25) self.assertEqual(getargs_f(BadFloat3(7.5)), 7.5) for x in (FLT_MIN, -FLT_MIN, FLT_MAX, -FLT_MAX, INF, -INF): self.assertEqual(getargs_f(x), x) if FLT_MAX < DBL_MAX: self.assertEqual(getargs_f(DBL_MAX), INF) self.assertEqual(getargs_f(-DBL_MAX), -INF) if FLT_MIN > DBL_MIN: self.assertEqualWithSign(getargs_f(DBL_MIN), 0.0) self.assertEqualWithSign(getargs_f(-DBL_MIN), -0.0) self.assertEqualWithSign(getargs_f(0.0), 0.0) self.assertEqualWithSign(getargs_f(-0.0), -0.0) r = getargs_f(NAN) self.assertNotEqual(r, r) @support.requires_IEEE_754 def test_f_rounding(self): from _testcapi import getargs_f self.assertEqual(getargs_f(3.40282356e38), FLT_MAX) self.assertEqual(getargs_f(-3.40282356e38), -FLT_MAX) def test_d(self): from _testcapi import getargs_d self.assertEqual(getargs_d(4.25), 4.25) self.assertEqual(getargs_d(4), 4.0) self.assertRaises(TypeError, getargs_d, 4.25+0j) self.assertEqual(getargs_d(Float()), 4.25) self.assertEqual(getargs_d(FloatSubclass(7.5)), 7.5) self.assertEqual(getargs_d(FloatSubclass2(7.5)), 7.5) self.assertRaises(TypeError, getargs_d, BadFloat()) with self.assertWarns(DeprecationWarning): self.assertEqual(getargs_d(BadFloat2()), 4.25) self.assertEqual(getargs_d(BadFloat3(7.5)), 7.5) for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF): self.assertEqual(getargs_d(x), x) self.assertRaises(OverflowError, getargs_d, 1<<DBL_MAX_EXP) self.assertRaises(OverflowError, getargs_d, -1<<DBL_MAX_EXP) self.assertEqualWithSign(getargs_d(0.0), 0.0) self.assertEqualWithSign(getargs_d(-0.0), -0.0) r = getargs_d(NAN) self.assertNotEqual(r, r) def test_D(self): from _testcapi import getargs_D self.assertEqual(getargs_D(4.25+0.5j), 4.25+0.5j) self.assertEqual(getargs_D(4.25), 4.25+0j) self.assertEqual(getargs_D(4), 4.0+0j) self.assertEqual(getargs_D(Complex()), 4.25+0.5j) self.assertEqual(getargs_D(ComplexSubclass(7.5+0.25j)), 7.5+0.25j) self.assertEqual(getargs_D(ComplexSubclass2(7.5+0.25j)), 7.5+0.25j) self.assertRaises(TypeError, getargs_D, BadComplex()) with self.assertWarns(DeprecationWarning): self.assertEqual(getargs_D(BadComplex2()), 4.25+0.5j) self.assertEqual(getargs_D(BadComplex3(7.5+0.25j)), 7.5+0.25j) for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF): c = complex(x, 1.0) self.assertEqual(getargs_D(c), c) c = complex(1.0, x) self.assertEqual(getargs_D(c), c) self.assertEqualWithSign(getargs_D(complex(0.0, 1.0)).real, 0.0) self.assertEqualWithSign(getargs_D(complex(-0.0, 1.0)).real, -0.0) self.assertEqualWithSign(getargs_D(complex(1.0, 0.0)).imag, 0.0) self.assertEqualWithSign(getargs_D(complex(1.0, -0.0)).imag, -0.0) class Paradox: "This statement is false." def __bool__(self): raise NotImplementedError class Boolean_TestCase(unittest.TestCase): def test_p(self): from _testcapi import getargs_p self.assertEqual(0, getargs_p(False)) self.assertEqual(0, getargs_p(None)) self.assertEqual(0, getargs_p(0)) self.assertEqual(0, getargs_p(0.0)) self.assertEqual(0, getargs_p(0j)) self.assertEqual(0, getargs_p('')) self.assertEqual(0, getargs_p(())) self.assertEqual(0, getargs_p([])) self.assertEqual(0, getargs_p({})) self.assertEqual(1, getargs_p(True)) self.assertEqual(1, getargs_p(1)) self.assertEqual(1, getargs_p(1.0)) self.assertEqual(1, getargs_p(1j)) self.assertEqual(1, getargs_p('x')) self.assertEqual(1, getargs_p((1,))) self.assertEqual(1, getargs_p([1])) self.assertEqual(1, getargs_p({1:2})) self.assertEqual(1, getargs_p(unittest.TestCase)) self.assertRaises(NotImplementedError, getargs_p, Paradox()) class Tuple_TestCase(unittest.TestCase): def test_args(self): from _testcapi import get_args ret = get_args(1, 2) self.assertEqual(ret, (1, 2)) self.assertIs(type(ret), tuple) ret = get_args(1, *(2, 3)) self.assertEqual(ret, (1, 2, 3)) self.assertIs(type(ret), tuple) ret = get_args(*[1, 2]) self.assertEqual(ret, (1, 2)) self.assertIs(type(ret), tuple) ret = get_args(*TupleSubclass([1, 2])) self.assertEqual(ret, (1, 2)) self.assertIs(type(ret), tuple) ret = get_args() self.assertIn(ret, ((), None)) self.assertIn(type(ret), (tuple, type(None))) ret = get_args(*()) self.assertIn(ret, ((), None)) self.assertIn(type(ret), (tuple, type(None))) def test_tuple(self): from _testcapi import getargs_tuple ret = getargs_tuple(1, (2, 3)) self.assertEqual(ret, (1,2,3)) # make sure invalid tuple arguments are handled correctly class seq: def __len__(self): return 2 def __getitem__(self, n): raise ValueError self.assertRaises(TypeError, getargs_tuple, 1, seq()) class Keywords_TestCase(unittest.TestCase): def test_kwargs(self): from _testcapi import get_kwargs ret = get_kwargs(a=1, b=2) self.assertEqual(ret, {'a': 1, 'b': 2}) self.assertIs(type(ret), dict) ret = get_kwargs(a=1, **{'b': 2, 'c': 3}) self.assertEqual(ret, {'a': 1, 'b': 2, 'c': 3}) self.assertIs(type(ret), dict) ret = get_kwargs(**DictSubclass({'a': 1, 'b': 2})) self.assertEqual(ret, {'a': 1, 'b': 2}) self.assertIs(type(ret), dict) ret = get_kwargs() self.assertIn(ret, ({}, None)) self.assertIn(type(ret), (dict, type(None))) ret = get_kwargs(**{}) self.assertIn(ret, ({}, None)) self.assertIn(type(ret), (dict, type(None))) def test_positional_args(self): # using all positional args self.assertEqual( getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) def test_mixed_args(self): # positional and keyword args self.assertEqual( getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) def test_keyword_args(self): # all keywords self.assertEqual( getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) def test_optional_args(self): # missing optional keyword args, skipping tuples self.assertEqual( getargs_keywords(arg1=(1,2), arg2=3, arg5=10), (1, 2, 3, -1, -1, -1, -1, -1, -1, 10) ) def test_required_args(self): # required arg missing try: getargs_keywords(arg1=(1,2)) except TypeError as err: self.assertEqual( str(err), "function missing required argument 'arg2' (pos 2)") else: self.fail('TypeError should have been raised') def test_too_many_args(self): try: getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) except TypeError as err: self.assertEqual(str(err), "function takes at most 5 arguments (6 given)") else: self.fail('TypeError should have been raised') def test_invalid_keyword(self): # extraneous keyword arg try: getargs_keywords((1,2),3,arg5=10,arg666=666) except TypeError as err: self.assertEqual(str(err), "'arg666' is an invalid keyword argument for this function") else: self.fail('TypeError should have been raised') def test_surrogate_keyword(self): try: getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10}) except TypeError as err: self.assertEqual(str(err), "'\udc80' is an invalid keyword argument for this function") else: self.fail('TypeError should have been raised') class KeywordOnly_TestCase(unittest.TestCase): def test_positional_args(self): # using all possible positional args self.assertEqual( getargs_keyword_only(1, 2), (1, 2, -1) ) def test_mixed_args(self): # positional and keyword args self.assertEqual( getargs_keyword_only(1, 2, keyword_only=3), (1, 2, 3) ) def test_keyword_args(self): # all keywords self.assertEqual( getargs_keyword_only(required=1, optional=2, keyword_only=3), (1, 2, 3) ) def test_optional_args(self): # missing optional keyword args, skipping tuples self.assertEqual( getargs_keyword_only(required=1, optional=2), (1, 2, -1) ) self.assertEqual( getargs_keyword_only(required=1, keyword_only=3), (1, -1, 3) ) def test_required_args(self): self.assertEqual( getargs_keyword_only(1), (1, -1, -1) ) self.assertEqual( getargs_keyword_only(required=1), (1, -1, -1) ) # required arg missing with self.assertRaisesRegex(TypeError, r"function missing required argument 'required' \(pos 1\)"): getargs_keyword_only(optional=2) with self.assertRaisesRegex(TypeError, r"function missing required argument 'required' \(pos 1\)"): getargs_keyword_only(keyword_only=3) def test_too_many_args(self): with self.assertRaisesRegex(TypeError, r"function takes at most 2 positional arguments \(3 given\)"): getargs_keyword_only(1, 2, 3) with self.assertRaisesRegex(TypeError, r"function takes at most 3 arguments \(4 given\)"): getargs_keyword_only(1, 2, 3, keyword_only=5) def test_invalid_keyword(self): # extraneous keyword arg with self.assertRaisesRegex(TypeError, "'monster' is an invalid keyword argument for this function"): getargs_keyword_only(1, 2, monster=666) def test_surrogate_keyword(self): with self.assertRaisesRegex(TypeError, "'\udc80' is an invalid keyword argument for this function"): getargs_keyword_only(1, 2, **{'\uDC80': 10}) class PositionalOnlyAndKeywords_TestCase(unittest.TestCase): from _testcapi import getargs_positional_only_and_keywords as getargs def test_positional_args(self): # using all possible positional args self.assertEqual(self.getargs(1, 2, 3), (1, 2, 3)) def test_mixed_args(self): # positional and keyword args self.assertEqual(self.getargs(1, 2, keyword=3), (1, 2, 3)) def test_optional_args(self): # missing optional args self.assertEqual(self.getargs(1, 2), (1, 2, -1)) self.assertEqual(self.getargs(1, keyword=3), (1, -1, 3)) def test_required_args(self): self.assertEqual(self.getargs(1), (1, -1, -1)) # required positional arg missing with self.assertRaisesRegex(TypeError, r"function takes at least 1 positional arguments \(0 given\)"): self.getargs() with self.assertRaisesRegex(TypeError, r"function takes at least 1 positional arguments \(0 given\)"): self.getargs(keyword=3) def test_empty_keyword(self): with self.assertRaisesRegex(TypeError, "'' is an invalid keyword argument for this function"): self.getargs(1, 2, **{'': 666}) class Bytes_TestCase(unittest.TestCase): def test_c(self): from _testcapi import getargs_c self.assertRaises(TypeError, getargs_c, b'abc') # len > 1 self.assertEqual(getargs_c(b'a'), 97) self.assertEqual(getargs_c(bytearray(b'a')), 97) self.assertRaises(TypeError, getargs_c, memoryview(b'a')) self.assertRaises(TypeError, getargs_c, 's') self.assertRaises(TypeError, getargs_c, 97) self.assertRaises(TypeError, getargs_c, None) def test_y(self): from _testcapi import getargs_y self.assertRaises(TypeError, getargs_y, 'abc\xe9') self.assertEqual(getargs_y(b'bytes'), b'bytes') self.assertRaises(ValueError, getargs_y, b'nul:\0') self.assertRaises(TypeError, getargs_y, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_y, memoryview(b'memoryview')) self.assertRaises(TypeError, getargs_y, None) def test_y_star(self): from _testcapi import getargs_y_star self.assertRaises(TypeError, getargs_y_star, 'abc\xe9') self.assertEqual(getargs_y_star(b'bytes'), b'bytes') self.assertEqual(getargs_y_star(b'nul:\0'), b'nul:\0') self.assertEqual(getargs_y_star(bytearray(b'bytearray')), b'bytearray') self.assertEqual(getargs_y_star(memoryview(b'memoryview')), b'memoryview') self.assertRaises(TypeError, getargs_y_star, None) def test_y_hash(self): from _testcapi import getargs_y_hash self.assertRaises(TypeError, getargs_y_hash, 'abc\xe9') self.assertEqual(getargs_y_hash(b'bytes'), b'bytes') self.assertEqual(getargs_y_hash(b'nul:\0'), b'nul:\0') self.assertRaises(TypeError, getargs_y_hash, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_y_hash, memoryview(b'memoryview')) self.assertRaises(TypeError, getargs_y_hash, None) def test_w_star(self): # getargs_w_star() modifies first and last byte from _testcapi import getargs_w_star self.assertRaises(TypeError, getargs_w_star, 'abc\xe9') self.assertRaises(TypeError, getargs_w_star, b'bytes') self.assertRaises(TypeError, getargs_w_star, b'nul:\0') self.assertRaises(TypeError, getargs_w_star, memoryview(b'bytes')) buf = bytearray(b'bytearray') self.assertEqual(getargs_w_star(buf), b'[ytearra]') self.assertEqual(buf, bytearray(b'[ytearra]')) buf = bytearray(b'memoryview') self.assertEqual(getargs_w_star(memoryview(buf)), b'[emoryvie]') self.assertEqual(buf, bytearray(b'[emoryvie]')) self.assertRaises(TypeError, getargs_w_star, None) class String_TestCase(unittest.TestCase): def test_C(self): from _testcapi import getargs_C self.assertRaises(TypeError, getargs_C, 'abc') # len > 1 self.assertEqual(getargs_C('a'), 97) self.assertEqual(getargs_C('\u20ac'), 0x20ac) self.assertEqual(getargs_C('\U0001f40d'), 0x1f40d) self.assertRaises(TypeError, getargs_C, b'a') self.assertRaises(TypeError, getargs_C, bytearray(b'a')) self.assertRaises(TypeError, getargs_C, memoryview(b'a')) self.assertRaises(TypeError, getargs_C, 97) self.assertRaises(TypeError, getargs_C, None) def test_s(self): from _testcapi import getargs_s self.assertEqual(getargs_s('abc\xe9'), b'abc\xc3\xa9') self.assertRaises(ValueError, getargs_s, 'nul:\0') self.assertRaises(TypeError, getargs_s, b'bytes') self.assertRaises(TypeError, getargs_s, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_s, memoryview(b'memoryview')) self.assertRaises(TypeError, getargs_s, None) def test_s_star(self): from _testcapi import getargs_s_star self.assertEqual(getargs_s_star('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_s_star('nul:\0'), b'nul:\0') self.assertEqual(getargs_s_star(b'bytes'), b'bytes') self.assertEqual(getargs_s_star(bytearray(b'bytearray')), b'bytearray') self.assertEqual(getargs_s_star(memoryview(b'memoryview')), b'memoryview') self.assertRaises(TypeError, getargs_s_star, None) def test_s_hash(self): from _testcapi import getargs_s_hash self.assertEqual(getargs_s_hash('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_s_hash('nul:\0'), b'nul:\0') self.assertEqual(getargs_s_hash(b'bytes'), b'bytes') self.assertRaises(TypeError, getargs_s_hash, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_s_hash, memoryview(b'memoryview')) self.assertRaises(TypeError, getargs_s_hash, None) def test_z(self): from _testcapi import getargs_z self.assertEqual(getargs_z('abc\xe9'), b'abc\xc3\xa9') self.assertRaises(ValueError, getargs_z, 'nul:\0') self.assertRaises(TypeError, getargs_z, b'bytes') self.assertRaises(TypeError, getargs_z, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_z, memoryview(b'memoryview')) self.assertIsNone(getargs_z(None)) def test_z_star(self): from _testcapi import getargs_z_star self.assertEqual(getargs_z_star('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_z_star('nul:\0'), b'nul:\0') self.assertEqual(getargs_z_star(b'bytes'), b'bytes') self.assertEqual(getargs_z_star(bytearray(b'bytearray')), b'bytearray') self.assertEqual(getargs_z_star(memoryview(b'memoryview')), b'memoryview') self.assertIsNone(getargs_z_star(None)) def test_z_hash(self): from _testcapi import getargs_z_hash self.assertEqual(getargs_z_hash('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_z_hash('nul:\0'), b'nul:\0') self.assertEqual(getargs_z_hash(b'bytes'), b'bytes') self.assertRaises(TypeError, getargs_z_hash, bytearray(b'bytearray')) self.assertRaises(TypeError, getargs_z_hash, memoryview(b'memoryview')) self.assertIsNone(getargs_z_hash(None)) def test_es(self): from _testcapi import getargs_es self.assertEqual(getargs_es('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_es('abc\xe9', 'latin1'), b'abc\xe9') self.assertRaises(UnicodeEncodeError, getargs_es, 'abc\xe9', 'ascii') self.assertRaises(LookupError, getargs_es, 'abc\xe9', 'spam') self.assertRaises(TypeError, getargs_es, b'bytes', 'latin1') self.assertRaises(TypeError, getargs_es, bytearray(b'bytearray'), 'latin1') self.assertRaises(TypeError, getargs_es, memoryview(b'memoryview'), 'latin1') self.assertRaises(TypeError, getargs_es, None, 'latin1') self.assertRaises(TypeError, getargs_es, 'nul:\0', 'latin1') def test_et(self): from _testcapi import getargs_et self.assertEqual(getargs_et('abc\xe9'), b'abc\xc3\xa9') self.assertEqual(getargs_et('abc\xe9', 'latin1'), b'abc\xe9') self.assertRaises(UnicodeEncodeError, getargs_et, 'abc\xe9', 'ascii') self.assertRaises(LookupError, getargs_et, 'abc\xe9', 'spam') self.assertEqual(getargs_et(b'bytes', 'latin1'), b'bytes') self.assertEqual(getargs_et(bytearray(b'bytearray'), 'latin1'), b'bytearray') self.assertRaises(TypeError, getargs_et, memoryview(b'memoryview'), 'latin1') self.assertRaises(TypeError, getargs_et, None, 'latin1') self.assertRaises(TypeError, getargs_et, 'nul:\0', 'latin1') self.assertRaises(TypeError, getargs_et, b'nul:\0', 'latin1') self.assertRaises(TypeError, getargs_et, bytearray(b'nul:\0'), 'latin1') def test_es_hash(self): from _testcapi import getargs_es_hash self.assertEqual(getargs_es_hash('abc\xe9'), b'abc\xc3\xa9')
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_unpack_ex.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_unpack_ex.py
# Tests for extended unpacking, starred expressions. doctests = """ Unpack tuple >>> t = (1, 2, 3) >>> a, *b, c = t >>> a == 1 and b == [2] and c == 3 True Unpack list >>> l = [4, 5, 6] >>> a, *b = l >>> a == 4 and b == [5, 6] True Unpack implied tuple >>> *a, = 7, 8, 9 >>> a == [7, 8, 9] True Unpack string... fun! >>> a, *b = 'one' >>> a == 'o' and b == ['n', 'e'] True Unpack long sequence >>> a, b, c, *d, e, f, g = range(10) >>> (a, b, c, d, e, f, g) == (0, 1, 2, [3, 4, 5, 6], 7, 8, 9) True Unpack short sequence >>> a, *b, c = (1, 2) >>> a == 1 and c == 2 and b == [] True Unpack generic sequence >>> class Seq: ... def __getitem__(self, i): ... if i >= 0 and i < 3: return i ... raise IndexError ... >>> a, *b = Seq() >>> a == 0 and b == [1, 2] True Unpack in for statement >>> for a, *b, c in [(1,2,3), (4,5,6,7)]: ... print(a, b, c) ... 1 [2] 3 4 [5, 6] 7 Unpack in list >>> [a, *b, c] = range(5) >>> a == 0 and b == [1, 2, 3] and c == 4 True Multiple targets >>> a, *b, c = *d, e = range(5) >>> a == 0 and b == [1, 2, 3] and c == 4 and d == [0, 1, 2, 3] and e == 4 True Assignment unpacking >>> a, b, *c = range(5) >>> a, b, c (0, 1, [2, 3, 4]) >>> *a, b, c = a, b, *c >>> a, b, c ([0, 1, 2], 3, 4) Set display element unpacking >>> a = [1, 2, 3] >>> sorted({1, *a, 0, 4}) [0, 1, 2, 3, 4] >>> {1, *1, 0, 4} Traceback (most recent call last): ... TypeError: 'int' object is not iterable Dict display element unpacking >>> kwds = {'z': 0, 'w': 12} >>> sorted({'x': 1, 'y': 2, **kwds}.items()) [('w', 12), ('x', 1), ('y', 2), ('z', 0)] >>> sorted({**{'x': 1}, 'y': 2, **{'z': 3}}.items()) [('x', 1), ('y', 2), ('z', 3)] >>> sorted({**{'x': 1}, 'y': 2, **{'x': 3}}.items()) [('x', 3), ('y', 2)] >>> sorted({**{'x': 1}, **{'x': 3}, 'x': 4}.items()) [('x', 4)] >>> {**{}} {} >>> a = {} >>> {**a}[0] = 1 >>> a {} >>> {**1} Traceback (most recent call last): ... TypeError: 'int' object is not a mapping >>> {**[]} Traceback (most recent call last): ... TypeError: 'list' object is not a mapping >>> len(eval("{" + ", ".join("**{{{}: {}}}".format(i, i) ... for i in range(1000)) + "}")) 1000 >>> {0:1, **{0:2}, 0:3, 0:4} {0: 4} List comprehension element unpacking >>> a, b, c = [0, 1, 2], 3, 4 >>> [*a, b, c] [0, 1, 2, 3, 4] >>> l = [a, (3, 4), {5}, {6: None}, (i for i in range(7, 10))] >>> [*item for item in l] Traceback (most recent call last): ... SyntaxError: iterable unpacking cannot be used in comprehension >>> [*[0, 1] for i in range(10)] Traceback (most recent call last): ... SyntaxError: iterable unpacking cannot be used in comprehension >>> [*'a' for i in range(10)] Traceback (most recent call last): ... SyntaxError: iterable unpacking cannot be used in comprehension >>> [*[] for i in range(10)] Traceback (most recent call last): ... SyntaxError: iterable unpacking cannot be used in comprehension Generator expression in function arguments >>> list(*x for x in (range(5) for i in range(3))) Traceback (most recent call last): ... list(*x for x in (range(5) for i in range(3))) ^ SyntaxError: invalid syntax >>> dict(**x for x in [{1:2}]) Traceback (most recent call last): ... dict(**x for x in [{1:2}]) ^ SyntaxError: invalid syntax Iterable argument unpacking >>> print(*[1], *[2], 3) 1 2 3 Make sure that they don't corrupt the passed-in dicts. >>> def f(x, y): ... print(x, y) ... >>> original_dict = {'x': 1} >>> f(**original_dict, y=2) 1 2 >>> original_dict {'x': 1} Now for some failures Make sure the raised errors are right for keyword argument unpackings >>> from collections.abc import MutableMapping >>> class CrazyDict(MutableMapping): ... def __init__(self): ... self.d = {} ... ... def __iter__(self): ... for x in self.d.__iter__(): ... if x == 'c': ... self.d['z'] = 10 ... yield x ... ... def __getitem__(self, k): ... return self.d[k] ... ... def __len__(self): ... return len(self.d) ... ... def __setitem__(self, k, v): ... self.d[k] = v ... ... def __delitem__(self, k): ... del self.d[k] ... >>> d = CrazyDict() >>> d.d = {chr(ord('a') + x): x for x in range(5)} >>> e = {**d} Traceback (most recent call last): ... RuntimeError: dictionary changed size during iteration >>> d.d = {chr(ord('a') + x): x for x in range(5)} >>> def f(**kwargs): print(kwargs) >>> f(**d) Traceback (most recent call last): ... RuntimeError: dictionary changed size during iteration Overridden parameters >>> f(x=5, **{'x': 3}, y=2) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'x' >>> f(**{'x': 3}, x=5, y=2) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'x' >>> f(**{'x': 3}, **{'x': 5}, y=2) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'x' >>> f(x=5, **{'x': 3}, **{'x': 2}) Traceback (most recent call last): ... TypeError: f() got multiple values for keyword argument 'x' >>> f(**{1: 3}, **{1: 5}) Traceback (most recent call last): ... TypeError: f() keywords must be strings Unpacking non-sequence >>> a, *b = 7 Traceback (most recent call last): ... TypeError: cannot unpack non-iterable int object Unpacking sequence too short >>> a, *b, c, d, e = Seq() Traceback (most recent call last): ... ValueError: not enough values to unpack (expected at least 4, got 3) Unpacking sequence too short and target appears last >>> a, b, c, d, *e = Seq() Traceback (most recent call last): ... ValueError: not enough values to unpack (expected at least 4, got 3) Unpacking a sequence where the test for too long raises a different kind of error >>> class BozoError(Exception): ... pass ... >>> class BadSeq: ... def __getitem__(self, i): ... if i >= 0 and i < 3: ... return i ... elif i == 3: ... raise BozoError ... else: ... raise IndexError ... Trigger code while not expecting an IndexError (unpack sequence too long, wrong error) >>> a, *b, c, d, e = BadSeq() Traceback (most recent call last): ... test.test_unpack_ex.BozoError Now some general starred expressions (all fail). >>> a, *b, c, *d, e = range(10) # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: two starred expressions in assignment >>> [*b, *c] = range(10) # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: two starred expressions in assignment >>> *a = range(10) # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: starred assignment target must be in a list or tuple >>> *a # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: can't use starred expression here >>> *1 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: can't use starred expression here >>> x = *a # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: can't use starred expression here Some size constraints (all fail.) >>> s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range(1<<8 + 1)" >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: too many expressions in star-unpacking assignment >>> s = ", ".join("a%d" % i for i in range(1<<8 + 1)) + ", *rest = range(1<<8 + 2)" >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: too many expressions in star-unpacking assignment (there is an additional limit, on the number of expressions after the '*rest', but it's 1<<24 and testing it takes too much memory.) """ __test__ = {'doctests' : doctests} def test_main(verbose=False): from test import support from test import test_unpack_ex support.run_doctest(test_unpack_ex, verbose) if __name__ == "__main__": test_main(verbose=True)
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.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_file.py
import sys import os import unittest from array import array from weakref import proxy import io import _pyio as pyio from test.support import TESTFN from test import support from collections import UserList class AutoFileTests: # file tests for which a test file is automatically set up def setUp(self): self.f = self.open(TESTFN, 'wb') def tearDown(self): if self.f: self.f.close() support.unlink(TESTFN) def testWeakRefs(self): # verify weak references p = proxy(self.f) p.write(b'teststring') self.assertEqual(self.f.tell(), p.tell()) self.f.close() self.f = None self.assertRaises(ReferenceError, getattr, p, 'tell') def testAttributes(self): # verify expected attributes exist f = self.f f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto def testReadinto(self): # verify readinto self.f.write(b'12') self.f.close() a = array('b', b'x'*10) self.f = self.open(TESTFN, 'rb') n = self.f.readinto(a) self.assertEqual(b'12', a.tobytes()[:n]) def testReadinto_text(self): # verify readinto refuses text files a = array('b', b'x'*10) self.f.close() self.f = self.open(TESTFN, 'r') if hasattr(self.f, "readinto"): self.assertRaises(TypeError, self.f.readinto, a) def testWritelinesUserList(self): # verify writelines with instance sequence l = UserList([b'1', b'2']) self.f.writelines(l) self.f.close() self.f = self.open(TESTFN, 'rb') buf = self.f.read() self.assertEqual(buf, b'12') def testWritelinesIntegers(self): # verify writelines with integers self.assertRaises(TypeError, self.f.writelines, [1, 2, 3]) def testWritelinesIntegersUserList(self): # verify writelines with integers in UserList l = UserList([1,2,3]) self.assertRaises(TypeError, self.f.writelines, l) def testWritelinesNonString(self): # verify writelines with non-string object class NonString: pass self.assertRaises(TypeError, self.f.writelines, [NonString(), NonString()]) def testErrors(self): f = self.f self.assertEqual(f.name, TESTFN) self.assertFalse(f.isatty()) self.assertFalse(f.closed) if hasattr(f, "readinto"): self.assertRaises((OSError, TypeError), f.readinto, "") f.close() self.assertTrue(f.closed) def testMethods(self): methods = [('fileno', ()), ('flush', ()), ('isatty', ()), ('__next__', ()), ('read', ()), ('write', (b"",)), ('readline', ()), ('readlines', ()), ('seek', (0,)), ('tell', ()), ('write', (b"",)), ('writelines', ([],)), ('__iter__', ()), ] methods.append(('truncate', ())) # __exit__ should close the file self.f.__exit__(None, None, None) self.assertTrue(self.f.closed) for methodname, args in methods: method = getattr(self.f, methodname) # should raise on closed file self.assertRaises(ValueError, method, *args) # file is closed, __exit__ shouldn't do anything self.assertEqual(self.f.__exit__(None, None, None), None) # it must also return None if an exception was given try: 1/0 except: self.assertEqual(self.f.__exit__(*sys.exc_info()), None) def testReadWhenWriting(self): self.assertRaises(OSError, self.f.read) class CAutoFileTests(AutoFileTests, unittest.TestCase): open = io.open class PyAutoFileTests(AutoFileTests, unittest.TestCase): open = staticmethod(pyio.open) class OtherFileTests: def tearDown(self): support.unlink(TESTFN) def testModeStrings(self): # check invalid mode strings self.open(TESTFN, 'wb').close() for mode in ("", "aU", "wU+", "U+", "+U", "rU+"): try: f = self.open(TESTFN, mode) except ValueError: pass else: f.close() self.fail('%r is an invalid file mode' % mode) def testBadModeArgument(self): # verify that we get a sensible error message for bad mode argument bad_mode = "qwerty" try: f = self.open(TESTFN, bad_mode) except ValueError as msg: if msg.args[0] != 0: s = str(msg) if TESTFN in s or bad_mode not in s: self.fail("bad error message for invalid mode: %s" % s) # if msg.args[0] == 0, we're probably on Windows where there may be # no obvious way to discover why open() failed. else: f.close() self.fail("no error for invalid mode: %s" % bad_mode) def testSetBufferSize(self): # make sure that explicitly setting the buffer size doesn't cause # misbehaviour especially with repeated close() calls for s in (-1, 0, 1, 512): try: f = self.open(TESTFN, 'wb', s) f.write(str(s).encode("ascii")) f.close() f.close() f = self.open(TESTFN, 'rb', s) d = int(f.read().decode("ascii")) f.close() f.close() except OSError as msg: self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.assertEqual(d, s) def testTruncateOnWindows(self): # SF bug <http://www.python.org/sf/801631> # "file.truncate fault on windows" f = self.open(TESTFN, 'wb') try: f.write(b'12345678901') # 11 bytes f.close() f = self.open(TESTFN,'rb+') data = f.read(5) if data != b'12345': self.fail("Read on file opened for update failed %r" % data) if f.tell() != 5: self.fail("File pos after read wrong %d" % f.tell()) f.truncate() if f.tell() != 5: self.fail("File pos after ftruncate wrong %d" % f.tell()) f.close() size = os.path.getsize(TESTFN) if size != 5: self.fail("File size after ftruncate wrong %d" % size) finally: f.close() def testIteration(self): # Test the complex interaction when mixing file-iteration and the # various read* methods. dataoffset = 16384 filler = b"ham\n" assert not dataoffset % len(filler), \ "dataoffset must be multiple of len(filler)" nchunks = dataoffset // len(filler) testlines = [ b"spam, spam and eggs\n", b"eggs, spam, ham and spam\n", b"saussages, spam, spam and eggs\n", b"spam, ham, spam and eggs\n", b"spam, spam, spam, spam, spam, ham, spam\n", b"wonderful spaaaaaam.\n" ] methods = [("readline", ()), ("read", ()), ("readlines", ()), ("readinto", (array("b", b" "*100),))] # Prepare the testfile bag = self.open(TESTFN, "wb") bag.write(filler * nchunks) bag.writelines(testlines) bag.close() # Test for appropriate errors mixing read* and iteration for methodname, args in methods: f = self.open(TESTFN, 'rb') self.assertEqual(next(f), filler) meth = getattr(f, methodname) meth(*args) # This simply shouldn't fail f.close() # Test to see if harmless (by accident) mixing of read* and # iteration still works. This depends on the size of the internal # iteration buffer (currently 8192,) but we can test it in a # flexible manner. Each line in the bag o' ham is 4 bytes # ("h", "a", "m", "\n"), so 4096 lines of that should get us # exactly on the buffer boundary for any power-of-2 buffersize # between 4 and 16384 (inclusive). f = self.open(TESTFN, 'rb') for i in range(nchunks): next(f) testline = testlines.pop(0) try: line = f.readline() except ValueError: self.fail("readline() after next() with supposedly empty " "iteration-buffer failed anyway") if line != testline: self.fail("readline() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) testline = testlines.pop(0) buf = array("b", b"\x00" * len(testline)) try: f.readinto(buf) except ValueError: self.fail("readinto() after next() with supposedly empty " "iteration-buffer failed anyway") line = buf.tobytes() if line != testline: self.fail("readinto() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) testline = testlines.pop(0) try: line = f.read(len(testline)) except ValueError: self.fail("read() after next() with supposedly empty " "iteration-buffer failed anyway") if line != testline: self.fail("read() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) try: lines = f.readlines() except ValueError: self.fail("readlines() after next() with supposedly empty " "iteration-buffer failed anyway") if lines != testlines: self.fail("readlines() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) f.close() # Reading after iteration hit EOF shouldn't hurt either f = self.open(TESTFN, 'rb') try: for line in f: pass try: f.readline() f.readinto(buf) f.read() f.readlines() except ValueError: self.fail("read* failed after next() consumed file") finally: f.close() class COtherFileTests(OtherFileTests, unittest.TestCase): open = io.open class PyOtherFileTests(OtherFileTests, unittest.TestCase): open = staticmethod(pyio.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_marshal.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_marshal.py
from test import support import array import io import marshal import sys import unittest import os import types try: import _testcapi except ImportError: _testcapi = None class HelperMixin: def helper(self, sample, *extra): new = marshal.loads(marshal.dumps(sample, *extra)) self.assertEqual(sample, new) try: with open(support.TESTFN, "wb") as f: marshal.dump(sample, f, *extra) with open(support.TESTFN, "rb") as f: new = marshal.load(f) self.assertEqual(sample, new) finally: support.unlink(support.TESTFN) class IntTestCase(unittest.TestCase, HelperMixin): def test_ints(self): # Test a range of Python ints larger than the machine word size. n = sys.maxsize ** 2 while n: for expected in (-n, n): self.helper(expected) n = n >> 1 def test_int64(self): # Simulate int marshaling with TYPE_INT64. maxint64 = (1 << 63) - 1 minint64 = -maxint64-1 for base in maxint64, minint64, -maxint64, -(minint64 >> 1): while base: s = b'I' + int.to_bytes(base, 8, 'little', signed=True) got = marshal.loads(s) self.assertEqual(base, got) if base == -1: # a fixed-point for shifting right 1 base = 0 else: base >>= 1 got = marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10') self.assertEqual(got, 0x1032547698badcfe) got = marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef') self.assertEqual(got, -0x1032547698badcff) got = marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f') self.assertEqual(got, 0x7f6e5d4c3b2a1908) got = marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80') self.assertEqual(got, -0x7f6e5d4c3b2a1909) def test_bool(self): for b in (True, False): self.helper(b) class FloatTestCase(unittest.TestCase, HelperMixin): def test_floats(self): # Test a few floats small = 1e-25 n = sys.maxsize * 3.7e250 while n > small: for expected in (-n, n): self.helper(float(expected)) n /= 123.4567 f = 0.0 s = marshal.dumps(f, 2) got = marshal.loads(s) self.assertEqual(f, got) # and with version <= 1 (floats marshalled differently then) s = marshal.dumps(f, 1) got = marshal.loads(s) self.assertEqual(f, got) n = sys.maxsize * 3.7e-250 while n < small: for expected in (-n, n): f = float(expected) self.helper(f) self.helper(f, 1) n *= 123.4567 class StringTestCase(unittest.TestCase, HelperMixin): def test_unicode(self): for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: self.helper(marshal.loads(marshal.dumps(s))) def test_string(self): for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: self.helper(s) def test_bytes(self): for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]: self.helper(s) class ExceptionTestCase(unittest.TestCase): def test_exceptions(self): new = marshal.loads(marshal.dumps(StopIteration)) self.assertEqual(StopIteration, new) class CodeTestCase(unittest.TestCase): def test_code(self): co = ExceptionTestCase.test_exceptions.__code__ new = marshal.loads(marshal.dumps(co)) self.assertEqual(co, new) def test_many_codeobjects(self): # Issue2957: bad recursion count on code objects count = 5000 # more than MAX_MARSHAL_STACK_DEPTH codes = (ExceptionTestCase.test_exceptions.__code__,) * count marshal.loads(marshal.dumps(codes)) def test_different_filenames(self): co1 = compile("x", "f1", "exec") co2 = compile("y", "f2", "exec") co1, co2 = marshal.loads(marshal.dumps((co1, co2))) self.assertEqual(co1.co_filename, "f1") self.assertEqual(co2.co_filename, "f2") @support.cpython_only def test_same_filename_used(self): s = """def f(): pass\ndef g(): pass""" co = compile(s, "myfile", "exec") co = marshal.loads(marshal.dumps(co)) for obj in co.co_consts: if isinstance(obj, types.CodeType): self.assertIs(co.co_filename, obj.co_filename) class ContainerTestCase(unittest.TestCase, HelperMixin): d = {'astring': 'foo@bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, 'ashortlong': 2, 'alist': ['.zyx.41'], 'atuple': ('.zyx.41',)*10, 'aboolean': False, 'aunicode': "Andr\xe8 Previn" } def test_dict(self): self.helper(self.d) def test_list(self): self.helper(list(self.d.items())) def test_tuple(self): self.helper(tuple(self.d.keys())) def test_sets(self): for constructor in (set, frozenset): self.helper(constructor(self.d.keys())) @support.cpython_only def test_empty_frozenset_singleton(self): # marshal.loads() must reuse the empty frozenset singleton obj = frozenset() obj2 = marshal.loads(marshal.dumps(obj)) self.assertIs(obj2, obj) class BufferTestCase(unittest.TestCase, HelperMixin): def test_bytearray(self): b = bytearray(b"abc") self.helper(b) new = marshal.loads(marshal.dumps(b)) self.assertEqual(type(new), bytes) def test_memoryview(self): b = memoryview(b"abc") self.helper(b) new = marshal.loads(marshal.dumps(b)) self.assertEqual(type(new), bytes) def test_array(self): a = array.array('B', b"abc") new = marshal.loads(marshal.dumps(a)) self.assertEqual(new, b"abc") class BugsTestCase(unittest.TestCase): def test_bug_5888452(self): # Simple-minded check for SF 588452: Debug build crashes marshal.dumps([128] * 1000) def test_patch_873224(self): self.assertRaises(Exception, marshal.loads, b'0') self.assertRaises(Exception, marshal.loads, b'f') self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1]) def test_version_argument(self): # Python 2.4.0 crashes for any call to marshal.dumps(x, y) self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5) self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5) def test_fuzz(self): # simple test that it's at least not *totally* trivial to # crash from bad marshal data for i in range(256): c = bytes([i]) try: marshal.loads(c) except Exception: pass def test_loads_recursion(self): def run_tests(N, check): # (((...None...),),) check(b')\x01' * N + b'N') check(b'(\x01\x00\x00\x00' * N + b'N') # [[[...None...]]] check(b'[\x01\x00\x00\x00' * N + b'N') # {None: {None: {None: ...None...}}} check(b'{N' * N + b'N' + b'0' * N) # frozenset([frozenset([frozenset([...None...])])]) check(b'>\x01\x00\x00\x00' * N + b'N') # Check that the generated marshal data is valid and marshal.loads() # works for moderately deep nesting run_tests(100, marshal.loads) # Very deeply nested structure shouldn't blow the stack def check(s): self.assertRaises(ValueError, marshal.loads, s) run_tests(2**20, check) def test_recursion_limit(self): # Create a deeply nested structure. head = last = [] # The max stack depth should match the value in Python/marshal.c. # BUG: https://bugs.python.org/issue33720 # Windows always limits the maximum depth on release and debug builds #if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'): if os.name == 'nt': MAX_MARSHAL_STACK_DEPTH = 1000 else: MAX_MARSHAL_STACK_DEPTH = 2000 for i in range(MAX_MARSHAL_STACK_DEPTH - 2): last.append([0]) last = last[-1] # Verify we don't blow out the stack with dumps/load. data = marshal.dumps(head) new_head = marshal.loads(data) # Don't use == to compare objects, it can exceed the recursion limit. self.assertEqual(len(new_head), len(head)) self.assertEqual(len(new_head[0]), len(head[0])) self.assertEqual(len(new_head[-1]), len(head[-1])) last.append([0]) self.assertRaises(ValueError, marshal.dumps, head) def test_exact_type_match(self): # Former bug: # >>> class Int(int): pass # >>> type(loads(dumps(Int()))) # <type 'int'> for typ in (int, float, complex, tuple, list, dict, set, frozenset): # Note: str subclasses are not tested because they get handled # by marshal's routines for objects supporting the buffer API. subtyp = type('subtyp', (typ,), {}) self.assertRaises(ValueError, marshal.dumps, subtyp()) # Issue #1792 introduced a change in how marshal increases the size of its # internal buffer; this test ensures that the new code is exercised. def test_large_marshal(self): size = int(1e6) testString = 'abc' * size marshal.dumps(testString) def test_invalid_longs(self): # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00' self.assertRaises(ValueError, marshal.loads, invalid_string) def test_multiple_dumps_and_loads(self): # Issue 12291: marshal.load() should be callable multiple times # with interleaved data written by non-marshal code # Adapted from a patch by Engelbert Gruber. data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c'])) for interleaved in (b'', b'0123'): ilen = len(interleaved) positions = [] try: with open(support.TESTFN, 'wb') as f: for d in data: marshal.dump(d, f) if ilen: f.write(interleaved) positions.append(f.tell()) with open(support.TESTFN, 'rb') as f: for i, d in enumerate(data): self.assertEqual(d, marshal.load(f)) if ilen: f.read(ilen) self.assertEqual(positions[i], f.tell()) finally: support.unlink(support.TESTFN) def test_loads_reject_unicode_strings(self): # Issue #14177: marshal.loads() should not accept unicode strings unicode_string = 'T' self.assertRaises(TypeError, marshal.loads, unicode_string) def test_bad_reader(self): class BadReader(io.BytesIO): def readinto(self, buf): n = super().readinto(buf) if n is not None and n > 4: n += 10**6 return n for value in (1.0, 1j, b'0123456789', '0123456789'): self.assertRaises(ValueError, marshal.load, BadReader(marshal.dumps(value))) def test_eof(self): data = marshal.dumps(("hello", "dolly", None)) for i in range(len(data)): self.assertRaises(EOFError, marshal.loads, data[0: i]) LARGE_SIZE = 2**31 pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4 class NullWriter: def write(self, s): pass @unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems") class LargeValuesTestCase(unittest.TestCase): def check_unmarshallable(self, data): self.assertRaises(ValueError, marshal.dump, data, NullWriter()) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_bytes(self, size): self.check_unmarshallable(b'x' * size) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_str(self, size): self.check_unmarshallable('x' * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) def test_tuple(self, size): self.check_unmarshallable((None,) * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) def test_list(self, size): self.check_unmarshallable([None] * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), dry_run=False) def test_set(self, size): self.check_unmarshallable(set(range(size))) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), dry_run=False) def test_frozenset(self, size): self.check_unmarshallable(frozenset(range(size))) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_bytearray(self, size): self.check_unmarshallable(bytearray(size)) def CollectObjectIDs(ids, obj): """Collect object ids seen in a structure""" if id(obj) in ids: return ids.add(id(obj)) if isinstance(obj, (list, tuple, set, frozenset)): for e in obj: CollectObjectIDs(ids, e) elif isinstance(obj, dict): for k, v in obj.items(): CollectObjectIDs(ids, k) CollectObjectIDs(ids, v) return len(ids) class InstancingTestCase(unittest.TestCase, HelperMixin): intobj = 123321 floatobj = 1.2345 strobj = "abcde"*3 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"} def helper3(self, rsample, recursive=False, simple=False): #we have two instances sample = (rsample, rsample) n0 = CollectObjectIDs(set(), sample) s3 = marshal.dumps(sample, 3) n3 = CollectObjectIDs(set(), marshal.loads(s3)) #same number of instances generated self.assertEqual(n3, n0) if not recursive: #can compare with version 2 s2 = marshal.dumps(sample, 2) n2 = CollectObjectIDs(set(), marshal.loads(s2)) #old format generated more instances self.assertGreater(n2, n0) #if complex objects are in there, old format is larger if not simple: self.assertGreater(len(s2), len(s3)) else: self.assertGreaterEqual(len(s2), len(s3)) def testInt(self): self.helper(self.intobj) self.helper3(self.intobj, simple=True) def testFloat(self): self.helper(self.floatobj) self.helper3(self.floatobj) def testStr(self): self.helper(self.strobj) self.helper3(self.strobj) def testDict(self): self.helper(self.dictobj) self.helper3(self.dictobj) def testModule(self): with open(__file__, "rb") as f: code = f.read() if __file__.endswith(".py"): code = compile(code, __file__, "exec") self.helper(code) self.helper3(code) def testRecursion(self): d = dict(self.dictobj) d["self"] = d self.helper3(d, recursive=True) l = [self.dictobj] l.append(l) self.helper3(l, recursive=True) class CompatibilityTestCase(unittest.TestCase): def _test(self, version): with open(__file__, "rb") as f: code = f.read() if __file__.endswith(".py"): code = compile(code, __file__, "exec") data = marshal.dumps(code, version) marshal.loads(data) def test0To3(self): self._test(0) def test1To3(self): self._test(1) def test2To3(self): self._test(2) def test3To3(self): self._test(3) class InterningTestCase(unittest.TestCase, HelperMixin): strobj = "this is an interned string" strobj = sys.intern(strobj) def testIntern(self): s = marshal.loads(marshal.dumps(self.strobj)) self.assertEqual(s, self.strobj) self.assertEqual(id(s), id(self.strobj)) s2 = sys.intern(s) self.assertEqual(id(s2), id(s)) def testNoIntern(self): s = marshal.loads(marshal.dumps(self.strobj, 2)) self.assertEqual(s, self.strobj) self.assertNotEqual(id(s), id(self.strobj)) s2 = sys.intern(s) self.assertNotEqual(id(s2), id(s)) @support.cpython_only @unittest.skipUnless(_testcapi, 'requires _testcapi') class CAPI_TestCase(unittest.TestCase, HelperMixin): def test_write_long_to_file(self): for v in range(marshal.version + 1): _testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v) with open(support.TESTFN, 'rb') as f: data = f.read() support.unlink(support.TESTFN) self.assertEqual(data, b'\x78\x56\x34\x12') def test_write_object_to_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000) for v in range(marshal.version + 1): _testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v) with open(support.TESTFN, 'rb') as f: data = f.read() support.unlink(support.TESTFN) self.assertEqual(marshal.loads(data), obj) def test_read_short_from_file(self): with open(support.TESTFN, 'wb') as f: f.write(b'\x34\x12xxxx') r, p = _testcapi.pymarshal_read_short_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, 0x1234) self.assertEqual(p, 2) with open(support.TESTFN, 'wb') as f: f.write(b'\x12') with self.assertRaises(EOFError): _testcapi.pymarshal_read_short_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_long_from_file(self): with open(support.TESTFN, 'wb') as f: f.write(b'\x78\x56\x34\x12xxxx') r, p = _testcapi.pymarshal_read_long_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, 0x12345678) self.assertEqual(p, 4) with open(support.TESTFN, 'wb') as f: f.write(b'\x56\x34\x12') with self.assertRaises(EOFError): _testcapi.pymarshal_read_long_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_last_object_from_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) for v in range(marshal.version + 1): data = marshal.dumps(obj, v) with open(support.TESTFN, 'wb') as f: f.write(data + b'xxxx') r, p = _testcapi.pymarshal_read_last_object_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, obj) with open(support.TESTFN, 'wb') as f: f.write(data[:1]) with self.assertRaises(EOFError): _testcapi.pymarshal_read_last_object_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_object_from_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) for v in range(marshal.version + 1): data = marshal.dumps(obj, v) with open(support.TESTFN, 'wb') as f: f.write(data + b'xxxx') r, p = _testcapi.pymarshal_read_object_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, obj) self.assertEqual(p, len(data)) with open(support.TESTFN, 'wb') as f: f.write(data[:1]) with self.assertRaises(EOFError): _testcapi.pymarshal_read_object_from_file(support.TESTFN) support.unlink(support.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_index.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_index.py
import unittest from test import support import operator maxsize = support.MAX_Py_ssize_t class newstyle: def __index__(self): return self.ind class TrapInt(int): def __index__(self): return int(self) class BaseTestCase(unittest.TestCase): def setUp(self): self.o = newstyle() self.n = newstyle() def test_basic(self): self.o.ind = -2 self.n.ind = 2 self.assertEqual(operator.index(self.o), -2) self.assertEqual(operator.index(self.n), 2) def test_slice(self): self.o.ind = 1 self.n.ind = 2 slc = slice(self.o, self.o, self.o) check_slc = slice(1, 1, 1) self.assertEqual(slc.indices(self.o), check_slc.indices(1)) slc = slice(self.n, self.n, self.n) check_slc = slice(2, 2, 2) self.assertEqual(slc.indices(self.n), check_slc.indices(2)) def test_wrappers(self): self.o.ind = 4 self.n.ind = 5 self.assertEqual(6 .__index__(), 6) self.assertEqual(-7 .__index__(), -7) self.assertEqual(self.o.__index__(), 4) self.assertEqual(self.n.__index__(), 5) self.assertEqual(True.__index__(), 1) self.assertEqual(False.__index__(), 0) def test_subclasses(self): r = list(range(10)) self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10]) self.assertEqual(slice(TrapInt()).indices(0), (0,0,1)) def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' self.assertRaises(TypeError, operator.index, self.o) self.assertRaises(TypeError, operator.index, self.n) self.assertRaises(TypeError, slice(self.o).indices, 0) self.assertRaises(TypeError, slice(self.n).indices, 0) def test_int_subclass_with_index(self): # __index__ should be used when computing indices, even for int # subclasses. See issue #17576. class MyInt(int): def __index__(self): return int(self) + 1 my_int = MyInt(7) direct_index = my_int.__index__() operator_index = operator.index(my_int) self.assertEqual(direct_index, 8) self.assertEqual(operator_index, 7) # Both results should be of exact type int. self.assertIs(type(direct_index), int) #self.assertIs(type(operator_index), int) def test_index_returns_int_subclass(self): class BadInt: def __index__(self): return True class BadInt2(int): def __index__(self): return True bad_int = BadInt() with self.assertWarns(DeprecationWarning): n = operator.index(bad_int) self.assertEqual(n, 1) bad_int = BadInt2() n = operator.index(bad_int) self.assertEqual(n, 0) class SeqTestCase: # This test case isn't run directly. It just defines common tests # to the different sequence types below def setUp(self): self.o = newstyle() self.n = newstyle() self.o2 = newstyle() self.n2 = newstyle() def test_index(self): self.o.ind = -2 self.n.ind = 2 self.assertEqual(self.seq[self.n], self.seq[2]) self.assertEqual(self.seq[self.o], self.seq[-2]) def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 self.assertEqual(self.seq[self.o:self.o2], self.seq[1:3]) self.assertEqual(self.seq[self.n:self.n2], self.seq[2:4]) def test_slice_bug7532(self): seqlen = len(self.seq) self.o.ind = int(seqlen * 1.5) self.n.ind = seqlen + 2 self.assertEqual(self.seq[self.o:], self.seq[0:0]) self.assertEqual(self.seq[:self.o], self.seq) self.assertEqual(self.seq[self.n:], self.seq[0:0]) self.assertEqual(self.seq[:self.n], self.seq) self.o2.ind = -seqlen - 2 self.n2.ind = -int(seqlen * 1.5) self.assertEqual(self.seq[self.o2:], self.seq) self.assertEqual(self.seq[:self.o2], self.seq[0:0]) self.assertEqual(self.seq[self.n2:], self.seq) self.assertEqual(self.seq[:self.n2], self.seq[0:0]) def test_repeat(self): self.o.ind = 3 self.n.ind = 2 self.assertEqual(self.seq * self.o, self.seq * 3) self.assertEqual(self.seq * self.n, self.seq * 2) self.assertEqual(self.o * self.seq, self.seq * 3) self.assertEqual(self.n * self.seq, self.seq * 2) def test_wrappers(self): self.o.ind = 4 self.n.ind = 5 self.assertEqual(self.seq.__getitem__(self.o), self.seq[4]) self.assertEqual(self.seq.__mul__(self.o), self.seq * 4) self.assertEqual(self.seq.__rmul__(self.o), self.seq * 4) self.assertEqual(self.seq.__getitem__(self.n), self.seq[5]) self.assertEqual(self.seq.__mul__(self.n), self.seq * 5) self.assertEqual(self.seq.__rmul__(self.n), self.seq * 5) def test_subclasses(self): self.assertEqual(self.seq[TrapInt()], self.seq[0]) def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' indexobj = lambda x, obj: obj.seq[x] self.assertRaises(TypeError, indexobj, self.o, self) self.assertRaises(TypeError, indexobj, self.n, self) sliceobj = lambda x, obj: obj.seq[x:] self.assertRaises(TypeError, sliceobj, self.o, self) self.assertRaises(TypeError, sliceobj, self.n, self) class ListTestCase(SeqTestCase, unittest.TestCase): seq = [0,10,20,30,40,50] def test_setdelitem(self): self.o.ind = -2 self.n.ind = 2 lst = list('ab!cdefghi!j') del lst[self.o] del lst[self.n] lst[self.o] = 'X' lst[self.n] = 'Y' self.assertEqual(lst, list('abYdefghXj')) lst = [5, 6, 7, 8, 9, 10, 11] lst.__setitem__(self.n, "here") self.assertEqual(lst, [5, 6, "here", 8, 9, 10, 11]) lst.__delitem__(self.n) self.assertEqual(lst, [5, 6, 8, 9, 10, 11]) def test_inplace_repeat(self): self.o.ind = 2 self.n.ind = 3 lst = [6, 4] lst *= self.o self.assertEqual(lst, [6, 4, 6, 4]) lst *= self.n self.assertEqual(lst, [6, 4, 6, 4] * 3) lst = [5, 6, 7, 8, 9, 11] l2 = lst.__imul__(self.n) self.assertIs(l2, lst) self.assertEqual(lst, [5, 6, 7, 8, 9, 11] * 3) class NewSeq: def __init__(self, iterable): self._list = list(iterable) def __repr__(self): return repr(self._list) def __eq__(self, other): return self._list == other def __len__(self): return len(self._list) def __mul__(self, n): return self.__class__(self._list*n) __rmul__ = __mul__ def __getitem__(self, index): return self._list[index] class TupleTestCase(SeqTestCase, unittest.TestCase): seq = (0,10,20,30,40,50) class ByteArrayTestCase(SeqTestCase, unittest.TestCase): seq = bytearray(b"this is a test") class BytesTestCase(SeqTestCase, unittest.TestCase): seq = b"this is a test" class StringTestCase(SeqTestCase, unittest.TestCase): seq = "this is a test" class NewSeqTestCase(SeqTestCase, unittest.TestCase): seq = NewSeq((0,10,20,30,40,50)) class RangeTestCase(unittest.TestCase): def test_range(self): n = newstyle() n.ind = 5 self.assertEqual(range(1, 20)[n], 6) self.assertEqual(range(1, 20).__getitem__(n), 6) class OverflowTestCase(unittest.TestCase): def setUp(self): self.pos = 2**100 self.neg = -self.pos def test_large_longs(self): self.assertEqual(self.pos.__index__(), self.pos) self.assertEqual(self.neg.__index__(), self.neg) def test_getitem(self): class GetItem: def __len__(self): assert False, "__len__ should not be invoked" def __getitem__(self, key): return key x = GetItem() self.assertEqual(x[self.pos], self.pos) self.assertEqual(x[self.neg], self.neg) self.assertEqual(x[self.neg:self.pos].indices(maxsize), (0, maxsize, 1)) self.assertEqual(x[self.neg:self.pos:1].indices(maxsize), (0, maxsize, 1)) def test_sequence_repeat(self): self.assertRaises(OverflowError, lambda: "a" * self.pos) self.assertRaises(OverflowError, lambda: "a" * self.neg) 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/regrtest.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/regrtest.py
#! /usr/bin/env python3 """ Script to run Python regression tests. Run this script with -h or --help for documentation. """ # We import importlib *ASAP* in order to test #15386 import importlib import os import sys from test.libregrtest import main # Alias for backward compatibility (just in case) main_in_temp_cwd = main def _main(): global __file__ # Remove regrtest.py's own directory from the module search path. Despite # the elimination of implicit relative imports, this is still needed to # ensure that submodules of the test package do not inappropriately appear # as top-level modules even when people (or buildbots!) invoke regrtest.py # directly instead of using the -m switch mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0]))) i = len(sys.path) - 1 while i >= 0: if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: del sys.path[i] else: i -= 1 # findtestdir() gets the dirname out of __file__, so we have to make it # absolute before changing the working directory. # For example __file__ may be relative when running trace or profile. # See issue #9323. __file__ = os.path.abspath(__file__) # sanity check assert __file__ == os.path.abspath(sys.argv[0]) main() if __name__ == '__main__': _main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/gdb_sample.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/gdb_sample.py
# Sample script for use by test_gdb.py def foo(a, b, c): bar(a, b, c) def bar(a, b, c): baz(a, b, c) def baz(*args): id(42) foo(1, 2, 3)
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_etree_c.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree_c.py
# xml.etree test for cElementTree import io import struct from test import support from test.support import import_fresh_module import types import unittest cET = import_fresh_module('xml.etree.ElementTree', fresh=['_elementtree']) cET_alias = import_fresh_module('xml.etree.cElementTree', fresh=['_elementtree', 'xml.etree'], deprecated=True) @unittest.skipUnless(cET, 'requires _elementtree') class MiscTests(unittest.TestCase): # Issue #8651. @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False) def test_length_overflow(self, size): data = b'x' * size parser = cET.XMLParser() try: self.assertRaises(OverflowError, parser.feed, data) finally: data = None def test_del_attribute(self): element = cET.Element('tag') element.tag = 'TAG' with self.assertRaises(AttributeError): del element.tag self.assertEqual(element.tag, 'TAG') with self.assertRaises(AttributeError): del element.text self.assertIsNone(element.text) element.text = 'TEXT' with self.assertRaises(AttributeError): del element.text self.assertEqual(element.text, 'TEXT') with self.assertRaises(AttributeError): del element.tail self.assertIsNone(element.tail) element.tail = 'TAIL' with self.assertRaises(AttributeError): del element.tail self.assertEqual(element.tail, 'TAIL') with self.assertRaises(AttributeError): del element.attrib self.assertEqual(element.attrib, {}) element.attrib = {'A': 'B', 'C': 'D'} with self.assertRaises(AttributeError): del element.attrib self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'}) def test_trashcan(self): # If this test fails, it will most likely die via segfault. e = root = cET.Element('root') for i in range(200000): e = cET.SubElement(e, 'x') del e del root support.gc_collect() def test_parser_ref_cycle(self): # bpo-31499: xmlparser_dealloc() crashed with a segmentation fault when # xmlparser_gc_clear() was called previously by the garbage collector, # when the parser was part of a reference cycle. def parser_ref_cycle(): parser = cET.XMLParser() # Create a reference cycle using an exception to keep the frame # alive, so the parser will be destroyed by the garbage collector try: raise ValueError except ValueError as exc: err = exc # Create a parser part of reference cycle parser_ref_cycle() # Trigger an explicit garbage collection to break the reference cycle # and so destroy the parser support.gc_collect() def test_bpo_31728(self): # A crash or an assertion failure shouldn't happen, in case garbage # collection triggers a call to clear() or a reading of text or tail, # while a setter or clear() or __setstate__() is already running. elem = cET.Element('elem') class X: def __del__(self): elem.text elem.tail elem.clear() elem.text = X() elem.clear() # shouldn't crash elem.tail = X() elem.clear() # shouldn't crash elem.text = X() elem.text = X() # shouldn't crash elem.clear() elem.tail = X() elem.tail = X() # shouldn't crash elem.clear() elem.text = X() elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure elem.clear() elem.tail = X() elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure def test_setstate_leaks(self): # Test reference leaks elem = cET.Element.__new__(cET.Element) for i in range(100): elem.__setstate__({'tag': 'foo', 'attrib': {'bar': 42}, '_children': [cET.Element('child')], 'text': 'text goes here', 'tail': 'opposite of head'}) self.assertEqual(elem.tag, 'foo') self.assertEqual(elem.text, 'text goes here') self.assertEqual(elem.tail, 'opposite of head') self.assertEqual(list(elem.attrib.items()), [('bar', 42)]) self.assertEqual(len(elem), 1) self.assertEqual(elem[0].tag, 'child') def test_iterparse_leaks(self): # Test reference leaks in TreeBuilder (issue #35502). # The test is written to be executed in the hunting reference leaks # mode. XML = '<a></a></b>' parser = cET.iterparse(io.StringIO(XML)) next(parser) del parser support.gc_collect() def test_xmlpullparser_leaks(self): # Test reference leaks in TreeBuilder (issue #35502). # The test is written to be executed in the hunting reference leaks # mode. XML = '<a></a></b>' parser = cET.XMLPullParser() parser.feed(XML) del parser support.gc_collect() @unittest.skipUnless(cET, 'requires _elementtree') class TestAliasWorking(unittest.TestCase): # Test that the cET alias module is alive def test_alias_working(self): e = cET_alias.Element('foo') self.assertEqual(e.tag, 'foo') @unittest.skipUnless(cET, 'requires _elementtree') @support.cpython_only class TestAcceleratorImported(unittest.TestCase): # Test that the C accelerator was imported, as expected def test_correct_import_cET(self): # SubElement is a function so it retains _elementtree as its module. self.assertEqual(cET.SubElement.__module__, '_elementtree') def test_correct_import_cET_alias(self): self.assertEqual(cET_alias.SubElement.__module__, '_elementtree') def test_parser_comes_from_C(self): # The type of methods defined in Python code is types.FunctionType, # while the type of methods defined inside _elementtree is # <class 'wrapper_descriptor'> self.assertNotIsInstance(cET.Element.__init__, types.FunctionType) @unittest.skipUnless(cET, 'requires _elementtree') @support.cpython_only class SizeofTest(unittest.TestCase): def setUp(self): self.elementsize = support.calcobjsize('5P') # extra self.extra = struct.calcsize('PnnP4P') check_sizeof = support.check_sizeof def test_element(self): e = cET.Element('a') self.check_sizeof(e, self.elementsize) def test_element_with_attrib(self): e = cET.Element('a', href='about:') self.check_sizeof(e, self.elementsize + self.extra) def test_element_with_children(self): e = cET.Element('a') for i in range(5): cET.SubElement(e, 'span') # should have space for 8 children now self.check_sizeof(e, self.elementsize + self.extra + struct.calcsize('8P')) def test_main(): from test import test_xml_etree # Run the tests specific to the C implementation support.run_unittest( MiscTests, TestAliasWorking, TestAcceleratorImported, SizeofTest, ) # Run the same test suite as the Python module test_xml_etree.test_main(module=cET) 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_sunau.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sunau.py
import unittest from test import audiotests from audioop import byteswap import io import struct import sys import sunau class SunauTest(audiotests.AudioWriteTests, audiotests.AudioTestsWithSourceFile): module = sunau class SunauPCM8Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm8.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 1 framerate = 11025 nframes = 48 comptype = 'NONE' compname = '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 SunauPCM16Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm16.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ 022EFFEA 4B5C00F9 311404EF 80DB0844 CBE006B0 48AB03F3 BFE601B5 0367FE80 \ B853FA42 B4AFF351 2997EBCD 1A5AE6DC EDF9E492 C627E277 0E06E0B7 EF29E029 \ 5759E271 FB34E83F 1377EF85 D82CF727 978EFB79 F5F7FC12 0864FB9E DF30FB40 \ 1183FA30 3EEAFB59 BC78FCB4 66D5FF60 CF130415 431A097D C1BA0EC7 512312A0 \ EEE11754 82071666 7FFE1448 80001298 49990EB7 52B40DC1 EFAD0F65 CE3A0FBE \ E4B70CE6 63490A57 08CC0A1D 2BBC0B09 51480E46 8BCB113C B6F60EE9 44150A5A \ """) class SunauPCM24Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm24.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 3 framerate = 11025 nframes = 48 comptype = 'NONE' compname = '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 SunauPCM32Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm32.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 4 framerate = 11025 nframes = 48 comptype = 'NONE' compname = '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 SunauULAWTest(SunauTest, unittest.TestCase): sndfilename = 'pluck-ulaw.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = 'ULAW' compname = 'CCITT G.711 u-law' frames = bytes.fromhex("""\ 022CFFE8 497C00F4 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 417C09BC 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 SunauMiscTests(audiotests.AudioMiscTests, unittest.TestCase): module = sunau class SunauLowLevelTest(unittest.TestCase): def test_read_bad_magic_number(self): b = b'SPA' with self.assertRaises(EOFError): sunau.open(io.BytesIO(b)) b = b'SPAM' with self.assertRaisesRegex(sunau.Error, 'bad magic number'): sunau.open(io.BytesIO(b)) def test_read_too_small_header(self): b = struct.pack('>LLLLL', sunau.AUDIO_FILE_MAGIC, 20, 0, sunau.AUDIO_FILE_ENCODING_LINEAR_8, 11025) with self.assertRaisesRegex(sunau.Error, 'header size too small'): sunau.open(io.BytesIO(b)) def test_read_too_large_header(self): b = struct.pack('>LLLLLL', sunau.AUDIO_FILE_MAGIC, 124, 0, sunau.AUDIO_FILE_ENCODING_LINEAR_8, 11025, 1) b += b'\0' * 100 with self.assertRaisesRegex(sunau.Error, 'header size ridiculously large'): sunau.open(io.BytesIO(b)) def test_read_wrong_encoding(self): b = struct.pack('>LLLLLL', sunau.AUDIO_FILE_MAGIC, 24, 0, 0, 11025, 1) with self.assertRaisesRegex(sunau.Error, r'encoding not \(yet\) supported'): sunau.open(io.BytesIO(b)) def test_read_wrong_number_of_channels(self): b = struct.pack('>LLLLLL', sunau.AUDIO_FILE_MAGIC, 24, 0, sunau.AUDIO_FILE_ENCODING_LINEAR_8, 11025, 0) with self.assertRaisesRegex(sunau.Error, 'bad # of channels'): sunau.open(io.BytesIO(b)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/audiotests.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/audiotests.py
from test.support import findfile, TESTFN, unlink import array import io from unittest import mock import pickle class UnseekableIO(io.FileIO): def tell(self): raise io.UnsupportedOperation def seek(self, *args, **kwargs): raise io.UnsupportedOperation class AudioTests: close_fd = False def setUp(self): self.f = self.fout = None def tearDown(self): if self.f is not None: self.f.close() if self.fout is not None: self.fout.close() unlink(TESTFN) def check_params(self, f, nchannels, sampwidth, framerate, nframes, comptype, compname): self.assertEqual(f.getnchannels(), nchannels) self.assertEqual(f.getsampwidth(), sampwidth) self.assertEqual(f.getframerate(), framerate) self.assertEqual(f.getnframes(), nframes) self.assertEqual(f.getcomptype(), comptype) self.assertEqual(f.getcompname(), compname) params = f.getparams() self.assertEqual(params, (nchannels, sampwidth, framerate, nframes, comptype, compname)) self.assertEqual(params.nchannels, nchannels) self.assertEqual(params.sampwidth, sampwidth) self.assertEqual(params.framerate, framerate) self.assertEqual(params.nframes, nframes) self.assertEqual(params.comptype, comptype) self.assertEqual(params.compname, compname) for proto in range(pickle.HIGHEST_PROTOCOL + 1): dump = pickle.dumps(params, proto) self.assertEqual(pickle.loads(dump), params) class AudioMiscTests(AudioTests): def test_openfp_deprecated(self): arg = "arg" mode = "mode" with mock.patch(f"{self.module.__name__}.open") as mock_open, \ self.assertWarns(DeprecationWarning): self.module.openfp(arg, mode=mode) mock_open.assert_called_with(arg, mode=mode) class AudioWriteTests(AudioTests): def create_file(self, testfile): f = self.fout = self.module.open(testfile, 'wb') f.setnchannels(self.nchannels) f.setsampwidth(self.sampwidth) f.setframerate(self.framerate) f.setcomptype(self.comptype, self.compname) return f def check_file(self, testfile, nframes, frames): with self.module.open(testfile, 'rb') as f: self.assertEqual(f.getnchannels(), self.nchannels) self.assertEqual(f.getsampwidth(), self.sampwidth) self.assertEqual(f.getframerate(), self.framerate) self.assertEqual(f.getnframes(), nframes) self.assertEqual(f.readframes(nframes), frames) def test_write_params(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(self.frames) self.check_params(f, self.nchannels, self.sampwidth, self.framerate, self.nframes, self.comptype, self.compname) f.close() def test_write_context_manager_calls_close(self): # Close checks for a minimum header and will raise an error # if it is not set, so this proves that close is called. with self.assertRaises(self.module.Error): with self.module.open(TESTFN, 'wb'): pass with self.assertRaises(self.module.Error): with open(TESTFN, 'wb') as testfile: with self.module.open(testfile): pass def test_context_manager_with_open_file(self): with open(TESTFN, 'wb') as testfile: with self.module.open(testfile) as f: f.setnchannels(self.nchannels) f.setsampwidth(self.sampwidth) f.setframerate(self.framerate) f.setcomptype(self.comptype, self.compname) self.assertEqual(testfile.closed, self.close_fd) with open(TESTFN, 'rb') as testfile: with self.module.open(testfile) as f: self.assertFalse(f.getfp().closed) params = f.getparams() self.assertEqual(params.nchannels, self.nchannels) self.assertEqual(params.sampwidth, self.sampwidth) self.assertEqual(params.framerate, self.framerate) if not self.close_fd: self.assertIsNone(f.getfp()) self.assertEqual(testfile.closed, self.close_fd) def test_context_manager_with_filename(self): # If the file doesn't get closed, this test won't fail, but it will # produce a resource leak warning. with self.module.open(TESTFN, 'wb') as f: f.setnchannels(self.nchannels) f.setsampwidth(self.sampwidth) f.setframerate(self.framerate) f.setcomptype(self.comptype, self.compname) with self.module.open(TESTFN) as f: self.assertFalse(f.getfp().closed) params = f.getparams() self.assertEqual(params.nchannels, self.nchannels) self.assertEqual(params.sampwidth, self.sampwidth) self.assertEqual(params.framerate, self.framerate) if not self.close_fd: self.assertIsNone(f.getfp()) def test_write(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(self.frames) f.close() self.check_file(TESTFN, self.nframes, self.frames) def test_write_bytearray(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(bytearray(self.frames)) f.close() self.check_file(TESTFN, self.nframes, self.frames) def test_write_array(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(array.array('h', self.frames)) f.close() self.check_file(TESTFN, self.nframes, self.frames) def test_write_memoryview(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(memoryview(self.frames)) f.close() self.check_file(TESTFN, self.nframes, self.frames) def test_incompleted_write(self): with open(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') f = self.create_file(testfile) f.setnframes(self.nframes + 1) f.writeframes(self.frames) f.close() with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') self.check_file(testfile, self.nframes, self.frames) def test_multiple_writes(self): with open(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') f = self.create_file(testfile) f.setnframes(self.nframes) framesize = self.nchannels * self.sampwidth f.writeframes(self.frames[:-framesize]) f.writeframes(self.frames[-framesize:]) f.close() with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') self.check_file(testfile, self.nframes, self.frames) def test_overflowed_write(self): with open(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') f = self.create_file(testfile) f.setnframes(self.nframes - 1) f.writeframes(self.frames) f.close() with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') self.check_file(testfile, self.nframes, self.frames) def test_unseekable_read(self): with self.create_file(TESTFN) as f: f.setnframes(self.nframes) f.writeframes(self.frames) with UnseekableIO(TESTFN, 'rb') as testfile: self.check_file(testfile, self.nframes, self.frames) def test_unseekable_write(self): with UnseekableIO(TESTFN, 'wb') as testfile: with self.create_file(testfile) as f: f.setnframes(self.nframes) f.writeframes(self.frames) self.check_file(TESTFN, self.nframes, self.frames) def test_unseekable_incompleted_write(self): with UnseekableIO(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') f = self.create_file(testfile) f.setnframes(self.nframes + 1) try: f.writeframes(self.frames) except OSError: pass try: f.close() except OSError: pass with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') self.check_file(testfile, self.nframes + 1, self.frames) def test_unseekable_overflowed_write(self): with UnseekableIO(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') f = self.create_file(testfile) f.setnframes(self.nframes - 1) try: f.writeframes(self.frames) except OSError: pass try: f.close() except OSError: pass with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') framesize = self.nchannels * self.sampwidth self.check_file(testfile, self.nframes - 1, self.frames[:-framesize]) class AudioTestsWithSourceFile(AudioTests): @classmethod def setUpClass(cls): cls.sndfilepath = findfile(cls.sndfilename, subdir='audiodata') def test_read_params(self): f = self.f = self.module.open(self.sndfilepath) #self.assertEqual(f.getfp().name, self.sndfilepath) self.check_params(f, self.nchannels, self.sampwidth, self.framerate, self.sndfilenframes, self.comptype, self.compname) def test_close(self): with open(self.sndfilepath, 'rb') as testfile: f = self.f = self.module.open(testfile) self.assertFalse(testfile.closed) f.close() self.assertEqual(testfile.closed, self.close_fd) with open(TESTFN, 'wb') as testfile: fout = self.fout = self.module.open(testfile, 'wb') self.assertFalse(testfile.closed) with self.assertRaises(self.module.Error): fout.close() self.assertEqual(testfile.closed, self.close_fd) fout.close() # do nothing def test_read(self): framesize = self.nchannels * self.sampwidth chunk1 = self.frames[:2 * framesize] chunk2 = self.frames[2 * framesize: 4 * framesize] f = self.f = self.module.open(self.sndfilepath) self.assertEqual(f.readframes(0), b'') self.assertEqual(f.tell(), 0) self.assertEqual(f.readframes(2), chunk1) f.rewind() pos0 = f.tell() self.assertEqual(pos0, 0) self.assertEqual(f.readframes(2), chunk1) pos2 = f.tell() self.assertEqual(pos2, 2) self.assertEqual(f.readframes(2), chunk2) f.setpos(pos2) self.assertEqual(f.readframes(2), chunk2) f.setpos(pos0) self.assertEqual(f.readframes(2), chunk1) with self.assertRaises(self.module.Error): f.setpos(-1) with self.assertRaises(self.module.Error): f.setpos(f.getnframes() + 1) def test_copy(self): f = self.f = self.module.open(self.sndfilepath) fout = self.fout = self.module.open(TESTFN, 'wb') fout.setparams(f.getparams()) i = 0 n = f.getnframes() while n > 0: i += 1 fout.writeframes(f.readframes(i)) n -= i fout.close() fout = self.fout = self.module.open(TESTFN, 'rb') f.rewind() self.assertEqual(f.getparams(), fout.getparams()) self.assertEqual(f.readframes(f.getnframes()), fout.readframes(fout.getnframes())) def test_read_not_from_start(self): with open(TESTFN, 'wb') as testfile: testfile.write(b'ababagalamaga') with open(self.sndfilepath, 'rb') as f: testfile.write(f.read()) with open(TESTFN, 'rb') as testfile: self.assertEqual(testfile.read(13), b'ababagalamaga') with self.module.open(testfile, 'rb') as f: self.assertEqual(f.getnchannels(), self.nchannels) self.assertEqual(f.getsampwidth(), self.sampwidth) self.assertEqual(f.getframerate(), self.framerate) self.assertEqual(f.getnframes(), self.sndfilenframes) self.assertEqual(f.readframes(self.nframes), self.frames)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ann_module3.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ann_module3.py
""" Correct syntax for variable annotation that should fail at runtime in a certain manner. More examples are in test_grammar and test_parser. """ def f_bad_ann(): __annotations__[1] = 2 class C_OK: def __init__(self, x: int) -> None: self.x: no_such_name = x # This one is OK as proposed by Guido class D_bad_ann: def __init__(self, x: int) -> None: sfel.y: int = 0 def g_bad_ann(): no_such_name.attr: int = 0
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_cgi.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cgi.py
from test.support import check_warnings import cgi import os import sys import tempfile import unittest import warnings from collections import namedtuple from io import StringIO, BytesIO from test import support class HackedSysModule: # The regression test will have real values in sys.argv, which # will completely confuse the test of the cgi module argv = [] stdin = sys.stdin cgi.sys = HackedSysModule() class ComparableException: def __init__(self, err): self.err = err def __str__(self): return str(self.err) def __eq__(self, anExc): if not isinstance(anExc, Exception): return NotImplemented return (self.err.__class__ == anExc.__class__ and self.err.args == anExc.args) def __getattr__(self, attr): return getattr(self.err, attr) def do_test(buf, method): env = {} if method == "GET": fp = None env['REQUEST_METHOD'] = 'GET' env['QUERY_STRING'] = buf elif method == "POST": fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes env['REQUEST_METHOD'] = 'POST' env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' env['CONTENT_LENGTH'] = str(len(buf)) else: raise ValueError("unknown method: %s" % method) try: return cgi.parse(fp, env, strict_parsing=1) except Exception as err: return ComparableException(err) parse_strict_test_cases = [ ("", ValueError("bad query field: ''")), ("&", ValueError("bad query field: ''")), ("&&", ValueError("bad query field: ''")), (";", ValueError("bad query field: ''")), (";&;", ValueError("bad query field: ''")), # Should the next few really be valid? ("=", {}), ("=&=", {}), ("=;=", {}), # This rest seem to make sense ("=a", {'': ['a']}), ("&=a", ValueError("bad query field: ''")), ("=a&", ValueError("bad query field: ''")), ("=&a", ValueError("bad query field: 'a'")), ("b=a", {'b': ['a']}), ("b+=a", {'b ': ['a']}), ("a=b=a", {'a': ['b=a']}), ("a=+b=a", {'a': [' b=a']}), ("&b=a", ValueError("bad query field: ''")), ("b&=a", ValueError("bad query field: 'b'")), ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}), ("a=a+b&a=b+a", {'a': ['a b', 'b a']}), ("x=1&y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("x=1;y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("x=1;y=2.0;z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}), ("Hbc5161168c542333633315dee1182227:key_store_seqid=400006&cuyer=r&view=bustomer&order_id=0bb2e248638833d48cb7fed300000f1b&expire=964546263&lobale=en-US&kid=130003.300038&ss=env", {'Hbc5161168c542333633315dee1182227:key_store_seqid': ['400006'], 'cuyer': ['r'], 'expire': ['964546263'], 'kid': ['130003.300038'], 'lobale': ['en-US'], 'order_id': ['0bb2e248638833d48cb7fed300000f1b'], 'ss': ['env'], 'view': ['bustomer'], }), ("group_id=5470&set=custom&_assigned_to=31392&_status=1&_category=100&SUBMIT=Browse", {'SUBMIT': ['Browse'], '_assigned_to': ['31392'], '_category': ['100'], '_status': ['1'], 'group_id': ['5470'], 'set': ['custom'], }) ] def norm(seq): return sorted(seq, key=repr) def first_elts(list): return [p[0] for p in list] def first_second_elts(list): return [(p[0], p[1][0]) for p in list] def gen_result(data, environ): encoding = 'latin-1' fake_stdin = BytesIO(data.encode(encoding)) fake_stdin.seek(0) form = cgi.FieldStorage(fp=fake_stdin, environ=environ, encoding=encoding) result = {} for k, v in dict(form).items(): result[k] = isinstance(v, list) and form.getlist(k) or v.value return result class CgiTests(unittest.TestCase): def test_parse_multipart(self): fp = BytesIO(POSTDATA.encode('latin1')) env = {'boundary': BOUNDARY.encode('latin1'), 'CONTENT-LENGTH': '558'} result = cgi.parse_multipart(fp, env) expected = {'submit': [' Add '], 'id': ['1234'], 'file': [b'Testing 123.\n'], 'title': ['']} self.assertEqual(result, expected) def test_parse_multipart_invalid_encoding(self): BOUNDARY = "JfISa01" POSTDATA = """--JfISa01 Content-Disposition: form-data; name="submit-name" Content-Length: 3 \u2603 --JfISa01""" fp = BytesIO(POSTDATA.encode('utf8')) env = {'boundary': BOUNDARY.encode('latin1'), 'CONTENT-LENGTH': str(len(POSTDATA.encode('utf8')))} result = cgi.parse_multipart(fp, env, encoding="ascii", errors="surrogateescape") expected = {'submit-name': ["\udce2\udc98\udc83"]} self.assertEqual(result, expected) self.assertEqual("\u2603".encode('utf8'), result["submit-name"][0].encode('utf8', 'surrogateescape')) def test_fieldstorage_properties(self): fs = cgi.FieldStorage() self.assertFalse(fs) self.assertIn("FieldStorage", repr(fs)) self.assertEqual(list(fs), list(fs.keys())) fs.list.append(namedtuple('MockFieldStorage', 'name')('fieldvalue')) self.assertTrue(fs) def test_fieldstorage_invalid(self): self.assertRaises(TypeError, cgi.FieldStorage, "not-a-file-obj", environ={"REQUEST_METHOD":"PUT"}) self.assertRaises(TypeError, cgi.FieldStorage, "foo", "bar") fs = cgi.FieldStorage(headers={'content-type':'text/plain'}) self.assertRaises(TypeError, bool, fs) def test_escape(self): # cgi.escape() is deprecated. with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'cgi\.escape', DeprecationWarning) self.assertEqual("test &amp; string", cgi.escape("test & string")) self.assertEqual("&lt;test string&gt;", cgi.escape("<test string>")) self.assertEqual("&quot;test string&quot;", cgi.escape('"test string"', True)) def test_strict(self): for orig, expect in parse_strict_test_cases: # Test basic parsing d = do_test(orig, "GET") self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig)) d = do_test(orig, "POST") self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig)) env = {'QUERY_STRING': orig} fs = cgi.FieldStorage(environ=env) if isinstance(expect, dict): # test dict interface self.assertEqual(len(expect), len(fs)) self.assertCountEqual(expect.keys(), fs.keys()) ##self.assertEqual(norm(expect.values()), norm(fs.values())) ##self.assertEqual(norm(expect.items()), norm(fs.items())) self.assertEqual(fs.getvalue("nonexistent field", "default"), "default") # test individual fields for key in expect.keys(): expect_val = expect[key] self.assertIn(key, fs) if len(expect_val) > 1: self.assertEqual(fs.getvalue(key), expect_val) else: self.assertEqual(fs.getvalue(key), expect_val[0]) def test_log(self): cgi.log("Testing") cgi.logfp = StringIO() cgi.initlog("%s", "Testing initlog 1") cgi.log("%s", "Testing log 2") self.assertEqual(cgi.logfp.getvalue(), "Testing initlog 1\nTesting log 2\n") if os.path.exists(os.devnull): cgi.logfp = None cgi.logfile = os.devnull cgi.initlog("%s", "Testing log 3") self.addCleanup(cgi.closelog) cgi.log("Testing log 4") def test_fieldstorage_readline(self): # FieldStorage uses readline, which has the capacity to read all # contents of the input file into memory; we use readline's size argument # to prevent that for files that do not contain any newlines in # non-GET/HEAD requests class TestReadlineFile: def __init__(self, file): self.file = file self.numcalls = 0 def readline(self, size=None): self.numcalls += 1 if size: return self.file.readline(size) else: return self.file.readline() def __getattr__(self, name): file = self.__dict__['file'] a = getattr(file, name) if not isinstance(a, int): setattr(self, name, a) return a f = TestReadlineFile(tempfile.TemporaryFile("wb+")) self.addCleanup(f.close) f.write(b'x' * 256 * 1024) f.seek(0) env = {'REQUEST_METHOD':'PUT'} fs = cgi.FieldStorage(fp=f, environ=env) self.addCleanup(fs.file.close) # if we're not chunking properly, readline is only called twice # (by read_binary); if we are chunking properly, it will be called 5 times # as long as the chunksize is 1 << 16. self.assertGreater(f.numcalls, 2) f.close() def test_fieldstorage_multipart(self): #Test basic FieldStorage multipart parsing env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH': '558'} fp = BytesIO(POSTDATA.encode('latin-1')) fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1") self.assertEqual(len(fs.list), 4) expect = [{'name':'id', 'filename':None, 'value':'1234'}, {'name':'title', 'filename':None, 'value':''}, {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'}, {'name':'submit', 'filename':None, 'value':' Add '}] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) self.assertEqual(got, exp) def test_fieldstorage_multipart_leading_whitespace(self): env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH': '560'} # Add some leading whitespace to our post data that will cause the # first line to not be the innerboundary. fp = BytesIO(b"\r\n" + POSTDATA.encode('latin-1')) fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1") self.assertEqual(len(fs.list), 4) expect = [{'name':'id', 'filename':None, 'value':'1234'}, {'name':'title', 'filename':None, 'value':''}, {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'}, {'name':'submit', 'filename':None, 'value':' Add '}] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) self.assertEqual(got, exp) def test_fieldstorage_multipart_non_ascii(self): #Test basic FieldStorage multipart parsing env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH':'558'} for encoding in ['iso-8859-1','utf-8']: fp = BytesIO(POSTDATA_NON_ASCII.encode(encoding)) fs = cgi.FieldStorage(fp, environ=env,encoding=encoding) self.assertEqual(len(fs.list), 1) expect = [{'name':'id', 'filename':None, 'value':'\xe7\xf1\x80'}] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) self.assertEqual(got, exp) def test_fieldstorage_multipart_maxline(self): # Issue #18167 maxline = 1 << 16 self.maxDiff = None def check(content): data = """---123 Content-Disposition: form-data; name="upload"; filename="fake.txt" Content-Type: text/plain %s ---123-- """.replace('\n', '\r\n') % content environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'REQUEST_METHOD': 'POST', } self.assertEqual(gen_result(data, environ), {'upload': content.encode('latin1')}) check('x' * (maxline - 1)) check('x' * (maxline - 1) + '\r') check('x' * (maxline - 1) + '\r' + 'y' * (maxline - 1)) def test_fieldstorage_multipart_w3c(self): # Test basic FieldStorage multipart parsing (W3C sample) env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY_W3), 'CONTENT_LENGTH': str(len(POSTDATA_W3))} fp = BytesIO(POSTDATA_W3.encode('latin-1')) fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1") self.assertEqual(len(fs.list), 2) self.assertEqual(fs.list[0].name, 'submit-name') self.assertEqual(fs.list[0].value, 'Larry') self.assertEqual(fs.list[1].name, 'files') files = fs.list[1].value self.assertEqual(len(files), 2) expect = [{'name': None, 'filename': 'file1.txt', 'value': b'... contents of file1.txt ...'}, {'name': None, 'filename': 'file2.gif', 'value': b'...contents of file2.gif...'}] for x in range(len(files)): for k, exp in expect[x].items(): got = getattr(files[x], k) self.assertEqual(got, exp) def test_fieldstorage_part_content_length(self): BOUNDARY = "JfISa01" POSTDATA = """--JfISa01 Content-Disposition: form-data; name="submit-name" Content-Length: 5 Larry --JfISa01""" env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY), 'CONTENT_LENGTH': str(len(POSTDATA))} fp = BytesIO(POSTDATA.encode('latin-1')) fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1") self.assertEqual(len(fs.list), 1) self.assertEqual(fs.list[0].name, 'submit-name') self.assertEqual(fs.list[0].value, 'Larry') def test_field_storage_multipart_no_content_length(self): fp = BytesIO(b"""--MyBoundary Content-Disposition: form-data; name="my-arg"; filename="foo" Test --MyBoundary-- """) env = { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=MyBoundary", "wsgi.input": fp, } fields = cgi.FieldStorage(fp, environ=env) self.assertEqual(len(fields["my-arg"].file.read()), 5) def test_fieldstorage_as_context_manager(self): fp = BytesIO(b'x' * 10) env = {'REQUEST_METHOD': 'PUT'} with cgi.FieldStorage(fp=fp, environ=env) as fs: content = fs.file.read() self.assertFalse(fs.file.closed) self.assertTrue(fs.file.closed) self.assertEqual(content, 'x' * 10) with self.assertRaisesRegex(ValueError, 'I/O operation on closed file'): fs.file.read() _qs_result = { 'key1': 'value1', 'key2': ['value2x', 'value2y'], 'key3': 'value3', 'key4': 'value4' } def testQSAndUrlEncode(self): data = "key2=value2x&key3=value3&key4=value4" environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'QUERY_STRING': 'key1=value1&key2=value2y', 'REQUEST_METHOD': 'POST', } v = gen_result(data, environ) self.assertEqual(self._qs_result, v) def test_max_num_fields(self): # For application/x-www-form-urlencoded data = '&'.join(['a=a']*11) environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'REQUEST_METHOD': 'POST', } with self.assertRaises(ValueError): cgi.FieldStorage( fp=BytesIO(data.encode()), environ=environ, max_num_fields=10, ) # For multipart/form-data data = """---123 Content-Disposition: form-data; name="a" 3 ---123 Content-Type: application/x-www-form-urlencoded a=4 ---123 Content-Type: application/x-www-form-urlencoded a=5 ---123-- """ environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'QUERY_STRING': 'a=1&a=2', 'REQUEST_METHOD': 'POST', } # 2 GET entities # 1 top level POST entities # 1 entity within the second POST entity # 1 entity within the third POST entity with self.assertRaises(ValueError): cgi.FieldStorage( fp=BytesIO(data.encode()), environ=environ, max_num_fields=4, ) cgi.FieldStorage( fp=BytesIO(data.encode()), environ=environ, max_num_fields=5, ) def testQSAndFormData(self): data = """---123 Content-Disposition: form-data; name="key2" value2y ---123 Content-Disposition: form-data; name="key3" value3 ---123 Content-Disposition: form-data; name="key4" value4 ---123-- """ environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'QUERY_STRING': 'key1=value1&key2=value2x', 'REQUEST_METHOD': 'POST', } v = gen_result(data, environ) self.assertEqual(self._qs_result, v) def testQSAndFormDataFile(self): data = """---123 Content-Disposition: form-data; name="key2" value2y ---123 Content-Disposition: form-data; name="key3" value3 ---123 Content-Disposition: form-data; name="key4" value4 ---123 Content-Disposition: form-data; name="upload"; filename="fake.txt" Content-Type: text/plain this is the content of the fake file ---123-- """ environ = { 'CONTENT_LENGTH': str(len(data)), 'CONTENT_TYPE': 'multipart/form-data; boundary=-123', 'QUERY_STRING': 'key1=value1&key2=value2x', 'REQUEST_METHOD': 'POST', } result = self._qs_result.copy() result.update({ 'upload': b'this is the content of the fake file\n' }) v = gen_result(data, environ) self.assertEqual(result, v) def test_deprecated_parse_qs(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qs is deprecated, use urllib.parse.' 'parse_qs instead', DeprecationWarning)): self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']}, cgi.parse_qs('a=A1&b=B2&B=B3')) def test_deprecated_parse_qsl(self): # this func is moved to urllib.parse, this is just a sanity check with check_warnings(('cgi.parse_qsl is deprecated, use urllib.parse.' 'parse_qsl instead', DeprecationWarning)): self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')], cgi.parse_qsl('a=A1&b=B2&B=B3')) def test_parse_header(self): self.assertEqual( cgi.parse_header("text/plain"), ("text/plain", {})) self.assertEqual( cgi.parse_header("text/vnd.just.made.this.up ; "), ("text/vnd.just.made.this.up", {})) self.assertEqual( cgi.parse_header("text/plain;charset=us-ascii"), ("text/plain", {"charset": "us-ascii"})) self.assertEqual( cgi.parse_header('text/plain ; charset="us-ascii"'), ("text/plain", {"charset": "us-ascii"})) self.assertEqual( cgi.parse_header('text/plain ; charset="us-ascii"; another=opt'), ("text/plain", {"charset": "us-ascii", "another": "opt"})) self.assertEqual( cgi.parse_header('attachment; filename="silly.txt"'), ("attachment", {"filename": "silly.txt"})) self.assertEqual( cgi.parse_header('attachment; filename="strange;name"'), ("attachment", {"filename": "strange;name"})) self.assertEqual( cgi.parse_header('attachment; filename="strange;name";size=123;'), ("attachment", {"filename": "strange;name", "size": "123"})) self.assertEqual( cgi.parse_header('form-data; name="files"; filename="fo\\"o;bar"'), ("form-data", {"name": "files", "filename": 'fo"o;bar'})) def test_all(self): blacklist = {"logfile", "logfp", "initlog", "dolog", "nolog", "closelog", "log", "maxlen", "valid_boundary"} support.check__all__(self, cgi, blacklist=blacklist) BOUNDARY = "---------------------------721837373350705526688164684" POSTDATA = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" 1234 -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="title" -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Testing 123. -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="submit" Add\x20 -----------------------------721837373350705526688164684-- """ POSTDATA_NON_ASCII = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" \xe7\xf1\x80 -----------------------------721837373350705526688164684 """ # http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4 BOUNDARY_W3 = "AaB03x" POSTDATA_W3 = """--AaB03x Content-Disposition: form-data; name="submit-name" Larry --AaB03x Content-Disposition: form-data; name="files" Content-Type: multipart/mixed; boundary=BbC04y --BbC04y Content-Disposition: file; filename="file1.txt" Content-Type: text/plain ... contents of file1.txt ... --BbC04y Content-Disposition: file; filename="file2.gif" Content-Type: image/gif Content-Transfer-Encoding: binary ...contents of file2.gif... --BbC04y-- --AaB03x-- """ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_1_str.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_1_str.py
from __future__ import annotations USING_STRINGS = True # dataclass_module_1.py and dataclass_module_1_str.py are identical # except only the latter uses string annotations. import dataclasses import typing T_CV2 = typing.ClassVar[int] T_CV3 = typing.ClassVar T_IV2 = dataclasses.InitVar[int] T_IV3 = dataclasses.InitVar @dataclasses.dataclass class CV: T_CV4 = typing.ClassVar cv0: typing.ClassVar[int] = 20 cv1: typing.ClassVar = 30 cv2: T_CV2 cv3: T_CV3 not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. @dataclasses.dataclass class IV: T_IV4 = dataclasses.InitVar iv0: dataclasses.InitVar[int] iv1: dataclasses.InitVar iv2: T_IV2 iv3: T_IV3 not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/memory_watchdog.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/memory_watchdog.py
"""Memory watchdog: periodically read the memory usage of the main test process and print it out, until terminated.""" # stdin should refer to the process' /proc/<PID>/statm: we don't pass the # process' PID to avoid a race condition in case of - unlikely - PID recycling. # If the process crashes, reading from the /proc entry will fail with ESRCH. import os import sys import time try: page_size = os.sysconf('SC_PAGESIZE') except (ValueError, AttributeError): try: page_size = os.sysconf('SC_PAGE_SIZE') except (ValueError, AttributeError): page_size = 4096 while True: sys.stdin.seek(0) statm = sys.stdin.read() data = int(statm.split()[5]) sys.stdout.write(" ... process data size: {data:.1f}G\n" .format(data=data * page_size / (1024 ** 3))) sys.stdout.flush() time.sleep(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_cprofile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_cprofile.py
"""Test suite for the cProfile module.""" import sys from test.support import run_unittest, TESTFN, unlink import unittest # rip off all interesting stuff from test_profile import cProfile from test.test_profile import ProfileTest, regenerate_expected_output from test.support.script_helper import assert_python_failure, assert_python_ok class CProfileTest(ProfileTest): profilerclass = cProfile.Profile profilermodule = cProfile expected_max_output = "{built-in method builtins.max}" def get_expected_output(self): return _ProfileOutput # Issue 3895. def test_bad_counter_during_dealloc(self): import _lsprof # Must use a file as StringIO doesn't trigger the bug. orig_stderr = sys.stderr try: with open(TESTFN, 'w') as file: sys.stderr = file try: obj = _lsprof.Profiler(lambda: int) obj.enable() obj = _lsprof.Profiler(1) obj.disable() obj.clear() finally: sys.stderr = orig_stderr finally: unlink(TESTFN) # Issue 21862 def test_module_path_option(self): # Test -m switch with modules # Test that -m switch needs an argument assert_python_failure('-m', 'cProfile', '-m') # Test failure for not-existent module assert_python_failure('-m', 'cProfile', '-m', 'random_module_xyz') # Test successful run assert_python_ok('-m', 'cProfile', '-m', 'timeit', '-n', '1') class TestCommandLine(unittest.TestCase): def test_sort(self): rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo') self.assertGreater(rc, 0) self.assertIn(b"option -s: invalid choice: 'demo'", err) def test_main(): run_unittest(CProfileTest, TestCommandLine) def main(): if '-r' not in sys.argv: test_main() else: regenerate_expected_output(__file__, CProfileTest) # Don't remove this comment. Everything below it is auto-generated. #--cut-------------------------------------------------------------------------- _ProfileOutput = {} _ProfileOutput['print_stats'] = """\ 28 0.028 0.001 0.028 0.001 profilee.py:110(__getattr__) 1 0.270 0.270 1.000 1.000 profilee.py:25(testfunc) 23/3 0.150 0.007 0.170 0.057 profilee.py:35(factorial) 20 0.020 0.001 0.020 0.001 profilee.py:48(mul) 2 0.040 0.020 0.600 0.300 profilee.py:55(helper) 4 0.116 0.029 0.120 0.030 profilee.py:73(helper1) 2 0.000 0.000 0.140 0.070 profilee.py:84(helper2_indirect) 8 0.312 0.039 0.400 0.050 profilee.py:88(helper2) 8 0.064 0.008 0.080 0.010 profilee.py:98(subhelper)""" _ProfileOutput['print_callers'] = """\ profilee.py:110(__getattr__) <- 16 0.016 0.016 profilee.py:98(subhelper) profilee.py:25(testfunc) <- 1 0.270 1.000 <string>:1(<module>) profilee.py:35(factorial) <- 1 0.014 0.130 profilee.py:25(testfunc) 20/3 0.130 0.147 profilee.py:35(factorial) 2 0.006 0.040 profilee.py:84(helper2_indirect) profilee.py:48(mul) <- 20 0.020 0.020 profilee.py:35(factorial) profilee.py:55(helper) <- 2 0.040 0.600 profilee.py:25(testfunc) profilee.py:73(helper1) <- 4 0.116 0.120 profilee.py:55(helper) profilee.py:84(helper2_indirect) <- 2 0.000 0.140 profilee.py:55(helper) profilee.py:88(helper2) <- 6 0.234 0.300 profilee.py:55(helper) 2 0.078 0.100 profilee.py:84(helper2_indirect) profilee.py:98(subhelper) <- 8 0.064 0.080 profilee.py:88(helper2) {built-in method builtins.hasattr} <- 4 0.000 0.004 profilee.py:73(helper1) 8 0.000 0.008 profilee.py:88(helper2) {built-in method sys.exc_info} <- 4 0.000 0.000 profilee.py:73(helper1) {method 'append' of 'list' objects} <- 4 0.000 0.000 profilee.py:73(helper1)""" _ProfileOutput['print_callees'] = """\ <string>:1(<module>) -> 1 0.270 1.000 profilee.py:25(testfunc) profilee.py:110(__getattr__) -> profilee.py:25(testfunc) -> 1 0.014 0.130 profilee.py:35(factorial) 2 0.040 0.600 profilee.py:55(helper) profilee.py:35(factorial) -> 20/3 0.130 0.147 profilee.py:35(factorial) 20 0.020 0.020 profilee.py:48(mul) profilee.py:48(mul) -> profilee.py:55(helper) -> 4 0.116 0.120 profilee.py:73(helper1) 2 0.000 0.140 profilee.py:84(helper2_indirect) 6 0.234 0.300 profilee.py:88(helper2) profilee.py:73(helper1) -> 4 0.000 0.004 {built-in method builtins.hasattr} profilee.py:84(helper2_indirect) -> 2 0.006 0.040 profilee.py:35(factorial) 2 0.078 0.100 profilee.py:88(helper2) profilee.py:88(helper2) -> 8 0.064 0.080 profilee.py:98(subhelper) profilee.py:98(subhelper) -> 16 0.016 0.016 profilee.py:110(__getattr__) {built-in method builtins.hasattr} -> 12 0.012 0.012 profilee.py:110(__getattr__)""" if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_filecmp.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_filecmp.py
import filecmp import os import shutil import tempfile import unittest from test import support class FileCompareTestCase(unittest.TestCase): def setUp(self): self.name = support.TESTFN self.name_same = support.TESTFN + '-same' self.name_diff = support.TESTFN + '-diff' data = 'Contents of file go here.\n' for name in [self.name, self.name_same, self.name_diff]: with open(name, 'w') as output: output.write(data) with open(self.name_diff, 'a+') as output: output.write('An extra line.\n') self.dir = tempfile.gettempdir() def tearDown(self): os.unlink(self.name) os.unlink(self.name_same) os.unlink(self.name_diff) def test_matching(self): self.assertTrue(filecmp.cmp(self.name, self.name), "Comparing file to itself fails") self.assertTrue(filecmp.cmp(self.name, self.name, shallow=False), "Comparing file to itself fails") self.assertTrue(filecmp.cmp(self.name, self.name_same), "Comparing file to identical file fails") self.assertTrue(filecmp.cmp(self.name, self.name_same, shallow=False), "Comparing file to identical file fails") def test_different(self): self.assertFalse(filecmp.cmp(self.name, self.name_diff), "Mismatched files compare as equal") self.assertFalse(filecmp.cmp(self.name, self.dir), "File and directory compare as equal") def test_cache_clear(self): first_compare = filecmp.cmp(self.name, self.name_same, shallow=False) second_compare = filecmp.cmp(self.name, self.name_diff, shallow=False) filecmp.clear_cache() self.assertTrue(len(filecmp._cache) == 0, "Cache not cleared after calling clear_cache") class DirCompareTestCase(unittest.TestCase): def setUp(self): tmpdir = tempfile.gettempdir() self.dir = os.path.join(tmpdir, 'dir') self.dir_same = os.path.join(tmpdir, 'dir-same') self.dir_diff = os.path.join(tmpdir, 'dir-diff') # Another dir is created under dir_same, but it has a name from the # ignored list so it should not affect testing results. self.dir_ignored = os.path.join(self.dir_same, '.hg') self.caseinsensitive = os.path.normcase('A') == os.path.normcase('a') data = 'Contents of file go here.\n' for dir in (self.dir, self.dir_same, self.dir_diff, self.dir_ignored): shutil.rmtree(dir, True) os.mkdir(dir) if self.caseinsensitive and dir is self.dir_same: fn = 'FiLe' # Verify case-insensitive comparison else: fn = 'file' with open(os.path.join(dir, fn), 'w') as output: output.write(data) with open(os.path.join(self.dir_diff, 'file2'), 'w') as output: output.write('An extra file.\n') def tearDown(self): for dir in (self.dir, self.dir_same, self.dir_diff): shutil.rmtree(dir) def test_default_ignores(self): self.assertIn('.hg', filecmp.DEFAULT_IGNORES) def test_cmpfiles(self): self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file']) == (['file'], [], []), "Comparing directory to itself fails") self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) == (['file'], [], []), "Comparing directory to same fails") # Try it with shallow=False self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file'], shallow=False) == (['file'], [], []), "Comparing directory to itself fails") self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file'], shallow=False), "Comparing directory to same fails") # Add different file2 with open(os.path.join(self.dir, 'file2'), 'w') as output: output.write('Different contents.\n') self.assertFalse(filecmp.cmpfiles(self.dir, self.dir_same, ['file', 'file2']) == (['file'], ['file2'], []), "Comparing mismatched directories fails") def test_dircmp(self): # Check attributes for comparison of two identical directories left_dir, right_dir = self.dir, self.dir_same d = filecmp.dircmp(left_dir, right_dir) self.assertEqual(d.left, left_dir) self.assertEqual(d.right, right_dir) if self.caseinsensitive: self.assertEqual([d.left_list, d.right_list],[['file'], ['FiLe']]) else: self.assertEqual([d.left_list, d.right_list],[['file'], ['file']]) self.assertEqual(d.common, ['file']) self.assertEqual(d.left_only, []) self.assertEqual(d.right_only, []) self.assertEqual(d.same_files, ['file']) self.assertEqual(d.diff_files, []) expected_report = [ "diff {} {}".format(self.dir, self.dir_same), "Identical files : ['file']", ] self._assert_report(d.report, expected_report) # Check attributes for comparison of two different directories (right) left_dir, right_dir = self.dir, self.dir_diff d = filecmp.dircmp(left_dir, right_dir) self.assertEqual(d.left, left_dir) self.assertEqual(d.right, right_dir) self.assertEqual(d.left_list, ['file']) self.assertEqual(d.right_list, ['file', 'file2']) self.assertEqual(d.common, ['file']) self.assertEqual(d.left_only, []) self.assertEqual(d.right_only, ['file2']) self.assertEqual(d.same_files, ['file']) self.assertEqual(d.diff_files, []) expected_report = [ "diff {} {}".format(self.dir, self.dir_diff), "Only in {} : ['file2']".format(self.dir_diff), "Identical files : ['file']", ] self._assert_report(d.report, expected_report) # Check attributes for comparison of two different directories (left) left_dir, right_dir = self.dir, self.dir_diff shutil.move( os.path.join(self.dir_diff, 'file2'), os.path.join(self.dir, 'file2') ) d = filecmp.dircmp(left_dir, right_dir) self.assertEqual(d.left, left_dir) self.assertEqual(d.right, right_dir) self.assertEqual(d.left_list, ['file', 'file2']) self.assertEqual(d.right_list, ['file']) self.assertEqual(d.common, ['file']) self.assertEqual(d.left_only, ['file2']) self.assertEqual(d.right_only, []) self.assertEqual(d.same_files, ['file']) self.assertEqual(d.diff_files, []) expected_report = [ "diff {} {}".format(self.dir, self.dir_diff), "Only in {} : ['file2']".format(self.dir), "Identical files : ['file']", ] self._assert_report(d.report, expected_report) # Add different file2 with open(os.path.join(self.dir_diff, 'file2'), 'w') as output: output.write('Different contents.\n') d = filecmp.dircmp(self.dir, self.dir_diff) self.assertEqual(d.same_files, ['file']) self.assertEqual(d.diff_files, ['file2']) expected_report = [ "diff {} {}".format(self.dir, self.dir_diff), "Identical files : ['file']", "Differing files : ['file2']", ] self._assert_report(d.report, expected_report) def test_report_partial_closure(self): left_dir, right_dir = self.dir, self.dir_same d = filecmp.dircmp(left_dir, right_dir) expected_report = [ "diff {} {}".format(self.dir, self.dir_same), "Identical files : ['file']", ] self._assert_report(d.report_partial_closure, expected_report) def test_report_full_closure(self): left_dir, right_dir = self.dir, self.dir_same d = filecmp.dircmp(left_dir, right_dir) expected_report = [ "diff {} {}".format(self.dir, self.dir_same), "Identical files : ['file']", ] self._assert_report(d.report_full_closure, expected_report) def _assert_report(self, dircmp_report, expected_report_lines): with support.captured_stdout() as stdout: dircmp_report() report_lines = stdout.getvalue().strip().split('\n') self.assertEqual(report_lines, expected_report_lines) def test_main(): support.run_unittest(FileCompareTestCase, DirCompareTestCase) 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_shelve.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shelve.py
import unittest import shelve import glob from test import support from collections.abc import MutableMapping from test.test_dbm import dbm_iterator def L1(s): return s.decode("latin-1") class byteskeydict(MutableMapping): "Mapping that supports bytes keys" def __init__(self): self.d = {} def __getitem__(self, key): return self.d[L1(key)] def __setitem__(self, key, value): self.d[L1(key)] = value def __delitem__(self, key): del self.d[L1(key)] def __len__(self): return len(self.d) def iterkeys(self): for k in self.d.keys(): yield k.encode("latin-1") __iter__ = iterkeys def keys(self): return list(self.iterkeys()) def copy(self): return byteskeydict(self.d) class TestCase(unittest.TestCase): fn = "shelftemp.db" def tearDown(self): for f in glob.glob(self.fn+"*"): support.unlink(f) def test_close(self): d1 = {} s = shelve.Shelf(d1, protocol=2, writeback=False) s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) self.assertEqual(len(s), 1) s.close() self.assertRaises(ValueError, len, s) try: s['key1'] except ValueError: pass else: self.fail('Closed shelf should not find a key') def test_ascii_file_shelf(self): s = shelve.open(self.fn, protocol=0) try: s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) finally: s.close() def test_binary_file_shelf(self): s = shelve.open(self.fn, protocol=1) try: s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) finally: s.close() def test_proto2_file_shelf(self): s = shelve.open(self.fn, protocol=2) try: s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) finally: s.close() def test_in_memory_shelf(self): d1 = byteskeydict() s = shelve.Shelf(d1, protocol=0) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() d2 = byteskeydict() s = shelve.Shelf(d2, protocol=1) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() self.assertEqual(len(d1), 1) self.assertEqual(len(d2), 1) self.assertNotEqual(d1.items(), d2.items()) def test_mutable_entry(self): d1 = byteskeydict() s = shelve.Shelf(d1, protocol=2, writeback=False) s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) s['key1'].append(5) self.assertEqual(s['key1'], [1,2,3,4]) s.close() d2 = byteskeydict() s = shelve.Shelf(d2, protocol=2, writeback=True) s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) s['key1'].append(5) self.assertEqual(s['key1'], [1,2,3,4,5]) s.close() self.assertEqual(len(d1), 1) self.assertEqual(len(d2), 1) def test_keyencoding(self): d = {} key = 'Pöp' # the default keyencoding is utf-8 shelve.Shelf(d)[key] = [1] self.assertIn(key.encode('utf-8'), d) # but a different one can be given shelve.Shelf(d, keyencoding='latin-1')[key] = [1] self.assertIn(key.encode('latin-1'), d) # with all consequences s = shelve.Shelf(d, keyencoding='ascii') self.assertRaises(UnicodeEncodeError, s.__setitem__, key, [1]) def test_writeback_also_writes_immediately(self): # Issue 5754 d = {} key = 'key' encodedkey = key.encode('utf-8') s = shelve.Shelf(d, writeback=True) s[key] = [1] p1 = d[encodedkey] # Will give a KeyError if backing store not updated s['key'].append(2) s.close() p2 = d[encodedkey] self.assertNotEqual(p1, p2) # Write creates new object in store def test_with(self): d1 = {} with shelve.Shelf(d1, protocol=2, writeback=False) as s: s['key1'] = [1,2,3,4] self.assertEqual(s['key1'], [1,2,3,4]) self.assertEqual(len(s), 1) self.assertRaises(ValueError, len, s) try: s['key1'] except ValueError: pass else: self.fail('Closed shelf should not find a key') def test_default_protocol(self): with shelve.Shelf({}) as s: self.assertEqual(s._protocol, 3) from test import mapping_tests class TestShelveBase(mapping_tests.BasicTestMappingProtocol): fn = "shelftemp.db" counter = 0 def __init__(self, *args, **kw): self._db = [] mapping_tests.BasicTestMappingProtocol.__init__(self, *args, **kw) type2test = shelve.Shelf def _reference(self): return {"key1":"value1", "key2":2, "key3":(1,2,3)} def _empty_mapping(self): if self._in_mem: x= shelve.Shelf(byteskeydict(), **self._args) else: self.counter+=1 x= shelve.open(self.fn+str(self.counter), **self._args) self._db.append(x) return x def tearDown(self): for db in self._db: db.close() self._db = [] if not self._in_mem: for f in glob.glob(self.fn+"*"): support.unlink(f) class TestAsciiFileShelve(TestShelveBase): _args={'protocol':0} _in_mem = False class TestBinaryFileShelve(TestShelveBase): _args={'protocol':1} _in_mem = False class TestProto2FileShelve(TestShelveBase): _args={'protocol':2} _in_mem = False class TestAsciiMemShelve(TestShelveBase): _args={'protocol':0} _in_mem = True class TestBinaryMemShelve(TestShelveBase): _args={'protocol':1} _in_mem = True class TestProto2MemShelve(TestShelveBase): _args={'protocol':2} _in_mem = True def test_main(): for module in dbm_iterator(): support.run_unittest( TestAsciiFileShelve, TestBinaryFileShelve, TestProto2FileShelve, TestAsciiMemShelve, TestBinaryMemShelve, TestProto2MemShelve, TestCase ) 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_mmap.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_mmap.py
from test.support import (TESTFN, run_unittest, import_module, unlink, requires, _2G, _4G, gc_collect, cpython_only) import unittest import os import re import itertools import socket import sys import weakref # Skip test if we can't import mmap. mmap = import_module('mmap') PAGESIZE = mmap.PAGESIZE class MmapTests(unittest.TestCase): def setUp(self): if os.path.exists(TESTFN): os.unlink(TESTFN) def tearDown(self): try: os.unlink(TESTFN) except OSError: pass def test_basic(self): # Test mmap module on Unix systems and Windows # Create a file to be mmap'ed. f = open(TESTFN, 'bw+') try: # Write 2 pages worth of data to the file f.write(b'\0'* PAGESIZE) f.write(b'foo') f.write(b'\0'* (PAGESIZE-3) ) f.flush() m = mmap.mmap(f.fileno(), 2 * PAGESIZE) finally: f.close() # Simple sanity checks tp = str(type(m)) # SF bug 128713: segfaulted on Linux self.assertEqual(m.find(b'foo'), PAGESIZE) self.assertEqual(len(m), 2*PAGESIZE) self.assertEqual(m[0], 0) self.assertEqual(m[0:3], b'\0\0\0') # Shouldn't crash on boundary (Issue #5292) self.assertRaises(IndexError, m.__getitem__, len(m)) self.assertRaises(IndexError, m.__setitem__, len(m), b'\0') # Modify the file's content m[0] = b'3'[0] m[PAGESIZE +3: PAGESIZE +3+3] = b'bar' # Check that the modification worked self.assertEqual(m[0], b'3'[0]) self.assertEqual(m[0:3], b'3\0\0') self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], b'\0foobar\0') m.flush() # Test doing a regular expression match in an mmap'ed file match = re.search(b'[A-Za-z]+', m) if match is None: self.fail('regex match on mmap failed!') else: start, end = match.span(0) length = end - start self.assertEqual(start, PAGESIZE) self.assertEqual(end, PAGESIZE + 6) # test seeking around (try to overflow the seek implementation) m.seek(0,0) self.assertEqual(m.tell(), 0) m.seek(42,1) self.assertEqual(m.tell(), 42) m.seek(0,2) self.assertEqual(m.tell(), len(m)) # Try to seek to negative position... self.assertRaises(ValueError, m.seek, -1) # Try to seek beyond end of mmap... self.assertRaises(ValueError, m.seek, 1, 2) # Try to seek to negative position... self.assertRaises(ValueError, m.seek, -len(m)-1, 2) # Try resizing map try: m.resize(512) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported self.assertEqual(len(m), 512) # Check that we can no longer seek beyond the new size. self.assertRaises(ValueError, m.seek, 513, 0) # Check that the underlying file is truncated too # (bug #728515) f = open(TESTFN, 'rb') try: f.seek(0, 2) self.assertEqual(f.tell(), 512) finally: f.close() self.assertEqual(m.size(), 512) m.close() def test_access_parameter(self): # Test for "access" keyword parameter mapsize = 10 with open(TESTFN, "wb") as fp: fp.write(b"a"*mapsize) with open(TESTFN, "rb") as f: m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ) self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.") # Ensuring that readonly mmap can't be slice assigned try: m[:] = b'b'*mapsize except TypeError: pass else: self.fail("Able to write to readonly memory map") # Ensuring that readonly mmap can't be item assigned try: m[0] = b'b' except TypeError: pass else: self.fail("Able to write to readonly memory map") # Ensuring that readonly mmap can't be write() to try: m.seek(0,0) m.write(b'abc') except TypeError: pass else: self.fail("Able to write to readonly memory map") # Ensuring that readonly mmap can't be write_byte() to try: m.seek(0,0) m.write_byte(b'd') except TypeError: pass else: self.fail("Able to write to readonly memory map") # Ensuring that readonly mmap can't be resized try: m.resize(2*mapsize) except SystemError: # resize is not universally supported pass except TypeError: pass else: self.fail("Able to resize readonly memory map") with open(TESTFN, "rb") as fp: self.assertEqual(fp.read(), b'a'*mapsize, "Readonly memory map data file was modified") # Opening mmap with size too big with open(TESTFN, "r+b") as f: try: m = mmap.mmap(f.fileno(), mapsize+1) except ValueError: # we do not expect a ValueError on Windows # CAUTION: This also changes the size of the file on disk, and # later tests assume that the length hasn't changed. We need to # repair that. if sys.platform.startswith('win'): self.fail("Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows if not sys.platform.startswith('win'): self.fail("Opening mmap with size+1 should raise ValueError.") m.close() if sys.platform.startswith('win'): # Repair damage from the resizing test. with open(TESTFN, 'r+b') as f: f.truncate(mapsize) # Opening mmap with access=ACCESS_WRITE with open(TESTFN, "r+b") as f: m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE) # Modifying write-through memory map m[:] = b'c'*mapsize self.assertEqual(m[:], b'c'*mapsize, "Write-through memory map memory not updated properly.") m.flush() m.close() with open(TESTFN, 'rb') as f: stuff = f.read() self.assertEqual(stuff, b'c'*mapsize, "Write-through memory map data file not updated properly.") # Opening mmap with access=ACCESS_COPY with open(TESTFN, "r+b") as f: m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY) # Modifying copy-on-write memory map m[:] = b'd'*mapsize self.assertEqual(m[:], b'd' * mapsize, "Copy-on-write memory map data not written correctly.") m.flush() with open(TESTFN, "rb") as fp: self.assertEqual(fp.read(), b'c'*mapsize, "Copy-on-write test data file should not be modified.") # Ensuring copy-on-write maps cannot be resized self.assertRaises(TypeError, m.resize, 2*mapsize) m.close() # Ensuring invalid access parameter raises exception with open(TESTFN, "r+b") as f: self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4) if os.name == "posix": # Try incompatible flags, prot and access parameters. with open(TESTFN, "r+b") as f: self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE) # Try writing with PROT_EXEC and without PROT_WRITE prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0) with open(TESTFN, "r+b") as f: m = mmap.mmap(f.fileno(), mapsize, prot=prot) self.assertRaises(TypeError, m.write, b"abcdef") self.assertRaises(TypeError, m.write_byte, 0) m.close() def test_bad_file_desc(self): # Try opening a bad file descriptor... self.assertRaises(OSError, mmap.mmap, -2, 4096) def test_tougher_find(self): # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. with open(TESTFN, 'wb+') as f: data = b'aabaac\x00deef\x00\x00aa\x00' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) for start in range(n+1): for finish in range(start, n+1): slice = data[start : finish] self.assertEqual(m.find(slice), data.find(slice)) self.assertEqual(m.find(slice + b'x'), -1) m.close() def test_find_end(self): # test the new 'end' parameter works as expected f = open(TESTFN, 'wb+') data = b'one two ones' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) f.close() self.assertEqual(m.find(b'one'), 0) self.assertEqual(m.find(b'ones'), 8) self.assertEqual(m.find(b'one', 0, -1), 0) self.assertEqual(m.find(b'one', 1), 8) self.assertEqual(m.find(b'one', 1, -1), 8) self.assertEqual(m.find(b'one', 1, -2), -1) self.assertEqual(m.find(bytearray(b'one')), 0) def test_rfind(self): # test the new 'end' parameter works as expected f = open(TESTFN, 'wb+') data = b'one two ones' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) f.close() self.assertEqual(m.rfind(b'one'), 8) self.assertEqual(m.rfind(b'one '), 0) self.assertEqual(m.rfind(b'one', 0, -1), 8) self.assertEqual(m.rfind(b'one', 0, -2), 0) self.assertEqual(m.rfind(b'one', 1, -1), 8) self.assertEqual(m.rfind(b'one', 1, -2), -1) self.assertEqual(m.rfind(bytearray(b'one')), 8) def test_double_close(self): # make sure a double close doesn't crash on Solaris (Bug# 665913) f = open(TESTFN, 'wb+') f.write(2**16 * b'a') # Arbitrary character f.close() f = open(TESTFN, 'rb') mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ) mf.close() mf.close() f.close() @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") def test_entire_file(self): # test mapping of entire file by passing 0 for map length f = open(TESTFN, "wb+") f.write(2**16 * b'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) self.assertEqual(len(mf), 2**16, "Map size should equal file size.") self.assertEqual(mf.read(2**16), 2**16 * b"m") mf.close() f.close() @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") def test_length_0_offset(self): # Issue #10916: test mapping of remainder of file by passing 0 for # map length with an offset doesn't cause a segfault. # NOTE: allocation granularity is currently 65536 under Win64, # and therefore the minimum offset alignment. with open(TESTFN, "wb") as f: f.write((65536 * 2) * b'm') # Arbitrary character with open(TESTFN, "rb") as f: with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf: self.assertRaises(IndexError, mf.__getitem__, 80000) @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") def test_length_0_large_offset(self): # Issue #10959: test mapping of a file by passing 0 for # map length with a large offset doesn't cause a segfault. with open(TESTFN, "wb") as f: f.write(115699 * b'm') # Arbitrary character with open(TESTFN, "w+b") as f: self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0, offset=2147418112) def test_move(self): # make move works everywhere (64-bit format problem earlier) f = open(TESTFN, 'wb+') f.write(b"ABCDEabcde") # Arbitrary character f.flush() mf = mmap.mmap(f.fileno(), 10) mf.move(5, 0, 5) self.assertEqual(mf[:], b"ABCDEABCDE", "Map move should have duplicated front 5") mf.close() f.close() # more excessive test data = b"0123456789" for dest in range(len(data)): for src in range(len(data)): for count in range(len(data) - max(dest, src)): expected = data[:dest] + data[src:src+count] + data[dest+count:] m = mmap.mmap(-1, len(data)) m[:] = data m.move(dest, src, count) self.assertEqual(m[:], expected) m.close() # segfault test (Issue 5387) m = mmap.mmap(-1, 100) offsets = [-100, -1, 0, 1, 100] for source, dest, size in itertools.product(offsets, offsets, offsets): try: m.move(source, dest, size) except ValueError: pass offsets = [(-1, -1, -1), (-1, -1, 0), (-1, 0, -1), (0, -1, -1), (-1, 0, 0), (0, -1, 0), (0, 0, -1)] for source, dest, size in offsets: self.assertRaises(ValueError, m.move, source, dest, size) m.close() m = mmap.mmap(-1, 1) # single byte self.assertRaises(ValueError, m.move, 0, 0, 2) self.assertRaises(ValueError, m.move, 1, 0, 1) self.assertRaises(ValueError, m.move, 0, 1, 1) m.move(0, 0, 1) m.move(0, 0, 0) def test_anonymous(self): # anonymous mmap.mmap(-1, PAGE) m = mmap.mmap(-1, PAGESIZE) for x in range(PAGESIZE): self.assertEqual(m[x], 0, "anonymously mmap'ed contents should be zero") for x in range(PAGESIZE): b = x & 0xff m[x] = b self.assertEqual(m[x], b) def test_read_all(self): m = mmap.mmap(-1, 16) self.addCleanup(m.close) # With no parameters, or None or a negative argument, reads all m.write(bytes(range(16))) m.seek(0) self.assertEqual(m.read(), bytes(range(16))) m.seek(8) self.assertEqual(m.read(), bytes(range(8, 16))) m.seek(16) self.assertEqual(m.read(), b'') m.seek(3) self.assertEqual(m.read(None), bytes(range(3, 16))) m.seek(4) self.assertEqual(m.read(-1), bytes(range(4, 16))) m.seek(5) self.assertEqual(m.read(-2), bytes(range(5, 16))) m.seek(9) self.assertEqual(m.read(-42), bytes(range(9, 16))) def test_read_invalid_arg(self): m = mmap.mmap(-1, 16) self.addCleanup(m.close) self.assertRaises(TypeError, m.read, 'foo') self.assertRaises(TypeError, m.read, 5.5) self.assertRaises(TypeError, m.read, [1, 2, 3]) def test_extended_getslice(self): # Test extended slicing by comparing with list slicing. s = bytes(reversed(range(256))) m = mmap.mmap(-1, len(s)) m[:] = s self.assertEqual(m[:], s) indices = (0, None, 1, 3, 19, 300, sys.maxsize, -1, -2, -31, -300) for start in indices: for stop in indices: # Skip step 0 (invalid) for step in indices[1:]: self.assertEqual(m[start:stop:step], s[start:stop:step]) def test_extended_set_del_slice(self): # Test extended slicing by comparing with list slicing. s = bytes(reversed(range(256))) m = mmap.mmap(-1, len(s)) indices = (0, None, 1, 3, 19, 300, sys.maxsize, -1, -2, -31, -300) for start in indices: for stop in indices: # Skip invalid step 0 for step in indices[1:]: m[:] = s self.assertEqual(m[:], s) L = list(s) # Make sure we have a slice of exactly the right length, # but with different data. data = L[start:stop:step] data = bytes(reversed(data)) L[start:stop:step] = data m[start:stop:step] = data self.assertEqual(m[:], bytes(L)) def make_mmap_file (self, f, halfsize): # Write 2 pages worth of data to the file f.write (b'\0' * halfsize) f.write (b'foo') f.write (b'\0' * (halfsize - 3)) f.flush () return mmap.mmap (f.fileno(), 0) def test_empty_file (self): f = open (TESTFN, 'w+b') f.close() with open(TESTFN, "rb") as f : self.assertRaisesRegex(ValueError, "cannot mmap an empty file", mmap.mmap, f.fileno(), 0, access=mmap.ACCESS_READ) def test_offset (self): f = open (TESTFN, 'w+b') try: # unlink TESTFN no matter what halfsize = mmap.ALLOCATIONGRANULARITY m = self.make_mmap_file (f, halfsize) m.close () f.close () mapsize = halfsize * 2 # Try invalid offset f = open(TESTFN, "r+b") for offset in [-2, -1, None]: try: m = mmap.mmap(f.fileno(), mapsize, offset=offset) self.assertEqual(0, 1) except (ValueError, TypeError, OverflowError): pass else: self.assertEqual(0, 0) f.close() # Try valid offset, hopefully 8192 works on all OSes f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize) self.assertEqual(m[0:3], b'foo') f.close() # Try resizing map try: m.resize(512) except SystemError: pass else: # resize() is supported self.assertEqual(len(m), 512) # Check that we can no longer seek beyond the new size. self.assertRaises(ValueError, m.seek, 513, 0) # Check that the content is not changed self.assertEqual(m[0:3], b'foo') # Check that the underlying file is truncated too f = open(TESTFN, 'rb') f.seek(0, 2) self.assertEqual(f.tell(), halfsize + 512) f.close() self.assertEqual(m.size(), halfsize + 512) m.close() finally: f.close() try: os.unlink(TESTFN) except OSError: pass def test_subclass(self): class anon_mmap(mmap.mmap): def __new__(klass, *args, **kwargs): return mmap.mmap.__new__(klass, -1, *args, **kwargs) anon_mmap(PAGESIZE) @unittest.skipUnless(hasattr(mmap, 'PROT_READ'), "needs mmap.PROT_READ") def test_prot_readonly(self): mapsize = 10 with open(TESTFN, "wb") as fp: fp.write(b"a"*mapsize) f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ) self.assertRaises(TypeError, m.write, "foo") f.close() def test_error(self): self.assertIs(mmap.error, OSError) def test_io_methods(self): data = b"0123456789" with open(TESTFN, "wb") as fp: fp.write(b"x"*len(data)) f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), len(data)) f.close() # Test write_byte() for i in range(len(data)): self.assertEqual(m.tell(), i) m.write_byte(data[i]) self.assertEqual(m.tell(), i+1) self.assertRaises(ValueError, m.write_byte, b"x"[0]) self.assertEqual(m[:], data) # Test read_byte() m.seek(0) for i in range(len(data)): self.assertEqual(m.tell(), i) self.assertEqual(m.read_byte(), data[i]) self.assertEqual(m.tell(), i+1) self.assertRaises(ValueError, m.read_byte) # Test read() m.seek(3) self.assertEqual(m.read(3), b"345") self.assertEqual(m.tell(), 6) # Test write() m.seek(3) m.write(b"bar") self.assertEqual(m.tell(), 6) self.assertEqual(m[:], b"012bar6789") m.write(bytearray(b"baz")) self.assertEqual(m.tell(), 9) self.assertEqual(m[:], b"012barbaz9") self.assertRaises(ValueError, m.write, b"ba") def test_non_ascii_byte(self): for b in (129, 200, 255): # > 128 m = mmap.mmap(-1, 1) m.write_byte(b) self.assertEqual(m[0], b) m.seek(0) self.assertEqual(m.read_byte(), b) m.close() @unittest.skipUnless(os.name == 'nt', 'requires Windows') def test_tagname(self): data1 = b"0123456789" data2 = b"abcdefghij" assert len(data1) == len(data2) # Test same tag m1 = mmap.mmap(-1, len(data1), tagname="foo") m1[:] = data1 m2 = mmap.mmap(-1, len(data2), tagname="foo") m2[:] = data2 self.assertEqual(m1[:], data2) self.assertEqual(m2[:], data2) m2.close() m1.close() # Test different tag m1 = mmap.mmap(-1, len(data1), tagname="foo") m1[:] = data1 m2 = mmap.mmap(-1, len(data2), tagname="boo") m2[:] = data2 self.assertEqual(m1[:], data1) self.assertEqual(m2[:], data2) m2.close() m1.close() @cpython_only @unittest.skipUnless(os.name == 'nt', 'requires Windows') def test_sizeof(self): m1 = mmap.mmap(-1, 100) tagname = "foo" m2 = mmap.mmap(-1, 100, tagname=tagname) self.assertEqual(sys.getsizeof(m2), sys.getsizeof(m1) + len(tagname) + 1) @unittest.skipUnless(os.name == 'nt', 'requires Windows') def test_crasher_on_windows(self): # Should not crash (Issue 1733986) m = mmap.mmap(-1, 1000, tagname="foo") try: mmap.mmap(-1, 5000, tagname="foo")[:] # same tagname, but larger size except: pass m.close() # Should not crash (Issue 5385) with open(TESTFN, "wb") as fp: fp.write(b"x"*10) f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), 0) f.close() try: m.resize(0) # will raise OSError except: pass try: m[:] except: pass m.close() @unittest.skipUnless(os.name == 'nt', 'requires Windows') def test_invalid_descriptor(self): # socket file descriptors are valid, but out of range # for _get_osfhandle, causing a crash when validating the # parameters to _get_osfhandle. s = socket.socket() try: with self.assertRaises(OSError): m = mmap.mmap(s.fileno(), 10) finally: s.close() def test_context_manager(self): with mmap.mmap(-1, 10) as m: self.assertFalse(m.closed) self.assertTrue(m.closed) def test_context_manager_exception(self): # Test that the OSError gets passed through with self.assertRaises(Exception) as exc: with mmap.mmap(-1, 10) as m: raise OSError self.assertIsInstance(exc.exception, OSError, "wrong exception raised in context manager") self.assertTrue(m.closed, "context manager failed") def test_weakref(self): # Check mmap objects are weakrefable mm = mmap.mmap(-1, 16) wr = weakref.ref(mm) self.assertIs(wr(), mm) del mm gc_collect() self.assertIs(wr(), None) def test_write_returning_the_number_of_bytes_written(self): mm = mmap.mmap(-1, 16) self.assertEqual(mm.write(b""), 0) self.assertEqual(mm.write(b"x"), 1) self.assertEqual(mm.write(b"yz"), 2) self.assertEqual(mm.write(b"python"), 6) @unittest.skipIf(os.name == 'nt', 'cannot resize anonymous mmaps on Windows') def test_resize_past_pos(self): m = mmap.mmap(-1, 8192) self.addCleanup(m.close) m.read(5000) try: m.resize(4096) except SystemError: self.skipTest("resizing not supported") self.assertEqual(m.read(14), b'') self.assertRaises(ValueError, m.read_byte) self.assertRaises(ValueError, m.write_byte, 42) self.assertRaises(ValueError, m.write, b'abc') def test_concat_repeat_exception(self): m = mmap.mmap(-1, 16) with self.assertRaises(TypeError): m + m with self.assertRaises(TypeError): m * 2 class LargeMmapTests(unittest.TestCase): def setUp(self): unlink(TESTFN) def tearDown(self): unlink(TESTFN) def _make_test_file(self, num_zeroes, tail): if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(0x180000000)) f = open(TESTFN, 'w+b') try: f.seek(num_zeroes) f.write(tail) f.flush() except (OSError, OverflowError, ValueError): try: f.close() except (OSError, OverflowError): pass raise unittest.SkipTest("filesystem does not have largefile support") return f def test_large_offset(self): with self._make_test_file(0x14FFFFFFF, b" ") as f: with mmap.mmap(f.fileno(), 0, offset=0x140000000, access=mmap.ACCESS_READ) as m: self.assertEqual(m[0xFFFFFFF], 32) def test_large_filesize(self): with self._make_test_file(0x17FFFFFFF, b" ") as f: if sys.maxsize < 0x180000000: # On 32 bit platforms the file is larger than sys.maxsize so # mapping the whole file should fail -- Issue #16743 with self.assertRaises(OverflowError): mmap.mmap(f.fileno(), 0x180000000, access=mmap.ACCESS_READ) with self.assertRaises(ValueError): mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) with mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ) as m: self.assertEqual(m.size(), 0x180000000) # Issue 11277: mmap() with large (~4 GiB) sparse files crashes on OS X. def _test_around_boundary(self, boundary): tail = b' DEARdear ' start = boundary - len(tail) // 2 end = start + len(tail) with self._make_test_file(start, tail) as f: with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: self.assertEqual(m[start:end], tail) @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems") def test_around_2GB(self): self._test_around_boundary(_2G) @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems") def test_around_4GB(self): self._test_around_boundary(_4G) def test_main(): run_unittest(MmapTests, LargeMmapTests) 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_xxtestfuzz.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xxtestfuzz.py
import faulthandler import test.support import unittest _xxtestfuzz = test.support.import_module('_xxtestfuzz') class TestFuzzer(unittest.TestCase): """To keep our https://github.com/google/oss-fuzz API working.""" def test_sample_input_smoke_test(self): """This is only a regression test: Check that it doesn't crash.""" _xxtestfuzz.run(b"") _xxtestfuzz.run(b"\0") _xxtestfuzz.run(b"{") _xxtestfuzz.run(b" ") _xxtestfuzz.run(b"x") _xxtestfuzz.run(b"1") if __name__ == "__main__": faulthandler.enable() 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_docxmlrpc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
from xmlrpc.server import DocXMLRPCServer import http.client import re import sys import threading from test import support import unittest def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request because # the server created in setUp blocks expecting one to come in. if not condition: return lambda func: func def decorator(func): def make_request_and_skip(self): self.client.request("GET", "/") self.client.getresponse() raise unittest.SkipTest(reason) return make_request_and_skip return decorator def make_server(): serv = DocXMLRPCServer(("localhost", 0), logRequests=False) try: # Add some documentation serv.set_server_title("DocXMLRPCServer Test Documentation") serv.set_server_name("DocXMLRPCServer Test Docs") serv.set_server_documentation( "This is an XML-RPC server's documentation, but the server " "can be used by POSTing to /RPC2. Try self.add, too.") # Create and register classes and functions class TestClass(object): def test_method(self, arg): """Test method's docs. This method truly does very little.""" self.arg = arg serv.register_introspection_functions() serv.register_instance(TestClass()) def add(x, y): """Add two instances together. This follows PEP008, but has nothing to do with RFC1952. Case should matter: pEp008 and rFC1952. Things that start with http and ftp should be auto-linked, too: http://google.com. """ return x + y def annotation(x: int): """ Use function annotations. """ return x class ClassWithAnnotation: def method_annotation(self, x: bytes): return x.decode() serv.register_function(add) serv.register_function(lambda x, y: x-y) serv.register_function(annotation) serv.register_instance(ClassWithAnnotation()) return serv except: serv.server_close() raise class DocXMLRPCHTTPGETServer(unittest.TestCase): def setUp(self): # Enable server feedback DocXMLRPCServer._send_traceback_header = True self.serv = make_server() self.thread = threading.Thread(target=self.serv.serve_forever) self.thread.start() PORT = self.serv.server_address[1] self.client = http.client.HTTPConnection("localhost:%d" % PORT) def tearDown(self): self.client.close() # Disable server feedback DocXMLRPCServer._send_traceback_header = False self.serv.shutdown() self.thread.join() self.serv.server_close() def test_valid_get_response(self): self.client.request("GET", "/") response = self.client.getresponse() self.assertEqual(response.status, 200) self.assertEqual(response.getheader("Content-type"), "text/html") # Server raises an exception if we don't start to read the data response.read() def test_invalid_get_response(self): self.client.request("GET", "/spam") response = self.client.getresponse() self.assertEqual(response.status, 404) self.assertEqual(response.getheader("Content-type"), "text/plain") response.read() def test_lambda(self): """Test that lambda functionality stays the same. The output produced currently is, I suspect invalid because of the unencoded brackets in the HTML, "<lambda>". The subtraction lambda method is tested. """ self.client.request("GET", "/") response = self.client.getresponse() self.assertIn((b'<dl><dt><a name="-&lt;lambda&gt;"><strong>' b'&lt;lambda&gt;</strong></a>(x, y)</dt></dl>'), response.read()) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_autolinking(self): """Test that the server correctly automatically wraps references to PEPS and RFCs with links, and that it linkifies text starting with http or ftp protocol prefixes. The documentation for the "add" method contains the test material. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd>' b'<tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;' b'follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">' b'PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;' b'with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">' b'RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;' b'and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;' b'with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;' b'auto-linked,&nbsp;too:<br>\n<a href="http://google.com">' b'http://google.com</a>.</tt></dd></dl>'), response) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_system_methods(self): """Test the presence of three consecutive system.* methods. This also tests their use of parameter type recognition and the systems related to that process. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp' b'</strong></a>(method_name)</dt><dd><tt><a href="#-system.method' b'Help">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;' b'two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a' b'&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;' b'the&nbsp;specified&nbsp;method.</tt></dd></dl>\n<dl><dt><a name' b'="-system.methodSignature"><strong>system.methodSignature</strong>' b'</a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">' b'system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;' b'int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;' b'describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.' b'&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;' b'method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments' b'<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;' b'<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system' b'.methodSignature.</tt></dd></dl>'), response) def test_autolink_dotted_methods(self): """Test that selfdot values are made strong automatically in the documentation.""" self.client.request("GET", "/") response = self.client.getresponse() self.assertIn(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""", response.read()) def test_annotations(self): """ Test that annotations works as expected """ self.client.request("GET", "/") response = self.client.getresponse() docstring = (b'' if sys.flags.optimize >= 2 else b'<dd><tt>Use&nbsp;function&nbsp;annotations.</tt></dd>') self.assertIn( (b'<dl><dt><a name="-annotation"><strong>annotation</strong></a>' b'(x: int)</dt>' + docstring + b'</dl>\n' b'<dl><dt><a name="-method_annotation"><strong>' b'method_annotation</strong></a>(x: bytes)</dt></dl>'), response.read()) def test_server_title_escape(self): # bpo-38243: Ensure that the server title and documentation # are escaped for HTML. self.serv.set_server_title('test_title<script>') self.serv.set_server_documentation('test_documentation<script>') self.assertEqual('test_title<script>', self.serv.server_title) self.assertEqual('test_documentation<script>', self.serv.server_documentation) generated = self.serv.generate_html_documentation() title = re.search(r'<title>(.+?)</title>', generated).group() documentation = re.search(r'<p><tt>(.+?)</tt></p>', generated).group() self.assertEqual('<title>Python: test_title&lt;script&gt;</title>', title) self.assertEqual('<p><tt>test_documentation&lt;script&gt;</tt></p>', documentation) 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_codeop.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codeop.py
""" Test cases for codeop.py Nick Mathewson """ import unittest from test.support import is_jython from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT import io if is_jython: import sys def unify_callables(d): for n,v in d.items(): if hasattr(v, '__call__'): d[n] = True return d class CodeopTests(unittest.TestCase): def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' if is_jython: code = compile_command(str, "<input>", symbol) self.assertTrue(code) if symbol == "single": d,r = {},{} saved_stdout = sys.stdout sys.stdout = io.StringIO() try: exec(code, d) exec(compile(str,"<input>","single"), r) finally: sys.stdout = saved_stdout elif symbol == 'eval': ctx = {'a': 2} d = { 'value': eval(code,ctx) } r = { 'value': eval(str,ctx) } self.assertEqual(unify_callables(r),unify_callables(d)) else: expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT) self.assertEqual(compile_command(str, "<input>", symbol), expected) def assertIncomplete(self, str, symbol='single'): '''succeed iff str is the start of a valid piece of code''' self.assertEqual(compile_command(str, symbol=symbol), None) def assertInvalid(self, str, symbol='single', is_syntax=1): '''succeed iff str is the start of an invalid piece of code''' try: compile_command(str,symbol=symbol) self.fail("No exception raised for invalid code") except SyntaxError: self.assertTrue(is_syntax) except OverflowError: self.assertTrue(not is_syntax) def test_valid(self): av = self.assertValid # special case if not is_jython: self.assertEqual(compile_command(""), compile("pass", "<input>", 'single', PyCF_DONT_IMPLY_DEDENT)) self.assertEqual(compile_command("\n"), compile("pass", "<input>", 'single', PyCF_DONT_IMPLY_DEDENT)) else: av("") av("\n") av("a = 1") av("\na = 1") av("a = 1\n") av("a = 1\n\n") av("\n\na = 1\n\n") av("def x():\n pass\n") av("if 1:\n pass\n") av("\n\nif 1: pass\n") av("\n\nif 1: pass\n\n") av("def x():\n\n pass\n") av("def x():\n pass\n \n") av("def x():\n pass\n \n") av("pass\n") av("3**3\n") av("if 9==3:\n pass\nelse:\n pass\n") av("if 1:\n pass\n if 1:\n pass\n else:\n pass\n") av("#a\n#b\na = 3\n") av("#a\n\n \na=3\n") av("a=3\n\n") av("a = 9+ \\\n3") av("3**3","eval") av("(lambda z: \n z**3)","eval") av("9+ \\\n3","eval") av("9+ \\\n3\n","eval") av("\n\na**3","eval") av("\n \na**3","eval") av("#a\n#b\na**3","eval") av("\n\na = 1\n\n") av("\n\nif 1: a=1\n\n") av("if 1:\n pass\n if 1:\n pass\n else:\n pass\n") av("#a\n\n \na=3\n\n") av("\n\na**3","eval") av("\n \na**3","eval") av("#a\n#b\na**3","eval") av("def f():\n try: pass\n finally: [x for x in (1,2)]\n") av("def f():\n pass\n#foo\n") av("@a.b.c\ndef f():\n pass\n") def test_incomplete(self): ai = self.assertIncomplete ai("(a **") ai("(a,b,") ai("(a,b,(") ai("(a,b,(") ai("a = (") ai("a = {") ai("b + {") ai("if 9==3:\n pass\nelse:") ai("if 9==3:\n pass\nelse:\n") ai("if 9==3:\n pass\nelse:\n pass") ai("if 1:") ai("if 1:\n") ai("if 1:\n pass\n if 1:\n pass\n else:") ai("if 1:\n pass\n if 1:\n pass\n else:\n") ai("if 1:\n pass\n if 1:\n pass\n else:\n pass") ai("def x():") ai("def x():\n") ai("def x():\n\n") ai("def x():\n pass") ai("def x():\n pass\n ") ai("def x():\n pass\n ") ai("\n\ndef x():\n pass") ai("a = 9+ \\") ai("a = 'a\\") ai("a = '''xy") ai("","eval") ai("\n","eval") ai("(","eval") ai("(\n\n\n","eval") ai("(9+","eval") ai("9+ \\","eval") ai("lambda z: \\","eval") ai("if True:\n if True:\n if True: \n") ai("@a(") ai("@a(b") ai("@a(b,") ai("@a(b,c") ai("@a(b,c,") ai("from a import (") ai("from a import (b") ai("from a import (b,") ai("from a import (b,c") ai("from a import (b,c,") ai("["); ai("[a"); ai("[a,"); ai("[a,b"); ai("[a,b,"); ai("{"); ai("{a"); ai("{a:"); ai("{a:b"); ai("{a:b,"); ai("{a:b,c"); ai("{a:b,c:"); ai("{a:b,c:d"); ai("{a:b,c:d,"); ai("a(") ai("a(b") ai("a(b,") ai("a(b,c") ai("a(b,c,") ai("a[") ai("a[b") ai("a[b,") ai("a[b:") ai("a[b:c") ai("a[b:c:") ai("a[b:c:d") ai("def a(") ai("def a(b") ai("def a(b,") ai("def a(b,c") ai("def a(b,c,") ai("(") ai("(a") ai("(a,") ai("(a,b") ai("(a,b,") ai("if a:\n pass\nelif b:") ai("if a:\n pass\nelif b:\n pass\nelse:") ai("while a:") ai("while a:\n pass\nelse:") ai("for a in b:") ai("for a in b:\n pass\nelse:") ai("try:") ai("try:\n pass\nexcept:") ai("try:\n pass\nfinally:") ai("try:\n pass\nexcept:\n pass\nfinally:") ai("with a:") ai("with a as b:") ai("class a:") ai("class a(") ai("class a(b") ai("class a(b,") ai("class a():") ai("[x for") ai("[x for x in") ai("[x for x in (") ai("(x for") ai("(x for x in") ai("(x for x in (") def test_invalid(self): ai = self.assertInvalid ai("a b") ai("a @") ai("a b @") ai("a ** @") ai("a = ") ai("a = 9 +") ai("def x():\n\npass\n") ai("\n\n if 1: pass\n\npass") ai("a = 9+ \\\n") ai("a = 'a\\ ") ai("a = 'a\\\n") ai("a = 1","eval") ai("a = (","eval") ai("]","eval") ai("())","eval") ai("[}","eval") ai("9+","eval") ai("lambda z:","eval") ai("a b","eval") ai("return 2.3") ai("if (a == 1 and b = 2): pass") ai("del 1") ai("del (1,)") ai("del [1]") ai("del '1'") ai("[i for i in range(10)] = (1, 2, 3)") def test_filename(self): self.assertEqual(compile_command("a = 1\n", "abc").co_filename, compile("a = 1\n", "abc", 'single').co_filename) self.assertNotEqual(compile_command("a = 1\n", "abc").co_filename, compile("a = 1\n", "def", 'single').co_filename) 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_weakref.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
import gc import sys import unittest import collections import weakref import operator import contextlib import copy import threading import time import random from test import support from test.support import script_helper # Used in ReferencesTestCase.test_ref_created_during_del() . ref_from_del = None # Used by FinalizeTestCase as a global that may be replaced by None # when the interpreter shuts down. _global_var = 'foobar' class C: def method(self): pass class Callable: bar = None def __call__(self, x): self.bar = x def create_function(): def f(): pass return f def create_bound_method(): return C().method class Object: def __init__(self, arg): self.arg = arg def __repr__(self): return "<Object %r>" % self.arg def __eq__(self, other): if isinstance(other, Object): return self.arg == other.arg return NotImplemented def __lt__(self, other): if isinstance(other, Object): return self.arg < other.arg return NotImplemented def __hash__(self): return hash(self.arg) def some_method(self): return 4 def other_method(self): return 5 class RefCycle: def __init__(self): self.cycle = self class TestBase(unittest.TestCase): def setUp(self): self.cbcalled = 0 def callback(self, ref): self.cbcalled += 1 @contextlib.contextmanager def collect_in_thread(period=0.0001): """ Ensure GC collections happen in a different thread, at a high frequency. """ please_stop = False def collect(): while not please_stop: time.sleep(period) gc.collect() with support.disable_gc(): t = threading.Thread(target=collect) t.start() try: yield finally: please_stop = True t.join() class ReferencesTestCase(TestBase): def test_basic_ref(self): self.check_basic_ref(C) self.check_basic_ref(create_function) self.check_basic_ref(create_bound_method) # Just make sure the tp_repr handler doesn't raise an exception. # Live reference: o = C() wr = weakref.ref(o) repr(wr) # Dead reference: del o repr(wr) def test_basic_callback(self): self.check_basic_callback(C) self.check_basic_callback(create_function) self.check_basic_callback(create_bound_method) @support.cpython_only def test_cfunction(self): import _testcapi create_cfunction = _testcapi.create_cfunction f = create_cfunction() wr = weakref.ref(f) self.assertIs(wr(), f) del f self.assertIsNone(wr()) self.check_basic_ref(create_cfunction) self.check_basic_callback(create_cfunction) def test_multiple_callbacks(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del o self.assertIsNone(ref1(), "expected reference to be invalidated") self.assertIsNone(ref2(), "expected reference to be invalidated") self.assertEqual(self.cbcalled, 2, "callback not called the right number of times") def test_multiple_selfref_callbacks(self): # Make sure all references are invalidated before callbacks are called # # What's important here is that we're using the first # reference in the callback invoked on the second reference # (the most recently created ref is cleaned up first). This # tests that all references to the object are invalidated # before any of the callbacks are invoked, so that we only # have one invocation of _weakref.c:cleanup_helper() active # for a particular object at a time. # def callback(object, self=self): self.ref() c = C() self.ref = weakref.ref(c, callback) ref1 = weakref.ref(c, callback) del c def test_constructor_kwargs(self): c = C() self.assertRaises(TypeError, weakref.ref, c, callback=None) def test_proxy_ref(self): o = C() o.bar = 1 ref1 = weakref.proxy(o, self.callback) ref2 = weakref.proxy(o, self.callback) del o def check(proxy): proxy.bar self.assertRaises(ReferenceError, check, ref1) self.assertRaises(ReferenceError, check, ref2) self.assertRaises(ReferenceError, bool, weakref.proxy(C())) self.assertEqual(self.cbcalled, 2) def check_basic_ref(self, factory): o = factory() ref = weakref.ref(o) self.assertIsNotNone(ref(), "weak reference to live object should be live") o2 = ref() self.assertIs(o, o2, "<ref>() should return original object if live") def check_basic_callback(self, factory): self.cbcalled = 0 o = factory() ref = weakref.ref(o, self.callback) del o self.assertEqual(self.cbcalled, 1, "callback did not properly set 'cbcalled'") self.assertIsNone(ref(), "ref2 should be dead after deleting object reference") def test_ref_reuse(self): o = C() ref1 = weakref.ref(o) # create a proxy to make sure that there's an intervening creation # between these two; it should make no difference proxy = weakref.proxy(o) ref2 = weakref.ref(o) self.assertIs(ref1, ref2, "reference object w/out callback should be re-used") o = C() proxy = weakref.proxy(o) ref1 = weakref.ref(o) ref2 = weakref.ref(o) self.assertIs(ref1, ref2, "reference object w/out callback should be re-used") self.assertEqual(weakref.getweakrefcount(o), 2, "wrong weak ref count for object") del proxy self.assertEqual(weakref.getweakrefcount(o), 1, "wrong weak ref count for object after deleting proxy") def test_proxy_reuse(self): o = C() proxy1 = weakref.proxy(o) ref = weakref.ref(o) proxy2 = weakref.proxy(o) self.assertIs(proxy1, proxy2, "proxy object w/out callback should have been re-used") def test_basic_proxy(self): o = C() self.check_proxy(o, weakref.proxy(o)) L = collections.UserList() p = weakref.proxy(L) self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) self.assertTrue(p, "proxy for non-empty UserList should be true") p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) self.assertIn(3, p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) L2 = collections.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) ## self.assertEqual(repr(L2), repr(p2)) L3 = collections.UserList(range(10)) p3 = weakref.proxy(L3) self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) self.assertEqual(L3[:5], p3[:5]) self.assertEqual(L3[2:5], p3[2:5]) def test_proxy_unicode(self): # See bug 5037 class C(object): def __str__(self): return "string" def __bytes__(self): return b"bytes" instance = C() self.assertIn("__bytes__", dir(weakref.proxy(instance))) self.assertEqual(bytes(weakref.proxy(instance)), b"bytes") def test_proxy_index(self): class C: def __index__(self): return 10 o = C() p = weakref.proxy(o) self.assertEqual(operator.index(p), 10) def test_proxy_div(self): class C: def __floordiv__(self, other): return 42 def __ifloordiv__(self, other): return 21 o = C() p = weakref.proxy(o) self.assertEqual(p // 5, 42) p //= 5 self.assertEqual(p, 21) # The PyWeakref_* C API is documented as allowing either NULL or # None as the value for the callback, where either means "no # callback". The "no callback" ref and proxy objects are supposed # to be shared so long as they exist by all callers so long as # they are active. In Python 2.3.3 and earlier, this guarantee # was not honored, and was broken in different ways for # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) def test_shared_ref_without_callback(self): self.check_shared_without_callback(weakref.ref) def test_shared_proxy_without_callback(self): self.check_shared_without_callback(weakref.proxy) def check_shared_without_callback(self, makeref): o = Object(1) p1 = makeref(o, None) p2 = makeref(o, None) self.assertIs(p1, p2, "both callbacks were None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o, None) self.assertIs(p1, p2, "callbacks were NULL, None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o) self.assertIs(p1, p2, "both callbacks were NULL in the C API") del p1, p2 p1 = makeref(o, None) p2 = makeref(o) self.assertIs(p1, p2, "callbacks were None, NULL in the C API") def test_callable_proxy(self): o = Callable() ref1 = weakref.proxy(o) self.check_proxy(o, ref1) self.assertIs(type(ref1), weakref.CallableProxyType, "proxy is not of callable type") ref1('twinkies!') self.assertEqual(o.bar, 'twinkies!', "call through proxy not passed through to original") ref1(x='Splat.') self.assertEqual(o.bar, 'Splat.', "call through proxy not passed through to original") # expect due to too few args self.assertRaises(TypeError, ref1) # expect due to too many args self.assertRaises(TypeError, ref1, 1, 2, 3) def check_proxy(self, o, proxy): o.foo = 1 self.assertEqual(proxy.foo, 1, "proxy does not reflect attribute addition") o.foo = 2 self.assertEqual(proxy.foo, 2, "proxy does not reflect attribute modification") del o.foo self.assertFalse(hasattr(proxy, 'foo'), "proxy does not reflect attribute removal") proxy.foo = 1 self.assertEqual(o.foo, 1, "object does not reflect attribute addition via proxy") proxy.foo = 2 self.assertEqual(o.foo, 2, "object does not reflect attribute modification via proxy") del proxy.foo self.assertFalse(hasattr(o, 'foo'), "object does not reflect attribute removal via proxy") def test_proxy_deletion(self): # Test clearing of SF bug #762891 class Foo: result = None def __delitem__(self, accessor): self.result = accessor g = Foo() f = weakref.proxy(g) del f[0] self.assertEqual(f.result, 0) def test_proxy_bool(self): # Test clearing of SF bug #1170766 class List(list): pass lyst = List() self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst)) def test_proxy_iter(self): # Test fails with a debug build of the interpreter # (see bpo-38395). obj = None class MyObj: def __iter__(self): nonlocal obj del obj return NotImplemented obj = MyObj() p = weakref.proxy(obj) with self.assertRaises(TypeError): # "blech" in p calls MyObj.__iter__ through the proxy, # without keeping a reference to the real object, so it # can be killed in the middle of the call "blech" in p def test_getweakrefcount(self): o = C() ref1 = weakref.ref(o) ref2 = weakref.ref(o, self.callback) self.assertEqual(weakref.getweakrefcount(o), 2, "got wrong number of weak reference objects") proxy1 = weakref.proxy(o) proxy2 = weakref.proxy(o, self.callback) self.assertEqual(weakref.getweakrefcount(o), 4, "got wrong number of weak reference objects") del ref1, ref2, proxy1, proxy2 self.assertEqual(weakref.getweakrefcount(o), 0, "weak reference objects not unlinked from" " referent when discarded.") # assumes ints do not support weakrefs self.assertEqual(weakref.getweakrefcount(1), 0, "got wrong number of weak reference objects for int") def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 self.assertEqual(weakref.getweakrefs(o), [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 self.assertEqual(weakref.getweakrefs(o), [ref1], "list of refs does not match") del ref1 self.assertEqual(weakref.getweakrefs(o), [], "list of refs not cleared") # assumes ints do not support weakrefs self.assertEqual(weakref.getweakrefs(1), [], "list of refs does not match for int") def test_newstyle_number_ops(self): class F(float): pass f = F(2.0) p = weakref.proxy(f) self.assertEqual(p + 1.0, 3.0) self.assertEqual(1.0 + p, 3.0) # this used to SEGV def test_callbacks_protected(self): # Callbacks protected from already-set exceptions? # Regression test for SF bug #478534. class BogusError(Exception): pass data = {} def remove(k): del data[k] def encapsulate(): f = lambda : () data[weakref.ref(f, remove)] = None raise BogusError try: encapsulate() except BogusError: pass else: self.fail("exception not properly restored") try: encapsulate() except BogusError: pass else: self.fail("exception not properly restored") def test_sf_bug_840829(self): # "weakref callbacks and gc corrupt memory" # subtype_dealloc erroneously exposed a new-style instance # already in the process of getting deallocated to gc, # causing double-deallocation if the instance had a weakref # callback that triggered gc. # If the bug exists, there probably won't be an obvious symptom # in a release build. In a debug build, a segfault will occur # when the second attempt to remove the instance from the "list # of all objects" occurs. import gc class C(object): pass c = C() wr = weakref.ref(c, lambda ignore: gc.collect()) del c # There endeth the first part. It gets worse. del wr c1 = C() c1.i = C() wr = weakref.ref(c1.i, lambda ignore: gc.collect()) c2 = C() c2.c1 = c1 del c1 # still alive because c2 points to it # Now when subtype_dealloc gets called on c2, it's not enough just # that c2 is immune from gc while the weakref callbacks associated # with c2 execute (there are none in this 2nd half of the test, btw). # subtype_dealloc goes on to call the base classes' deallocs too, # so any gc triggered by weakref callbacks associated with anything # torn down by a base class dealloc can also trigger double # deallocation of c2. del c2 def test_callback_in_cycle_1(self): import gc class J(object): pass class II(object): def acallback(self, ignore): self.J I = II() I.J = J I.wr = weakref.ref(J, I.acallback) # Now J and II are each in a self-cycle (as all new-style class # objects are, since their __mro__ points back to them). I holds # both a weak reference (I.wr) and a strong reference (I.J) to class # J. I is also in a cycle (I.wr points to a weakref that references # I.acallback). When we del these three, they all become trash, but # the cycles prevent any of them from getting cleaned up immediately. # Instead they have to wait for cyclic gc to deduce that they're # trash. # # gc used to call tp_clear on all of them, and the order in which # it does that is pretty accidental. The exact order in which we # built up these things manages to provoke gc into running tp_clear # in just the right order (I last). Calling tp_clear on II leaves # behind an insane class object (its __mro__ becomes NULL). Calling # tp_clear on J breaks its self-cycle, but J doesn't get deleted # just then because of the strong reference from I.J. Calling # tp_clear on I starts to clear I's __dict__, and just happens to # clear I.J first -- I.wr is still intact. That removes the last # reference to J, which triggers the weakref callback. The callback # tries to do "self.J", and instances of new-style classes look up # attributes ("J") in the class dict first. The class (II) wants to # search II.__mro__, but that's NULL. The result was a segfault in # a release build, and an assert failure in a debug build. del I, J, II gc.collect() def test_callback_in_cycle_2(self): import gc # This is just like test_callback_in_cycle_1, except that II is an # old-style class. The symptom is different then: an instance of an # old-style class looks in its own __dict__ first. 'J' happens to # get cleared from I.__dict__ before 'wr', and 'J' was never in II's # __dict__, so the attribute isn't found. The difference is that # the old-style II doesn't have a NULL __mro__ (it doesn't have any # __mro__), so no segfault occurs. Instead it got: # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ... # Exception exceptions.AttributeError: # "II instance has no attribute 'J'" in <bound method II.acallback # of <?.II instance at 0x00B9B4B8>> ignored class J(object): pass class II: def acallback(self, ignore): self.J I = II() I.J = J I.wr = weakref.ref(J, I.acallback) del I, J, II gc.collect() def test_callback_in_cycle_3(self): import gc # This one broke the first patch that fixed the last two. In this # case, the objects reachable from the callback aren't also reachable # from the object (c1) *triggering* the callback: you can get to # c1 from c2, but not vice-versa. The result was that c2's __dict__ # got tp_clear'ed by the time the c2.cb callback got invoked. class C: def cb(self, ignore): self.me self.c1 self.wr c1, c2 = C(), C() c2.me = c2 c2.c1 = c1 c2.wr = weakref.ref(c1, c2.cb) del c1, c2 gc.collect() def test_callback_in_cycle_4(self): import gc # Like test_callback_in_cycle_3, except c2 and c1 have different # classes. c2's class (C) isn't reachable from c1 then, so protecting # objects reachable from the dying object (c1) isn't enough to stop # c2's class (C) from getting tp_clear'ed before c2.cb is invoked. # The result was a segfault (C.__mro__ was NULL when the callback # tried to look up self.me). class C(object): def cb(self, ignore): self.me self.c1 self.wr class D: pass c1, c2 = D(), C() c2.me = c2 c2.c1 = c1 c2.wr = weakref.ref(c1, c2.cb) del c1, c2, C, D gc.collect() @support.requires_type_collecting def test_callback_in_cycle_resurrection(self): import gc # Do something nasty in a weakref callback: resurrect objects # from dead cycles. For this to be attempted, the weakref and # its callback must also be part of the cyclic trash (else the # objects reachable via the callback couldn't be in cyclic trash # to begin with -- the callback would act like an external root). # But gc clears trash weakrefs with callbacks early now, which # disables the callbacks, so the callbacks shouldn't get called # at all (and so nothing actually gets resurrected). alist = [] class C(object): def __init__(self, value): self.attribute = value def acallback(self, ignore): alist.append(self.c) c1, c2 = C(1), C(2) c1.c = c2 c2.c = c1 c1.wr = weakref.ref(c2, c1.acallback) c2.wr = weakref.ref(c1, c2.acallback) def C_went_away(ignore): alist.append("C went away") wr = weakref.ref(C, C_went_away) del c1, c2, C # make them all trash self.assertEqual(alist, []) # del isn't enough to reclaim anything gc.collect() # c1.wr and c2.wr were part of the cyclic trash, so should have # been cleared without their callbacks executing. OTOH, the weakref # to C is bound to a function local (wr), and wasn't trash, so that # callback should have been invoked when C went away. self.assertEqual(alist, ["C went away"]) # The remaining weakref should be dead now (its callback ran). self.assertEqual(wr(), None) del alist[:] gc.collect() self.assertEqual(alist, []) def test_callbacks_on_callback(self): import gc # Set up weakref callbacks *on* weakref callbacks. alist = [] def safe_callback(ignore): alist.append("safe_callback called") class C(object): def cb(self, ignore): alist.append("cb called") c, d = C(), C() c.other = d d.other = c callback = c.cb c.wr = weakref.ref(d, callback) # this won't trigger d.wr = weakref.ref(callback, d.cb) # ditto external_wr = weakref.ref(callback, safe_callback) # but this will self.assertIs(external_wr(), callback) # The weakrefs attached to c and d should get cleared, so that # C.cb is never called. But external_wr isn't part of the cyclic # trash, and no cyclic trash is reachable from it, so safe_callback # should get invoked when the bound method object callback (c.cb) # -- which is itself a callback, and also part of the cyclic trash -- # gets reclaimed at the end of gc. del callback, c, d, C self.assertEqual(alist, []) # del isn't enough to clean up cycles gc.collect() self.assertEqual(alist, ["safe_callback called"]) self.assertEqual(external_wr(), None) del alist[:] gc.collect() self.assertEqual(alist, []) def test_gc_during_ref_creation(self): self.check_gc_during_creation(weakref.ref) def test_gc_during_proxy_creation(self): self.check_gc_during_creation(weakref.proxy) def check_gc_during_creation(self, makeref): thresholds = gc.get_threshold() gc.set_threshold(1, 1, 1) gc.collect() class A: pass def callback(*args): pass referenced = A() a = A() a.a = a a.wr = makeref(referenced) try: # now make sure the object and the ref get labeled as # cyclic trash: a = A() weakref.ref(referenced, callback) finally: gc.set_threshold(*thresholds) def test_ref_created_during_del(self): # Bug #1377858 # A weakref created in an object's __del__() would crash the # interpreter when the weakref was cleaned up since it would refer to # non-existent memory. This test should not segfault the interpreter. class Target(object): def __del__(self): global ref_from_del ref_from_del = weakref.ref(self) w = Target() def test_init(self): # Issue 3634 # <weakref to class>.__init__() doesn't check errors correctly r = weakref.ref(Exception) self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0) # No exception should be raised here gc.collect() def test_classes(self): # Check that classes are weakrefable. class A(object): pass l = [] weakref.ref(int) a = weakref.ref(A, l.append) A = None gc.collect() self.assertEqual(a(), None) self.assertEqual(l, [a]) def test_equality(self): # Alive weakrefs defer equality testing to their underlying object. x = Object(1) y = Object(1) z = Object(2) a = weakref.ref(x) b = weakref.ref(y) c = weakref.ref(z) d = weakref.ref(x) # Note how we directly test the operators here, to stress both # __eq__ and __ne__. self.assertTrue(a == b) self.assertFalse(a != b) self.assertFalse(a == c) self.assertTrue(a != c) self.assertTrue(a == d) self.assertFalse(a != d) del x, y, z gc.collect() for r in a, b, c: # Sanity check self.assertIs(r(), None) # Dead weakrefs compare by identity: whether `a` and `d` are the # same weakref object is an implementation detail, since they pointed # to the same original object and didn't have a callback. # (see issue #16453). self.assertFalse(a == b) self.assertTrue(a != b) self.assertFalse(a == c) self.assertTrue(a != c) self.assertEqual(a == d, a is d) self.assertEqual(a != d, a is not d) def test_ordering(self): # weakrefs cannot be ordered, even if the underlying objects can. ops = [operator.lt, operator.gt, operator.le, operator.ge] x = Object(1) y = Object(1) a = weakref.ref(x) b = weakref.ref(y) for op in ops: self.assertRaises(TypeError, op, a, b) # Same when dead. del x, y gc.collect() for op in ops: self.assertRaises(TypeError, op, a, b) def test_hashing(self): # Alive weakrefs hash the same as the underlying object x = Object(42) y = Object(42) a = weakref.ref(x) b = weakref.ref(y) self.assertEqual(hash(a), hash(42)) del x, y gc.collect() # Dead weakrefs: # - retain their hash is they were hashed when alive; # - otherwise, cannot be hashed. self.assertEqual(hash(a), hash(42)) self.assertRaises(TypeError, hash, b) def test_trashcan_16602(self): # Issue #16602: when a weakref's target was part of a long # deallocation chain, the trashcan mechanism could delay clearing # of the weakref and make the target object visible from outside # code even though its refcount had dropped to 0. A crash ensued. class C: def __init__(self, parent): if not parent: return wself = weakref.ref(self) def cb(wparent): o = wself() self.wparent = weakref.ref(parent, cb) d = weakref.WeakKeyDictionary() root = c = C(None) for n in range(100): d[c] = c = C(c) del root gc.collect() def test_callback_attribute(self): x = Object(1) callback = lambda ref: None ref1 = weakref.ref(x, callback) self.assertIs(ref1.__callback__, callback) ref2 = weakref.ref(x) self.assertIsNone(ref2.__callback__) def test_callback_attribute_after_deletion(self): x = Object(1) ref = weakref.ref(x, self.callback) self.assertIsNotNone(ref.__callback__) del x support.gc_collect() self.assertIsNone(ref.__callback__) def test_set_callback_attribute(self): x = Object(1) callback = lambda ref: None ref1 = weakref.ref(x, callback) with self.assertRaises(AttributeError): ref1.__callback__ = lambda ref: None def test_callback_gcs(self): class ObjectWithDel(Object): def __del__(self): pass x = ObjectWithDel(1) ref1 = weakref.ref(x, lambda ref: support.gc_collect()) del x support.gc_collect() class SubclassableWeakrefTestCase(TestBase): def test_subclass_refs(self): class MyRef(weakref.ref): def __init__(self, ob, callback=None, value=42): self.value = value super().__init__(ob, callback) def __call__(self): self.called = True return super().__call__() o = Object("foo") mr = MyRef(o, value=24) self.assertIs(mr(), o) self.assertTrue(mr.called) self.assertEqual(mr.value, 24) del o self.assertIsNone(mr()) self.assertTrue(mr.called) def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assertIsNot(r1, r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) self.assertIs(r2, refs[0]) self.assertIn(r1, refs[1:]) self.assertIn(r3, refs[1:]) def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) self.assertIsNot(r1, r2) refs = weakref.getweakrefs(o) self.assertIn(r1, refs) self.assertIn(r2, refs) def test_subclass_refs_with_slots(self): class MyRef(weakref.ref): __slots__ = "slot1", "slot2" def __new__(type, ob, callback, slot1, slot2): return weakref.ref.__new__(type, ob, callback) def __init__(self, ob, callback, slot1, slot2): self.slot1 = slot1 self.slot2 = slot2 def meth(self): return self.slot1 + self.slot2 o = Object(42) r = MyRef(o, None, "abc", "def") self.assertEqual(r.slot1, "abc") self.assertEqual(r.slot2, "def") self.assertEqual(r.meth(), "abcdef") self.assertFalse(hasattr(r, "__dict__")) def test_subclass_refs_with_cycle(self): """Confirm https://bugs.python.org/issue3100 is fixed.""" # An instance of a weakref subclass can have attributes. # If such a weakref holds the only strong reference to the object, # deleting the weakref will delete the object. In this case, # the callback must not be called, because the ref object is # being deleted. class MyRef(weakref.ref): pass # Use a local callback, for "regrtest -R::" # to detect refcounting problems def callback(w): self.cbcalled += 1 o = C() r1 = MyRef(o, callback) r1.o = o del o del r1 # Used to crash here self.assertEqual(self.cbcalled, 0) # Same test, with two weakrefs to the same 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_dict.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py
import collections import collections.abc import gc import pickle import random import string import sys import unittest import weakref from test import support class DictTest(unittest.TestCase): def test_invalid_keyword_arguments(self): class Custom(dict): pass for invalid in {1 : 2}, Custom({1 : 2}): with self.assertRaises(TypeError): dict(**invalid) with self.assertRaises(TypeError): {}.update(**invalid) def test_constructor(self): # calling built-in types without argument must return empty self.assertEqual(dict(), {}) self.assertIsNot(dict(), {}) def test_literal_constructor(self): # check literal constructor for different sized dicts # (to exercise the BUILD_MAP oparg). for n in (0, 1, 6, 256, 400): items = [(''.join(random.sample(string.ascii_letters, 8)), i) for i in range(n)] random.shuffle(items) formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items) dictliteral = '{' + ', '.join(formatted_items) + '}' self.assertEqual(eval(dictliteral), dict(items)) def test_bool(self): self.assertIs(not {}, True) self.assertTrue({1: 2}) self.assertIs(bool({}), False) self.assertIs(bool({1: 2}), True) def test_keys(self): d = {} self.assertEqual(set(d.keys()), set()) d = {'a': 1, 'b': 2} k = d.keys() self.assertEqual(set(k), {'a', 'b'}) self.assertIn('a', k) self.assertIn('b', k) self.assertIn('a', d) self.assertIn('b', d) self.assertRaises(TypeError, d.keys, None) self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])") def test_values(self): d = {} self.assertEqual(set(d.values()), set()) d = {1:2} self.assertEqual(set(d.values()), {2}) self.assertRaises(TypeError, d.values, None) self.assertEqual(repr(dict(a=1).values()), "dict_values([1])") def test_items(self): d = {} self.assertEqual(set(d.items()), set()) d = {1:2} self.assertEqual(set(d.items()), {(1, 2)}) self.assertRaises(TypeError, d.items, None) self.assertEqual(repr(dict(a=1).items()), "dict_items([('a', 1)])") def test_contains(self): d = {} self.assertNotIn('a', d) self.assertFalse('a' in d) self.assertTrue('a' not in d) d = {'a': 1, 'b': 2} self.assertIn('a', d) self.assertIn('b', d) self.assertNotIn('c', d) self.assertRaises(TypeError, d.__contains__) def test_len(self): d = {} self.assertEqual(len(d), 0) d = {'a': 1, 'b': 2} self.assertEqual(len(d), 2) def test_getitem(self): d = {'a': 1, 'b': 2} self.assertEqual(d['a'], 1) self.assertEqual(d['b'], 2) d['c'] = 3 d['a'] = 4 self.assertEqual(d['c'], 3) self.assertEqual(d['a'], 4) del d['b'] self.assertEqual(d, {'a': 4, 'c': 3}) self.assertRaises(TypeError, d.__getitem__) class BadEq(object): def __eq__(self, other): raise Exc() def __hash__(self): return 24 d = {} d[BadEq()] = 42 self.assertRaises(KeyError, d.__getitem__, 23) class Exc(Exception): pass class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.__getitem__, x) def test_clear(self): d = {1:1, 2:2, 3:3} d.clear() self.assertEqual(d, {}) self.assertRaises(TypeError, d.clear, None) def test_update(self): d = {} d.update({1:100}) d.update({2:20}) d.update({1:1, 2:2, 3:3}) self.assertEqual(d, {1:1, 2:2, 3:3}) d.update() self.assertEqual(d, {1:1, 2:2, 3:3}) self.assertRaises((TypeError, AttributeError), d.update, None) class SimpleUserDict: def __init__(self): self.d = {1:1, 2:2, 3:3} def keys(self): return self.d.keys() def __getitem__(self, i): return self.d[i] d.clear() d.update(SimpleUserDict()) self.assertEqual(d, {1:1, 2:2, 3:3}) class Exc(Exception): pass d.clear() class FailingUserDict: def keys(self): raise Exc self.assertRaises(Exc, d.update, FailingUserDict()) class FailingUserDict: def keys(self): class BogonIter: def __init__(self): self.i = 1 def __iter__(self): return self def __next__(self): if self.i: self.i = 0 return 'a' raise Exc return BogonIter() def __getitem__(self, key): return key self.assertRaises(Exc, d.update, FailingUserDict()) class FailingUserDict: def keys(self): class BogonIter: def __init__(self): self.i = ord('a') def __iter__(self): return self def __next__(self): if self.i <= ord('z'): rtn = chr(self.i) self.i += 1 return rtn raise StopIteration return BogonIter() def __getitem__(self, key): raise Exc self.assertRaises(Exc, d.update, FailingUserDict()) class badseq(object): def __iter__(self): return self def __next__(self): raise Exc() self.assertRaises(Exc, {}.update, badseq()) self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} self.assertIsNot(d.fromkeys('abc'), d) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) def g(): yield 1 self.assertEqual(d.fromkeys(g()), {1:None}) self.assertRaises(TypeError, {}.fromkeys, 3) class dictlike(dict): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) self.assertIsInstance(dictlike.fromkeys('a'), dictlike) self.assertIsInstance(dictlike().fromkeys('a'), dictlike) class mydict(dict): def __new__(cls): return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) self.assertIsInstance(ud, collections.UserDict) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass class baddict1(dict): def __init__(self): raise Exc() self.assertRaises(Exc, baddict1.fromkeys, [1]) class BadSeq(object): def __iter__(self): return self def __next__(self): raise Exc() self.assertRaises(Exc, dict.fromkeys, BadSeq()) class baddict2(dict): def __setitem__(self, key, value): raise Exc() self.assertRaises(Exc, baddict2.fromkeys, [1]) # test fast path for dictionary inputs d = dict(zip(range(6), range(6))) self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6))) class baddict3(dict): def __new__(cls): return d d = {i : i for i in range(10)} res = d.copy() res.update(a=None, b=None, c=None) self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res) def test_copy(self): d = {1: 1, 2: 2, 3: 3} self.assertIsNot(d.copy(), d) self.assertEqual(d.copy(), d) self.assertEqual(d.copy(), {1: 1, 2: 2, 3: 3}) copy = d.copy() d[4] = 4 self.assertNotEqual(copy, d) self.assertEqual({}.copy(), {}) self.assertRaises(TypeError, d.copy, None) def test_copy_fuzz(self): for dict_size in [10, 100, 1000, 10000, 100000]: dict_size = random.randrange( dict_size // 2, dict_size + dict_size // 2) with self.subTest(dict_size=dict_size): d = {} for i in range(dict_size): d[i] = i d2 = d.copy() self.assertIsNot(d2, d) self.assertEqual(d, d2) d2['key'] = 'value' self.assertNotEqual(d, d2) self.assertEqual(len(d2), len(d) + 1) def test_copy_maintains_tracking(self): class A: pass key = A() for d in ({}, {'a': 1}, {key: 'val'}): d2 = d.copy() self.assertEqual(gc.is_tracked(d), gc.is_tracked(d2)) def test_copy_noncompact(self): # Dicts don't compact themselves on del/pop operations. # Copy will use a slow merging strategy that produces # a compacted copy when roughly 33% of dict is a non-used # keys-space (to optimize memory footprint). # In this test we want to hit the slow/compacting # branch of dict.copy() and make sure it works OK. d = {k: k for k in range(1000)} for k in range(950): del d[k] d2 = d.copy() self.assertEqual(d2, d) def test_get(self): d = {} self.assertIs(d.get('c'), None) self.assertEqual(d.get('c', 3), 3) d = {'a': 1, 'b': 2} self.assertIs(d.get('c'), None) self.assertEqual(d.get('c', 3), 3) self.assertEqual(d.get('a'), 1) self.assertEqual(d.get('a', 3), 1) self.assertRaises(TypeError, d.get) self.assertRaises(TypeError, d.get, None, None, None) def test_setdefault(self): # dict.setdefault() d = {} self.assertIs(d.setdefault('key0'), None) d.setdefault('key0', []) self.assertIs(d.setdefault('key0'), None) d.setdefault('key', []).append(3) self.assertEqual(d['key'][0], 3) d.setdefault('key', []).append(4) self.assertEqual(len(d['key']), 2) self.assertRaises(TypeError, d.setdefault) class Exc(Exception): pass class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.setdefault, x, []) def test_setdefault_atomic(self): # Issue #13521: setdefault() calls __hash__ and __eq__ only once. class Hashed(object): def __init__(self): self.hash_count = 0 self.eq_count = 0 def __hash__(self): self.hash_count += 1 return 42 def __eq__(self, other): self.eq_count += 1 return id(self) == id(other) hashed1 = Hashed() y = {hashed1: 5} hashed2 = Hashed() y.setdefault(hashed2, []) self.assertEqual(hashed1.hash_count, 1) self.assertEqual(hashed2.hash_count, 1) self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) def test_setitem_atomic_at_resize(self): class Hashed(object): def __init__(self): self.hash_count = 0 self.eq_count = 0 def __hash__(self): self.hash_count += 1 return 42 def __eq__(self, other): self.eq_count += 1 return id(self) == id(other) hashed1 = Hashed() # 5 items y = {hashed1: 5, 0: 0, 1: 1, 2: 2, 3: 3} hashed2 = Hashed() # 6th item forces a resize y[hashed2] = [] self.assertEqual(hashed1.hash_count, 1) self.assertEqual(hashed2.hash_count, 1) self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1) def test_popitem(self): # dict.popitem() for copymode in -1, +1: # -1: b has same structure as a # +1: b is a.copy() for log2size in range(12): size = 2**log2size a = {} b = {} for i in range(size): a[repr(i)] = i if copymode < 0: b[repr(i)] = i if copymode > 0: b = a.copy() for i in range(size): ka, va = ta = a.popitem() self.assertEqual(va, int(ka)) kb, vb = tb = b.popitem() self.assertEqual(vb, int(kb)) self.assertFalse(copymode < 0 and ta != tb) self.assertFalse(a) self.assertFalse(b) d = {} self.assertRaises(KeyError, d.popitem) def test_pop(self): # Tests for pop with specified key d = {} k, v = 'abc', 'def' d[k] = v self.assertRaises(KeyError, d.pop, 'ghi') self.assertEqual(d.pop(k), v) self.assertEqual(len(d), 0) self.assertRaises(KeyError, d.pop, k) self.assertEqual(d.pop(k, v), v) d[k] = v self.assertEqual(d.pop(k, 1), v) self.assertRaises(TypeError, d.pop) class Exc(Exception): pass class BadHash(object): fail = False def __hash__(self): if self.fail: raise Exc() else: return 42 x = BadHash() d[x] = 42 x.fail = True self.assertRaises(Exc, d.pop, x) def test_mutating_iteration(self): # changing dict size during iteration d = {} d[1] = 1 with self.assertRaises(RuntimeError): for i in d: d[i+1] = 1 def test_mutating_lookup(self): # changing dict during a lookup (issue #14417) class NastyKey: mutate_dict = None def __init__(self, value): self.value = value def __hash__(self): # hash collision! return 1 def __eq__(self, other): if NastyKey.mutate_dict: mydict, key = NastyKey.mutate_dict NastyKey.mutate_dict = None del mydict[key] return self.value == other.value key1 = NastyKey(1) key2 = NastyKey(2) d = {key1: 1} NastyKey.mutate_dict = (d, key1) d[key2] = 2 self.assertEqual(d, {key2: 2}) def test_repr(self): d = {} self.assertEqual(repr(d), '{}') d[1] = 2 self.assertEqual(repr(d), '{1: 2}') d = {} d[1] = d self.assertEqual(repr(d), '{1: {...}}') class Exc(Exception): pass class BadRepr(object): def __repr__(self): raise Exc() d = {1: BadRepr()} self.assertRaises(Exc, repr, d) def test_repr_deep(self): d = {} for i in range(sys.getrecursionlimit() + 100): d = {1: d} self.assertRaises(RecursionError, repr, d) def test_eq(self): self.assertEqual({}, {}) self.assertEqual({1: 2}, {1: 2}) class Exc(Exception): pass class BadCmp(object): def __eq__(self, other): raise Exc() def __hash__(self): return 1 d1 = {BadCmp(): 1} d2 = {1: 1} with self.assertRaises(Exc): d1 == d2 def test_keys_contained(self): self.helper_keys_contained(lambda x: x.keys()) self.helper_keys_contained(lambda x: x.items()) def helper_keys_contained(self, fn): # Test rich comparisons against dict key views, which should behave the # same as sets. empty = fn(dict()) empty2 = fn(dict()) smaller = fn({1:1, 2:2}) larger = fn({1:1, 2:2, 3:3}) larger2 = fn({1:1, 2:2, 3:3}) larger3 = fn({4:1, 2:2, 3:3}) self.assertTrue(smaller < larger) self.assertTrue(smaller <= larger) self.assertTrue(larger > smaller) self.assertTrue(larger >= smaller) self.assertFalse(smaller >= larger) self.assertFalse(smaller > larger) self.assertFalse(larger <= smaller) self.assertFalse(larger < smaller) self.assertFalse(smaller < larger3) self.assertFalse(smaller <= larger3) self.assertFalse(larger3 > smaller) self.assertFalse(larger3 >= smaller) # Inequality strictness self.assertTrue(larger2 >= larger) self.assertTrue(larger2 <= larger) self.assertFalse(larger2 > larger) self.assertFalse(larger2 < larger) self.assertTrue(larger == larger2) self.assertTrue(smaller != larger) # There is an optimization on the zero-element case. self.assertTrue(empty == empty2) self.assertFalse(empty != empty2) self.assertFalse(empty == smaller) self.assertTrue(empty != smaller) # With the same size, an elementwise compare happens self.assertTrue(larger != larger3) self.assertFalse(larger == larger3) def test_errors_in_view_containment_check(self): class C: def __eq__(self, other): raise RuntimeError d1 = {1: C()} d2 = {1: C()} with self.assertRaises(RuntimeError): d1.items() == d2.items() with self.assertRaises(RuntimeError): d1.items() != d2.items() with self.assertRaises(RuntimeError): d1.items() <= d2.items() with self.assertRaises(RuntimeError): d1.items() >= d2.items() d3 = {1: C(), 2: C()} with self.assertRaises(RuntimeError): d2.items() < d3.items() with self.assertRaises(RuntimeError): d3.items() > d2.items() def test_dictview_set_operations_on_keys(self): k1 = {1:1, 2:2}.keys() k2 = {1:1, 2:2, 3:3}.keys() k3 = {4:4}.keys() self.assertEqual(k1 - k2, set()) self.assertEqual(k1 - k3, {1,2}) self.assertEqual(k2 - k1, {3}) self.assertEqual(k3 - k1, {4}) self.assertEqual(k1 & k2, {1,2}) self.assertEqual(k1 & k3, set()) self.assertEqual(k1 | k2, {1,2,3}) self.assertEqual(k1 ^ k2, {3}) self.assertEqual(k1 ^ k3, {1,2,4}) def test_dictview_set_operations_on_items(self): k1 = {1:1, 2:2}.items() k2 = {1:1, 2:2, 3:3}.items() k3 = {4:4}.items() self.assertEqual(k1 - k2, set()) self.assertEqual(k1 - k3, {(1,1), (2,2)}) self.assertEqual(k2 - k1, {(3,3)}) self.assertEqual(k3 - k1, {(4,4)}) self.assertEqual(k1 & k2, {(1,1), (2,2)}) self.assertEqual(k1 & k3, set()) self.assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) self.assertEqual(k1 ^ k2, {(3,3)}) self.assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) def test_dictview_mixed_set_operations(self): # Just a few for .keys() self.assertTrue({1:1}.keys() == {1}) self.assertTrue({1} == {1:1}.keys()) self.assertEqual({1:1}.keys() | {2}, {1, 2}) self.assertEqual({2} | {1:1}.keys(), {1, 2}) # And a few for .items() self.assertTrue({1:1}.items() == {(1,1)}) self.assertTrue({(1,1)} == {1:1}.items()) self.assertEqual({1:1}.items() | {2}, {(1,1), 2}) self.assertEqual({2} | {1:1}.items(), {(1,1), 2}) def test_missing(self): # Make sure dict doesn't have a __missing__ method self.assertFalse(hasattr(dict, "__missing__")) self.assertFalse(hasattr({}, "__missing__")) # Test several cases: # (D) subclass defines __missing__ method returning a value # (E) subclass defines __missing__ method raising RuntimeError # (F) subclass sets __missing__ instance variable (no effect) # (G) subclass doesn't define __missing__ at all class D(dict): def __missing__(self, key): return 42 d = D({1: 2, 3: 4}) self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) self.assertNotIn(2, d) self.assertNotIn(2, d.keys()) self.assertEqual(d[2], 42) class E(dict): def __missing__(self, key): raise RuntimeError(key) e = E() with self.assertRaises(RuntimeError) as c: e[42] self.assertEqual(c.exception.args, (42,)) class F(dict): def __init__(self): # An instance variable __missing__ should have no effect self.__missing__ = lambda key: None f = F() with self.assertRaises(KeyError) as c: f[42] self.assertEqual(c.exception.args, (42,)) class G(dict): pass g = G() with self.assertRaises(KeyError) as c: g[42] self.assertEqual(c.exception.args, (42,)) def test_tuple_keyerror(self): # SF #1576657 d = {} with self.assertRaises(KeyError) as c: d[(1,)] self.assertEqual(c.exception.args, ((1,),)) def test_bad_key(self): # Dictionary lookups should fail if __eq__() raises an exception. class CustomException(Exception): pass class BadDictKey: def __hash__(self): return hash(self.__class__) def __eq__(self, other): if isinstance(other, self.__class__): raise CustomException return other d = {} x1 = BadDictKey() x2 = BadDictKey() d[x1] = 1 for stmt in ['d[x2] = 2', 'z = d[x2]', 'x2 in d', 'd.get(x2)', 'd.setdefault(x2, 42)', 'd.pop(x2)', 'd.update({x2: 2})']: with self.assertRaises(CustomException): exec(stmt, locals()) def test_resize1(self): # Dict resizing bug, found by Jack Jansen in 2.2 CVS development. # This version got an assert failure in debug build, infinite loop in # release build. Unfortunately, provoking this kind of stuff requires # a mix of inserts and deletes hitting exactly the right hash codes in # exactly the right order, and I can't think of a randomized approach # that would be *likely* to hit a failing case in reasonable time. d = {} for i in range(5): d[i] = i for i in range(5): del d[i] for i in range(5, 9): # i==8 was the problem d[i] = i def test_resize2(self): # Another dict resizing bug (SF bug #1456209). # This caused Segmentation faults or Illegal instructions. class X(object): def __hash__(self): return 5 def __eq__(self, other): if resizing: d.clear() return False d = {} resizing = False d[X()] = 1 d[X()] = 2 d[X()] = 3 d[X()] = 4 d[X()] = 5 # now trigger a resize resizing = True d[9] = 6 def test_empty_presized_dict_in_freelist(self): # Bug #3537: if an empty but presized dict with a size larger # than 7 was in the freelist, it triggered an assertion failure with self.assertRaises(ZeroDivisionError): d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'g': None, 'h': None} d = {} def test_container_iterator(self): # Bug #3680: tp_traverse was not implemented for dictiter and # dictview objects. class C(object): pass views = (dict.items, dict.values, dict.keys) for v in views: obj = C() ref = weakref.ref(obj) container = {obj: 1} obj.v = v(container) obj.x = iter(obj.v) del obj, container gc.collect() self.assertIs(ref(), None, "Cycle was not collected") def _not_tracked(self, t): # Nested containers can take several collections to untrack gc.collect() gc.collect() self.assertFalse(gc.is_tracked(t), t) def _tracked(self, t): self.assertTrue(gc.is_tracked(t), t) gc.collect() gc.collect() self.assertTrue(gc.is_tracked(t), t) @support.cpython_only def test_track_literals(self): # Test GC-optimization of dict literals x, y, z, w = 1.5, "a", (1, None), [] self._not_tracked({}) self._not_tracked({x:(), y:x, z:1}) self._not_tracked({1: "a", "b": 2}) self._not_tracked({1: 2, (None, True, False, ()): int}) self._not_tracked({1: object()}) # Dicts with mutable elements are always tracked, even if those # elements are not tracked right now. self._tracked({1: []}) self._tracked({1: ([],)}) self._tracked({1: {}}) self._tracked({1: set()}) @support.cpython_only def test_track_dynamic(self): # Test GC-optimization of dynamically-created dicts class MyObject(object): pass x, y, z, w, o = 1.5, "a", (1, object()), [], MyObject() d = dict() self._not_tracked(d) d[1] = "a" self._not_tracked(d) d[y] = 2 self._not_tracked(d) d[z] = 3 self._not_tracked(d) self._not_tracked(d.copy()) d[4] = w self._tracked(d) self._tracked(d.copy()) d[4] = None self._not_tracked(d) self._not_tracked(d.copy()) # dd isn't tracked right now, but it may mutate and therefore d # which contains it must be tracked. d = dict() dd = dict() d[1] = dd self._not_tracked(dd) self._tracked(d) dd[1] = d self._tracked(dd) d = dict.fromkeys([x, y, z]) self._not_tracked(d) dd = dict() dd.update(d) self._not_tracked(dd) d = dict.fromkeys([x, y, z, o]) self._tracked(d) dd = dict() dd.update(d) self._tracked(dd) d = dict(x=x, y=y, z=z) self._not_tracked(d) d = dict(x=x, y=y, z=z, w=w) self._tracked(d) d = dict() d.update(x=x, y=y, z=z) self._not_tracked(d) d.update(w=w) self._tracked(d) d = dict([(x, y), (z, 1)]) self._not_tracked(d) d = dict([(x, y), (z, w)]) self._tracked(d) d = dict() d.update([(x, y), (z, 1)]) self._not_tracked(d) d.update([(x, y), (z, w)]) self._tracked(d) @support.cpython_only def test_track_subtypes(self): # Dict subtypes are always tracked class MyDict(dict): pass self._tracked(MyDict()) def make_shared_key_dict(self, n): class C: pass dicts = [] for i in range(n): a = C() a.x, a.y, a.z = 1, 2, 3 dicts.append(a.__dict__) return dicts @support.cpython_only def test_splittable_setdefault(self): """split table must be combined when setdefault() breaks insertion order""" a, b = self.make_shared_key_dict(2) a['a'] = 1 size_a = sys.getsizeof(a) a['b'] = 2 b.setdefault('b', 2) size_b = sys.getsizeof(b) b['a'] = 1 self.assertGreater(size_b, size_a) self.assertEqual(list(a), ['x', 'y', 'z', 'a', 'b']) self.assertEqual(list(b), ['x', 'y', 'z', 'b', 'a']) @support.cpython_only def test_splittable_del(self): """split table must be combined when del d[k]""" a, b = self.make_shared_key_dict(2) orig_size = sys.getsizeof(a) del a['y'] # split table is combined with self.assertRaises(KeyError): del a['y'] self.assertGreater(sys.getsizeof(a), orig_size) self.assertEqual(list(a), ['x', 'z']) self.assertEqual(list(b), ['x', 'y', 'z']) # Two dicts have different insertion order. a['y'] = 42 self.assertEqual(list(a), ['x', 'z', 'y']) self.assertEqual(list(b), ['x', 'y', 'z']) @support.cpython_only def test_splittable_pop(self): """split table must be combined when d.pop(k)""" a, b = self.make_shared_key_dict(2) orig_size = sys.getsizeof(a) a.pop('y') # split table is combined with self.assertRaises(KeyError): a.pop('y') self.assertGreater(sys.getsizeof(a), orig_size) self.assertEqual(list(a), ['x', 'z']) self.assertEqual(list(b), ['x', 'y', 'z']) # Two dicts have different insertion order. a['y'] = 42 self.assertEqual(list(a), ['x', 'z', 'y']) self.assertEqual(list(b), ['x', 'y', 'z']) @support.cpython_only def test_splittable_pop_pending(self): """pop a pending key in a splitted table should not crash""" a, b = self.make_shared_key_dict(2) a['a'] = 4 with self.assertRaises(KeyError): b.pop('a') @support.cpython_only def test_splittable_popitem(self): """split table must be combined when d.popitem()""" a, b = self.make_shared_key_dict(2) orig_size = sys.getsizeof(a) item = a.popitem() # split table is combined self.assertEqual(item, ('z', 3)) with self.assertRaises(KeyError): del a['z'] self.assertGreater(sys.getsizeof(a), orig_size) self.assertEqual(list(a), ['x', 'y']) self.assertEqual(list(b), ['x', 'y', 'z']) @support.cpython_only def test_splittable_setattr_after_pop(self): """setattr() must not convert combined table into split table.""" # Issue 28147 import _testcapi class C: pass a = C() a.a = 1 self.assertTrue(_testcapi.dict_hassplittable(a.__dict__)) # dict.pop() convert it to combined table a.__dict__.pop('a') self.assertFalse(_testcapi.dict_hassplittable(a.__dict__)) # But C should not convert a.__dict__ to split table again. a.a = 1 self.assertFalse(_testcapi.dict_hassplittable(a.__dict__)) # Same for popitem() a = C() a.a = 2 self.assertTrue(_testcapi.dict_hassplittable(a.__dict__)) a.__dict__.popitem() self.assertFalse(_testcapi.dict_hassplittable(a.__dict__)) a.a = 3 self.assertFalse(_testcapi.dict_hassplittable(a.__dict__)) def test_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): data = {1:"a", 2:"b", 3:"c"} it = iter(data) d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(sorted(it), sorted(data)) it = pickle.loads(d) try: drop = next(it) except StopIteration: continue d = pickle.dumps(it, proto) it = pickle.loads(d) del data[drop] self.assertEqual(sorted(it), sorted(data)) def test_itemiterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): data = {1:"a", 2:"b", 3:"c"} # dictviews aren't picklable, only their iterators itorg = iter(data.items()) d = pickle.dumps(itorg, proto) it = pickle.loads(d)
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_unicode_identifiers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_unicode_identifiers.py
import unittest class PEP3131Test(unittest.TestCase): def test_valid(self): class T: ä = 1 µ = 2 # this is a compatibility character 蟒 = 3 x󠄀 = 4 self.assertEqual(getattr(T, "\xe4"), 1) self.assertEqual(getattr(T, "\u03bc"), 2) self.assertEqual(getattr(T, '\u87d2'), 3) self.assertEqual(getattr(T, 'x\U000E0100'), 4) def test_non_bmp_normalized(self): 𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = 1 self.assertIn("Unicode", dir()) def test_invalid(self): try: from test import badsyntax_3131 except SyntaxError as s: self.assertEqual(str(s), "invalid character in identifier (badsyntax_3131.py, line 2)") else: self.fail("expected exception didn't occur") 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_tempfile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tempfile.py
# tempfile.py unit tests. import tempfile import errno import io import os import pathlib import signal import sys import re import warnings import contextlib import weakref from unittest import mock import unittest from test import support from test.support import script_helper if hasattr(os, 'stat'): import stat has_stat = 1 else: has_stat = 0 has_textmode = (tempfile._text_openflags != tempfile._bin_openflags) has_spawnl = hasattr(os, 'spawnl') # TEST_FILES may need to be tweaked for systems depending on the maximum # number of files that can be opened at one time (see ulimit -n) if sys.platform.startswith('openbsd'): TEST_FILES = 48 else: TEST_FILES = 100 # This is organized as one test for each chunk of code in tempfile.py, # in order of their appearance in the file. Testing which requires # threads is not done here. class TestLowLevelInternals(unittest.TestCase): def test_infer_return_type_singles(self): self.assertIs(str, tempfile._infer_return_type('')) self.assertIs(bytes, tempfile._infer_return_type(b'')) self.assertIs(str, tempfile._infer_return_type(None)) def test_infer_return_type_multiples(self): self.assertIs(str, tempfile._infer_return_type('', '')) self.assertIs(bytes, tempfile._infer_return_type(b'', b'')) with self.assertRaises(TypeError): tempfile._infer_return_type('', b'') with self.assertRaises(TypeError): tempfile._infer_return_type(b'', '') def test_infer_return_type_multiples_and_none(self): self.assertIs(str, tempfile._infer_return_type(None, '')) self.assertIs(str, tempfile._infer_return_type('', None)) self.assertIs(str, tempfile._infer_return_type(None, None)) self.assertIs(bytes, tempfile._infer_return_type(b'', None)) self.assertIs(bytes, tempfile._infer_return_type(None, b'')) with self.assertRaises(TypeError): tempfile._infer_return_type('', None, b'') with self.assertRaises(TypeError): tempfile._infer_return_type(b'', None, '') def test_infer_return_type_pathlib(self): self.assertIs(str, tempfile._infer_return_type(pathlib.Path('/'))) # Common functionality. class BaseTestCase(unittest.TestCase): str_check = re.compile(r"^[a-z0-9_-]{8}$") b_check = re.compile(br"^[a-z0-9_-]{8}$") def setUp(self): self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("ignore", category=RuntimeWarning, message="mktemp", module=__name__) def tearDown(self): self._warnings_manager.__exit__(None, None, None) def nameCheck(self, name, dir, pre, suf): (ndir, nbase) = os.path.split(name) npre = nbase[:len(pre)] nsuf = nbase[len(nbase)-len(suf):] if dir is not None: self.assertIs( type(name), str if type(dir) is str or isinstance(dir, os.PathLike) else bytes, "unexpected return type", ) if pre is not None: self.assertIs(type(name), str if type(pre) is str else bytes, "unexpected return type") if suf is not None: self.assertIs(type(name), str if type(suf) is str else bytes, "unexpected return type") if (dir, pre, suf) == (None, None, None): self.assertIs(type(name), str, "default return type must be str") # check for equality of the absolute paths! self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir), "file %r not in directory %r" % (name, dir)) self.assertEqual(npre, pre, "file %r does not begin with %r" % (nbase, pre)) self.assertEqual(nsuf, suf, "file %r does not end with %r" % (nbase, suf)) nbase = nbase[len(pre):len(nbase)-len(suf)] check = self.str_check if isinstance(nbase, str) else self.b_check self.assertTrue(check.match(nbase), "random characters %r do not match %r" % (nbase, check.pattern)) class TestExports(BaseTestCase): def test_exports(self): # There are no surprising symbols in the tempfile module dict = tempfile.__dict__ expected = { "NamedTemporaryFile" : 1, "TemporaryFile" : 1, "mkstemp" : 1, "mkdtemp" : 1, "mktemp" : 1, "TMP_MAX" : 1, "gettempprefix" : 1, "gettempprefixb" : 1, "gettempdir" : 1, "gettempdirb" : 1, "tempdir" : 1, "template" : 1, "SpooledTemporaryFile" : 1, "TemporaryDirectory" : 1, } unexp = [] for key in dict: if key[0] != '_' and key not in expected: unexp.append(key) self.assertTrue(len(unexp) == 0, "unexpected keys: %s" % unexp) class TestRandomNameSequence(BaseTestCase): """Test the internal iterator object _RandomNameSequence.""" def setUp(self): self.r = tempfile._RandomNameSequence() super().setUp() def test_get_six_char_str(self): # _RandomNameSequence returns a six-character string s = next(self.r) self.nameCheck(s, '', '', '') def test_many(self): # _RandomNameSequence returns no duplicate strings (stochastic) dict = {} r = self.r for i in range(TEST_FILES): s = next(r) self.nameCheck(s, '', '', '') self.assertNotIn(s, dict) dict[s] = 1 def supports_iter(self): # _RandomNameSequence supports the iterator protocol i = 0 r = self.r for s in r: i += 1 if i == 20: break @unittest.skipUnless(hasattr(os, 'fork'), "os.fork is required for this test") def test_process_awareness(self): # ensure that the random source differs between # child and parent. read_fd, write_fd = os.pipe() pid = None try: pid = os.fork() if not pid: # child process os.close(read_fd) os.write(write_fd, next(self.r).encode("ascii")) os.close(write_fd) # bypass the normal exit handlers- leave those to # the parent. os._exit(0) # parent process parent_value = next(self.r) child_value = os.read(read_fd, len(parent_value)).decode("ascii") finally: if pid: # best effort to ensure the process can't bleed out # via any bugs above try: os.kill(pid, signal.SIGKILL) except OSError: pass # Read the process exit status to avoid zombie process os.waitpid(pid, 0) os.close(read_fd) os.close(write_fd) self.assertNotEqual(child_value, parent_value) class TestCandidateTempdirList(BaseTestCase): """Test the internal function _candidate_tempdir_list.""" def test_nonempty_list(self): # _candidate_tempdir_list returns a nonempty list of strings cand = tempfile._candidate_tempdir_list() self.assertFalse(len(cand) == 0) for c in cand: self.assertIsInstance(c, str) def test_wanted_dirs(self): # _candidate_tempdir_list contains the expected directories # Make sure the interesting environment variables are all set. with support.EnvironmentVarGuard() as env: for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = os.getenv(envname) if not dirname: env[envname] = os.path.abspath(envname) cand = tempfile._candidate_tempdir_list() for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = os.getenv(envname) if not dirname: raise ValueError self.assertIn(dirname, cand) try: dirname = os.getcwd() except (AttributeError, OSError): dirname = os.curdir self.assertIn(dirname, cand) # Not practical to try to verify the presence of OS-specific # paths in this list. # We test _get_default_tempdir some more by testing gettempdir. class TestGetDefaultTempdir(BaseTestCase): """Test _get_default_tempdir().""" def test_no_files_left_behind(self): # use a private empty directory with tempfile.TemporaryDirectory() as our_temp_directory: # force _get_default_tempdir() to consider our empty directory def our_candidate_list(): return [our_temp_directory] with support.swap_attr(tempfile, "_candidate_tempdir_list", our_candidate_list): # verify our directory is empty after _get_default_tempdir() tempfile._get_default_tempdir() self.assertEqual(os.listdir(our_temp_directory), []) def raise_OSError(*args, **kwargs): raise OSError() with support.swap_attr(io, "open", raise_OSError): # test again with failing io.open() with self.assertRaises(FileNotFoundError): tempfile._get_default_tempdir() self.assertEqual(os.listdir(our_temp_directory), []) def bad_writer(*args, **kwargs): fp = orig_open(*args, **kwargs) fp.write = raise_OSError return fp with support.swap_attr(io, "open", bad_writer) as orig_open: # test again with failing write() with self.assertRaises(FileNotFoundError): tempfile._get_default_tempdir() self.assertEqual(os.listdir(our_temp_directory), []) class TestGetCandidateNames(BaseTestCase): """Test the internal function _get_candidate_names.""" def test_retval(self): # _get_candidate_names returns a _RandomNameSequence object obj = tempfile._get_candidate_names() self.assertIsInstance(obj, tempfile._RandomNameSequence) def test_same_thing(self): # _get_candidate_names always returns the same object a = tempfile._get_candidate_names() b = tempfile._get_candidate_names() self.assertTrue(a is b) @contextlib.contextmanager def _inside_empty_temp_dir(): dir = tempfile.mkdtemp() try: with support.swap_attr(tempfile, 'tempdir', dir): yield finally: support.rmtree(dir) def _mock_candidate_names(*names): return support.swap_attr(tempfile, '_get_candidate_names', lambda: iter(names)) class TestBadTempdir: def test_read_only_directory(self): with _inside_empty_temp_dir(): oldmode = mode = os.stat(tempfile.tempdir).st_mode mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) os.chmod(tempfile.tempdir, mode) try: if os.access(tempfile.tempdir, os.W_OK): self.skipTest("can't set the directory read-only") with self.assertRaises(PermissionError): self.make_temp() self.assertEqual(os.listdir(tempfile.tempdir), []) finally: os.chmod(tempfile.tempdir, oldmode) def test_nonexisting_directory(self): with _inside_empty_temp_dir(): tempdir = os.path.join(tempfile.tempdir, 'nonexistent') with support.swap_attr(tempfile, 'tempdir', tempdir): with self.assertRaises(FileNotFoundError): self.make_temp() def test_non_directory(self): with _inside_empty_temp_dir(): tempdir = os.path.join(tempfile.tempdir, 'file') open(tempdir, 'wb').close() with support.swap_attr(tempfile, 'tempdir', tempdir): with self.assertRaises((NotADirectoryError, FileNotFoundError)): self.make_temp() class TestMkstempInner(TestBadTempdir, BaseTestCase): """Test the internal function _mkstemp_inner.""" class mkstemped: _bflags = tempfile._bin_openflags _tflags = tempfile._text_openflags _close = os.close _unlink = os.unlink def __init__(self, dir, pre, suf, bin): if bin: flags = self._bflags else: flags = self._tflags output_type = tempfile._infer_return_type(dir, pre, suf) (self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags, output_type) def write(self, str): os.write(self.fd, str) def __del__(self): self._close(self.fd) self._unlink(self.name) def do_create(self, dir=None, pre=None, suf=None, bin=1): output_type = tempfile._infer_return_type(dir, pre, suf) if dir is None: if output_type is str: dir = tempfile.gettempdir() else: dir = tempfile.gettempdirb() if pre is None: pre = output_type() if suf is None: suf = output_type() file = self.mkstemped(dir, pre, suf, bin) self.nameCheck(file.name, dir, pre, suf) return file def test_basic(self): # _mkstemp_inner can create files self.do_create().write(b"blat") self.do_create(pre="a").write(b"blat") self.do_create(suf="b").write(b"blat") self.do_create(pre="a", suf="b").write(b"blat") self.do_create(pre="aa", suf=".txt").write(b"blat") def test_basic_with_bytes_names(self): # _mkstemp_inner can create files when given name parts all # specified as bytes. dir_b = tempfile.gettempdirb() self.do_create(dir=dir_b, suf=b"").write(b"blat") self.do_create(dir=dir_b, pre=b"a").write(b"blat") self.do_create(dir=dir_b, suf=b"b").write(b"blat") self.do_create(dir=dir_b, pre=b"a", suf=b"b").write(b"blat") self.do_create(dir=dir_b, pre=b"aa", suf=b".txt").write(b"blat") # Can't mix str & binary types in the args. with self.assertRaises(TypeError): self.do_create(dir="", suf=b"").write(b"blat") with self.assertRaises(TypeError): self.do_create(dir=dir_b, pre="").write(b"blat") with self.assertRaises(TypeError): self.do_create(dir=dir_b, pre=b"", suf="").write(b"blat") def test_basic_many(self): # _mkstemp_inner can create many files (stochastic) extant = list(range(TEST_FILES)) for i in extant: extant[i] = self.do_create(pre="aa") def test_choose_directory(self): # _mkstemp_inner can create files in a user-selected directory dir = tempfile.mkdtemp() try: self.do_create(dir=dir).write(b"blat") self.do_create(dir=pathlib.Path(dir)).write(b"blat") finally: os.rmdir(dir) @unittest.skipUnless(has_stat, 'os.stat not available') def test_file_mode(self): # _mkstemp_inner creates files with the proper mode file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) expected = 0o600 if sys.platform == 'win32': # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 expected = user * (1 + 8 + 64) self.assertEqual(mode, expected) @unittest.skipUnless(has_spawnl, 'os.spawnl not available') def test_noinherit(self): # _mkstemp_inner file handles are not inherited by child processes if support.verbose: v="v" else: v="q" file = self.do_create() self.assertEqual(os.get_inheritable(file.fd), False) fd = "%d" % file.fd try: me = __file__ except NameError: me = sys.argv[0] # We have to exec something, so that FD_CLOEXEC will take # effect. The core of this test is therefore in # tf_inherit_check.py, which see. tester = os.path.join(os.path.dirname(os.path.abspath(me)), "tf_inherit_check.py") # On Windows a spawn* /path/ with embedded spaces shouldn't be quoted, # but an arg with embedded spaces should be decorated with double # quotes on each end if sys.platform == 'win32': decorated = '"%s"' % sys.executable tester = '"%s"' % tester else: decorated = sys.executable retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd) self.assertFalse(retval < 0, "child process caught fatal signal %d" % -retval) self.assertFalse(retval > 0, "child process reports failure %d"%retval) @unittest.skipUnless(has_textmode, "text mode not available") def test_textmode(self): # _mkstemp_inner can create files in text mode # A text file is truncated at the first Ctrl+Z byte f = self.do_create(bin=0) f.write(b"blat\x1a") f.write(b"extra\n") os.lseek(f.fd, 0, os.SEEK_SET) self.assertEqual(os.read(f.fd, 20), b"blat") def make_temp(self): return tempfile._mkstemp_inner(tempfile.gettempdir(), tempfile.gettempprefix(), '', tempfile._bin_openflags, str) def test_collision_with_existing_file(self): # _mkstemp_inner tries another name when a file with # the chosen name already exists with _inside_empty_temp_dir(), \ _mock_candidate_names('aaa', 'aaa', 'bbb'): (fd1, name1) = self.make_temp() os.close(fd1) self.assertTrue(name1.endswith('aaa')) (fd2, name2) = self.make_temp() os.close(fd2) self.assertTrue(name2.endswith('bbb')) def test_collision_with_existing_directory(self): # _mkstemp_inner tries another name when a directory with # the chosen name already exists with _inside_empty_temp_dir(), \ _mock_candidate_names('aaa', 'aaa', 'bbb'): dir = tempfile.mkdtemp() self.assertTrue(dir.endswith('aaa')) (fd, name) = self.make_temp() os.close(fd) self.assertTrue(name.endswith('bbb')) class TestGetTempPrefix(BaseTestCase): """Test gettempprefix().""" def test_sane_template(self): # gettempprefix returns a nonempty prefix string p = tempfile.gettempprefix() self.assertIsInstance(p, str) self.assertGreater(len(p), 0) pb = tempfile.gettempprefixb() self.assertIsInstance(pb, bytes) self.assertGreater(len(pb), 0) def test_usable_template(self): # gettempprefix returns a usable prefix string # Create a temp directory, avoiding use of the prefix. # Then attempt to create a file whose name is # prefix + 'xxxxxx.xxx' in that directory. p = tempfile.gettempprefix() + "xxxxxx.xxx" d = tempfile.mkdtemp(prefix="") try: p = os.path.join(d, p) fd = os.open(p, os.O_RDWR | os.O_CREAT) os.close(fd) os.unlink(p) finally: os.rmdir(d) class TestGetTempDir(BaseTestCase): """Test gettempdir().""" def test_directory_exists(self): # gettempdir returns a directory which exists for d in (tempfile.gettempdir(), tempfile.gettempdirb()): self.assertTrue(os.path.isabs(d) or d == os.curdir, "%r is not an absolute path" % d) self.assertTrue(os.path.isdir(d), "%r is not a directory" % d) def test_directory_writable(self): # gettempdir returns a directory writable by the user # sneaky: just instantiate a NamedTemporaryFile, which # defaults to writing into the directory returned by # gettempdir. file = tempfile.NamedTemporaryFile() file.write(b"blat") file.close() def test_same_thing(self): # gettempdir always returns the same object a = tempfile.gettempdir() b = tempfile.gettempdir() c = tempfile.gettempdirb() self.assertTrue(a is b) self.assertNotEqual(type(a), type(c)) self.assertEqual(a, os.fsdecode(c)) def test_case_sensitive(self): # gettempdir should not flatten its case # even on a case-insensitive file system case_sensitive_tempdir = tempfile.mkdtemp("-Temp") _tempdir, tempfile.tempdir = tempfile.tempdir, None try: with support.EnvironmentVarGuard() as env: # Fake the first env var which is checked as a candidate env["TMPDIR"] = case_sensitive_tempdir self.assertEqual(tempfile.gettempdir(), case_sensitive_tempdir) finally: tempfile.tempdir = _tempdir support.rmdir(case_sensitive_tempdir) class TestMkstemp(BaseTestCase): """Test mkstemp().""" def do_create(self, dir=None, pre=None, suf=None): output_type = tempfile._infer_return_type(dir, pre, suf) if dir is None: if output_type is str: dir = tempfile.gettempdir() else: dir = tempfile.gettempdirb() if pre is None: pre = output_type() if suf is None: suf = output_type() (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf) (ndir, nbase) = os.path.split(name) adir = os.path.abspath(dir) self.assertEqual(adir, ndir, "Directory '%s' incorrectly returned as '%s'" % (adir, ndir)) try: self.nameCheck(name, dir, pre, suf) finally: os.close(fd) os.unlink(name) def test_basic(self): # mkstemp can create files self.do_create() self.do_create(pre="a") self.do_create(suf="b") self.do_create(pre="a", suf="b") self.do_create(pre="aa", suf=".txt") self.do_create(dir=".") def test_basic_with_bytes_names(self): # mkstemp can create files when given name parts all # specified as bytes. d = tempfile.gettempdirb() self.do_create(dir=d, suf=b"") self.do_create(dir=d, pre=b"a") self.do_create(dir=d, suf=b"b") self.do_create(dir=d, pre=b"a", suf=b"b") self.do_create(dir=d, pre=b"aa", suf=b".txt") self.do_create(dir=b".") with self.assertRaises(TypeError): self.do_create(dir=".", pre=b"aa", suf=b".txt") with self.assertRaises(TypeError): self.do_create(dir=b".", pre="aa", suf=b".txt") with self.assertRaises(TypeError): self.do_create(dir=b".", pre=b"aa", suf=".txt") def test_choose_directory(self): # mkstemp can create directories in a user-selected directory dir = tempfile.mkdtemp() try: self.do_create(dir=dir) self.do_create(dir=pathlib.Path(dir)) finally: os.rmdir(dir) class TestMkdtemp(TestBadTempdir, BaseTestCase): """Test mkdtemp().""" def make_temp(self): return tempfile.mkdtemp() def do_create(self, dir=None, pre=None, suf=None): output_type = tempfile._infer_return_type(dir, pre, suf) if dir is None: if output_type is str: dir = tempfile.gettempdir() else: dir = tempfile.gettempdirb() if pre is None: pre = output_type() if suf is None: suf = output_type() name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf) try: self.nameCheck(name, dir, pre, suf) return name except: os.rmdir(name) raise def test_basic(self): # mkdtemp can create directories os.rmdir(self.do_create()) os.rmdir(self.do_create(pre="a")) os.rmdir(self.do_create(suf="b")) os.rmdir(self.do_create(pre="a", suf="b")) os.rmdir(self.do_create(pre="aa", suf=".txt")) def test_basic_with_bytes_names(self): # mkdtemp can create directories when given all binary parts d = tempfile.gettempdirb() os.rmdir(self.do_create(dir=d)) os.rmdir(self.do_create(dir=d, pre=b"a")) os.rmdir(self.do_create(dir=d, suf=b"b")) os.rmdir(self.do_create(dir=d, pre=b"a", suf=b"b")) os.rmdir(self.do_create(dir=d, pre=b"aa", suf=b".txt")) with self.assertRaises(TypeError): os.rmdir(self.do_create(dir=d, pre="aa", suf=b".txt")) with self.assertRaises(TypeError): os.rmdir(self.do_create(dir=d, pre=b"aa", suf=".txt")) with self.assertRaises(TypeError): os.rmdir(self.do_create(dir="", pre=b"aa", suf=b".txt")) def test_basic_many(self): # mkdtemp can create many directories (stochastic) extant = list(range(TEST_FILES)) try: for i in extant: extant[i] = self.do_create(pre="aa") finally: for i in extant: if(isinstance(i, str)): os.rmdir(i) def test_choose_directory(self): # mkdtemp can create directories in a user-selected directory dir = tempfile.mkdtemp() try: os.rmdir(self.do_create(dir=dir)) os.rmdir(self.do_create(dir=pathlib.Path(dir))) finally: os.rmdir(dir) @unittest.skipUnless(has_stat, 'os.stat not available') def test_mode(self): # mkdtemp creates directories with the proper mode dir = self.do_create() try: mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0o777 # Mask off sticky bits inherited from /tmp expected = 0o700 if sys.platform == 'win32': # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 expected = user * (1 + 8 + 64) self.assertEqual(mode, expected) finally: os.rmdir(dir) def test_collision_with_existing_file(self): # mkdtemp tries another name when a file with # the chosen name already exists with _inside_empty_temp_dir(), \ _mock_candidate_names('aaa', 'aaa', 'bbb'): file = tempfile.NamedTemporaryFile(delete=False) file.close() self.assertTrue(file.name.endswith('aaa')) dir = tempfile.mkdtemp() self.assertTrue(dir.endswith('bbb')) def test_collision_with_existing_directory(self): # mkdtemp tries another name when a directory with # the chosen name already exists with _inside_empty_temp_dir(), \ _mock_candidate_names('aaa', 'aaa', 'bbb'): dir1 = tempfile.mkdtemp() self.assertTrue(dir1.endswith('aaa')) dir2 = tempfile.mkdtemp() self.assertTrue(dir2.endswith('bbb')) class TestMktemp(BaseTestCase): """Test mktemp().""" # For safety, all use of mktemp must occur in a private directory. # We must also suppress the RuntimeWarning it generates. def setUp(self): self.dir = tempfile.mkdtemp() super().setUp() def tearDown(self): if self.dir: os.rmdir(self.dir) self.dir = None super().tearDown() class mktemped: _unlink = os.unlink _bflags = tempfile._bin_openflags def __init__(self, dir, pre, suf): self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf) # Create the file. This will raise an exception if it's # mysteriously appeared in the meanwhile. os.close(os.open(self.name, self._bflags, 0o600)) def __del__(self): self._unlink(self.name) def do_create(self, pre="", suf=""): file = self.mktemped(self.dir, pre, suf) self.nameCheck(file.name, self.dir, pre, suf) return file def test_basic(self): # mktemp can choose usable file names self.do_create() self.do_create(pre="a") self.do_create(suf="b") self.do_create(pre="a", suf="b") self.do_create(pre="aa", suf=".txt") def test_many(self): # mktemp can choose many usable file names (stochastic) extant = list(range(TEST_FILES)) for i in extant: extant[i] = self.do_create(pre="aa") ## def test_warning(self): ## # mktemp issues a warning when used ## warnings.filterwarnings("error", ## category=RuntimeWarning, ## message="mktemp") ## self.assertRaises(RuntimeWarning, ## tempfile.mktemp, dir=self.dir) # We test _TemporaryFileWrapper by testing NamedTemporaryFile. class TestNamedTemporaryFile(BaseTestCase): """Test NamedTemporaryFile().""" def do_create(self, dir=None, pre="", suf="", delete=True): if dir is None: dir = tempfile.gettempdir() file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf, delete=delete) self.nameCheck(file.name, dir, pre, suf) return file def test_basic(self): # NamedTemporaryFile can create files self.do_create() self.do_create(pre="a") self.do_create(suf="b") self.do_create(pre="a", suf="b") self.do_create(pre="aa", suf=".txt") def test_method_lookup(self): # Issue #18879: Looking up a temporary file method should keep it # alive long enough. f = self.do_create() wr = weakref.ref(f) write = f.write write2 = f.write del f write(b'foo') del write write2(b'bar') del write2 if support.check_impl_detail(cpython=True): # No reference cycle was created. self.assertIsNone(wr()) def test_iter(self): # Issue #23700: getting iterator from a temporary file should keep # it alive as long as it's being iterated over lines = [b'spam\n', b'eggs\n', b'beans\n'] def make_file(): f = tempfile.NamedTemporaryFile(mode='w+b') f.write(b''.join(lines)) f.seek(0) return f for i, l in enumerate(make_file()): self.assertEqual(l, lines[i]) self.assertEqual(i, len(lines) - 1) def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile() self.assertTrue(os.path.exists(f.name), "NamedTemporaryFile %s does not exist" % f.name) def test_del_on_close(self): # A NamedTemporaryFile is deleted when closed dir = tempfile.mkdtemp() try: f = tempfile.NamedTemporaryFile(dir=dir) f.write(b'blat') f.close() self.assertFalse(os.path.exists(f.name), "NamedTemporaryFile %s exists after close" % f.name) finally: os.rmdir(dir) def test_dis_del_on_close(self): # Tests that delete-on-close can be disabled dir = tempfile.mkdtemp() tmp = None try: f = tempfile.NamedTemporaryFile(dir=dir, delete=False) tmp = f.name f.write(b'blat') f.close() self.assertTrue(os.path.exists(f.name), "NamedTemporaryFile %s missing after close" % f.name) finally: if tmp is not None: os.unlink(tmp) os.rmdir(dir) def test_multiple_close(self): # A NamedTemporaryFile can be closed many times without error
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_html.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_html.py
""" Tests for the html module functions. """ import html import unittest class HtmlTests(unittest.TestCase): def test_escape(self): self.assertEqual( html.escape('\'<script>"&foo;"</script>\''), '&#x27;&lt;script&gt;&quot;&amp;foo;&quot;&lt;/script&gt;&#x27;') self.assertEqual( html.escape('\'<script>"&foo;"</script>\'', False), '\'&lt;script&gt;"&amp;foo;"&lt;/script&gt;\'') def test_unescape(self): numeric_formats = ['&#%d', '&#%d;', '&#x%x', '&#x%x;'] errmsg = 'unescape(%r) should have returned %r' def check(text, expected): self.assertEqual(html.unescape(text), expected, msg=errmsg % (text, expected)) def check_num(num, expected): for format in numeric_formats: text = format % num self.assertEqual(html.unescape(text), expected, msg=errmsg % (text, expected)) # check text with no character references check('no character references', 'no character references') # check & followed by invalid chars check('&\n&\t& &&', '&\n&\t& &&') # check & followed by numbers and letters check('&0 &9 &a &0; &9; &a;', '&0 &9 &a &0; &9; &a;') # check incomplete entities at the end of the string for x in ['&', '&#', '&#x', '&#X', '&#y', '&#xy', '&#Xy']: check(x, x) check(x+';', x+';') # check several combinations of numeric character references, # possibly followed by different characters formats = ['&#%d', '&#%07d', '&#%d;', '&#%07d;', '&#x%x', '&#x%06x', '&#x%x;', '&#x%06x;', '&#x%X', '&#x%06X', '&#X%x;', '&#X%06x;'] for num, char in zip([65, 97, 34, 38, 0x2603, 0x101234], ['A', 'a', '"', '&', '\u2603', '\U00101234']): for s in formats: check(s % num, char) for end in [' ', 'X']: check((s+end) % num, char+end) # check invalid code points for cp in [0xD800, 0xDB00, 0xDC00, 0xDFFF, 0x110000]: check_num(cp, '\uFFFD') # check more invalid code points for cp in [0x1, 0xb, 0xe, 0x7f, 0xfffe, 0xffff, 0x10fffe, 0x10ffff]: check_num(cp, '') # check invalid numbers for num, ch in zip([0x0d, 0x80, 0x95, 0x9d], '\r\u20ac\u2022\x9d'): check_num(num, ch) # check small numbers check_num(0, '\uFFFD') check_num(9, '\t') # check a big number check_num(1000000000000000000, '\uFFFD') # check that multiple trailing semicolons are handled correctly for e in ['&quot;;', '&#34;;', '&#x22;;', '&#X22;;']: check(e, '";') # check that semicolons in the middle don't create problems for e in ['&quot;quot;', '&#34;quot;', '&#x22;quot;', '&#X22;quot;']: check(e, '"quot;') # check triple adjacent charrefs for e in ['&quot', '&#34', '&#x22', '&#X22']: check(e*3, '"""') check((e+';')*3, '"""') # check that the case is respected for e in ['&amp', '&amp;', '&AMP', '&AMP;']: check(e, '&') for e in ['&Amp', '&Amp;']: check(e, e) # check that non-existent named entities are returned unchanged check('&svadilfari;', '&svadilfari;') # the following examples are in the html5 specs check('&notit', '¬it') check('&notit;', '¬it;') check('&notin', '¬in') check('&notin;', '∉') # a similar example with a long name check('&notReallyAnExistingNamedCharacterReference;', '¬ReallyAnExistingNamedCharacterReference;') # longest valid name check('&CounterClockwiseContourIntegral;', '∳') # check a charref that maps to two unicode chars check('&acE;', '\u223E\u0333') check('&acE', '&acE') # see #12888 check('&#123; ' * 1050, '{ ' * 1050) # see #15156 check('&Eacuteric&Eacute;ric&alphacentauri&alpha;centauri', 'ÉricÉric&alphacentauriαcentauri') check('&co;', '&co;') 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_memoryview.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_memoryview.py
"""Unit tests for the memoryview Some tests are in test_bytes. Many tests that require _testbuffer.ndarray are in test_buffer. """ import unittest import test.support import sys import gc import weakref import array import io import copy import pickle class AbstractMemoryTests: source_bytes = b"abcdef" @property def _source(self): return self.source_bytes @property def _types(self): return filter(None, [self.ro_type, self.rw_type]) def check_getitem_with_type(self, tp): b = tp(self._source) oldrefcount = sys.getrefcount(b) m = self._view(b) self.assertEqual(m[0], ord(b"a")) self.assertIsInstance(m[0], int) self.assertEqual(m[5], ord(b"f")) self.assertEqual(m[-1], ord(b"f")) self.assertEqual(m[-6], ord(b"a")) # Bounds checking self.assertRaises(IndexError, lambda: m[6]) self.assertRaises(IndexError, lambda: m[-7]) self.assertRaises(IndexError, lambda: m[sys.maxsize]) self.assertRaises(IndexError, lambda: m[-sys.maxsize]) # Type checking self.assertRaises(TypeError, lambda: m[None]) self.assertRaises(TypeError, lambda: m[0.0]) self.assertRaises(TypeError, lambda: m["a"]) m = None self.assertEqual(sys.getrefcount(b), oldrefcount) def test_getitem(self): for tp in self._types: self.check_getitem_with_type(tp) def test_iter(self): for tp in self._types: b = tp(self._source) m = self._view(b) self.assertEqual(list(m), [m[i] for i in range(len(m))]) def test_setitem_readonly(self): if not self.ro_type: self.skipTest("no read-only type to test") b = self.ro_type(self._source) oldrefcount = sys.getrefcount(b) m = self._view(b) def setitem(value): m[0] = value self.assertRaises(TypeError, setitem, b"a") self.assertRaises(TypeError, setitem, 65) self.assertRaises(TypeError, setitem, memoryview(b"a")) m = None self.assertEqual(sys.getrefcount(b), oldrefcount) def test_setitem_writable(self): if not self.rw_type: self.skipTest("no writable type to test") tp = self.rw_type b = self.rw_type(self._source) oldrefcount = sys.getrefcount(b) m = self._view(b) m[0] = ord(b'1') self._check_contents(tp, b, b"1bcdef") m[0:1] = tp(b"0") self._check_contents(tp, b, b"0bcdef") m[1:3] = tp(b"12") self._check_contents(tp, b, b"012def") m[1:1] = tp(b"") self._check_contents(tp, b, b"012def") m[:] = tp(b"abcdef") self._check_contents(tp, b, b"abcdef") # Overlapping copies of a view into itself m[0:3] = m[2:5] self._check_contents(tp, b, b"cdedef") m[:] = tp(b"abcdef") m[2:5] = m[0:3] self._check_contents(tp, b, b"ababcf") def setitem(key, value): m[key] = tp(value) # Bounds checking self.assertRaises(IndexError, setitem, 6, b"a") self.assertRaises(IndexError, setitem, -7, b"a") self.assertRaises(IndexError, setitem, sys.maxsize, b"a") self.assertRaises(IndexError, setitem, -sys.maxsize, b"a") # Wrong index/slice types self.assertRaises(TypeError, setitem, 0.0, b"a") self.assertRaises(TypeError, setitem, (0,), b"a") self.assertRaises(TypeError, setitem, (slice(0,1,1), 0), b"a") self.assertRaises(TypeError, setitem, (0, slice(0,1,1)), b"a") self.assertRaises(TypeError, setitem, (0,), b"a") self.assertRaises(TypeError, setitem, "a", b"a") # Not implemented: multidimensional slices slices = (slice(0,1,1), slice(0,1,2)) self.assertRaises(NotImplementedError, setitem, slices, b"a") # Trying to resize the memory object exc = ValueError if m.format == 'c' else TypeError self.assertRaises(exc, setitem, 0, b"") self.assertRaises(exc, setitem, 0, b"ab") self.assertRaises(ValueError, setitem, slice(1,1), b"a") self.assertRaises(ValueError, setitem, slice(0,2), b"a") m = None self.assertEqual(sys.getrefcount(b), oldrefcount) def test_delitem(self): for tp in self._types: b = tp(self._source) m = self._view(b) with self.assertRaises(TypeError): del m[1] with self.assertRaises(TypeError): del m[1:4] def test_tobytes(self): for tp in self._types: m = self._view(tp(self._source)) b = m.tobytes() # This calls self.getitem_type() on each separate byte of b"abcdef" expected = b"".join( self.getitem_type(bytes([c])) for c in b"abcdef") self.assertEqual(b, expected) self.assertIsInstance(b, bytes) def test_tolist(self): for tp in self._types: m = self._view(tp(self._source)) l = m.tolist() self.assertEqual(l, list(b"abcdef")) def test_compare(self): # memoryviews can compare for equality with other objects # having the buffer interface. for tp in self._types: m = self._view(tp(self._source)) for tp_comp in self._types: self.assertTrue(m == tp_comp(b"abcdef")) self.assertFalse(m != tp_comp(b"abcdef")) self.assertFalse(m == tp_comp(b"abcde")) self.assertTrue(m != tp_comp(b"abcde")) self.assertFalse(m == tp_comp(b"abcde1")) self.assertTrue(m != tp_comp(b"abcde1")) self.assertTrue(m == m) self.assertTrue(m == m[:]) self.assertTrue(m[0:6] == m[:]) self.assertFalse(m[0:5] == m) # Comparison with objects which don't support the buffer API self.assertFalse(m == "abcdef") self.assertTrue(m != "abcdef") self.assertFalse("abcdef" == m) self.assertTrue("abcdef" != m) # Unordered comparisons for c in (m, b"abcdef"): self.assertRaises(TypeError, lambda: m < c) self.assertRaises(TypeError, lambda: c <= m) self.assertRaises(TypeError, lambda: m >= c) self.assertRaises(TypeError, lambda: c > m) def check_attributes_with_type(self, tp): m = self._view(tp(self._source)) self.assertEqual(m.format, self.format) self.assertEqual(m.itemsize, self.itemsize) self.assertEqual(m.ndim, 1) self.assertEqual(m.shape, (6,)) self.assertEqual(len(m), 6) self.assertEqual(m.strides, (self.itemsize,)) self.assertEqual(m.suboffsets, ()) return m def test_attributes_readonly(self): if not self.ro_type: self.skipTest("no read-only type to test") m = self.check_attributes_with_type(self.ro_type) self.assertEqual(m.readonly, True) def test_attributes_writable(self): if not self.rw_type: self.skipTest("no writable type to test") m = self.check_attributes_with_type(self.rw_type) self.assertEqual(m.readonly, False) def test_getbuffer(self): # Test PyObject_GetBuffer() on a memoryview object. for tp in self._types: b = tp(self._source) oldrefcount = sys.getrefcount(b) m = self._view(b) oldviewrefcount = sys.getrefcount(m) s = str(m, "utf-8") self._check_contents(tp, b, s.encode("utf-8")) self.assertEqual(sys.getrefcount(m), oldviewrefcount) m = None self.assertEqual(sys.getrefcount(b), oldrefcount) def test_gc(self): for tp in self._types: if not isinstance(tp, type): # If tp is a factory rather than a plain type, skip continue class MyView(): def __init__(self, base): self.m = memoryview(base) class MySource(tp): pass class MyObject: pass # Create a reference cycle through a memoryview object. # This exercises mbuf_clear(). b = MySource(tp(b'abc')) m = self._view(b) o = MyObject() b.m = m b.o = o wr = weakref.ref(o) b = m = o = None # The cycle must be broken gc.collect() self.assertTrue(wr() is None, wr()) # This exercises memory_clear(). m = MyView(tp(b'abc')) o = MyObject() m.x = m m.o = o wr = weakref.ref(o) m = o = None # The cycle must be broken gc.collect() self.assertTrue(wr() is None, wr()) def _check_released(self, m, tp): check = self.assertRaisesRegex(ValueError, "released") with check: bytes(m) with check: m.tobytes() with check: m.tolist() with check: m[0] with check: m[0] = b'x' with check: len(m) with check: m.format with check: m.itemsize with check: m.ndim with check: m.readonly with check: m.shape with check: m.strides with check: with m: pass # str() and repr() still function self.assertIn("released memory", str(m)) self.assertIn("released memory", repr(m)) self.assertEqual(m, m) self.assertNotEqual(m, memoryview(tp(self._source))) self.assertNotEqual(m, tp(self._source)) def test_contextmanager(self): for tp in self._types: b = tp(self._source) m = self._view(b) with m as cm: self.assertIs(cm, m) self._check_released(m, tp) m = self._view(b) # Can release explicitly inside the context manager with m: m.release() def test_release(self): for tp in self._types: b = tp(self._source) m = self._view(b) m.release() self._check_released(m, tp) # Can be called a second time (it's a no-op) m.release() self._check_released(m, tp) def test_writable_readonly(self): # Issue #10451: memoryview incorrectly exposes a readonly # buffer as writable causing a segfault if using mmap tp = self.ro_type if tp is None: self.skipTest("no read-only type to test") b = tp(self._source) m = self._view(b) i = io.BytesIO(b'ZZZZ') self.assertRaises(TypeError, i.readinto, m) def test_getbuf_fail(self): self.assertRaises(TypeError, self._view, {}) def test_hash(self): # Memoryviews of readonly (hashable) types are hashable, and they # hash as hash(obj.tobytes()). tp = self.ro_type if tp is None: self.skipTest("no read-only type to test") b = tp(self._source) m = self._view(b) self.assertEqual(hash(m), hash(b"abcdef")) # Releasing the memoryview keeps the stored hash value (as with weakrefs) m.release() self.assertEqual(hash(m), hash(b"abcdef")) # Hashing a memoryview for the first time after it is released # results in an error (as with weakrefs). m = self._view(b) m.release() self.assertRaises(ValueError, hash, m) def test_hash_writable(self): # Memoryviews of writable types are unhashable tp = self.rw_type if tp is None: self.skipTest("no writable type to test") b = tp(self._source) m = self._view(b) self.assertRaises(ValueError, hash, m) def test_weakref(self): # Check memoryviews are weakrefable for tp in self._types: b = tp(self._source) m = self._view(b) L = [] def callback(wr, b=b): L.append(b) wr = weakref.ref(m, callback) self.assertIs(wr(), m) del m test.support.gc_collect() self.assertIs(wr(), None) self.assertIs(L[0], b) def test_reversed(self): for tp in self._types: b = tp(self._source) m = self._view(b) aslist = list(reversed(m.tolist())) self.assertEqual(list(reversed(m)), aslist) self.assertEqual(list(reversed(m)), list(m[::-1])) def test_issue22668(self): a = array.array('H', [256, 256, 256, 256]) x = memoryview(a) m = x.cast('B') b = m.cast('H') c = b[0:2] d = memoryview(b) del b self.assertEqual(c[0], 256) self.assertEqual(d[0], 256) self.assertEqual(c.format, "H") self.assertEqual(d.format, "H") _ = m.cast('I') self.assertEqual(c[0], 256) self.assertEqual(d[0], 256) self.assertEqual(c.format, "H") self.assertEqual(d.format, "H") # Variations on source objects for the buffer: bytes-like objects, then arrays # with itemsize > 1. # NOTE: support for multi-dimensional objects is unimplemented. class BaseBytesMemoryTests(AbstractMemoryTests): ro_type = bytes rw_type = bytearray getitem_type = bytes itemsize = 1 format = 'B' class BaseArrayMemoryTests(AbstractMemoryTests): ro_type = None rw_type = lambda self, b: array.array('i', list(b)) getitem_type = lambda self, b: array.array('i', list(b)).tobytes() itemsize = array.array('i').itemsize format = 'i' @unittest.skip('XXX test should be adapted for non-byte buffers') def test_getbuffer(self): pass @unittest.skip('XXX NotImplementedError: tolist() only supports byte views') def test_tolist(self): pass # Variations on indirection levels: memoryview, slice of memoryview, # slice of slice of memoryview. # This is important to test allocation subtleties. class BaseMemoryviewTests: def _view(self, obj): return memoryview(obj) def _check_contents(self, tp, obj, contents): self.assertEqual(obj, tp(contents)) class BaseMemorySliceTests: source_bytes = b"XabcdefY" def _view(self, obj): m = memoryview(obj) return m[1:7] def _check_contents(self, tp, obj, contents): self.assertEqual(obj[1:7], tp(contents)) def test_refs(self): for tp in self._types: m = memoryview(tp(self._source)) oldrefcount = sys.getrefcount(m) m[1:2] self.assertEqual(sys.getrefcount(m), oldrefcount) class BaseMemorySliceSliceTests: source_bytes = b"XabcdefY" def _view(self, obj): m = memoryview(obj) return m[:7][1:] def _check_contents(self, tp, obj, contents): self.assertEqual(obj[1:7], tp(contents)) # Concrete test classes class BytesMemoryviewTest(unittest.TestCase, BaseMemoryviewTests, BaseBytesMemoryTests): def test_constructor(self): for tp in self._types: ob = tp(self._source) self.assertTrue(memoryview(ob)) self.assertTrue(memoryview(object=ob)) self.assertRaises(TypeError, memoryview) self.assertRaises(TypeError, memoryview, ob, ob) self.assertRaises(TypeError, memoryview, argument=ob) self.assertRaises(TypeError, memoryview, ob, argument=True) class ArrayMemoryviewTest(unittest.TestCase, BaseMemoryviewTests, BaseArrayMemoryTests): def test_array_assign(self): # Issue #4569: segfault when mutating a memoryview with itemsize != 1 a = array.array('i', range(10)) m = memoryview(a) new_a = array.array('i', range(9, -1, -1)) m[:] = new_a self.assertEqual(a, new_a) class BytesMemorySliceTest(unittest.TestCase, BaseMemorySliceTests, BaseBytesMemoryTests): pass class ArrayMemorySliceTest(unittest.TestCase, BaseMemorySliceTests, BaseArrayMemoryTests): pass class BytesMemorySliceSliceTest(unittest.TestCase, BaseMemorySliceSliceTests, BaseBytesMemoryTests): pass class ArrayMemorySliceSliceTest(unittest.TestCase, BaseMemorySliceSliceTests, BaseArrayMemoryTests): pass class OtherTest(unittest.TestCase): def test_ctypes_cast(self): # Issue 15944: Allow all source formats when casting to bytes. ctypes = test.support.import_module("ctypes") p6 = bytes(ctypes.c_double(0.6)) d = ctypes.c_double() m = memoryview(d).cast("B") m[:2] = p6[:2] m[2:] = p6[2:] self.assertEqual(d.value, 0.6) for format in "Bbc": with self.subTest(format): d = ctypes.c_double() m = memoryview(d).cast(format) m[:2] = memoryview(p6).cast(format)[:2] m[2:] = memoryview(p6).cast(format)[2:] self.assertEqual(d.value, 0.6) def test_memoryview_hex(self): # Issue #9951: memoryview.hex() segfaults with non-contiguous buffers. x = b'0' * 200000 m1 = memoryview(x) m2 = m1[::-1] self.assertEqual(m2.hex(), '30' * 200000) def test_copy(self): m = memoryview(b'abc') with self.assertRaises(TypeError): copy.copy(m) def test_pickle(self): m = memoryview(b'abc') for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError): pickle.dumps(m, proto) 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_capi.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_capi.py
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _testcapi exports whose name begins with 'test_'. from collections import OrderedDict import os import pickle import random import re import subprocess import sys import sysconfig import textwrap import threading import time import unittest from test import support from test.support import MISSING_C_DOCSTRINGS from test.support.script_helper import assert_python_failure, assert_python_ok try: import _posixsubprocess except ImportError: _posixsubprocess = None # Skip this test if the _testcapi module isn't available. _testcapi = support.import_module('_testcapi') # Were we compiled --with-pydebug or with #define Py_DEBUG? Py_DEBUG = hasattr(sys, 'gettotalrefcount') def testfunction(self): """some doc""" return self class InstanceMethod: id = _testcapi.instancemethod(id) testfunction = _testcapi.instancemethod(testfunction) class CAPITest(unittest.TestCase): def test_instancemethod(self): inst = InstanceMethod() self.assertEqual(id(inst), inst.id()) self.assertTrue(inst.testfunction() is inst) self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__) self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__) InstanceMethod.testfunction.attribute = "test" self.assertEqual(testfunction.attribute, "test") self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") def test_no_FatalError_infinite_loop(self): with support.SuppressCrashReport(): p = subprocess.Popen([sys.executable, "-c", 'import _testcapi;' '_testcapi.crash_no_current_thread()'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() self.assertEqual(out, b'') # This used to cause an infinite loop. self.assertTrue(err.rstrip().startswith( b'Fatal Python error:' b' PyThreadState_Get: no current thread')) def test_memoryview_from_NULL_pointer(self): self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer) def test_exc_info(self): raised_exception = ValueError("5") new_exc = TypeError("TEST") try: raise raised_exception except ValueError as e: tb = e.__traceback__ orig_sys_exc_info = sys.exc_info() orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None) new_sys_exc_info = sys.exc_info() new_exc_info = _testcapi.set_exc_info(*orig_exc_info) reset_sys_exc_info = sys.exc_info() self.assertEqual(orig_exc_info[1], e) self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb)) self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info) self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info) self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None)) self.assertSequenceEqual(new_sys_exc_info, new_exc_info) else: self.assertTrue(False) @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.') def test_seq_bytes_to_charp_array(self): # Issue #15732: crash in _PySequence_BytesToCharpArray() class Z(object): def __len__(self): return 1 self.assertRaises(TypeError, _posixsubprocess.fork_exec, 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17) # Issue #15736: overflow in _PySequence_BytesToCharpArray() class Z(object): def __len__(self): return sys.maxsize def __getitem__(self, i): return b'x' self.assertRaises(MemoryError, _posixsubprocess.fork_exec, 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17) @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.') def test_subprocess_fork_exec(self): class Z(object): def __len__(self): return 1 # Issue #15738: crash in subprocess_fork_exec() self.assertRaises(TypeError, _posixsubprocess.fork_exec, Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17) @unittest.skipIf(MISSING_C_DOCSTRINGS, "Signature information for builtins requires docstrings") def test_docstring_signature_parsing(self): self.assertEqual(_testcapi.no_docstring.__doc__, None) self.assertEqual(_testcapi.no_docstring.__text_signature__, None) self.assertEqual(_testcapi.docstring_empty.__doc__, None) self.assertEqual(_testcapi.docstring_empty.__text_signature__, None) self.assertEqual(_testcapi.docstring_no_signature.__doc__, "This docstring has no signature.") self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None) self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__, "docstring_with_invalid_signature($module, /, boo)\n" "\n" "This docstring has an invalid signature." ) self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None) self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__, "docstring_with_invalid_signature2($module, /, boo)\n" "\n" "--\n" "\n" "This docstring also has an invalid signature." ) self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None) self.assertEqual(_testcapi.docstring_with_signature.__doc__, "This docstring has a valid signature.") self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)") self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None) self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__, "($module, /, sig)") self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__, "\nThis docstring has a valid signature and some extra newlines.") self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__, "($module, /, parameter)") def test_c_type_with_matrix_multiplication(self): M = _testcapi.matmulType m1 = M() m2 = M() self.assertEqual(m1 @ m2, ("matmul", m1, m2)) self.assertEqual(m1 @ 42, ("matmul", m1, 42)) self.assertEqual(42 @ m1, ("matmul", 42, m1)) o = m1 o @= m2 self.assertEqual(o, ("imatmul", m1, m2)) o = m1 o @= 42 self.assertEqual(o, ("imatmul", m1, 42)) o = 42 o @= m1 self.assertEqual(o, ("matmul", 42, m1)) def test_return_null_without_error(self): # Issue #23571: A function must not return NULL without setting an # error if Py_DEBUG: code = textwrap.dedent(""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.return_null_without_error() """) rc, out, err = assert_python_failure('-c', code) self.assertRegex(err.replace(b'\r', b''), br'Fatal Python error: a function returned NULL ' br'without setting an error\n' br'SystemError: <built-in function ' br'return_null_without_error> returned NULL ' br'without setting an error\n' br'\n' br'Current thread.*:\n' br' File .*", line 6 in <module>') else: with self.assertRaises(SystemError) as cm: _testcapi.return_null_without_error() self.assertRegex(str(cm.exception), 'return_null_without_error.* ' 'returned NULL without setting an error') def test_return_result_with_error(self): # Issue #23571: A function must not return a result with an error set if Py_DEBUG: code = textwrap.dedent(""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.return_result_with_error() """) rc, out, err = assert_python_failure('-c', code) self.assertRegex(err.replace(b'\r', b''), br'Fatal Python error: a function returned a ' br'result with an error set\n' br'ValueError\n' br'\n' br'The above exception was the direct cause ' br'of the following exception:\n' br'\n' br'SystemError: <built-in ' br'function return_result_with_error> ' br'returned a result with an error set\n' br'\n' br'Current thread.*:\n' br' File .*, line 6 in <module>') else: with self.assertRaises(SystemError) as cm: _testcapi.return_result_with_error() self.assertRegex(str(cm.exception), 'return_result_with_error.* ' 'returned a result with an error set') def test_buildvalue_N(self): _testcapi.test_buildvalue_N() def test_set_nomemory(self): code = """if 1: import _testcapi class C(): pass # The first loop tests both functions and that remove_mem_hooks() # can be called twice in a row. The second loop checks a call to # set_nomemory() after a call to remove_mem_hooks(). The third # loop checks the start and stop arguments of set_nomemory(). for outer_cnt in range(1, 4): start = 10 * outer_cnt for j in range(100): if j == 0: if outer_cnt != 3: _testcapi.set_nomemory(start) else: _testcapi.set_nomemory(start, start + 1) try: C() except MemoryError as e: if outer_cnt != 3: _testcapi.remove_mem_hooks() print('MemoryError', outer_cnt, j) _testcapi.remove_mem_hooks() break """ rc, out, err = assert_python_ok('-c', code) self.assertIn(b'MemoryError 1 10', out) self.assertIn(b'MemoryError 2 20', out) self.assertIn(b'MemoryError 3 30', out) def test_mapping_keys_values_items(self): class Mapping1(dict): def keys(self): return list(super().keys()) def values(self): return list(super().values()) def items(self): return list(super().items()) class Mapping2(dict): def keys(self): return tuple(super().keys()) def values(self): return tuple(super().values()) def items(self): return tuple(super().items()) dict_obj = {'foo': 1, 'bar': 2, 'spam': 3} for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(), dict_obj, OrderedDict(dict_obj), Mapping1(dict_obj), Mapping2(dict_obj)]: self.assertListEqual(_testcapi.get_mapping_keys(mapping), list(mapping.keys())) self.assertListEqual(_testcapi.get_mapping_values(mapping), list(mapping.values())) self.assertListEqual(_testcapi.get_mapping_items(mapping), list(mapping.items())) def test_mapping_keys_values_items_bad_arg(self): self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None) self.assertRaises(AttributeError, _testcapi.get_mapping_values, None) self.assertRaises(AttributeError, _testcapi.get_mapping_items, None) class BadMapping: def keys(self): return None def values(self): return None def items(self): return None bad_mapping = BadMapping() self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping) self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping) self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping) class TestPendingCalls(unittest.TestCase): def pendingcalls_submit(self, l, n): def callback(): #this function can be interrupted by thread switching so let's #use an atomic operation l.append(None) for i in range(n): time.sleep(random.random()*0.02) #0.01 secs on average #try submitting callback until successful. #rely on regular interrupt to flush queue if we are #unsuccessful. while True: if _testcapi._pending_threadfunc(callback): break; def pendingcalls_wait(self, l, n, context = None): #now, stick around until l[0] has grown to 10 count = 0; while len(l) != n: #this busy loop is where we expect to be interrupted to #run our callbacks. Note that callbacks are only run on the #main thread if False and support.verbose: print("(%i)"%(len(l),),) for i in range(1000): a = i*i if context and not context.event.is_set(): continue count += 1 self.assertTrue(count < 10000, "timeout waiting for %i callbacks, got %i"%(n, len(l))) if False and support.verbose: print("(%i)"%(len(l),)) def test_pendingcalls_threaded(self): #do every callback on a separate thread n = 32 #total callbacks threads = [] class foo(object):pass context = foo() context.l = [] context.n = 2 #submits per thread context.nThreads = n // context.n context.nFinished = 0 context.lock = threading.Lock() context.event = threading.Event() threads = [threading.Thread(target=self.pendingcalls_thread, args=(context,)) for i in range(context.nThreads)] with support.start_threads(threads): self.pendingcalls_wait(context.l, n, context) def pendingcalls_thread(self, context): try: self.pendingcalls_submit(context.l, context.n) finally: with context.lock: context.nFinished += 1 nFinished = context.nFinished if False and support.verbose: print("finished threads: ", nFinished) if nFinished == context.nThreads: context.event.set() def test_pendingcalls_non_threaded(self): #again, just using the main thread, likely they will all be dispatched at #once. It is ok to ask for too many, because we loop until we find a slot. #the loop can be interrupted to dispatch. #there are only 32 dispatch slots, so we go for twice that! l = [] n = 64 self.pendingcalls_submit(l, n) self.pendingcalls_wait(l, n) class SubinterpreterTest(unittest.TestCase): def test_subinterps(self): import builtins r, w = os.pipe() code = """if 1: import sys, builtins, pickle with open({:d}, "wb") as f: pickle.dump(id(sys.modules), f) pickle.dump(id(builtins), f) """.format(w) with open(r, "rb") as f: ret = support.run_in_subinterp(code) self.assertEqual(ret, 0) self.assertNotEqual(pickle.load(f), id(sys.modules)) self.assertNotEqual(pickle.load(f), id(builtins)) class TestThreadState(unittest.TestCase): @support.reap_threads def test_thread_state(self): # some extra thread-state tests driven via _testcapi def target(): idents = [] def callback(): idents.append(threading.get_ident()) _testcapi._test_thread_state(callback) a = b = callback time.sleep(1) # Check our main thread is in the list exactly 3 times. self.assertEqual(idents.count(threading.get_ident()), 3, "Couldn't find main thread correctly in the list") target() t = threading.Thread(target=target) t.start() t.join() class Test_testcapi(unittest.TestCase): locals().update((name, getattr(_testcapi, name)) for name in dir(_testcapi) if name.startswith('test_') and not name.endswith('_code')) class PyMemDebugTests(unittest.TestCase): PYTHONMALLOC = 'debug' # '0x04c06e0' or '04C06E0' PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+' def check(self, code): with support.SuppressCrashReport(): out = assert_python_failure('-c', code, PYTHONMALLOC=self.PYTHONMALLOC) stderr = out.err return stderr.decode('ascii', 'replace') def test_buffer_overflow(self): out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()') regex = (r"Debug memory block at address p={ptr}: API 'm'\n" r" 16 bytes originally requested\n" r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n" r" at tail\+0: 0x78 \*\*\* OUCH\n" r" at tail\+1: 0xfd\n" r" at tail\+2: 0xfd\n" r" .*\n" r" The block was made by call #[0-9]+ to debug malloc/realloc.\n" r" Data at p: cd cd cd .*\n" r"\n" r"Enable tracemalloc to get the memory block allocation traceback\n" r"\n" r"Fatal Python error: bad trailing pad byte") regex = regex.format(ptr=self.PTR_REGEX) regex = re.compile(regex, flags=re.DOTALL) self.assertRegex(out, regex) def test_api_misuse(self): out = self.check('import _testcapi; _testcapi.pymem_api_misuse()') regex = (r"Debug memory block at address p={ptr}: API 'm'\n" r" 16 bytes originally requested\n" r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n" r" The block was made by call #[0-9]+ to debug malloc/realloc.\n" r" Data at p: cd cd cd .*\n" r"\n" r"Enable tracemalloc to get the memory block allocation traceback\n" r"\n" r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n") regex = regex.format(ptr=self.PTR_REGEX) self.assertRegex(out, regex) def check_malloc_without_gil(self, code): out = self.check(code) expected = ('Fatal Python error: Python memory allocator called ' 'without holding the GIL') self.assertIn(expected, out) def test_pymem_malloc_without_gil(self): # Debug hooks must raise an error if PyMem_Malloc() is called # without holding the GIL code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()' self.check_malloc_without_gil(code) def test_pyobject_malloc_without_gil(self): # Debug hooks must raise an error if PyObject_Malloc() is called # without holding the GIL code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()' self.check_malloc_without_gil(code) def check_pyobject_is_freed(self, func): code = textwrap.dedent(''' import gc, os, sys, _testcapi # Disable the GC to avoid crash on GC collection gc.disable() obj = _testcapi.{func}() error = (_testcapi.pyobject_is_freed(obj) == False) # Exit immediately to avoid a crash while deallocating # the invalid object os._exit(int(error)) ''') code = code.format(func=func) assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC) def test_pyobject_is_freed_uninitialized(self): self.check_pyobject_is_freed('pyobject_uninitialized') def test_pyobject_is_freed_forbidden_bytes(self): self.check_pyobject_is_freed('pyobject_forbidden_bytes') def test_pyobject_is_freed_free(self): self.check_pyobject_is_freed('pyobject_freed') class PyMemMallocDebugTests(PyMemDebugTests): PYTHONMALLOC = 'malloc_debug' @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc') class PyMemPymallocDebugTests(PyMemDebugTests): PYTHONMALLOC = 'pymalloc_debug' @unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG') class PyMemDefaultTests(PyMemDebugTests): # test default allocator of Python compiled in debug mode PYTHONMALLOC = '' 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/ssl_servers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
import os import sys import ssl import pprint import threading import urllib.parse # Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer. from http.server import (HTTPServer as _HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler) from test import support here = os.path.dirname(__file__) HOST = support.HOST CERTFILE = os.path.join(here, 'keycert.pem') # This one's based on HTTPServer, which is based on socketserver class HTTPSServer(_HTTPServer): def __init__(self, server_address, handler_class, context): _HTTPServer.__init__(self, server_address, handler_class) self.context = context def __str__(self): return ('<%s %s:%s>' % (self.__class__.__name__, self.server_name, self.server_port)) def get_request(self): # override this to wrap socket with SSL try: sock, addr = self.socket.accept() sslconn = self.context.wrap_socket(sock, server_side=True) except OSError as e: # socket errors are silenced by the caller, print them here if support.verbose: sys.stderr.write("Got an error:\n%s\n" % e) raise return sslconn, addr class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): # need to override translate_path to get a known root, # instead of using os.curdir, since the test could be # run from anywhere server_version = "TestHTTPS/1.0" root = here # Avoid hanging when a request gets interrupted by the client timeout = 5 def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = urllib.parse.urlparse(path)[2] path = os.path.normpath(urllib.parse.unquote(path)) words = path.split('/') words = filter(None, words) path = self.root for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) path = os.path.join(path, word) return path def log_message(self, format, *args): # we override this to suppress logging unless "verbose" if support.verbose: sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" % (self.server.server_address, self.server.server_port, self.request.cipher(), self.log_date_time_string(), format%args)) class StatsRequestHandler(BaseHTTPRequestHandler): """Example HTTP request handler which returns SSL statistics on GET requests. """ server_version = "StatsHTTPS/1.0" def do_GET(self, send_body=True): """Serve a GET request.""" sock = self.rfile.raw._sock context = sock.context stats = { 'session_cache': context.session_stats(), 'cipher': sock.cipher(), 'compression': sock.compression(), } body = pprint.pformat(stats) body = body.encode('utf-8') self.send_response(200) self.send_header("Content-type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() if send_body: self.wfile.write(body) def do_HEAD(self): """Serve a HEAD request.""" self.do_GET(send_body=False) def log_request(self, format, *args): if support.verbose: BaseHTTPRequestHandler.log_request(self, format, *args) class HTTPSServerThread(threading.Thread): def __init__(self, context, host=HOST, handler_class=None): self.flag = None self.server = HTTPSServer((host, 0), handler_class or RootedHTTPRequestHandler, context) self.port = self.server.server_port threading.Thread.__init__(self) self.daemon = True def __str__(self): return "<%s %s>" % (self.__class__.__name__, self.server) def start(self, flag=None): self.flag = flag threading.Thread.start(self) def run(self): if self.flag: self.flag.set() try: self.server.serve_forever(0.05) finally: self.server.server_close() def stop(self): self.server.shutdown() def make_https_server(case, *, context=None, certfile=CERTFILE, host=HOST, handler_class=None): if context is None: context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) # We assume the certfile contains both private key and certificate context.load_cert_chain(certfile) server = HTTPSServerThread(context, host, handler_class) flag = threading.Event() server.start(flag) flag.wait() def cleanup(): if support.verbose: sys.stdout.write('stopping HTTPS server\n') server.stop() if support.verbose: sys.stdout.write('joining HTTPS thread\n') server.join() case.addCleanup(cleanup) return server if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description='Run a test HTTPS server. ' 'By default, the current directory is served.') parser.add_argument('-p', '--port', type=int, default=4433, help='port to listen on (default: %(default)s)') parser.add_argument('-q', '--quiet', dest='verbose', default=True, action='store_false', help='be less verbose') parser.add_argument('-s', '--stats', dest='use_stats_handler', default=False, action='store_true', help='always return stats page') parser.add_argument('--curve-name', dest='curve_name', type=str, action='store', help='curve name for EC-based Diffie-Hellman') parser.add_argument('--ciphers', dest='ciphers', type=str, help='allowed cipher list') parser.add_argument('--dh', dest='dh_file', type=str, action='store', help='PEM file containing DH parameters') args = parser.parse_args() support.verbose = args.verbose if args.use_stats_handler: handler_class = StatsRequestHandler else: handler_class = RootedHTTPRequestHandler handler_class.root = os.getcwd() context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain(CERTFILE) if args.curve_name: context.set_ecdh_curve(args.curve_name) if args.dh_file: context.load_dh_params(args.dh_file) if args.ciphers: context.set_ciphers(args.ciphers) server = HTTPSServer(("", args.port), handler_class, context) if args.verbose: print("Listening on https://localhost:{0.port}".format(args)) server.serve_forever(0.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/time_hashlib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/time_hashlib.py
# It's intended that this script be run by hand. It runs speed tests on # hashlib functions; it does not test for correctness. import sys import time import hashlib def creatorFunc(): raise RuntimeError("eek, creatorFunc not overridden") def test_scaled_msg(scale, name): iterations = 106201//scale * 20 longStr = b'Z'*scale localCF = creatorFunc start = time.perf_counter() for f in range(iterations): x = localCF(longStr).digest() end = time.perf_counter() print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name) def test_create(): start = time.perf_counter() for f in range(20000): d = creatorFunc() end = time.perf_counter() print(('%2.2f' % (end-start)), "seconds", '[20000 creations]') def test_zero(): start = time.perf_counter() for f in range(20000): x = creatorFunc().digest() end = time.perf_counter() print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]') hName = sys.argv[1] # # setup our creatorFunc to test the requested hash # if hName in ('_md5', '_sha'): exec('import '+hName) exec('creatorFunc = '+hName+'.new') print("testing speed of old", hName, "legacy interface") elif hName == '_hashlib' and len(sys.argv) > 3: import _hashlib exec('creatorFunc = _hashlib.%s' % sys.argv[2]) print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])) elif hName == '_hashlib' and len(sys.argv) == 3: import _hashlib exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]) print("testing speed of _hashlib.new(%r)" % sys.argv[2]) elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'): creatorFunc = getattr(hashlib, hName) print("testing speed of hashlib."+hName, getattr(hashlib, hName)) else: exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName) print("testing speed of hashlib.new(%r)" % hName) try: test_create() except ValueError: print() print("pass argument(s) naming the hash to run a speed test on:") print(" '_md5' and '_sha' test the legacy builtin md5 and sha") print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib") print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)") print(" 'hName' tests the hashlib.hName() implementation if it exists") print(" otherwise it uses hashlib.new(hName).") print() raise test_zero() test_scaled_msg(scale=106201, name='[huge data]') test_scaled_msg(scale=10620, name='[large data]') test_scaled_msg(scale=1062, name='[medium data]') test_scaled_msg(scale=424, name='[4*small data]') test_scaled_msg(scale=336, name='[3*small data]') test_scaled_msg(scale=212, name='[2*small data]') test_scaled_msg(scale=106, name='[small data]') test_scaled_msg(scale=creatorFunc().digest_size, name='[digest_size data]') test_scaled_msg(scale=10, name='[tiny data]')
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_structmembers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_structmembers.py
import unittest from test import support # Skip this test if the _testcapi module isn't available. support.import_module('_testcapi') from _testcapi import _test_structmembersType, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \ INT_MAX, INT_MIN, UINT_MAX, \ LONG_MAX, LONG_MIN, ULONG_MAX, \ LLONG_MAX, LLONG_MIN, ULLONG_MAX, \ PY_SSIZE_T_MAX, PY_SSIZE_T_MIN ts=_test_structmembersType(False, # T_BOOL 1, # T_BYTE 2, # T_UBYTE 3, # T_SHORT 4, # T_USHORT 5, # T_INT 6, # T_UINT 7, # T_LONG 8, # T_ULONG 23, # T_PYSSIZET 9.99999,# T_FLOAT 10.1010101010, # T_DOUBLE "hi" # T_STRING_INPLACE ) class ReadWriteTests(unittest.TestCase): def test_bool(self): ts.T_BOOL = True self.assertEqual(ts.T_BOOL, True) ts.T_BOOL = False self.assertEqual(ts.T_BOOL, False) self.assertRaises(TypeError, setattr, ts, 'T_BOOL', 1) def test_byte(self): ts.T_BYTE = CHAR_MAX self.assertEqual(ts.T_BYTE, CHAR_MAX) ts.T_BYTE = CHAR_MIN self.assertEqual(ts.T_BYTE, CHAR_MIN) ts.T_UBYTE = UCHAR_MAX self.assertEqual(ts.T_UBYTE, UCHAR_MAX) def test_short(self): ts.T_SHORT = SHRT_MAX self.assertEqual(ts.T_SHORT, SHRT_MAX) ts.T_SHORT = SHRT_MIN self.assertEqual(ts.T_SHORT, SHRT_MIN) ts.T_USHORT = USHRT_MAX self.assertEqual(ts.T_USHORT, USHRT_MAX) def test_int(self): ts.T_INT = INT_MAX self.assertEqual(ts.T_INT, INT_MAX) ts.T_INT = INT_MIN self.assertEqual(ts.T_INT, INT_MIN) ts.T_UINT = UINT_MAX self.assertEqual(ts.T_UINT, UINT_MAX) def test_long(self): ts.T_LONG = LONG_MAX self.assertEqual(ts.T_LONG, LONG_MAX) ts.T_LONG = LONG_MIN self.assertEqual(ts.T_LONG, LONG_MIN) ts.T_ULONG = ULONG_MAX self.assertEqual(ts.T_ULONG, ULONG_MAX) def test_py_ssize_t(self): ts.T_PYSSIZET = PY_SSIZE_T_MAX self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MAX) ts.T_PYSSIZET = PY_SSIZE_T_MIN self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MIN) @unittest.skipUnless(hasattr(ts, "T_LONGLONG"), "long long not present") def test_longlong(self): ts.T_LONGLONG = LLONG_MAX self.assertEqual(ts.T_LONGLONG, LLONG_MAX) ts.T_LONGLONG = LLONG_MIN self.assertEqual(ts.T_LONGLONG, LLONG_MIN) ts.T_ULONGLONG = ULLONG_MAX self.assertEqual(ts.T_ULONGLONG, ULLONG_MAX) ## make sure these will accept a plain int as well as a long ts.T_LONGLONG = 3 self.assertEqual(ts.T_LONGLONG, 3) ts.T_ULONGLONG = 4 self.assertEqual(ts.T_ULONGLONG, 4) def test_bad_assignments(self): integer_attributes = [ 'T_BOOL', 'T_BYTE', 'T_UBYTE', 'T_SHORT', 'T_USHORT', 'T_INT', 'T_UINT', 'T_LONG', 'T_ULONG', 'T_PYSSIZET' ] if hasattr(ts, 'T_LONGLONG'): integer_attributes.extend(['T_LONGLONG', 'T_ULONGLONG']) # issue8014: this produced 'bad argument to internal function' # internal error for nonint in None, 3.2j, "full of eels", {}, []: for attr in integer_attributes: self.assertRaises(TypeError, setattr, ts, attr, nonint) def test_inplace_string(self): self.assertEqual(ts.T_STRING_INPLACE, "hi") self.assertRaises(TypeError, setattr, ts, "T_STRING_INPLACE", "s") self.assertRaises(TypeError, delattr, ts, "T_STRING_INPLACE") class TestWarnings(unittest.TestCase): def test_byte_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MAX+1 def test_byte_min(self): with support.check_warnings(('', RuntimeWarning)): ts.T_BYTE = CHAR_MIN-1 def test_ubyte_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_UBYTE = UCHAR_MAX+1 def test_short_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MAX+1 def test_short_min(self): with support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MIN-1 def test_ushort_max(self): with support.check_warnings(('', RuntimeWarning)): ts.T_USHORT = USHRT_MAX+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_httplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
import errno from http import client import io import itertools import os import array import re import socket import threading import unittest TestCase = unittest.TestCase from test import support 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') # Self-signed cert file for self-signed.pythontest.net CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem') # constants for testing chunked encoding chunked_start = ( 'HTTP/1.1 200 OK\r\n' 'Transfer-Encoding: chunked\r\n\r\n' 'a\r\n' 'hello worl\r\n' '3\r\n' 'd! \r\n' '8\r\n' 'and now \r\n' '22\r\n' 'for something completely different\r\n' ) chunked_expected = b'hello world! and now for something completely different' chunk_extension = ";foo=bar" last_chunk = "0\r\n" last_chunk_extended = "0" + chunk_extension + "\r\n" trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n" chunked_end = "\r\n" HOST = support.HOST class FakeSocket: def __init__(self, text, fileclass=io.BytesIO, host=None, port=None): if isinstance(text, str): text = text.encode("ascii") self.text = text self.fileclass = fileclass self.data = b'' self.sendall_calls = 0 self.file_closed = False self.host = host self.port = port def sendall(self, data): self.sendall_calls += 1 self.data += data def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise client.UnimplementedFileMode() # keep the file around so we can check how much was read from it self.file = self.fileclass(self.text) self.file.close = self.file_close #nerf close () return self.file def file_close(self): self.file_closed = True def close(self): pass def setsockopt(self, level, optname, value): pass class EPipeSocket(FakeSocket): def __init__(self, text, pipe_trigger): # When sendall() is called with pipe_trigger, raise EPIPE. FakeSocket.__init__(self, text) self.pipe_trigger = pipe_trigger def sendall(self, data): if self.pipe_trigger in data: raise OSError(errno.EPIPE, "gotcha") self.data += data def close(self): pass class NoEOFBytesIO(io.BytesIO): """Like BytesIO, but raises AssertionError on EOF. This is used below to test that http.client doesn't try to read more from the underlying file than it should. """ def read(self, n=-1): data = io.BytesIO.read(self, n) if data == b'': raise AssertionError('caller tried to read past EOF') return data def readline(self, length=None): data = io.BytesIO.readline(self, length) if data == b'': raise AssertionError('caller tried to read past EOF') return data class FakeSocketHTTPConnection(client.HTTPConnection): """HTTPConnection subclass using FakeSocket; counts connect() calls""" def __init__(self, *args): self.connections = 0 super().__init__('example.com') self.fake_socket_args = args self._create_connection = self.create_connection def connect(self): """Count the number of times connect() is invoked""" self.connections += 1 return super().connect() def create_connection(self, *pos, **kw): return FakeSocket(*self.fake_socket_args) class HeaderTests(TestCase): def test_auto_headers(self): # Some headers are added automatically, but should not be added by # .request() if they are explicitly set. class HeaderCountingBuffer(list): def __init__(self): self.count = {} def append(self, item): kv = item.split(b':') if len(kv) > 1: # item is a 'Key: Value' header string lcKey = kv[0].decode('ascii').lower() self.count.setdefault(lcKey, 0) self.count[lcKey] += 1 list.append(self, item) for explicit_header in True, False: for header in 'Content-length', 'Host', 'Accept-encoding': conn = client.HTTPConnection('example.com') conn.sock = FakeSocket('blahblahblah') conn._buffer = HeaderCountingBuffer() body = 'spamspamspam' headers = {} if explicit_header: headers[header] = str(len(body)) conn.request('POST', '/', body, headers) self.assertEqual(conn._buffer.count[header.lower()], 1) def test_content_length_0(self): class ContentLengthChecker(list): def __init__(self): list.__init__(self) self.content_length = None def append(self, item): kv = item.split(b':', 1) if len(kv) > 1 and kv[0].lower() == b'content-length': self.content_length = kv[1].strip() list.append(self, item) # Here, we're testing that methods expecting a body get a # content-length set to zero if the body is empty (either None or '') bodies = (None, '') methods_with_body = ('PUT', 'POST', 'PATCH') for method, body in itertools.product(methods_with_body, bodies): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(None) conn._buffer = ContentLengthChecker() conn.request(method, '/', body) self.assertEqual( conn._buffer.content_length, b'0', 'Header Content-Length incorrect on {}'.format(method) ) # For these methods, we make sure that content-length is not set when # the body is None because it might cause unexpected behaviour on the # server. methods_without_body = ( 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE', ) for method in methods_without_body: conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(None) conn._buffer = ContentLengthChecker() conn.request(method, '/', None) self.assertEqual( conn._buffer.content_length, None, 'Header Content-Length set for empty body on {}'.format(method) ) # If the body is set to '', that's considered to be "present but # empty" rather than "missing", so content length would be set, even # for methods that don't expect a body. for method in methods_without_body: conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(None) conn._buffer = ContentLengthChecker() conn.request(method, '/', '') self.assertEqual( conn._buffer.content_length, b'0', 'Header Content-Length incorrect on {}'.format(method) ) # If the body is set, make sure Content-Length is set. for method in itertools.chain(methods_without_body, methods_with_body): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(None) conn._buffer = ContentLengthChecker() conn.request(method, '/', ' ') self.assertEqual( conn._buffer.content_length, b'1', 'Header Content-Length incorrect on {}'.format(method) ) def test_putheader(self): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(None) conn.putrequest('GET','/') conn.putheader('Content-length', 42) self.assertIn(b'Content-length: 42', conn._buffer) conn.putheader('Foo', ' bar ') self.assertIn(b'Foo: bar ', conn._buffer) conn.putheader('Bar', '\tbaz\t') self.assertIn(b'Bar: \tbaz\t', conn._buffer) conn.putheader('Authorization', 'Bearer mytoken') self.assertIn(b'Authorization: Bearer mytoken', conn._buffer) conn.putheader('IterHeader', 'IterA', 'IterB') self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer) conn.putheader('LatinHeader', b'\xFF') self.assertIn(b'LatinHeader: \xFF', conn._buffer) conn.putheader('Utf8Header', b'\xc3\x80') self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer) conn.putheader('C1-Control', b'next\x85line') self.assertIn(b'C1-Control: next\x85line', conn._buffer) conn.putheader('Embedded-Fold-Space', 'is\r\n allowed') self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer) conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed') self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer) conn.putheader('Key Space', 'value') self.assertIn(b'Key Space: value', conn._buffer) conn.putheader('KeySpace ', 'value') self.assertIn(b'KeySpace : value', conn._buffer) conn.putheader(b'Nonbreak\xa0Space', 'value') self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer) conn.putheader(b'\xa0NonbreakSpace', 'value') self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer) def test_ipv6host_header(self): # Default host header on IPv6 transaction should be wrapped by [] if # it is an IPv6 address expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \ b'Accept-Encoding: identity\r\n\r\n' conn = client.HTTPConnection('[2001::]:81') sock = FakeSocket('') conn.sock = sock conn.request('GET', '/foo') self.assertTrue(sock.data.startswith(expected)) expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \ b'Accept-Encoding: identity\r\n\r\n' conn = client.HTTPConnection('[2001:102A::]') sock = FakeSocket('') conn.sock = sock conn.request('GET', '/foo') self.assertTrue(sock.data.startswith(expected)) def test_malformed_headers_coped_with(self): # Issue 19996 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.getheader('First'), 'val') self.assertEqual(resp.getheader('Second'), 'val') def test_parse_all_octets(self): # Ensure no valid header field octet breaks the parser body = ( b'HTTP/1.1 200 OK\r\n' b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n' b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n' b'obs-fold: text\r\n' b' folded with space\r\n' b'\tfolded with tab\r\n' b'Content-Length: 0\r\n' b'\r\n' ) sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.getheader('Content-Length'), '0') self.assertEqual(resp.msg['Content-Length'], '0') self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value') self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value') vchar = ''.join(map(chr, range(0x21, 0x7E + 1))) self.assertEqual(resp.getheader('VCHAR'), vchar) self.assertEqual(resp.msg['VCHAR'], vchar) self.assertIsNotNone(resp.getheader('obs-text')) self.assertIn('obs-text', resp.msg) for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']): self.assertTrue(folded.startswith('text')) self.assertIn(' folded with space', folded) self.assertTrue(folded.endswith('folded with tab')) def test_invalid_headers(self): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket('') conn.putrequest('GET', '/') # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no # longer allowed in header names cases = ( (b'Invalid\r\nName', b'ValidValue'), (b'Invalid\rName', b'ValidValue'), (b'Invalid\nName', b'ValidValue'), (b'\r\nInvalidName', b'ValidValue'), (b'\rInvalidName', b'ValidValue'), (b'\nInvalidName', b'ValidValue'), (b' InvalidName', b'ValidValue'), (b'\tInvalidName', b'ValidValue'), (b'Invalid:Name', b'ValidValue'), (b':InvalidName', b'ValidValue'), (b'ValidName', b'Invalid\r\nValue'), (b'ValidName', b'Invalid\rValue'), (b'ValidName', b'Invalid\nValue'), (b'ValidName', b'InvalidValue\r\n'), (b'ValidName', b'InvalidValue\r'), (b'ValidName', b'InvalidValue\n'), ) for name, value in cases: with self.subTest((name, value)): with self.assertRaisesRegex(ValueError, 'Invalid header'): conn.putheader(name, value) def test_headers_debuglevel(self): body = ( b'HTTP/1.1 200 OK\r\n' b'First: val\r\n' b'Second: val1\r\n' b'Second: val2\r\n' ) sock = FakeSocket(body) resp = client.HTTPResponse(sock, debuglevel=1) with support.captured_stdout() as output: resp.begin() lines = output.getvalue().splitlines() self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'") self.assertEqual(lines[1], "header: First: val") self.assertEqual(lines[2], "header: Second: val1") self.assertEqual(lines[3], "header: Second: val2") class TransferEncodingTest(TestCase): expected_body = b"It's just a flesh wound" def test_endheaders_chunked(self): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') conn.putrequest('POST', '/') conn.endheaders(self._make_body(), encode_chunked=True) _, _, body = self._parse_request(conn.sock.data) body = self._parse_chunked(body) self.assertEqual(body, self.expected_body) def test_explicit_headers(self): # explicit chunked conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') # this shouldn't actually be automatically chunk-encoded because the # calling code has explicitly stated that it's taking care of it conn.request( 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'}) _, headers, body = self._parse_request(conn.sock.data) self.assertNotIn('content-length', [k.lower() for k in headers.keys()]) self.assertEqual(headers['Transfer-Encoding'], 'chunked') self.assertEqual(body, self.expected_body) # explicit chunked, string body conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') conn.request( 'POST', '/', self.expected_body.decode('latin-1'), {'Transfer-Encoding': 'chunked'}) _, headers, body = self._parse_request(conn.sock.data) self.assertNotIn('content-length', [k.lower() for k in headers.keys()]) self.assertEqual(headers['Transfer-Encoding'], 'chunked') self.assertEqual(body, self.expected_body) # User-specified TE, but request() does the chunk encoding conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') conn.request('POST', '/', headers={'Transfer-Encoding': 'gzip, chunked'}, encode_chunked=True, body=self._make_body()) _, headers, body = self._parse_request(conn.sock.data) self.assertNotIn('content-length', [k.lower() for k in headers]) self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked') self.assertEqual(self._parse_chunked(body), self.expected_body) def test_request(self): for empty_lines in (False, True,): conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') conn.request( 'POST', '/', self._make_body(empty_lines=empty_lines)) _, headers, body = self._parse_request(conn.sock.data) body = self._parse_chunked(body) self.assertEqual(body, self.expected_body) self.assertEqual(headers['Transfer-Encoding'], 'chunked') # Content-Length and Transfer-Encoding SHOULD not be sent in the # same request self.assertNotIn('content-length', [k.lower() for k in headers]) def test_empty_body(self): # Zero-length iterable should be treated like any other iterable conn = client.HTTPConnection('example.com') conn.sock = FakeSocket(b'') conn.request('POST', '/', ()) _, headers, body = self._parse_request(conn.sock.data) self.assertEqual(headers['Transfer-Encoding'], 'chunked') self.assertNotIn('content-length', [k.lower() for k in headers]) self.assertEqual(body, b"0\r\n\r\n") def _make_body(self, empty_lines=False): lines = self.expected_body.split(b' ') for idx, line in enumerate(lines): # for testing handling empty lines if empty_lines and idx % 2: yield b'' if idx < len(lines) - 1: yield line + b' ' else: yield line def _parse_request(self, data): lines = data.split(b'\r\n') request = lines[0] headers = {} n = 1 while n < len(lines) and len(lines[n]) > 0: key, val = lines[n].split(b':') key = key.decode('latin-1').strip() headers[key] = val.decode('latin-1').strip() n += 1 return request, headers, b'\r\n'.join(lines[n + 1:]) def _parse_chunked(self, data): body = [] trailers = {} n = 0 lines = data.split(b'\r\n') # parse body while True: size, chunk = lines[n:n+2] size = int(size, 16) if size == 0: n += 1 break self.assertEqual(size, len(chunk)) body.append(chunk) n += 2 # we /should/ hit the end chunk, but check against the size of # lines so we're not stuck in an infinite loop should we get # malformed data if n > len(lines): break return b''.join(body) class BasicTest(TestCase): def test_status_lines(self): # Test HTTP status lines body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(0), b'') # Issue #20007 self.assertFalse(resp.isclosed()) self.assertFalse(resp.closed) self.assertEqual(resp.read(), b"Text") self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) self.assertRaises(client.BadStatusLine, resp.begin) def test_bad_status_repr(self): exc = client.BadStatusLine('') self.assertEqual(repr(exc), '''BadStatusLine("''")''') def test_partial_reads(self): # if we have Content-Length, HTTPResponse knows when to close itself, # the same behaviour as when we read the whole thing with read() body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(2), b'Te') self.assertFalse(resp.isclosed()) self.assertEqual(resp.read(2), b'xt') self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) def test_mixed_reads(self): # readline() should update the remaining length, so that read() knows # how much data is left and does not raise IncompleteRead body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.readline(), b'Text\r\n') self.assertFalse(resp.isclosed()) self.assertEqual(resp.read(), b'Another') self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) def test_partial_readintos(self): # if we have Content-Length, HTTPResponse knows when to close itself, # the same behaviour as when we read the whole thing with read() body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() b = bytearray(2) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'Te') self.assertFalse(resp.isclosed()) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'xt') self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) def test_partial_reads_no_content_length(self): # when no length is present, the socket should be gracefully closed when # all data was read body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(2), b'Te') self.assertFalse(resp.isclosed()) self.assertEqual(resp.read(2), b'xt') self.assertEqual(resp.read(1), b'') self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) def test_partial_readintos_no_content_length(self): # when no length is present, the socket should be gracefully closed when # all data was read body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() b = bytearray(2) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'Te') self.assertFalse(resp.isclosed()) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'xt') n = resp.readinto(b) self.assertEqual(n, 0) self.assertTrue(resp.isclosed()) def test_partial_reads_incomplete_body(self): # if the server shuts down the connection before the whole # content-length is delivered, the socket is gracefully closed body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(2), b'Te') self.assertFalse(resp.isclosed()) self.assertEqual(resp.read(2), b'xt') self.assertEqual(resp.read(1), b'') self.assertTrue(resp.isclosed()) def test_partial_readintos_incomplete_body(self): # if the server shuts down the connection before the whole # content-length is delivered, the socket is gracefully closed body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() b = bytearray(2) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'Te') self.assertFalse(resp.isclosed()) n = resp.readinto(b) self.assertEqual(n, 2) self.assertEqual(bytes(b), b'xt') n = resp.readinto(b) self.assertEqual(n, 0) self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) def test_host_port(self): # Check invalid host_port for hp in ("www.python.org:abc", "user:password@www.python.org"): self.assertRaises(client.InvalidURL, client.HTTPConnection, hp) for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", 8000), ("www.python.org:80", "www.python.org", 80), ("www.python.org:", "www.python.org", 80), ("www.python.org", "www.python.org", 80), ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80), ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)): c = client.HTTPConnection(hp) self.assertEqual(h, c.host) self.assertEqual(p, c.port) def test_response_headers(self): # test response with multiple message headers with the same field name. text = ('HTTP/1.1 200 OK\r\n' 'Set-Cookie: Customer="WILE_E_COYOTE"; ' 'Version="1"; Path="/acme"\r\n' 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' ' Path="/acme"\r\n' '\r\n' 'No body\r\n') hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' ', ' 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') s = FakeSocket(text) r = client.HTTPResponse(s) r.begin() cookies = r.getheader("Set-Cookie") self.assertEqual(cookies, hdr) def test_read_head(self): # Test that the library doesn't attempt to read any data # from a HEAD request. (Tickles SF bug #622042.) sock = FakeSocket( 'HTTP/1.1 200 OK\r\n' 'Content-Length: 14432\r\n' '\r\n', NoEOFBytesIO) resp = client.HTTPResponse(sock, method="HEAD") resp.begin() if resp.read(): self.fail("Did not expect response from HEAD request") def test_readinto_head(self): # Test that the library doesn't attempt to read any data # from a HEAD request. (Tickles SF bug #622042.) sock = FakeSocket( 'HTTP/1.1 200 OK\r\n' 'Content-Length: 14432\r\n' '\r\n', NoEOFBytesIO) resp = client.HTTPResponse(sock, method="HEAD") resp.begin() b = bytearray(5) if resp.readinto(b) != 0: self.fail("Did not expect response from HEAD request") self.assertEqual(bytes(b), b'\x00'*5) def test_too_many_headers(self): headers = '\r\n'.join('Header%d: foo' % i for i in range(client._MAXHEADERS + 1)) + '\r\n' text = ('HTTP/1.1 200 OK\r\n' + headers) s = FakeSocket(text) r = client.HTTPResponse(s) self.assertRaisesRegex(client.HTTPException, r"got more than \d+ headers", r.begin) def test_send_file(self): expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' b'Accept-Encoding: identity\r\n' b'Transfer-Encoding: chunked\r\n' b'\r\n') with open(__file__, 'rb') as body: conn = client.HTTPConnection('example.com') sock = FakeSocket(body) conn.sock = sock conn.request('GET', '/foo', body) self.assertTrue(sock.data.startswith(expected), '%r != %r' % (sock.data[:len(expected)], expected)) def test_send(self): expected = b'this is a test this is only a test' conn = client.HTTPConnection('example.com') sock = FakeSocket(None) conn.sock = sock conn.send(expected) self.assertEqual(expected, sock.data) sock.data = b'' conn.send(array.array('b', expected)) self.assertEqual(expected, sock.data) sock.data = b'' conn.send(io.BytesIO(expected)) self.assertEqual(expected, sock.data) def test_send_updating_file(self): def data(): yield 'data' yield None yield 'data_two' class UpdatingFile(io.TextIOBase): mode = 'r' d = data() def read(self, blocksize=-1): return next(self.d) expected = b'data' conn = client.HTTPConnection('example.com') sock = FakeSocket("") conn.sock = sock conn.send(UpdatingFile()) self.assertEqual(sock.data, expected) def test_send_iter(self): expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \ b'\r\nonetwothree' def body(): yield b"one" yield b"two" yield b"three" conn = client.HTTPConnection('example.com') sock = FakeSocket("") conn.sock = sock conn.request('GET', '/foo', body(), {'Content-Length': '11'}) self.assertEqual(sock.data, expected) def test_blocksize_request(self): """Check that request() respects the configured block size.""" blocksize = 8 # For easy debugging. conn = client.HTTPConnection('example.com', blocksize=blocksize) sock = FakeSocket(None) conn.sock = sock expected = b"a" * blocksize + b"b" conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"}) self.assertEqual(sock.sendall_calls, 3) body = sock.data.split(b"\r\n\r\n", 1)[1] self.assertEqual(body, expected) def test_blocksize_send(self): """Check that send() respects the configured block size.""" blocksize = 8 # For easy debugging. conn = client.HTTPConnection('example.com', blocksize=blocksize) sock = FakeSocket(None) conn.sock = sock expected = b"a" * blocksize + b"b" conn.send(io.BytesIO(expected)) self.assertEqual(sock.sendall_calls, 2) self.assertEqual(sock.data, expected) def test_send_type_error(self): # See: Issue #12676 conn = client.HTTPConnection('example.com') conn.sock = FakeSocket('') with self.assertRaises(TypeError): conn.request('POST', 'test', conn) def test_chunked(self): expected = chunked_expected sock = FakeSocket(chunked_start + last_chunk + chunked_end) resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(), expected) resp.close() # Various read sizes for n in range(1, 12): sock = FakeSocket(chunked_start + last_chunk + chunked_end) resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected) resp.close() for x in ('', 'foo\r\n'): sock = FakeSocket(chunked_start + x) resp = client.HTTPResponse(sock, method="GET") resp.begin() try: resp.read() except client.IncompleteRead as i: self.assertEqual(i.partial, expected) expected_message = 'IncompleteRead(%d bytes read)' % len(expected) self.assertEqual(repr(i), expected_message) self.assertEqual(str(i), expected_message) else: self.fail('IncompleteRead expected') finally: resp.close() def test_readinto_chunked(self): expected = chunked_expected nexpected = len(expected) b = bytearray(128) sock = FakeSocket(chunked_start + last_chunk + chunked_end) resp = client.HTTPResponse(sock, method="GET") resp.begin() n = resp.readinto(b) self.assertEqual(b[:nexpected], expected) self.assertEqual(n, nexpected) resp.close() # Various read sizes for n in range(1, 12): sock = FakeSocket(chunked_start + last_chunk + chunked_end) resp = client.HTTPResponse(sock, method="GET") resp.begin() m = memoryview(b) i = resp.readinto(m[0:n]) i += resp.readinto(m[i:n + i])
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_tuple.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tuple.py
from test import support, seq_tests import unittest import gc import pickle class TupleTest(seq_tests.CommonTest): type2test = tuple def test_getitem_error(self): msg = "tuple indices must be integers or slices" with self.assertRaisesRegex(TypeError, msg): ()['a'] def test_constructors(self): super().test_constructors() # calling built-in types without argument must return empty self.assertEqual(tuple(), ()) t0_3 = (0, 1, 2, 3) t0_3_bis = tuple(t0_3) self.assertTrue(t0_3 is t0_3_bis) self.assertEqual(tuple([]), ()) self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) self.assertEqual(tuple(''), ()) self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) self.assertEqual(tuple(x for x in range(10) if x % 2), (1, 3, 5, 7, 9)) def test_keyword_args(self): with self.assertRaisesRegex(TypeError, 'keyword argument'): tuple(sequence=()) def test_truth(self): super().test_truth() self.assertTrue(not ()) self.assertTrue((42, )) 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_iadd(self): super().test_iadd() u = (0, 1) u2 = u u += (2, 3) self.assertTrue(u is not u2) def test_imul(self): super().test_imul() u = (0, 1) u2 = u u *= 3 self.assertTrue(u is not u2) def test_tupleresizebug(self): # Check that a specific bug in _PyTuple_Resize() is squashed. def f(): for i in range(1000): yield i self.assertEqual(list(tuple(f())), list(range(1000))) def test_hash(self): # See SF bug 942952: Weakness in tuple hash # The hash should: # be non-commutative # should spread-out closely spaced values # should not exhibit cancellation in tuples like (x,(x,y)) # should be distinct from element hashes: hash(x)!=hash((x,)) # This test exercises those cases. # For a pure random hash and N=50, the expected number of occupied # buckets when tossing 252,600 balls into 2**32 buckets # is 252,592.6, or about 7.4 expected collisions. The # standard deviation is 2.73. On a box with 64-bit hash # codes, no collisions are expected. Here we accept no # more than 15 collisions. Any worse and the hash function # is sorely suspect. N=50 base = list(range(N)) xp = [(i, j) for i in base for j in base] inps = base + [(i, j) for i in base for j in xp] + \ [(i, j) for i in xp for j in base] + xp + list(zip(base)) collisions = len(inps) - len(set(map(hash, inps))) self.assertTrue(collisions <= 15) def test_repr(self): l0 = tuple() l2 = (0, 1, 2) a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), repr(l0)) self.assertEqual(str(a2), repr(l2)) self.assertEqual(repr(a0), "()") self.assertEqual(repr(a2), "(0, 1, 2)") def _not_tracked(self, t): # Nested tuples can take several collections to untrack gc.collect() gc.collect() self.assertFalse(gc.is_tracked(t), t) def _tracked(self, t): self.assertTrue(gc.is_tracked(t), t) gc.collect() gc.collect() self.assertTrue(gc.is_tracked(t), t) @support.cpython_only def test_track_literals(self): # Test GC-optimization of tuple literals x, y, z = 1.5, "a", [] self._not_tracked(()) self._not_tracked((1,)) self._not_tracked((1, 2)) self._not_tracked((1, 2, "a")) self._not_tracked((1, 2, (None, True, False, ()), int)) self._not_tracked((object(),)) self._not_tracked(((1, x), y, (2, 3))) # Tuples with mutable elements are always tracked, even if those # elements are not tracked right now. self._tracked(([],)) self._tracked(([1],)) self._tracked(({},)) self._tracked((set(),)) self._tracked((x, y, z)) def check_track_dynamic(self, tp, always_track): x, y, z = 1.5, "a", [] check = self._tracked if always_track else self._not_tracked check(tp()) check(tp([])) check(tp(set())) check(tp([1, x, y])) check(tp(obj for obj in [1, x, y])) check(tp(set([1, x, y]))) check(tp(tuple([obj]) for obj in [1, x, y])) check(tuple(tp([obj]) for obj in [1, x, y])) self._tracked(tp([z])) self._tracked(tp([[x, y]])) self._tracked(tp([{x: y}])) self._tracked(tp(obj for obj in [x, y, z])) self._tracked(tp(tuple([obj]) for obj in [x, y, z])) self._tracked(tuple(tp([obj]) for obj in [x, y, z])) @support.cpython_only def test_track_dynamic(self): # Test GC-optimization of dynamically constructed tuples. self.check_track_dynamic(tuple, False) @support.cpython_only def test_track_subtypes(self): # Tuple subtypes must always be tracked class MyTuple(tuple): pass self.check_track_dynamic(MyTuple, True) @support.cpython_only def test_bug7466(self): # Trying to untrack an unfinished tuple could crash Python self._not_tracked(tuple(gc.collect() for i in range(101))) 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): # Userlist iterators don't support pickling yet since # they are based on generators. data = self.type2test([4, 5, 6, 7]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): itorg = iter(data) d = pickle.dumps(itorg, proto) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(self.type2test(it), self.type2test(data)) it = pickle.loads(d) next(it) d = pickle.dumps(it, proto) self.assertEqual(self.type2test(it), self.type2test(data)[1:]) def test_reversed_pickle(self): data = self.type2test([4, 5, 6, 7]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): itorg = reversed(data) d = pickle.dumps(itorg, proto) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(self.type2test(it), self.type2test(reversed(data))) it = pickle.loads(d) next(it) d = pickle.dumps(it, proto) self.assertEqual(self.type2test(it), self.type2test(reversed(data))[1:]) 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 T(tuple): pass with self.assertRaises(TypeError): [3,] + T((1,2)) def test_lexicographic_ordering(self): # Issue 21100 a = self.type2test([1, 2]) b = self.type2test([1, 2, 0]) c = self.type2test([1, 3]) self.assertLess(a, b) self.assertLess(b, c) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_2_str.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dataclass_module_2_str.py
from __future__ import annotations USING_STRINGS = True # dataclass_module_2.py and dataclass_module_2_str.py are identical # except only the latter uses string annotations. from dataclasses import dataclass, InitVar from typing import ClassVar T_CV2 = ClassVar[int] T_CV3 = ClassVar T_IV2 = InitVar[int] T_IV3 = InitVar @dataclass class CV: T_CV4 = ClassVar cv0: ClassVar[int] = 20 cv1: ClassVar = 30 cv2: T_CV2 cv3: T_CV3 not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. @dataclass class IV: T_IV4 = InitVar iv0: InitVar[int] iv1: InitVar iv2: T_IV2 iv3: T_IV3 not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_funcattrs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_funcattrs.py
import types import unittest def global_function(): def inner_function(): class LocalClass: pass global inner_global_function def inner_global_function(): def inner_function2(): pass return inner_function2 return LocalClass return lambda: inner_function class FuncAttrsTest(unittest.TestCase): def setUp(self): class F: def a(self): pass def b(): return 3 self.fi = F() self.F = F self.b = b def cannot_set_attr(self, obj, name, value, exceptions): try: setattr(obj, name, value) except exceptions: pass else: self.fail("shouldn't be able to set %s to %r" % (name, value)) try: delattr(obj, name) except exceptions: pass else: self.fail("shouldn't be able to del %s" % name) class FunctionPropertiesTest(FuncAttrsTest): # Include the external setUp method that is common to all tests def test_module(self): self.assertEqual(self.b.__module__, __name__) def test_dir_includes_correct_attrs(self): self.b.known_attr = 7 self.assertIn('known_attr', dir(self.b), "set attributes not in dir listing of method") # Test on underlying function object of method self.F.a.known_attr = 7 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function " "implementations, should show up in next dir") def test_duplicate_function_equality(self): # Body of `duplicate' is the exact same as self.b def duplicate(): 'my docstring' return 3 self.assertNotEqual(self.b, duplicate) def test_copying___code__(self): def test(): pass self.assertEqual(test(), None) test.__code__ = self.b.__code__ self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily def test___globals__(self): self.assertIs(self.b.__globals__, globals()) self.cannot_set_attr(self.b, '__globals__', 2, (AttributeError, TypeError)) def test___closure__(self): a = 12 def f(): print(a) c = f.__closure__ self.assertIsInstance(c, tuple) self.assertEqual(len(c), 1) # don't have a type object handy self.assertEqual(c[0].__class__.__name__, "cell") self.cannot_set_attr(f, "__closure__", c, AttributeError) def test_empty_cell(self): def f(): print(a) try: f.__closure__[0].cell_contents except ValueError: pass else: self.fail("shouldn't be able to read an empty cell") a = 12 def test_set_cell(self): a = 12 def f(): return a c = f.__closure__ c[0].cell_contents = 9 self.assertEqual(c[0].cell_contents, 9) self.assertEqual(f(), 9) self.assertEqual(a, 9) del c[0].cell_contents try: c[0].cell_contents except ValueError: pass else: self.fail("shouldn't be able to read an empty cell") with self.assertRaises(NameError): f() with self.assertRaises(UnboundLocalError): print(a) def test___name__(self): self.assertEqual(self.b.__name__, 'b') self.b.__name__ = 'c' self.assertEqual(self.b.__name__, 'c') self.b.__name__ = 'd' self.assertEqual(self.b.__name__, 'd') # __name__ and __name__ must be a string self.cannot_set_attr(self.b, '__name__', 7, TypeError) # __name__ must be available when in restricted mode. Exec will raise # AttributeError if __name__ is not available on f. s = """def f(): pass\nf.__name__""" exec(s, {'__builtins__': {}}) # Test on methods, too self.assertEqual(self.fi.a.__name__, 'a') self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError) def test___qualname__(self): # PEP 3155 self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b') self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp') self.assertEqual(global_function.__qualname__, 'global_function') self.assertEqual(global_function().__qualname__, 'global_function.<locals>.<lambda>') self.assertEqual(global_function()().__qualname__, 'global_function.<locals>.inner_function') self.assertEqual(global_function()()().__qualname__, 'global_function.<locals>.inner_function.<locals>.LocalClass') self.assertEqual(inner_global_function.__qualname__, 'inner_global_function') self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2') self.b.__qualname__ = 'c' self.assertEqual(self.b.__qualname__, 'c') self.b.__qualname__ = 'd' self.assertEqual(self.b.__qualname__, 'd') # __qualname__ must be a string self.cannot_set_attr(self.b, '__qualname__', 7, TypeError) def test___code__(self): num_one, num_two = 7, 8 def a(): pass def b(): return 12 def c(): return num_one def d(): return num_two def e(): return num_one, num_two for func in [a, b, c, d, e]: self.assertEqual(type(func.__code__), types.CodeType) self.assertEqual(c(), 7) self.assertEqual(d(), 8) d.__code__ = c.__code__ self.assertEqual(c.__code__, d.__code__) self.assertEqual(c(), 7) # self.assertEqual(d(), 7) try: b.__code__ = c.__code__ except ValueError: pass else: self.fail("__code__ with different numbers of free vars should " "not be possible") try: e.__code__ = d.__code__ except ValueError: pass else: self.fail("__code__ with different numbers of free vars should " "not be possible") def test_blank_func_defaults(self): self.assertEqual(self.b.__defaults__, None) del self.b.__defaults__ self.assertEqual(self.b.__defaults__, None) def test_func_default_args(self): def first_func(a, b): return a+b def second_func(a=1, b=2): return a+b self.assertEqual(first_func.__defaults__, None) self.assertEqual(second_func.__defaults__, (1, 2)) first_func.__defaults__ = (1, 2) self.assertEqual(first_func.__defaults__, (1, 2)) self.assertEqual(first_func(), 3) self.assertEqual(first_func(3), 5) self.assertEqual(first_func(3, 5), 8) del second_func.__defaults__ self.assertEqual(second_func.__defaults__, None) try: second_func() except TypeError: pass else: self.fail("__defaults__ does not update; deleting it does not " "remove requirement") class InstancemethodAttrTest(FuncAttrsTest): def test___class__(self): self.assertEqual(self.fi.a.__self__.__class__, self.F) self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError) def test___func__(self): self.assertEqual(self.fi.a.__func__, self.F.a) self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError) def test___self__(self): self.assertEqual(self.fi.a.__self__, self.fi) self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError) def test___func___non_method(self): # Behavior should be the same when a method is added via an attr # assignment self.fi.id = types.MethodType(id, self.fi) self.assertEqual(self.fi.id(), id(self.fi)) # Test usage try: self.fi.id.unknown_attr except AttributeError: pass else: self.fail("using unknown attributes should raise AttributeError") # Test assignment and deletion self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) class ArbitraryFunctionAttrTest(FuncAttrsTest): def test_set_attr(self): self.b.known_attr = 7 self.assertEqual(self.b.known_attr, 7) try: self.fi.a.known_attr = 7 except AttributeError: pass else: self.fail("setting attributes on methods should raise error") def test_delete_unknown_attr(self): try: del self.b.unknown_attr except AttributeError: pass else: self.fail("deleting unknown attribute should raise TypeError") def test_unset_attr(self): for func in [self.b, self.fi.a]: try: func.non_existent_attr except AttributeError: pass else: self.fail("using unknown attributes should raise " "AttributeError") class FunctionDictsTest(FuncAttrsTest): def test_setting_dict_to_invalid(self): self.cannot_set_attr(self.b, '__dict__', None, TypeError) from collections import UserDict d = UserDict({'known_attr': 7}) self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError) def test_setting_dict_to_valid(self): d = {'known_attr': 7} self.b.__dict__ = d # Test assignment self.assertIs(d, self.b.__dict__) # ... and on all the different ways of referencing the method's func self.F.a.__dict__ = d self.assertIs(d, self.fi.a.__func__.__dict__) self.assertIs(d, self.fi.a.__dict__) # Test value self.assertEqual(self.b.known_attr, 7) self.assertEqual(self.b.__dict__['known_attr'], 7) # ... and again, on all the different method's names self.assertEqual(self.fi.a.__func__.known_attr, 7) self.assertEqual(self.fi.a.known_attr, 7) def test_delete___dict__(self): try: del self.b.__dict__ except TypeError: pass else: self.fail("deleting function dictionary should raise TypeError") def test_unassigned_dict(self): self.assertEqual(self.b.__dict__, {}) def test_func_as_dict_key(self): value = "Some string" d = {} d[self.b] = value self.assertEqual(d[self.b], value) class FunctionDocstringTest(FuncAttrsTest): def test_set_docstring_attr(self): self.assertEqual(self.b.__doc__, None) docstr = "A test method that does nothing" self.b.__doc__ = docstr self.F.a.__doc__ = docstr self.assertEqual(self.b.__doc__, docstr) self.assertEqual(self.fi.a.__doc__, docstr) self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError) def test_delete_docstring(self): self.b.__doc__ = "The docstring" del self.b.__doc__ self.assertEqual(self.b.__doc__, None) def cell(value): """Create a cell containing the given value.""" def f(): print(a) a = value return f.__closure__[0] def empty_cell(empty=True): """Create an empty cell.""" def f(): print(a) # the intent of the following line is simply "if False:"; it's # spelt this way to avoid the danger that a future optimization # might simply remove an "if False:" code block. if not empty: a = 1729 return f.__closure__[0] class CellTest(unittest.TestCase): def test_comparison(self): # These tests are here simply to exercise the comparison code; # their presence should not be interpreted as providing any # guarantees about the semantics (or even existence) of cell # comparisons in future versions of CPython. self.assertTrue(cell(2) < cell(3)) self.assertTrue(empty_cell() < cell('saturday')) self.assertTrue(empty_cell() == empty_cell()) self.assertTrue(cell(-36) == cell(-36.0)) self.assertTrue(cell(True) > empty_cell()) class StaticMethodAttrsTest(unittest.TestCase): def test_func_attribute(self): def f(): pass c = classmethod(f) self.assertTrue(c.__func__ is f) s = staticmethod(f) self.assertTrue(s.__func__ is f) class BuiltinFunctionPropertiesTest(unittest.TestCase): # XXX Not sure where this should really go since I can't find a # test module specifically for builtin_function_or_method. def test_builtin__qualname__(self): import time # builtin function: self.assertEqual(len.__qualname__, 'len') self.assertEqual(time.time.__qualname__, 'time') # builtin classmethod: self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys') self.assertEqual(float.__getformat__.__qualname__, 'float.__getformat__') # builtin staticmethod: self.assertEqual(str.maketrans.__qualname__, 'str.maketrans') self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans') # builtin bound instance method: self.assertEqual([1, 2, 3].append.__qualname__, 'list.append') self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop') 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_structseq.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_structseq.py
import os import time import unittest class StructSeqTest(unittest.TestCase): def test_tuple(self): t = time.gmtime() self.assertIsInstance(t, tuple) astuple = tuple(t) self.assertEqual(len(t), len(astuple)) self.assertEqual(t, astuple) # Check that slicing works the same way; at one point, slicing t[i:j] with # 0 < i < j could produce NULLs in the result. for i in range(-len(t), len(t)): self.assertEqual(t[i:], astuple[i:]) for j in range(-len(t), len(t)): self.assertEqual(t[i:j], astuple[i:j]) for j in range(-len(t), len(t)): self.assertEqual(t[:j], astuple[:j]) self.assertRaises(IndexError, t.__getitem__, -len(t)-1) self.assertRaises(IndexError, t.__getitem__, len(t)) for i in range(-len(t), len(t)-1): self.assertEqual(t[i], astuple[i]) def test_repr(self): t = time.gmtime() self.assertTrue(repr(t)) t = time.gmtime(0) self.assertEqual(repr(t), "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, " "tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)") # os.stat() gives a complicated struct sequence. st = os.stat(__file__) rep = repr(st) self.assertTrue(rep.startswith("os.stat_result")) self.assertIn("st_mode=", rep) self.assertIn("st_ino=", rep) self.assertIn("st_dev=", rep) def test_concat(self): t1 = time.gmtime() t2 = t1 + tuple(t1) for i in range(len(t1)): self.assertEqual(t2[i], t2[i+len(t1)]) def test_repeat(self): t1 = time.gmtime() t2 = 3 * t1 for i in range(len(t1)): self.assertEqual(t2[i], t2[i+len(t1)]) self.assertEqual(t2[i], t2[i+2*len(t1)]) def test_contains(self): t1 = time.gmtime() for item in t1: self.assertIn(item, t1) self.assertNotIn(-42, t1) def test_hash(self): t1 = time.gmtime() self.assertEqual(hash(t1), hash(tuple(t1))) def test_cmp(self): t1 = time.gmtime() t2 = type(t1)(t1) self.assertEqual(t1, t2) self.assertTrue(not (t1 < t2)) self.assertTrue(t1 <= t2) self.assertTrue(not (t1 > t2)) self.assertTrue(t1 >= t2) self.assertTrue(not (t1 != t2)) def test_fields(self): t = time.gmtime() self.assertEqual(len(t), t.n_sequence_fields) self.assertEqual(t.n_unnamed_fields, 0) self.assertEqual(t.n_fields, time._STRUCT_TM_ITEMS) def test_constructor(self): t = time.struct_time self.assertRaises(TypeError, t) self.assertRaises(TypeError, t, None) self.assertRaises(TypeError, t, "123") self.assertRaises(TypeError, t, "123", dict={}) self.assertRaises(TypeError, t, "123456789", dict=None) s = "123456789" self.assertEqual("".join(t(s)), s) def test_eviltuple(self): class Exc(Exception): pass # Devious code could crash structseqs' constructors class C: def __getitem__(self, i): raise Exc def __len__(self): return 9 self.assertRaises(Exc, time.struct_time, C()) def test_reduce(self): t = time.gmtime() x = t.__reduce__() def test_extended_getslice(self): # Test extended slicing by comparing with list slicing. t = time.gmtime() L = list(t) indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300) for start in indices: for stop in indices: # Skip step 0 (invalid) for step in indices[1:]: self.assertEqual(list(t[start:stop:step]), L[start:stop:step]) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/_test_multiprocessing.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/_test_multiprocessing.py
# # Unit tests for the multiprocessing package # import unittest import queue as pyqueue import contextlib import time import io import itertools import sys import os import gc import errno import signal import array import socket import random import logging import struct import operator import weakref import test.support import test.support.script_helper from test import support # Skip tests if _multiprocessing wasn't built. _multiprocessing = test.support.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. test.support.import_module('multiprocessing.synchronize') # import threading after _multiprocessing to raise a more relevant error # message: "No module named _multiprocessing". _multiprocessing is not compiled # without thread support. import threading import multiprocessing.connection import multiprocessing.dummy import multiprocessing.heap import multiprocessing.managers import multiprocessing.pool import multiprocessing.queues from multiprocessing import util try: from multiprocessing import reduction HAS_REDUCTION = reduction.HAVE_SEND_HANDLE except ImportError: HAS_REDUCTION = False try: from multiprocessing.sharedctypes import Value, copy HAS_SHAREDCTYPES = True except ImportError: HAS_SHAREDCTYPES = False try: import msvcrt except ImportError: msvcrt = None # # # # Timeout to wait until a process completes TIMEOUT = 60.0 # seconds def latin(s): return s.encode('latin') def close_queue(queue): if isinstance(queue, multiprocessing.queues.Queue): queue.close() queue.join_thread() def join_process(process): # Since multiprocessing.Process has the same API than threading.Thread # (join() and is_alive(), the support function can be reused support.join_thread(process, timeout=TIMEOUT) # # Constants # LOG_LEVEL = util.SUBWARNING #LOG_LEVEL = logging.DEBUG DELTA = 0.1 CHECK_TIMINGS = False # making true makes tests take a lot longer # and can sometimes cause some non-serious # failures because some calls block a bit # longer than expected if CHECK_TIMINGS: TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4 else: TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1 HAVE_GETVALUE = not getattr(_multiprocessing, 'HAVE_BROKEN_SEM_GETVALUE', False) WIN32 = (sys.platform == "win32") from multiprocessing.connection import wait def wait_for_handle(handle, timeout): if timeout is not None and timeout < 0.0: timeout = None return wait([handle], timeout) try: MAXFD = os.sysconf("SC_OPEN_MAX") except: MAXFD = 256 # To speed up tests when using the forkserver, we can preload these: PRELOAD = ['__main__', 'test.test_multiprocessing_forkserver'] # # Some tests require ctypes # try: from ctypes import Structure, c_int, c_double, c_longlong except ImportError: Structure = object c_int = c_double = c_longlong = None def check_enough_semaphores(): """Check that the system supports enough semaphores to run the test.""" # minimum number of semaphores available according to POSIX nsems_min = 256 try: nsems = os.sysconf("SC_SEM_NSEMS_MAX") except (AttributeError, ValueError): # sysconf not available or setting not available return if nsems == -1 or nsems >= nsems_min: return raise unittest.SkipTest("The OS doesn't support enough semaphores " "to run the test (required: %d)." % nsems_min) # # Creates a wrapper for a function which records the time it takes to finish # class TimingWrapper(object): def __init__(self, func): self.func = func self.elapsed = None def __call__(self, *args, **kwds): t = time.monotonic() try: return self.func(*args, **kwds) finally: self.elapsed = time.monotonic() - t # # Base class for test cases # class BaseTestCase(object): ALLOWED_TYPES = ('processes', 'manager', 'threads') def assertTimingAlmostEqual(self, a, b): if CHECK_TIMINGS: self.assertAlmostEqual(a, b, 1) def assertReturnsIfImplemented(self, value, func, *args): try: res = func(*args) except NotImplementedError: pass else: return self.assertEqual(value, res) # For the sanity of Windows users, rather than crashing or freezing in # multiple ways. def __reduce__(self, *args): raise NotImplementedError("shouldn't try to pickle a test case") __reduce_ex__ = __reduce__ # # Return the value of a semaphore # def get_value(self): try: return self.get_value() except AttributeError: try: return self._Semaphore__value except AttributeError: try: return self._value except AttributeError: raise NotImplementedError # # Testcases # class DummyCallable: def __call__(self, q, c): assert isinstance(c, DummyCallable) q.put(5) class _TestProcess(BaseTestCase): ALLOWED_TYPES = ('processes', 'threads') def test_current(self): if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) current = self.current_process() authkey = current.authkey self.assertTrue(current.is_alive()) self.assertTrue(not current.daemon) self.assertIsInstance(authkey, bytes) self.assertTrue(len(authkey) > 0) self.assertEqual(current.ident, os.getpid()) self.assertEqual(current.exitcode, None) def test_daemon_argument(self): if self.TYPE == "threads": self.skipTest('test not appropriate for {}'.format(self.TYPE)) # By default uses the current process's daemon flag. proc0 = self.Process(target=self._test) self.assertEqual(proc0.daemon, self.current_process().daemon) proc1 = self.Process(target=self._test, daemon=True) self.assertTrue(proc1.daemon) proc2 = self.Process(target=self._test, daemon=False) self.assertFalse(proc2.daemon) @classmethod def _test(cls, q, *args, **kwds): current = cls.current_process() q.put(args) q.put(kwds) q.put(current.name) if cls.TYPE != 'threads': q.put(bytes(current.authkey)) q.put(current.pid) def test_process(self): q = self.Queue(1) e = self.Event() args = (q, 1, 2) kwargs = {'hello':23, 'bye':2.54} name = 'SomeProcess' p = self.Process( target=self._test, args=args, kwargs=kwargs, name=name ) p.daemon = True current = self.current_process() if self.TYPE != 'threads': self.assertEqual(p.authkey, current.authkey) self.assertEqual(p.is_alive(), False) self.assertEqual(p.daemon, True) self.assertNotIn(p, self.active_children()) self.assertTrue(type(self.active_children()) is list) self.assertEqual(p.exitcode, None) p.start() self.assertEqual(p.exitcode, None) self.assertEqual(p.is_alive(), True) self.assertIn(p, self.active_children()) self.assertEqual(q.get(), args[1:]) self.assertEqual(q.get(), kwargs) self.assertEqual(q.get(), p.name) if self.TYPE != 'threads': self.assertEqual(q.get(), current.authkey) self.assertEqual(q.get(), p.pid) p.join() self.assertEqual(p.exitcode, 0) self.assertEqual(p.is_alive(), False) self.assertNotIn(p, self.active_children()) close_queue(q) @classmethod def _sleep_some(cls): time.sleep(100) @classmethod def _test_sleep(cls, delay): time.sleep(delay) def _kill_process(self, meth): if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) p = self.Process(target=self._sleep_some) p.daemon = True p.start() self.assertEqual(p.is_alive(), True) self.assertIn(p, self.active_children()) self.assertEqual(p.exitcode, None) join = TimingWrapper(p.join) self.assertEqual(join(0), None) self.assertTimingAlmostEqual(join.elapsed, 0.0) self.assertEqual(p.is_alive(), True) self.assertEqual(join(-1), None) self.assertTimingAlmostEqual(join.elapsed, 0.0) self.assertEqual(p.is_alive(), True) # XXX maybe terminating too soon causes the problems on Gentoo... time.sleep(1) meth(p) if hasattr(signal, 'alarm'): # On the Gentoo buildbot waitpid() often seems to block forever. # We use alarm() to interrupt it if it blocks for too long. def handler(*args): raise RuntimeError('join took too long: %s' % p) old_handler = signal.signal(signal.SIGALRM, handler) try: signal.alarm(10) self.assertEqual(join(), None) finally: signal.alarm(0) signal.signal(signal.SIGALRM, old_handler) else: self.assertEqual(join(), None) self.assertTimingAlmostEqual(join.elapsed, 0.0) self.assertEqual(p.is_alive(), False) self.assertNotIn(p, self.active_children()) p.join() return p.exitcode def test_terminate(self): exitcode = self._kill_process(multiprocessing.Process.terminate) if os.name != 'nt': self.assertEqual(exitcode, -signal.SIGTERM) def test_kill(self): exitcode = self._kill_process(multiprocessing.Process.kill) if os.name != 'nt': self.assertEqual(exitcode, -signal.SIGKILL) def test_cpu_count(self): try: cpus = multiprocessing.cpu_count() except NotImplementedError: cpus = 1 self.assertTrue(type(cpus) is int) self.assertTrue(cpus >= 1) def test_active_children(self): self.assertEqual(type(self.active_children()), list) p = self.Process(target=time.sleep, args=(DELTA,)) self.assertNotIn(p, self.active_children()) p.daemon = True p.start() self.assertIn(p, self.active_children()) p.join() self.assertNotIn(p, self.active_children()) @classmethod def _test_recursion(cls, wconn, id): wconn.send(id) if len(id) < 2: for i in range(2): p = cls.Process( target=cls._test_recursion, args=(wconn, id+[i]) ) p.start() p.join() def test_recursion(self): rconn, wconn = self.Pipe(duplex=False) self._test_recursion(wconn, []) time.sleep(DELTA) result = [] while rconn.poll(): result.append(rconn.recv()) expected = [ [], [0], [0, 0], [0, 1], [1], [1, 0], [1, 1] ] self.assertEqual(result, expected) @classmethod def _test_sentinel(cls, event): event.wait(10.0) def test_sentinel(self): if self.TYPE == "threads": self.skipTest('test not appropriate for {}'.format(self.TYPE)) event = self.Event() p = self.Process(target=self._test_sentinel, args=(event,)) with self.assertRaises(ValueError): p.sentinel p.start() self.addCleanup(p.join) sentinel = p.sentinel self.assertIsInstance(sentinel, int) self.assertFalse(wait_for_handle(sentinel, timeout=0.0)) event.set() p.join() self.assertTrue(wait_for_handle(sentinel, timeout=1)) @classmethod def _test_close(cls, rc=0, q=None): if q is not None: q.get() sys.exit(rc) def test_close(self): if self.TYPE == "threads": self.skipTest('test not appropriate for {}'.format(self.TYPE)) q = self.Queue() p = self.Process(target=self._test_close, kwargs={'q': q}) p.daemon = True p.start() self.assertEqual(p.is_alive(), True) # Child is still alive, cannot close with self.assertRaises(ValueError): p.close() q.put(None) p.join() self.assertEqual(p.is_alive(), False) self.assertEqual(p.exitcode, 0) p.close() with self.assertRaises(ValueError): p.is_alive() with self.assertRaises(ValueError): p.join() with self.assertRaises(ValueError): p.terminate() p.close() wr = weakref.ref(p) del p gc.collect() self.assertIs(wr(), None) close_queue(q) def test_many_processes(self): if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) sm = multiprocessing.get_start_method() N = 5 if sm == 'spawn' else 100 # Try to overwhelm the forkserver loop with events procs = [self.Process(target=self._test_sleep, args=(0.01,)) for i in range(N)] for p in procs: p.start() for p in procs: join_process(p) for p in procs: self.assertEqual(p.exitcode, 0) procs = [self.Process(target=self._sleep_some) for i in range(N)] for p in procs: p.start() time.sleep(0.001) # let the children start... for p in procs: p.terminate() for p in procs: join_process(p) if os.name != 'nt': exitcodes = [-signal.SIGTERM] if sys.platform == 'darwin': # bpo-31510: On macOS, killing a freshly started process with # SIGTERM sometimes kills the process with SIGKILL. exitcodes.append(-signal.SIGKILL) for p in procs: self.assertIn(p.exitcode, exitcodes) def test_lose_target_ref(self): c = DummyCallable() wr = weakref.ref(c) q = self.Queue() p = self.Process(target=c, args=(q, c)) del c p.start() p.join() self.assertIs(wr(), None) self.assertEqual(q.get(), 5) close_queue(q) @classmethod def _test_child_fd_inflation(self, evt, q): q.put(test.support.fd_count()) evt.wait() def test_child_fd_inflation(self): # Number of fds in child processes should not grow with the # number of running children. if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) sm = multiprocessing.get_start_method() if sm == 'fork': # The fork method by design inherits all fds from the parent, # trying to go against it is a lost battle self.skipTest('test not appropriate for {}'.format(sm)) N = 5 evt = self.Event() q = self.Queue() procs = [self.Process(target=self._test_child_fd_inflation, args=(evt, q)) for i in range(N)] for p in procs: p.start() try: fd_counts = [q.get() for i in range(N)] self.assertEqual(len(set(fd_counts)), 1, fd_counts) finally: evt.set() for p in procs: p.join() close_queue(q) @classmethod def _test_wait_for_threads(self, evt): def func1(): time.sleep(0.5) evt.set() def func2(): time.sleep(20) evt.clear() threading.Thread(target=func1).start() threading.Thread(target=func2, daemon=True).start() def test_wait_for_threads(self): # A child process should wait for non-daemonic threads to end # before exiting if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) evt = self.Event() proc = self.Process(target=self._test_wait_for_threads, args=(evt,)) proc.start() proc.join() self.assertTrue(evt.is_set()) @classmethod def _test_error_on_stdio_flush(self, evt, break_std_streams={}): for stream_name, action in break_std_streams.items(): if action == 'close': stream = io.StringIO() stream.close() else: assert action == 'remove' stream = None setattr(sys, stream_name, None) evt.set() def test_error_on_stdio_flush_1(self): # Check that Process works with broken standard streams streams = [io.StringIO(), None] streams[0].close() for stream_name in ('stdout', 'stderr'): for stream in streams: old_stream = getattr(sys, stream_name) setattr(sys, stream_name, stream) try: evt = self.Event() proc = self.Process(target=self._test_error_on_stdio_flush, args=(evt,)) proc.start() proc.join() self.assertTrue(evt.is_set()) self.assertEqual(proc.exitcode, 0) finally: setattr(sys, stream_name, old_stream) def test_error_on_stdio_flush_2(self): # Same as test_error_on_stdio_flush_1(), but standard streams are # broken by the child process for stream_name in ('stdout', 'stderr'): for action in ('close', 'remove'): old_stream = getattr(sys, stream_name) try: evt = self.Event() proc = self.Process(target=self._test_error_on_stdio_flush, args=(evt, {stream_name: action})) proc.start() proc.join() self.assertTrue(evt.is_set()) self.assertEqual(proc.exitcode, 0) finally: setattr(sys, stream_name, old_stream) @classmethod def _sleep_and_set_event(self, evt, delay=0.0): time.sleep(delay) evt.set() def check_forkserver_death(self, signum): # bpo-31308: if the forkserver process has died, we should still # be able to create and run new Process instances (the forkserver # is implicitly restarted). if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) sm = multiprocessing.get_start_method() if sm != 'forkserver': # The fork method by design inherits all fds from the parent, # trying to go against it is a lost battle self.skipTest('test not appropriate for {}'.format(sm)) from multiprocessing.forkserver import _forkserver _forkserver.ensure_running() # First process sleeps 500 ms delay = 0.5 evt = self.Event() proc = self.Process(target=self._sleep_and_set_event, args=(evt, delay)) proc.start() pid = _forkserver._forkserver_pid os.kill(pid, signum) # give time to the fork server to die and time to proc to complete time.sleep(delay * 2.0) evt2 = self.Event() proc2 = self.Process(target=self._sleep_and_set_event, args=(evt2,)) proc2.start() proc2.join() self.assertTrue(evt2.is_set()) self.assertEqual(proc2.exitcode, 0) proc.join() self.assertTrue(evt.is_set()) self.assertIn(proc.exitcode, (0, 255)) def test_forkserver_sigint(self): # Catchable signal self.check_forkserver_death(signal.SIGINT) def test_forkserver_sigkill(self): # Uncatchable signal if os.name != 'nt': self.check_forkserver_death(signal.SIGKILL) # # # class _UpperCaser(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.child_conn, self.parent_conn = multiprocessing.Pipe() def run(self): self.parent_conn.close() for s in iter(self.child_conn.recv, None): self.child_conn.send(s.upper()) self.child_conn.close() def submit(self, s): assert type(s) is str self.parent_conn.send(s) return self.parent_conn.recv() def stop(self): self.parent_conn.send(None) self.parent_conn.close() self.child_conn.close() class _TestSubclassingProcess(BaseTestCase): ALLOWED_TYPES = ('processes',) def test_subclassing(self): uppercaser = _UpperCaser() uppercaser.daemon = True uppercaser.start() self.assertEqual(uppercaser.submit('hello'), 'HELLO') self.assertEqual(uppercaser.submit('world'), 'WORLD') uppercaser.stop() uppercaser.join() def test_stderr_flush(self): # sys.stderr is flushed at process shutdown (issue #13812) if self.TYPE == "threads": self.skipTest('test not appropriate for {}'.format(self.TYPE)) testfn = test.support.TESTFN self.addCleanup(test.support.unlink, testfn) proc = self.Process(target=self._test_stderr_flush, args=(testfn,)) proc.start() proc.join() with open(testfn, 'r') as f: err = f.read() # The whole traceback was printed self.assertIn("ZeroDivisionError", err) self.assertIn("test_multiprocessing.py", err) self.assertIn("1/0 # MARKER", err) @classmethod def _test_stderr_flush(cls, testfn): fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL) sys.stderr = open(fd, 'w', closefd=False) 1/0 # MARKER @classmethod def _test_sys_exit(cls, reason, testfn): fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL) sys.stderr = open(fd, 'w', closefd=False) sys.exit(reason) def test_sys_exit(self): # See Issue 13854 if self.TYPE == 'threads': self.skipTest('test not appropriate for {}'.format(self.TYPE)) testfn = test.support.TESTFN self.addCleanup(test.support.unlink, testfn) for reason in ( [1, 2, 3], 'ignore this', ): p = self.Process(target=self._test_sys_exit, args=(reason, testfn)) p.daemon = True p.start() join_process(p) self.assertEqual(p.exitcode, 1) with open(testfn, 'r') as f: content = f.read() self.assertEqual(content.rstrip(), str(reason)) os.unlink(testfn) for reason in (True, False, 8): p = self.Process(target=sys.exit, args=(reason,)) p.daemon = True p.start() join_process(p) self.assertEqual(p.exitcode, reason) # # # def queue_empty(q): if hasattr(q, 'empty'): return q.empty() else: return q.qsize() == 0 def queue_full(q, maxsize): if hasattr(q, 'full'): return q.full() else: return q.qsize() == maxsize class _TestQueue(BaseTestCase): @classmethod def _test_put(cls, queue, child_can_start, parent_can_continue): child_can_start.wait() for i in range(6): queue.get() parent_can_continue.set() def test_put(self): MAXSIZE = 6 queue = self.Queue(maxsize=MAXSIZE) child_can_start = self.Event() parent_can_continue = self.Event() proc = self.Process( target=self._test_put, args=(queue, child_can_start, parent_can_continue) ) proc.daemon = True proc.start() self.assertEqual(queue_empty(queue), True) self.assertEqual(queue_full(queue, MAXSIZE), False) queue.put(1) queue.put(2, True) queue.put(3, True, None) queue.put(4, False) queue.put(5, False, None) queue.put_nowait(6) # the values may be in buffer but not yet in pipe so sleep a bit time.sleep(DELTA) self.assertEqual(queue_empty(queue), False) self.assertEqual(queue_full(queue, MAXSIZE), True) put = TimingWrapper(queue.put) put_nowait = TimingWrapper(queue.put_nowait) self.assertRaises(pyqueue.Full, put, 7, False) self.assertTimingAlmostEqual(put.elapsed, 0) self.assertRaises(pyqueue.Full, put, 7, False, None) self.assertTimingAlmostEqual(put.elapsed, 0) self.assertRaises(pyqueue.Full, put_nowait, 7) self.assertTimingAlmostEqual(put_nowait.elapsed, 0) self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1) self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1) self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2) self.assertTimingAlmostEqual(put.elapsed, 0) self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3) self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3) child_can_start.set() parent_can_continue.wait() self.assertEqual(queue_empty(queue), True) self.assertEqual(queue_full(queue, MAXSIZE), False) proc.join() close_queue(queue) @classmethod def _test_get(cls, queue, child_can_start, parent_can_continue): child_can_start.wait() #queue.put(1) queue.put(2) queue.put(3) queue.put(4) queue.put(5) parent_can_continue.set() def test_get(self): queue = self.Queue() child_can_start = self.Event() parent_can_continue = self.Event() proc = self.Process( target=self._test_get, args=(queue, child_can_start, parent_can_continue) ) proc.daemon = True proc.start() self.assertEqual(queue_empty(queue), True) child_can_start.set() parent_can_continue.wait() time.sleep(DELTA) self.assertEqual(queue_empty(queue), False) # Hangs unexpectedly, remove for now #self.assertEqual(queue.get(), 1) self.assertEqual(queue.get(True, None), 2) self.assertEqual(queue.get(True), 3) self.assertEqual(queue.get(timeout=1), 4) self.assertEqual(queue.get_nowait(), 5) self.assertEqual(queue_empty(queue), True) get = TimingWrapper(queue.get) get_nowait = TimingWrapper(queue.get_nowait) self.assertRaises(pyqueue.Empty, get, False) self.assertTimingAlmostEqual(get.elapsed, 0) self.assertRaises(pyqueue.Empty, get, False, None) self.assertTimingAlmostEqual(get.elapsed, 0) self.assertRaises(pyqueue.Empty, get_nowait) self.assertTimingAlmostEqual(get_nowait.elapsed, 0) self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1) self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2) self.assertTimingAlmostEqual(get.elapsed, 0) self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3) self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3) proc.join() close_queue(queue) @classmethod def _test_fork(cls, queue): for i in range(10, 20): queue.put(i) # note that at this point the items may only be buffered, so the # process cannot shutdown until the feeder thread has finished # pushing items onto the pipe. def test_fork(self): # Old versions of Queue would fail to create a new feeder # thread for a forked process if the original process had its # own feeder thread. This test checks that this no longer # happens. queue = self.Queue() # put items on queue so that main process starts a feeder thread for i in range(10): queue.put(i) # wait to make sure thread starts before we fork a new process time.sleep(DELTA) # fork process p = self.Process(target=self._test_fork, args=(queue,)) p.daemon = True p.start() # check that all expected items are in the queue for i in range(20): self.assertEqual(queue.get(), i) self.assertRaises(pyqueue.Empty, queue.get, False) p.join() close_queue(queue) def test_qsize(self): q = self.Queue() try: self.assertEqual(q.qsize(), 0) except NotImplementedError: self.skipTest('qsize method not implemented') q.put(1) self.assertEqual(q.qsize(), 1) q.put(5) self.assertEqual(q.qsize(), 2) q.get() self.assertEqual(q.qsize(), 1) q.get() self.assertEqual(q.qsize(), 0) close_queue(q) @classmethod def _test_task_done(cls, q): for obj in iter(q.get, None): time.sleep(DELTA) q.task_done() def test_task_done(self): queue = self.JoinableQueue() workers = [self.Process(target=self._test_task_done, args=(queue,)) for i in range(4)] for p in workers: p.daemon = True p.start() for i in range(10): queue.put(i) queue.join() for p in workers: queue.put(None) for p in workers: p.join() close_queue(queue) def test_no_import_lock_contention(self): with test.support.temp_cwd(): module_name = 'imported_by_an_imported_module' with open(module_name + '.py', 'w') as f: f.write("""if 1: import multiprocessing q = multiprocessing.Queue() q.put('knock knock') q.get(timeout=3) q.close() del q """) with test.support.DirsOnSysPath(os.getcwd()): try: __import__(module_name) except pyqueue.Empty: self.fail("Probable regression on import lock contention;" " see Issue #22853") def test_timeout(self): q = multiprocessing.Queue() start = time.monotonic() self.assertRaises(pyqueue.Empty, q.get, True, 0.200) delta = time.monotonic() - start # bpo-30317: Tolerate a delta of 100 ms because of the bad clock # resolution on Windows (usually 15.6 ms). x86 Windows7 3.x once # failed because the delta was only 135.8 ms. self.assertGreaterEqual(delta, 0.100) close_queue(q) def test_queue_feeder_donot_stop_onexc(self): # bpo-30414: verify feeder handles exceptions correctly if self.TYPE != 'processes': self.skipTest('test not appropriate for {}'.format(self.TYPE)) class NotSerializable(object): def __reduce__(self): raise AttributeError with test.support.captured_stderr(): q = self.Queue() q.put(NotSerializable()) q.put(True) self.assertTrue(q.get(timeout=TIMEOUT)) close_queue(q) with test.support.captured_stderr(): # bpo-33078: verify that the queue size is correctly handled # on errors. q = self.Queue(maxsize=1) q.put(NotSerializable()) q.put(True) try: self.assertEqual(q.qsize(), 1) except NotImplementedError: # qsize is not available on all platform as it # relies on sem_getvalue pass # bpo-30595: use a timeout of 1 second for slow buildbots self.assertTrue(q.get(timeout=1.0)) # Check that the size of the queue is correct self.assertTrue(q.empty()) close_queue(q) def test_queue_feeder_on_queue_feeder_error(self): # bpo-30006: verify feeder handles exceptions using the # _on_queue_feeder_error hook. if self.TYPE != 'processes': self.skipTest('test not appropriate for {}'.format(self.TYPE)) class NotSerializable(object): """Mock unserializable object""" def __init__(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/dis_module.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/dis_module.py
# A simple module for testing the dis module. def f(): pass def g(): 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_dynamicclassattribute.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dynamicclassattribute.py
# Test case for DynamicClassAttribute # more tests are in test_descr import abc import sys import unittest from types import DynamicClassAttribute 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 @DynamicClassAttribute 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): spam = BaseClass.__dict__['spam'] @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 = DynamicClassAttribute(_get_spam, doc="spam spam spam") class PropertyDocSub(PropertyDocBase): spam = PropertyDocBase.__dict__['spam'] @spam.getter def spam(self): """The decorator does not use this doc string""" return self._spam class PropertySubNewGetter(BaseClass): spam = BaseClass.__dict__['spam'] @spam.getter def spam(self): """new docstring""" return 5 class PropertyNewGetter(object): @DynamicClassAttribute def spam(self): """original docstring""" return 1 @spam.getter def spam(self): """new docstring""" return 8 class ClassWithAbstractVirtualProperty(metaclass=abc.ABCMeta): @DynamicClassAttribute @abc.abstractmethod def color(): pass class ClassWithPropertyAbstractVirtual(metaclass=abc.ABCMeta): @abc.abstractmethod @DynamicClassAttribute def color(): pass 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__.__dict__['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__.__dict__['spam'].__doc__, "BaseClass.getter") def test_property_decorator_doc(self): base = PropertyDocBase() sub = PropertyDocSub() self.assertEqual(base.__class__.__dict__['spam'].__doc__, "spam spam spam") self.assertEqual(sub.__class__.__dict__['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__.__dict__['spam'].__doc__, "new docstring") newgetter = PropertyNewGetter() self.assertEqual(newgetter.spam, 8) self.assertEqual(newgetter.__class__.__dict__['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 = DynamicClassAttribute(foo) self.assertIs(C.__dict__['foo'].__isabstractmethod__, bool(val)) # check that the DynamicClassAttribute'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 = DynamicClassAttribute(foo) def test_abstract_virtual(self): self.assertRaises(TypeError, ClassWithAbstractVirtualProperty) self.assertRaises(TypeError, ClassWithPropertyAbstractVirtual) class APV(ClassWithPropertyAbstractVirtual): pass self.assertRaises(TypeError, APV) class AVP(ClassWithAbstractVirtualProperty): pass self.assertRaises(TypeError, AVP) class Okay1(ClassWithAbstractVirtualProperty): @DynamicClassAttribute def color(self): return self._color def __init__(self): self._color = 'cyan' with self.assertRaises(AttributeError): Okay1.color self.assertEqual(Okay1().color, 'cyan') class Okay2(ClassWithAbstractVirtualProperty): @DynamicClassAttribute def color(self): return self._color def __init__(self): self._color = 'magenta' with self.assertRaises(AttributeError): Okay2.color self.assertEqual(Okay2().color, 'magenta') # Issue 5890: subclasses of DynamicClassAttribute do not preserve method __doc__ strings class PropertySub(DynamicClassAttribute): """This is a subclass of DynamicClassAttribute""" class PropertySubSlots(DynamicClassAttribute): """This is a subclass of DynamicClassAttribute that defines __slots__""" __slots__ = () class PropertySubclassTests(unittest.TestCase): @unittest.skipIf(hasattr(PropertySubSlots, '__doc__'), "__doc__ is already present, __slots__ will have no effect") 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 print('\n',spam.__doc__) 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 DynamicClassAttribute subclass""" return 1 self.assertEqual( Foo.__dict__['spam'].__doc__, "spam wrapped in DynamicClassAttribute 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 DynamicClassAttribute 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.__dict__['spam'].__doc__, "spam wrapped in DynamicClassAttribute subclass") class FooSub(Foo): spam = Foo.__dict__['spam'] @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.__dict__['spam'].__doc__, "spam wrapped in DynamicClassAttribute 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.__dict__['spam'].__doc__, "a new docstring") class FooBase(object): @PropertySub def spam(self): """a docstring""" return 1 class Foo2(FooBase): spam = FooBase.__dict__['spam'] @spam.getter def spam(self): """a new docstring""" return 2 self.assertEqual(Foo.__dict__['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_robotparser.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_robotparser.py
import io import os import threading import unittest import urllib.robotparser from test import support from http.server import BaseHTTPRequestHandler, HTTPServer class BaseRobotTest: robots_txt = '' agent = 'test_robotparser' good = [] bad = [] def setUp(self): lines = io.StringIO(self.robots_txt).readlines() self.parser = urllib.robotparser.RobotFileParser() self.parser.parse(lines) def get_agent_and_url(self, url): if isinstance(url, tuple): agent, url = url return agent, url return self.agent, url def test_good_urls(self): for url in self.good: agent, url = self.get_agent_and_url(url) with self.subTest(url=url, agent=agent): self.assertTrue(self.parser.can_fetch(agent, url)) def test_bad_urls(self): for url in self.bad: agent, url = self.get_agent_and_url(url) with self.subTest(url=url, agent=agent): self.assertFalse(self.parser.can_fetch(agent, url)) class UserAgentWildcardTest(BaseRobotTest, unittest.TestCase): robots_txt = """\ User-agent: * Disallow: /cyberworld/map/ # This is an infinite virtual URL space Disallow: /tmp/ # these will soon disappear Disallow: /foo.html """ good = ['/', '/test.html'] bad = ['/cyberworld/map/index.html', '/tmp/xxx', '/foo.html'] class CrawlDelayAndCustomAgentTest(BaseRobotTest, unittest.TestCase): robots_txt = """\ # robots.txt for http://www.example.com/ User-agent: * Crawl-delay: 1 Request-rate: 3/15 Disallow: /cyberworld/map/ # This is an infinite virtual URL space # Cybermapper knows where to go. User-agent: cybermapper Disallow: """ good = ['/', '/test.html', ('cybermapper', '/cyberworld/map/index.html')] bad = ['/cyberworld/map/index.html'] class RejectAllRobotsTest(BaseRobotTest, unittest.TestCase): robots_txt = """\ # go away User-agent: * Disallow: / """ good = [] bad = ['/cyberworld/map/index.html', '/', '/tmp/'] class BaseRequestRateTest(BaseRobotTest): request_rate = None crawl_delay = None def test_request_rate(self): parser = self.parser for url in self.good + self.bad: agent, url = self.get_agent_and_url(url) with self.subTest(url=url, agent=agent): self.assertEqual(parser.crawl_delay(agent), self.crawl_delay) parsed_request_rate = parser.request_rate(agent) self.assertEqual(parsed_request_rate, self.request_rate) if self.request_rate is not None: self.assertIsInstance( parsed_request_rate, urllib.robotparser.RequestRate ) self.assertEqual( parsed_request_rate.requests, self.request_rate.requests ) self.assertEqual( parsed_request_rate.seconds, self.request_rate.seconds ) class EmptyFileTest(BaseRequestRateTest, unittest.TestCase): robots_txt = '' good = ['/foo'] class CrawlDelayAndRequestRateTest(BaseRequestRateTest, unittest.TestCase): robots_txt = """\ User-agent: figtree Crawl-delay: 3 Request-rate: 9/30 Disallow: /tmp Disallow: /a%3cd.html Disallow: /a%2fb.html Disallow: /%7ejoe/index.html """ agent = 'figtree' request_rate = urllib.robotparser.RequestRate(9, 30) crawl_delay = 3 good = [('figtree', '/foo.html')] bad = ['/tmp', '/tmp.html', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', '/a%2fb.html', '/~joe/index.html'] class DifferentAgentTest(CrawlDelayAndRequestRateTest): agent = 'FigTree Robot libwww-perl/5.04' class InvalidRequestRateTest(BaseRobotTest, unittest.TestCase): robots_txt = """\ User-agent: * Disallow: /tmp/ Disallow: /a%3Cd.html Disallow: /a/b.html Disallow: /%7ejoe/index.html Crawl-delay: 3 Request-rate: 9/banana """ good = ['/tmp'] bad = ['/tmp/', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', '/a/b.html', '/%7Ejoe/index.html'] crawl_delay = 3 class InvalidCrawlDelayTest(BaseRobotTest, unittest.TestCase): # From bug report #523041 robots_txt = """\ User-Agent: * Disallow: /. Crawl-delay: pears """ good = ['/foo.html'] # bug report says "/" should be denied, but that is not in the RFC bad = [] class AnotherInvalidRequestRateTest(BaseRobotTest, unittest.TestCase): # also test that Allow and Diasallow works well with each other robots_txt = """\ User-agent: Googlebot Allow: /folder1/myfile.html Disallow: /folder1/ Request-rate: whale/banana """ agent = 'Googlebot' good = ['/folder1/myfile.html'] bad = ['/folder1/anotherfile.html'] class UserAgentOrderingTest(BaseRobotTest, unittest.TestCase): # the order of User-agent should be correct. note # that this file is incorrect because "Googlebot" is a # substring of "Googlebot-Mobile" robots_txt = """\ User-agent: Googlebot Disallow: / User-agent: Googlebot-Mobile Allow: / """ agent = 'Googlebot' bad = ['/something.jpg'] class UserAgentGoogleMobileTest(UserAgentOrderingTest): agent = 'Googlebot-Mobile' class GoogleURLOrderingTest(BaseRobotTest, unittest.TestCase): # Google also got the order wrong. You need # to specify the URLs from more specific to more general robots_txt = """\ User-agent: Googlebot Allow: /folder1/myfile.html Disallow: /folder1/ """ agent = 'googlebot' good = ['/folder1/myfile.html'] bad = ['/folder1/anotherfile.html'] class DisallowQueryStringTest(BaseRobotTest, unittest.TestCase): # see issue #6325 for details robots_txt = """\ User-agent: * Disallow: /some/path?name=value """ good = ['/some/path'] bad = ['/some/path?name=value'] class UseFirstUserAgentWildcardTest(BaseRobotTest, unittest.TestCase): # obey first * entry (#4108) robots_txt = """\ User-agent: * Disallow: /some/path User-agent: * Disallow: /another/path """ good = ['/another/path'] bad = ['/some/path'] class EmptyQueryStringTest(BaseRobotTest, unittest.TestCase): # normalize the URL first (#17403) robots_txt = """\ User-agent: * Allow: /some/path? Disallow: /another/path? """ good = ['/some/path?'] bad = ['/another/path?'] class DefaultEntryTest(BaseRequestRateTest, unittest.TestCase): robots_txt = """\ User-agent: * Crawl-delay: 1 Request-rate: 3/15 Disallow: /cyberworld/map/ """ request_rate = urllib.robotparser.RequestRate(3, 15) crawl_delay = 1 good = ['/', '/test.html'] bad = ['/cyberworld/map/index.html'] class StringFormattingTest(BaseRobotTest, unittest.TestCase): robots_txt = """\ User-agent: * Crawl-delay: 1 Request-rate: 3/15 Disallow: /cyberworld/map/ # This is an infinite virtual URL space # Cybermapper knows where to go. User-agent: cybermapper Disallow: /some/path """ expected_output = """\ User-agent: cybermapper Disallow: /some/path User-agent: * Crawl-delay: 1 Request-rate: 3/15 Disallow: /cyberworld/map/ """ def test_string_formatting(self): self.assertEqual(str(self.parser), self.expected_output) class RobotHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_error(403, "Forbidden access") def log_message(self, format, *args): pass class PasswordProtectedSiteTestCase(unittest.TestCase): def setUp(self): self.server = HTTPServer((support.HOST, 0), RobotHandler) self.t = threading.Thread( name='HTTPServer serving', target=self.server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval':0.01}) self.t.daemon = True # In case this function raises. self.t.start() def tearDown(self): self.server.shutdown() self.t.join() self.server.server_close() @support.reap_threads def testPasswordProtectedSite(self): addr = self.server.server_address url = 'http://' + support.HOST + ':' + str(addr[1]) robots_url = url + "/robots.txt" parser = urllib.robotparser.RobotFileParser() parser.set_url(url) parser.read() self.assertFalse(parser.can_fetch("*", robots_url)) class NetworkTestCase(unittest.TestCase): base_url = 'http://www.pythontest.net/' robots_txt = '{}elsewhere/robots.txt'.format(base_url) @classmethod def setUpClass(cls): support.requires('network') with support.transient_internet(cls.base_url): cls.parser = urllib.robotparser.RobotFileParser(cls.robots_txt) cls.parser.read() def url(self, path): return '{}{}{}'.format( self.base_url, path, '/' if not os.path.splitext(path)[1] else '' ) def test_basic(self): self.assertFalse(self.parser.disallow_all) self.assertFalse(self.parser.allow_all) self.assertGreater(self.parser.mtime(), 0) self.assertFalse(self.parser.crawl_delay('*')) self.assertFalse(self.parser.request_rate('*')) def test_can_fetch(self): self.assertTrue(self.parser.can_fetch('*', self.url('elsewhere'))) self.assertFalse(self.parser.can_fetch('Nutch', self.base_url)) self.assertFalse(self.parser.can_fetch('Nutch', self.url('brian'))) self.assertFalse(self.parser.can_fetch('Nutch', self.url('webstats'))) self.assertFalse(self.parser.can_fetch('*', self.url('webstats'))) self.assertTrue(self.parser.can_fetch('*', self.base_url)) def test_read_404(self): parser = urllib.robotparser.RobotFileParser(self.url('i-robot.txt')) parser.read() self.assertTrue(parser.allow_all) self.assertFalse(parser.disallow_all) self.assertEqual(parser.mtime(), 0) self.assertIsNone(parser.crawl_delay('*')) self.assertIsNone(parser.request_rate('*')) 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_sys_setprofile.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_sys_setprofile.py
import gc import pprint import sys import unittest class TestGetProfile(unittest.TestCase): def setUp(self): sys.setprofile(None) def tearDown(self): sys.setprofile(None) def test_empty(self): self.assertIsNone(sys.getprofile()) def test_setget(self): def fn(*args): pass sys.setprofile(fn) self.assertIs(sys.getprofile(), fn) class HookWatcher: def __init__(self): self.frames = [] self.events = [] def callback(self, frame, event, arg): if (event == "call" or event == "return" or event == "exception"): self.add_event(event, frame) def add_event(self, event, frame=None): """Add an event to the log.""" if frame is None: frame = sys._getframe(1) try: frameno = self.frames.index(frame) except ValueError: frameno = len(self.frames) self.frames.append(frame) self.events.append((frameno, event, ident(frame))) def get_events(self): """Remove calls to add_event().""" disallowed = [ident(self.add_event.__func__), ident(ident)] self.frames = None return [item for item in self.events if item[2] not in disallowed] class ProfileSimulator(HookWatcher): def __init__(self, testcase): self.testcase = testcase self.stack = [] HookWatcher.__init__(self) def callback(self, frame, event, arg): # Callback registered with sys.setprofile()/sys.settrace() self.dispatch[event](self, frame) def trace_call(self, frame): self.add_event('call', frame) self.stack.append(frame) def trace_return(self, frame): self.add_event('return', frame) self.stack.pop() def trace_exception(self, frame): self.testcase.fail( "the profiler should never receive exception events") def trace_pass(self, frame): pass dispatch = { 'call': trace_call, 'exception': trace_exception, 'return': trace_return, 'c_call': trace_pass, 'c_return': trace_pass, 'c_exception': trace_pass, } class TestCaseBase(unittest.TestCase): def check_events(self, callable, expected): events = capture_events(callable, self.new_watcher()) if events != expected: self.fail("Expected events:\n%s\nReceived events:\n%s" % (pprint.pformat(expected), pprint.pformat(events))) class ProfileHookTestCase(TestCaseBase): def new_watcher(self): return HookWatcher() def test_simple(self): def f(p): pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_caught_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_caught_nested_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_nested_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), # This isn't what I expected: # (0, 'exception', protect_ident), # I expected this again: (1, 'return', f_ident), ]) def test_exception_in_except_clause(self): def f(p): 1/0 def g(p): try: f(p) except: try: f(p) except: pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), (2, 'call', f_ident), (2, 'return', f_ident), (3, 'call', f_ident), (3, 'return', f_ident), (1, 'return', g_ident), ]) def test_exception_propagation(self): def f(p): 1/0 def g(p): try: f(p) finally: p.add_event("falling through") f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), (2, 'call', f_ident), (2, 'return', f_ident), (1, 'falling through', g_ident), (1, 'return', g_ident), ]) def test_raise_twice(self): def f(p): try: 1/0 except: 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_raise_reraise(self): def f(p): try: 1/0 except: raise f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_raise(self): def f(p): raise Exception() f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_distant_exception(self): def f(): 1/0 def g(): f() def h(): g() def i(): h() def j(p): i() f_ident = ident(f) g_ident = ident(g) h_ident = ident(h) i_ident = ident(i) j_ident = ident(j) self.check_events(j, [(1, 'call', j_ident), (2, 'call', i_ident), (3, 'call', h_ident), (4, 'call', g_ident), (5, 'call', f_ident), (5, 'return', f_ident), (4, 'return', g_ident), (3, 'return', h_ident), (2, 'return', i_ident), (1, 'return', j_ident), ]) def test_generator(self): def f(): for i in range(2): yield i def g(p): for i in f(): pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), # call the iterator twice to generate values (2, 'call', f_ident), (2, 'return', f_ident), (2, 'call', f_ident), (2, 'return', f_ident), # once more; returns end-of-iteration with # actually raising an exception (2, 'call', f_ident), (2, 'return', f_ident), (1, 'return', g_ident), ]) def test_stop_iteration(self): def f(): for i in range(2): yield i def g(p): for i in f(): pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), # call the iterator twice to generate values (2, 'call', f_ident), (2, 'return', f_ident), (2, 'call', f_ident), (2, 'return', f_ident), # once more to hit the raise: (2, 'call', f_ident), (2, 'return', f_ident), (1, 'return', g_ident), ]) class ProfileSimulatorTestCase(TestCaseBase): def new_watcher(self): return ProfileSimulator(self) def test_simple(self): def f(p): pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_basic_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_caught_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) def test_distant_exception(self): def f(): 1/0 def g(): f() def h(): g() def i(): h() def j(p): i() f_ident = ident(f) g_ident = ident(g) h_ident = ident(h) i_ident = ident(i) j_ident = ident(j) self.check_events(j, [(1, 'call', j_ident), (2, 'call', i_ident), (3, 'call', h_ident), (4, 'call', g_ident), (5, 'call', f_ident), (5, 'return', f_ident), (4, 'return', g_ident), (3, 'return', h_ident), (2, 'return', i_ident), (1, 'return', j_ident), ]) # Test an invalid call (bpo-34126) def test_unbound_method_no_args(self): def f(p): dict.get() f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) # Test an invalid call (bpo-34126) def test_unbound_method_invalid_args(self): def f(p): dict.get(print, 42) f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) def ident(function): if hasattr(function, "f_code"): code = function.f_code else: code = function.__code__ return code.co_firstlineno, code.co_name def protect(f, p): try: f(p) except: pass protect_ident = ident(protect) def capture_events(callable, p=None): if p is None: p = HookWatcher() # Disable the garbage collector. This prevents __del__s from showing up in # traces. old_gc = gc.isenabled() gc.disable() try: sys.setprofile(p.callback) protect(callable, p) sys.setprofile(None) finally: if old_gc: gc.enable() return p.get_events()[1:-1] def show_events(callable): import pprint pprint.pprint(capture_events(callable)) 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_plistlib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_plistlib.py
# Copyright (C) 2003-2013 Python Software Foundation import unittest import plistlib import os import datetime import codecs import binascii import collections from test import support from io import BytesIO ALL_FORMATS=(plistlib.FMT_XML, plistlib.FMT_BINARY) # The testdata is generated using Mac/Tools/plistlib_generate_testdata.py # (which using PyObjC to control the Cocoa classes for generating plists) TESTDATA={ plistlib.FMT_XML: binascii.a2b_base64(b''' PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NU WVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VO IiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4w LmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk+YUJp Z0ludDwva2V5PgoJPGludGVnZXI+OTIyMzM3MjAzNjg1NDc3NTc2NDwvaW50 ZWdlcj4KCTxrZXk+YUJpZ0ludDI8L2tleT4KCTxpbnRlZ2VyPjkyMjMzNzIw MzY4NTQ3NzU4NTI8L2ludGVnZXI+Cgk8a2V5PmFEYXRlPC9rZXk+Cgk8ZGF0 ZT4yMDA0LTEwLTI2VDEwOjMzOjMzWjwvZGF0ZT4KCTxrZXk+YURpY3Q8L2tl eT4KCTxkaWN0PgoJCTxrZXk+YUZhbHNlVmFsdWU8L2tleT4KCQk8ZmFsc2Uv PgoJCTxrZXk+YVRydWVWYWx1ZTwva2V5PgoJCTx0cnVlLz4KCQk8a2V5PmFV bmljb2RlVmFsdWU8L2tleT4KCQk8c3RyaW5nPk3DpHNzaWcsIE1hw588L3N0 cmluZz4KCQk8a2V5PmFub3RoZXJTdHJpbmc8L2tleT4KCQk8c3RyaW5nPiZs dDtoZWxsbyAmYW1wOyAnaGknIHRoZXJlISZndDs8L3N0cmluZz4KCQk8a2V5 PmRlZXBlckRpY3Q8L2tleT4KCQk8ZGljdD4KCQkJPGtleT5hPC9rZXk+CgkJ CTxpbnRlZ2VyPjE3PC9pbnRlZ2VyPgoJCQk8a2V5PmI8L2tleT4KCQkJPHJl YWw+MzIuNTwvcmVhbD4KCQkJPGtleT5jPC9rZXk+CgkJCTxhcnJheT4KCQkJ CTxpbnRlZ2VyPjE8L2ludGVnZXI+CgkJCQk8aW50ZWdlcj4yPC9pbnRlZ2Vy PgoJCQkJPHN0cmluZz50ZXh0PC9zdHJpbmc+CgkJCTwvYXJyYXk+CgkJPC9k aWN0PgoJPC9kaWN0PgoJPGtleT5hRmxvYXQ8L2tleT4KCTxyZWFsPjAuNTwv cmVhbD4KCTxrZXk+YUxpc3Q8L2tleT4KCTxhcnJheT4KCQk8c3RyaW5nPkE8 L3N0cmluZz4KCQk8c3RyaW5nPkI8L3N0cmluZz4KCQk8aW50ZWdlcj4xMjwv aW50ZWdlcj4KCQk8cmVhbD4zMi41PC9yZWFsPgoJCTxhcnJheT4KCQkJPGlu dGVnZXI+MTwvaW50ZWdlcj4KCQkJPGludGVnZXI+MjwvaW50ZWdlcj4KCQkJ PGludGVnZXI+MzwvaW50ZWdlcj4KCQk8L2FycmF5PgoJPC9hcnJheT4KCTxr ZXk+YU5lZ2F0aXZlQmlnSW50PC9rZXk+Cgk8aW50ZWdlcj4tODAwMDAwMDAw MDA8L2ludGVnZXI+Cgk8a2V5PmFOZWdhdGl2ZUludDwva2V5PgoJPGludGVn ZXI+LTU8L2ludGVnZXI+Cgk8a2V5PmFTdHJpbmc8L2tleT4KCTxzdHJpbmc+ RG9vZGFoPC9zdHJpbmc+Cgk8a2V5PmFuRW1wdHlEaWN0PC9rZXk+Cgk8ZGlj dC8+Cgk8a2V5PmFuRW1wdHlMaXN0PC9rZXk+Cgk8YXJyYXkvPgoJPGtleT5h bkludDwva2V5PgoJPGludGVnZXI+NzI4PC9pbnRlZ2VyPgoJPGtleT5uZXN0 ZWREYXRhPC9rZXk+Cgk8YXJyYXk+CgkJPGRhdGE+CgkJUEd4dmRITWdiMlln WW1sdVlYSjVJR2QxYm1zK0FBRUNBenhzYjNSeklHOW1JR0pwYm1GeWVTQm5k VzVyCgkJUGdBQkFnTThiRzkwY3lCdlppQmlhVzVoY25rZ1ozVnVhejRBQVFJ RFBHeHZkSE1nYjJZZ1ltbHVZWEo1CgkJSUdkMWJtcytBQUVDQXp4c2IzUnpJ RzltSUdKcGJtRnllU0JuZFc1clBnQUJBZ004Ykc5MGN5QnZaaUJpCgkJYVc1 aGNua2daM1Z1YXo0QUFRSURQR3h2ZEhNZ2IyWWdZbWx1WVhKNUlHZDFibXMr QUFFQ0F6eHNiM1J6CgkJSUc5bUlHSnBibUZ5ZVNCbmRXNXJQZ0FCQWdNOGJH OTBjeUJ2WmlCaWFXNWhjbmtnWjNWdWF6NEFBUUlECgkJUEd4dmRITWdiMlln WW1sdVlYSjVJR2QxYm1zK0FBRUNBdz09CgkJPC9kYXRhPgoJPC9hcnJheT4K CTxrZXk+c29tZURhdGE8L2tleT4KCTxkYXRhPgoJUEdKcGJtRnllU0JuZFc1 clBnPT0KCTwvZGF0YT4KCTxrZXk+c29tZU1vcmVEYXRhPC9rZXk+Cgk8ZGF0 YT4KCVBHeHZkSE1nYjJZZ1ltbHVZWEo1SUdkMWJtcytBQUVDQXp4c2IzUnpJ RzltSUdKcGJtRnllU0JuZFc1clBnQUJBZ004CgliRzkwY3lCdlppQmlhVzVo Y25rZ1ozVnVhejRBQVFJRFBHeHZkSE1nYjJZZ1ltbHVZWEo1SUdkMWJtcytB QUVDQXp4cwoJYjNSeklHOW1JR0pwYm1GeWVTQm5kVzVyUGdBQkFnTThiRzkw Y3lCdlppQmlhVzVoY25rZ1ozVnVhejRBQVFJRFBHeHYKCWRITWdiMllnWW1s dVlYSjVJR2QxYm1zK0FBRUNBenhzYjNSeklHOW1JR0pwYm1GeWVTQm5kVzVy UGdBQkFnTThiRzkwCgljeUJ2WmlCaWFXNWhjbmtnWjNWdWF6NEFBUUlEUEd4 dmRITWdiMllnWW1sdVlYSjVJR2QxYm1zK0FBRUNBdz09Cgk8L2RhdGE+Cgk8 a2V5PsOFYmVucmFhPC9rZXk+Cgk8c3RyaW5nPlRoYXQgd2FzIGEgdW5pY29k ZSBrZXkuPC9zdHJpbmc+CjwvZGljdD4KPC9wbGlzdD4K'''), plistlib.FMT_BINARY: binascii.a2b_base64(b''' YnBsaXN0MDDfEBABAgMEBQYHCAkKCwwNDg8QERITFCgpLzAxMjM0NTc2OFdh QmlnSW50WGFCaWdJbnQyVWFEYXRlVWFEaWN0VmFGbG9hdFVhTGlzdF8QD2FO ZWdhdGl2ZUJpZ0ludFxhTmVnYXRpdmVJbnRXYVN0cmluZ1thbkVtcHR5RGlj dFthbkVtcHR5TGlzdFVhbkludFpuZXN0ZWREYXRhWHNvbWVEYXRhXHNvbWVN b3JlRGF0YWcAxQBiAGUAbgByAGEAYRN/////////1BQAAAAAAAAAAIAAAAAA AAAsM0GcuX30AAAA1RUWFxgZGhscHR5bYUZhbHNlVmFsdWVaYVRydWVWYWx1 ZV1hVW5pY29kZVZhbHVlXWFub3RoZXJTdHJpbmdaZGVlcGVyRGljdAgJawBN AOQAcwBzAGkAZwAsACAATQBhAN9fEBU8aGVsbG8gJiAnaGknIHRoZXJlIT7T HyAhIiMkUWFRYlFjEBEjQEBAAAAAAACjJSYnEAEQAlR0ZXh0Iz/gAAAAAAAA pSorLCMtUUFRQhAMoyUmLhADE////+1foOAAE//////////7VkRvb2RhaNCg EQLYoTZPEPo8bG90cyBvZiBiaW5hcnkgZ3Vuaz4AAQIDPGxvdHMgb2YgYmlu YXJ5IGd1bms+AAECAzxsb3RzIG9mIGJpbmFyeSBndW5rPgABAgM8bG90cyBv ZiBiaW5hcnkgZ3Vuaz4AAQIDPGxvdHMgb2YgYmluYXJ5IGd1bms+AAECAzxs b3RzIG9mIGJpbmFyeSBndW5rPgABAgM8bG90cyBvZiBiaW5hcnkgZ3Vuaz4A AQIDPGxvdHMgb2YgYmluYXJ5IGd1bms+AAECAzxsb3RzIG9mIGJpbmFyeSBn dW5rPgABAgM8bG90cyBvZiBiaW5hcnkgZ3Vuaz4AAQIDTTxiaW5hcnkgZ3Vu az5fEBdUaGF0IHdhcyBhIHVuaWNvZGUga2V5LgAIACsAMwA8AEIASABPAFUA ZwB0AHwAiACUAJoApQCuALsAygDTAOQA7QD4AQQBDwEdASsBNgE3ATgBTwFn AW4BcAFyAXQBdgF/AYMBhQGHAYwBlQGbAZ0BnwGhAaUBpwGwAbkBwAHBAcIB xQHHAsQC0gAAAAAAAAIBAAAAAAAAADkAAAAAAAAAAAAAAAAAAALs'''), } class TestPlistlib(unittest.TestCase): def tearDown(self): try: os.unlink(support.TESTFN) except: pass def _create(self, fmt=None): pl = dict( aString="Doodah", aList=["A", "B", 12, 32.5, [1, 2, 3]], aFloat = 0.5, anInt = 728, aBigInt = 2 ** 63 - 44, aBigInt2 = 2 ** 63 + 44, aNegativeInt = -5, aNegativeBigInt = -80000000000, aDict=dict( anotherString="<hello & 'hi' there!>", aUnicodeValue='M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, deeperDict=dict(a=17, b=32.5, c=[1, 2, "text"]), ), someData = b"<binary gunk>", someMoreData = b"<lots of binary gunk>\0\1\2\3" * 10, nestedData = [b"<lots of binary gunk>\0\1\2\3" * 10], aDate = datetime.datetime(2004, 10, 26, 10, 33, 33), anEmptyDict = dict(), anEmptyList = list() ) pl['\xc5benraa'] = "That was a unicode key." return pl def test_create(self): pl = self._create() self.assertEqual(pl["aString"], "Doodah") self.assertEqual(pl["aDict"]["aFalseValue"], False) def test_io(self): pl = self._create() with open(support.TESTFN, 'wb') as fp: plistlib.dump(pl, fp) with open(support.TESTFN, 'rb') as fp: pl2 = plistlib.load(fp) self.assertEqual(dict(pl), dict(pl2)) self.assertRaises(AttributeError, plistlib.dump, pl, 'filename') self.assertRaises(AttributeError, plistlib.load, 'filename') def test_invalid_type(self): pl = [ object() ] for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): self.assertRaises(TypeError, plistlib.dumps, pl, fmt=fmt) def test_int(self): for pl in [0, 2**8-1, 2**8, 2**16-1, 2**16, 2**32-1, 2**32, 2**63-1, 2**64-1, 1, -2**63]: for fmt in ALL_FORMATS: with self.subTest(pl=pl, fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertIsInstance(pl2, int) self.assertEqual(pl, pl2) data2 = plistlib.dumps(pl2, fmt=fmt) self.assertEqual(data, data2) for fmt in ALL_FORMATS: for pl in (2 ** 64 + 1, 2 ** 127-1, -2**64, -2 ** 127): with self.subTest(pl=pl, fmt=fmt): self.assertRaises(OverflowError, plistlib.dumps, pl, fmt=fmt) def test_bytearray(self): for pl in (b'<binary gunk>', b"<lots of binary gunk>\0\1\2\3" * 10): for fmt in ALL_FORMATS: with self.subTest(pl=pl, fmt=fmt): data = plistlib.dumps(bytearray(pl), fmt=fmt) pl2 = plistlib.loads(data) self.assertIsInstance(pl2, bytes) self.assertEqual(pl2, pl) data2 = plistlib.dumps(pl2, fmt=fmt) self.assertEqual(data, data2) def test_bytes(self): pl = self._create() data = plistlib.dumps(pl) pl2 = plistlib.loads(data) self.assertEqual(dict(pl), dict(pl2)) data2 = plistlib.dumps(pl2) self.assertEqual(data, data2) def test_indentation_array(self): data = [[[[[[[[{'test': b'aaaaaa'}]]]]]]]] self.assertEqual(plistlib.loads(plistlib.dumps(data)), data) def test_indentation_dict(self): data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': b'aaaaaa'}}}}}}}}} self.assertEqual(plistlib.loads(plistlib.dumps(data)), data) def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': b'aaaaaa'}]]]]]}]}} self.assertEqual(plistlib.loads(plistlib.dumps(data)), data) def test_appleformatting(self): for use_builtin_types in (True, False): for fmt in ALL_FORMATS: with self.subTest(fmt=fmt, use_builtin_types=use_builtin_types): pl = plistlib.loads(TESTDATA[fmt], use_builtin_types=use_builtin_types) data = plistlib.dumps(pl, fmt=fmt) self.assertEqual(data, TESTDATA[fmt], "generated data was not identical to Apple's output") def test_appleformattingfromliteral(self): self.maxDiff = None for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): pl = self._create(fmt=fmt) pl2 = plistlib.loads(TESTDATA[fmt], fmt=fmt) self.assertEqual(dict(pl), dict(pl2), "generated data was not identical to Apple's output") pl2 = plistlib.loads(TESTDATA[fmt]) self.assertEqual(dict(pl), dict(pl2), "generated data was not identical to Apple's output") def test_bytesio(self): for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): b = BytesIO() pl = self._create(fmt=fmt) plistlib.dump(pl, b, fmt=fmt) pl2 = plistlib.load(BytesIO(b.getvalue()), fmt=fmt) self.assertEqual(dict(pl), dict(pl2)) pl2 = plistlib.load(BytesIO(b.getvalue())) self.assertEqual(dict(pl), dict(pl2)) def test_keysort_bytesio(self): pl = collections.OrderedDict() pl['b'] = 1 pl['a'] = 2 pl['c'] = 3 for fmt in ALL_FORMATS: for sort_keys in (False, True): with self.subTest(fmt=fmt, sort_keys=sort_keys): b = BytesIO() plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys) pl2 = plistlib.load(BytesIO(b.getvalue()), dict_type=collections.OrderedDict) self.assertEqual(dict(pl), dict(pl2)) if sort_keys: self.assertEqual(list(pl2.keys()), ['a', 'b', 'c']) else: self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) def test_keysort(self): pl = collections.OrderedDict() pl['b'] = 1 pl['a'] = 2 pl['c'] = 3 for fmt in ALL_FORMATS: for sort_keys in (False, True): with self.subTest(fmt=fmt, sort_keys=sort_keys): data = plistlib.dumps(pl, fmt=fmt, sort_keys=sort_keys) pl2 = plistlib.loads(data, dict_type=collections.OrderedDict) self.assertEqual(dict(pl), dict(pl2)) if sort_keys: self.assertEqual(list(pl2.keys()), ['a', 'b', 'c']) else: self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) def test_keys_no_string(self): pl = { 42: 'aNumber' } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): self.assertRaises(TypeError, plistlib.dumps, pl, fmt=fmt) b = BytesIO() self.assertRaises(TypeError, plistlib.dump, pl, b, fmt=fmt) def test_skipkeys(self): pl = { 42: 'aNumber', 'snake': 'aWord', } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps( pl, fmt=fmt, skipkeys=True, sort_keys=False) pl2 = plistlib.loads(data) self.assertEqual(pl2, {'snake': 'aWord'}) fp = BytesIO() plistlib.dump( pl, fp, fmt=fmt, skipkeys=True, sort_keys=False) data = fp.getvalue() pl2 = plistlib.loads(fp.getvalue()) self.assertEqual(pl2, {'snake': 'aWord'}) def test_tuple_members(self): pl = { 'first': (1, 2), 'second': (1, 2), 'third': (3, 4), } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertEqual(pl2, { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], }) if fmt != plistlib.FMT_BINARY: self.assertIsNot(pl2['first'], pl2['second']) def test_list_members(self): pl = { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertEqual(pl2, { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], }) self.assertIsNot(pl2['first'], pl2['second']) def test_dict_members(self): pl = { 'first': {'a': 1}, 'second': {'a': 1}, 'third': {'b': 2 }, } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertEqual(pl2, { 'first': {'a': 1}, 'second': {'a': 1}, 'third': {'b': 2 }, }) self.assertIsNot(pl2['first'], pl2['second']) def test_controlcharacters(self): for i in range(128): c = chr(i) testString = "string containing %s" % c if i >= 32 or c in "\r\n\t": # \r, \n and \t are the only legal control chars in XML data = plistlib.dumps(testString, fmt=plistlib.FMT_XML) if c != "\r": self.assertEqual(plistlib.loads(data), testString) else: with self.assertRaises(ValueError): plistlib.dumps(testString, fmt=plistlib.FMT_XML) plistlib.dumps(testString, fmt=plistlib.FMT_BINARY) def test_non_bmp_characters(self): pl = {'python': '\U0001f40d'} for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) self.assertEqual(plistlib.loads(data), pl) def test_lone_surrogates(self): for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): with self.assertRaises(UnicodeEncodeError): plistlib.dumps('\ud8ff', fmt=fmt) with self.assertRaises(UnicodeEncodeError): plistlib.dumps('\udcff', fmt=fmt) def test_nondictroot(self): for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.loads(plistlib.dumps(test1, fmt=fmt)) result2 = plistlib.loads(plistlib.dumps(test2, fmt=fmt)) self.assertEqual(test1, result1) self.assertEqual(test2, result2) def test_invalidarray(self): for i in ["<key>key inside an array</key>", "<key>key inside an array2</key><real>3</real>", "<true/><key>key inside an array3</key>"]: self.assertRaises(ValueError, plistlib.loads, ("<plist><array>%s</array></plist>"%i).encode()) def test_invaliddict(self): for i in ["<key><true/>k</key><string>compound key</string>", "<key>single key</key>", "<string>missing key</string>", "<key>k1</key><string>v1</string><real>5.3</real>" "<key>k1</key><key>k2</key><string>double key</string>"]: self.assertRaises(ValueError, plistlib.loads, ("<plist><dict>%s</dict></plist>"%i).encode()) self.assertRaises(ValueError, plistlib.loads, ("<plist><array><dict>%s</dict></array></plist>"%i).encode()) def test_invalidinteger(self): self.assertRaises(ValueError, plistlib.loads, b"<plist><integer>not integer</integer></plist>") def test_invalidreal(self): self.assertRaises(ValueError, plistlib.loads, b"<plist><integer>not real</integer></plist>") def test_xml_encodings(self): base = TESTDATA[plistlib.FMT_XML] for xml_encoding, encoding, bom in [ (b'utf-8', 'utf-8', codecs.BOM_UTF8), (b'utf-16', 'utf-16-le', codecs.BOM_UTF16_LE), (b'utf-16', 'utf-16-be', codecs.BOM_UTF16_BE), # Expat does not support UTF-32 #(b'utf-32', 'utf-32-le', codecs.BOM_UTF32_LE), #(b'utf-32', 'utf-32-be', codecs.BOM_UTF32_BE), ]: pl = self._create(fmt=plistlib.FMT_XML) with self.subTest(encoding=encoding): data = base.replace(b'UTF-8', xml_encoding) data = bom + data.decode('utf-8').encode(encoding) pl2 = plistlib.loads(data) self.assertEqual(dict(pl), dict(pl2)) class TestBinaryPlistlib(unittest.TestCase): def test_nonstandard_refs_size(self): # Issue #21538: Refs and offsets are 24-bit integers data = (b'bplist00' b'\xd1\x00\x00\x01\x00\x00\x02QaQb' b'\x00\x00\x08\x00\x00\x0f\x00\x00\x11' b'\x00\x00\x00\x00\x00\x00' b'\x03\x03' b'\x00\x00\x00\x00\x00\x00\x00\x03' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x13') self.assertEqual(plistlib.loads(data), {'a': 'b'}) def test_dump_duplicates(self): # Test effectiveness of saving duplicated objects for x in (None, False, True, 12345, 123.45, 'abcde', b'abcde', datetime.datetime(2004, 10, 26, 10, 33, 33), plistlib.Data(b'abcde'), bytearray(b'abcde'), [12, 345], (12, 345), {'12': 345}): with self.subTest(x=x): data = plistlib.dumps([x]*1000, fmt=plistlib.FMT_BINARY) self.assertLess(len(data), 1100, repr(data)) def test_identity(self): for x in (None, False, True, 12345, 123.45, 'abcde', b'abcde', datetime.datetime(2004, 10, 26, 10, 33, 33), plistlib.Data(b'abcde'), bytearray(b'abcde'), [12, 345], (12, 345), {'12': 345}): with self.subTest(x=x): data = plistlib.dumps([x]*2, fmt=plistlib.FMT_BINARY) a, b = plistlib.loads(data) if isinstance(x, tuple): x = list(x) self.assertEqual(a, x) self.assertEqual(b, x) self.assertIs(a, b) def test_cycles(self): # recursive list a = [] a.append(a) b = plistlib.loads(plistlib.dumps(a, fmt=plistlib.FMT_BINARY)) self.assertIs(b[0], b) # recursive tuple a = ([],) a[0].append(a) b = plistlib.loads(plistlib.dumps(a, fmt=plistlib.FMT_BINARY)) self.assertIs(b[0][0], b) # recursive dict a = {} a['x'] = a b = plistlib.loads(plistlib.dumps(a, fmt=plistlib.FMT_BINARY)) self.assertIs(b['x'], b) def test_large_timestamp(self): # Issue #26709: 32-bit timestamp out of range for ts in -2**31-1, 2**31: with self.subTest(ts=ts): d = (datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(seconds=ts)) data = plistlib.dumps(d, fmt=plistlib.FMT_BINARY) self.assertEqual(plistlib.loads(data), d) def test_invalid_binary(self): for data in [ # too short data b'', # too large offset_table_offset and nonstandard offset_size b'\x00\x08' b'\x00\x00\x00\x00\x00\x00\x03\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x2a', # integer overflow in offset_table_offset b'\x00\x08' b'\x00\x00\x00\x00\x00\x00\x01\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\xff\xff\xff\xff\xff\xff\xff\xff', # offset_size = 0 b'\x00\x08' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x09', # ref_size = 0 b'\xa1\x01\x00\x08\x0a' b'\x00\x00\x00\x00\x00\x00\x01\x00' b'\x00\x00\x00\x00\x00\x00\x00\x02' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x0b', # integer overflow in offset b'\x00\xff\xff\xff\xff\xff\xff\xff\xff' b'\x00\x00\x00\x00\x00\x00\x08\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x09', # invalid ASCII b'\x51\xff\x08' b'\x00\x00\x00\x00\x00\x00\x01\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x0a', # invalid UTF-16 b'\x61\xd8\x00\x08' b'\x00\x00\x00\x00\x00\x00\x01\x01' b'\x00\x00\x00\x00\x00\x00\x00\x01' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x0b', ]: with self.assertRaises(plistlib.InvalidFileException): plistlib.loads(b'bplist00' + data, fmt=plistlib.FMT_BINARY) class TestPlistlibDeprecated(unittest.TestCase): def test_io_deprecated(self): pl_in = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer', } } pl_out = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': plistlib.Data(b'buffer'), } } self.addCleanup(support.unlink, support.TESTFN) with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, support.TESTFN) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(support.TESTFN) self.assertEqual(pl_out, pl2) os.unlink(support.TESTFN) with open(support.TESTFN, 'wb') as fp: with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, fp) with open(support.TESTFN, 'rb') as fp: with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(fp) self.assertEqual(pl_out, pl2) def test_bytes_deprecated(self): pl = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer', } } with self.assertWarns(DeprecationWarning): data = plistlib.writePlistToBytes(pl) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlistFromBytes(data) self.assertIsInstance(pl2, dict) self.assertEqual(pl2, dict( key=42, sub=dict( key=9, alt='value', data=plistlib.Data(b'buffer'), ) )) with self.assertWarns(DeprecationWarning): data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2) def test_dataobject_deprecated(self): in_data = { 'key': plistlib.Data(b'hello') } out_data = { 'key': b'hello' } buf = plistlib.dumps(in_data) cur = plistlib.loads(buf) self.assertEqual(cur, out_data) self.assertEqual(cur, in_data) cur = plistlib.loads(buf, use_builtin_types=False) self.assertEqual(cur, out_data) self.assertEqual(cur, in_data) with self.assertWarns(DeprecationWarning): cur = plistlib.readPlistFromBytes(buf) self.assertEqual(cur, out_data) self.assertEqual(cur, in_data) class MiscTestCase(unittest.TestCase): def test__all__(self): blacklist = {"PlistFormat", "PLISTHEADER"} support.check__all__(self, plistlib, blacklist=blacklist) def test_main(): support.run_unittest(TestPlistlib, TestPlistlibDeprecated, MiscTestCase) 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_pipes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pipes.py
import pipes import os import string import unittest import shutil from test.support import TESTFN, run_unittest, unlink, reap_children if os.name != 'posix': raise unittest.SkipTest('pipes module only works on posix') TESTFN2 = TESTFN + "2" # tr a-z A-Z is not portable, so make the ranges explicit s_command = 'tr %s %s' % (string.ascii_lowercase, string.ascii_uppercase) class SimplePipeTests(unittest.TestCase): def tearDown(self): for f in (TESTFN, TESTFN2): unlink(f) def testSimplePipe1(self): if shutil.which('tr') is None: self.skipTest('tr is not available') t = pipes.Template() t.append(s_command, pipes.STDIN_STDOUT) f = t.open(TESTFN, 'w') f.write('hello world #1') f.close() with open(TESTFN) as f: self.assertEqual(f.read(), 'HELLO WORLD #1') def testSimplePipe2(self): if shutil.which('tr') is None: self.skipTest('tr is not available') with open(TESTFN, 'w') as f: f.write('hello world #2') t = pipes.Template() t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT) t.copy(TESTFN, TESTFN2) with open(TESTFN2) as f: self.assertEqual(f.read(), 'HELLO WORLD #2') def testSimplePipe3(self): if shutil.which('tr') is None: self.skipTest('tr is not available') with open(TESTFN, 'w') as f: f.write('hello world #2') t = pipes.Template() t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT) f = t.open(TESTFN, 'r') try: self.assertEqual(f.read(), 'HELLO WORLD #2') finally: f.close() def testEmptyPipeline1(self): # copy through empty pipe d = 'empty pipeline test COPY' with open(TESTFN, 'w') as f: f.write(d) with open(TESTFN2, 'w') as f: f.write('') t=pipes.Template() t.copy(TESTFN, TESTFN2) with open(TESTFN2) as f: self.assertEqual(f.read(), d) def testEmptyPipeline2(self): # read through empty pipe d = 'empty pipeline test READ' with open(TESTFN, 'w') as f: f.write(d) t=pipes.Template() f = t.open(TESTFN, 'r') try: self.assertEqual(f.read(), d) finally: f.close() def testEmptyPipeline3(self): # write through empty pipe d = 'empty pipeline test WRITE' t = pipes.Template() with t.open(TESTFN, 'w') as f: f.write(d) with open(TESTFN) as f: self.assertEqual(f.read(), d) def testRepr(self): t = pipes.Template() self.assertEqual(repr(t), "<Template instance, steps=[]>") t.append('tr a-z A-Z', pipes.STDIN_STDOUT) self.assertEqual(repr(t), "<Template instance, steps=[('tr a-z A-Z', '--')]>") def testSetDebug(self): t = pipes.Template() t.debug(False) self.assertEqual(t.debugging, False) t.debug(True) self.assertEqual(t.debugging, True) def testReadOpenSink(self): # check calling open('r') on a pipe ending with # a sink raises ValueError t = pipes.Template() t.append('boguscmd', pipes.SINK) self.assertRaises(ValueError, t.open, 'bogusfile', 'r') def testWriteOpenSource(self): # check calling open('w') on a pipe ending with # a source raises ValueError t = pipes.Template() t.prepend('boguscmd', pipes.SOURCE) self.assertRaises(ValueError, t.open, 'bogusfile', 'w') def testBadAppendOptions(self): t = pipes.Template() # try a non-string command self.assertRaises(TypeError, t.append, 7, pipes.STDIN_STDOUT) # try a type that isn't recognized self.assertRaises(ValueError, t.append, 'boguscmd', 'xx') # shouldn't be able to append a source self.assertRaises(ValueError, t.append, 'boguscmd', pipes.SOURCE) # check appending two sinks t = pipes.Template() t.append('boguscmd', pipes.SINK) self.assertRaises(ValueError, t.append, 'boguscmd', pipes.SINK) # command needing file input but with no $IN t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd $OUT', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd', pipes.FILEIN_STDOUT) # command needing file output but with no $OUT t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd $IN', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.append, 'boguscmd', pipes.STDIN_FILEOUT) def testBadPrependOptions(self): t = pipes.Template() # try a non-string command self.assertRaises(TypeError, t.prepend, 7, pipes.STDIN_STDOUT) # try a type that isn't recognized self.assertRaises(ValueError, t.prepend, 'tr a-z A-Z', 'xx') # shouldn't be able to prepend a sink self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.SINK) # check prepending two sources t = pipes.Template() t.prepend('boguscmd', pipes.SOURCE) self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.SOURCE) # command needing file input but with no $IN t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd $OUT', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.FILEIN_STDOUT) # command needing file output but with no $OUT t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd $IN', pipes.FILEIN_FILEOUT) t = pipes.Template() self.assertRaises(ValueError, t.prepend, 'boguscmd', pipes.STDIN_FILEOUT) def testBadOpenMode(self): t = pipes.Template() self.assertRaises(ValueError, t.open, 'bogusfile', 'x') def testClone(self): t = pipes.Template() t.append('tr a-z A-Z', pipes.STDIN_STDOUT) u = t.clone() self.assertNotEqual(id(t), id(u)) self.assertEqual(t.steps, u.steps) self.assertNotEqual(id(t.steps), id(u.steps)) self.assertEqual(t.debugging, u.debugging) def test_main(): run_unittest(SimplePipeTests) 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_random.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_random.py
import unittest import unittest.mock import random import os import time import pickle import warnings from functools import partial from math import log, exp, pi, fsum, sin, factorial from test import support from fractions import Fraction class TestBasicOps: # Superclass with tests common to all generators. # Subclasses must arrange for self.gen to retrieve the Random instance # to be tested. def randomlist(self, n): """Helper function to make a list of random numbers""" return [self.gen.random() for i in range(n)] def test_autoseed(self): self.gen.seed() state1 = self.gen.getstate() time.sleep(0.1) self.gen.seed() # different seeds at different times state2 = self.gen.getstate() self.assertNotEqual(state1, state2) def test_saverestore(self): N = 1000 self.gen.seed() state = self.gen.getstate() randseq = self.randomlist(N) self.gen.setstate(state) # should regenerate the same sequence self.assertEqual(randseq, self.randomlist(N)) def test_seedargs(self): # Seed value with a negative hash. class MySeed(object): def __hash__(self): return -1729 for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20), 3.14, 1+2j, 'a', tuple('abc'), MySeed()]: self.gen.seed(arg) for arg in [list(range(3)), dict(one=1)]: self.assertRaises(TypeError, self.gen.seed, arg) self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4) self.assertRaises(TypeError, type(self.gen), []) @unittest.mock.patch('random._urandom') # os.urandom def test_seed_when_randomness_source_not_found(self, urandom_mock): # Random.seed() uses time.time() when an operating system specific # randomness source is not found. To test this on machines where it # exists, run the above test, test_seedargs(), again after mocking # os.urandom() so that it raises the exception expected when the # randomness source is not available. urandom_mock.side_effect = NotImplementedError self.test_seedargs() def test_shuffle(self): shuffle = self.gen.shuffle lst = [] shuffle(lst) self.assertEqual(lst, []) lst = [37] shuffle(lst) self.assertEqual(lst, [37]) seqs = [list(range(n)) for n in range(10)] shuffled_seqs = [list(range(n)) for n in range(10)] for shuffled_seq in shuffled_seqs: shuffle(shuffled_seq) for (seq, shuffled_seq) in zip(seqs, shuffled_seqs): self.assertEqual(len(seq), len(shuffled_seq)) self.assertEqual(set(seq), set(shuffled_seq)) # The above tests all would pass if the shuffle was a # no-op. The following non-deterministic test covers that. It # asserts that the shuffled sequence of 1000 distinct elements # must be different from the original one. Although there is # mathematically a non-zero probability that this could # actually happen in a genuinely random shuffle, it is # completely negligible, given that the number of possible # permutations of 1000 objects is 1000! (factorial of 1000), # which is considerably larger than the number of atoms in the # universe... lst = list(range(1000)) shuffled_lst = list(range(1000)) shuffle(shuffled_lst) self.assertTrue(lst != shuffled_lst) shuffle(lst) self.assertTrue(lst != shuffled_lst) self.assertRaises(TypeError, shuffle, (1, 2, 3)) def test_shuffle_random_argument(self): # Test random argument to shuffle. shuffle = self.gen.shuffle mock_random = unittest.mock.Mock(return_value=0.5) seq = bytearray(b'abcdefghijk') shuffle(seq, mock_random) mock_random.assert_called_with() def test_choice(self): choice = self.gen.choice with self.assertRaises(IndexError): choice([]) self.assertEqual(choice([50]), 50) self.assertIn(choice([25, 75]), [25, 75]) def test_sample(self): # For the entire allowable range of 0 <= k <= N, validate that # the sample is of the correct length and contains only unique items N = 100 population = range(N) for k in range(N+1): s = self.gen.sample(population, k) self.assertEqual(len(s), k) uniq = set(s) self.assertEqual(len(uniq), k) self.assertTrue(uniq <= set(population)) self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 # Exception raised if size of sample exceeds that of population self.assertRaises(ValueError, self.gen.sample, population, N+1) self.assertRaises(ValueError, self.gen.sample, [], -1) def test_sample_distribution(self): # For the entire allowable range of 0 <= k <= N, validate that # sample generates all possible permutations n = 5 pop = range(n) trials = 10000 # large num prevents false negatives without slowing normal case for k in range(n): expected = factorial(n) // factorial(n-k) perms = {} for i in range(trials): perms[tuple(self.gen.sample(pop, k))] = None if len(perms) == expected: break else: self.fail() def test_sample_inputs(self): # SF bug #801342 -- population can be any iterable defining __len__() self.gen.sample(set(range(20)), 2) self.gen.sample(range(20), 2) self.gen.sample(range(20), 2) self.gen.sample(str('abcdefghijklmnopqrst'), 2) self.gen.sample(tuple('abcdefghijklmnopqrst'), 2) def test_sample_on_dicts(self): self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2) def test_choices(self): choices = self.gen.choices data = ['red', 'green', 'blue', 'yellow'] str_data = 'abcd' range_data = range(4) set_data = set(range(4)) # basic functionality for sample in [ choices(data, k=5), choices(data, range(4), k=5), choices(k=5, population=data, weights=range(4)), choices(k=5, population=data, cum_weights=range(4)), ]: self.assertEqual(len(sample), 5) self.assertEqual(type(sample), list) self.assertTrue(set(sample) <= set(data)) # test argument handling with self.assertRaises(TypeError): # missing arguments choices(2) self.assertEqual(choices(data, k=0), []) # k == 0 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1`` with self.assertRaises(TypeError): choices(data, k=2.5) # k is a float self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range with self.assertRaises(TypeError): choices(set_data, k=2) # population is not a sequence self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data)) with self.assertRaises(ValueError): choices(data, [1,2], k=5) # len(weights) != len(population) with self.assertRaises(TypeError): choices(data, 10, k=5) # non-iterable weights with self.assertRaises(TypeError): choices(data, [None]*4, k=5) # non-numeric weights for weights in [ [15, 10, 25, 30], # integer weights [15.1, 10.2, 25.2, 30.3], # float weights [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights [True, False, True, False] # booleans (include / exclude) ]: self.assertTrue(set(choices(data, weights, k=5)) <= set(data)) with self.assertRaises(ValueError): choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population) with self.assertRaises(TypeError): choices(data, cum_weights=10, k=5) # non-iterable cum_weights with self.assertRaises(TypeError): choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights with self.assertRaises(TypeError): choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights for weights in [ [15, 10, 25, 30], # integer cum_weights [15.1, 10.2, 25.2, 30.3], # float cum_weights [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights ]: self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data)) # Test weight focused on a single element of the population self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a']) self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b']) self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c']) self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d']) # Test consistency with random.choice() for empty population with self.assertRaises(IndexError): choices([], k=1) with self.assertRaises(IndexError): choices([], weights=[], k=1) with self.assertRaises(IndexError): choices([], cum_weights=[], k=5) def test_choices_subnormal(self): # Subnormal weights would occasionally trigger an IndexError # in choices() when the value returned by random() was large # enough to make `random() * total` round up to the total. # See https://bugs.python.org/msg275594 for more detail. choices = self.gen.choices choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000) def test_gauss(self): # Ensure that the seed() method initializes all the hidden state. In # particular, through 2.2.1 it failed to reset a piece of state used # by (and only by) the .gauss() method. for seed in 1, 12, 123, 1234, 12345, 123456, 654321: self.gen.seed(seed) x1 = self.gen.random() y1 = self.gen.gauss(0, 1) self.gen.seed(seed) x2 = self.gen.random() y2 = self.gen.gauss(0, 1) self.assertEqual(x1, x2) self.assertEqual(y1, y2) def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): state = pickle.dumps(self.gen, proto) origseq = [self.gen.random() for i in range(10)] newgen = pickle.loads(state) restoredseq = [newgen.random() for i in range(10)] self.assertEqual(origseq, restoredseq) def test_bug_1727780(self): # verify that version-2-pickles can be loaded # fine, whether they are created on 32-bit or 64-bit # platforms, and that version-3-pickles load fine. files = [("randv2_32.pck", 780), ("randv2_64.pck", 866), ("randv3.pck", 343)] for file, value in files: f = open(support.findfile(file),"rb") r = pickle.load(f) f.close() self.assertEqual(int(r.random()*1000), value) def test_bug_9025(self): # Had problem with an uneven distribution in int(n*random()) # Verify the fix by checking that distributions fall within expectations. n = 100000 randrange = self.gen.randrange k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n)) self.assertTrue(0.30 < k/n < .37, (k/n)) try: random.SystemRandom().random() except NotImplementedError: SystemRandom_available = False else: SystemRandom_available = True @unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available") class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase): gen = random.SystemRandom() def test_autoseed(self): # Doesn't need to do anything except not fail self.gen.seed() def test_saverestore(self): self.assertRaises(NotImplementedError, self.gen.getstate) self.assertRaises(NotImplementedError, self.gen.setstate, None) def test_seedargs(self): # Doesn't need to do anything except not fail self.gen.seed(100) def test_gauss(self): self.gen.gauss_next = None self.gen.seed(100) self.assertEqual(self.gen.gauss_next, None) def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto) def test_53_bits_per_float(self): # This should pass whenever a C double has 53 bit precision. span = 2 ** 53 cum = 0 for i in range(100): cum |= int(self.gen.random() * span) self.assertEqual(cum, span-1) def test_bigrand(self): # The randrange routine should build-up the required number of bits # in stages so that all bit positions are active. span = 2 ** 500 cum = 0 for i in range(100): r = self.gen.randrange(span) self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) def test_bigrand_ranges(self): for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: start = self.gen.randrange(2 ** (i-2)) stop = self.gen.randrange(2 ** i) if stop <= start: continue self.assertTrue(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: self.assertEqual(set(range(start,stop)), set([self.gen.randrange(start,stop) for i in range(100)])) def test_randrange_nonunit_step(self): rint = self.gen.randrange(0, 10, 2) self.assertIn(rint, (0, 2, 4, 6, 8)) rint = self.gen.randrange(0, 2, 2) self.assertEqual(rint, 0) def test_randrange_errors(self): raises = partial(self.assertRaises, ValueError, self.gen.randrange) # Empty range raises(3, 3) raises(-721) raises(0, 100, -12) # Non-integer start/stop raises(3.14159) raises(0, 2.71828) # Zero and non-integer step raises(0, 42, 0) raises(0, 42, 3.14159) def test_genrandbits(self): # Verify ranges for k in range(1, 1000): self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in range(100): cum |= getbits(span) self.assertEqual(cum, 2**span-1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1) self.assertRaises(TypeError, self.gen.getrandbits, 10.1) def test_randbelow_logic(self, _log=log, int=int): # check bitcount transition points: 2**i and 2**(i+1)-1 # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in range(1, 1000): n = 1 << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) self.assertEqual(n, 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) self.assertIn(k, [numbits, numbits+1]) self.assertTrue(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase): gen = random.Random() def test_guaranteed_stable(self): # These sequences are guaranteed to stay the same across versions of python self.gen.seed(3456147, version=1) self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1', '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1']) self.gen.seed("the quick brown fox", version=2) self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4', '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1']) def test_bug_27706(self): # Verify that version 1 seeds are unaffected by hash randomization self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5', '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6']) self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3', '0x1.3052b9c072678p-2', '0x1.578f332106574p-3']) self.gen.seed('', version=1) # hash('') == 0 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1', '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2']) def test_bug_31478(self): # There shouldn't be an assertion failure in _random.Random.seed() in # case the argument has a bad __abs__() method. class BadInt(int): def __abs__(self): return None try: self.gen.seed(BadInt()) except TypeError: pass def test_bug_31482(self): # Verify that version 1 seeds are unaffected by hash randomization # when the seeds are expressed as bytes rather than strings. # The hash(b) values listed are the Python2.7 hash() values # which were used for seeding. self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5', '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6']) self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3', '0x1.3052b9c072678p-2', '0x1.578f332106574p-3']) self.gen.seed(b'', version=1) # hash('') == 0 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1', '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2']) b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0' self.gen.seed(b, version=1) # hash(b) == 5015594239749365497 self.assertEqual([self.gen.random().hex() for i in range(4)], ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2', '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2']) def test_setstate_first_arg(self): self.assertRaises(ValueError, self.gen.setstate, (1, None, None)) def test_setstate_middle_arg(self): start_state = self.gen.getstate() # Wrong type, s/b tuple self.assertRaises(TypeError, self.gen.setstate, (2, None, None)) # Wrong length, s/b 625 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None)) # Wrong type, s/b tuple of 625 ints self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) # Last element s/b an int also self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) # Last element s/b between 0 and 624 with self.assertRaises((ValueError, OverflowError)): self.gen.setstate((2, (1,)*624+(625,), None)) with self.assertRaises((ValueError, OverflowError)): self.gen.setstate((2, (1,)*624+(-1,), None)) # Failed calls to setstate() should not have changed the state. bits100 = self.gen.getrandbits(100) self.gen.setstate(start_state) self.assertEqual(self.gen.getrandbits(100), bits100) # Little trick to make "tuple(x % (2**32) for x in internalstate)" # raise ValueError. I cannot think of a simple way to achieve this, so # I am opting for using a generator as the middle argument of setstate # which attempts to cast a NaN to integer. state_values = self.gen.getstate()[1] state_values = list(state_values) state_values[-1] = float('nan') state = (int(x) for x in state_values) self.assertRaises(TypeError, self.gen.setstate, (2, state, None)) def test_referenceImplementation(self): # Compare the python implementation with results from the original # code. Create 2000 53-bit precision random floats. Compare only # the last ten entries to show that the independent implementations # are tracking. Here is the main() function needed to create the # list of expected random numbers: # void main(void){ # int i; # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; # init_by_array(init, length); # for (i=0; i<2000; i++) { # printf("%.15f ", genrand_res53()); # if (i%5==4) printf("\n"); # } # } expected = [0.45839803073713259, 0.86057815201978782, 0.92848331726782152, 0.35932681119782461, 0.081823493762449573, 0.14332226470169329, 0.084297823823520024, 0.53814864671831453, 0.089215024911993401, 0.78486196105372907] self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): self.assertAlmostEqual(a,e,places=14) def test_strong_reference_implementation(self): # Like test_referenceImplementation, but checks for exact bit-level # equality. This should pass on any box where C double contains # at least 53 bits of precision (the underlying algorithm suffers # no rounding errors -- all results are exact). from math import ldexp expected = [0x0eab3258d2231f, 0x1b89db315277a5, 0x1db622a5518016, 0x0b7f9af0d575bf, 0x029e4c4db82240, 0x04961892f5d673, 0x02b291598e4589, 0x11388382c15694, 0x02dad977c9e1fe, 0x191d96d4d334c6] self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): self.assertEqual(int(ldexp(a, 53)), e) def test_long_seed(self): # This is most interesting to run in debug mode, just to make sure # nothing blows up. Under the covers, a dynamically resized array # is allocated, consuming space proportional to the number of bits # in the seed. Unfortunately, that's a quadratic-time algorithm, # so don't make this horribly big. seed = (1 << (10000 * 8)) - 1 # about 10K bytes self.gen.seed(seed) def test_53_bits_per_float(self): # This should pass whenever a C double has 53 bit precision. span = 2 ** 53 cum = 0 for i in range(100): cum |= int(self.gen.random() * span) self.assertEqual(cum, span-1) def test_bigrand(self): # The randrange routine should build-up the required number of bits # in stages so that all bit positions are active. span = 2 ** 500 cum = 0 for i in range(100): r = self.gen.randrange(span) self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) def test_bigrand_ranges(self): for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: start = self.gen.randrange(2 ** (i-2)) stop = self.gen.randrange(2 ** i) if stop <= start: continue self.assertTrue(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: self.assertEqual(set(range(start,stop)), set([self.gen.randrange(start,stop) for i in range(100)])) def test_genrandbits(self): # Verify cross-platform repeatability self.gen.seed(1234567) self.assertEqual(self.gen.getrandbits(100), 97904845777343510404718956115) # Verify ranges for k in range(1, 1000): self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in range(100): cum |= getbits(span) self.assertEqual(cum, 2**span-1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 'a') self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1) def test_randbelow_logic(self, _log=log, int=int): # check bitcount transition points: 2**i and 2**(i+1)-1 # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in range(1, 1000): n = 1 << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) self.assertEqual(n, 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) self.assertIn(k, [numbits, numbits+1]) self.assertTrue(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion @unittest.mock.patch('random.Random.random') def test_randbelow_overridden_random(self, random_mock): # Random._randbelow() can only use random() when the built-in one # has been overridden but no new getrandbits() method was supplied. random_mock.side_effect = random.SystemRandom().random maxsize = 1<<random.BPF with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) # Population range too large (n >= maxsize) self.gen._randbelow(maxsize+1, maxsize = maxsize) self.gen._randbelow(5640, maxsize = maxsize) # issue 33203: test that _randbelow raises ValueError on # n == 0 also in its getrandbits-independent branch. with self.assertRaises(ValueError): self.gen._randbelow(0, maxsize=maxsize) # This might be going too far to test a single line, but because of our # noble aim of achieving 100% test coverage we need to write a case in # which the following line in Random._randbelow() gets executed: # # rem = maxsize % n # limit = (maxsize - rem) / maxsize # r = random() # while r >= limit: # r = random() # <== *This line* <==< # # Therefore, to guarantee that the while loop is executed at least # once, we need to mock random() so that it returns a number greater # than 'limit' the first time it gets called. n = 42 epsilon = 0.01 limit = (maxsize - (maxsize % n)) / maxsize random_mock.side_effect = [limit + epsilon, limit - epsilon] self.gen._randbelow(n, maxsize = maxsize) def test_randrange_bug_1590891(self): start = 1000000000000 stop = -100000000000000000000 step = -200 x = self.gen.randrange(start, stop, step) self.assertTrue(stop < x <= start) self.assertEqual((x+stop)%step, 0) def test_choices_algorithms(self): # The various ways of specifying weights should produce the same results choices = self.gen.choices n = 104729 self.gen.seed(8675309) a = self.gen.choices(range(n), k=10000) self.gen.seed(8675309) b = self.gen.choices(range(n), [1]*n, k=10000) self.assertEqual(a, b) self.gen.seed(8675309) c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000) self.assertEqual(a, c) # American Roulette population = ['Red', 'Black', 'Green'] weights = [18, 18, 2] cum_weights = [18, 36, 38] expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2 self.gen.seed(9035768) a = self.gen.choices(expanded_population, k=10000) self.gen.seed(9035768) b = self.gen.choices(population, weights, k=10000) self.assertEqual(a, b) self.gen.seed(9035768) c = self.gen.choices(population, cum_weights=cum_weights, k=10000) self.assertEqual(a, c) def gamma(z, sqrt2pi=(2.0*pi)**0.5): # Reflection to right half of complex plane if z < 0.5: return pi / sin(pi*z) / gamma(1.0-z) # Lanczos approximation with g=7 az = z + (7.0 - 0.5) return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([ 0.9999999999995183, 676.5203681218835 / z, -1259.139216722289 / (z+1.0), 771.3234287757674 / (z+2.0), -176.6150291498386 / (z+3.0), 12.50734324009056 / (z+4.0), -0.1385710331296526 / (z+5.0), 0.9934937113930748e-05 / (z+6.0), 0.1659470187408462e-06 / (z+7.0), ]) class TestDistributions(unittest.TestCase): def test_zeroinputs(self): # Verify that distributions can handle a series of zero inputs' g = random.Random() x = [g.random() for i in range(50)] + [0.0]*5 g.random = x[:].pop; g.uniform(1,10) g.random = x[:].pop; g.paretovariate(1.0) g.random = x[:].pop; g.expovariate(1.0) g.random = x[:].pop; g.weibullvariate(1.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) g.random = x[:].pop; g.normalvariate(0.0, 1.0) g.random = x[:].pop; g.gauss(0.0, 1.0) g.random = x[:].pop; g.lognormvariate(0.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) g.random = x[:].pop; g.gammavariate(0.01, 1.0) g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) def test_avg_std(self): # Use integration to test distribution average and standard deviation.
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_long.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py
import unittest from test import support import sys import random import math import array # SHIFT should match the value in longintrepr.h for best testing. SHIFT = sys.int_info.bits_per_digit BASE = 2 ** SHIFT MASK = BASE - 1 KARATSUBA_CUTOFF = 70 # from longobject.c # Max number of base BASE digits to use in test cases. Doubling # this will more than double the runtime. MAXDIGITS = 15 # build some special values special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa] # some solid strings of one bits p2 = 4 # 0 and 1 already added for i in range(2*SHIFT): special.append(p2 - 1) p2 = p2 << 1 del p2 # add complements & negations special += [~x for x in special] + [-x for x in special] DBL_MAX = sys.float_info.max DBL_MAX_EXP = sys.float_info.max_exp DBL_MIN_EXP = sys.float_info.min_exp DBL_MANT_DIG = sys.float_info.mant_dig DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1) # Pure Python version of correctly-rounded integer-to-float conversion. def int_to_float(n): """ Correctly-rounded integer-to-float conversion. """ # Constants, depending only on the floating-point format in use. # We use an extra 2 bits of precision for rounding purposes. PRECISION = sys.float_info.mant_dig + 2 SHIFT_MAX = sys.float_info.max_exp - PRECISION Q_MAX = 1 << PRECISION ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1] # Reduce to the case where n is positive. if n == 0: return 0.0 elif n < 0: return -int_to_float(-n) # Convert n to a 'floating-point' number q * 2**shift, where q is an # integer with 'PRECISION' significant bits. When shifting n to create q, # the least significant bit of q is treated as 'sticky'. That is, the # least significant bit of q is set if either the corresponding bit of n # was already set, or any one of the bits of n lost in the shift was set. shift = n.bit_length() - PRECISION q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift)) # Round half to even (actually rounds to the nearest multiple of 4, # rounding ties to a multiple of 8). q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7] # Detect overflow. if shift + (q == Q_MAX) > SHIFT_MAX: raise OverflowError("integer too large to convert to float") # Checks: q is exactly representable, and q**2**shift doesn't overflow. assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig) assert q * 2**shift <= sys.float_info.max # Some circularity here, since float(q) is doing an int-to-float # conversion. But here q is of bounded size, and is exactly representable # as a float. In a low-level C-like language, this operation would be a # simple cast (e.g., from unsigned long long to double). return math.ldexp(float(q), shift) # pure Python version of correctly-rounded true division def truediv(a, b): """Correctly-rounded true division for integers.""" negative = a^b < 0 a, b = abs(a), abs(b) # exceptions: division by zero, overflow if not b: raise ZeroDivisionError("division by zero") if a >= DBL_MIN_OVERFLOW * b: raise OverflowError("int/int too large to represent as a float") # find integer d satisfying 2**(d - 1) <= a/b < 2**d d = a.bit_length() - b.bit_length() if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b: d += 1 # compute 2**-exp * a / b for suitable exp exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG a, b = a << max(-exp, 0), b << max(exp, 0) q, r = divmod(a, b) # round-half-to-even: fractional part is r/b, which is > 0.5 iff # 2*r > b, and == 0.5 iff 2*r == b. if 2*r > b or 2*r == b and q % 2 == 1: q += 1 result = math.ldexp(q, exp) return -result if negative else result class LongTest(unittest.TestCase): # Get quasi-random long consisting of ndigits digits (in base BASE). # quasi == the most-significant digit will not be 0, and the number # is constructed to contain long strings of 0 and 1 bits. These are # more likely than random bits to provoke digit-boundary errors. # The sign of the number is also random. def getran(self, ndigits): self.assertGreater(ndigits, 0) nbits_hi = ndigits * SHIFT nbits_lo = nbits_hi - SHIFT + 1 answer = 0 nbits = 0 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start while nbits < nbits_lo: bits = (r >> 1) + 1 bits = min(bits, nbits_hi - nbits) self.assertTrue(1 <= bits <= SHIFT) nbits = nbits + bits answer = answer << bits if r & 1: answer = answer | ((1 << bits) - 1) r = int(random.random() * (SHIFT * 2)) self.assertTrue(nbits_lo <= nbits <= nbits_hi) if random.random() < 0.5: answer = -answer return answer # Get random long consisting of ndigits random digits (relative to base # BASE). The sign bit is also random. def getran2(ndigits): answer = 0 for i in range(ndigits): answer = (answer << SHIFT) | random.randint(0, MASK) if random.random() < 0.5: answer = -answer return answer def check_division(self, x, y): eq = self.assertEqual with self.subTest(x=x, y=y): q, r = divmod(x, y) q2, r2 = x//y, x%y pab, pba = x*y, y*x eq(pab, pba, "multiplication does not commute") eq(q, q2, "divmod returns different quotient than /") eq(r, r2, "divmod returns different mod than %") eq(x, q*y + r, "x != q*y + r after divmod") if y > 0: self.assertTrue(0 <= r < y, "bad mod from divmod") else: self.assertTrue(y < r <= 0, "bad mod from divmod") def test_division(self): digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 14)) digits.append(KARATSUBA_CUTOFF * 3) for lenx in digits: x = self.getran(lenx) for leny in digits: y = self.getran(leny) or 1 self.check_division(x, y) # specific numbers chosen to exercise corner cases of the # current long division implementation # 30-bit cases involving a quotient digit estimate of BASE+1 self.check_division(1231948412290879395966702881, 1147341367131428698) self.check_division(815427756481275430342312021515587883, 707270836069027745) self.check_division(627976073697012820849443363563599041, 643588798496057020) self.check_division(1115141373653752303710932756325578065, 1038556335171453937726882627) # 30-bit cases that require the post-subtraction correction step self.check_division(922498905405436751940989320930368494, 949985870686786135626943396) self.check_division(768235853328091167204009652174031844, 1091555541180371554426545266) # 15-bit cases involving a quotient digit estimate of BASE+1 self.check_division(20172188947443, 615611397) self.check_division(1020908530270155025, 950795710) self.check_division(128589565723112408, 736393718) self.check_division(609919780285761575, 18613274546784) # 15-bit cases that require the post-subtraction correction step self.check_division(710031681576388032, 26769404391308) self.check_division(1933622614268221, 30212853348836) def test_karatsuba(self): digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)) digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100]) bits = [digit * SHIFT for digit in digits] # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) == # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check. for abits in bits: a = (1 << abits) - 1 for bbits in bits: if bbits < abits: continue with self.subTest(abits=abits, bbits=bbits): b = (1 << bbits) - 1 x = a * b y = ((1 << (abits + bbits)) - (1 << abits) - (1 << bbits) + 1) self.assertEqual(x, y) def check_bitop_identities_1(self, x): eq = self.assertEqual with self.subTest(x=x): eq(x & 0, 0) eq(x | 0, x) eq(x ^ 0, x) eq(x & -1, x) eq(x | -1, -1) eq(x ^ -1, ~x) eq(x, ~~x) eq(x & x, x) eq(x | x, x) eq(x ^ x, 0) eq(x & ~x, 0) eq(x | ~x, -1) eq(x ^ ~x, -1) eq(-x, 1 + ~x) eq(-x, ~(x-1)) for n in range(2*SHIFT): p2 = 2 ** n with self.subTest(x=x, n=n, p2=p2): eq(x << n >> n, x) eq(x // p2, x >> n) eq(x * p2, x << n) eq(x & -p2, x >> n << n) eq(x & -p2, x & ~(p2 - 1)) def check_bitop_identities_2(self, x, y): eq = self.assertEqual with self.subTest(x=x, y=y): eq(x & y, y & x) eq(x | y, y | x) eq(x ^ y, y ^ x) eq(x ^ y ^ x, y) eq(x & y, ~(~x | ~y)) eq(x | y, ~(~x & ~y)) eq(x ^ y, (x | y) & ~(x & y)) eq(x ^ y, (x & ~y) | (~x & y)) eq(x ^ y, (x | y) & (~x | ~y)) def check_bitop_identities_3(self, x, y, z): eq = self.assertEqual with self.subTest(x=x, y=y, z=z): eq((x & y) & z, x & (y & z)) eq((x | y) | z, x | (y | z)) eq((x ^ y) ^ z, x ^ (y ^ z)) eq(x & (y | z), (x & y) | (x & z)) eq(x | (y & z), (x | y) & (x | z)) def test_bitop_identities(self): for x in special: self.check_bitop_identities_1(x) digits = range(1, MAXDIGITS+1) for lenx in digits: x = self.getran(lenx) self.check_bitop_identities_1(x) for leny in digits: y = self.getran(leny) self.check_bitop_identities_2(x, y) self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2)) def slow_format(self, x, base): digits = [] sign = 0 if x < 0: sign, x = 1, -x while x: x, r = divmod(x, base) digits.append(int(r)) digits.reverse() digits = digits or [0] return '-'[:sign] + \ {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \ "".join("0123456789abcdef"[i] for i in digits) def check_format_1(self, x): for base, mapper in (2, bin), (8, oct), (10, str), (10, repr), (16, hex): got = mapper(x) with self.subTest(x=x, mapper=mapper.__name__): expected = self.slow_format(x, base) self.assertEqual(got, expected) with self.subTest(got=got): self.assertEqual(int(got, 0), x) def test_format(self): for x in special: self.check_format_1(x) for i in range(10): for lenx in range(1, MAXDIGITS+1): x = self.getran(lenx) self.check_format_1(x) def test_long(self): # Check conversions from string LL = [ ('1' + '0'*20, 10**20), ('1' + '0'*100, 10**100) ] for s, v in LL: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(int(ss), vv) except ValueError: pass # trailing L should no longer be accepted... self.assertRaises(ValueError, int, '123L') self.assertRaises(ValueError, int, '123l') self.assertRaises(ValueError, int, '0L') self.assertRaises(ValueError, int, '-37L') self.assertRaises(ValueError, int, '0x32L', 16) self.assertRaises(ValueError, int, '1L', 21) # ... but it's just a normal digit if base >= 22 self.assertEqual(int('1L', 22), 43) # tests with base 0 self.assertEqual(int('000', 0), 0) self.assertEqual(int('0o123', 0), 83) self.assertEqual(int('0x123', 0), 291) self.assertEqual(int('0b100', 0), 4) self.assertEqual(int(' 0O123 ', 0), 83) self.assertEqual(int(' 0X123 ', 0), 291) self.assertEqual(int(' 0B100 ', 0), 4) self.assertEqual(int('0', 0), 0) self.assertEqual(int('+0', 0), 0) self.assertEqual(int('-0', 0), 0) self.assertEqual(int('00', 0), 0) self.assertRaises(ValueError, int, '08', 0) self.assertRaises(ValueError, int, '-012395', 0) # invalid bases invalid_bases = [-909, 2**31-1, 2**31, -2**31, -2**31-1, 2**63-1, 2**63, -2**63, -2**63-1, 2**100, -2**100, ] for base in invalid_bases: self.assertRaises(ValueError, int, '42', base) # Invalid unicode string # See bpo-34087 self.assertRaises(ValueError, int, '\u3053\u3093\u306b\u3061\u306f') def test_conversion(self): class JustLong: # test that __long__ no longer used in 3.x def __long__(self): return 42 self.assertRaises(TypeError, int, JustLong()) class LongTrunc: # __long__ should be ignored in 3.x def __long__(self): return 42 def __trunc__(self): return 1729 self.assertEqual(int(LongTrunc()), 1729) def check_float_conversion(self, n): # Check that int -> float conversion behaviour matches # that of the pure Python version above. try: actual = float(n) except OverflowError: actual = 'overflow' try: expected = int_to_float(n) except OverflowError: expected = 'overflow' msg = ("Error in conversion of integer {} to float. " "Got {}, expected {}.".format(n, actual, expected)) self.assertEqual(actual, expected, msg) @support.requires_IEEE_754 def test_float_conversion(self): exact_values = [0, 1, 2, 2**53-3, 2**53-2, 2**53-1, 2**53, 2**53+2, 2**54-4, 2**54-2, 2**54, 2**54+4] for x in exact_values: self.assertEqual(float(x), x) self.assertEqual(float(-x), -x) # test round-half-even for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]: for p in range(15): self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y)) for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8), (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12), (13, 12), (14, 16), (15, 16)]: for p in range(15): self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y)) # behaviour near extremes of floating-point range int_dbl_max = int(DBL_MAX) top_power = 2**DBL_MAX_EXP halfway = (int_dbl_max + top_power)//2 self.assertEqual(float(int_dbl_max), DBL_MAX) self.assertEqual(float(int_dbl_max+1), DBL_MAX) self.assertEqual(float(halfway-1), DBL_MAX) self.assertRaises(OverflowError, float, halfway) self.assertEqual(float(1-halfway), -DBL_MAX) self.assertRaises(OverflowError, float, -halfway) self.assertRaises(OverflowError, float, top_power-1) self.assertRaises(OverflowError, float, top_power) self.assertRaises(OverflowError, float, top_power+1) self.assertRaises(OverflowError, float, 2*top_power-1) self.assertRaises(OverflowError, float, 2*top_power) self.assertRaises(OverflowError, float, top_power*top_power) for p in range(100): x = 2**p * (2**53 + 1) + 1 y = 2**p * (2**53 + 2) self.assertEqual(int(float(x)), y) x = 2**p * (2**53 + 1) y = 2**p * 2**53 self.assertEqual(int(float(x)), y) # Compare builtin float conversion with pure Python int_to_float # function above. test_values = [ int_dbl_max-1, int_dbl_max, int_dbl_max+1, halfway-1, halfway, halfway + 1, top_power-1, top_power, top_power+1, 2*top_power-1, 2*top_power, top_power*top_power, ] test_values.extend(exact_values) for p in range(-4, 8): for x in range(-128, 128): test_values.append(2**(p+53) + x) for value in test_values: self.check_float_conversion(value) self.check_float_conversion(-value) def test_float_overflow(self): for x in -2.0, -1.0, 0.0, 1.0, 2.0: self.assertEqual(float(int(x)), x) shuge = '12345' * 120 huge = 1 << 30000 mhuge = -huge namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math} for test in ["float(huge)", "float(mhuge)", "complex(huge)", "complex(mhuge)", "complex(huge, 1)", "complex(mhuge, 1)", "complex(1, huge)", "complex(1, mhuge)", "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.", "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.", "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.", "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.", "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.", "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.", "math.sin(huge)", "math.sin(mhuge)", "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better # math.floor() of an int returns an int now ##"math.floor(huge)", "math.floor(mhuge)", ]: self.assertRaises(OverflowError, eval, test, namespace) # XXX Perhaps float(shuge) can raise OverflowError on some box? # The comparison should not. self.assertNotEqual(float(shuge), int(shuge), "float(shuge) should not equal int(shuge)") def test_logs(self): LOG10E = math.log10(math.e) for exp in list(range(10)) + [100, 1000, 10000]: value = 10 ** exp log10 = math.log10(value) self.assertAlmostEqual(log10, exp) # log10(value) == exp, so log(value) == log10(value)/log10(e) == # exp/LOG10E expected = exp / LOG10E log = math.log(value) self.assertAlmostEqual(log, expected) for bad in -(1 << 10000), -2, 0: self.assertRaises(ValueError, math.log, bad) self.assertRaises(ValueError, math.log10, bad) def test_mixed_compares(self): eq = self.assertEqual # We're mostly concerned with that mixing floats and ints does the # right stuff, even when ints are too large to fit in a float. # The safest way to check the results is to use an entirely different # method, which we do here via a skeletal rational class (which # represents all Python ints and floats exactly). class Rat: def __init__(self, value): if isinstance(value, int): self.n = value self.d = 1 elif isinstance(value, float): # Convert to exact rational equivalent. f, e = math.frexp(abs(value)) assert f == 0 or 0.5 <= f < 1.0 # |value| = f * 2**e exactly # Suck up CHUNK bits at a time; 28 is enough so that we suck # up all bits in 2 iterations for all known binary double- # precision formats, and small enough to fit in an int. CHUNK = 28 top = 0 # invariant: |value| = (top + f) * 2**e exactly while f: f = math.ldexp(f, CHUNK) digit = int(f) assert digit >> CHUNK == 0 top = (top << CHUNK) | digit f -= digit assert 0.0 <= f < 1.0 e -= CHUNK # Now |value| = top * 2**e exactly. if e >= 0: n = top << e d = 1 else: n = top d = 1 << -e if value < 0: n = -n self.n = n self.d = d assert float(n) / float(d) == value else: raise TypeError("can't deal with %r" % value) def _cmp__(self, other): if not isinstance(other, Rat): other = Rat(other) x, y = self.n * other.d, self.d * other.n return (x > y) - (x < y) def __eq__(self, other): return self._cmp__(other) == 0 def __ge__(self, other): return self._cmp__(other) >= 0 def __gt__(self, other): return self._cmp__(other) > 0 def __le__(self, other): return self._cmp__(other) <= 0 def __lt__(self, other): return self._cmp__(other) < 0 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200] # 2**48 is an important boundary in the internals. 2**53 is an # important boundary for IEEE double precision. for t in 2.0**48, 2.0**50, 2.0**53: cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0, int(t-1), int(t), int(t+1)]) cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)]) # 1 << 20000 should exceed all double formats. int(1e200) is to # check that we get equality with 1e200 above. t = int(1e200) cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1]) cases.extend([-x for x in cases]) for x in cases: Rx = Rat(x) for y in cases: Ry = Rat(y) Rcmp = (Rx > Ry) - (Rx < Ry) with self.subTest(x=x, y=y, Rcmp=Rcmp): xycmp = (x > y) - (x < y) eq(Rcmp, xycmp) eq(x == y, Rcmp == 0) eq(x != y, Rcmp != 0) eq(x < y, Rcmp < 0) eq(x <= y, Rcmp <= 0) eq(x > y, Rcmp > 0) eq(x >= y, Rcmp >= 0) def test__format__(self): self.assertEqual(format(123456789, 'd'), '123456789') self.assertEqual(format(123456789, 'd'), '123456789') self.assertEqual(format(123456789, ','), '123,456,789') self.assertEqual(format(123456789, '_'), '123_456_789') # sign and aligning are interdependent self.assertEqual(format(1, "-"), '1') self.assertEqual(format(-1, "-"), '-1') self.assertEqual(format(1, "-3"), ' 1') self.assertEqual(format(-1, "-3"), ' -1') self.assertEqual(format(1, "+3"), ' +1') self.assertEqual(format(-1, "+3"), ' -1') self.assertEqual(format(1, " 3"), ' 1') self.assertEqual(format(-1, " 3"), ' -1') self.assertEqual(format(1, " "), ' 1') self.assertEqual(format(-1, " "), '-1') # hex self.assertEqual(format(3, "x"), "3") self.assertEqual(format(3, "X"), "3") self.assertEqual(format(1234, "x"), "4d2") self.assertEqual(format(-1234, "x"), "-4d2") self.assertEqual(format(1234, "8x"), " 4d2") self.assertEqual(format(-1234, "8x"), " -4d2") self.assertEqual(format(1234, "x"), "4d2") self.assertEqual(format(-1234, "x"), "-4d2") self.assertEqual(format(-3, "x"), "-3") self.assertEqual(format(-3, "X"), "-3") self.assertEqual(format(int('be', 16), "x"), "be") self.assertEqual(format(int('be', 16), "X"), "BE") self.assertEqual(format(-int('be', 16), "x"), "-be") self.assertEqual(format(-int('be', 16), "X"), "-BE") self.assertRaises(ValueError, format, 1234567890, ',x') self.assertEqual(format(1234567890, '_x'), '4996_02d2') self.assertEqual(format(1234567890, '_X'), '4996_02D2') # octal self.assertEqual(format(3, "o"), "3") self.assertEqual(format(-3, "o"), "-3") self.assertEqual(format(1234, "o"), "2322") self.assertEqual(format(-1234, "o"), "-2322") self.assertEqual(format(1234, "-o"), "2322") self.assertEqual(format(-1234, "-o"), "-2322") self.assertEqual(format(1234, " o"), " 2322") self.assertEqual(format(-1234, " o"), "-2322") self.assertEqual(format(1234, "+o"), "+2322") self.assertEqual(format(-1234, "+o"), "-2322") self.assertRaises(ValueError, format, 1234567890, ',o') self.assertEqual(format(1234567890, '_o'), '111_4540_1322') # binary self.assertEqual(format(3, "b"), "11") self.assertEqual(format(-3, "b"), "-11") self.assertEqual(format(1234, "b"), "10011010010") self.assertEqual(format(-1234, "b"), "-10011010010") self.assertEqual(format(1234, "-b"), "10011010010") self.assertEqual(format(-1234, "-b"), "-10011010010") self.assertEqual(format(1234, " b"), " 10011010010") self.assertEqual(format(-1234, " b"), "-10011010010") self.assertEqual(format(1234, "+b"), "+10011010010") self.assertEqual(format(-1234, "+b"), "-10011010010") self.assertRaises(ValueError, format, 1234567890, ',b') self.assertEqual(format(12345, '_b'), '11_0000_0011_1001') # make sure these are errors self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed self.assertRaises(ValueError, format, 3, "_c") # underscore, self.assertRaises(ValueError, format, 3, ",c") # comma, and self.assertRaises(ValueError, format, 3, "+c") # sign not allowed # with 'c' self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,') self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_') self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,d') self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_d') self.assertRaisesRegex(ValueError, "Cannot specify ',' with 's'", format, 3, ',s') self.assertRaisesRegex(ValueError, "Cannot specify '_' with 's'", format, 3, '_s') # 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, format, 0, format_spec) self.assertRaises(ValueError, format, 1, format_spec) self.assertRaises(ValueError, format, -1, format_spec) self.assertRaises(ValueError, format, 2**100, format_spec) self.assertRaises(ValueError, format, -(2**100), 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(format(value, format_spec), format(float(value), format_spec)) def test_nan_inf(self): self.assertRaises(OverflowError, int, float('inf')) self.assertRaises(OverflowError, int, float('-inf')) self.assertRaises(ValueError, int, float('nan')) def test_mod_division(self): with self.assertRaises(ZeroDivisionError): _ = 1 % 0 self.assertEqual(13 % 10, 3) self.assertEqual(-13 % 10, 7) self.assertEqual(13 % -10, -7) self.assertEqual(-13 % -10, -3) self.assertEqual(12 % 4, 0) self.assertEqual(-12 % 4, 0) self.assertEqual(12 % -4, 0) self.assertEqual(-12 % -4, 0) def test_true_division(self): huge = 1 << 40000 mhuge = -huge self.assertEqual(huge / huge, 1.0) self.assertEqual(mhuge / mhuge, 1.0) self.assertEqual(huge / mhuge, -1.0) self.assertEqual(mhuge / huge, -1.0) self.assertEqual(1 / huge, 0.0) self.assertEqual(1 / huge, 0.0) self.assertEqual(1 / mhuge, 0.0) self.assertEqual(1 / mhuge, 0.0) self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5) self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5) self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5) self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5) self.assertEqual(huge / (huge << 1), 0.5) self.assertEqual((1000000 * huge) / huge, 1000000) namespace = {'huge': huge, 'mhuge': mhuge} for overflow in ["float(huge)", "float(mhuge)", "huge / 1", "huge / 2", "huge / -1", "huge / -2", "mhuge / 100", "mhuge / 200"]: self.assertRaises(OverflowError, eval, overflow, namespace) for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge", "100 / mhuge", "200 / mhuge"]: result = eval(underflow, namespace) self.assertEqual(result, 0.0, "expected underflow to 0 from %r" % underflow) for zero in ["huge / 0", "mhuge / 0"]: self.assertRaises(ZeroDivisionError, eval, zero, namespace) def test_floordiv(self): with self.assertRaises(ZeroDivisionError): _ = 1 // 0 self.assertEqual(2 // 3, 0) self.assertEqual(2 // -3, -1) self.assertEqual(-2 // 3, -1) self.assertEqual(-2 // -3, 0) self.assertEqual(-11 // -3, 3) self.assertEqual(-11 // 3, -4) self.assertEqual(11 // -3, -4) self.assertEqual(11 // 3, 3) self.assertEqual(-12 // -3, 4) self.assertEqual(-12 // 3, -4) self.assertEqual(12 // -3, -4) self.assertEqual(12 // 3, 4) def check_truediv(self, a, b, skip_small=True): """Verify that the result of a/b is correctly rounded, by comparing it with a pure Python implementation of correctly rounded division. b should be nonzero.""" # skip check for small a and b: in this case, the current # implementation converts the arguments to float directly and # then applies a float division. This can give doubly-rounded # results on x87-using machines (particularly 32-bit Linux). if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG: return try: # use repr so that we can distinguish between -0.0 and 0.0 expected = repr(truediv(a, b)) except OverflowError: expected = 'overflow' except ZeroDivisionError: expected = 'zerodivision' try: got = repr(a / b) except OverflowError: got = 'overflow' except ZeroDivisionError: got = 'zerodivision'
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_ordered_dict.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ordered_dict.py
import builtins import contextlib import copy import gc import pickle from random import randrange, shuffle import struct import sys import unittest import weakref from collections.abc import MutableMapping from test import mapping_tests, support py_coll = support.import_fresh_module('collections', blocked=['_collections']) c_coll = support.import_fresh_module('collections', fresh=['_collections']) @contextlib.contextmanager def replaced_module(name, replacement): original_module = sys.modules[name] sys.modules[name] = replacement try: yield finally: sys.modules[name] = original_module class OrderedDictTests: def test_init(self): OrderedDict = self.OrderedDict with self.assertRaises(TypeError): OrderedDict([('a', 1), ('b', 2)], None) # too many args pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5).items()), pairs) # mixed input # make sure no positional args conflict with possible kwdargs self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)]) self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)]) self.assertRaises(TypeError, OrderedDict, 42) self.assertRaises(TypeError, OrderedDict, (), ()) self.assertRaises(TypeError, OrderedDict.__init__) # Make sure that direct calls to __init__ do not clear previous contents d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) d.__init__([('e', 5), ('f', 6)], g=7, d=4) self.assertEqual(list(d.items()), [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) def test_468(self): OrderedDict = self.OrderedDict items = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)] shuffle(items) argdict = OrderedDict(items) d = OrderedDict(**argdict) self.assertEqual(list(d.items()), items) def test_update(self): OrderedDict = self.OrderedDict with self.assertRaises(TypeError): OrderedDict().update([('a', 1), ('b', 2)], None) # too many args pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] od = OrderedDict() od.update(dict(pairs)) self.assertEqual(sorted(od.items()), pairs) # dict input od = OrderedDict() od.update(**dict(pairs)) self.assertEqual(sorted(od.items()), pairs) # kwds input od = OrderedDict() od.update(pairs) self.assertEqual(list(od.items()), pairs) # pairs input od = OrderedDict() od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) self.assertEqual(list(od.items()), pairs) # mixed input # Issue 9137: Named argument called 'other' or 'self' # shouldn't be treated specially. od = OrderedDict() od.update(self=23) self.assertEqual(list(od.items()), [('self', 23)]) od = OrderedDict() od.update(other={}) self.assertEqual(list(od.items()), [('other', {})]) od = OrderedDict() od.update(red=5, blue=6, other=7, self=8) self.assertEqual(sorted(list(od.items())), [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) # Make sure that direct calls to update do not clear previous contents # add that updates items are not moved to the end d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) d.update([('e', 5), ('f', 6)], g=7, d=4) self.assertEqual(list(d.items()), [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) self.assertRaises(TypeError, OrderedDict().update, 42) self.assertRaises(TypeError, OrderedDict().update, (), ()) self.assertRaises(TypeError, OrderedDict.update) self.assertRaises(TypeError, OrderedDict().update, 42) self.assertRaises(TypeError, OrderedDict().update, (), ()) self.assertRaises(TypeError, OrderedDict.update) def test_init_calls(self): calls = [] class Spam: def keys(self): calls.append('keys') return () def items(self): calls.append('items') return () self.OrderedDict(Spam()) self.assertEqual(calls, ['keys']) def test_fromkeys(self): OrderedDict = self.OrderedDict od = OrderedDict.fromkeys('abc') self.assertEqual(list(od.items()), [(c, None) for c in 'abc']) od = OrderedDict.fromkeys('abc', value=None) self.assertEqual(list(od.items()), [(c, None) for c in 'abc']) od = OrderedDict.fromkeys('abc', value=0) self.assertEqual(list(od.items()), [(c, 0) for c in 'abc']) def test_abc(self): OrderedDict = self.OrderedDict self.assertIsInstance(OrderedDict(), MutableMapping) self.assertTrue(issubclass(OrderedDict, MutableMapping)) def test_clear(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od = OrderedDict(pairs) self.assertEqual(len(od), len(pairs)) od.clear() self.assertEqual(len(od), 0) def test_delitem(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) del od['a'] self.assertNotIn('a', od) with self.assertRaises(KeyError): del od['a'] self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) def test_setitem(self): OrderedDict = self.OrderedDict od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) od['c'] = 10 # existing element od['f'] = 20 # new element self.assertEqual(list(od.items()), [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) def test_iterators(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od = OrderedDict(pairs) self.assertEqual(list(od), [t[0] for t in pairs]) self.assertEqual(list(od.keys()), [t[0] for t in pairs]) self.assertEqual(list(od.values()), [t[1] for t in pairs]) self.assertEqual(list(od.items()), pairs) self.assertEqual(list(reversed(od)), [t[0] for t in reversed(pairs)]) self.assertEqual(list(reversed(od.keys())), [t[0] for t in reversed(pairs)]) self.assertEqual(list(reversed(od.values())), [t[1] for t in reversed(pairs)]) self.assertEqual(list(reversed(od.items())), list(reversed(pairs))) def test_detect_deletion_during_iteration(self): OrderedDict = self.OrderedDict od = OrderedDict.fromkeys('abc') it = iter(od) key = next(it) del od[key] with self.assertRaises(Exception): # Note, the exact exception raised is not guaranteed # The only guarantee that the next() will not succeed next(it) def test_sorted_iterators(self): OrderedDict = self.OrderedDict with self.assertRaises(TypeError): OrderedDict([('a', 1), ('b', 2)], None) pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] od = OrderedDict(pairs) self.assertEqual(sorted(od), [t[0] for t in pairs]) self.assertEqual(sorted(od.keys()), [t[0] for t in pairs]) self.assertEqual(sorted(od.values()), [t[1] for t in pairs]) self.assertEqual(sorted(od.items()), pairs) self.assertEqual(sorted(reversed(od)), sorted([t[0] for t in reversed(pairs)])) def test_iterators_empty(self): OrderedDict = self.OrderedDict od = OrderedDict() empty = [] self.assertEqual(list(od), empty) self.assertEqual(list(od.keys()), empty) self.assertEqual(list(od.values()), empty) self.assertEqual(list(od.items()), empty) self.assertEqual(list(reversed(od)), empty) self.assertEqual(list(reversed(od.keys())), empty) self.assertEqual(list(reversed(od.values())), empty) self.assertEqual(list(reversed(od.items())), empty) def test_popitem(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od = OrderedDict(pairs) while pairs: self.assertEqual(od.popitem(), pairs.pop()) with self.assertRaises(KeyError): od.popitem() self.assertEqual(len(od), 0) def test_popitem_last(self): OrderedDict = self.OrderedDict pairs = [(i, i) for i in range(30)] obj = OrderedDict(pairs) for i in range(8): obj.popitem(True) obj.popitem(True) obj.popitem(last=True) self.assertEqual(len(obj), 20) def test_pop(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od = OrderedDict(pairs) shuffle(pairs) while pairs: k, v = pairs.pop() self.assertEqual(od.pop(k), v) with self.assertRaises(KeyError): od.pop('xyz') self.assertEqual(len(od), 0) self.assertEqual(od.pop(k, 12345), 12345) # make sure pop still works when __missing__ is defined class Missing(OrderedDict): def __missing__(self, key): return 0 m = Missing(a=1) self.assertEqual(m.pop('b', 5), 5) self.assertEqual(m.pop('a', 6), 1) self.assertEqual(m.pop('a', 6), 6) self.assertEqual(m.pop('a', default=6), 6) with self.assertRaises(KeyError): m.pop('a') def test_equality(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od1 = OrderedDict(pairs) od2 = OrderedDict(pairs) self.assertEqual(od1, od2) # same order implies equality pairs = pairs[2:] + pairs[:2] od2 = OrderedDict(pairs) self.assertNotEqual(od1, od2) # different order implies inequality # comparison to regular dict is not order sensitive self.assertEqual(od1, dict(od2)) self.assertEqual(dict(od2), od1) # different length implied inequality self.assertNotEqual(od1, OrderedDict(pairs[:-1])) def test_copying(self): OrderedDict = self.OrderedDict # Check that ordered dicts are copyable, deepcopyable, picklable, # and have a repr/eval round-trip pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) def check(dup): msg = "\ncopy: %s\nod: %s" % (dup, od) self.assertIsNot(dup, od, msg) self.assertEqual(dup, od) self.assertEqual(list(dup.items()), list(od.items())) self.assertEqual(len(dup), len(od)) self.assertEqual(type(dup), type(od)) check(od.copy()) check(copy.copy(od)) check(copy.deepcopy(od)) # pickle directly pulls the module, so we have to fake it with replaced_module('collections', self.module): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): check(pickle.loads(pickle.dumps(od, proto))) check(eval(repr(od))) update_test = OrderedDict() update_test.update(od) check(update_test) check(OrderedDict(od)) def test_yaml_linkage(self): OrderedDict = self.OrderedDict # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. # In yaml, lists are native but tuples are not. pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) # yaml.dump(od) --> # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) def test_reduce_not_too_fat(self): OrderedDict = self.OrderedDict # do not save instance dictionary if not needed pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) self.assertIsInstance(od.__dict__, dict) self.assertIsNone(od.__reduce__()[2]) od.x = 10 self.assertEqual(od.__dict__['x'], 10) self.assertEqual(od.__reduce__()[2], {'x': 10}) def test_pickle_recursive(self): OrderedDict = self.OrderedDict od = OrderedDict() od[1] = od # pickle directly pulls the module, so we have to fake it with replaced_module('collections', self.module): for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1): dup = pickle.loads(pickle.dumps(od, proto)) self.assertIsNot(dup, od) self.assertEqual(list(dup.keys()), [1]) self.assertIs(dup[1], dup) def test_repr(self): OrderedDict = self.OrderedDict od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) self.assertEqual(repr(od), "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") self.assertEqual(eval(repr(od)), od) self.assertEqual(repr(OrderedDict()), "OrderedDict()") def test_repr_recursive(self): OrderedDict = self.OrderedDict # See issue #9826 od = OrderedDict.fromkeys('abc') od['x'] = od self.assertEqual(repr(od), "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") def test_repr_recursive_values(self): OrderedDict = self.OrderedDict od = OrderedDict() od[42] = od.values() r = repr(od) # Cannot perform a stronger test, as the contents of the repr # are implementation-dependent. All we can say is that we # want a str result, not an exception of any sort. self.assertIsInstance(r, str) od[42] = od.items() r = repr(od) # Again. self.assertIsInstance(r, str) def test_setdefault(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] shuffle(pairs) od = OrderedDict(pairs) pair_order = list(od.items()) self.assertEqual(od.setdefault('a', 10), 3) # make sure order didn't change self.assertEqual(list(od.items()), pair_order) self.assertEqual(od.setdefault('x', 10), 10) # make sure 'x' is added to the end self.assertEqual(list(od.items())[-1], ('x', 10)) self.assertEqual(od.setdefault('g', default=9), 9) # make sure setdefault still works when __missing__ is defined class Missing(OrderedDict): def __missing__(self, key): return 0 self.assertEqual(Missing().setdefault(5, 9), 9) def test_reinsert(self): OrderedDict = self.OrderedDict # Given insert a, insert b, delete a, re-insert a, # verify that a is now later than b. od = OrderedDict() od['a'] = 1 od['b'] = 2 del od['a'] self.assertEqual(list(od.items()), [('b', 2)]) od['a'] = 1 self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) def test_move_to_end(self): OrderedDict = self.OrderedDict od = OrderedDict.fromkeys('abcde') self.assertEqual(list(od), list('abcde')) od.move_to_end('c') self.assertEqual(list(od), list('abdec')) od.move_to_end('c', 0) self.assertEqual(list(od), list('cabde')) od.move_to_end('c', 0) self.assertEqual(list(od), list('cabde')) od.move_to_end('e') self.assertEqual(list(od), list('cabde')) od.move_to_end('b', last=False) self.assertEqual(list(od), list('bcade')) with self.assertRaises(KeyError): od.move_to_end('x') with self.assertRaises(KeyError): od.move_to_end('x', 0) def test_move_to_end_issue25406(self): OrderedDict = self.OrderedDict od = OrderedDict.fromkeys('abc') od.move_to_end('c', last=False) self.assertEqual(list(od), list('cab')) od.move_to_end('a', last=False) self.assertEqual(list(od), list('acb')) od = OrderedDict.fromkeys('abc') od.move_to_end('a') self.assertEqual(list(od), list('bca')) od.move_to_end('c') self.assertEqual(list(od), list('bac')) def test_sizeof(self): OrderedDict = self.OrderedDict # Wimpy test: Just verify the reported size is larger than a regular dict d = dict(a=1) od = OrderedDict(**d) self.assertGreater(sys.getsizeof(od), sys.getsizeof(d)) def test_views(self): OrderedDict = self.OrderedDict # See http://bugs.python.org/issue24286 s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split() od = OrderedDict.fromkeys(s) self.assertEqual(od.keys(), dict(od).keys()) self.assertEqual(od.items(), dict(od).items()) def test_override_update(self): OrderedDict = self.OrderedDict # Verify that subclasses can override update() without breaking __init__() class MyOD(OrderedDict): def update(self, *args, **kwds): raise Exception() items = [('a', 1), ('c', 3), ('b', 2)] self.assertEqual(list(MyOD(items).items()), items) def test_highly_nested(self): # Issue 25395: crashes during garbage collection OrderedDict = self.OrderedDict obj = None for _ in range(1000): obj = OrderedDict([(None, obj)]) del obj support.gc_collect() def test_highly_nested_subclass(self): # Issue 25395: crashes during garbage collection OrderedDict = self.OrderedDict deleted = [] class MyOD(OrderedDict): def __del__(self): deleted.append(self.i) obj = None for i in range(100): obj = MyOD([(None, obj)]) obj.i = i del obj support.gc_collect() self.assertEqual(deleted, list(reversed(range(100)))) def test_delitem_hash_collision(self): OrderedDict = self.OrderedDict class Key: def __init__(self, hash): self._hash = hash self.value = str(id(self)) def __hash__(self): return self._hash def __eq__(self, other): try: return self.value == other.value except AttributeError: return False def __repr__(self): return self.value def blocking_hash(hash): # See the collision-handling in lookdict (in Objects/dictobject.c). MINSIZE = 8 i = (hash & MINSIZE-1) return (i << 2) + i + hash + 1 COLLIDING = 1 key = Key(COLLIDING) colliding = Key(COLLIDING) blocking = Key(blocking_hash(COLLIDING)) od = OrderedDict() od[key] = ... od[blocking] = ... od[colliding] = ... od['after'] = ... del od[blocking] del od[colliding] self.assertEqual(list(od.items()), [(key, ...), ('after', ...)]) def test_issue24347(self): OrderedDict = self.OrderedDict class Key: def __hash__(self): return randrange(100000) od = OrderedDict() for i in range(100): key = Key() od[key] = i # These should not crash. with self.assertRaises(KeyError): list(od.values()) with self.assertRaises(KeyError): list(od.items()) with self.assertRaises(KeyError): repr(od) with self.assertRaises(KeyError): od.copy() def test_issue24348(self): OrderedDict = self.OrderedDict class Key: def __hash__(self): return 1 od = OrderedDict() od[Key()] = 0 # This should not crash. od.popitem() def test_issue24667(self): """ dict resizes after a certain number of insertion operations, whether or not there were deletions that freed up slots in the hash table. During fast node lookup, OrderedDict must correctly respond to all resizes, even if the current "size" is the same as the old one. We verify that here by forcing a dict resize on a sparse odict and then perform an operation that should trigger an odict resize (e.g. popitem). One key aspect here is that we will keep the size of the odict the same at each popitem call. This verifies that we handled the dict resize properly. """ OrderedDict = self.OrderedDict od = OrderedDict() for c0 in '0123456789ABCDEF': for c1 in '0123456789ABCDEF': if len(od) == 4: # This should not raise a KeyError. od.popitem(last=False) key = c0 + c1 od[key] = key # Direct use of dict methods def test_dict_setitem(self): OrderedDict = self.OrderedDict od = OrderedDict() dict.__setitem__(od, 'spam', 1) self.assertNotIn('NULL', repr(od)) def test_dict_delitem(self): OrderedDict = self.OrderedDict od = OrderedDict() od['spam'] = 1 od['ham'] = 2 dict.__delitem__(od, 'spam') with self.assertRaises(KeyError): repr(od) def test_dict_clear(self): OrderedDict = self.OrderedDict od = OrderedDict() od['spam'] = 1 od['ham'] = 2 dict.clear(od) self.assertNotIn('NULL', repr(od)) def test_dict_pop(self): OrderedDict = self.OrderedDict od = OrderedDict() od['spam'] = 1 od['ham'] = 2 dict.pop(od, 'spam') with self.assertRaises(KeyError): repr(od) def test_dict_popitem(self): OrderedDict = self.OrderedDict od = OrderedDict() od['spam'] = 1 od['ham'] = 2 dict.popitem(od) with self.assertRaises(KeyError): repr(od) def test_dict_setdefault(self): OrderedDict = self.OrderedDict od = OrderedDict() dict.setdefault(od, 'spam', 1) self.assertNotIn('NULL', repr(od)) def test_dict_update(self): OrderedDict = self.OrderedDict od = OrderedDict() dict.update(od, [('spam', 1)]) self.assertNotIn('NULL', repr(od)) def test_reference_loop(self): # Issue 25935 OrderedDict = self.OrderedDict class A: od = OrderedDict() A.od[A] = None r = weakref.ref(A) del A gc.collect() self.assertIsNone(r()) def test_free_after_iterating(self): support.check_free_after_iterating(self, iter, self.OrderedDict) support.check_free_after_iterating(self, lambda d: iter(d.keys()), self.OrderedDict) support.check_free_after_iterating(self, lambda d: iter(d.values()), self.OrderedDict) support.check_free_after_iterating(self, lambda d: iter(d.items()), self.OrderedDict) class PurePythonOrderedDictTests(OrderedDictTests, unittest.TestCase): module = py_coll OrderedDict = py_coll.OrderedDict class CPythonBuiltinDictTests(unittest.TestCase): """Builtin dict preserves insertion order. Reuse some of tests in OrderedDict selectively. """ module = builtins OrderedDict = dict for method in ( "test_init test_update test_abc test_clear test_delitem " + "test_setitem test_detect_deletion_during_iteration " + "test_popitem test_reinsert test_override_update " + "test_highly_nested test_highly_nested_subclass " + "test_delitem_hash_collision ").split(): setattr(CPythonBuiltinDictTests, method, getattr(OrderedDictTests, method)) del method @unittest.skipUnless(c_coll, 'requires the C version of the collections module') class CPythonOrderedDictTests(OrderedDictTests, unittest.TestCase): module = c_coll OrderedDict = c_coll.OrderedDict check_sizeof = support.check_sizeof @support.cpython_only def test_sizeof_exact(self): OrderedDict = self.OrderedDict calcsize = struct.calcsize size = support.calcobjsize check = self.check_sizeof basicsize = size('nQ2P' + '3PnPn2P') + calcsize('2nP2n') entrysize = calcsize('n2P') p = calcsize('P') nodesize = calcsize('Pn2P') od = OrderedDict() check(od, basicsize + 8 + 5*entrysize) # 8byte indices + 8*2//3 * entry table od.x = 1 check(od, basicsize + 8 + 5*entrysize) od.update([(i, i) for i in range(3)]) check(od, basicsize + 8*p + 8 + 5*entrysize + 3*nodesize) od.update([(i, i) for i in range(3, 10)]) check(od, basicsize + 16*p + 16 + 10*entrysize + 10*nodesize) check(od.keys(), size('P')) check(od.items(), size('P')) check(od.values(), size('P')) itersize = size('iP2n2P') check(iter(od), itersize) check(iter(od.keys()), itersize) check(iter(od.items()), itersize) check(iter(od.values()), itersize) def test_key_change_during_iteration(self): OrderedDict = self.OrderedDict od = OrderedDict.fromkeys('abcde') self.assertEqual(list(od), list('abcde')) with self.assertRaises(RuntimeError): for i, k in enumerate(od): od.move_to_end(k) self.assertLess(i, 5) with self.assertRaises(RuntimeError): for k in od: od['f'] = None with self.assertRaises(RuntimeError): for k in od: del od['c'] self.assertEqual(list(od), list('bdeaf')) def test_iterators_pickling(self): OrderedDict = self.OrderedDict pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) for method_name in ('keys', 'values', 'items'): meth = getattr(od, method_name) expected = list(meth())[1:] for i in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(method_name=method_name, protocol=i): it = iter(meth()) next(it) p = pickle.dumps(it, i) unpickled = pickle.loads(p) self.assertEqual(list(unpickled), expected) self.assertEqual(list(it), expected) @support.cpython_only def test_weakref_list_is_not_traversed(self): # Check that the weakref list is not traversed when collecting # OrderedDict objects. See bpo-39778 for more information. gc.collect() x = self.OrderedDict() x.cycle = x cycle = [] cycle.append(cycle) x_ref = weakref.ref(x) cycle.append(x_ref) del x, cycle, x_ref gc.collect() class PurePythonOrderedDictSubclassTests(PurePythonOrderedDictTests): module = py_coll class OrderedDict(py_coll.OrderedDict): pass class CPythonOrderedDictSubclassTests(CPythonOrderedDictTests): module = c_coll class OrderedDict(c_coll.OrderedDict): pass class PurePythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol): @classmethod def setUpClass(cls): cls.type2test = py_coll.OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) @unittest.skipUnless(c_coll, 'requires the C version of the collections module') class CPythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol): @classmethod def setUpClass(cls): cls.type2test = c_coll.OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) class PurePythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol): @classmethod def setUpClass(cls): class MyOrderedDict(py_coll.OrderedDict): pass cls.type2test = MyOrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) @unittest.skipUnless(c_coll, 'requires the C version of the collections module') class CPythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol): @classmethod def setUpClass(cls): class MyOrderedDict(c_coll.OrderedDict): pass cls.type2test = MyOrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) 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_syntax.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_syntax.py
"""This module tests SyntaxErrors. Here's an example of the sort of thing that is tested. >>> def f(x): ... global x Traceback (most recent call last): SyntaxError: name 'x' is parameter and global The tests are all raise SyntaxErrors. They were created by checking each C call that raises SyntaxError. There are several modules that raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and symtable.c. The parser itself outlaws a lot of invalid syntax. None of these errors are tested here at the moment. We should add some tests; since there are infinitely many programs with invalid syntax, we would need to be judicious in selecting some. The compiler generates a synthetic module name for code executed by doctest. Since all the code comes from the same module, a suffix like [1] is appended to the module name, As a consequence, changing the order of tests in this module means renumbering all the errors after it. (Maybe we should enable the ellipsis option for these tests.) In ast.c, syntax errors are raised by calling ast_error(). Errors from set_context(): >>> obj.None = 1 Traceback (most recent call last): SyntaxError: invalid syntax >>> None = 1 Traceback (most recent call last): SyntaxError: can't assign to keyword >>> f() = 1 Traceback (most recent call last): SyntaxError: can't assign to function call >>> del f() Traceback (most recent call last): SyntaxError: can't delete function call >>> a + 1 = 2 Traceback (most recent call last): SyntaxError: can't assign to operator >>> (x for x in x) = 1 Traceback (most recent call last): SyntaxError: can't assign to generator expression >>> 1 = 1 Traceback (most recent call last): SyntaxError: can't assign to literal >>> "abc" = 1 Traceback (most recent call last): SyntaxError: can't assign to literal >>> b"" = 1 Traceback (most recent call last): SyntaxError: can't assign to literal >>> `1` = 1 Traceback (most recent call last): SyntaxError: invalid syntax If the left-hand side of an assignment is a list or tuple, an illegal expression inside that contain should still cause a syntax error. This test just checks a couple of cases rather than enumerating all of them. >>> (a, "b", c) = (1, 2, 3) Traceback (most recent call last): SyntaxError: can't assign to literal >>> [a, b, c + 1] = [1, 2, 3] Traceback (most recent call last): SyntaxError: can't assign to operator >>> a if 1 else b = 1 Traceback (most recent call last): SyntaxError: can't assign to conditional expression From compiler_complex_args(): >>> def f(None=1): ... pass Traceback (most recent call last): SyntaxError: invalid syntax From ast_for_arguments(): >>> def f(x, y=1, z): ... pass Traceback (most recent call last): SyntaxError: non-default argument follows default argument >>> def f(x, None): ... pass Traceback (most recent call last): SyntaxError: invalid syntax >>> def f(*None): ... pass Traceback (most recent call last): SyntaxError: invalid syntax >>> def f(**None): ... pass Traceback (most recent call last): SyntaxError: invalid syntax From ast_for_funcdef(): >>> def None(x): ... pass Traceback (most recent call last): SyntaxError: invalid syntax From ast_for_call(): >>> def f(it, *varargs, **kwargs): ... return list(it) >>> L = range(10) >>> f(x for x in L) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> f(x for x in L, 1) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(x for x in L, y=1) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(x for x in L, *[]) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(x for x in L, **{}) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(L, x for x in L) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(x for x in L, y for y in L) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f(x for x in L,) Traceback (most recent call last): SyntaxError: Generator expression must be parenthesized >>> f((x for x in L), 1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> class C(x for x in L): ... pass Traceback (most recent call last): SyntaxError: invalid syntax >>> def g(*args, **kwargs): ... print(args, sorted(kwargs.items())) >>> g(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, ... 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, ... 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, ... 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, ... 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, ... 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, ... 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, ... 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, ... 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, ... 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, ... 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, ... 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, ... 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, ... 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, ... 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, ... 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, ... 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, ... 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, ... 290, 291, 292, 293, 294, 295, 296, 297, 298, 299) # doctest: +ELLIPSIS (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) [] >>> g(a000=0, a001=1, a002=2, a003=3, a004=4, a005=5, a006=6, a007=7, a008=8, ... a009=9, a010=10, a011=11, a012=12, a013=13, a014=14, a015=15, a016=16, ... a017=17, a018=18, a019=19, a020=20, a021=21, a022=22, a023=23, a024=24, ... a025=25, a026=26, a027=27, a028=28, a029=29, a030=30, a031=31, a032=32, ... a033=33, a034=34, a035=35, a036=36, a037=37, a038=38, a039=39, a040=40, ... a041=41, a042=42, a043=43, a044=44, a045=45, a046=46, a047=47, a048=48, ... a049=49, a050=50, a051=51, a052=52, a053=53, a054=54, a055=55, a056=56, ... a057=57, a058=58, a059=59, a060=60, a061=61, a062=62, a063=63, a064=64, ... a065=65, a066=66, a067=67, a068=68, a069=69, a070=70, a071=71, a072=72, ... a073=73, a074=74, a075=75, a076=76, a077=77, a078=78, a079=79, a080=80, ... a081=81, a082=82, a083=83, a084=84, a085=85, a086=86, a087=87, a088=88, ... a089=89, a090=90, a091=91, a092=92, a093=93, a094=94, a095=95, a096=96, ... a097=97, a098=98, a099=99, a100=100, a101=101, a102=102, a103=103, ... a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110, ... a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117, ... a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124, ... a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131, ... a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138, ... a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145, ... a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152, ... a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159, ... a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166, ... a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173, ... a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180, ... a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187, ... a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194, ... a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201, ... a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208, ... a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215, ... a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222, ... a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229, ... a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236, ... a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243, ... a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250, ... a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257, ... a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264, ... a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271, ... a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278, ... a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285, ... a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292, ... a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299) ... # doctest: +ELLIPSIS () [('a000', 0), ('a001', 1), ('a002', 2), ..., ('a298', 298), ('a299', 299)] >>> class C: ... def meth(self, *args): ... return args >>> obj = C() >>> obj.meth( ... 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, ... 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, ... 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, ... 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, ... 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, ... 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, ... 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, ... 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, ... 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, ... 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, ... 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, ... 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, ... 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, ... 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, ... 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, ... 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, ... 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, ... 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, ... 290, 291, 292, 293, 294, 295, 296, 297, 298, 299) # doctest: +ELLIPSIS (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) >>> f(lambda x: x[0] = 3) Traceback (most recent call last): SyntaxError: lambda cannot contain assignment The grammar accepts any test (basically, any expression) in the keyword slot of a call site. Test a few different options. >>> f(x()=2) Traceback (most recent call last): SyntaxError: keyword can't be an expression >>> f(a or b=1) Traceback (most recent call last): SyntaxError: keyword can't be an expression >>> f(x.y=1) Traceback (most recent call last): SyntaxError: keyword can't be an expression More set_context(): >>> (x for x in x) += 1 Traceback (most recent call last): SyntaxError: can't assign to generator expression >>> None += 1 Traceback (most recent call last): SyntaxError: can't assign to keyword >>> f() += 1 Traceback (most recent call last): SyntaxError: can't assign to function call Test continue in finally in weird combinations. continue in for loop under finally should be ok. >>> def test(): ... try: ... pass ... finally: ... for abc in range(10): ... continue ... print(abc) >>> test() 9 Start simple, a continue in a finally should not be allowed. >>> def test(): ... for abc in range(10): ... try: ... pass ... finally: ... continue Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause This is essentially a continue in a finally which should not be allowed. >>> def test(): ... for abc in range(10): ... try: ... pass ... finally: ... try: ... continue ... except: ... pass Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause >>> def foo(): ... try: ... pass ... finally: ... continue Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause >>> def foo(): ... for a in (): ... try: ... pass ... finally: ... continue Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause >>> def foo(): ... for a in (): ... try: ... pass ... finally: ... try: ... continue ... finally: ... pass Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause >>> def foo(): ... for a in (): ... try: pass ... finally: ... try: ... pass ... except: ... continue Traceback (most recent call last): ... SyntaxError: 'continue' not supported inside 'finally' clause There is one test for a break that is not in a loop. The compiler uses a single data structure to keep track of try-finally and loops, so we need to be sure that a break is actually inside a loop. If it isn't, there should be a syntax error. >>> try: ... print(1) ... break ... print(2) ... finally: ... print(3) Traceback (most recent call last): ... SyntaxError: 'break' outside loop This raises a SyntaxError, it used to raise a SystemError. Context for this change can be found on issue #27514 In 2.5 there was a missing exception and an assert was triggered in a debug build. The number of blocks must be greater than CO_MAXBLOCKS. SF #1565514 >>> while 1: ... while 2: ... while 3: ... while 4: ... while 5: ... while 6: ... while 8: ... while 9: ... while 10: ... while 11: ... while 12: ... while 13: ... while 14: ... while 15: ... while 16: ... while 17: ... while 18: ... while 19: ... while 20: ... while 21: ... while 22: ... break Traceback (most recent call last): ... SyntaxError: too many statically nested blocks Misuse of the nonlocal and global statement can lead to a few unique syntax errors. >>> def f(): ... print(x) ... global x Traceback (most recent call last): ... SyntaxError: name 'x' is used prior to global declaration >>> def f(): ... x = 1 ... global x Traceback (most recent call last): ... SyntaxError: name 'x' is assigned to before global declaration >>> def f(x): ... global x Traceback (most recent call last): ... SyntaxError: name 'x' is parameter and global >>> def f(): ... x = 1 ... def g(): ... print(x) ... nonlocal x Traceback (most recent call last): ... SyntaxError: name 'x' is used prior to nonlocal declaration >>> def f(): ... x = 1 ... def g(): ... x = 2 ... nonlocal x Traceback (most recent call last): ... SyntaxError: name 'x' is assigned to before nonlocal declaration >>> def f(x): ... nonlocal x Traceback (most recent call last): ... SyntaxError: name 'x' is parameter and nonlocal >>> def f(): ... global x ... nonlocal x Traceback (most recent call last): ... SyntaxError: name 'x' is nonlocal and global >>> def f(): ... nonlocal x Traceback (most recent call last): ... SyntaxError: no binding for nonlocal 'x' found From SF bug #1705365 >>> nonlocal x Traceback (most recent call last): ... SyntaxError: nonlocal declaration not allowed at module level From https://bugs.python.org/issue25973 >>> class A: ... def f(self): ... nonlocal __x Traceback (most recent call last): ... SyntaxError: no binding for nonlocal '_A__x' found This tests assignment-context; there was a bug in Python 2.5 where compiling a complex 'if' (one with 'elif') would fail to notice an invalid suite, leading to spurious errors. >>> if 1: ... x() = 1 ... elif 1: ... pass Traceback (most recent call last): ... SyntaxError: can't assign to function call >>> if 1: ... pass ... elif 1: ... x() = 1 Traceback (most recent call last): ... SyntaxError: can't assign to function call >>> if 1: ... x() = 1 ... elif 1: ... pass ... else: ... pass Traceback (most recent call last): ... SyntaxError: can't assign to function call >>> if 1: ... pass ... elif 1: ... x() = 1 ... else: ... pass Traceback (most recent call last): ... SyntaxError: can't assign to function call >>> if 1: ... pass ... elif 1: ... pass ... else: ... x() = 1 Traceback (most recent call last): ... SyntaxError: can't assign to function call Make sure that the old "raise X, Y[, Z]" form is gone: >>> raise X, Y Traceback (most recent call last): ... SyntaxError: invalid syntax >>> raise X, Y, Z Traceback (most recent call last): ... SyntaxError: invalid syntax >>> f(a=23, a=234) Traceback (most recent call last): ... SyntaxError: keyword argument repeated >>> {1, 2, 3} = 42 Traceback (most recent call last): SyntaxError: can't assign to literal Corner-cases that used to fail to raise the correct error: >>> def f(*, x=lambda __debug__:0): pass Traceback (most recent call last): SyntaxError: assignment to keyword >>> def f(*args:(lambda __debug__:0)): pass Traceback (most recent call last): SyntaxError: assignment to keyword >>> def f(**kwargs:(lambda __debug__:0)): pass Traceback (most recent call last): SyntaxError: assignment to keyword >>> with (lambda *:0): pass Traceback (most recent call last): SyntaxError: named arguments must follow bare * Corner-cases that used to crash: >>> def f(**__debug__): pass Traceback (most recent call last): SyntaxError: assignment to keyword >>> def f(*xx, __debug__): pass Traceback (most recent call last): SyntaxError: assignment to keyword """ import re import unittest from test import support class SyntaxTestCase(unittest.TestCase): def _check_error(self, code, errtext, filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None): """Check that compiling code raises SyntaxError with errtext. errtest is a regular expression that must be present in the test of the exception raised. If subclass is specified it is the expected subclass of SyntaxError (e.g. IndentationError). """ try: compile(code, filename, mode) except SyntaxError as err: if subclass and not isinstance(err, subclass): self.fail("SyntaxError is not a %s" % subclass.__name__) mo = re.search(errtext, str(err)) if mo is None: self.fail("SyntaxError did not contain '%r'" % (errtext,)) self.assertEqual(err.filename, filename) if lineno is not None: self.assertEqual(err.lineno, lineno) if offset is not None: self.assertEqual(err.offset, offset) else: self.fail("compile() did not raise SyntaxError") def test_assign_call(self): self._check_error("f() = 1", "assign") def test_assign_del(self): self._check_error("del f()", "delete") def test_global_param_err_first(self): source = """if 1: def error(a): global a # SyntaxError def error2(): b = 1 global b # SyntaxError """ self._check_error(source, "parameter and global", lineno=3) def test_nonlocal_param_err_first(self): source = """if 1: def error(a): nonlocal a # SyntaxError def error2(): b = 1 global b # SyntaxError """ self._check_error(source, "parameter and nonlocal", lineno=3) def test_break_outside_loop(self): self._check_error("break", "outside loop") def test_unexpected_indent(self): self._check_error("foo()\n bar()\n", "unexpected indent", subclass=IndentationError) def test_no_indent(self): self._check_error("if 1:\nfoo()", "expected an indented block", subclass=IndentationError) def test_bad_outdent(self): self._check_error("if 1:\n foo()\n bar()", "unindent does not match .* level", subclass=IndentationError) def test_kwargs_last(self): self._check_error("int(base=10, '2')", "positional argument follows keyword argument") def test_kwargs_last2(self): self._check_error("int(**{'base': 10}, '2')", "positional argument follows " "keyword argument unpacking") def test_kwargs_last3(self): self._check_error("int(**{'base': 10}, *['2'])", "iterable argument unpacking follows " "keyword argument unpacking") def test_main(): support.run_unittest(SyntaxTestCase) from test import test_syntax support.run_doctest(test_syntax, verbosity=True) if __name__ == "__main__": test_main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/pickletester.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/pickletester.py
import collections import copyreg import dbm import io import functools import os import pickle import pickletools import shutil import struct import sys import threading import unittest import weakref from textwrap import dedent from http.cookies import SimpleCookie from test import support from test.support import ( TestFailed, TESTFN, run_with_locale, no_tracing, _2G, _4G, bigmemtest, reap_threads, forget, ) from pickle import bytes_types requires_32b = unittest.skipUnless(sys.maxsize < 2**32, "test is only meaningful on 32-bit builds") # Tests that try a number of pickle protocols should have a # for proto in protocols: # kind of outer loop. protocols = range(pickle.HIGHEST_PROTOCOL + 1) # Return True if opcode code appears in the pickle, else False. def opcode_in_pickle(code, pickle): for op, dummy, dummy in pickletools.genops(pickle): if op.code == code.decode("latin-1"): return True return False # Return the number of times opcode code appears in pickle. def count_opcode(code, pickle): n = 0 for op, dummy, dummy in pickletools.genops(pickle): if op.code == code.decode("latin-1"): n += 1 return n class UnseekableIO(io.BytesIO): def peek(self, *args): raise NotImplementedError def seekable(self): return False def seek(self, *args): raise io.UnsupportedOperation def tell(self): raise io.UnsupportedOperation # We can't very well test the extension registry without putting known stuff # in it, but we have to be careful to restore its original state. Code # should do this: # # e = ExtensionSaver(extension_code) # try: # fiddle w/ the extension registry's stuff for extension_code # finally: # e.restore() class ExtensionSaver: # Remember current registration for code (if any), and remove it (if # there is one). def __init__(self, code): self.code = code if code in copyreg._inverted_registry: self.pair = copyreg._inverted_registry[code] copyreg.remove_extension(self.pair[0], self.pair[1], code) else: self.pair = None # Restore previous registration for code. def restore(self): code = self.code curpair = copyreg._inverted_registry.get(code) if curpair is not None: copyreg.remove_extension(curpair[0], curpair[1], code) pair = self.pair if pair is not None: copyreg.add_extension(pair[0], pair[1], code) class C: def __eq__(self, other): return self.__dict__ == other.__dict__ class D(C): def __init__(self, arg): pass class E(C): def __getinitargs__(self): return () class H(object): pass # Hashable mutable key class K(object): def __init__(self, value): self.value = value def __reduce__(self): # Shouldn't support the recursion itself return K, (self.value,) import __main__ __main__.C = C C.__module__ = "__main__" __main__.D = D D.__module__ = "__main__" __main__.E = E E.__module__ = "__main__" __main__.H = H H.__module__ = "__main__" __main__.K = K K.__module__ = "__main__" class myint(int): def __init__(self, x): self.str = str(x) class initarg(C): def __init__(self, a, b): self.a = a self.b = b def __getinitargs__(self): return self.a, self.b class metaclass(type): pass class use_metaclass(object, metaclass=metaclass): pass class pickling_metaclass(type): def __eq__(self, other): return (type(self) == type(other) and self.reduce_args == other.reduce_args) def __reduce__(self): return (create_dynamic_class, self.reduce_args) def create_dynamic_class(name, bases): result = pickling_metaclass(name, bases, dict()) result.reduce_args = (name, bases) return result # DATA0 .. DATA4 are the pickles we expect under the various protocols, for # the object returned by create_data(). DATA0 = ( b'(lp0\nL0L\naL1L\naF2.0\n' b'ac__builtin__\ncomple' b'x\np1\n(F3.0\nF0.0\ntp2\n' b'Rp3\naL1L\naL-1L\naL255' b'L\naL-255L\naL-256L\naL' b'65535L\naL-65535L\naL-' b'65536L\naL2147483647L' b'\naL-2147483647L\naL-2' b'147483648L\na(Vabc\np4' b'\ng4\nccopy_reg\n_recon' b'structor\np5\n(c__main' b'__\nC\np6\nc__builtin__' b'\nobject\np7\nNtp8\nRp9\n' b'(dp10\nVfoo\np11\nL1L\ns' b'Vbar\np12\nL2L\nsbg9\ntp' b'13\nag13\naL5L\na.' ) # Disassembly of DATA0 DATA0_DIS = """\ 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: L LONG 0 9: a APPEND 10: L LONG 1 14: a APPEND 15: F FLOAT 2.0 20: a APPEND 21: c GLOBAL '__builtin__ complex' 42: p PUT 1 45: ( MARK 46: F FLOAT 3.0 51: F FLOAT 0.0 56: t TUPLE (MARK at 45) 57: p PUT 2 60: R REDUCE 61: p PUT 3 64: a APPEND 65: L LONG 1 69: a APPEND 70: L LONG -1 75: a APPEND 76: L LONG 255 82: a APPEND 83: L LONG -255 90: a APPEND 91: L LONG -256 98: a APPEND 99: L LONG 65535 107: a APPEND 108: L LONG -65535 117: a APPEND 118: L LONG -65536 127: a APPEND 128: L LONG 2147483647 141: a APPEND 142: L LONG -2147483647 156: a APPEND 157: L LONG -2147483648 171: a APPEND 172: ( MARK 173: V UNICODE 'abc' 178: p PUT 4 181: g GET 4 184: c GLOBAL 'copy_reg _reconstructor' 209: p PUT 5 212: ( MARK 213: c GLOBAL '__main__ C' 225: p PUT 6 228: c GLOBAL '__builtin__ object' 248: p PUT 7 251: N NONE 252: t TUPLE (MARK at 212) 253: p PUT 8 256: R REDUCE 257: p PUT 9 260: ( MARK 261: d DICT (MARK at 260) 262: p PUT 10 266: V UNICODE 'foo' 271: p PUT 11 275: L LONG 1 279: s SETITEM 280: V UNICODE 'bar' 285: p PUT 12 289: L LONG 2 293: s SETITEM 294: b BUILD 295: g GET 9 298: t TUPLE (MARK at 172) 299: p PUT 13 303: a APPEND 304: g GET 13 308: a APPEND 309: L LONG 5 313: a APPEND 314: . STOP highest protocol among opcodes = 0 """ DATA1 = ( b']q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c__' b'builtin__\ncomplex\nq\x01' b'(G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00t' b'q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ' b'\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff' b'\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00ab' b'cq\x04h\x04ccopy_reg\n_reco' b'nstructor\nq\x05(c__main' b'__\nC\nq\x06c__builtin__\n' b'object\nq\x07Ntq\x08Rq\t}q\n(' b'X\x03\x00\x00\x00fooq\x0bK\x01X\x03\x00\x00\x00bar' b'q\x0cK\x02ubh\ttq\rh\rK\x05e.' ) # Disassembly of DATA1 DATA1_DIS = """\ 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: K BININT1 0 6: K BININT1 1 8: G BINFLOAT 2.0 17: c GLOBAL '__builtin__ complex' 38: q BINPUT 1 40: ( MARK 41: G BINFLOAT 3.0 50: G BINFLOAT 0.0 59: t TUPLE (MARK at 40) 60: q BINPUT 2 62: R REDUCE 63: q BINPUT 3 65: K BININT1 1 67: J BININT -1 72: K BININT1 255 74: J BININT -255 79: J BININT -256 84: M BININT2 65535 87: J BININT -65535 92: J BININT -65536 97: J BININT 2147483647 102: J BININT -2147483647 107: J BININT -2147483648 112: ( MARK 113: X BINUNICODE 'abc' 121: q BINPUT 4 123: h BINGET 4 125: c GLOBAL 'copy_reg _reconstructor' 150: q BINPUT 5 152: ( MARK 153: c GLOBAL '__main__ C' 165: q BINPUT 6 167: c GLOBAL '__builtin__ object' 187: q BINPUT 7 189: N NONE 190: t TUPLE (MARK at 152) 191: q BINPUT 8 193: R REDUCE 194: q BINPUT 9 196: } EMPTY_DICT 197: q BINPUT 10 199: ( MARK 200: X BINUNICODE 'foo' 208: q BINPUT 11 210: K BININT1 1 212: X BINUNICODE 'bar' 220: q BINPUT 12 222: K BININT1 2 224: u SETITEMS (MARK at 199) 225: b BUILD 226: h BINGET 9 228: t TUPLE (MARK at 112) 229: q BINPUT 13 231: h BINGET 13 233: K BININT1 5 235: e APPENDS (MARK at 3) 236: . STOP highest protocol among opcodes = 1 """ DATA2 = ( b'\x80\x02]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c' b'__builtin__\ncomplex\n' b'q\x01G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00' b'\x86q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xff' b'J\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff' b'\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00a' b'bcq\x04h\x04c__main__\nC\nq\x05' b')\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08K\x01' b'X\x03\x00\x00\x00barq\tK\x02ubh\x06tq\nh' b'\nK\x05e.' ) # Disassembly of DATA2 DATA2_DIS = """\ 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: ( MARK 6: K BININT1 0 8: K BININT1 1 10: G BINFLOAT 2.0 19: c GLOBAL '__builtin__ complex' 40: q BINPUT 1 42: G BINFLOAT 3.0 51: G BINFLOAT 0.0 60: \x86 TUPLE2 61: q BINPUT 2 63: R REDUCE 64: q BINPUT 3 66: K BININT1 1 68: J BININT -1 73: K BININT1 255 75: J BININT -255 80: J BININT -256 85: M BININT2 65535 88: J BININT -65535 93: J BININT -65536 98: J BININT 2147483647 103: J BININT -2147483647 108: J BININT -2147483648 113: ( MARK 114: X BINUNICODE 'abc' 122: q BINPUT 4 124: h BINGET 4 126: c GLOBAL '__main__ C' 138: q BINPUT 5 140: ) EMPTY_TUPLE 141: \x81 NEWOBJ 142: q BINPUT 6 144: } EMPTY_DICT 145: q BINPUT 7 147: ( MARK 148: X BINUNICODE 'foo' 156: q BINPUT 8 158: K BININT1 1 160: X BINUNICODE 'bar' 168: q BINPUT 9 170: K BININT1 2 172: u SETITEMS (MARK at 147) 173: b BUILD 174: h BINGET 6 176: t TUPLE (MARK at 113) 177: q BINPUT 10 179: h BINGET 10 181: K BININT1 5 183: e APPENDS (MARK at 5) 184: . STOP highest protocol among opcodes = 2 """ DATA3 = ( b'\x80\x03]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c' b'builtins\ncomplex\nq\x01G' b'@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00\x86q\x02' b'Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff' b'\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7f' b'J\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00abcq' b'\x04h\x04c__main__\nC\nq\x05)\x81q' b'\x06}q\x07(X\x03\x00\x00\x00barq\x08K\x02X\x03\x00' b'\x00\x00fooq\tK\x01ubh\x06tq\nh\nK\x05' b'e.' ) # Disassembly of DATA3 DATA3_DIS = """\ 0: \x80 PROTO 3 2: ] EMPTY_LIST 3: q BINPUT 0 5: ( MARK 6: K BININT1 0 8: K BININT1 1 10: G BINFLOAT 2.0 19: c GLOBAL 'builtins complex' 37: q BINPUT 1 39: G BINFLOAT 3.0 48: G BINFLOAT 0.0 57: \x86 TUPLE2 58: q BINPUT 2 60: R REDUCE 61: q BINPUT 3 63: K BININT1 1 65: J BININT -1 70: K BININT1 255 72: J BININT -255 77: J BININT -256 82: M BININT2 65535 85: J BININT -65535 90: J BININT -65536 95: J BININT 2147483647 100: J BININT -2147483647 105: J BININT -2147483648 110: ( MARK 111: X BINUNICODE 'abc' 119: q BINPUT 4 121: h BINGET 4 123: c GLOBAL '__main__ C' 135: q BINPUT 5 137: ) EMPTY_TUPLE 138: \x81 NEWOBJ 139: q BINPUT 6 141: } EMPTY_DICT 142: q BINPUT 7 144: ( MARK 145: X BINUNICODE 'bar' 153: q BINPUT 8 155: K BININT1 2 157: X BINUNICODE 'foo' 165: q BINPUT 9 167: K BININT1 1 169: u SETITEMS (MARK at 144) 170: b BUILD 171: h BINGET 6 173: t TUPLE (MARK at 110) 174: q BINPUT 10 176: h BINGET 10 178: K BININT1 5 180: e APPENDS (MARK at 5) 181: . STOP highest protocol among opcodes = 2 """ DATA4 = ( b'\x80\x04\x95\xa8\x00\x00\x00\x00\x00\x00\x00]\x94(K\x00K\x01G@' b'\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x07' b'complex\x94\x93\x94G@\x08\x00\x00\x00\x00\x00\x00G' b'\x00\x00\x00\x00\x00\x00\x00\x00\x86\x94R\x94K\x01J\xff\xff\xff\xffK' b'\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ' b'\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(' b'\x8c\x03abc\x94h\x06\x8c\x08__main__\x94\x8c' b'\x01C\x94\x93\x94)\x81\x94}\x94(\x8c\x03bar\x94K\x02\x8c' b'\x03foo\x94K\x01ubh\nt\x94h\x0eK\x05e.' ) # Disassembly of DATA4 DATA4_DIS = """\ 0: \x80 PROTO 4 2: \x95 FRAME 168 11: ] EMPTY_LIST 12: \x94 MEMOIZE 13: ( MARK 14: K BININT1 0 16: K BININT1 1 18: G BINFLOAT 2.0 27: \x8c SHORT_BINUNICODE 'builtins' 37: \x94 MEMOIZE 38: \x8c SHORT_BINUNICODE 'complex' 47: \x94 MEMOIZE 48: \x93 STACK_GLOBAL 49: \x94 MEMOIZE 50: G BINFLOAT 3.0 59: G BINFLOAT 0.0 68: \x86 TUPLE2 69: \x94 MEMOIZE 70: R REDUCE 71: \x94 MEMOIZE 72: K BININT1 1 74: J BININT -1 79: K BININT1 255 81: J BININT -255 86: J BININT -256 91: M BININT2 65535 94: J BININT -65535 99: J BININT -65536 104: J BININT 2147483647 109: J BININT -2147483647 114: J BININT -2147483648 119: ( MARK 120: \x8c SHORT_BINUNICODE 'abc' 125: \x94 MEMOIZE 126: h BINGET 6 128: \x8c SHORT_BINUNICODE '__main__' 138: \x94 MEMOIZE 139: \x8c SHORT_BINUNICODE 'C' 142: \x94 MEMOIZE 143: \x93 STACK_GLOBAL 144: \x94 MEMOIZE 145: ) EMPTY_TUPLE 146: \x81 NEWOBJ 147: \x94 MEMOIZE 148: } EMPTY_DICT 149: \x94 MEMOIZE 150: ( MARK 151: \x8c SHORT_BINUNICODE 'bar' 156: \x94 MEMOIZE 157: K BININT1 2 159: \x8c SHORT_BINUNICODE 'foo' 164: \x94 MEMOIZE 165: K BININT1 1 167: u SETITEMS (MARK at 150) 168: b BUILD 169: h BINGET 10 171: t TUPLE (MARK at 119) 172: \x94 MEMOIZE 173: h BINGET 14 175: K BININT1 5 177: e APPENDS (MARK at 13) 178: . STOP highest protocol among opcodes = 4 """ # set([1,2]) pickled from 2.x with protocol 2 DATA_SET = b'\x80\x02c__builtin__\nset\nq\x00]q\x01(K\x01K\x02e\x85q\x02Rq\x03.' # xrange(5) pickled from 2.x with protocol 2 DATA_XRANGE = b'\x80\x02c__builtin__\nxrange\nq\x00K\x00K\x05K\x01\x87q\x01Rq\x02.' # a SimpleCookie() object pickled from 2.x with protocol 2 DATA_COOKIE = (b'\x80\x02cCookie\nSimpleCookie\nq\x00)\x81q\x01U\x03key' b'q\x02cCookie\nMorsel\nq\x03)\x81q\x04(U\x07commentq\x05U' b'\x00q\x06U\x06domainq\x07h\x06U\x06secureq\x08h\x06U\x07' b'expiresq\th\x06U\x07max-ageq\nh\x06U\x07versionq\x0bh\x06U' b'\x04pathq\x0ch\x06U\x08httponlyq\rh\x06u}q\x0e(U\x0b' b'coded_valueq\x0fU\x05valueq\x10h\x10h\x10h\x02h\x02ubs}q\x11b.') # set([3]) pickled from 2.x with protocol 2 DATA_SET2 = b'\x80\x02c__builtin__\nset\nq\x00]q\x01K\x03a\x85q\x02Rq\x03.' python2_exceptions_without_args = ( ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, DeprecationWarning, EOFError, EnvironmentError, Exception, FloatingPointError, FutureWarning, GeneratorExit, IOError, ImportError, ImportWarning, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError, PendingDeprecationWarning, ReferenceError, RuntimeError, RuntimeWarning, # StandardError is gone in Python 3, we map it to Exception StopIteration, SyntaxError, SyntaxWarning, SystemError, SystemExit, TabError, TypeError, UnboundLocalError, UnicodeError, UnicodeWarning, UserWarning, ValueError, Warning, ZeroDivisionError, ) exception_pickle = b'\x80\x02cexceptions\n?\nq\x00)Rq\x01.' # UnicodeEncodeError object pickled from 2.x with protocol 2 DATA_UEERR = (b'\x80\x02cexceptions\nUnicodeEncodeError\n' b'q\x00(U\x05asciiq\x01X\x03\x00\x00\x00fooq\x02K\x00K\x01' b'U\x03badq\x03tq\x04Rq\x05.') def create_data(): c = C() c.foo = 1 c.bar = 2 x = [0, 1, 2.0, 3.0+0j] # Append some integer test cases at cPickle.c's internal size # cutoffs. uint1max = 0xff uint2max = 0xffff int4max = 0x7fffffff x.extend([1, -1, uint1max, -uint1max, -uint1max-1, uint2max, -uint2max, -uint2max-1, int4max, -int4max, -int4max-1]) y = ('abc', 'abc', c, c) x.append(y) x.append(y) x.append(5) return x class AbstractUnpickleTests(unittest.TestCase): # Subclass must define self.loads. _testdata = create_data() def assert_is_copy(self, obj, objcopy, msg=None): """Utility method to verify if two objects are copies of each others. """ if msg is None: msg = "{!r} is not a copy of {!r}".format(obj, objcopy) self.assertEqual(obj, objcopy, msg=msg) self.assertIs(type(obj), type(objcopy), msg=msg) if hasattr(obj, '__dict__'): self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg) self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg) if hasattr(obj, '__slots__'): self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg) for slot in obj.__slots__: self.assertEqual( hasattr(obj, slot), hasattr(objcopy, slot), msg=msg) self.assertEqual(getattr(obj, slot, None), getattr(objcopy, slot, None), msg=msg) def check_unpickling_error(self, errors, data): with self.subTest(data=data), \ self.assertRaises(errors): try: self.loads(data) except BaseException as exc: if support.verbose > 1: print('%-32r - %s: %s' % (data, exc.__class__.__name__, exc)) raise def test_load_from_data0(self): self.assert_is_copy(self._testdata, self.loads(DATA0)) def test_load_from_data1(self): self.assert_is_copy(self._testdata, self.loads(DATA1)) def test_load_from_data2(self): self.assert_is_copy(self._testdata, self.loads(DATA2)) def test_load_from_data3(self): self.assert_is_copy(self._testdata, self.loads(DATA3)) def test_load_from_data4(self): self.assert_is_copy(self._testdata, self.loads(DATA4)) def test_load_classic_instance(self): # See issue5180. Test loading 2.x pickles that # contain an instance of old style class. for X, args in [(C, ()), (D, ('x',)), (E, ())]: xname = X.__name__.encode('ascii') # Protocol 0 (text mode pickle): """ 0: ( MARK 1: i INST '__main__ X' (MARK at 0) 13: p PUT 0 16: ( MARK 17: d DICT (MARK at 16) 18: p PUT 1 21: b BUILD 22: . STOP """ pickle0 = (b"(i__main__\n" b"X\n" b"p0\n" b"(dp1\nb.").replace(b'X', xname) self.assert_is_copy(X(*args), self.loads(pickle0)) # Protocol 1 (binary mode pickle) """ 0: ( MARK 1: c GLOBAL '__main__ X' 13: q BINPUT 0 15: o OBJ (MARK at 0) 16: q BINPUT 1 18: } EMPTY_DICT 19: q BINPUT 2 21: b BUILD 22: . STOP """ pickle1 = (b'(c__main__\n' b'X\n' b'q\x00oq\x01}q\x02b.').replace(b'X', xname) self.assert_is_copy(X(*args), self.loads(pickle1)) # Protocol 2 (pickle2 = b'\x80\x02' + pickle1) """ 0: \x80 PROTO 2 2: ( MARK 3: c GLOBAL '__main__ X' 15: q BINPUT 0 17: o OBJ (MARK at 2) 18: q BINPUT 1 20: } EMPTY_DICT 21: q BINPUT 2 23: b BUILD 24: . STOP """ pickle2 = (b'\x80\x02(c__main__\n' b'X\n' b'q\x00oq\x01}q\x02b.').replace(b'X', xname) self.assert_is_copy(X(*args), self.loads(pickle2)) def test_maxint64(self): maxint64 = (1 << 63) - 1 data = b'I' + str(maxint64).encode("ascii") + b'\n.' got = self.loads(data) self.assert_is_copy(maxint64, got) # Try too with a bogus literal. data = b'I' + str(maxint64).encode("ascii") + b'JUNK\n.' self.check_unpickling_error(ValueError, data) def test_unpickle_from_2x(self): # Unpickle non-trivial data from Python 2.x. loaded = self.loads(DATA_SET) self.assertEqual(loaded, set([1, 2])) loaded = self.loads(DATA_XRANGE) self.assertEqual(type(loaded), type(range(0))) self.assertEqual(list(loaded), list(range(5))) loaded = self.loads(DATA_COOKIE) self.assertEqual(type(loaded), SimpleCookie) self.assertEqual(list(loaded.keys()), ["key"]) self.assertEqual(loaded["key"].value, "value") # Exception objects without arguments pickled from 2.x with protocol 2 for exc in python2_exceptions_without_args: data = exception_pickle.replace(b'?', exc.__name__.encode("ascii")) loaded = self.loads(data) self.assertIs(type(loaded), exc) # StandardError is mapped to Exception, test that separately loaded = self.loads(exception_pickle.replace(b'?', b'StandardError')) self.assertIs(type(loaded), Exception) loaded = self.loads(DATA_UEERR) self.assertIs(type(loaded), UnicodeEncodeError) self.assertEqual(loaded.object, "foo") self.assertEqual(loaded.encoding, "ascii") self.assertEqual(loaded.start, 0) self.assertEqual(loaded.end, 1) self.assertEqual(loaded.reason, "bad") def test_load_python2_str_as_bytes(self): # From Python 2: pickle.dumps('a\x00\xa0', protocol=0) self.assertEqual(self.loads(b"S'a\\x00\\xa0'\n.", encoding="bytes"), b'a\x00\xa0') # From Python 2: pickle.dumps('a\x00\xa0', protocol=1) self.assertEqual(self.loads(b'U\x03a\x00\xa0.', encoding="bytes"), b'a\x00\xa0') # From Python 2: pickle.dumps('a\x00\xa0', protocol=2) self.assertEqual(self.loads(b'\x80\x02U\x03a\x00\xa0.', encoding="bytes"), b'a\x00\xa0') def test_load_python2_unicode_as_str(self): # From Python 2: pickle.dumps(u'π', protocol=0) self.assertEqual(self.loads(b'V\\u03c0\n.', encoding='bytes'), 'π') # From Python 2: pickle.dumps(u'π', protocol=1) self.assertEqual(self.loads(b'X\x02\x00\x00\x00\xcf\x80.', encoding="bytes"), 'π') # From Python 2: pickle.dumps(u'π', protocol=2) self.assertEqual(self.loads(b'\x80\x02X\x02\x00\x00\x00\xcf\x80.', encoding="bytes"), 'π') def test_load_long_python2_str_as_bytes(self): # From Python 2: pickle.dumps('x' * 300, protocol=1) self.assertEqual(self.loads(pickle.BINSTRING + struct.pack("<I", 300) + b'x' * 300 + pickle.STOP, encoding='bytes'), b'x' * 300) def test_constants(self): self.assertIsNone(self.loads(b'N.')) self.assertIs(self.loads(b'\x88.'), True) self.assertIs(self.loads(b'\x89.'), False) self.assertIs(self.loads(b'I01\n.'), True) self.assertIs(self.loads(b'I00\n.'), False) def test_empty_bytestring(self): # issue 11286 empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r') self.assertEqual(empty, '') def test_short_binbytes(self): dumped = b'\x80\x03C\x04\xe2\x82\xac\x00.' self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00') def test_binbytes(self): dumped = b'\x80\x03B\x04\x00\x00\x00\xe2\x82\xac\x00.' self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00') @requires_32b def test_negative_32b_binbytes(self): # On 32-bit builds, a BINBYTES of 2**31 or more is refused dumped = b'\x80\x03B\xff\xff\xff\xffxyzq\x00.' self.check_unpickling_error((pickle.UnpicklingError, OverflowError), dumped) @requires_32b def test_negative_32b_binunicode(self): # On 32-bit builds, a BINUNICODE of 2**31 or more is refused dumped = b'\x80\x03X\xff\xff\xff\xffxyzq\x00.' self.check_unpickling_error((pickle.UnpicklingError, OverflowError), dumped) def test_short_binunicode(self): dumped = b'\x80\x04\x8c\x04\xe2\x82\xac\x00.' self.assertEqual(self.loads(dumped), '\u20ac\x00') def test_misc_get(self): self.check_unpickling_error(KeyError, b'g0\np0') self.assert_is_copy([(100,), (100,)], self.loads(b'((Kdtp0\nh\x00l.))')) def test_binbytes8(self): dumped = b'\x80\x04\x8e\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.' self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00') def test_binunicode8(self): dumped = b'\x80\x04\x8d\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.' self.assertEqual(self.loads(dumped), '\u20ac\x00') @requires_32b def test_large_32b_binbytes8(self): dumped = b'\x80\x04\x8e\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.' self.check_unpickling_error((pickle.UnpicklingError, OverflowError), dumped) @requires_32b def test_large_32b_binunicode8(self): dumped = b'\x80\x04\x8d\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.' self.check_unpickling_error((pickle.UnpicklingError, OverflowError), dumped) def test_get(self): pickled = b'((lp100000\ng100000\nt.' unpickled = self.loads(pickled) self.assertEqual(unpickled, ([],)*2) self.assertIs(unpickled[0], unpickled[1]) def test_binget(self): pickled = b'(]q\xffh\xfft.' unpickled = self.loads(pickled) self.assertEqual(unpickled, ([],)*2) self.assertIs(unpickled[0], unpickled[1]) def test_long_binget(self): pickled = b'(]r\x00\x00\x01\x00j\x00\x00\x01\x00t.' unpickled = self.loads(pickled) self.assertEqual(unpickled, ([],)*2) self.assertIs(unpickled[0], unpickled[1]) def test_dup(self): pickled = b'((l2t.' unpickled = self.loads(pickled) self.assertEqual(unpickled, ([],)*2) self.assertIs(unpickled[0], unpickled[1]) def test_negative_put(self): # Issue #12847 dumped = b'Va\np-1\n.' self.check_unpickling_error(ValueError, dumped) @requires_32b def test_negative_32b_binput(self): # Issue #12847 dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.' self.check_unpickling_error(ValueError, dumped) def test_badly_escaped_string(self): self.check_unpickling_error(ValueError, b"S'\\'\n.") def test_badly_quoted_string(self): # Issue #17710 badpickles = [b"S'\n.", b'S"\n.', b'S\' \n.', b'S" \n.', b'S\'"\n.', b'S"\'\n.', b"S' ' \n.", b'S" " \n.', b"S ''\n.", b'S ""\n.', b'S \n.', b'S\n.', b'S.'] for p in badpickles: self.check_unpickling_error(pickle.UnpicklingError, p) def test_correctly_quoted_string(self): goodpickles = [(b"S''\n.", ''), (b'S""\n.', ''), (b'S"\\n"\n.', '\n'), (b"S'\\n'\n.", '\n')] for p, expected in goodpickles: self.assertEqual(self.loads(p), expected) def test_frame_readline(self): pickled = b'\x80\x04\x95\x05\x00\x00\x00\x00\x00\x00\x00I42\n.' # 0: \x80 PROTO 4 # 2: \x95 FRAME 5 # 11: I INT 42 # 15: . STOP self.assertEqual(self.loads(pickled), 42) def test_compat_unpickle(self): # xrange(1, 7) pickled = b'\x80\x02c__builtin__\nxrange\nK\x01K\x07K\x01\x87R.' unpickled = self.loads(pickled) self.assertIs(type(unpickled), range) self.assertEqual(unpickled, range(1, 7)) self.assertEqual(list(unpickled), [1, 2, 3, 4, 5, 6]) # reduce pickled = b'\x80\x02c__builtin__\nreduce\n.' self.assertIs(self.loads(pickled), functools.reduce) # whichdb.whichdb pickled = b'\x80\x02cwhichdb\nwhichdb\n.' self.assertIs(self.loads(pickled), dbm.whichdb) # Exception(), StandardError() for name in (b'Exception', b'StandardError'): pickled = (b'\x80\x02cexceptions\n' + name + b'\nU\x03ugh\x85R.') unpickled = self.loads(pickled) self.assertIs(type(unpickled), Exception) self.assertEqual(str(unpickled), 'ugh') # UserDict.UserDict({1: 2}), UserDict.IterableUserDict({1: 2}) for name in (b'UserDict', b'IterableUserDict'): pickled = (b'\x80\x02(cUserDict\n' + name +
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_eof.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_eof.py
"""test script for a few new invalid token catches""" import unittest from test import support class EOFTestCase(unittest.TestCase): def test_EOFC(self): expect = "EOL while scanning string literal (<string>, line 1)" try: eval("""'this is a test\ """) except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise support.TestFailed def test_EOFS(self): expect = ("EOF while scanning triple-quoted string literal " "(<string>, line 1)") try: eval("""'''this is a test""") except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise support.TestFailed 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_socketserver.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socketserver.py
""" Test suite for socketserver. """ import contextlib import io import os import select import signal import socket import tempfile import threading import unittest import socketserver import test.support from test.support import reap_children, reap_threads, verbose test.support.requires("network") TEST_STR = b"hello world\n" HOST = test.support.HOST HAVE_UNIX_SOCKETS = hasattr(socket, "AF_UNIX") requires_unix_sockets = unittest.skipUnless(HAVE_UNIX_SOCKETS, 'requires Unix sockets') HAVE_FORKING = hasattr(os, "fork") requires_forking = unittest.skipUnless(HAVE_FORKING, 'requires forking') def signal_alarm(n): """Call signal.alarm when it exists (i.e. not on Windows).""" if hasattr(signal, 'alarm'): signal.alarm(n) # Remember real select() to avoid interferences with mocking _real_select = select.select def receive(sock, n, timeout=20): r, w, x = _real_select([sock], [], [], timeout) if sock in r: return sock.recv(n) else: raise RuntimeError("timed out on %r" % (sock,)) if HAVE_UNIX_SOCKETS and HAVE_FORKING: class ForkingUnixStreamServer(socketserver.ForkingMixIn, socketserver.UnixStreamServer): pass class ForkingUnixDatagramServer(socketserver.ForkingMixIn, socketserver.UnixDatagramServer): pass @contextlib.contextmanager def simple_subprocess(testcase): """Tests that a custom child process is not waited on (Issue 1540386)""" pid = os.fork() if pid == 0: # Don't raise an exception; it would be caught by the test harness. os._exit(72) try: yield None except: raise finally: pid2, status = os.waitpid(pid, 0) testcase.assertEqual(pid2, pid) testcase.assertEqual(72 << 8, status) class SocketServerTest(unittest.TestCase): """Test all socket servers.""" def setUp(self): signal_alarm(60) # Kill deadlocks after 60 seconds. self.port_seed = 0 self.test_files = [] def tearDown(self): signal_alarm(0) # Didn't deadlock. reap_children() for fn in self.test_files: try: os.remove(fn) except OSError: pass self.test_files[:] = [] def pickaddr(self, proto): if proto == socket.AF_INET: return (HOST, 0) else: # XXX: We need a way to tell AF_UNIX to pick its own name # like AF_INET provides port==0. dir = None fn = tempfile.mktemp(prefix='unix_socket.', dir=dir) self.test_files.append(fn) return fn def make_server(self, addr, svrcls, hdlrbase): class MyServer(svrcls): def handle_error(self, request, client_address): self.close_request(request) raise class MyHandler(hdlrbase): def handle(self): line = self.rfile.readline() self.wfile.write(line) if verbose: print("creating server") try: server = MyServer(addr, MyHandler) except PermissionError as e: # Issue 29184: cannot bind() a Unix socket on Android. self.skipTest('Cannot create server (%s, %s): %s' % (svrcls, addr, e)) self.assertEqual(server.server_address, server.socket.getsockname()) return server @reap_threads def run_server(self, svrcls, hdlrbase, testfunc): server = self.make_server(self.pickaddr(svrcls.address_family), svrcls, hdlrbase) # We had the OS pick a port, so pull the real address out of # the server. addr = server.server_address if verbose: print("ADDR =", addr) print("CLASS =", svrcls) t = threading.Thread( name='%s serving' % svrcls, target=server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval':0.01}) t.daemon = True # In case this function raises. t.start() if verbose: print("server running") for i in range(3): if verbose: print("test client", i) testfunc(svrcls.address_family, addr) if verbose: print("waiting for server") server.shutdown() t.join() server.server_close() self.assertEqual(-1, server.socket.fileno()) if HAVE_FORKING and isinstance(server, socketserver.ForkingMixIn): # bpo-31151: Check that ForkingMixIn.server_close() waits until # all children completed self.assertFalse(server.active_children) if verbose: print("done") def stream_examine(self, proto, addr): s = socket.socket(proto, socket.SOCK_STREAM) s.connect(addr) s.sendall(TEST_STR) buf = data = receive(s, 100) while data and b'\n' not in buf: data = receive(s, 100) buf += data self.assertEqual(buf, TEST_STR) s.close() def dgram_examine(self, proto, addr): s = socket.socket(proto, socket.SOCK_DGRAM) if HAVE_UNIX_SOCKETS and proto == socket.AF_UNIX: s.bind(self.pickaddr(proto)) s.sendto(TEST_STR, addr) buf = data = receive(s, 100) while data and b'\n' not in buf: data = receive(s, 100) buf += data self.assertEqual(buf, TEST_STR) s.close() def test_TCPServer(self): self.run_server(socketserver.TCPServer, socketserver.StreamRequestHandler, self.stream_examine) def test_ThreadingTCPServer(self): self.run_server(socketserver.ThreadingTCPServer, socketserver.StreamRequestHandler, self.stream_examine) @requires_forking def test_ForkingTCPServer(self): with simple_subprocess(self): self.run_server(socketserver.ForkingTCPServer, socketserver.StreamRequestHandler, self.stream_examine) @requires_unix_sockets def test_UnixStreamServer(self): self.run_server(socketserver.UnixStreamServer, socketserver.StreamRequestHandler, self.stream_examine) @requires_unix_sockets def test_ThreadingUnixStreamServer(self): self.run_server(socketserver.ThreadingUnixStreamServer, socketserver.StreamRequestHandler, self.stream_examine) @requires_unix_sockets @requires_forking def test_ForkingUnixStreamServer(self): with simple_subprocess(self): self.run_server(ForkingUnixStreamServer, socketserver.StreamRequestHandler, self.stream_examine) def test_UDPServer(self): self.run_server(socketserver.UDPServer, socketserver.DatagramRequestHandler, self.dgram_examine) def test_ThreadingUDPServer(self): self.run_server(socketserver.ThreadingUDPServer, socketserver.DatagramRequestHandler, self.dgram_examine) @requires_forking def test_ForkingUDPServer(self): with simple_subprocess(self): self.run_server(socketserver.ForkingUDPServer, socketserver.DatagramRequestHandler, self.dgram_examine) @requires_unix_sockets def test_UnixDatagramServer(self): self.run_server(socketserver.UnixDatagramServer, socketserver.DatagramRequestHandler, self.dgram_examine) @requires_unix_sockets def test_ThreadingUnixDatagramServer(self): self.run_server(socketserver.ThreadingUnixDatagramServer, socketserver.DatagramRequestHandler, self.dgram_examine) @requires_unix_sockets @requires_forking def test_ForkingUnixDatagramServer(self): self.run_server(ForkingUnixDatagramServer, socketserver.DatagramRequestHandler, self.dgram_examine) @reap_threads def test_shutdown(self): # Issue #2302: shutdown() should always succeed in making an # other thread leave serve_forever(). class MyServer(socketserver.TCPServer): pass class MyHandler(socketserver.StreamRequestHandler): pass threads = [] for i in range(20): s = MyServer((HOST, 0), MyHandler) t = threading.Thread( name='MyServer serving', target=s.serve_forever, kwargs={'poll_interval':0.01}) t.daemon = True # In case this function raises. threads.append((t, s)) for t, s in threads: t.start() s.shutdown() for t, s in threads: t.join() s.server_close() def test_tcpserver_bind_leak(self): # Issue #22435: the server socket wouldn't be closed if bind()/listen() # failed. # Create many servers for which bind() will fail, to see if this result # in FD exhaustion. for i in range(1024): with self.assertRaises(OverflowError): socketserver.TCPServer((HOST, -1), socketserver.StreamRequestHandler) def test_context_manager(self): with socketserver.TCPServer((HOST, 0), socketserver.StreamRequestHandler) as server: pass self.assertEqual(-1, server.socket.fileno()) class ErrorHandlerTest(unittest.TestCase): """Test that the servers pass normal exceptions from the handler to handle_error(), and that exiting exceptions like SystemExit and KeyboardInterrupt are not passed.""" def tearDown(self): test.support.unlink(test.support.TESTFN) def test_sync_handled(self): BaseErrorTestServer(ValueError) self.check_result(handled=True) def test_sync_not_handled(self): with self.assertRaises(SystemExit): BaseErrorTestServer(SystemExit) self.check_result(handled=False) def test_threading_handled(self): ThreadingErrorTestServer(ValueError) self.check_result(handled=True) def test_threading_not_handled(self): ThreadingErrorTestServer(SystemExit) self.check_result(handled=False) @requires_forking def test_forking_handled(self): ForkingErrorTestServer(ValueError) self.check_result(handled=True) @requires_forking def test_forking_not_handled(self): ForkingErrorTestServer(SystemExit) self.check_result(handled=False) def check_result(self, handled): with open(test.support.TESTFN) as log: expected = 'Handler called\n' + 'Error handled\n' * handled self.assertEqual(log.read(), expected) class BaseErrorTestServer(socketserver.TCPServer): def __init__(self, exception): self.exception = exception super().__init__((HOST, 0), BadHandler) with socket.create_connection(self.server_address): pass try: self.handle_request() finally: self.server_close() self.wait_done() def handle_error(self, request, client_address): with open(test.support.TESTFN, 'a') as log: log.write('Error handled\n') def wait_done(self): pass class BadHandler(socketserver.BaseRequestHandler): def handle(self): with open(test.support.TESTFN, 'a') as log: log.write('Handler called\n') raise self.server.exception('Test error') class ThreadingErrorTestServer(socketserver.ThreadingMixIn, BaseErrorTestServer): def __init__(self, *pos, **kw): self.done = threading.Event() super().__init__(*pos, **kw) def shutdown_request(self, *pos, **kw): super().shutdown_request(*pos, **kw) self.done.set() def wait_done(self): self.done.wait() if HAVE_FORKING: class ForkingErrorTestServer(socketserver.ForkingMixIn, BaseErrorTestServer): pass class SocketWriterTest(unittest.TestCase): def test_basics(self): class Handler(socketserver.StreamRequestHandler): def handle(self): self.server.wfile = self.wfile self.server.wfile_fileno = self.wfile.fileno() self.server.request_fileno = self.request.fileno() server = socketserver.TCPServer((HOST, 0), Handler) self.addCleanup(server.server_close) s = socket.socket( server.address_family, socket.SOCK_STREAM, socket.IPPROTO_TCP) with s: s.connect(server.server_address) server.handle_request() self.assertIsInstance(server.wfile, io.BufferedIOBase) self.assertEqual(server.wfile_fileno, server.request_fileno) def test_write(self): # Test that wfile.write() sends data immediately, and that it does # not truncate sends when interrupted by a Unix signal pthread_kill = test.support.get_attribute(signal, 'pthread_kill') class Handler(socketserver.StreamRequestHandler): def handle(self): self.server.sent1 = self.wfile.write(b'write data\n') # Should be sent immediately, without requiring flush() self.server.received = self.rfile.readline() big_chunk = b'\0' * test.support.SOCK_MAX_SIZE self.server.sent2 = self.wfile.write(big_chunk) server = socketserver.TCPServer((HOST, 0), Handler) self.addCleanup(server.server_close) interrupted = threading.Event() def signal_handler(signum, frame): interrupted.set() original = signal.signal(signal.SIGUSR1, signal_handler) self.addCleanup(signal.signal, signal.SIGUSR1, original) response1 = None received2 = None main_thread = threading.get_ident() def run_client(): s = socket.socket(server.address_family, socket.SOCK_STREAM, socket.IPPROTO_TCP) with s, s.makefile('rb') as reader: s.connect(server.server_address) nonlocal response1 response1 = reader.readline() s.sendall(b'client response\n') reader.read(100) # The main thread should now be blocking in a send() syscall. # But in theory, it could get interrupted by other signals, # and then retried. So keep sending the signal in a loop, in # case an earlier signal happens to be delivered at an # inconvenient moment. while True: pthread_kill(main_thread, signal.SIGUSR1) if interrupted.wait(timeout=float(1)): break nonlocal received2 received2 = len(reader.read()) background = threading.Thread(target=run_client) background.start() server.handle_request() background.join() self.assertEqual(server.sent1, len(response1)) self.assertEqual(response1, b'write data\n') self.assertEqual(server.received, b'client response\n') self.assertEqual(server.sent2, test.support.SOCK_MAX_SIZE) self.assertEqual(received2, test.support.SOCK_MAX_SIZE - 100) class MiscTestCase(unittest.TestCase): def test_all(self): # objects defined in the module should be in __all__ expected = [] for name in dir(socketserver): if not name.startswith('_'): mod_object = getattr(socketserver, name) if getattr(mod_object, '__module__', None) == 'socketserver': expected.append(name) self.assertCountEqual(socketserver.__all__, expected) def test_shutdown_request_called_if_verify_request_false(self): # Issue #26309: BaseServer should call shutdown_request even if # verify_request is False class MyServer(socketserver.TCPServer): def verify_request(self, request, client_address): return False shutdown_called = 0 def shutdown_request(self, request): self.shutdown_called += 1 socketserver.TCPServer.shutdown_request(self, request) server = MyServer((HOST, 0), socketserver.StreamRequestHandler) s = socket.socket(server.address_family, socket.SOCK_STREAM) s.connect(server.server_address) s.close() server.handle_request() self.assertEqual(server.shutdown_called, 1) server.server_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_dataclasses.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dataclasses.py
# Deliberately use "from dataclasses import *". Every name in __all__ # is tested, so they all must be present. This is a way to catch # missing ones. from dataclasses import * import pickle import inspect import builtins import unittest from unittest.mock import Mock from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional from typing import get_type_hints from collections import deque, OrderedDict, namedtuple from functools import total_ordering import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation. import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation. # Just any custom exception we can catch. class CustomError(Exception): pass class TestCase(unittest.TestCase): def test_no_fields(self): @dataclass class C: pass o = C() self.assertEqual(len(fields(C)), 0) def test_no_fields_but_member_variable(self): @dataclass class C: i = 0 o = C() self.assertEqual(len(fields(C)), 0) def test_one_field_no_default(self): @dataclass class C: x: int o = C(42) self.assertEqual(o.x, 42) def test_field_default_default_factory_error(self): msg = "cannot specify both default and default_factory" with self.assertRaisesRegex(ValueError, msg): @dataclass class C: x: int = field(default=1, default_factory=int) def test_field_repr(self): int_field = field(default=1, init=True, repr=False) int_field.name = "id" repr_output = repr(int_field) expected_output = "Field(name='id',type=None," \ f"default=1,default_factory={MISSING!r}," \ "init=True,repr=False,hash=None," \ "compare=True,metadata=mappingproxy({})," \ "_field_type=None)" self.assertEqual(repr_output, expected_output) def test_named_init_params(self): @dataclass class C: x: int o = C(x=32) self.assertEqual(o.x, 32) def test_two_fields_one_default(self): @dataclass class C: x: int y: int = 0 o = C(3) self.assertEqual((o.x, o.y), (3, 0)) # Non-defaults following defaults. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument"): @dataclass class C: x: int = 0 y: int # A derived class adds a non-default field after a default one. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument"): @dataclass class B: x: int = 0 @dataclass class C(B): y: int # Override a base class field and add a default to # a field which didn't use to have a default. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument"): @dataclass class B: x: int y: int @dataclass class C(B): x: int = 0 def test_overwrite_hash(self): # Test that declaring this class isn't an error. It should # use the user-provided __hash__. @dataclass(frozen=True) class C: x: int def __hash__(self): return 301 self.assertEqual(hash(C(100)), 301) # Test that declaring this class isn't an error. It should # use the generated __hash__. @dataclass(frozen=True) class C: x: int def __eq__(self, other): return False self.assertEqual(hash(C(100)), hash((100,))) # But this one should generate an exception, because with # unsafe_hash=True, it's an error to have a __hash__ defined. with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'): @dataclass(unsafe_hash=True) class C: def __hash__(self): pass # Creating this class should not generate an exception, # because even though __hash__ exists before @dataclass is # called, (due to __eq__ being defined), since it's None # that's okay. @dataclass(unsafe_hash=True) class C: x: int def __eq__(self): pass # The generated hash function works as we'd expect. self.assertEqual(hash(C(10)), hash((10,))) # Creating this class should generate an exception, because # __hash__ exists and is not None, which it would be if it # had been auto-generated due to __eq__ being defined. with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'): @dataclass(unsafe_hash=True) class C: x: int def __eq__(self): pass def __hash__(self): pass def test_overwrite_fields_in_derived_class(self): # Note that x from C1 replaces x in Base, but the order remains # the same as defined in Base. @dataclass class Base: x: Any = 15.0 y: int = 0 @dataclass class C1(Base): z: int = 10 x: int = 15 o = Base() self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.Base(x=15.0, y=0)') o = C1() self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=15, y=0, z=10)') o = C1(x=5) self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=5, y=0, z=10)') def test_field_named_self(self): @dataclass class C: self: str c=C('foo') self.assertEqual(c.self, 'foo') # Make sure the first parameter is not named 'self'. sig = inspect.signature(C.__init__) first = next(iter(sig.parameters)) self.assertNotEqual('self', first) # But we do use 'self' if no field named self. @dataclass class C: selfx: str # Make sure the first parameter is named 'self'. sig = inspect.signature(C.__init__) first = next(iter(sig.parameters)) self.assertEqual('self', first) def test_field_named_object(self): @dataclass class C: object: str c = C('foo') self.assertEqual(c.object, 'foo') def test_field_named_object_frozen(self): @dataclass(frozen=True) class C: object: str c = C('foo') self.assertEqual(c.object, 'foo') def test_field_named_like_builtin(self): # Attribute names can shadow built-in names # since code generation is used. # Ensure that this is not happening. exclusions = {'None', 'True', 'False'} builtins_names = sorted( b for b in builtins.__dict__.keys() if not b.startswith('__') and b not in exclusions ) attributes = [(name, str) for name in builtins_names] C = make_dataclass('C', attributes) c = C(*[name for name in builtins_names]) for name in builtins_names: self.assertEqual(getattr(c, name), name) def test_field_named_like_builtin_frozen(self): # Attribute names can shadow built-in names # since code generation is used. # Ensure that this is not happening # for frozen data classes. exclusions = {'None', 'True', 'False'} builtins_names = sorted( b for b in builtins.__dict__.keys() if not b.startswith('__') and b not in exclusions ) attributes = [(name, str) for name in builtins_names] C = make_dataclass('C', attributes, frozen=True) c = C(*[name for name in builtins_names]) for name in builtins_names: self.assertEqual(getattr(c, name), name) def test_0_field_compare(self): # Ensure that order=False is the default. @dataclass class C0: pass @dataclass(order=False) class C1: pass for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(), cls()) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(), cls()) @dataclass(order=True) class C: pass self.assertLessEqual(C(), C()) self.assertGreaterEqual(C(), C()) def test_1_field_compare(self): # Ensure that order=False is the default. @dataclass class C0: x: int @dataclass(order=False) class C1: x: int for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(1), cls(1)) self.assertNotEqual(cls(0), cls(1)) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(0), cls(0)) @dataclass(order=True) class C: x: int self.assertLess(C(0), C(1)) self.assertLessEqual(C(0), C(1)) self.assertLessEqual(C(1), C(1)) self.assertGreater(C(1), C(0)) self.assertGreaterEqual(C(1), C(0)) self.assertGreaterEqual(C(1), C(1)) def test_simple_compare(self): # Ensure that order=False is the default. @dataclass class C0: x: int y: int @dataclass(order=False) class C1: x: int y: int for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(0, 0), cls(0, 0)) self.assertEqual(cls(1, 2), cls(1, 2)) self.assertNotEqual(cls(1, 0), cls(0, 0)) self.assertNotEqual(cls(1, 0), cls(1, 1)) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(0, 0), cls(0, 0)) @dataclass(order=True) class C: x: int y: int for idx, fn in enumerate([lambda a, b: a == b, lambda a, b: a <= b, lambda a, b: a >= b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 0), C(0, 0))) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a != b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 0), C(0, 1))) self.assertTrue(fn(C(0, 1), C(1, 0))) self.assertTrue(fn(C(1, 0), C(1, 1))) for idx, fn in enumerate([lambda a, b: a > b, lambda a, b: a >= b, lambda a, b: a != b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 1), C(0, 0))) self.assertTrue(fn(C(1, 0), C(0, 1))) self.assertTrue(fn(C(1, 1), C(1, 0))) def test_compare_subclasses(self): # Comparisons fail for subclasses, even if no fields # are added. @dataclass class B: i: int @dataclass class C(B): pass for idx, (fn, expected) in enumerate([(lambda a, b: a == b, False), (lambda a, b: a != b, True)]): with self.subTest(idx=idx): self.assertEqual(fn(B(0), C(0)), expected) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, "not supported between instances of 'B' and 'C'"): fn(B(0), C(0)) def test_eq_order(self): # Test combining eq and order. for (eq, order, result ) in [ (False, False, 'neither'), (False, True, 'exception'), (True, False, 'eq_only'), (True, True, 'both'), ]: with self.subTest(eq=eq, order=order): if result == 'exception': with self.assertRaisesRegex(ValueError, 'eq must be true if order is true'): @dataclass(eq=eq, order=order) class C: pass else: @dataclass(eq=eq, order=order) class C: pass if result == 'neither': self.assertNotIn('__eq__', C.__dict__) self.assertNotIn('__lt__', C.__dict__) self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) elif result == 'both': self.assertIn('__eq__', C.__dict__) self.assertIn('__lt__', C.__dict__) self.assertIn('__le__', C.__dict__) self.assertIn('__gt__', C.__dict__) self.assertIn('__ge__', C.__dict__) elif result == 'eq_only': self.assertIn('__eq__', C.__dict__) self.assertNotIn('__lt__', C.__dict__) self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) else: assert False, f'unknown result {result!r}' def test_field_no_default(self): @dataclass class C: x: int = field() self.assertEqual(C(5).x, 5) with self.assertRaisesRegex(TypeError, r"__init__\(\) missing 1 required " "positional argument: 'x'"): C() def test_field_default(self): default = object() @dataclass class C: x: object = field(default=default) self.assertIs(C.x, default) c = C(10) self.assertEqual(c.x, 10) # If we delete the instance attribute, we should then see the # class attribute. del c.x self.assertIs(c.x, default) self.assertIs(C().x, default) def test_not_in_repr(self): @dataclass class C: x: int = field(repr=False) with self.assertRaises(TypeError): C() c = C(10) self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C()') @dataclass class C: x: int = field(repr=False) y: int c = C(10, 20) self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C(y=20)') def test_not_in_compare(self): @dataclass class C: x: int = 0 y: int = field(compare=False, default=4) self.assertEqual(C(), C(0, 20)) self.assertEqual(C(1, 10), C(1, 20)) self.assertNotEqual(C(3), C(4, 10)) self.assertNotEqual(C(3, 10), C(4, 10)) def test_hash_field_rules(self): # Test all 6 cases of: # hash=True/False/None # compare=True/False for (hash_, compare, result ) in [ (True, False, 'field' ), (True, True, 'field' ), (False, False, 'absent'), (False, True, 'absent'), (None, False, 'absent'), (None, True, 'field' ), ]: with self.subTest(hash=hash_, compare=compare): @dataclass(unsafe_hash=True) class C: x: int = field(compare=compare, hash=hash_, default=5) if result == 'field': # __hash__ contains the field. self.assertEqual(hash(C(5)), hash((5,))) elif result == 'absent': # The field is not present in the hash. self.assertEqual(hash(C(5)), hash(())) else: assert False, f'unknown result {result!r}' def test_init_false_no_default(self): # If init=False and no default value, then the field won't be # present in the instance. @dataclass class C: x: int = field(init=False) self.assertNotIn('x', C().__dict__) @dataclass class C: x: int y: int = 0 z: int = field(init=False) t: int = 10 self.assertNotIn('z', C(0).__dict__) self.assertEqual(vars(C(5)), {'t': 10, 'x': 5, 'y': 0}) def test_class_marker(self): @dataclass class C: x: int y: str = field(init=False, default=None) z: str = field(repr=False) the_fields = fields(C) # the_fields is a tuple of 3 items, each value # is in __annotations__. self.assertIsInstance(the_fields, tuple) for f in the_fields: self.assertIs(type(f), Field) self.assertIn(f.name, C.__annotations__) self.assertEqual(len(the_fields), 3) self.assertEqual(the_fields[0].name, 'x') self.assertEqual(the_fields[0].type, int) self.assertFalse(hasattr(C, 'x')) self.assertTrue (the_fields[0].init) self.assertTrue (the_fields[0].repr) self.assertEqual(the_fields[1].name, 'y') self.assertEqual(the_fields[1].type, str) self.assertIsNone(getattr(C, 'y')) self.assertFalse(the_fields[1].init) self.assertTrue (the_fields[1].repr) self.assertEqual(the_fields[2].name, 'z') self.assertEqual(the_fields[2].type, str) self.assertFalse(hasattr(C, 'z')) self.assertTrue (the_fields[2].init) self.assertFalse(the_fields[2].repr) def test_field_order(self): @dataclass class B: a: str = 'B:a' b: str = 'B:b' c: str = 'B:c' @dataclass class C(B): b: str = 'C:b' self.assertEqual([(f.name, f.default) for f in fields(C)], [('a', 'B:a'), ('b', 'C:b'), ('c', 'B:c')]) @dataclass class D(B): c: str = 'D:c' self.assertEqual([(f.name, f.default) for f in fields(D)], [('a', 'B:a'), ('b', 'B:b'), ('c', 'D:c')]) @dataclass class E(D): a: str = 'E:a' d: str = 'E:d' self.assertEqual([(f.name, f.default) for f in fields(E)], [('a', 'E:a'), ('b', 'B:b'), ('c', 'D:c'), ('d', 'E:d')]) def test_class_attrs(self): # We only have a class attribute if a default value is # specified, either directly or via a field with a default. default = object() @dataclass class C: x: int y: int = field(repr=False) z: object = default t: int = field(default=100) self.assertFalse(hasattr(C, 'x')) self.assertFalse(hasattr(C, 'y')) self.assertIs (C.z, default) self.assertEqual(C.t, 100) def test_disallowed_mutable_defaults(self): # For the known types, don't allow mutable default values. for typ, empty, non_empty in [(list, [], [1]), (dict, {}, {0:1}), (set, set(), set([1])), ]: with self.subTest(typ=typ): # Can't use a zero-length value. with self.assertRaisesRegex(ValueError, f'mutable default {typ} for field ' 'x is not allowed'): @dataclass class Point: x: typ = empty # Nor a non-zero-length value with self.assertRaisesRegex(ValueError, f'mutable default {typ} for field ' 'y is not allowed'): @dataclass class Point: y: typ = non_empty # Check subtypes also fail. class Subclass(typ): pass with self.assertRaisesRegex(ValueError, f"mutable default .*Subclass'>" ' for field z is not allowed' ): @dataclass class Point: z: typ = Subclass() # Because this is a ClassVar, it can be mutable. @dataclass class C: z: ClassVar[typ] = typ() # Because this is a ClassVar, it can be mutable. @dataclass class C: x: ClassVar[typ] = Subclass() def test_deliberately_mutable_defaults(self): # If a mutable default isn't in the known list of # (list, dict, set), then it's okay. class Mutable: def __init__(self): self.l = [] @dataclass class C: x: Mutable # These 2 instances will share this value of x. lst = Mutable() o1 = C(lst) o2 = C(lst) self.assertEqual(o1, o2) o1.x.l.extend([1, 2]) self.assertEqual(o1, o2) self.assertEqual(o1.x.l, [1, 2]) self.assertIs(o1.x, o2.x) def test_no_options(self): # Call with dataclass(). @dataclass() class C: x: int self.assertEqual(C(42).x, 42) def test_not_tuple(self): # Make sure we can't be compared to a tuple. @dataclass class Point: x: int y: int self.assertNotEqual(Point(1, 2), (1, 2)) # And that we can't compare to another unrelated dataclass. @dataclass class C: x: int y: int self.assertNotEqual(Point(1, 3), C(1, 3)) def test_not_tuple(self): # Test that some of the problems with namedtuple don't happen # here. @dataclass class Point3D: x: int y: int z: int @dataclass class Date: year: int month: int day: int self.assertNotEqual(Point3D(2017, 6, 3), Date(2017, 6, 3)) self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3)) # Make sure we can't unpack. with self.assertRaisesRegex(TypeError, 'unpack'): x, y, z = Point3D(4, 5, 6) # Make sure another class with the same field names isn't # equal. @dataclass class Point3Dv1: x: int = 0 y: int = 0 z: int = 0 self.assertNotEqual(Point3D(0, 0, 0), Point3Dv1()) def test_function_annotations(self): # Some dummy class and instance to use as a default. class F: pass f = F() def validate_class(cls): # First, check __annotations__, even though they're not # function annotations. self.assertEqual(cls.__annotations__['i'], int) self.assertEqual(cls.__annotations__['j'], str) self.assertEqual(cls.__annotations__['k'], F) self.assertEqual(cls.__annotations__['l'], float) self.assertEqual(cls.__annotations__['z'], complex) # Verify __init__. signature = inspect.signature(cls.__init__) # Check the return type, should be None. self.assertIs(signature.return_annotation, None) # Check each parameter. params = iter(signature.parameters.values()) param = next(params) # This is testing an internal name, and probably shouldn't be tested. self.assertEqual(param.name, 'self') param = next(params) self.assertEqual(param.name, 'i') self.assertIs (param.annotation, int) self.assertEqual(param.default, inspect.Parameter.empty) self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'j') self.assertIs (param.annotation, str) self.assertEqual(param.default, inspect.Parameter.empty) self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'k') self.assertIs (param.annotation, F) # Don't test for the default, since it's set to MISSING. self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'l') self.assertIs (param.annotation, float) # Don't test for the default, since it's set to MISSING. self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) self.assertRaises(StopIteration, next, params) @dataclass class C: i: int j: str k: F = f l: float=field(default=None) z: complex=field(default=3+4j, init=False) validate_class(C) # Now repeat with __hash__. @dataclass(frozen=True, unsafe_hash=True) class C: i: int j: str k: F = f l: float=field(default=None) z: complex=field(default=3+4j, init=False) validate_class(C) def test_missing_default(self): # Test that MISSING works the same as a default not being # specified. @dataclass class C: x: int=field(default=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): C() self.assertNotIn('x', C.__dict__) @dataclass class D: x: int with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): D() self.assertNotIn('x', D.__dict__) def test_missing_default_factory(self): # Test that MISSING works the same as a default factory not # being specified (which is really the same as a default not # being specified, too). @dataclass class C: x: int=field(default_factory=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): C() self.assertNotIn('x', C.__dict__) @dataclass class D: x: int=field(default=MISSING, default_factory=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): D() self.assertNotIn('x', D.__dict__) def test_missing_repr(self): self.assertIn('MISSING_TYPE object', repr(MISSING)) def test_dont_include_other_annotations(self): @dataclass class C: i: int def foo(self) -> int: return 4 @property def bar(self) -> int: return 5 self.assertEqual(list(C.__annotations__), ['i']) self.assertEqual(C(10).foo(), 4) self.assertEqual(C(10).bar, 5) self.assertEqual(C(10).i, 10) def test_post_init(self): # Just make sure it gets called @dataclass class C: def __post_init__(self): raise CustomError() with self.assertRaises(CustomError): C() @dataclass class C: i: int = 10 def __post_init__(self): if self.i == 10: raise CustomError() with self.assertRaises(CustomError): C() # post-init gets called, but doesn't raise. This is just # checking that self is used correctly. C(5) # If there's not an __init__, then post-init won't get called. @dataclass(init=False) class C: def __post_init__(self): raise CustomError() # Creating the class won't raise C() @dataclass class C: x: int = 0 def __post_init__(self): self.x *= 2 self.assertEqual(C().x, 0) self.assertEqual(C(2).x, 4) # Make sure that if we're frozen, post-init can't set # attributes. @dataclass(frozen=True) class C: x: int = 0 def __post_init__(self): self.x *= 2 with self.assertRaises(FrozenInstanceError): C() def test_post_init_super(self): # Make sure super() post-init isn't called by default. class B: def __post_init__(self): raise CustomError() @dataclass class C(B): def __post_init__(self): self.x = 5 self.assertEqual(C().x, 5) # Now call super(), and it will raise. @dataclass class C(B): def __post_init__(self): super().__post_init__() with self.assertRaises(CustomError): C() # Make sure post-init is called, even if not defined in our # class. @dataclass class C(B): pass with self.assertRaises(CustomError): C() def test_post_init_staticmethod(self): flag = False @dataclass class C: x: int y: int @staticmethod def __post_init__(): nonlocal flag flag = True
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_codecencodings_cn.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_codecencodings_cn.py
# # test_codecencodings_cn.py # Codec encoding tests for PRC encodings. # from test import multibytecodec_support import unittest class Test_GB2312(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'gb2312' tstring = multibytecodec_support.load_teststring('gb2312') codectests = ( # invalid bytes (b"abc\x81\x81\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x81\x81\xc1\xc4", "replace", "abc\ufffd\ufffd\u804a"), (b"abc\x81\x81\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"), (b"abc\x81\x81\xc1\xc4", "ignore", "abc\u804a"), (b"\xc1\x64", "strict", None), ) class Test_GBK(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'gbk' tstring = multibytecodec_support.load_teststring('gbk') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\u804a"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\u804a"), (b"\x83\x34\x83\x31", "strict", None), ("\u30fb", "strict", None), ) class Test_GB18030(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'gb18030' tstring = multibytecodec_support.load_teststring('gb18030') codectests = ( # invalid bytes (b"abc\x80\x80\xc1\xc4", "strict", None), (b"abc\xc8", "strict", None), (b"abc\x80\x80\xc1\xc4", "replace", "abc\ufffd\ufffd\u804a"), (b"abc\x80\x80\xc1\xc4\xc8", "replace", "abc\ufffd\ufffd\u804a\ufffd"), (b"abc\x80\x80\xc1\xc4", "ignore", "abc\u804a"), (b"abc\x84\x39\x84\x39\xc1\xc4", "replace", "abc\ufffd9\ufffd9\u804a"), ("\u30fb", "strict", b"\x819\xa79"), (b"abc\x84\x32\x80\x80def", "replace", 'abc\ufffd2\ufffd\ufffddef'), (b"abc\x81\x30\x81\x30def", "strict", 'abc\x80def'), (b"abc\x86\x30\x81\x30def", "replace", 'abc\ufffd0\ufffd0def'), # issue29990 (b"\xff\x30\x81\x30", "strict", None), (b"\x81\x30\xff\x30", "strict", None), (b"abc\x81\x39\xff\x39\xc1\xc4", "replace", "abc\ufffd\x39\ufffd\x39\u804a"), (b"abc\xab\x36\xff\x30def", "replace", 'abc\ufffd\x36\ufffd\x30def'), (b"abc\xbf\x38\xff\x32\xc1\xc4", "ignore", "abc\x38\x32\u804a"), ) has_iso10646 = True class Test_HZ(multibytecodec_support.TestBase, unittest.TestCase): encoding = 'hz' tstring = multibytecodec_support.load_teststring('hz') codectests = ( # test '~\n' (3 lines) (b'This sentence is in ASCII.\n' b'The next sentence is in GB.~{<:Ky2;S{#,~}~\n' b'~{NpJ)l6HK!#~}Bye.\n', 'strict', 'This sentence is in ASCII.\n' 'The next sentence is in GB.' '\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002' 'Bye.\n'), # test '~\n' (4 lines) (b'This sentence is in ASCII.\n' b'The next sentence is in GB.~\n' b'~{<:Ky2;S{#,NpJ)l6HK!#~}~\n' b'Bye.\n', 'strict', 'This sentence is in ASCII.\n' 'The next sentence is in GB.' '\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002' 'Bye.\n'), # invalid bytes (b'ab~cd', 'replace', 'ab\uFFFDcd'), (b'ab\xffcd', 'replace', 'ab\uFFFDcd'), (b'ab~{\x81\x81\x41\x44~}cd', 'replace', 'ab\uFFFD\uFFFD\u804Acd'), (b'ab~{\x41\x44~}cd', 'replace', 'ab\u804Acd'), (b"ab~{\x79\x79\x41\x44~}cd", "replace", "ab\ufffd\ufffd\u804acd"), # issue 30003 ('ab~cd', 'strict', b'ab~~cd'), # escape ~ (b'~{Dc~~:C~}', 'strict', None), # ~~ only in ASCII mode (b'~{Dc~\n:C~}', 'strict', None), # ~\n only in ASCII mode ) 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_resource.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_resource.py
import contextlib import sys import os import unittest from test import support import time resource = support.import_module('resource') # This test is checking a few specific problem spots with the resource module. class ResourceTest(unittest.TestCase): def test_args(self): self.assertRaises(TypeError, resource.getrlimit) self.assertRaises(TypeError, resource.getrlimit, 42, 42) self.assertRaises(TypeError, resource.setrlimit) self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) def test_fsize_ismax(self): try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: pass else: # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big # number on a platform with large file support. On these platforms, # we need to test that the get/setrlimit functions properly convert # the number to a C long long and that the conversion doesn't raise # an error. self.assertEqual(resource.RLIM_INFINITY, max) resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) def test_fsize_enforced(self): try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: pass else: # Check to see what happens when the RLIMIT_FSIZE is small. Some # versions of Python were terminated by an uncaught SIGXFSZ, but # pythonrun.c has been fixed to ignore that exception. If so, the # write() should return EFBIG when the limit is exceeded. # At least one platform has an unlimited RLIMIT_FSIZE and attempts # to change it raise ValueError instead. try: try: resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) limit_set = True except ValueError: limit_set = False f = open(support.TESTFN, "wb") try: f.write(b"X" * 1024) try: f.write(b"Y") f.flush() # On some systems (e.g., Ubuntu on hppa) the flush() # doesn't always cause the exception, but the close() # does eventually. Try flushing several times in # an attempt to ensure the file is really synced and # the exception raised. for i in range(5): time.sleep(.1) f.flush() except OSError: if not limit_set: raise if limit_set: # Close will attempt to flush the byte we wrote # Restore limit first to avoid getting a spurious error resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) finally: f.close() finally: if limit_set: resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) support.unlink(support.TESTFN) def test_fsize_toobig(self): # Be sure that setrlimit is checking for really large values too_big = 10**50 try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: pass else: try: resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) except (OverflowError, ValueError): pass try: resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) except (OverflowError, ValueError): pass def test_getrusage(self): self.assertRaises(TypeError, resource.getrusage) self.assertRaises(TypeError, resource.getrusage, 42, 42) usageself = resource.getrusage(resource.RUSAGE_SELF) usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN) # May not be available on all systems. try: usageboth = resource.getrusage(resource.RUSAGE_BOTH) except (ValueError, AttributeError): pass try: usage_thread = resource.getrusage(resource.RUSAGE_THREAD) except (ValueError, AttributeError): pass # Issue 6083: Reference counting bug def test_setrusage_refcount(self): try: limits = resource.getrlimit(resource.RLIMIT_CPU) except AttributeError: pass else: class BadSequence: def __len__(self): return 2 def __getitem__(self, key): if key in (0, 1): return len(tuple(range(1000000))) raise IndexError resource.setrlimit(resource.RLIMIT_CPU, BadSequence()) def test_pagesize(self): pagesize = resource.getpagesize() self.assertIsInstance(pagesize, int) self.assertGreaterEqual(pagesize, 0) @unittest.skipUnless(sys.platform == 'linux', 'test requires Linux') def test_linux_constants(self): for attr in ['MSGQUEUE', 'NICE', 'RTPRIO', 'RTTIME', 'SIGPENDING']: with contextlib.suppress(AttributeError): self.assertIsInstance(getattr(resource, 'RLIMIT_' + attr), int) def test_freebsd_contants(self): for attr in ['SWAP', 'SBSIZE', 'NPTS']: with contextlib.suppress(AttributeError): self.assertIsInstance(getattr(resource, 'RLIMIT_' + attr), int) @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit') @support.requires_linux_version(2, 6, 36) def test_prlimit(self): self.assertRaises(TypeError, resource.prlimit) self.assertRaises(ProcessLookupError, resource.prlimit, -1, resource.RLIMIT_AS) limit = resource.getrlimit(resource.RLIMIT_AS) self.assertEqual(resource.prlimit(0, resource.RLIMIT_AS), limit) self.assertEqual(resource.prlimit(0, resource.RLIMIT_AS, limit), limit) # Issue 20191: Reference counting bug @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit') @support.requires_linux_version(2, 6, 36) def test_prlimit_refcount(self): class BadSeq: def __len__(self): return 2 def __getitem__(self, key): return limits[key] - 1 # new reference limits = resource.getrlimit(resource.RLIMIT_AS) self.assertEqual(resource.prlimit(0, resource.RLIMIT_AS, BadSeq()), limits) def test_main(verbose=None): support.run_unittest(ResourceTest) 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_ftplib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ftplib.py
"""Test script for ftplib module.""" # Modified by Giampaolo Rodola' to test FTP class, IPv6 and TLS # environment import ftplib import asyncore import asynchat import socket import io import errno import os import threading import time try: import ssl except ImportError: ssl = None from unittest import TestCase, skipUnless from test import support from test.support import HOST, HOSTv6 TIMEOUT = 3 # the dummy data returned by server over the data channel when # RETR, LIST, NLST, MLSD commands are issued RETR_DATA = 'abcde12345\r\n' * 1000 LIST_DATA = 'foo\r\nbar\r\n' NLST_DATA = 'foo\r\nbar\r\n' MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n" "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n" "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n" "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n" "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n" "type=file;perm=awr;unique==keVO1+8G4; writable\r\n" "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n" "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n" "type=file;perm=r;unique==keVO1+EG4; two words\r\n" "type=file;perm=r;unique==keVO1+IH4; leading space\r\n" "type=file;perm=r;unique==keVO1+1G4; file1\r\n" "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n" "type=file;perm=r;unique==keVO1+1G4; file2\r\n" "type=file;perm=r;unique==keVO1+1G4; file3\r\n" "type=file;perm=r;unique==keVO1+1G4; file4\r\n") class DummyDTPHandler(asynchat.async_chat): dtp_conn_closed = False def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) self.baseclass = baseclass self.baseclass.last_received_data = '' def handle_read(self): self.baseclass.last_received_data += self.recv(1024).decode('ascii') def handle_close(self): # XXX: this method can be called many times in a row for a single # connection, including in clear-text (non-TLS) mode. # (behaviour witnessed with test_data_connection) if not self.dtp_conn_closed: self.baseclass.push('226 transfer complete') self.close() self.dtp_conn_closed = True def push(self, what): if self.baseclass.next_data is not None: what = self.baseclass.next_data self.baseclass.next_data = None if not what: return self.close_when_done() super(DummyDTPHandler, self).push(what.encode('ascii')) def handle_error(self): raise Exception class DummyFTPHandler(asynchat.async_chat): dtp_handler = DummyDTPHandler def __init__(self, conn): asynchat.async_chat.__init__(self, conn) # tells the socket to handle urgent data inline (ABOR command) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1) self.set_terminator(b"\r\n") self.in_buffer = [] self.dtp = None self.last_received_cmd = None self.last_received_data = '' self.next_response = '' self.next_data = None self.rest = None self.next_retr_data = RETR_DATA self.push('220 welcome') def collect_incoming_data(self, data): self.in_buffer.append(data) def found_terminator(self): line = b''.join(self.in_buffer).decode('ascii') self.in_buffer = [] if self.next_response: self.push(self.next_response) self.next_response = '' cmd = line.split(' ')[0].lower() self.last_received_cmd = cmd 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('550 command "%s" not understood.' %cmd) def handle_error(self): raise Exception def push(self, data): asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n') def cmd_port(self, arg): addr = list(map(int, arg.split(','))) ip = '%d.%d.%d.%d' %tuple(addr[:4]) port = (addr[4] * 256) + addr[5] s = socket.create_connection((ip, port), timeout=TIMEOUT) self.dtp = self.dtp_handler(s, baseclass=self) self.push('200 active data connection established') def cmd_pasv(self, arg): with socket.socket() as sock: sock.bind((self.socket.getsockname()[0], 0)) sock.listen() sock.settimeout(TIMEOUT) ip, port = sock.getsockname()[:2] ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2)) conn, addr = sock.accept() self.dtp = self.dtp_handler(conn, baseclass=self) def cmd_eprt(self, arg): af, ip, port = arg.split(arg[0])[1:-1] port = int(port) s = socket.create_connection((ip, port), timeout=TIMEOUT) self.dtp = self.dtp_handler(s, baseclass=self) self.push('200 active data connection established') def cmd_epsv(self, arg): with socket.socket(socket.AF_INET6) as sock: sock.bind((self.socket.getsockname()[0], 0)) sock.listen() sock.settimeout(TIMEOUT) port = sock.getsockname()[1] self.push('229 entering extended passive mode (|||%d|)' %port) conn, addr = sock.accept() self.dtp = self.dtp_handler(conn, baseclass=self) def cmd_echo(self, arg): # sends back the received string (used by the test suite) self.push(arg) def cmd_noop(self, arg): self.push('200 noop ok') def cmd_user(self, arg): self.push('331 username ok') def cmd_pass(self, arg): self.push('230 password ok') def cmd_acct(self, arg): self.push('230 acct ok') def cmd_rnfr(self, arg): self.push('350 rnfr ok') def cmd_rnto(self, arg): self.push('250 rnto ok') def cmd_dele(self, arg): self.push('250 dele ok') def cmd_cwd(self, arg): self.push('250 cwd ok') def cmd_size(self, arg): self.push('250 1000') def cmd_mkd(self, arg): self.push('257 "%s"' %arg) def cmd_rmd(self, arg): self.push('250 rmd ok') def cmd_pwd(self, arg): self.push('257 "pwd ok"') def cmd_type(self, arg): self.push('200 type ok') def cmd_quit(self, arg): self.push('221 quit ok') self.close() def cmd_abor(self, arg): self.push('226 abor ok') def cmd_stor(self, arg): self.push('125 stor ok') def cmd_rest(self, arg): self.rest = arg self.push('350 rest ok') def cmd_retr(self, arg): self.push('125 retr ok') if self.rest is not None: offset = int(self.rest) else: offset = 0 self.dtp.push(self.next_retr_data[offset:]) self.dtp.close_when_done() self.rest = None def cmd_list(self, arg): self.push('125 list ok') self.dtp.push(LIST_DATA) self.dtp.close_when_done() def cmd_nlst(self, arg): self.push('125 nlst ok') self.dtp.push(NLST_DATA) self.dtp.close_when_done() def cmd_opts(self, arg): self.push('200 opts ok') def cmd_mlsd(self, arg): self.push('125 mlsd ok') self.dtp.push(MLSD_DATA) self.dtp.close_when_done() def cmd_setlongretr(self, arg): # For testing. Next RETR will return long line. self.next_retr_data = 'x' * int(arg) self.push('125 setlongretr ok') class DummyFTPServer(asyncore.dispatcher, threading.Thread): handler = DummyFTPHandler 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() while self.active and asyncore.socket_map: self.active_lock.acquire() asyncore.loop(timeout=0.1, count=1) self.active_lock.release() 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 Exception if ssl is not None: CERTFILE = os.path.join(os.path.dirname(__file__), "keycert3.pem") CAFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") class SSLConnection(asyncore.dispatcher): """An asyncore.dispatcher subclass supporting TLS/SSL.""" _ssl_accepting = False _ssl_closing = False def secure_connection(self): context = ssl.SSLContext() context.load_cert_chain(CERTFILE) socket = context.wrap_socket(self.socket, suppress_ragged_eofs=False, server_side=True, do_handshake_on_connect=False) self.del_channel() self.set_socket(socket) self._ssl_accepting = True def _do_ssl_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]: return self.handle_close() raise except OSError as err: if err.args[0] == errno.ECONNABORTED: return self.handle_close() else: self._ssl_accepting = False def _do_ssl_shutdown(self): self._ssl_closing = True try: self.socket = self.socket.unwrap() except ssl.SSLError as err: if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): return except OSError as err: # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return # from OpenSSL's SSL_shutdown(), corresponding to a # closed socket condition. See also: # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html pass self._ssl_closing = False if getattr(self, '_ccc', False) is False: super(SSLConnection, self).close() else: pass def handle_read_event(self): if self._ssl_accepting: self._do_ssl_handshake() elif self._ssl_closing: self._do_ssl_shutdown() else: super(SSLConnection, self).handle_read_event() def handle_write_event(self): if self._ssl_accepting: self._do_ssl_handshake() elif self._ssl_closing: self._do_ssl_shutdown() else: super(SSLConnection, self).handle_write_event() def send(self, data): try: return super(SSLConnection, self).send(data) except ssl.SSLError as err: if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN, ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): return 0 raise def recv(self, buffer_size): try: return super(SSLConnection, self).recv(buffer_size) except ssl.SSLError as err: if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): return b'' if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN): self.handle_close() return b'' raise def handle_error(self): raise Exception def close(self): if (isinstance(self.socket, ssl.SSLSocket) and self.socket._sslobj is not None): self._do_ssl_shutdown() else: super(SSLConnection, self).close() class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler): """A DummyDTPHandler subclass supporting TLS/SSL.""" def __init__(self, conn, baseclass): DummyDTPHandler.__init__(self, conn, baseclass) if self.baseclass.secure_data_channel: self.secure_connection() class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler): """A DummyFTPHandler subclass supporting TLS/SSL.""" dtp_handler = DummyTLS_DTPHandler def __init__(self, conn): DummyFTPHandler.__init__(self, conn) self.secure_data_channel = False self._ccc = False def cmd_auth(self, line): """Set up secure control channel.""" self.push('234 AUTH TLS successful') self.secure_connection() def cmd_ccc(self, line): self.push('220 Reverting back to clear-text') self._ccc = True self._do_ssl_shutdown() def cmd_pbsz(self, line): """Negotiate size of buffer for secure data transfer. For TLS/SSL the only valid value for the parameter is '0'. Any other value is accepted but ignored. """ self.push('200 PBSZ=0 successful.') def cmd_prot(self, line): """Setup un/secure data channel.""" arg = line.upper() if arg == 'C': self.push('200 Protection set to Clear') self.secure_data_channel = False elif arg == 'P': self.push('200 Protection set to Private') self.secure_data_channel = True else: self.push("502 Unrecognized PROT type (use C or P).") class DummyTLS_FTPServer(DummyFTPServer): handler = DummyTLS_FTPHandler class TestFTPClass(TestCase): def setUp(self): self.server = DummyFTPServer((HOST, 0)) self.server.start() self.client = ftplib.FTP(timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None asyncore.close_all(ignore_all=True) def check_data(self, received, expected): self.assertEqual(len(received), len(expected)) self.assertEqual(received, expected) def test_getwelcome(self): self.assertEqual(self.client.getwelcome(), '220 welcome') def test_sanitize(self): self.assertEqual(self.client.sanitize('foo'), repr('foo')) self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****')) self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****')) def test_exceptions(self): self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r\n0') self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\n0') self.assertRaises(ValueError, self.client.sendcmd, 'echo 40\r0') self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400') self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500') self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599') self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999') def test_all_errors(self): exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm, ftplib.error_proto, ftplib.Error, OSError, EOFError) for x in exceptions: try: raise x('exception not included in all_errors set') except ftplib.all_errors: pass def test_set_pasv(self): # passive mode is supposed to be enabled by default self.assertTrue(self.client.passiveserver) self.client.set_pasv(True) self.assertTrue(self.client.passiveserver) self.client.set_pasv(False) self.assertFalse(self.client.passiveserver) def test_voidcmd(self): self.client.voidcmd('echo 200') self.client.voidcmd('echo 299') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199') self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300') def test_login(self): self.client.login() def test_acct(self): self.client.acct('passwd') def test_rename(self): self.client.rename('a', 'b') self.server.handler_instance.next_response = '200' self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b') def test_delete(self): self.client.delete('foo') self.server.handler_instance.next_response = '199' self.assertRaises(ftplib.error_reply, self.client.delete, 'foo') def test_size(self): self.client.size('foo') def test_mkd(self): dir = self.client.mkd('/foo') self.assertEqual(dir, '/foo') def test_rmd(self): self.client.rmd('foo') def test_cwd(self): dir = self.client.cwd('/foo') self.assertEqual(dir, '250 cwd ok') def test_pwd(self): dir = self.client.pwd() self.assertEqual(dir, 'pwd ok') def test_quit(self): self.assertEqual(self.client.quit(), '221 quit ok') # Ensure the connection gets closed; sock attribute should be None self.assertEqual(self.client.sock, None) def test_abort(self): self.client.abort() def test_retrbinary(self): def callback(data): received.append(data.decode('ascii')) received = [] self.client.retrbinary('retr', callback) self.check_data(''.join(received), RETR_DATA) def test_retrbinary_rest(self): def callback(data): received.append(data.decode('ascii')) for rest in (0, 10, 20): received = [] self.client.retrbinary('retr', callback, rest=rest) self.check_data(''.join(received), RETR_DATA[rest:]) def test_retrlines(self): received = [] self.client.retrlines('retr', received.append) self.check_data(''.join(received), RETR_DATA.replace('\r\n', '')) def test_storbinary(self): f = io.BytesIO(RETR_DATA.encode('ascii')) self.client.storbinary('stor', f) self.check_data(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storbinary('stor', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) def test_storbinary_rest(self): f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii')) for r in (30, '30'): f.seek(0) self.client.storbinary('stor', f, rest=r) self.assertEqual(self.server.handler_instance.rest, str(r)) def test_storlines(self): f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii')) self.client.storlines('stor', f) self.check_data(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) self.client.storlines('stor foo', f, callback=lambda x: flag.append(None)) self.assertTrue(flag) f = io.StringIO(RETR_DATA.replace('\r\n', '\n')) # storlines() expects a binary file, not a text file with support.check_warnings(('', BytesWarning), quiet=True): self.assertRaises(TypeError, self.client.storlines, 'stor foo', f) def test_nlst(self): self.client.nlst() self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1]) def test_dir(self): l = [] self.client.dir(lambda x: l.append(x)) self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', '')) def test_mlsd(self): list(self.client.mlsd()) list(self.client.mlsd(path='/')) list(self.client.mlsd(path='/', facts=['size', 'type'])) ls = list(self.client.mlsd()) for name, facts in ls: self.assertIsInstance(name, str) self.assertIsInstance(facts, dict) self.assertTrue(name) self.assertIn('type', facts) self.assertIn('perm', facts) self.assertIn('unique', facts) def set_data(data): self.server.handler_instance.next_data = data def test_entry(line, type=None, perm=None, unique=None, name=None): type = 'type' if type is None else type perm = 'perm' if perm is None else perm unique = 'unique' if unique is None else unique name = 'name' if name is None else name set_data(line) _name, facts = next(self.client.mlsd()) self.assertEqual(_name, name) self.assertEqual(facts['type'], type) self.assertEqual(facts['perm'], perm) self.assertEqual(facts['unique'], unique) # plain test_entry('type=type;perm=perm;unique=unique; name\r\n') # "=" in fact value test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe") test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type") test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe") test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====") # spaces in name test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me") test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ") test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name") test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e") # ";" in name test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me") test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name") test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;") test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;") # case sensitiveness set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n') _name, facts = next(self.client.mlsd()) for x in facts: self.assertTrue(x.islower()) # no data (directory empty) set_data('') self.assertRaises(StopIteration, next, self.client.mlsd()) set_data('') for x in self.client.mlsd(): self.fail("unexpected data %s" % x) def test_makeport(self): with self.client.makeport(): # IPv4 is in use, just make sure send_eprt has not been used self.assertEqual(self.server.handler_instance.last_received_cmd, 'port') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), timeout=TIMEOUT) conn.close() # IPv4 is in use, just make sure send_epsv has not been used self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv') def test_with_statement(self): self.client.quit() def is_client_connected(): if self.client.sock is None: return False try: self.client.sendcmd('noop') except (OSError, EOFError): return False return True # base test with ftplib.FTP(timeout=TIMEOUT) as self.client: self.client.connect(self.server.host, self.server.port) self.client.sendcmd('noop') self.assertTrue(is_client_connected()) self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') self.assertFalse(is_client_connected()) # QUIT sent inside the with block with ftplib.FTP(timeout=TIMEOUT) as self.client: self.client.connect(self.server.host, self.server.port) self.client.sendcmd('noop') self.client.quit() self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') self.assertFalse(is_client_connected()) # force a wrong response code to be sent on QUIT: error_perm # is expected and the connection is supposed to be closed try: with ftplib.FTP(timeout=TIMEOUT) as self.client: self.client.connect(self.server.host, self.server.port) self.client.sendcmd('noop') self.server.handler_instance.next_response = '550 error on quit' except ftplib.error_perm as err: self.assertEqual(str(err), '550 error on quit') else: self.fail('Exception not raised') # needed to give the threaded server some time to set the attribute # which otherwise would still be == 'noop' time.sleep(0.1) self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') self.assertFalse(is_client_connected()) def test_source_address(self): self.client.quit() port = support.find_unused_port() try: self.client.connect(self.server.host, self.server.port, source_address=(HOST, port)) self.assertEqual(self.client.sock.getsockname()[1], port) self.client.quit() except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise def test_source_address_passive_connection(self): port = support.find_unused_port() self.client.source_address = (HOST, port) try: with self.client.transfercmd('list') as sock: self.assertEqual(sock.getsockname()[1], port) except OSError as e: if e.errno == errno.EADDRINUSE: self.skipTest("couldn't bind to port %d" % port) raise def test_parse257(self): self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar') self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar') self.assertEqual(ftplib.parse257('257 ""'), '') self.assertEqual(ftplib.parse257('257 "" created'), '') self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"') # The 257 response is supposed to include the directory # name and in case it contains embedded double-quotes # they must be doubled (see RFC-959, chapter 7, appendix 2). self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar') self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar') def test_line_too_long(self): self.assertRaises(ftplib.Error, self.client.sendcmd, 'x' * self.client.maxline * 2) def test_retrlines_too_long(self): self.client.sendcmd('SETLONGRETR %d' % (self.client.maxline * 2)) received = [] self.assertRaises(ftplib.Error, self.client.retrlines, 'retr', received.append) def test_storlines_too_long(self): f = io.BytesIO(b'x' * self.client.maxline * 2) self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f) @skipUnless(support.IPV6_ENABLED, "IPv6 not enabled") class TestIPv6Environment(TestCase): def setUp(self): self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6) self.server.start() self.client = ftplib.FTP(timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None asyncore.close_all(ignore_all=True) def test_af(self): self.assertEqual(self.client.af, socket.AF_INET6) def test_makeport(self): with self.client.makeport(): self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), timeout=TIMEOUT) conn.close() self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv') def test_transfer(self): def retr(): def callback(data): received.append(data.decode('ascii')) received = [] self.client.retrbinary('retr', callback) self.assertEqual(len(''.join(received)), len(RETR_DATA)) self.assertEqual(''.join(received), RETR_DATA) self.client.set_pasv(True) retr() self.client.set_pasv(False) retr() @skipUnless(ssl, "SSL not available") class TestTLS_FTPClassMixin(TestFTPClass): """Repeat TestFTPClass tests starting the TLS layer for both control and data connections first. """ def setUp(self): self.server = DummyTLS_FTPServer((HOST, 0)) self.server.start() self.client = ftplib.FTP_TLS(timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) # enable TLS self.client.auth() self.client.prot_p() @skipUnless(ssl, "SSL not available") class TestTLS_FTPClass(TestCase): """Specific TLS_FTP class tests.""" def setUp(self): self.server = DummyTLS_FTPServer((HOST, 0)) self.server.start() self.client = ftplib.FTP_TLS(timeout=TIMEOUT) self.client.connect(self.server.host, self.server.port) def tearDown(self): self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None asyncore.close_all(ignore_all=True) def test_control_connection(self): self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) self.client.auth() self.assertIsInstance(self.client.sock, ssl.SSLSocket) def test_data_connection(self): # clear text with self.client.transfercmd('list') as sock: self.assertNotIsInstance(sock, ssl.SSLSocket) self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) self.assertEqual(self.client.voidresp(), "226 transfer complete") # secured, after PROT P self.client.prot_p() with self.client.transfercmd('list') as sock: self.assertIsInstance(sock, ssl.SSLSocket) # consume from SSL socket to finalize handshake and avoid # "SSLError [SSL] shutdown while in init" self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) self.assertEqual(self.client.voidresp(), "226 transfer complete") # PROT C is issued, the connection must be in cleartext again self.client.prot_c() with self.client.transfercmd('list') as sock: self.assertNotIsInstance(sock, ssl.SSLSocket) self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) self.assertEqual(self.client.voidresp(), "226 transfer complete") def test_login(self): # login() is supposed to implicitly secure the control connection
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_bdb.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bdb.py
""" Test the bdb module. A test defines a list of tuples that may be seen as paired tuples, each pair being defined by 'expect_tuple, set_tuple' as follows: ([event, [lineno[, co_name[, eargs]]]]), (set_type, [sargs]) * 'expect_tuple' describes the expected current state of the Bdb instance. It may be the empty tuple and no check is done in that case. * 'set_tuple' defines the set_*() method to be invoked when the Bdb instance reaches this state. Example of an 'expect_tuple, set_tuple' pair: ('line', 2, 'tfunc_main'), ('step', ) Definitions of the members of the 'expect_tuple': event: Name of the trace event. The set methods that do not give back control to the tracer [1] do not trigger a tracer event and in that case the next 'event' may be 'None' by convention, its value is not checked. [1] Methods that trigger a trace event are set_step(), set_next(), set_return(), set_until() and set_continue(). lineno: Line number. Line numbers are relative to the start of the function when tracing a function in the test_bdb module (i.e. this module). co_name: Name of the function being currently traced. eargs: A tuple: * On an 'exception' event the tuple holds a class object, the current exception must be an instance of this class. * On a 'line' event, the tuple holds a dictionary and a list. The dictionary maps each breakpoint number that has been hit on this line to its hits count. The list holds the list of breakpoint number temporaries that are being deleted. Definitions of the members of the 'set_tuple': set_type: The type of the set method to be invoked. This may be the type of one of the Bdb set methods: 'step', 'next', 'until', 'return', 'continue', 'break', 'quit', or the type of one of the set methods added by test_bdb.Bdb: 'ignore', 'enable', 'disable', 'clear', 'up', 'down'. sargs: The arguments of the set method if any, packed in a tuple. """ import bdb as _bdb import sys import os import unittest import textwrap import importlib import linecache from contextlib import contextmanager from itertools import islice, repeat import test.support class BdbException(Exception): pass class BdbError(BdbException): """Error raised by the Bdb instance.""" class BdbSyntaxError(BdbException): """Syntax error in the test case.""" class BdbNotExpectedError(BdbException): """Unexpected result.""" # When 'dry_run' is set to true, expect tuples are ignored and the actual # state of the tracer is printed after running each set_*() method of the test # case. The full list of breakpoints and their attributes is also printed # after each 'line' event where a breakpoint has been hit. dry_run = 0 def reset_Breakpoint(): _bdb.Breakpoint.next = 1 _bdb.Breakpoint.bplist = {} _bdb.Breakpoint.bpbynumber = [None] def info_breakpoints(): bp_list = [bp for bp in _bdb.Breakpoint.bpbynumber if bp] if not bp_list: return '' header_added = False for bp in bp_list: if not header_added: info = 'BpNum Temp Enb Hits Ignore Where\n' header_added = True disp = 'yes ' if bp.temporary else 'no ' enab = 'yes' if bp.enabled else 'no ' info += ('%-5d %s %s %-4d %-6d at %s:%d' % (bp.number, disp, enab, bp.hits, bp.ignore, os.path.basename(bp.file), bp.line)) if bp.cond: info += '\n\tstop only if %s' % (bp.cond,) info += '\n' return info class Bdb(_bdb.Bdb): """Extend Bdb to enhance test coverage.""" def trace_dispatch(self, frame, event, arg): self.currentbp = None return super().trace_dispatch(frame, event, arg) def set_break(self, filename, lineno, temporary=False, cond=None, funcname=None): if isinstance(funcname, str): if filename == __file__: globals_ = globals() else: module = importlib.import_module(filename[:-3]) globals_ = module.__dict__ func = eval(funcname, globals_) code = func.__code__ filename = code.co_filename lineno = code.co_firstlineno funcname = code.co_name res = super().set_break(filename, lineno, temporary=temporary, cond=cond, funcname=funcname) if isinstance(res, str): raise BdbError(res) return res def get_stack(self, f, t): self.stack, self.index = super().get_stack(f, t) self.frame = self.stack[self.index][0] return self.stack, self.index def set_ignore(self, bpnum): """Increment the ignore count of Breakpoint number 'bpnum'.""" bp = self.get_bpbynumber(bpnum) bp.ignore += 1 def set_enable(self, bpnum): bp = self.get_bpbynumber(bpnum) bp.enabled = True def set_disable(self, bpnum): bp = self.get_bpbynumber(bpnum) bp.enabled = False def set_clear(self, fname, lineno): err = self.clear_break(fname, lineno) if err: raise BdbError(err) def set_up(self): """Move up in the frame stack.""" if not self.index: raise BdbError('Oldest frame') self.index -= 1 self.frame = self.stack[self.index][0] def set_down(self): """Move down in the frame stack.""" if self.index + 1 == len(self.stack): raise BdbError('Newest frame') self.index += 1 self.frame = self.stack[self.index][0] class Tracer(Bdb): """A tracer for testing the bdb module.""" def __init__(self, expect_set, skip=None, dry_run=False, test_case=None): super().__init__(skip=skip) self.expect_set = expect_set self.dry_run = dry_run self.header = ('Dry-run results for %s:' % test_case if test_case is not None else None) self.init_test() def init_test(self): self.cur_except = None self.expect_set_no = 0 self.breakpoint_hits = None self.expected_list = list(islice(self.expect_set, 0, None, 2)) self.set_list = list(islice(self.expect_set, 1, None, 2)) def trace_dispatch(self, frame, event, arg): # On an 'exception' event, call_exc_trace() in Python/ceval.c discards # a BdbException raised by the Tracer instance, so we raise it on the # next trace_dispatch() call that occurs unless the set_quit() or # set_continue() method has been invoked on the 'exception' event. if self.cur_except is not None: raise self.cur_except if event == 'exception': try: res = super().trace_dispatch(frame, event, arg) return res except BdbException as e: self.cur_except = e return self.trace_dispatch else: return super().trace_dispatch(frame, event, arg) def user_call(self, frame, argument_list): # Adopt the same behavior as pdb and, as a side effect, skip also the # first 'call' event when the Tracer is started with Tracer.runcall() # which may be possibly considered as a bug. if not self.stop_here(frame): return self.process_event('call', frame, argument_list) self.next_set_method() def user_line(self, frame): self.process_event('line', frame) if self.dry_run and self.breakpoint_hits: info = info_breakpoints().strip('\n') # Indent each line. for line in info.split('\n'): print(' ' + line) self.delete_temporaries() self.breakpoint_hits = None self.next_set_method() def user_return(self, frame, return_value): self.process_event('return', frame, return_value) self.next_set_method() def user_exception(self, frame, exc_info): self.exc_info = exc_info self.process_event('exception', frame) self.next_set_method() def do_clear(self, arg): # The temporary breakpoints are deleted in user_line(). bp_list = [self.currentbp] self.breakpoint_hits = (bp_list, bp_list) def delete_temporaries(self): if self.breakpoint_hits: for n in self.breakpoint_hits[1]: self.clear_bpbynumber(n) def pop_next(self): self.expect_set_no += 1 try: self.expect = self.expected_list.pop(0) except IndexError: raise BdbNotExpectedError( 'expect_set list exhausted, cannot pop item %d' % self.expect_set_no) self.set_tuple = self.set_list.pop(0) def process_event(self, event, frame, *args): # Call get_stack() to enable walking the stack with set_up() and # set_down(). tb = None if event == 'exception': tb = self.exc_info[2] self.get_stack(frame, tb) # A breakpoint has been hit and it is not a temporary. if self.currentbp is not None and not self.breakpoint_hits: bp_list = [self.currentbp] self.breakpoint_hits = (bp_list, []) # Pop next event. self.event= event self.pop_next() if self.dry_run: self.print_state(self.header) return # Validate the expected results. if self.expect: self.check_equal(self.expect[0], event, 'Wrong event type') self.check_lno_name() if event in ('call', 'return'): self.check_expect_max_size(3) elif len(self.expect) > 3: if event == 'line': bps, temporaries = self.expect[3] bpnums = sorted(bps.keys()) if not self.breakpoint_hits: self.raise_not_expected( 'No breakpoints hit at expect_set item %d' % self.expect_set_no) self.check_equal(bpnums, self.breakpoint_hits[0], 'Breakpoint numbers do not match') self.check_equal([bps[n] for n in bpnums], [self.get_bpbynumber(n).hits for n in self.breakpoint_hits[0]], 'Wrong breakpoint hit count') self.check_equal(sorted(temporaries), self.breakpoint_hits[1], 'Wrong temporary breakpoints') elif event == 'exception': if not isinstance(self.exc_info[1], self.expect[3]): self.raise_not_expected( "Wrong exception at expect_set item %d, got '%s'" % (self.expect_set_no, self.exc_info)) def check_equal(self, expected, result, msg): if expected == result: return self.raise_not_expected("%s at expect_set item %d, got '%s'" % (msg, self.expect_set_no, result)) def check_lno_name(self): """Check the line number and function co_name.""" s = len(self.expect) if s > 1: lineno = self.lno_abs2rel() self.check_equal(self.expect[1], lineno, 'Wrong line number') if s > 2: self.check_equal(self.expect[2], self.frame.f_code.co_name, 'Wrong function name') def check_expect_max_size(self, size): if len(self.expect) > size: raise BdbSyntaxError('Invalid size of the %s expect tuple: %s' % (self.event, self.expect)) def lno_abs2rel(self): fname = self.canonic(self.frame.f_code.co_filename) lineno = self.frame.f_lineno return ((lineno - self.frame.f_code.co_firstlineno + 1) if fname == self.canonic(__file__) else lineno) def lno_rel2abs(self, fname, lineno): return (self.frame.f_code.co_firstlineno + lineno - 1 if (lineno and self.canonic(fname) == self.canonic(__file__)) else lineno) def get_state(self): lineno = self.lno_abs2rel() co_name = self.frame.f_code.co_name state = "('%s', %d, '%s'" % (self.event, lineno, co_name) if self.breakpoint_hits: bps = '{' for n in self.breakpoint_hits[0]: if bps != '{': bps += ', ' bps += '%s: %s' % (n, self.get_bpbynumber(n).hits) bps += '}' bps = '(' + bps + ', ' + str(self.breakpoint_hits[1]) + ')' state += ', ' + bps elif self.event == 'exception': state += ', ' + self.exc_info[0].__name__ state += '), ' return state.ljust(32) + str(self.set_tuple) + ',' def print_state(self, header=None): if header is not None and self.expect_set_no == 1: print() print(header) print('%d: %s' % (self.expect_set_no, self.get_state())) def raise_not_expected(self, msg): msg += '\n' msg += ' Expected: %s\n' % str(self.expect) msg += ' Got: ' + self.get_state() raise BdbNotExpectedError(msg) def next_set_method(self): set_type = self.set_tuple[0] args = self.set_tuple[1] if len(self.set_tuple) == 2 else None set_method = getattr(self, 'set_' + set_type) # The following set methods give back control to the tracer. if set_type in ('step', 'continue', 'quit'): set_method() return elif set_type in ('next', 'return'): set_method(self.frame) return elif set_type == 'until': lineno = None if args: lineno = self.lno_rel2abs(self.frame.f_code.co_filename, args[0]) set_method(self.frame, lineno) return # The following set methods do not give back control to the tracer and # next_set_method() is called recursively. if (args and set_type in ('break', 'clear', 'ignore', 'enable', 'disable')) or set_type in ('up', 'down'): if set_type in ('break', 'clear'): fname, lineno, *remain = args lineno = self.lno_rel2abs(fname, lineno) args = [fname, lineno] args.extend(remain) set_method(*args) elif set_type in ('ignore', 'enable', 'disable'): set_method(*args) elif set_type in ('up', 'down'): set_method() # Process the next expect_set item. # It is not expected that a test may reach the recursion limit. self.event= None self.pop_next() if self.dry_run: self.print_state() else: if self.expect: self.check_lno_name() self.check_expect_max_size(3) self.next_set_method() else: raise BdbSyntaxError('"%s" is an invalid set_tuple' % self.set_tuple) class TracerRun(): """Provide a context for running a Tracer instance with a test case.""" def __init__(self, test_case, skip=None): self.test_case = test_case self.dry_run = test_case.dry_run self.tracer = Tracer(test_case.expect_set, skip=skip, dry_run=self.dry_run, test_case=test_case.id()) self._original_tracer = None def __enter__(self): # test_pdb does not reset Breakpoint class attributes on exit :-( reset_Breakpoint() self._original_tracer = sys.gettrace() return self.tracer def __exit__(self, type_=None, value=None, traceback=None): reset_Breakpoint() sys.settrace(self._original_tracer) not_empty = '' if self.tracer.set_list: not_empty += 'All paired tuples have not been processed, ' not_empty += ('the last one was number %d' % self.tracer.expect_set_no) # Make a BdbNotExpectedError a unittest failure. if type_ is not None and issubclass(BdbNotExpectedError, type_): if isinstance(value, BaseException) and value.args: err_msg = value.args[0] if not_empty: err_msg += '\n' + not_empty if self.dry_run: print(err_msg) return True else: self.test_case.fail(err_msg) else: assert False, 'BdbNotExpectedError with empty args' if not_empty: if self.dry_run: print(not_empty) else: self.test_case.fail(not_empty) def run_test(modules, set_list, skip=None): """Run a test and print the dry-run results. 'modules': A dictionary mapping module names to their source code as a string. The dictionary MUST include one module named 'test_module' with a main() function. 'set_list': A list of set_type tuples to be run on the module. For example, running the following script outputs the following results: ***************************** SCRIPT ******************************** from test.test_bdb import run_test, break_in_func code = ''' def func(): lno = 3 def main(): func() lno = 7 ''' set_list = [ break_in_func('func', 'test_module.py'), ('continue', ), ('step', ), ('step', ), ('step', ), ('quit', ), ] modules = { 'test_module': code } run_test(modules, set_list) **************************** results ******************************** 1: ('line', 2, 'tfunc_import'), ('next',), 2: ('line', 3, 'tfunc_import'), ('step',), 3: ('call', 5, 'main'), ('break', ('test_module.py', None, False, None, 'func')), 4: ('None', 5, 'main'), ('continue',), 5: ('line', 3, 'func', ({1: 1}, [])), ('step',), BpNum Temp Enb Hits Ignore Where 1 no yes 1 0 at test_module.py:2 6: ('return', 3, 'func'), ('step',), 7: ('line', 7, 'main'), ('step',), 8: ('return', 7, 'main'), ('quit',), ************************************************************************* """ def gen(a, b): try: while 1: x = next(a) y = next(b) yield x yield y except StopIteration: return # Step over the import statement in tfunc_import using 'next' and step # into main() in test_module. sl = [('next', ), ('step', )] sl.extend(set_list) test = BaseTestCase() test.dry_run = True test.id = lambda : None test.expect_set = list(gen(repeat(()), iter(sl))) with create_modules(modules): with TracerRun(test, skip=skip) as tracer: tracer.runcall(tfunc_import) @contextmanager def create_modules(modules): with test.support.temp_cwd(): sys.path.append(os.getcwd()) try: for m in modules: fname = m + '.py' with open(fname, 'w') as f: f.write(textwrap.dedent(modules[m])) linecache.checkcache(fname) importlib.invalidate_caches() yield finally: for m in modules: test.support.forget(m) sys.path.pop() def break_in_func(funcname, fname=__file__, temporary=False, cond=None): return 'break', (fname, None, temporary, cond, funcname) TEST_MODULE = 'test_module_for_bdb' TEST_MODULE_FNAME = TEST_MODULE + '.py' def tfunc_import(): import test_module_for_bdb test_module_for_bdb.main() def tfunc_main(): lno = 2 tfunc_first() tfunc_second() lno = 5 lno = 6 lno = 7 def tfunc_first(): lno = 2 lno = 3 lno = 4 def tfunc_second(): lno = 2 class BaseTestCase(unittest.TestCase): """Base class for all tests.""" dry_run = dry_run def fail(self, msg=None): # Override fail() to use 'raise from None' to avoid repetition of the # error message and traceback. raise self.failureException(msg) from None class StateTestCase(BaseTestCase): """Test the step, next, return, until and quit 'set_' methods.""" def test_step(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('step', ), ('line', 2, 'tfunc_first'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_step_next_on_last_statement(self): for set_type in ('step', 'next'): with self.subTest(set_type=set_type): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('break', (__file__, 3)), ('None', 1, 'tfunc_first'), ('continue', ), ('line', 3, 'tfunc_first', ({1:1}, [])), (set_type, ), ('line', 4, 'tfunc_first'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_next(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('next', ), ('line', 4, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_second'), ('step', ), ('line', 2, 'tfunc_second'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_next_over_import(self): code = """ def main(): lno = 3 """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), ('next', ), ('line', 3, 'tfunc_import'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_next_on_plain_statement(self): # Check that set_next() is equivalent to set_step() on a plain # statement. self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('next', ), ('line', 2, 'tfunc_first'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_next_in_caller_frame(self): # Check that set_next() in the caller frame causes the tracer # to stop next in the caller frame. self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('up', ), ('None', 3, 'tfunc_main'), ('next', ), ('line', 4, 'tfunc_main'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_return(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('step', ), ('line', 2, 'tfunc_first'), ('return', ), ('return', 4, 'tfunc_first'), ('step', ), ('line', 4, 'tfunc_main'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_return_in_caller_frame(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('up', ), ('None', 3, 'tfunc_main'), ('return', ), ('return', 7, 'tfunc_main'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_until(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('step', ), ('line', 2, 'tfunc_first'), ('until', (4, )), ('line', 4, 'tfunc_first'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_until_with_too_large_count(self): self.expect_set = [ ('line', 2, 'tfunc_main'), break_in_func('tfunc_first'), ('None', 2, 'tfunc_main'), ('continue', ), ('line', 2, 'tfunc_first', ({1:1}, [])), ('until', (9999, )), ('return', 4, 'tfunc_first'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_until_in_caller_frame(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('up', ), ('None', 3, 'tfunc_main'), ('until', (6, )), ('line', 6, 'tfunc_main'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) def test_skip(self): # Check that tracing is skipped over the import statement in # 'tfunc_import()'. code = """ def main(): lno = 3 """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), ('step', ), ('line', 3, 'tfunc_import'), ('quit', ), ] skip = ('importlib*', TEST_MODULE) with TracerRun(self, skip=skip) as tracer: tracer.runcall(tfunc_import) def test_down(self): # Check that set_down() raises BdbError at the newest frame. self.expect_set = [ ('line', 2, 'tfunc_main'), ('down', ), ] with TracerRun(self) as tracer: self.assertRaises(BdbError, tracer.runcall, tfunc_main) def test_up(self): self.expect_set = [ ('line', 2, 'tfunc_main'), ('step', ), ('line', 3, 'tfunc_main'), ('step', ), ('call', 1, 'tfunc_first'), ('up', ), ('None', 3, 'tfunc_main'), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_main) class BreakpointTestCase(BaseTestCase): """Test the breakpoint set method.""" def test_bp_on_non_existent_module(self): self.expect_set = [ ('line', 2, 'tfunc_import'), ('break', ('/non/existent/module.py', 1)) ] with TracerRun(self) as tracer: self.assertRaises(BdbError, tracer.runcall, tfunc_import) def test_bp_after_last_statement(self): code = """ def main(): lno = 3 """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 4)) ] with TracerRun(self) as tracer: self.assertRaises(BdbError, tracer.runcall, tfunc_import) def test_temporary_bp(self): code = """ def func(): lno = 3 def main(): for i in range(2): func() """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME, True), ('None', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME, True), ('None', 2, 'tfunc_import'), ('continue', ), ('line', 3, 'func', ({1:1}, [1])), ('continue', ), ('line', 3, 'func', ({2:1}, [2])), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_disabled_temporary_bp(self): code = """ def func(): lno = 3 def main(): for i in range(3): func() """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME), ('None', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME, True), ('None', 2, 'tfunc_import'), ('disable', (2, )), ('None', 2, 'tfunc_import'), ('continue', ), ('line', 3, 'func', ({1:1}, [])), ('enable', (2, )), ('None', 3, 'func'), ('disable', (1, )), ('None', 3, 'func'), ('continue', ), ('line', 3, 'func', ({2:1}, [2])), ('enable', (1, )), ('None', 3, 'func'), ('continue', ), ('line', 3, 'func', ({1:2}, [])), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_bp_condition(self): code = """ def func(a): lno = 3 def main(): for i in range(3): func(i) """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME, False, 'a == 2'), ('None', 2, 'tfunc_import'), ('continue', ), ('line', 3, 'func', ({1:3}, [])), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_bp_exception_on_condition_evaluation(self): code = """ def func(a): lno = 3 def main(): func(0) """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME, False, '1 / 0'), ('None', 2, 'tfunc_import'), ('continue', ), ('line', 3, 'func', ({1:1}, [])), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_bp_ignore_count(self): code = """ def func(): lno = 3 def main(): for i in range(2): func() """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME), ('None', 2, 'tfunc_import'), ('ignore', (1, )), ('None', 2, 'tfunc_import'), ('continue', ), ('line', 3, 'func', ({1:2}, [])), ('quit', ), ] with TracerRun(self) as tracer: tracer.runcall(tfunc_import) def test_ignore_count_on_disabled_bp(self): code = """ def func(): lno = 3 def main(): for i in range(3): func() """ modules = { TEST_MODULE: code } with create_modules(modules): self.expect_set = [ ('line', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME), ('None', 2, 'tfunc_import'), break_in_func('func', TEST_MODULE_FNAME),
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true