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
194
url
stringlengths
46
254
license
stringclasses
4 values
def prepare_data(self): """Overload method from UnivariateCommonMixin.""" # Make sure test data has exactly one mode. return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
Overload method from UnivariateCommonMixin.
prepare_data
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
MIT
def load_tests(loader, tests, ignore): """Used for doctest/unittest integration.""" tests.addTests(doctest.DocTestSuite()) return tests
Used for doctest/unittest integration.
load_tests
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_statistics.py
MIT
def test_method(self, arg): """Test method's docs. This method truly does very little.""" self.arg = arg
Test method's docs. This method truly does very little.
make_server.test_method
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def add(x, y): """Add two instances together. This follows PEP008, but has nothing to do with RFC1952. Case should matter: pEp008 and rFC1952. Things that start with http and ftp should be auto-linked, too: http://google.com. """ return x + y
Add two instances together. This follows PEP008, but has nothing to do with RFC1952. Case should matter: pEp008 and rFC1952. Things that start with http and ftp should be auto-linked, too: http://google.com.
make_server.add
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def annotation(x: int): """ Use function annotations. """ return x
Use function annotations.
make_server.annotation
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def make_server(): serv = DocXMLRPCServer(("localhost", 0), logRequests=False) try: # Add some documentation serv.set_server_title("DocXMLRPCServer Test Documentation") serv.set_server_name("DocXMLRPCServer Test Docs") serv.set_server_documentation( "This is an XML-RPC server's documentation, but the server " "can be used by POSTing to /RPC2. Try self.add, too.") # Create and register classes and functions class TestClass(object): def test_method(self, arg): """Test method's docs. This method truly does very little.""" self.arg = arg serv.register_introspection_functions() serv.register_instance(TestClass()) def add(x, y): """Add two instances together. This follows PEP008, but has nothing to do with RFC1952. Case should matter: pEp008 and rFC1952. Things that start with http and ftp should be auto-linked, too: http://google.com. """ return x + y def annotation(x: int): """ Use function annotations. """ return x class ClassWithAnnotation: def method_annotation(self, x: bytes): return x.decode() serv.register_function(add) serv.register_function(lambda x, y: x-y) serv.register_function(annotation) serv.register_instance(ClassWithAnnotation()) return serv except: serv.server_close() raise
Test method's docs. This method truly does very little.
make_server
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def test_lambda(self): """Test that lambda functionality stays the same. The output produced currently is, I suspect invalid because of the unencoded brackets in the HTML, "<lambda>". The subtraction lambda method is tested. """ self.client.request("GET", "/") response = self.client.getresponse() self.assertIn((b'<dl><dt><a name="-&lt;lambda&gt;"><strong>' b'&lt;lambda&gt;</strong></a>(x, y)</dt></dl>'), response.read())
Test that lambda functionality stays the same. The output produced currently is, I suspect invalid because of the unencoded brackets in the HTML, "<lambda>". The subtraction lambda method is tested.
test_lambda
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def test_autolinking(self): """Test that the server correctly automatically wraps references to PEPS and RFCs with links, and that it linkifies text starting with http or ftp protocol prefixes. The documentation for the "add" method contains the test material. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd>' b'<tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;' b'follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">' b'PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;' b'with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">' b'RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;' b'and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;' b'with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;' b'auto-linked,&nbsp;too:<br>\n<a href="http://google.com">' b'http://google.com</a>.</tt></dd></dl>'), response)
Test that the server correctly automatically wraps references to PEPS and RFCs with links, and that it linkifies text starting with http or ftp protocol prefixes. The documentation for the "add" method contains the test material.
test_autolinking
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def test_system_methods(self): """Test the presence of three consecutive system.* methods. This also tests their use of parameter type recognition and the systems related to that process. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp' b'</strong></a>(method_name)</dt><dd><tt><a href="#-system.method' b'Help">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;' b'two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a' b'&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;' b'the&nbsp;specified&nbsp;method.</tt></dd></dl>\n<dl><dt><a name' b'="-system.methodSignature"><strong>system.methodSignature</strong>' b'</a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">' b'system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;' b'int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;' b'describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.' b'&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;' b'method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments' b'<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;' b'<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system' b'.methodSignature.</tt></dd></dl>'), response)
Test the presence of three consecutive system.* methods. This also tests their use of parameter type recognition and the systems related to that process.
test_system_methods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def test_autolink_dotted_methods(self): """Test that selfdot values are made strong automatically in the documentation.""" self.client.request("GET", "/") response = self.client.getresponse() self.assertIn(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""", response.read())
Test that selfdot values are made strong automatically in the documentation.
test_autolink_dotted_methods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def test_annotations(self): """ Test that annotations works as expected """ self.client.request("GET", "/") response = self.client.getresponse() docstring = (b'' if sys.flags.optimize >= 2 else b'<dd><tt>Use&nbsp;function&nbsp;annotations.</tt></dd>') self.assertIn( (b'<dl><dt><a name="-annotation"><strong>annotation</strong></a>' b'(x: int)</dt>' + docstring + b'</dl>\n' b'<dl><dt><a name="-method_annotation"><strong>' b'method_annotation</strong></a>(x: bytes)</dt></dl>'), response.read())
Test that annotations works as expected
test_annotations
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_docxmlrpc.py
MIT
def native_type_range(fmt): """Return range of a native type.""" if fmt == 'c': lh = (0, 256) elif fmt == '?': lh = (0, 2) elif fmt == 'f': lh = (-(1<<63), 1<<63) elif fmt == 'd': lh = (-(1<<1023), 1<<1023) else: for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7): try: struct.pack(fmt, (1<<exp)-1) break except struct.error: pass lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp) return lh
Return range of a native type.
native_type_range
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def randrange_fmt(mode, char, obj): """Return random item for a type specified by a mode and a single format character.""" x = randrange(*fmtdict[mode][char]) if char == 'c': x = bytes([x]) if obj == 'numpy' and x == b'\x00': # http://projects.scipy.org/numpy/ticket/1925 x = b'\x01' if char == '?': x = bool(x) if char == 'f' or char == 'd': x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x
Return random item for a type specified by a mode and a single format character.
randrange_fmt
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def gen_item(fmt, obj): """Return single random item.""" mode, chars = fmt.split('#') x = [] for c in chars: x.append(randrange_fmt(mode, c, obj)) return x[0] if len(x) == 1 else tuple(x)
Return single random item.
gen_item
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def gen_items(n, fmt, obj): """Return a list of random items (or a scalar).""" if n == 0: return gen_item(fmt, obj) lst = [0] * n for i in range(n): lst[i] = gen_item(fmt, obj) return lst
Return a list of random items (or a scalar).
gen_items
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def randitems(n, obj='ndarray', mode=None, char=None): """Return random format, items, item.""" if mode is None: mode = choice(cap[obj][MODE]) if char is None: char = choice(tuple(fmtdict[mode])) multiplier = choice(cap[obj][MULT]) fmt = mode + '#' + char * int(multiplier if multiplier else 1) items = gen_items(n, fmt, obj) item = gen_item(fmt, obj) fmt = mode.strip('amb') + multiplier + char return fmt, items, item
Return random format, items, item.
randitems
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def iter_mode(n, obj='ndarray'): """Iterate through supported mode/char combinations.""" for mode in cap[obj][MODE]: for char in fmtdict[mode]: yield randitems(n, obj, mode, char)
Iterate through supported mode/char combinations.
iter_mode
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def iter_format(nitems, testobj='ndarray'): """Yield (format, items, item) for all possible modes and format characters plus one random compound format string.""" for t in iter_mode(nitems, testobj): yield t if testobj != 'ndarray': return yield struct_items(nitems, testobj)
Yield (format, items, item) for all possible modes and format characters plus one random compound format string.
iter_format
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def is_memoryview_format(fmt): """format suitable for memoryview""" x = len(fmt) return ((x == 1 or (x == 2 and fmt[0] == '@')) and fmt[x-1] in MEMORYVIEW)
format suitable for memoryview
is_memoryview_format
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def atomp(lst): """Tuple items (representing structs) are regarded as atoms.""" return not isinstance(lst, list)
Tuple items (representing structs) are regarded as atoms.
atomp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def prod(lst): """Product of list elements.""" if len(lst) == 0: return 0 x = lst[0] for v in lst[1:]: x *= v return x
Product of list elements.
prod
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def strides_from_shape(ndim, shape, itemsize, layout): """Calculate strides of a contiguous array. Layout is 'C' or 'F' (Fortran).""" if ndim == 0: return () if layout == 'C': strides = list(shape[1:]) + [itemsize] for i in range(ndim-2, -1, -1): strides[i] *= strides[i+1] else: strides = [itemsize] + list(shape[:-1]) for i in range(1, ndim): strides[i] *= strides[i-1] return strides
Calculate strides of a contiguous array. Layout is 'C' or 'F' (Fortran).
strides_from_shape
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def _ca(items, s): """Convert flat item list to the nested list representation of a multidimensional C array with shape 's'.""" if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = len(items) // s[0] if s[0] else 0 for i in range(s[0]): start = i*stride lst[i] = _ca(items[start:start+stride], s[1:]) return lst
Convert flat item list to the nested list representation of a multidimensional C array with shape 's'.
_ca
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def _fa(items, s): """Convert flat item list to the nested list representation of a multidimensional Fortran array with shape 's'.""" if atomp(items): return items if len(s) == 0: return items[0] lst = [0] * s[0] stride = s[0] for i in range(s[0]): lst[i] = _fa(items[i::stride], s[1:]) return lst
Convert flat item list to the nested list representation of a multidimensional Fortran array with shape 's'.
_fa
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def indices(shape): """Generate all possible tuples of indices.""" iterables = [range(v) for v in shape] return product(*iterables)
Generate all possible tuples of indices.
indices
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def getindex(ndim, ind, strides): """Convert multi-dimensional index to the position in the flat list.""" ret = 0 for i in range(ndim): ret += strides[i] * ind[i] return ret
Convert multi-dimensional index to the position in the flat list.
getindex
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def transpose(src, shape): """Transpose flat item list that is regarded as a multi-dimensional matrix defined by shape: dest...[k][j][i] = src[i][j][k]... """ if not shape: return src ndim = len(shape) sstrides = strides_from_shape(ndim, shape, 1, 'C') dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C') dest = [0] * len(src) for ind in indices(shape): fr = getindex(ndim, ind, sstrides) to = getindex(ndim, ind[::-1], dstrides) dest[to] = src[fr] return dest
Transpose flat item list that is regarded as a multi-dimensional matrix defined by shape: dest...[k][j][i] = src[i][j][k]...
transpose
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def _flatten(lst): """flatten list""" if lst == []: return lst if atomp(lst): return [lst] return _flatten(lst[0]) + _flatten(lst[1:])
flatten list
_flatten
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def flatten(lst): """flatten list or return scalar""" if atomp(lst): # scalar return lst return _flatten(lst)
flatten list or return scalar
flatten
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def slice_shape(lst, slices): """Get the shape of lst after slicing: slices is a list of slice objects.""" if atomp(lst): return [] return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:])
Get the shape of lst after slicing: slices is a list of slice objects.
slice_shape
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def multislice(lst, slices): """Multi-dimensional slicing: slices is a list of slice objects.""" if atomp(lst): return lst return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]]
Multi-dimensional slicing: slices is a list of slice objects.
multislice
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def m_assign(llst, rlst, lslices, rslices): """Multi-dimensional slice assignment: llst and rlst are the operands, lslices and rslices are lists of slice objects. llst and rlst must have the same structure. For a two-dimensional example, this is not implemented in Python: llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1] Instead we write: lslices = [slice(0,3,2), slice(0,3,2)] rslices = [slice(1,3,1), slice(1,3,1)] multislice_assign(llst, rlst, lslices, rslices) """ if atomp(rlst): return rlst rlst = [m_assign(l, r, lslices[1:], rslices[1:]) for l, r in zip(llst[lslices[0]], rlst[rslices[0]])] llst[lslices[0]] = rlst return llst
Multi-dimensional slice assignment: llst and rlst are the operands, lslices and rslices are lists of slice objects. llst and rlst must have the same structure. For a two-dimensional example, this is not implemented in Python: llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1] Instead we write: lslices = [slice(0,3,2), slice(0,3,2)] rslices = [slice(1,3,1), slice(1,3,1)] multislice_assign(llst, rlst, lslices, rslices)
m_assign
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def cmp_structure(llst, rlst, lslices, rslices): """Compare the structure of llst[lslices] and rlst[rslices].""" lshape = slice_shape(llst, lslices) rshape = slice_shape(rlst, rslices) if (len(lshape) != len(rshape)): return -1 for i in range(len(lshape)): if lshape[i] != rshape[i]: return -1 if lshape[i] == 0: return 0 return 0
Compare the structure of llst[lslices] and rlst[rslices].
cmp_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def multislice_assign(llst, rlst, lslices, rslices): """Return llst after assigning: llst[lslices] = rlst[rslices]""" if cmp_structure(llst, rlst, lslices, rslices) < 0: raise ValueError("lvalue and rvalue have different structures") return m_assign(llst, rlst, lslices, rslices)
Return llst after assigning: llst[lslices] = rlst[rslices]
multislice_assign
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf - mem """ if offset % itemsize: return False if offset < 0 or offset+itemsize > memlen: return False if any(v % itemsize for v in strides): return False if ndim <= 0: return ndim == 0 and not shape and not strides if 0 in shape: return True imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) return 0 <= offset+imin and offset+imax+itemsize <= memlen
Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf - mem
verify_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def memory_index(indices, t): """Location of an item in the underlying memory.""" memlen, itemsize, ndim, shape, strides, offset = t p = offset for i in range(ndim): p += strides[i]*indices[i] return p
Location of an item in the underlying memory.
memory_index
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def is_overlapping(t): """The structure 't' is overlapping if at least one memory location is visited twice while iterating through all possible tuples of indices.""" memlen, itemsize, ndim, shape, strides, offset = t visited = 1<<memlen for ind in indices(shape): i = memory_index(ind, t) bit = 1<<i if visited & bit: return True visited |= bit return False
The structure 't' is overlapping if at least one memory location is visited twice while iterating through all possible tuples of indices.
is_overlapping
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): """Return random structure: (memlen, itemsize, ndim, shape, strides, offset) If 'valid' is true, the returned structure is valid, otherwise invalid. If 'shape' is given, use that instead of creating a random shape. """ if not shape: ndim = randrange(maxdim+1) if (ndim == 0): if valid: return itemsize, itemsize, ndim, (), (), 0 else: nitems = randrange(1, 16+1) memlen = nitems * itemsize offset = -itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, (), (), offset minshape = 2 n = randrange(100) if n >= 95 and valid: minshape = 0 elif n >= 90: minshape = 1 shape = [0] * ndim for i in range(ndim): shape[i] = randrange(minshape, maxshape+1) else: ndim = len(shape) maxstride = 5 n = randrange(100) zero_stride = True if n >= 95 and n & 1 else False strides = [0] * ndim strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1) if not zero_stride and strides[ndim-1] == 0: strides[ndim-1] = itemsize for i in range(ndim-2, -1, -1): maxstride *= shape[i+1] if shape[i+1] else 1 if zero_stride: strides[i] = itemsize * randrange(-maxstride, maxstride+1) else: strides[i] = ((1,-1)[randrange(2)] * itemsize * randrange(1, maxstride+1)) imin = imax = 0 if not 0 in shape: imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] <= 0) imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) if strides[j] > 0) nitems = imax - imin if valid: offset = -imin * itemsize memlen = offset + (imax+1) * itemsize else: memlen = (-imin + imax) * itemsize offset = -imin-itemsize if randrange(2) == 0 else memlen return memlen, itemsize, ndim, shape, strides, offset
Return random structure: (memlen, itemsize, ndim, shape, strides, offset) If 'valid' is true, the returned structure is valid, otherwise invalid. If 'shape' is given, use that instead of creating a random shape.
rand_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def randslice_from_slicelen(slicelen, listlen): """Create a random slice of len slicelen that fits into listlen.""" maxstart = listlen - slicelen start = randrange(maxstart+1) maxstep = (listlen - start) // slicelen if slicelen else 1 step = randrange(1, maxstep+1) stop = start + slicelen * step s = slice(start, stop, step) _, _, _, control = slice_indices(s, listlen) if control != slicelen: raise RuntimeError return s
Create a random slice of len slicelen that fits into listlen.
randslice_from_slicelen
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def randslice_from_shape(ndim, shape): """Create two sets of slices for an array x with shape 'shape' such that shapeof(x[lslices]) == shapeof(x[rslices]).""" lslices = [0] * ndim rslices = [0] * ndim for n in range(ndim): l = shape[n] slicelen = randrange(1, l+1) if l > 0 else 0 lslices[n] = randslice_from_slicelen(slicelen, l) rslices[n] = randslice_from_slicelen(slicelen, l) return tuple(lslices), tuple(rslices)
Create two sets of slices for an array x with shape 'shape' such that shapeof(x[lslices]) == shapeof(x[rslices]).
randslice_from_shape
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def rand_aligned_slices(maxdim=5, maxshape=16): """Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array with shape 'lshape' and y is an array with shape 'rshape'.""" ndim = randrange(1, maxdim+1) minshape = 2 n = randrange(100) if n >= 95: minshape = 0 elif n >= 90: minshape = 1 all_random = True if randrange(100) >= 80 else False lshape = [0]*ndim; rshape = [0]*ndim lslices = [0]*ndim; rslices = [0]*ndim for n in range(ndim): small = randrange(minshape, maxshape+1) big = randrange(minshape, maxshape+1) if big < small: big, small = small, big # Create a slice that fits the smaller value. if all_random: start = randrange(-small, small+1) stop = randrange(-small, small+1) step = (1,-1)[randrange(2)] * randrange(1, small+2) s_small = slice(start, stop, step) _, _, _, slicelen = slice_indices(s_small, small) else: slicelen = randrange(1, small+1) if small > 0 else 0 s_small = randslice_from_slicelen(slicelen, small) # Create a slice of the same length for the bigger value. s_big = randslice_from_slicelen(slicelen, big) if randrange(2) == 0: rshape[n], lshape[n] = big, small rslices[n], lslices[n] = s_big, s_small else: rshape[n], lshape[n] = small, big rslices[n], lslices[n] = s_small, s_big return lshape, rshape, tuple(lslices), tuple(rslices)
Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array with shape 'lshape' and y is an array with shape 'rshape'.
rand_aligned_slices
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def randitems_from_structure(fmt, t): """Return a list of random items for structure 't' with format 'fmtchar'.""" memlen, itemsize, _, _, _, _ = t return gen_items(memlen//itemsize, '#'+fmt, 'numpy')
Return a list of random items for structure 't' with format 'fmtchar'.
randitems_from_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def ndarray_from_structure(items, fmt, t, flags=0): """Return ndarray from the tuple returned by rand_structure()""" memlen, itemsize, ndim, shape, strides, offset = t return ndarray(items, shape=shape, strides=strides, format=fmt, offset=offset, flags=ND_WRITABLE|flags)
Return ndarray from the tuple returned by rand_structure()
ndarray_from_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def numpy_array_from_structure(items, fmt, t): """Return numpy_array from the tuple returned by rand_structure()""" memlen, itemsize, ndim, shape, strides, offset = t buf = bytearray(memlen) for j, v in enumerate(items): struct.pack_into(fmt, buf, j*itemsize, v) return numpy_array(buffer=buf, shape=shape, strides=strides, dtype=fmt, offset=offset)
Return numpy_array from the tuple returned by rand_structure()
numpy_array_from_structure
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def cast_items(exporter, fmt, itemsize, shape=None): """Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1-D with n * itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) * itemsize = bytelen applies. On success, return (items, shape). If the constraints cannot be met, return (None, None). If a chunk of bytes is interpreted as NaN as a result of float conversion, return ('nan', None).""" bytelen = exporter.nbytes if shape: if prod(shape) * itemsize != bytelen: return None, shape elif shape == []: if exporter.ndim == 0 or itemsize != bytelen: return None, shape else: n, r = divmod(bytelen, itemsize) shape = [n] if r != 0: return None, shape mem = exporter.tobytes() byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)] items = [] for v in byteitems: item = struct.unpack(fmt, v)[0] if item != item: return 'nan', shape items.append(item) return (items, shape) if shape != [] else (items[0], shape)
Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1-D with n * itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) * itemsize = bytelen applies. On success, return (items, shape). If the constraints cannot be met, return (None, None). If a chunk of bytes is interpreted as NaN as a result of float conversion, return ('nan', None).
cast_items
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def gencastshapes(): """Generate shapes to test casting.""" for n in range(32): yield [n] ndim = randrange(4, 6) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)] ndim = randrange(2, 4) minshape = 1 if randrange(100) > 80 else 2 yield [randrange(minshape, 5) for _ in range(ndim)]
Generate shapes to test casting.
gencastshapes
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def genslices(n): """Generate all possible slices for a single dimension.""" return product(range(-n, n+1), range(-n, n+1), range(-n, n+1))
Generate all possible slices for a single dimension.
genslices
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def genslices_ndim(ndim, shape): """Generate all possible slice tuples for 'shape'.""" iterables = [genslices(shape[n]) for n in range(ndim)] return product(*iterables)
Generate all possible slice tuples for 'shape'.
genslices_ndim
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def rslice(n, allow_empty=False): """Generate random slice for a single dimension of length n. If zero=True, the slices may be empty, otherwise they will be non-empty.""" minlen = 0 if allow_empty or n == 0 else 1 slicelen = randrange(minlen, n+1) return randslice_from_slicelen(slicelen, n)
Generate random slice for a single dimension of length n. If zero=True, the slices may be empty, otherwise they will be non-empty.
rslice
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def rslices(n, allow_empty=False): """Generate random slices for a single dimension.""" for _ in range(5): yield rslice(n, allow_empty)
Generate random slices for a single dimension.
rslices
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def rslices_ndim(ndim, shape, iterations=5): """Generate random slice tuples for 'shape'.""" # non-empty slices for _ in range(iterations): yield tuple(rslice(shape[n]) for n in range(ndim)) # possibly empty slices for _ in range(iterations): yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim)) # invalid slices yield tuple(slice(0,1,0) for _ in range(ndim))
Generate random slice tuples for 'shape'.
rslices_ndim
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def ndarray_print(nd): """Print ndarray for debugging.""" try: x = nd.tolist() except (TypeError, NotImplementedError): x = nd.tobytes() if isinstance(nd, ndarray): offset = nd.offset flags = nd.flags else: offset = 'unknown' flags = 'unknown' print("ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, " "format='%s', itemsize=%s, flags=%s)" % (x, nd.shape, nd.strides, nd.suboffsets, offset, nd.format, nd.itemsize, flags)) sys.stdout.flush()
Print ndarray for debugging.
ndarray_print
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_buffer.py
MIT
def _async_test(func): """Decorator to turn an async function into a test case.""" @functools.wraps(func) def wrapper(*args, **kwargs): coro = func(*args, **kwargs) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() asyncio.set_event_loop(None) return wrapper
Decorator to turn an async function into a test case.
_async_test
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
MIT
async def baz(spam): """Whee!""" yield
Whee!
_create_contextmanager_attribs.baz
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
MIT
def _create_contextmanager_attribs(self): def attribs(**kw): def decorate(func): for k,v in kw.items(): setattr(func,k,v) return func return decorate @asynccontextmanager @attribs(foo='bar') async def baz(spam): """Whee!""" yield return baz
Whee!
_create_contextmanager_attribs
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
MIT
async def _exit(*args, **kwds): """Test metadata propagation""" result.append((args, kwds))
Test metadata propagation
test_async_callback._exit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
MIT
async def test_async_callback(self): expected = [ ((), {}), ((1,), {}), ((1,2), {}), ((), dict(example=1)), ((1,), dict(example=1)), ((1,2), dict(example=1)), ] result = [] async def _exit(*args, **kwds): """Test metadata propagation""" result.append((args, kwds)) async with AsyncExitStack() as stack: for args, kwds in reversed(expected): if args and kwds: f = stack.push_async_callback(_exit, *args, **kwds) elif args: f = stack.push_async_callback(_exit, *args) elif kwds: f = stack.push_async_callback(_exit, **kwds) else: f = stack.push_async_callback(_exit) self.assertIs(f, _exit) for wrapper in stack._exit_callbacks: self.assertIs(wrapper[1].__wrapped__, _exit) self.assertNotEqual(wrapper[1].__name__, _exit.__name__) self.assertIsNone(wrapper[1].__doc__, _exit.__doc__) self.assertEqual(result, expected) result = [] async with AsyncExitStack() as stack: with self.assertRaises(TypeError): stack.push_async_callback(arg=1) with self.assertRaises(TypeError): self.exit_stack.push_async_callback(arg=2) stack.push_async_callback(callback=_exit, arg=3) self.assertEqual(result, [((), {'arg': 3})])
Test metadata propagation
test_async_callback
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_contextlib_async.py
MIT
def _check_error(self, code, errtext, filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None): """Check that compiling code raises SyntaxError with errtext. errtest is a regular expression that must be present in the test of the exception raised. If subclass is specified it is the expected subclass of SyntaxError (e.g. IndentationError). """ try: compile(code, filename, mode) except SyntaxError as err: if subclass and not isinstance(err, subclass): self.fail("SyntaxError is not a %s" % subclass.__name__) mo = re.search(errtext, str(err)) if mo is None: self.fail("SyntaxError did not contain '%r'" % (errtext,)) self.assertEqual(err.filename, filename) if lineno is not None: self.assertEqual(err.lineno, lineno) if offset is not None: self.assertEqual(err.offset, offset) else: self.fail("compile() did not raise SyntaxError")
Check that compiling code raises SyntaxError with errtext. errtest is a regular expression that must be present in the test of the exception raised. If subclass is specified it is the expected subclass of SyntaxError (e.g. IndentationError).
_check_error
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_syntax.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_syntax.py
MIT
def assertCloseAbs(self, x, y, eps=1e-9): """Return true iff floats x and y "are close".""" # put the one with larger magnitude second if abs(x) > abs(y): x, y = y, x if y == 0: return abs(x) < eps if x == 0: return abs(y) < eps # check that relative difference < eps self.assertTrue(abs((x-y)/y) < eps)
Return true iff floats x and y "are close".
assertCloseAbs
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def assertFloatsAreIdentical(self, x, y): """assert that floats x and y are identical, in the sense that: (1) both x and y are nans, or (2) both x and y are infinities, with the same sign, or (3) both x and y are zeros, with the same sign, or (4) x and y are both finite and nonzero, and x == y """ msg = 'floats {!r} and {!r} are not identical' if isnan(x) or isnan(y): if isnan(x) and isnan(y): return elif x == y: if x != 0.0: return # both zero; check that signs match elif copysign(1.0, x) == copysign(1.0, y): return else: msg += ': zeros have different signs' self.fail(msg.format(x, y))
assert that floats x and y are identical, in the sense that: (1) both x and y are nans, or (2) both x and y are infinities, with the same sign, or (3) both x and y are zeros, with the same sign, or (4) x and y are both finite and nonzero, and x == y
assertFloatsAreIdentical
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def assertClose(self, x, y, eps=1e-9): """Return true iff complexes x and y "are close".""" self.assertCloseAbs(x.real, y.real, eps) self.assertCloseAbs(x.imag, y.imag, eps)
Return true iff complexes x and y "are close".
assertClose
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def check_div(self, x, y): """Compute complex z=x*y, and check that z/x==y and z/y==x.""" z = x * y if x != 0: q = z / x self.assertClose(q, y) q = z.__truediv__(x) self.assertClose(q, y) if y != 0: q = z / y self.assertClose(q, x) q = z.__truediv__(y) self.assertClose(q, x)
Compute complex z=x*y, and check that z/x==y and z/y==x.
check_div
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def split_zeros(x): """Function that produces different results for 0. and -0.""" return atan2(x, -1.)
Function that produces different results for 0. and -0.
test_constructor.split_zeros
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def test_constructor(self): class OS: def __init__(self, value): self.value = value def __complex__(self): return self.value class NS(object): def __init__(self, value): self.value = value def __complex__(self): return self.value self.assertEqual(complex(OS(1+10j)), 1+10j) self.assertEqual(complex(NS(1+10j)), 1+10j) self.assertRaises(TypeError, complex, OS(None)) self.assertRaises(TypeError, complex, NS(None)) self.assertRaises(TypeError, complex, {}) self.assertRaises(TypeError, complex, NS(1.5)) self.assertRaises(TypeError, complex, NS(1)) self.assertAlmostEqual(complex("1+10j"), 1+10j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10.0), 10+0j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10+0j), 10+0j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10.0), 1+10j) self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) self.assertAlmostEqual(complex(3.14), 3.14+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0j, 3.14), 3.14j) self.assertAlmostEqual(complex(0.0, 3.14), 3.14j) self.assertAlmostEqual(complex("1"), 1+0j) self.assertAlmostEqual(complex("1j"), 1j) self.assertAlmostEqual(complex(), 0) self.assertAlmostEqual(complex("-1"), -1) self.assertAlmostEqual(complex("+1"), +1) self.assertAlmostEqual(complex("(1+2j)"), 1+2j) self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j) self.assertAlmostEqual(complex("3.14+1J"), 3.14+1j) self.assertAlmostEqual(complex(" ( +3.14-6J )"), 3.14-6j) self.assertAlmostEqual(complex(" ( +3.14-J )"), 3.14-1j) self.assertAlmostEqual(complex(" ( +3.14+j )"), 3.14+1j) self.assertAlmostEqual(complex("J"), 1j) self.assertAlmostEqual(complex("( j )"), 1j) self.assertAlmostEqual(complex("+J"), 1j) self.assertAlmostEqual(complex("( -j)"), -1j) self.assertAlmostEqual(complex('1e-500'), 0.0 + 0.0j) self.assertAlmostEqual(complex('-1e-500j'), 0.0 - 0.0j) self.assertAlmostEqual(complex('-1e-500+1e-500j'), -0.0 + 0.0j) class complex2(complex): pass self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j) self.assertAlmostEqual(complex(real=17, imag=23), 17+23j) self.assertAlmostEqual(complex(real=17+23j), 17+23j) self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j) self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j) # check that the sign of a zero in the real or imaginary part # is preserved when constructing from two floats. (These checks # are harmless on systems without support for signed zeros.) def split_zeros(x): """Function that produces different results for 0. and -0.""" return atan2(x, -1.) self.assertEqual(split_zeros(complex(1., 0.).imag), split_zeros(0.)) self.assertEqual(split_zeros(complex(1., -0.).imag), split_zeros(-0.)) self.assertEqual(split_zeros(complex(0., 1.).real), split_zeros(0.)) self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.)) c = 3.14 + 1j self.assertTrue(complex(c) is c) del c self.assertRaises(TypeError, complex, "1", "1") self.assertRaises(TypeError, complex, 1, "1") # SF bug 543840: complex(string) accepts strings with \0 # Fixed in 2.3. self.assertRaises(ValueError, complex, '1+1j\0j') self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, float, 5+3j) self.assertRaises(ValueError, complex, "") self.assertRaises(TypeError, complex, None) self.assertRaisesRegex(TypeError, "not 'NoneType'", complex, None) self.assertRaises(ValueError, complex, "\0") self.assertRaises(ValueError, complex, "3\09") self.assertRaises(TypeError, complex, "1", "2") self.assertRaises(TypeError, complex, "1", 42) self.assertRaises(TypeError, complex, 1, "2") self.assertRaises(ValueError, complex, "1+") self.assertRaises(ValueError, complex, "1+1j+1j") self.assertRaises(ValueError, complex, "--") self.assertRaises(ValueError, complex, "(1+2j") self.assertRaises(ValueError, complex, "1+2j)") self.assertRaises(ValueError, complex, "1+(2j)") self.assertRaises(ValueError, complex, "(1+2j)123") self.assertRaises(ValueError, complex, "x") self.assertRaises(ValueError, complex, "1j+2") self.assertRaises(ValueError, complex, "1e1ej") self.assertRaises(ValueError, complex, "1e++1ej") self.assertRaises(ValueError, complex, ")1+2j(") self.assertRaisesRegex( TypeError, "first argument must be a string or a number, not 'dict'", complex, {1:2}, 1) self.assertRaisesRegex( TypeError, "second argument must be a number, not 'dict'", complex, 1, {1:2}) # the following three are accepted by Python 2.6 self.assertRaises(ValueError, complex, "1..1j") self.assertRaises(ValueError, complex, "1.11.1j") self.assertRaises(ValueError, complex, "1e1.1j") # check that complex accepts long unicode strings self.assertEqual(type(complex("1"*500)), complex) # check whitespace processing self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j) # Invalid unicode string # See bpo-34087 self.assertRaises(ValueError, complex, '\u3053\u3093\u306b\u3061\u306f') class EvilExc(Exception): pass class evilcomplex: def __complex__(self): raise EvilExc self.assertRaises(EvilExc, complex, evilcomplex()) class float2: def __init__(self, value): self.value = value def __float__(self): return self.value self.assertAlmostEqual(complex(float2(42.)), 42) self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j) self.assertRaises(TypeError, complex, float2(None)) class complex0(complex): """Test usage of __complex__() when inheriting from 'complex'""" def __complex__(self): return 42j class complex1(complex): """Test usage of __complex__() with a __new__() method""" def __new__(self, value=0j): return complex.__new__(self, 2*value) def __complex__(self): return self class complex2(complex): """Make sure that __complex__() calls fail if anything other than a complex is returned""" def __complex__(self): return None self.assertEqual(complex(complex0(1j)), 42j) with self.assertWarns(DeprecationWarning): self.assertEqual(complex(complex1(1j)), 2j) self.assertRaises(TypeError, complex, complex2(1j))
Function that produces different results for 0. and -0.
test_constructor
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_complex.py
MIT
def write_file(path, content, binary=False): """Write *content* to a file located at *path*. If *path* is a tuple instead of a string, os.path.join will be used to make a path. If *binary* is true, the file will be opened in binary mode. """ if isinstance(path, tuple): path = os.path.join(*path) with open(path, 'wb' if binary else 'w') as fp: fp.write(content)
Write *content* to a file located at *path*. If *path* is a tuple instead of a string, os.path.join will be used to make a path. If *binary* is true, the file will be opened in binary mode.
write_file
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
MIT
def read_file(path, binary=False): """Return contents from a file located at *path*. If *path* is a tuple instead of a string, os.path.join will be used to make a path. If *binary* is true, the file will be opened in binary mode. """ if isinstance(path, tuple): path = os.path.join(*path) with open(path, 'rb' if binary else 'r') as fp: return fp.read()
Return contents from a file located at *path*. If *path* is a tuple instead of a string, os.path.join will be used to make a path. If *binary* is true, the file will be opened in binary mode.
read_file
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
MIT
def mkdtemp(self): """Create a temporary directory that will be cleaned up. Returns the path of the directory. """ d = tempfile.mkdtemp() self.tempdirs.append(d) return d
Create a temporary directory that will be cleaned up. Returns the path of the directory.
mkdtemp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
MIT
def test_does_not_crash(self): """Check if get_terminal_size() returns a meaningful value. There's no easy portable way to actually check the size of the terminal, so let's check if it returns something sensible instead. """ size = shutil.get_terminal_size() self.assertGreaterEqual(size.columns, 0) self.assertGreaterEqual(size.lines, 0)
Check if get_terminal_size() returns a meaningful value. There's no easy portable way to actually check the size of the terminal, so let's check if it returns something sensible instead.
test_does_not_crash
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
MIT
def test_stty_match(self): """Check if stty returns the same results ignoring env This test will fail if stdin and stdout are connected to different terminals with different sizes. Nevertheless, such situations should be pretty rare. """ try: size = subprocess.check_output(['stty', 'size']).decode().split() except (FileNotFoundError, PermissionError, subprocess.CalledProcessError): self.skipTest("stty invocation failed") expected = (int(size[1]), int(size[0])) # reversed order with support.EnvironmentVarGuard() as env: del env['LINES'] del env['COLUMNS'] actual = shutil.get_terminal_size() self.assertEqual(expected, actual)
Check if stty returns the same results ignoring env This test will fail if stdin and stdout are connected to different terminals with different sizes. Nevertheless, such situations should be pretty rare.
test_stty_match
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_shutil.py
MIT
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = urllib.parse.urlparse(path)[2] path = os.path.normpath(urllib.parse.unquote(path)) words = path.split('/') words = filter(None, words) path = self.root for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) path = os.path.join(path, word) return path
Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)
translate_path
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
MIT
def do_GET(self, send_body=True): """Serve a GET request.""" sock = self.rfile.raw._sock context = sock.context stats = { 'session_cache': context.session_stats(), 'cipher': sock.cipher(), 'compression': sock.compression(), } body = pprint.pformat(stats) body = body.encode('utf-8') self.send_response(200) self.send_header("Content-type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() if send_body: self.wfile.write(body)
Serve a GET request.
do_GET
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
MIT
def do_HEAD(self): """Serve a HEAD request.""" self.do_GET(send_body=False)
Serve a HEAD request.
do_HEAD
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/ssl_servers.py
MIT
def normalize_trace_output(output): """Normalize DTrace output for comparison. DTrace keeps a per-CPU buffer, and when showing the fired probes, buffers are concatenated. So if the operating system moves our thread around, the straight result can be "non-causal". So we add timestamps to the probe firing, sort by that field, then strip it from the output""" # When compiling with '--with-pydebug', strip '[# refs]' debug output. output = re.sub(r"\[[0-9]+ refs\]", "", output) try: result = [ row.split("\t") for row in output.splitlines() if row and not row.startswith('#') ] result.sort(key=lambda row: int(row[0])) result = [row[1] for row in result] return "\n".join(result) except (IndexError, ValueError): raise AssertionError( "tracer produced unparseable output:\n{}".format(output) )
Normalize DTrace output for comparison. DTrace keeps a per-CPU buffer, and when showing the fired probes, buffers are concatenated. So if the operating system moves our thread around, the straight result can be "non-causal". So we add timestamps to the probe firing, sort by that field, then strip it from the output
normalize_trace_output
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dtrace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dtrace.py
MIT
def test_verify_call_opcodes(self): """Ensure our call stack test hits all function call opcodes""" opcodes = set(["CALL_FUNCTION", "CALL_FUNCTION_EX", "CALL_FUNCTION_KW"]) with open(abspath("call_stack.py")) as f: code_string = f.read() def get_function_instructions(funcname): # Recompile with appropriate optimization setting code = compile(source=code_string, filename="<string>", mode="exec", optimize=self.optimize_python) for c in code.co_consts: if isinstance(c, types.CodeType) and c.co_name == funcname: return dis.get_instructions(c) return [] for instruction in get_function_instructions('start'): opcodes.discard(instruction.opname) self.assertEqual(set(), opcodes)
Ensure our call stack test hits all function call opcodes
test_verify_call_opcodes
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dtrace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dtrace.py
MIT
def collect_in_thread(period=0.0001): """ Ensure GC collections happen in a different thread, at a high frequency. """ please_stop = False def collect(): while not please_stop: time.sleep(period) gc.collect() with support.disable_gc(): t = threading.Thread(target=collect) t.start() try: yield finally: please_stop = True t.join()
Ensure GC collections happen in a different thread, at a high frequency.
collect_in_thread
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
MIT
def test_subclass_refs_with_cycle(self): """Confirm https://bugs.python.org/issue3100 is fixed.""" # An instance of a weakref subclass can have attributes. # If such a weakref holds the only strong reference to the object, # deleting the weakref will delete the object. In this case, # the callback must not be called, because the ref object is # being deleted. class MyRef(weakref.ref): pass # Use a local callback, for "regrtest -R::" # to detect refcounting problems def callback(w): self.cbcalled += 1 o = C() r1 = MyRef(o, callback) r1.o = o del o del r1 # Used to crash here self.assertEqual(self.cbcalled, 0) # Same test, with two weakrefs to the same object # (since code paths are different) o = C() r1 = MyRef(o, callback) r2 = MyRef(o, callback) r1.r = r2 r2.o = o del o del r2 del r1 # Used to crash here self.assertEqual(self.cbcalled, 0)
Confirm https://bugs.python.org/issue3100 is fixed.
test_subclass_refs_with_cycle
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
MIT
def _subclass(self): """Return an Object subclass overriding `some_method`.""" class C(Object): def some_method(self): return 6 return C
Return an Object subclass overriding `some_method`.
_subclass
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_weakref.py
MIT
def signal_alarm(n): """Call signal.alarm when it exists (i.e. not on Windows).""" if hasattr(signal, 'alarm'): signal.alarm(n)
Call signal.alarm when it exists (i.e. not on Windows).
signal_alarm
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socketserver.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socketserver.py
MIT
def simple_subprocess(testcase): """Tests that a custom child process is not waited on (Issue 1540386)""" pid = os.fork() if pid == 0: # Don't raise an exception; it would be caught by the test harness. os._exit(72) try: yield None except: raise finally: pid2, status = os.waitpid(pid, 0) testcase.assertEqual(pid2, pid) testcase.assertEqual(72 << 8, status)
Tests that a custom child process is not waited on (Issue 1540386)
simple_subprocess
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socketserver.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_socketserver.py
MIT
def test_inherited_doctype(self): '''Ensure that ordinary usage is not deprecated (Issue 19176)''' with warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) class MyParserWithoutDoctype(ET.XMLParser): pass parser = MyParserWithoutDoctype() parser.feed(self.sample2) parser.close()
Ensure that ordinary usage is not deprecated (Issue 19176)
test_inherited_doctype
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
MIT
def _make_elem_with_children(self, numchildren): """Create an Element with a tag 'a', with the given amount of children named 'a0', 'a1' ... and so on. """ e = ET.Element('a') for i in range(numchildren): ET.SubElement(e, 'a%s' % i) return e
Create an Element with a tag 'a', with the given amount of children named 'a0', 'a1' ... and so on.
_make_elem_with_children
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
MIT
def test_write_to_binary_file_with_bom(self): self.addCleanup(support.unlink, TESTFN) tree = ET.ElementTree(ET.XML('''<site />''')) # test BOM writing to buffered file with open(TESTFN, 'wb') as f: tree.write(f, encoding='utf-16') self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) # test BOM writing to non-buffered file with open(TESTFN, 'wb', buffering=0) as f: tree.write(f, encoding='utf-16') self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16"))
<?xml version='1.0' encoding='utf-16'?>\n
test_write_to_binary_file_with_bom
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
MIT
def test_write_to_user_binary_writer_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write writer.seekable = lambda: True writer.tell = raw.tell tree.write(writer, encoding="utf-16") self.assertEqual(raw.getvalue(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16"))
<?xml version='1.0' encoding='utf-16'?>\n
test_write_to_user_binary_writer_with_bom
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_xml_etree.py
MIT
def test_basic(self): self.check_tokenize("1 + 1", """\ NUMBER '1' (1, 0) (1, 1) OP '+' (1, 2) (1, 3) NUMBER '1' (1, 4) (1, 5) """) self.check_tokenize("if False:\n" " # NL\n" " \n" " True = False # NEWLINE\n", """\ NAME 'if' (1, 0) (1, 2) NAME 'False' (1, 3) (1, 8) OP ':' (1, 8) (1, 9) NEWLINE '\\n' (1, 9) (1, 10) COMMENT '# NL' (2, 4) (2, 8) NL '\\n' (2, 8) (2, 9) NL '\\n' (3, 4) (3, 5) INDENT ' ' (4, 0) (4, 4) NAME 'True' (4, 4) (4, 8) OP '=' (4, 9) (4, 10) NAME 'False' (4, 11) (4, 16) COMMENT '# NEWLINE' (4, 17) (4, 26) NEWLINE '\\n' (4, 26) (4, 27) DEDENT '' (5, 0) (5, 0) """) indent_error_file = b"""\ def k(x): x += 2 x += 5 """ readline = BytesIO(indent_error_file).readline with self.assertRaisesRegex(IndentationError, "unindent does not match any " "outer indentation level"): for tok in tokenize(readline): pass
) self.check_tokenize("if False:\n" " # NL\n" " \n" " True = False # NEWLINE\n", """\ NAME 'if' (1, 0) (1, 2) NAME 'False' (1, 3) (1, 8) OP ':' (1, 8) (1, 9) NEWLINE '\\n' (1, 9) (1, 10) COMMENT '# NL' (2, 4) (2, 8) NL '\\n' (2, 8) (2, 9) NL '\\n' (3, 4) (3, 5) INDENT ' ' (4, 0) (4, 4) NAME 'True' (4, 4) (4, 8) OP '=' (4, 9) (4, 10) NAME 'False' (4, 11) (4, 16) COMMENT '# NEWLINE' (4, 17) (4, 26) NEWLINE '\\n' (4, 26) (4, 27) DEDENT '' (5, 0) (5, 0) """) indent_error_file = b"""\ def k(x): x += 2 x += 5
test_basic
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
MIT
def test_latin1_coding_cookie_and_utf8_bom(self): """ As per PEP 0263, if a file starts with a utf-8 BOM signature, the only allowed encoding for the comment is 'utf-8'. The text file used in this test starts with a BOM signature, but specifies latin1 as the coding, so verify that a SyntaxError is raised, which matches the behaviour of the interpreter when it encounters a similar condition. """ f = 'tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt' self.assertRaises(SyntaxError, self._testFile, f)
As per PEP 0263, if a file starts with a utf-8 BOM signature, the only allowed encoding for the comment is 'utf-8'. The text file used in this test starts with a BOM signature, but specifies latin1 as the coding, so verify that a SyntaxError is raised, which matches the behaviour of the interpreter when it encounters a similar condition.
test_latin1_coding_cookie_and_utf8_bom
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
MIT
def check_roundtrip(self, f): """ Test roundtrip for `untokenize`. `f` is an open file or a string. The source code in f is tokenized to both 5- and 2-tuples. Both sequences are converted back to source code via tokenize.untokenize(), and the latter tokenized again to 2-tuples. The test fails if the 3 pair tokenizations do not match. When untokenize bugs are fixed, untokenize with 5-tuples should reproduce code that does not contain a backslash continuation following spaces. A proper test should test this. """ # Get source code and original tokenizations if isinstance(f, str): code = f.encode('utf-8') else: code = f.read() f.close() readline = iter(code.splitlines(keepends=True)).__next__ tokens5 = list(tokenize(readline)) tokens2 = [tok[:2] for tok in tokens5] # Reproduce tokens2 from pairs bytes_from2 = untokenize(tokens2) readline2 = iter(bytes_from2.splitlines(keepends=True)).__next__ tokens2_from2 = [tok[:2] for tok in tokenize(readline2)] self.assertEqual(tokens2_from2, tokens2) # Reproduce tokens2 from 5-tuples bytes_from5 = untokenize(tokens5) readline5 = iter(bytes_from5.splitlines(keepends=True)).__next__ tokens2_from5 = [tok[:2] for tok in tokenize(readline5)] self.assertEqual(tokens2_from5, tokens2)
Test roundtrip for `untokenize`. `f` is an open file or a string. The source code in f is tokenized to both 5- and 2-tuples. Both sequences are converted back to source code via tokenize.untokenize(), and the latter tokenized again to 2-tuples. The test fails if the 3 pair tokenizations do not match. When untokenize bugs are fixed, untokenize with 5-tuples should reproduce code that does not contain a backslash continuation following spaces. A proper test should test this.
check_roundtrip
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
MIT
def test_indentation_semantics_retained(self): """ Ensure that although whitespace might be mutated in a roundtrip, the semantic meaning of the indentation remains consistent. """ code = "if False:\n\tx=3\n\tx=3\n" codelines = self.roundtrip(code).split('\n') self.assertEqual(codelines[1], codelines[2]) self.check_roundtrip(code)
Ensure that although whitespace might be mutated in a roundtrip, the semantic meaning of the indentation remains consistent.
test_indentation_semantics_retained
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_tokenize.py
MIT
def test_string_literals(self): x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' self.assertTrue(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' self.assertTrue(len(x) == 24 and x == y) x = """ The "quick" brown fox jumps over the 'lazy' dog. """ y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' self.assertEqual(x, y) y = ''' The "quick" brown fox jumps over the 'lazy' dog. ''' self.assertEqual(x, y) y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ " self.assertEqual(x, y) y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ ' self.assertEqual(x, y)
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' self.assertEqual(x, y) y =
test_string_literals
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_grammar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_grammar.py
MIT
def test_existing_docstring_not_overridden(self): @dataclass class C: """Lorem ipsum""" x: int self.assertEqual(C.__doc__, "Lorem ipsum")
Lorem ipsum
test_existing_docstring_not_overridden
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dataclasses.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dataclasses.py
MIT
def mock_generate_time_safe(self, safe_value): """ Mock uuid._generate_time_safe() to return a given *safe_value*. """ if os.name != 'posix': self.skipTest('POSIX-only test') self.uuid._load_system_functions() f = self.uuid._generate_time_safe if f is None: self.skipTest('need uuid._generate_time_safe') with unittest.mock.patch.object(self.uuid, '_generate_time_safe', lambda: (f()[0], safe_value)): yield
Mock uuid._generate_time_safe() to return a given *safe_value*.
mock_generate_time_safe
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_uuid.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_uuid.py
MIT
def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, env_vars): """Returns expected child process details for a given encoding""" _stream = stream_encoding + ":{}" # stdin and stdout should use surrogateescape either because the # coercion triggered, or because the C locale was detected stream_info = 2*[_stream.format("surrogateescape")] # stderr should always use backslashreplace stream_info.append(_stream.format("backslashreplace")) expected_lang = env_vars.get("LANG", "not set") if coercion_expected: expected_lc_ctype = CLI_COERCION_TARGET else: expected_lc_ctype = env_vars.get("LC_CTYPE", "not set") expected_lc_all = env_vars.get("LC_ALL", "not set") env_info = expected_lang, expected_lc_ctype, expected_lc_all return dict(cls(fs_encoding, *stream_info, *env_info)._asdict())
Returns expected child process details for a given encoding
get_expected_details
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
MIT
def get_child_details(cls, env_vars): """Retrieves fsencoding and standard stream details from a child process Returns (encoding_details, stderr_lines): - encoding_details: EncodingDetails for eager decoding - stderr_lines: result of calling splitlines() on the stderr output The child is run in isolated mode if the current interpreter supports that. """ result, py_cmd = run_python_until_end( "-X", "utf8=0", "-c", cls.CHILD_PROCESS_SCRIPT, **env_vars ) if not result.rc == 0: result.fail(py_cmd) # All subprocess outputs in this test case should be pure ASCII stdout_lines = result.out.decode("ascii").splitlines() child_encoding_details = dict(cls(*stdout_lines)._asdict()) stderr_lines = result.err.decode("ascii").rstrip().splitlines() return child_encoding_details, stderr_lines
Retrieves fsencoding and standard stream details from a child process Returns (encoding_details, stderr_lines): - encoding_details: EncodingDetails for eager decoding - stderr_lines: result of calling splitlines() on the stderr output The child is run in isolated mode if the current interpreter supports that.
get_child_details
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
MIT
def _check_child_encoding_details(self, env_vars, expected_fs_encoding, expected_stream_encoding, expected_warnings, coercion_expected): """Check the C locale handling for the given process environment Parameters: expected_fs_encoding: expected sys.getfilesystemencoding() result expected_stream_encoding: expected encoding for standard streams expected_warning: stderr output to expect (if any) """ result = EncodingDetails.get_child_details(env_vars) encoding_details, stderr_lines = result expected_details = EncodingDetails.get_expected_details( coercion_expected, expected_fs_encoding, expected_stream_encoding, env_vars ) self.assertEqual(encoding_details, expected_details) if expected_warnings is None: expected_warnings = [] self.assertEqual(stderr_lines, expected_warnings)
Check the C locale handling for the given process environment Parameters: expected_fs_encoding: expected sys.getfilesystemencoding() result expected_stream_encoding: expected encoding for standard streams expected_warning: stderr output to expect (if any)
_check_child_encoding_details
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
MIT
def _check_c_locale_coercion(self, fs_encoding, stream_encoding, coerce_c_locale, expected_warnings=None, coercion_expected=True, **extra_vars): """Check the C locale handling for various configurations Parameters: fs_encoding: expected sys.getfilesystemencoding() result stream_encoding: expected encoding for standard streams coerce_c_locale: setting to use for PYTHONCOERCECLOCALE None: don't set the variable at all str: the value set in the child's environment expected_warnings: expected warning lines on stderr extra_vars: additional environment variables to set in subprocess """ self.maxDiff = None if not AVAILABLE_TARGETS: # Locale coercion is disabled when there aren't any target locales fs_encoding = EXPECTED_C_LOCALE_FS_ENCODING stream_encoding = EXPECTED_C_LOCALE_STREAM_ENCODING coercion_expected = False if expected_warnings: expected_warnings = [LEGACY_LOCALE_WARNING] base_var_dict = { "LANG": "", "LC_CTYPE": "", "LC_ALL": "", "PYTHONCOERCECLOCALE": "", } base_var_dict.update(extra_vars) if coerce_c_locale is not None: base_var_dict["PYTHONCOERCECLOCALE"] = coerce_c_locale # Check behaviour for the default locale with self.subTest(default_locale=True, PYTHONCOERCECLOCALE=coerce_c_locale): if EXPECT_COERCION_IN_DEFAULT_LOCALE: _expected_warnings = expected_warnings _coercion_expected = coercion_expected else: _expected_warnings = None _coercion_expected = False # On Android CLI_COERCION_WARNING is not printed when all the # locale environment variables are undefined or empty. When # this code path is run with environ['LC_ALL'] == 'C', then # LEGACY_LOCALE_WARNING is printed. if (test.support.is_android and _expected_warnings == [CLI_COERCION_WARNING]): _expected_warnings = None self._check_child_encoding_details(base_var_dict, fs_encoding, stream_encoding, _expected_warnings, _coercion_expected) # Check behaviour for explicitly configured locales for locale_to_set in EXPECTED_C_LOCALE_EQUIVALENTS: for env_var in ("LANG", "LC_CTYPE"): with self.subTest(env_var=env_var, nominal_locale=locale_to_set, PYTHONCOERCECLOCALE=coerce_c_locale): var_dict = base_var_dict.copy() var_dict[env_var] = locale_to_set # Check behaviour on successful coercion self._check_child_encoding_details(var_dict, fs_encoding, stream_encoding, expected_warnings, coercion_expected)
Check the C locale handling for various configurations Parameters: fs_encoding: expected sys.getfilesystemencoding() result stream_encoding: expected encoding for standard streams coerce_c_locale: setting to use for PYTHONCOERCECLOCALE None: don't set the variable at all str: the value set in the child's environment expected_warnings: expected warning lines on stderr extra_vars: additional environment variables to set in subprocess
_check_c_locale_coercion
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_c_locale_coercion.py
MIT
def run_gdb(*args, **env_vars): """Runs gdb in --batch mode with the additional arguments given by *args. Returns its (stdout, stderr) decoded from utf-8 using the replace handler. """ if env_vars: env = os.environ.copy() env.update(env_vars) else: env = None # -nx: Do not execute commands from any .gdbinit initialization files # (issue #22188) base_cmd = ('gdb', '--batch', '-nx') if (gdb_major_version, gdb_minor_version) >= (7, 4): base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path) proc = subprocess.Popen(base_cmd + args, # Redirect stdin to prevent GDB from messing with # the terminal settings stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) with proc: out, err = proc.communicate() return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Runs gdb in --batch mode with the additional arguments given by *args. Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
run_gdb
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT
def get_stack_trace(self, source=None, script=None, breakpoint=BREAKPOINT_FN, cmds_after_breakpoint=None, import_site=False): ''' Run 'python -c SOURCE' under gdb with a breakpoint. Support injecting commands after the breakpoint is reached Returns the stdout from gdb cmds_after_breakpoint: if provided, a list of strings: gdb commands ''' # We use "set breakpoint pending yes" to avoid blocking with a: # Function "foo" not defined. # Make breakpoint pending on future shared library load? (y or [n]) # error, which typically happens python is dynamically linked (the # breakpoints of interest are to be found in the shared library) # When this happens, we still get: # Function "textiowrapper_write" not defined. # emitted to stderr each time, alas. # Initially I had "--eval-command=continue" here, but removed it to # avoid repeated print breakpoints when traversing hierarchical data # structures # Generate a list of commands in gdb's language: commands = ['set breakpoint pending yes', 'break %s' % breakpoint, # The tests assume that the first frame of printed # backtrace will not contain program counter, # that is however not guaranteed by gdb # therefore we need to use 'set print address off' to # make sure the counter is not there. For example: # #0 in PyObject_Print ... # is assumed, but sometimes this can be e.g. # #0 0x00003fffb7dd1798 in PyObject_Print ... 'set print address off', 'run'] # GDB as of 7.4 onwards can distinguish between the # value of a variable at entry vs current value: # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html # which leads to the selftests failing with errors like this: # AssertionError: 'v@entry=()' != '()' # Disable this: if (gdb_major_version, gdb_minor_version) >= (7, 4): commands += ['set print entry-values no'] if cmds_after_breakpoint: if CET_PROTECTION: # bpo-32962: When Python is compiled with -mcet # -fcf-protection, function arguments are unusable before # running the first instruction of the function entry point. # The 'next' command makes the required first step. commands += ['next'] commands += cmds_after_breakpoint else: commands += ['backtrace'] # print commands # Use "commands" to generate the arguments with which to invoke "gdb": args = ['--eval-command=%s' % cmd for cmd in commands] args += ["--args", sys.executable] args.extend(subprocess._args_from_interpreter_flags()) if not import_site: # -S suppresses the default 'import site' args += ["-S"] if source: args += ["-c", source] elif script: args += [script] # Use "args" to invoke gdb, capturing stdout, stderr: out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED) for line in err.splitlines(): print(line, file=sys.stderr) # bpo-34007: Sometimes some versions of the shared libraries that # are part of the traceback are compiled in optimised mode and the # Program Counter (PC) is not present, not allowing gdb to walk the # frames back. When this happens, the Python bindings of gdb raise # an exception, making the test impossible to succeed. if "PC not saved" in err: raise unittest.SkipTest("gdb cannot walk the frame object" " because the Program Counter is" " not present") return out
Run 'python -c SOURCE' under gdb with a breakpoint. Support injecting commands after the breakpoint is reached Returns the stdout from gdb cmds_after_breakpoint: if provided, a list of strings: gdb commands
get_stack_trace
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT
def assertEndsWith(self, actual, exp_end): '''Ensure that the given "actual" string ends with "exp_end"''' self.assertTrue(actual.endswith(exp_end), msg='%r did not end with %r' % (actual, exp_end))
Ensure that the given "actual" string ends with "exp_end"
assertEndsWith
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT
def test_exceptions(self): # Test a RuntimeError gdb_repr, gdb_output = self.get_gdb_repr(''' try: raise RuntimeError("I am an error") except RuntimeError as e: id(e) ''') self.assertEqual(gdb_repr, "RuntimeError('I am an error',)") # Test division by zero: gdb_repr, gdb_output = self.get_gdb_repr(''' try: a = 1 / 0 except ZeroDivisionError as e: id(e) ''') self.assertEqual(gdb_repr, "ZeroDivisionError('division by zero',)")
) self.assertEqual(gdb_repr, "RuntimeError('I am an error',)") # Test division by zero: gdb_repr, gdb_output = self.get_gdb_repr(
test_exceptions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT
def assertSane(self, source, corruption, exprepr=None): '''Run Python under gdb, corrupting variables in the inferior process immediately before taking a backtrace. Verify that the variable's representation is the expected failsafe representation''' if corruption: cmds_after_breakpoint=[corruption, 'backtrace'] else: cmds_after_breakpoint=['backtrace'] gdb_repr, gdb_output = \ self.get_gdb_repr(source, cmds_after_breakpoint=cmds_after_breakpoint) if exprepr: if gdb_repr == exprepr: # gdb managed to print the value in spite of the corruption; # this is good (see http://bugs.python.org/issue8330) return # Match anything for the type name; 0xDEADBEEF could point to # something arbitrary (see http://bugs.python.org/issue8330) pattern = '<.* at remote 0x-?[0-9a-f]+>' m = re.match(pattern, gdb_repr) if not m: self.fail('Unexpected gdb representation: %r\n%s' % \ (gdb_repr, gdb_output))
Run Python under gdb, corrupting variables in the inferior process immediately before taking a backtrace. Verify that the variable's representation is the expected failsafe representation
assertSane
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT
def test_selfreferential_list(self): '''Ensure that a reference loop involving a list doesn't lead proxyval into an infinite loop:''' gdb_repr, gdb_output = \ self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)") self.assertEqual(gdb_repr, '[3, 4, 5, [...]]') gdb_repr, gdb_output = \ self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)") self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Ensure that a reference loop involving a list doesn't lead proxyval into an infinite loop:
test_selfreferential_list
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_gdb.py
MIT