code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def dump(co): """Print out a text representation of a code object.""" for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames", "cellvars", "freevars", "nlocals", "flags"]: print("%s: %s" % (attr, getattr(co, "co_" + attr))) print("consts:", tuple(consts(co.co_consts)))
Print out a text representation of a code object.
dump
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
MIT
def new_code(c): '''A new code object with a __class__ cell added to freevars''' return CodeType( c.co_argcount, c.co_kwonlyargcount, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names, c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab, c.co_freevars + ('__class__',), c.co_cellvars)
A new code object with a __class__ cell added to freevars
test_closure_injection.new_code
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_code.py
MIT
def test_threaded_import_lock_fork(self): """Check fork() in main thread works while a subthread is doing an import""" import_started = threading.Event() fake_module_name = "fake test module" partial_module = "partial" complete_module = "complete" def importer(): imp.acquire_lock() sys.modules[fake_module_name] = partial_module import_started.set() time.sleep(0.01) # Give the other thread time to try and acquire. sys.modules[fake_module_name] = complete_module imp.release_lock() t = threading.Thread(target=importer) t.start() import_started.wait() pid = os.fork() try: # PyOS_BeforeFork should have waited for the import to complete # before forking, so the child can recreate the import lock # correctly, but also won't see a partially initialised module if not pid: m = __import__(fake_module_name) if m == complete_module: os._exit(0) else: if verbose > 1: print("Child encountered partial module") os._exit(1) else: t.join() # Exitcode 1 means the child got a partial module (bad.) No # exitcode (but a hang, which manifests as 'got pid 0') # means the child deadlocked (also bad.) self.wait_impl(pid) finally: try: os.kill(pid, signal.SIGKILL) except OSError: pass
Check fork() in main thread works while a subthread is doing an import
test_threaded_import_lock_fork
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fork1.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fork1.py
MIT
def test_nested_import_lock_fork(self): """Check fork() in main thread works while the main thread is doing an import""" # Issue 9573: this used to trigger RuntimeError in the child process def fork_with_import_lock(level): release = 0 in_child = False try: try: for i in range(level): imp.acquire_lock() release += 1 pid = os.fork() in_child = not pid finally: for i in range(release): imp.release_lock() except RuntimeError: if in_child: if verbose > 1: print("RuntimeError in child") os._exit(1) raise if in_child: os._exit(0) self.wait_impl(pid) # Check this works with various levels of nested # import in the main thread for level in range(5): fork_with_import_lock(level)
Check fork() in main thread works while the main thread is doing an import
test_nested_import_lock_fork
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fork1.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fork1.py
MIT
def testDecompressLimited(self): """Decompressed data buffering should be limited""" bomb = bz2.compress(b'\0' * int(2e6), compresslevel=9) self.assertLess(len(bomb), _compression.BUFFER_SIZE) decomp = BZ2File(BytesIO(bomb)) self.assertEqual(decomp.read(1), b'\0') max_decomp = 1 + DEFAULT_BUFFER_SIZE self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp, "Excessive amount of data was decompressed")
Decompressed data buffering should be limited
testDecompressLimited
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bz2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_bz2.py
MIT
def sample_func(v): """ Blah blah >>> print(sample_func(22)) 44 Yee ha! """ return v+v
Blah blah >>> print(sample_func(22)) 44 Yee ha!
sample_func
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def __init__(self, val): """ >>> print(SampleClass(12).get()) 12 """ self.val = val
>>> print(SampleClass(12).get()) 12
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def double(self): """ >>> print(SampleClass(12).double().get()) 24 """ return SampleClass(self.val + self.val)
>>> print(SampleClass(12).double().get()) 24
double
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def get(self): """ >>> print(SampleClass(-5).get()) -5 """ return self.val
>>> print(SampleClass(-5).get()) -5
get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def a_staticmethod(v): """ >>> print(SampleClass.a_staticmethod(10)) 11 """ return v+1
>>> print(SampleClass.a_staticmethod(10)) 11
a_staticmethod
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def a_classmethod(cls, v): """ >>> print(SampleClass.a_classmethod(10)) 12 >>> print(SampleClass(0).a_classmethod(10)) 12 """ return v+2
>>> print(SampleClass.a_classmethod(10)) 12 >>> print(SampleClass(0).a_classmethod(10)) 12
a_classmethod
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def __init__(self, val=0): """ >>> print(SampleClass.NestedClass().get()) 0 """ self.val = val
>>> print(SampleClass.NestedClass().get()) 0
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def __init__(self, val): """ >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val
>>> print(SampleNewStyleClass(12).get()) 12
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def double(self): """ >>> print(SampleNewStyleClass(12).double().get()) 24 """ return SampleNewStyleClass(self.val + self.val)
>>> print(SampleNewStyleClass(12).double().get()) 24
double
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def get(self): """ >>> print(SampleNewStyleClass(-5).get()) -5 """ return self.val
>>> print(SampleNewStyleClass(-5).get()) -5
get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_DocTest(): r""" Unit tests for the `DocTest` class. DocTest is a collection of examples, extracted from a docstring, along with information about where the docstring comes from (a name, filename, and line number). The docstring is parsed by the `DocTest` constructor: >>> docstring = ''' ... >>> print(12) ... 12 ... ... Non-example text. ... ... >>> print('another\\example') ... another ... example ... ''' >>> globs = {} # globals to run the test in. >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_file', 20) >>> print(test) <DocTest some_test from some_file:20 (2 examples)> >>> len(test.examples) 2 >>> e1, e2 = test.examples >>> (e1.source, e1.want, e1.lineno) ('print(12)\n', '12\n', 1) >>> (e2.source, e2.want, e2.lineno) ("print('another\\example')\n", 'another\nexample\n', 6) Source information (name, filename, and line number) is available as attributes on the doctest object: >>> (test.name, test.filename, test.lineno) ('some_test', 'some_file', 20) The line number of an example within its containing file is found by adding the line number of the example and the line number of its containing test: >>> test.lineno + e1.lineno 21 >>> test.lineno + e2.lineno 26 If the docstring contains inconsistent leading whitespace in the expected output of an example, then `DocTest` will raise a ValueError: >>> docstring = r''' ... >>> print('bad\nindentation') ... bad ... indentation ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation' If the docstring contains inconsistent leading whitespace on continuation lines, then `DocTest` will raise a ValueError: >>> docstring = r''' ... >>> print(('bad indentation', ... ... 2)) ... ('bad', 'indentation') ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))' If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: >>> docstring = '>>>print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)' If there's no blank space after a PS2 prompt ('...'), then `DocTest` will raise a ValueError: >>> docstring = '>>> if 1:\n...print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)' Compare `DocTest`: >>> docstring = ''' ... >>> print 12 ... 12 ... ''' >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_test', 20) >>> same_test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_test', 20) >>> test == same_test True >>> test != same_test False >>> hash(test) == hash(same_test) True >>> docstring = ''' ... >>> print 42 ... 42 ... ''' >>> other_test = parser.get_doctest(docstring, globs, 'other_test', ... 'other_file', 10) >>> test == other_test False >>> test != other_test True Compare `DocTestCase`: >>> DocTestCase = doctest.DocTestCase >>> test_case = DocTestCase(test) >>> same_test_case = DocTestCase(same_test) >>> other_test_case = DocTestCase(other_test) >>> test_case == same_test_case True >>> test_case != same_test_case False >>> hash(test_case) == hash(same_test_case) True >>> test == other_test_case False >>> test != other_test_case True """ class test_DocTestFinder: def basics(): r""" Unit tests for the `DocTestFinder` class. DocTestFinder is used to extract DocTests from an object's docstring and the docstrings of its contained objects. It can be used with modules, functions, classes, methods, staticmethods, classmethods, and properties. Finding Tests in Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~ For a function whose docstring contains examples, DocTestFinder.find() will return a single test (for that function's docstring): >>> finder = doctest.DocTestFinder() We'll simulate a __file__ attr that ends in pyc: >>> import test.test_doctest >>> old = test.test_doctest.__file__ >>> test.test_doctest.__file__ = 'test_doctest.pyc' >>> tests = finder.find(sample_func) >>> print(tests) # doctest: +ELLIPSIS [<DocTest sample_func from ...:21 (1 example)>] The exact name depends on how test_doctest was invoked, so allow for leading path components. >>> tests[0].filename # doctest: +ELLIPSIS '...test_doctest.py' >>> test.test_doctest.__file__ = old >>> e = tests[0].examples[0] >>> (e.source, e.want, e.lineno) ('print(sample_func(22))\n', '44\n', 3) By default, tests are created for objects with no docstring: >>> def no_docstring(v): ... pass >>> finder.find(no_docstring) [] However, the optional argument `exclude_empty` to the DocTestFinder constructor can be used to exclude tests for objects with empty docstrings: >>> def no_docstring(v): ... pass >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True) >>> excl_empty_finder.find(no_docstring) [] If the function has a docstring with no examples, then a test with no examples is returned. (This lets `DocTestRunner` collect statistics about which functions have no tests -- but is that useful? And should an empty test also be created when there's no docstring?) >>> def no_examples(v): ... ''' no doctest examples ''' >>> finder.find(no_examples) # doctest: +ELLIPSIS [<DocTest no_examples from ...:1 (no examples)>] Finding Tests in Classes ~~~~~~~~~~~~~~~~~~~~~~~~ For a class, DocTestFinder will create a test for the class's docstring, and will recursively explore its contents, including methods, classmethods, staticmethods, properties, and nested classes. >>> finder = doctest.DocTestFinder() >>> tests = finder.find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get New-style classes are also supported: >>> tests = finder.find(SampleNewStyleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 1 SampleNewStyleClass 1 SampleNewStyleClass.__init__ 1 SampleNewStyleClass.double 1 SampleNewStyleClass.get Finding Tests in Modules ~~~~~~~~~~~~~~~~~~~~~~~~ For a module, DocTestFinder will create a test for the class's docstring, and will recursively explore its contents, including functions, classes, and the `__test__` dictionary, if it exists: >>> # A module >>> import types >>> m = types.ModuleType('some_module') >>> def triple(val): ... ''' ... >>> print(triple(11)) ... 33 ... ''' ... return val*3 >>> m.__dict__.update({ ... 'sample_func': sample_func, ... 'SampleClass': SampleClass, ... '__doc__': ''' ... Module docstring. ... >>> print('module') ... module ... ''', ... '__test__': { ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n', ... 'c': triple}}) >>> finder = doctest.DocTestFinder() >>> # Use module=test.test_doctest, to prevent doctest from >>> # ignoring the objects since they weren't defined in m. >>> import test.test_doctest >>> tests = finder.find(m, module=test.test_doctest) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 1 some_module 3 some_module.SampleClass 3 some_module.SampleClass.NestedClass 1 some_module.SampleClass.NestedClass.__init__ 1 some_module.SampleClass.__init__ 2 some_module.SampleClass.a_classmethod 1 some_module.SampleClass.a_property 1 some_module.SampleClass.a_staticmethod 1 some_module.SampleClass.double 1 some_module.SampleClass.get 1 some_module.__test__.c 2 some_module.__test__.d 1 some_module.sample_func Duplicate Removal ~~~~~~~~~~~~~~~~~ If a single object is listed twice (under different names), then tests will only be generated for it once: >>> from test import doctest_aliases >>> assert doctest_aliases.TwoNames.f >>> assert doctest_aliases.TwoNames.g >>> tests = excl_empty_finder.find(doctest_aliases) >>> print(len(tests)) 2 >>> print(tests[0].name) test.doctest_aliases.TwoNames TwoNames.f and TwoNames.g are bound to the same object. We can't guess which will be found in doctest's traversal of TwoNames.__dict__ first, so we have to allow for either. >>> tests[1].name.split('.')[-1] in ['f', 'g'] True Empty Tests ~~~~~~~~~~~ By default, an object with no doctests doesn't create any tests: >>> tests = doctest.DocTestFinder().find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get By default, that excluded objects with no doctests. exclude_empty=False tells it to include (empty) tests for objects with no doctests. This feature is really to support backward compatibility in what doctest.master.summarize() displays. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ 0 SampleClass.NestedClass.get 0 SampleClass.NestedClass.square 1 SampleClass.__init__ 2 SampleClass.a_classmethod 1 SampleClass.a_property 1 SampleClass.a_staticmethod 1 SampleClass.double 1 SampleClass.get Turning off Recursion ~~~~~~~~~~~~~~~~~~~~~ DocTestFinder can be told not to look for tests in contained objects using the `recurse` flag: >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass) >>> for t in tests: ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass Line numbers ~~~~~~~~~~~~ DocTestFinder finds the line number of each example: >>> def f(x): ... ''' ... >>> x = 12 ... ... some text ... ... >>> # examples are not created for comments & bare prompts. ... >>> ... ... ... ... >>> for x in range(10): ... ... print(x, end=' ') ... 0 1 2 3 4 5 6 7 8 9 ... >>> x//2 ... 6 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> [e.lineno for e in test.examples] [1, 9, 12] """ if int.__doc__: # simple check for --without-doc-strings, skip if lacking def non_Python_modules(): r""" Finding Doctests in Modules Not Written in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DocTestFinder can also find doctests in most modules not written in Python. We'll use builtins as an example, since it almost certainly isn't written in plain ol' Python and is guaranteed to be available. >>> import builtins >>> tests = doctest.DocTestFinder().find(builtins) >>> 800 < len(tests) < 820 # approximate number of objects with docstrings True >>> real_tests = [t for t in tests if len(t.examples) > 0] >>> len(real_tests) # objects that actually have doctests 8 >>> for t in real_tests: ... print('{} {}'.format(len(t.examples), t.name)) ... 1 builtins.bin 3 builtins.float.as_integer_ratio 2 builtins.float.fromhex 2 builtins.float.hex 1 builtins.hex 1 builtins.int 2 builtins.int.bit_length 1 builtins.oct Note here that 'bin', 'oct', and 'hex' are functions; 'float.as_integer_ratio', 'float.hex', and 'int.bit_length' are methods; 'float.fromhex' is a classmethod, and 'int' is a type. """
class test_DocTestFinder: def basics(): r
test_DocTest
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_pdb_set_trace(): """Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporarily replaces pdb.set_trace with a version that restores stdout. This is necessary for you to see debugger output. >>> doc = ''' ... >>> x = 42 ... >>> raise Exception('clé') ... Traceback (most recent call last): ... Exception: clé ... >>> import pdb; pdb.set_trace() ... ''' >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "[email protected]", 0) >>> runner = doctest.DocTestRunner(verbose=False) To demonstrate this, we'll create a fake standard input that captures our debugger input: >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) >>> try: runner.run(test) ... finally: sys.stdin = real_stdin --Return-- > <doctest foo-bar@baz[2]>(1)<module>()->None -> import pdb; pdb.set_trace() (Pdb) print(x) 42 (Pdb) continue TestResults(failed=0, attempted=3) You can also put pdb.set_trace in a function called from a test: >>> def calls_set_trace(): ... y=2 ... import pdb; pdb.set_trace() >>> doc = ''' ... >>> x=1 ... >>> calls_set_trace() ... ''' >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(y)', # print data defined in the function ... 'up', # out of function ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) >>> try: ... runner.run(test) ... finally: ... sys.stdin = real_stdin --Return-- > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None -> import pdb; pdb.set_trace() (Pdb) print(y) 2 (Pdb) up > <doctest foo-bar@baz[1]>(1)<module>() -> calls_set_trace() (Pdb) print(x) 1 (Pdb) continue TestResults(failed=0, attempted=2) During interactive debugging, source code is shown, even for doctest examples: >>> doc = ''' ... >>> def f(x): ... ... g(x*2) ... >>> def g(x): ... ... print(x+3) ... ... import pdb; pdb.set_trace() ... >>> f(3) ... ''' >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'list', # list source from example 2 ... 'next', # return from g() ... 'list', # list source from example 1 ... 'next', # return from f() ... 'list', # list source from example 3 ... 'continue', # stop debugging ... '']) >>> try: runner.run(test) ... finally: sys.stdin = real_stdin ... # doctest: +NORMALIZE_WHITESPACE --Return-- > <doctest foo-bar@baz[1]>(3)g()->None -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] (Pdb) next --Return-- > <doctest foo-bar@baz[0]>(2)f()->None -> g(x*2) (Pdb) list 1 def f(x): 2 -> g(x*2) [EOF] (Pdb) next --Return-- > <doctest foo-bar@baz[2]>(1)<module>()->None -> f(3) (Pdb) list 1 -> f(3) [EOF] (Pdb) continue ********************************************************************** File "[email protected]", line 7, in foo-bar@baz Failed example: f(3) Expected nothing Got: 9 TestResults(failed=1, attempted=3) """
Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporarily replaces pdb.set_trace with a version that restores stdout. This is necessary for you to see debugger output. >>> doc =
test_debug.test_pdb_set_trace
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_pdb_set_trace_nested(): """This illustrates more-demanding use of set_trace with nested functions. >>> class C(object): ... def calls_set_trace(self): ... y = 1 ... import pdb; pdb.set_trace() ... self.f1() ... y = 2 ... def f1(self): ... x = 1 ... self.f2() ... x = 2 ... def f2(self): ... z = 1 ... z = 2 >>> calls_set_trace = C().calls_set_trace >>> doc = ''' ... >>> a = 1 ... >>> calls_set_trace() ... ''' >>> parser = doctest.DocTestParser() >>> runner = doctest.DocTestRunner(verbose=False) >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(y)', # print data defined in the function ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)', ... 'up', 'print(x)', ... 'up', 'print(y)', ... 'up', 'print(foo)', ... 'continue', # stop debugging ... '']) >>> try: ... runner.run(test) ... finally: ... sys.stdin = real_stdin ... # doctest: +REPORT_NDIFF > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() -> self.f1() (Pdb) print(y) 1 (Pdb) step --Call-- > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1() -> def f1(self): (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1() -> x = 1 (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() -> self.f2() (Pdb) step --Call-- > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2() -> def f2(self): (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2() -> z = 1 (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2() -> z = 2 (Pdb) print(z) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() -> self.f2() (Pdb) print(x) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() -> self.f1() (Pdb) print(y) 1 (Pdb) up > <doctest foo-bar@baz[1]>(1)<module>() -> calls_set_trace() (Pdb) print(foo) *** NameError: name 'foo' is not defined (Pdb) continue TestResults(failed=0, attempted=2) """
This illustrates more-demanding use of set_trace with nested functions. >>> class C(object): ... def calls_set_trace(self): ... y = 1 ... import pdb; pdb.set_trace() ... self.f1() ... y = 2 ... def f1(self): ... x = 1 ... self.f2() ... x = 2 ... def f2(self): ... z = 1 ... z = 2 >>> calls_set_trace = C().calls_set_trace >>> doc =
test_debug.test_pdb_set_trace_nested
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_debug(): r""" Create a docstring that we want to debug: >>> s = ''' ... >>> x = 12 ... >>> print(x) ... 12 ... ''' Create some fake stdin input, to feed to the debugger: >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue']) Run the debugger on the docstring, and then restore sys.stdin. >>> try: doctest.debug_src(s) ... finally: sys.stdin = real_stdin > <string>(1)<module>() (Pdb) next 12 --Return-- > <string>(1)<module>()->None (Pdb) print(x) 12 (Pdb) continue """ if not hasattr(sys, 'gettrace') or not sys.gettrace(): def test_pdb_set_trace(): """Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporarily replaces pdb.set_trace with a version that restores stdout. This is necessary for you to see debugger output. >>> doc = ''' ... >>> x = 42 ... >>> raise Exception('clé') ... Traceback (most recent call last): ... Exception: clé ... >>> import pdb; pdb.set_trace() ... ''' >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "[email protected]", 0) >>> runner = doctest.DocTestRunner(verbose=False) To demonstrate this, we'll create a fake standard input that captures our debugger input: >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) >>> try: runner.run(test) ... finally: sys.stdin = real_stdin --Return-- > <doctest foo-bar@baz[2]>(1)<module>()->None -> import pdb; pdb.set_trace() (Pdb) print(x) 42 (Pdb) continue TestResults(failed=0, attempted=3) You can also put pdb.set_trace in a function called from a test: >>> def calls_set_trace(): ... y=2 ... import pdb; pdb.set_trace() >>> doc = ''' ... >>> x=1 ... >>> calls_set_trace() ... ''' >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(y)', # print data defined in the function ... 'up', # out of function ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) >>> try: ... runner.run(test) ... finally: ... sys.stdin = real_stdin --Return-- > <doctest test.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None -> import pdb; pdb.set_trace() (Pdb) print(y) 2 (Pdb) up > <doctest foo-bar@baz[1]>(1)<module>() -> calls_set_trace() (Pdb) print(x) 1 (Pdb) continue TestResults(failed=0, attempted=2) During interactive debugging, source code is shown, even for doctest examples: >>> doc = ''' ... >>> def f(x): ... ... g(x*2) ... >>> def g(x): ... ... print(x+3) ... ... import pdb; pdb.set_trace() ... >>> f(3) ... ''' >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'list', # list source from example 2 ... 'next', # return from g() ... 'list', # list source from example 1 ... 'next', # return from f() ... 'list', # list source from example 3 ... 'continue', # stop debugging ... '']) >>> try: runner.run(test) ... finally: sys.stdin = real_stdin ... # doctest: +NORMALIZE_WHITESPACE --Return-- > <doctest foo-bar@baz[1]>(3)g()->None -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] (Pdb) next --Return-- > <doctest foo-bar@baz[0]>(2)f()->None -> g(x*2) (Pdb) list 1 def f(x): 2 -> g(x*2) [EOF] (Pdb) next --Return-- > <doctest foo-bar@baz[2]>(1)<module>()->None -> f(3) (Pdb) list 1 -> f(3) [EOF] (Pdb) continue ********************************************************************** File "[email protected]", line 7, in foo-bar@baz Failed example: f(3) Expected nothing Got: 9 TestResults(failed=1, attempted=3) """ def test_pdb_set_trace_nested(): """This illustrates more-demanding use of set_trace with nested functions. >>> class C(object): ... def calls_set_trace(self): ... y = 1 ... import pdb; pdb.set_trace() ... self.f1() ... y = 2 ... def f1(self): ... x = 1 ... self.f2() ... x = 2 ... def f2(self): ... z = 1 ... z = 2 >>> calls_set_trace = C().calls_set_trace >>> doc = ''' ... >>> a = 1 ... >>> calls_set_trace() ... ''' >>> parser = doctest.DocTestParser() >>> runner = doctest.DocTestRunner(verbose=False) >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "[email protected]", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ ... 'print(y)', # print data defined in the function ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)', ... 'up', 'print(x)', ... 'up', 'print(y)', ... 'up', 'print(foo)', ... 'continue', # stop debugging ... '']) >>> try: ... runner.run(test) ... finally: ... sys.stdin = real_stdin ... # doctest: +REPORT_NDIFF > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() -> self.f1() (Pdb) print(y) 1 (Pdb) step --Call-- > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1() -> def f1(self): (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1() -> x = 1 (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() -> self.f2() (Pdb) step --Call-- > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2() -> def f2(self): (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2() -> z = 1 (Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2() -> z = 2 (Pdb) print(z) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() -> self.f2() (Pdb) print(x) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() -> self.f1() (Pdb) print(y) 1 (Pdb) up > <doctest foo-bar@baz[1]>(1)<module>() -> calls_set_trace() (Pdb) print(foo) *** NameError: name 'foo' is not defined (Pdb) continue TestResults(failed=0, attempted=2) """
if not hasattr(sys, 'gettrace') or not sys.gettrace(): def test_pdb_set_trace(): """Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporarily replaces pdb.set_trace with a version that restores stdout. This is necessary for you to see debugger output. >>> doc =
test_debug
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_DocTestSuite(): """DocTestSuite creates a unittest test suite from a doctest. We create a Suite by providing a module. A module can be provided by passing a module object: >>> import unittest >>> import test.sample_doctest >>> suite = doctest.DocTestSuite(test.sample_doctest) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can also supply the module by name: >>> suite = doctest.DocTestSuite('test.sample_doctest') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> The module need not contain any doctest examples: >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> The module need not contain any docstrings either: >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> We can use the current module: >>> suite = test.sample_doctest.test_suite() >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can also provide a DocTestFinder: >>> finder = doctest.DocTestFinder() >>> suite = doctest.DocTestSuite('test.sample_doctest', ... test_finder=finder) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> The DocTestFinder need not return any tests: >>> finder = doctest.DocTestFinder() >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings', ... test_finder=finder) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> We can supply global variables. If we pass globs, they will be used instead of the module globals. Here we'll pass an empty globals, triggering an extra error: >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> Alternatively, we can provide extra globals. Here we'll make an error go away by providing an extra global variable: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... extraglobs={'y': 1}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> You can pass option flags. Here we'll cause an extra error by disabling the blank-line feature: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> You can supply setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: module 'test.test_doctest' has no attribute 'sillySetup' The setUp and tearDown functions are passed test objects. Here we'll use the setUp function to supply the missing variable y: >>> def setUp(test): ... test.globs['y'] = 1 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> Here, we didn't need to use a tearDown function because we modified the test globals, which are a copy of the sample_doctest module dictionary. The test globals are automatically cleared for us after a test. """
DocTestSuite creates a unittest test suite from a doctest. We create a Suite by providing a module. A module can be provided by passing a module object: >>> import unittest >>> import test.sample_doctest >>> suite = doctest.DocTestSuite(test.sample_doctest) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can also supply the module by name: >>> suite = doctest.DocTestSuite('test.sample_doctest') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> The module need not contain any doctest examples: >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> The module need not contain any docstrings either: >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> We can use the current module: >>> suite = test.sample_doctest.test_suite() >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can also provide a DocTestFinder: >>> finder = doctest.DocTestFinder() >>> suite = doctest.DocTestSuite('test.sample_doctest', ... test_finder=finder) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> The DocTestFinder need not return any tests: >>> finder = doctest.DocTestFinder() >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings', ... test_finder=finder) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=0 errors=0 failures=0> We can supply global variables. If we pass globs, they will be used instead of the module globals. Here we'll pass an empty globals, triggering an extra error: >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> Alternatively, we can provide extra globals. Here we'll make an error go away by providing an extra global variable: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... extraglobs={'y': 1}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> You can pass option flags. Here we'll cause an extra error by disabling the blank-line feature: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> You can supply setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: module 'test.test_doctest' has no attribute 'sillySetup' The setUp and tearDown functions are passed test objects. Here we'll use the setUp function to supply the missing variable y: >>> def setUp(test): ... test.globs['y'] = 1 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> Here, we didn't need to use a tearDown function because we modified the test globals, which are a copy of the sample_doctest module dictionary. The test globals are automatically cleared for us after a test.
test_DocTestSuite
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_DocFileSuite(): """We can test tests found in text files using a DocFileSuite. We create a suite by providing the names of one or more text files that include examples: >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> The test files are looked for in the directory containing the calling module. A package keyword argument can be provided to specify a different relative location. >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> Support for using a package's __loader__.get_data() is also provided. >>> import unittest, pkgutil, test >>> added_loader = False >>> if not hasattr(test, '__loader__'): ... test.__loader__ = pkgutil.get_loader(test) ... added_loader = True >>> try: ... suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') ... suite.run(unittest.TestResult()) ... finally: ... if added_loader: ... del test.__loader__ <unittest.result.TestResult run=3 errors=0 failures=2> '/' should be used as a path separator. It will be converted to a native separator at run time: >>> suite = doctest.DocFileSuite('../test/test_doctest.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> If DocFileSuite is used from an interactive session, then files are resolved relative to the directory of sys.argv[0]: >>> import types, os.path, test.test_doctest >>> save_argv = sys.argv >>> sys.argv = [test.test_doctest.__file__] >>> suite = doctest.DocFileSuite('test_doctest.txt', ... package=types.ModuleType('__main__')) >>> sys.argv = save_argv By setting `module_relative=False`, os-specific paths may be used (including absolute paths and paths relative to the working directory): >>> # Get the absolute path of the test package. >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__) >>> test_pkg_path = os.path.split(test_doctest_path)[0] >>> # Use it to find the absolute path of test_doctest.txt. >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt') >>> suite = doctest.DocFileSuite(test_file, module_relative=False) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> It is an error to specify `package` when `module_relative=False`: >>> suite = doctest.DocFileSuite(test_file, module_relative=False, ... package='test') Traceback (most recent call last): ValueError: Package may only be specified for module-relative paths. You can specify initial global variables: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=1> In this case, we supplied a missing favorite color. You can provide doctest options: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE, ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> And, you can provide setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=1> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: module 'test.test_doctest' has no attribute 'sillySetup' The setUp and tearDown functions are passed test objects. Here, we'll use a setUp function to set the favorite color in test_doctest.txt: >>> def setUp(test): ... test.globs['favorite_color'] = 'blue' >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> Here, we didn't need to use a tearDown function because we modified the test globals. The test globals are automatically cleared for us after a test. Tests in a file run using `DocFileSuite` can also access the `__file__` global, which is set to the name of the file containing the tests: >>> suite = doctest.DocFileSuite('test_doctest3.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> If the tests contain non-ASCII characters, we have to specify which encoding the file is encoded with. We do so by using the `encoding` parameter: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... encoding='utf-8') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> """
We can test tests found in text files using a DocFileSuite. We create a suite by providing the names of one or more text files that include examples: >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> The test files are looked for in the directory containing the calling module. A package keyword argument can be provided to specify a different relative location. >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> Support for using a package's __loader__.get_data() is also provided. >>> import unittest, pkgutil, test >>> added_loader = False >>> if not hasattr(test, '__loader__'): ... test.__loader__ = pkgutil.get_loader(test) ... added_loader = True >>> try: ... suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') ... suite.run(unittest.TestResult()) ... finally: ... if added_loader: ... del test.__loader__ <unittest.result.TestResult run=3 errors=0 failures=2> '/' should be used as a path separator. It will be converted to a native separator at run time: >>> suite = doctest.DocFileSuite('../test/test_doctest.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> If DocFileSuite is used from an interactive session, then files are resolved relative to the directory of sys.argv[0]: >>> import types, os.path, test.test_doctest >>> save_argv = sys.argv >>> sys.argv = [test.test_doctest.__file__] >>> suite = doctest.DocFileSuite('test_doctest.txt', ... package=types.ModuleType('__main__')) >>> sys.argv = save_argv By setting `module_relative=False`, os-specific paths may be used (including absolute paths and paths relative to the working directory): >>> # Get the absolute path of the test package. >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__) >>> test_pkg_path = os.path.split(test_doctest_path)[0] >>> # Use it to find the absolute path of test_doctest.txt. >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt') >>> suite = doctest.DocFileSuite(test_file, module_relative=False) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> It is an error to specify `package` when `module_relative=False`: >>> suite = doctest.DocFileSuite(test_file, module_relative=False, ... package='test') Traceback (most recent call last): ValueError: Package may only be specified for module-relative paths. You can specify initial global variables: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=1> In this case, we supplied a missing favorite color. You can provide doctest options: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE, ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> And, you can provide setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=1> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: module 'test.test_doctest' has no attribute 'sillySetup' The setUp and tearDown functions are passed test objects. Here, we'll use a setUp function to set the favorite color in test_doctest.txt: >>> def setUp(test): ... test.globs['favorite_color'] = 'blue' >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> Here, we didn't need to use a tearDown function because we modified the test globals. The test globals are automatically cleared for us after a test. Tests in a file run using `DocFileSuite` can also access the `__file__` global, which is set to the name of the file containing the tests: >>> suite = doctest.DocFileSuite('test_doctest3.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> If the tests contain non-ASCII characters, we have to specify which encoding the file is encoded with. We do so by using the `encoding` parameter: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... encoding='utf-8') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2>
test_DocFileSuite
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_trailing_space_in_test(): """ Trailing spaces in expected output are significant: >>> x, y = 'foo', '' >>> print(x, y) foo \n """
Trailing spaces in expected output are significant: >>> x, y = 'foo', '' >>> print(x, y) foo \n
test_trailing_space_in_test
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_look_in_unwrapped(): """ Docstrings in wrapped functions must be detected as well. >>> 'one other test' 'one other test' """
Docstrings in wrapped functions must be detected as well. >>> 'one other test' 'one other test'
test_look_in_unwrapped
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_unittest_reportflags(): """Default unittest reporting flags can be set to control reporting Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see only the first failure of each test. First, we'll look at the output without the flag. The file test_doctest.txt file has two tests. They both fail if blank lines are disabled: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> import unittest >>> result = suite.run(unittest.TestResult()) >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color ... Failed example: if 1: ... Note that we see both failures displayed. >>> old = doctest.set_unittest_reportflags( ... doctest.REPORT_ONLY_FIRST_FAILURE) Now, when we run the test: >>> result = suite.run(unittest.TestResult()) >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color Exception raised: ... NameError: name 'favorite_color' is not defined <BLANKLINE> <BLANKLINE> We get only the first failure. If we give any reporting options when we set up the tests, however: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF) Then the default eporting options are ignored: >>> result = suite.run(unittest.TestResult()) *NOTE*: These doctest are intentionally not placed in raw string to depict the trailing whitespace using `\x20` in the diff below. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color ... Failed example: if 1: print('a') print() print('b') Differences (ndiff with -expected +actual): a - <BLANKLINE> +\x20 b <BLANKLINE> <BLANKLINE> Test runners can restore the formatting flags after they run: >>> ignored = doctest.set_unittest_reportflags(old) """
Default unittest reporting flags can be set to control reporting Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see only the first failure of each test. First, we'll look at the output without the flag. The file test_doctest.txt file has two tests. They both fail if blank lines are disabled: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> import unittest >>> result = suite.run(unittest.TestResult()) >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color ... Failed example: if 1: ... Note that we see both failures displayed. >>> old = doctest.set_unittest_reportflags( ... doctest.REPORT_ONLY_FIRST_FAILURE) Now, when we run the test: >>> result = suite.run(unittest.TestResult()) >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color Exception raised: ... NameError: name 'favorite_color' is not defined <BLANKLINE> <BLANKLINE> We get only the first failure. If we give any reporting options when we set up the tests, however: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF) Then the default eporting options are ignored: >>> result = suite.run(unittest.TestResult()) *NOTE*: These doctest are intentionally not placed in raw string to depict the trailing whitespace using `\x20` in the diff below. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color ... Failed example: if 1: print('a') print() print('b') Differences (ndiff with -expected +actual): a - <BLANKLINE> +\x20 b <BLANKLINE> <BLANKLINE> Test runners can restore the formatting flags after they run: >>> ignored = doctest.set_unittest_reportflags(old)
test_unittest_reportflags
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest.py
MIT
def test_walkpackages_zipfile(self): """Tests the same as test_walkpackages_filesys, only with a zip file.""" zip = 'test_walkpackages_zipfile.zip' pkg1 = 'test_walkpackages_zipfile' pkg2 = 'sub' zip_file = os.path.join(self.dirname, zip) z = zipfile.ZipFile(zip_file, 'w') z.writestr(pkg2 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "") z.writestr(pkg1 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "") z.close() sys.path.insert(0, zip_file) expected = [ 'sub', 'sub.test_walkpackages_zipfile', 'sub.test_walkpackages_zipfile.mod', 'test_walkpackages_zipfile', 'test_walkpackages_zipfile.sub', 'test_walkpackages_zipfile.sub.mod', ] actual= [e[1] for e in pkgutil.walk_packages([zip_file])] self.assertEqual(actual, expected) del sys.path[0] for pkg in expected: if pkg.endswith('mod'): continue del sys.modules[pkg]
Tests the same as test_walkpackages_filesys, only with a zip file.
test_walkpackages_zipfile
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pkgutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pkgutil.py
MIT
def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): """Run the Python REPL with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. """ # To run the REPL without using a terminal, spawn python with the command # line option '-i' and the process name set to '<stdin>'. # The directory of argv[0] must match the directory of the Python # executable for the Popen() call to python to succeed as the directory # path may be used by Py_GetPath() to build the default module search # path. stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>") cmd_line = [stdin_fname, '-E', '-i'] cmd_line.extend(args) # Set TERM=vt100, for the rationale see the comments in spawn_python() of # test.support.script_helper. env = kw.setdefault('env', dict(os.environ)) env['TERM'] = 'vt100' return subprocess.Popen(cmd_line, executable=sys.executable, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw)
Run the Python REPL with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object.
spawn_repl
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_repl.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_repl.py
MIT
def assertParseOK(self, args, expected_opts, expected_positional_args): """Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and positional args for further testing. """ (options, positional_args) = self.parser.parse_args(args) optdict = vars(options) self.assertEqual(optdict, expected_opts, """ Options are %(optdict)s. Should be %(expected_opts)s. Args were %(args)s.""" % locals()) self.assertEqual(positional_args, expected_positional_args, """ Positional arguments are %(positional_args)s. Should be %(expected_positional_args)s. Args were %(args)s.""" % locals ()) return (options, positional_args)
Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and positional args for further testing.
assertParseOK
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
MIT
def assertRaises(self, func, args, kwargs, expected_exception, expected_message): """ Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_message -- expected exception message (or pattern if a compiled regex object) Returns the exception raised for further testing. """ if args is None: args = () if kwargs is None: kwargs = {} try: func(*args, **kwargs) except expected_exception as err: actual_message = str(err) if isinstance(expected_message, re.Pattern): self.assertTrue(expected_message.search(actual_message), """\ expected exception message pattern: /%s/ actual exception message: '''%s''' """ % (expected_message.pattern, actual_message)) else: self.assertEqual(actual_message, expected_message, """\ expected exception message: '''%s''' actual exception message: '''%s''' """ % (expected_message, actual_message)) return err else: self.fail("""expected exception %(expected_exception)s not raised called %(func)r with args %(args)r and kwargs %(kwargs)r """ % locals ())
Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_message -- expected exception message (or pattern if a compiled regex object) Returns the exception raised for further testing.
assertRaises
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
MIT
def assertParseFail(self, cmdline_args, expected_output): """ Assert the parser fails with the expected message. Caller must ensure that self.parser is an InterceptingOptionParser. """ try: self.parser.parse_args(cmdline_args) except InterceptedError as err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure")
Assert the parser fails with the expected message. Caller must ensure that self.parser is an InterceptingOptionParser.
assertParseFail
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
MIT
def assertOutput(self, cmdline_args, expected_output, expected_status=0, expected_error=None): """Assert the parser prints the expected output on stdout.""" save_stdout = sys.stdout try: try: sys.stdout = StringIO() self.parser.parse_args(cmdline_args) finally: output = sys.stdout.getvalue() sys.stdout = save_stdout except InterceptedError as err: self.assertTrue( isinstance(output, str), "expected output to be an ordinary string, not %r" % type(output)) if output != expected_output: self.fail("expected: \n'''\n" + expected_output + "'''\nbut got \n'''\n" + output + "'''") self.assertEqual(err.exit_status, expected_status) self.assertEqual(err.exit_message, expected_error) else: self.assertFalse("expected parser.exit()")
Assert the parser prints the expected output on stdout.
assertOutput
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
MIT
def assertTypeError(self, func, expected_message, *args): """Assert that TypeError is raised when executing func.""" self.assertRaises(func, args, None, TypeError, expected_message)
Assert that TypeError is raised when executing func.
assertTypeError
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_optparse.py
MIT
def test_annotation_usage_with_methods(self): self.assertEqual(XMeth(1).double(), 2) self.assertEqual(XMeth(42).x, XMeth(42)[0]) self.assertEqual(str(XRepr(42)), '42 -> 1') self.assertEqual(XRepr(1, 2) + XRepr(3), 0) with self.assertRaises(AttributeError): exec(""" class XMethBad(NamedTuple): x: int def _fields(self): return 'no chance for this' """) with self.assertRaises(AttributeError): exec(""" class XMethBad2(NamedTuple): x: int def _source(self): return 'no chance for this as well' """)
) with self.assertRaises(AttributeError): exec(
test_annotation_usage_with_methods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typing.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typing.py
MIT
def _test(self, meth, *, args=[URL], kw={}, options, arguments): """Given a web browser instance method name along with arguments and keywords for same (which defaults to the single argument URL), creates a browser instance from the class pointed to by self.browser, calls the indicated instance method with the indicated arguments, and compares the resulting options and arguments passed to Popen by the browser instance against the 'options' and 'args' lists. Options are compared in a position independent fashion, and the arguments are compared in sequence order to whatever is left over after removing the options. """ popen = PopenMock() support.patch(self, subprocess, 'Popen', popen) browser = self.browser_class(name=CMD_NAME) getattr(browser, meth)(*args, **kw) popen_args = subprocess.Popen.call_args[0][0] self.assertEqual(popen_args[0], CMD_NAME) popen_args.pop(0) for option in options: self.assertIn(option, popen_args) popen_args.pop(popen_args.index(option)) self.assertEqual(popen_args, arguments)
Given a web browser instance method name along with arguments and keywords for same (which defaults to the single argument URL), creates a browser instance from the class pointed to by self.browser, calls the indicated instance method with the indicated arguments, and compares the resulting options and arguments passed to Popen by the browser instance against the 'options' and 'args' lists. Options are compared in a position independent fashion, and the arguments are compared in sequence order to whatever is left over after removing the options.
_test
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_webbrowser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_webbrowser.py
MIT
def fix_ext_py(filename): """Given a .pyc filename converts it to the appropriate .py""" if filename.endswith('.pyc'): filename = filename[:-1] return filename
Given a .pyc filename converts it to the appropriate .py
fix_ext_py
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
MIT
def my_file_and_modname(): """The .py file and module name of this file (__file__)""" modname = os.path.splitext(os.path.basename(__file__))[0] return fix_ext_py(__file__), modname
The .py file and module name of this file (__file__)
my_file_and_modname
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_trace.py
MIT
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
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.
test_issue24667
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ordered_dict.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_ordered_dict.py
MIT
def test_builtin_sequence_types(self): # a collection of tests on builtin sequence types a = range(10) for i in a: self.assertIn(i, a) self.assertNotIn(16, a) self.assertNotIn(a, a) a = tuple(a) for i in a: self.assertIn(i, a) self.assertNotIn(16, a) self.assertNotIn(a, a) class Deviant1: """Behaves strangely when compared This class is designed to make sure that the contains code works when the list is modified during the check. """ aList = list(range(15)) def __eq__(self, other): if other == 12: self.aList.remove(12) self.aList.remove(13) self.aList.remove(14) return 0 self.assertNotIn(Deviant1(), Deviant1.aList)
Behaves strangely when compared This class is designed to make sure that the contains code works when the list is modified during the check.
test_builtin_sequence_types
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contains.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contains.py
MIT
def test_block_fallback(self): # blocking fallback with __contains__ = None class ByContains(object): def __contains__(self, other): return False c = ByContains() class BlockContains(ByContains): """Is not a container This class is a perfectly good iterable (as tested by list(bc)), as well as inheriting from a perfectly good container, but __contains__ = None prevents the usual fallback to iteration in the container protocol. That is, normally, 0 in bc would fall back to the equivalent of any(x==0 for x in bc), but here it's blocked from doing so. """ def __iter__(self): while False: yield None __contains__ = None bc = BlockContains() self.assertFalse(0 in c) self.assertFalse(0 in list(bc)) self.assertRaises(TypeError, lambda: 0 in bc)
Is not a container This class is a perfectly good iterable (as tested by list(bc)), as well as inheriting from a perfectly good container, but __contains__ = None prevents the usual fallback to iteration in the container protocol. That is, normally, 0 in bc would fall back to the equivalent of any(x==0 for x in bc), but here it's blocked from doing so.
test_block_fallback
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contains.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contains.py
MIT
def is_env_var_to_ignore(n): """Determine if an environment variable is under our control.""" # This excludes some __CF_* and VERSIONER_* keys MacOS insists # on adding even when the environment in exec is empty. # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist. return ('VERSIONER' in n or '__CF' in n or # MacOS '__PYVENV_LAUNCHER__' in n or # MacOS framework build n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo n == 'LC_CTYPE') # Locale coercion triggered
Determine if an environment variable is under our control.
test_empty_env.is_env_var_to_ignore
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_empty_env(self): """Verify that env={} is as empty as possible.""" def is_env_var_to_ignore(n): """Determine if an environment variable is under our control.""" # This excludes some __CF_* and VERSIONER_* keys MacOS insists # on adding even when the environment in exec is empty. # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist. return ('VERSIONER' in n or '__CF' in n or # MacOS '__PYVENV_LAUNCHER__' in n or # MacOS framework build n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo n == 'LC_CTYPE') # Locale coercion triggered with subprocess.Popen([sys.executable, "-c", 'import os; print(list(os.environ.keys()))'], stdout=subprocess.PIPE, env={}) as p: stdout, stderr = p.communicate() child_env_names = eval(stdout.strip()) self.assertIsInstance(child_env_names, list) child_env_names = [k for k in child_env_names if not is_env_var_to_ignore(k)] self.assertEqual(child_env_names, [])
Verify that env={} is as empty as possible.
test_empty_env
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_threadsafe_wait(self): """Issue21291: Popen.wait() needs to be threadsafe for returncode.""" proc = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(12)']) self.assertEqual(proc.returncode, None) results = [] def kill_proc_timer_thread(): results.append(('thread-start-poll-result', proc.poll())) # terminate it from the thread and wait for the result. proc.kill() proc.wait() results.append(('thread-after-kill-and-wait', proc.returncode)) # this wait should be a no-op given the above. proc.wait() results.append(('thread-after-second-wait', proc.returncode)) # This is a timing sensitive test, the failure mode is # triggered when both the main thread and this thread are in # the wait() call at once. The delay here is to allow the # main thread to most likely be blocked in its wait() call. t = threading.Timer(0.2, kill_proc_timer_thread) t.start() if mswindows: expected_errorcode = 1 else: # Should be -9 because of the proc.kill() from the thread. expected_errorcode = -9 # Wait for the process to finish; the thread should kill it # long before it finishes on its own. Supplying a timeout # triggers a different code path for better coverage. proc.wait(timeout=20) self.assertEqual(proc.returncode, expected_errorcode, msg="unexpected result in wait from main thread") # This should be a no-op with no change in returncode. proc.wait() self.assertEqual(proc.returncode, expected_errorcode, msg="unexpected result in second main wait.") t.join() # Ensure that all of the thread results are as expected. # When a race condition occurs in wait(), the returncode could # be set by the wrong thread that doesn't actually have it # leading to an incorrect value. self.assertEqual([('thread-start-poll-result', None), ('thread-after-kill-and-wait', expected_errorcode), ('thread-after-second-wait', expected_errorcode)], results)
Issue21291: Popen.wait() needs to be threadsafe for returncode.
test_threadsafe_wait
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_failed_child_execute_fd_leak(self): """Test for the fork() failure fd leak reported in issue16327.""" fd_directory = '/proc/%d/fd' % os.getpid() fds_before_popen = os.listdir(fd_directory) with self.assertRaises(PopenTestException): PopenExecuteChildRaises( [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # NOTE: This test doesn't verify that the real _execute_child # does not close the file descriptors itself on the way out # during an exception. Code inspection has confirmed that. fds_after_exception = os.listdir(fd_directory) self.assertEqual(fds_before_popen, fds_after_exception)
Test for the fork() failure fd leak reported in issue16327.
test_failed_child_execute_fd_leak
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def run_python(self, code, **kwargs): """Run Python code in a subprocess using subprocess.run""" argv = [sys.executable, "-c", code] return subprocess.run(argv, **kwargs)
Run Python code in a subprocess using subprocess.run
run_python
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_run_with_shell_timeout_and_capture_output(self): """Output capturing after a timeout mustn't hang forever on open filehandles.""" before_secs = time.monotonic() try: subprocess.run('sleep 3', shell=True, timeout=0.1, capture_output=True) # New session unspecified. except subprocess.TimeoutExpired as exc: after_secs = time.monotonic() stacks = traceback.format_exc() # assertRaises doesn't give this. else: self.fail("TimeoutExpired not raised.") self.assertLess(after_secs - before_secs, 1.5, msg="TimeoutExpired was delayed! Bad traceback:\n```\n" f"{stacks}```")
Output capturing after a timeout mustn't hang forever on open filehandles.
test_run_with_shell_timeout_and_capture_output
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_exception_cwd(self): """Test error in the child raised in the parent for a bad cwd.""" desired_exception = self._get_chdir_exception() try: p = subprocess.Popen([sys.executable, "-c", ""], cwd=self._nonexistent_dir) except OSError as e: # Test that the child process chdir failure actually makes # it up to the parent process as the correct exception. self.assertEqual(desired_exception.errno, e.errno) self.assertEqual(desired_exception.strerror, e.strerror) else: self.fail("Expected OSError: %s" % desired_exception)
Test error in the child raised in the parent for a bad cwd.
test_exception_cwd
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_exception_bad_executable(self): """Test error in the child raised in the parent for a bad executable.""" desired_exception = self._get_chdir_exception() try: p = subprocess.Popen([sys.executable, "-c", ""], executable=self._nonexistent_dir) except OSError as e: # Test that the child process exec failure actually makes # it up to the parent process as the correct exception. self.assertEqual(desired_exception.errno, e.errno) self.assertEqual(desired_exception.strerror, e.strerror) else: self.fail("Expected OSError: %s" % desired_exception)
Test error in the child raised in the parent for a bad executable.
test_exception_bad_executable
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_exception_bad_args_0(self): """Test error in the child raised in the parent for a bad args[0].""" desired_exception = self._get_chdir_exception() try: p = subprocess.Popen([self._nonexistent_dir, "-c", ""]) except OSError as e: # Test that the child process exec failure actually makes # it up to the parent process as the correct exception. self.assertEqual(desired_exception.errno, e.errno) self.assertEqual(desired_exception.strerror, e.strerror) else: self.fail("Expected OSError: %s" % desired_exception)
Test error in the child raised in the parent for a bad args[0].
test_exception_bad_args_0
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_exception_errpipe_normal(self, fork_exec): """Test error passing done through errpipe_write in the good case""" def proper_error(*args): errpipe_write = args[13] # Write the hex for the error code EISDIR: 'is a directory' err_code = '{:x}'.format(errno.EISDIR).encode() os.write(errpipe_write, b"OSError:" + err_code + b":") return 0 fork_exec.side_effect = proper_error with mock.patch("subprocess.os.waitpid", side_effect=ChildProcessError): with self.assertRaises(IsADirectoryError): self.PopenNoDestructor(["non_existent_command"])
Test error passing done through errpipe_write in the good case
test_exception_errpipe_normal
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_exception_errpipe_bad_data(self, fork_exec): """Test error passing done through errpipe_write where its not in the expected format""" error_data = b"\xFF\x00\xDE\xAD" def bad_error(*args): errpipe_write = args[13] # Anything can be in the pipe, no assumptions should # be made about its encoding, so we'll write some # arbitrary hex bytes to test it out os.write(errpipe_write, error_data) return 0 fork_exec.side_effect = bad_error with mock.patch("subprocess.os.waitpid", side_effect=ChildProcessError): with self.assertRaises(subprocess.SubprocessError) as e: self.PopenNoDestructor(["non_existent_command"]) self.assertIn(repr(error_data), str(e.exception))
Test error passing done through errpipe_write where its not in the expected format
test_exception_errpipe_bad_data
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_preexec_errpipe_does_not_double_close_pipes(self): """Issue16140: Don't double close pipes on preexec error.""" def raise_it(): raise subprocess.SubprocessError( "force the _execute_child() errpipe_data path.") with self.assertRaises(subprocess.SubprocessError): self._TestExecuteChildPopen( self, [sys.executable, "-c", "pass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=raise_it)
Issue16140: Don't double close pipes on preexec error.
test_preexec_errpipe_does_not_double_close_pipes
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_small_errpipe_write_fd(self): """Issue #15798: Popen should work when stdio fds are available.""" new_stdin = os.dup(0) new_stdout = os.dup(1) try: os.close(0) os.close(1) # Side test: if errpipe_write fails to have its CLOEXEC # flag set this should cause the parent to think the exec # failed. Extremely unlikely: everyone supports CLOEXEC. subprocess.Popen([ sys.executable, "-c", "print('AssertionError:0:CLOEXEC failure.')"]).wait() finally: # Restore original stdin and stdout os.dup2(new_stdin, 0) os.dup2(new_stdout, 1) os.close(new_stdin) os.close(new_stdout)
Issue #15798: Popen should work when stdio fds are available.
test_small_errpipe_write_fd
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds): saved_fds = self._save_fds(range(3)) try: for from_fd in from_fds: with tempfile.TemporaryFile() as f: os.dup2(f.fileno(), from_fd) fd_to_close = (set(range(3)) - set(from_fds)).pop() os.close(fd_to_close) arg_names = ['stdin', 'stdout', 'stderr'] kwargs = {} for from_fd, to_fd in zip(from_fds, to_fds): kwargs[arg_names[to_fd]] = from_fd code = textwrap.dedent(r''' import os, sys skipped_fd = int(sys.argv[1]) for fd in range(3): if fd != skipped_fd: os.write(fd, str(fd).encode('ascii')) ''') skipped_fd = (set(range(3)) - set(to_fds)).pop() rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)], **kwargs) self.assertEqual(rc, 0) for from_fd, to_fd in zip(from_fds, to_fds): os.lseek(from_fd, 0, os.SEEK_SET) read_bytes = os.read(from_fd, 1024) read_fds = list(map(int, read_bytes.decode('ascii'))) msg = textwrap.dedent(f""" When testing {from_fds} to {to_fds} redirection, parent descriptor {from_fd} got redirected to descriptor(s) {read_fds} instead of descriptor {to_fd}. """) self.assertEqual([to_fd], read_fds, msg) finally: self._restore_fds(saved_fds)
) skipped_fd = (set(range(3)) - set(to_fds)).pop() rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)], **kwargs) self.assertEqual(rc, 0) for from_fd, to_fd in zip(from_fds, to_fds): os.lseek(from_fd, 0, os.SEEK_SET) read_bytes = os.read(from_fd, 1024) read_fds = list(map(int, read_bytes.decode('ascii'))) msg = textwrap.dedent(f
_check_swap_std_fds_with_one_closed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_close_fds_when_max_fd_is_lowered(self): """Confirm that issue21618 is fixed (may fail under valgrind).""" fd_status = support.findfile("fd_status.py", subdir="subprocessdata") # This launches the meat of the test in a child process to # avoid messing with the larger unittest processes maximum # number of file descriptors. # This process launches: # +--> Process that lowers its RLIMIT_NOFILE aftr setting up # a bunch of high open fds above the new lower rlimit. # Those are reported via stdout before launching a new # process with close_fds=False to run the actual test: # +--> The TEST: This one launches a fd_status.py # subprocess with close_fds=True so we can find out if # any of the fds above the lowered rlimit are still open. p = subprocess.Popen([sys.executable, '-c', textwrap.dedent( ''' import os, resource, subprocess, sys, textwrap open_fds = set() # Add a bunch more fds to pass down. for _ in range(40): fd = os.open(os.devnull, os.O_RDONLY) open_fds.add(fd) # Leave a two pairs of low ones available for use by the # internal child error pipe and the stdout pipe. # We also leave 10 more open as some Python buildbots run into # "too many open files" errors during the test if we do not. for fd in sorted(open_fds)[:14]: os.close(fd) open_fds.remove(fd) for fd in open_fds: #self.addCleanup(os.close, fd) os.set_inheritable(fd, True) max_fd_open = max(open_fds) # Communicate the open_fds to the parent unittest.TestCase process. print(','.join(map(str, sorted(open_fds)))) sys.stdout.flush() rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE) try: # 29 is lower than the highest fds we are leaving open. resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max)) # Launch a new Python interpreter with our low fd rlim_cur that # inherits open fds above that limit. It then uses subprocess # with close_fds=True to get a report of open fds in the child. # An explicit list of fds to check is passed to fd_status.py as # letting fd_status rely on its default logic would miss the # fds above rlim_cur as it normally only checks up to that limit. subprocess.Popen( [sys.executable, '-c', textwrap.dedent(""" import subprocess, sys subprocess.Popen([sys.executable, %r] + [str(x) for x in range({max_fd})], close_fds=True).wait() """.format(max_fd=max_fd_open+1))], close_fds=False).wait() finally: resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max)) ''' % fd_status)], stdout=subprocess.PIPE) output, unused_stderr = p.communicate() output_lines = output.splitlines() self.assertEqual(len(output_lines), 2, msg="expected exactly two lines of output:\n%r" % output) opened_fds = set(map(int, output_lines[0].strip().split(b','))) remaining_fds = set(map(int, output_lines[1].strip().split(b','))) self.assertFalse(remaining_fds & opened_fds, msg="Some fds were left open.")
Confirm that issue21618 is fixed (may fail under valgrind).
test_close_fds_when_max_fd_is_lowered
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_pass_fds_redirected(self): """Regression test for https://bugs.python.org/issue32270.""" fd_status = support.findfile("fd_status.py", subdir="subprocessdata") pass_fds = [] for _ in range(2): fd = os.open(os.devnull, os.O_RDWR) self.addCleanup(os.close, fd) pass_fds.append(fd) stdout_r, stdout_w = os.pipe() self.addCleanup(os.close, stdout_r) self.addCleanup(os.close, stdout_w) pass_fds.insert(1, stdout_w) with subprocess.Popen([sys.executable, fd_status], stdin=pass_fds[0], stdout=pass_fds[1], stderr=pass_fds[2], close_fds=True, pass_fds=pass_fds): output = os.read(stdout_r, 1024) fds = {int(num) for num in output.split(b',')} self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
Regression test for https://bugs.python.org/issue32270.
test_pass_fds_redirected
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_stopped(self): """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335.""" args = [sys.executable, '-c', 'pass'] proc = subprocess.Popen(args) # Wait until the real process completes to avoid zombie process pid = proc.pid pid, status = os.waitpid(pid, 0) self.assertEqual(status, 0) status = _testcapi.W_STOPCODE(3) with mock.patch('subprocess.os.waitpid', return_value=(pid, status)): returncode = proc.wait() self.assertEqual(returncode, -3)
Test wait() behavior when waitpid returns WIFSTOPPED; issue29335.
test_stopped
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate, **kwargs): """Fake a SIGINT happening during Popen._communicate() and ._wait(). This avoids the need to actually try and get test environments to send and receive signals reliably across platforms. The net effect of a ^C happening during a blocking subprocess execution which we want to clean up from is a KeyboardInterrupt coming out of communicate() or wait(). """ mock__communicate.side_effect = KeyboardInterrupt try: with mock.patch.object(subprocess.Popen, "_wait") as mock__wait: # We patch out _wait() as no signal was involved so the # child process isn't actually going to exit rapidly. mock__wait.side_effect = KeyboardInterrupt with mock.patch.object(subprocess, "Popen", self.RecordingPopen): with self.assertRaises(KeyboardInterrupt): popener([sys.executable, "-c", "import time\ntime.sleep(9)\nimport sys\n" "sys.stderr.write('\\n!runaway child!\\n')"], stdout=subprocess.DEVNULL, **kwargs) for call in mock__wait.call_args_list[1:]: self.assertNotEqual( call, mock.call(timeout=None), "no open-ended wait() after the first allowed: " f"{mock__wait.call_args_list}") sigint_calls = [] for call in mock__wait.call_args_list: if call == mock.call(timeout=0.25): # from Popen.__init__ sigint_calls.append(call) self.assertLessEqual(mock__wait.call_count, 2, msg=mock__wait.call_args_list) self.assertEqual(len(sigint_calls), 1, msg=mock__wait.call_args_list) finally: # cleanup the forgotten (due to our mocks) child process process = self.RecordingPopen.instances_created.pop() process.kill() process.wait() self.assertEqual([], self.RecordingPopen.instances_created)
Fake a SIGINT happening during Popen._communicate() and ._wait(). This avoids the need to actually try and get test environments to send and receive signals reliably across platforms. The net effect of a ^C happening during a blocking subprocess execution which we want to clean up from is a KeyboardInterrupt coming out of communicate() or wait().
_test_keyboardinterrupt_no_kill
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test__all__(self): """Ensure that __all__ is populated properly.""" intentionally_excluded = {"list2cmdline", "Handle"} exported = set(subprocess.__all__) possible_exports = set() import types for name, value in subprocess.__dict__.items(): if name.startswith('_'): continue if isinstance(value, (types.ModuleType,)): continue possible_exports.add(name) self.assertEqual(exported, possible_exports - intentionally_excluded)
Ensure that __all__ is populated properly.
test__all__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_broken_pipe_cleanup(self): """Broken pipe error should not prevent wait() (Issue 21619)""" proc = subprocess.Popen([sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, bufsize=support.PIPE_MAX_SIZE*2) proc = proc.__enter__() # Prepare to send enough data to overflow any OS pipe buffering and # guarantee a broken pipe error. Data is held in BufferedWriter # buffer until closed. proc.stdin.write(b'x' * support.PIPE_MAX_SIZE) self.assertIsNone(proc.returncode) # EPIPE expected under POSIX; EINVAL under Windows self.assertRaises(OSError, proc.__exit__, None, None, None) self.assertEqual(proc.returncode, 0) self.assertTrue(proc.stdin.closed)
Broken pipe error should not prevent wait() (Issue 21619)
test_broken_pipe_cleanup
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_subprocess.py
MIT
def test_pattern_override(self): class MyPattern(Template): pattern = r""" (?P<escaped>@{2}) | @(?P<named>[_a-z][._a-z0-9]*) | @{(?P<braced>[_a-z][._a-z0-9]*)} | (?P<invalid>@) """ m = Mapping() m.bag = Bag() m.bag.foo = Bag() m.bag.foo.who = 'tim' m.bag.what = 'ham' s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what') self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham') class BadPattern(Template): pattern = r""" (?P<badname>.*) | (?P<escaped>@{2}) | @(?P<named>[_a-z][._a-z0-9]*) | @{(?P<braced>[_a-z][._a-z0-9]*)} | (?P<invalid>@) | """ s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what') self.assertRaises(ValueError, s.substitute, {}) self.assertRaises(ValueError, s.safe_substitute, {})
m = Mapping() m.bag = Bag() m.bag.foo = Bag() m.bag.foo.who = 'tim' m.bag.what = 'ham' s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what') self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham') class BadPattern(Template): pattern = r
test_pattern_override
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_string.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_string.py
MIT
def evaluate_slice_index(arg): """ Helper function to convert a slice argument to an integer, and raise TypeError with a suitable message on failure. """ if hasattr(arg, '__index__'): return operator.index(arg) else: raise TypeError( "slice indices must be integers or " "None or have an __index__ method")
Helper function to convert a slice argument to an integer, and raise TypeError with a suitable message on failure.
evaluate_slice_index
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_slice.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_slice.py
MIT
def slice_indices(slice, length): """ Reference implementation for the slice.indices method. """ # Compute step and length as integers. length = operator.index(length) step = 1 if slice.step is None else evaluate_slice_index(slice.step) # Raise ValueError for negative length or zero step. if length < 0: raise ValueError("length should not be negative") if step == 0: raise ValueError("slice step cannot be zero") # Find lower and upper bounds for start and stop. lower = -1 if step < 0 else 0 upper = length - 1 if step < 0 else length # Compute start. if slice.start is None: start = upper if step < 0 else lower else: start = evaluate_slice_index(slice.start) start = max(start + length, lower) if start < 0 else min(start, upper) # Compute stop. if slice.stop is None: stop = lower if step < 0 else upper else: stop = evaluate_slice_index(slice.stop) stop = max(stop + length, lower) if stop < 0 else min(stop, upper) return start, stop, step
Reference implementation for the slice.indices method.
slice_indices
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_slice.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_slice.py
MIT
def _have_socket_can(): """Check whether CAN sockets are supported on this host.""" try: s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) except (AttributeError, OSError): return False else: s.close() return True
Check whether CAN sockets are supported on this host.
_have_socket_can
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def _have_socket_can_isotp(): """Check whether CAN ISOTP sockets are supported on this host.""" try: s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) except (AttributeError, OSError): return False else: s.close() return True
Check whether CAN ISOTP sockets are supported on this host.
_have_socket_can_isotp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def _have_socket_rds(): """Check whether RDS sockets are supported on this host.""" try: s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) except (AttributeError, OSError): return False else: s.close() return True
Check whether RDS sockets are supported on this host.
_have_socket_rds
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def _have_socket_alg(): """Check whether AF_ALG sockets are supported on this host.""" try: s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) except (AttributeError, OSError): return False else: s.close() return True
Check whether AF_ALG sockets are supported on this host.
_have_socket_alg
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def _have_socket_vsock(): """Check whether AF_VSOCK sockets are supported on this host.""" ret = get_cid() is not None return ret
Check whether AF_VSOCK sockets are supported on this host.
_have_socket_vsock
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def serverExplicitReady(self): """This method allows the server to explicitly indicate that it wants the client thread to proceed. This is useful if the server is about to execute a blocking routine that is dependent upon the client thread during its setup routine.""" self.server_ready.set()
This method allows the server to explicitly indicate that it wants the client thread to proceed. This is useful if the server is about to execute a blocking routine that is dependent upon the client thread during its setup routine.
serverExplicitReady
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def bindServer(self): """Bind server socket and set self.serv_addr to its address.""" self.bindSock(self.serv) self.serv_addr = self.serv.getsockname()
Bind server socket and set self.serv_addr to its address.
bindServer
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def newClientSocket(self): """Return a new socket for use as client.""" return self.newSocket()
Return a new socket for use as client.
newClientSocket
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def bindClient(self): """Bind client socket and set self.cli_addr to its address.""" self.bindSock(self.cli) self.cli_addr = self.cli.getsockname()
Bind client socket and set self.cli_addr to its address.
bindClient
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def skipWithClientIf(condition, reason): """Skip decorated test if condition is true, add client_skip decorator. If the decorated object is not a class, sets its attribute "client_skip" to a decorator which will return an empty function if the test is to be skipped, or the original function if it is not. This can be used to avoid running the client part of a skipped test when using ThreadableTest. """ def client_pass(*args, **kwargs): pass def skipdec(obj): retval = unittest.skip(reason)(obj) if not isinstance(obj, type): retval.client_skip = lambda f: client_pass return retval def noskipdec(obj): if not (isinstance(obj, type) or hasattr(obj, "client_skip")): obj.client_skip = lambda f: f return obj return skipdec if condition else noskipdec
Skip decorated test if condition is true, add client_skip decorator. If the decorated object is not a class, sets its attribute "client_skip" to a decorator which will return an empty function if the test is to be skipped, or the original function if it is not. This can be used to avoid running the client part of a skipped test when using ThreadableTest.
skipWithClientIf
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def requireAttrs(obj, *attributes): """Skip decorated test if obj is missing any of the given attributes. Sets client_skip attribute as skipWithClientIf() does. """ missing = [name for name in attributes if not hasattr(obj, name)] return skipWithClientIf( missing, "don't have " + ", ".join(name for name in missing))
Skip decorated test if obj is missing any of the given attributes. Sets client_skip attribute as skipWithClientIf() does.
requireAttrs
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def requireSocket(*args): """Skip decorated test if a socket cannot be created with given arguments. When an argument is given as a string, will use the value of that attribute of the socket module, or skip the test if it doesn't exist. Sets client_skip attribute as skipWithClientIf() does. """ err = None missing = [obj for obj in args if isinstance(obj, str) and not hasattr(socket, obj)] if missing: err = "don't have " + ", ".join(name for name in missing) else: callargs = [getattr(socket, obj) if isinstance(obj, str) else obj for obj in args] try: s = socket.socket(*callargs) except OSError as e: # XXX: check errno? err = str(e) else: s.close() return skipWithClientIf( err is not None, "can't create socket({0}): {1}".format( ", ".join(str(o) for o in args), err))
Skip decorated test if a socket cannot be created with given arguments. When an argument is given as a string, will use the value of that attribute of the socket module, or skip the test if it doesn't exist. Sets client_skip attribute as skipWithClientIf() does.
requireSocket
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def build_can_frame(cls, can_id, data): """Build a CAN frame.""" can_dlc = len(data) data = data.ljust(8, b'\x00') return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
Build a CAN frame.
build_can_frame
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def dissect_can_frame(cls, frame): """Dissect a CAN frame.""" can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame) return (can_id, can_dlc, data[:can_dlc])
Dissect a CAN frame.
dissect_can_frame
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def mocked_socket_module(self): """Return a socket which times out on connect""" old_socket = socket.socket socket.socket = self.MockSocket try: yield finally: socket.socket = old_socket
Return a socket which times out on connect
mocked_socket_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def isTipcAvailable(): """Check if the TIPC module is loaded The TIPC module is not loaded automatically on Ubuntu and probably other Linux distros. """ if not hasattr(socket, "AF_TIPC"): return False try: f = open("/proc/modules") except (FileNotFoundError, IsADirectoryError, PermissionError): # It's ok if the file does not exist, is a directory or if we # have not the permission to read it. return False with f: for line in f: if line.startswith("tipc "): return True return False
Check if the TIPC module is loaded The TIPC module is not loaded automatically on Ubuntu and probably other Linux distros.
isTipcAvailable
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socket.py
MIT
def test_map_submits_without_iteration(self): """Tests verifying issue 11777.""" finished = [] def record_finished(n): finished.append(n) self.executor.map(record_finished, range(10)) self.executor.shutdown(wait=True) self.assertCountEqual(finished, range(10))
Tests verifying issue 11777.
test_map_submits_without_iteration
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
MIT
def _crash(delay=None): """Induces a segfault.""" if delay: time.sleep(delay) import faulthandler faulthandler.disable() faulthandler._sigsegv()
Induces a segfault.
_crash
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
MIT
def _exit(): """Induces a sys exit with exitcode 1.""" sys.exit(1)
Induces a sys exit with exitcode 1.
_exit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
MIT
def _raise_error(Err): """Function that raises an Exception in process.""" hide_process_stderr() raise Err()
Function that raises an Exception in process.
_raise_error
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
MIT
def _return_instance(cls): """Function that returns a instance of cls.""" hide_process_stderr() return cls()
Function that returns a instance of cls.
_return_instance
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_concurrent_futures.py
MIT
def test_no_substitution(self): self._test(""" abc """, """ abc """)
,
test_no_substitution
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
MIT
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)
) self.assertEqual(
test_explicit_parameters_in_docstring
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
MIT
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())
) 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(),
test_left_group
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
MIT
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())
) 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(),
test_nested_groups
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_clinic.py
MIT
def test_empty_maildir(self): """Test an empty maildir mailbox""" # Test for regression on bug #117490: # Make sure the boxes attribute actually gets set. self.mbox = mailbox.Maildir(support.TESTFN) #self.assertTrue(hasattr(self.mbox, "boxes")) #self.assertEqual(len(self.mbox.boxes), 0) self.assertIsNone(self.mbox.next()) self.assertIsNone(self.mbox.next())
Test an empty maildir mailbox
test_empty_maildir
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_mailbox.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_mailbox.py
MIT
def connect(self): """Count the number of times connect() is invoked""" self.connections += 1 return super().connect()
Count the number of times connect() is invoked
connect
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
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)
Check that request() respects the configured block size.
test_blocksize_request
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
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)
Check that send() respects the configured block size.
test_blocksize_send
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_chunked_missing_end(self): """some servers may serve up a short chunked encoding stream""" expected = chunked_expected sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(), expected) resp.close()
some servers may serve up a short chunked encoding stream
test_chunked_missing_end
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_chunked_trailers(self): """See that trailers are read and ignored""" expected = chunked_expected sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end) resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(), expected) # we should have reached the end of the file self.assertEqual(sock.file.read(), b"") #we read to the end resp.close()
See that trailers are read and ignored
test_chunked_trailers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_chunked_sync(self): """Check that we don't read past the end of the chunked-encoding stream""" expected = chunked_expected extradata = "extradata" sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata) resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(), expected) # the file should now have our extradata ready to be read self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end resp.close()
Check that we don't read past the end of the chunked-encoding stream
test_chunked_sync
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_content_length_sync(self): """Check that we don't read past the end of the Content-Length stream""" extradata = b"extradata" expected = b"Hello123\r\n" sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata) resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEqual(resp.read(), expected) # the file should now have our extradata ready to be read self.assertEqual(sock.file.read(), extradata) #we read to the end resp.close()
Check that we don't read past the end of the Content-Length stream
test_content_length_sync
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_putrequest_override_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216). """ class UnsafeHTTPConnection(client.HTTPConnection): def _validate_path(self, url): pass conn = UnsafeHTTPConnection('example.com') conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00')
It should be possible to override the default validation behavior in putrequest (bpo-38216).
test_putrequest_override_validation
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_putrequest_override_encoding(self): """ It should be possible to override the default encoding to transmit bytes in another encoding even if invalid (bpo-36274). """ class UnsafeHTTPConnection(client.HTTPConnection): def _encode_request(self, str_url): return str_url.encode('utf-8') conn = UnsafeHTTPConnection('example.com') conn.sock = FakeSocket('') conn.putrequest('GET', '/☃')
It should be possible to override the default encoding to transmit bytes in another encoding even if invalid (bpo-36274).
test_putrequest_override_encoding
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def make_reset_reader(text): """Return BufferedReader that raises ECONNRESET at EOF""" stream = io.BytesIO(text) def readinto(buffer): size = io.BytesIO.readinto(stream, buffer) if size == 0: raise ConnectionResetError() return size stream.readinto = readinto return io.BufferedReader(stream)
Return BufferedReader that raises ECONNRESET at EOF
test_disconnected.make_reset_reader
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_httplib.py
MIT
def test_windows_message(self): """Should fill in unknown error code in Windows error message""" ctypes = import_module('ctypes') # this error code has no message, Python formats it as hexadecimal code = 3765269347 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Should fill in unknown error code in Windows error message
test_windows_message
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exceptions.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_exceptions.py
MIT
def test_request_headers_dict(self): """ The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset. """ url = "http://example.com" self.assertEqual(Request(url, headers={"Spam-eggs": "blah"} ).headers["Spam-eggs"], "blah") self.assertEqual(Request(url, headers={"spam-EggS": "blah"} ).headers["Spam-eggs"], "blah")
The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset.
test_request_headers_dict
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def test_request_headers_methods(self): """ Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. Method r.remove_header should remove items both from r.headers and r.unredirected_hdrs dictionaries """ url = "http://example.com" req = Request(url, headers={"Spam-eggs": "blah"}) self.assertTrue(req.has_header("Spam-eggs")) self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')]) req.add_header("Foo-Bar", "baz") self.assertEqual(sorted(req.header_items()), [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]) self.assertFalse(req.has_header("Not-there")) self.assertIsNone(req.get_header("Not-there")) self.assertEqual(req.get_header("Not-there", "default"), "default") req.remove_header("Spam-eggs") self.assertFalse(req.has_header("Spam-eggs")) req.add_unredirected_header("Unredirected-spam", "Eggs") self.assertTrue(req.has_header("Unredirected-spam")) req.remove_header("Unredirected-spam") self.assertFalse(req.has_header("Unredirected-spam"))
Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. Method r.remove_header should remove items both from r.headers and r.unredirected_hdrs dictionaries
test_request_headers_methods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT