code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def test_password_manager_default_port(self): """ The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password. """ mgr = urllib.request.HTTPPasswordMgr() add = mgr.add_password find_user_pass = mgr.find_user_password add("f", "http://g.example.com:80", "10", "j") add("g", "http://h.example.com", "11", "k") add("h", "i.example.com:80", "12", "l") add("i", "j.example.com", "13", "m") self.assertEqual(find_user_pass("f", "g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "g.example.com"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "http://g.example.com"), ('10', 'j')) self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k')) self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("g", "http://h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("h", "i.example.com"), (None, None)) self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("h", "http://i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "j.example.com:80"), (None, None)) self.assertEqual(find_user_pass("i", "http://j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "http://j.example.com:80"), (None, None))
The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password.
test_password_manager_default_port
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def add_ordered_mock_handlers(opener, meth_spec): """Create MockHandlers and add them to an OpenerDirector. meth_spec: list of lists of tuples and strings defining methods to define on handlers. eg: [["http_error", "ftp_open"], ["http_open"]] defines methods .http_error() and .ftp_open() on one handler, and .http_open() on another. These methods just record their arguments and return None. Using a tuple instead of a string causes the method to perform some action (see MockHandler.handle()), eg: [["http_error"], [("http_open", "return request")]] defines .http_error() on one handler (which simply returns None), and .http_open() on another handler, which returns a Request object. """ handlers = [] count = 0 for meths in meth_spec: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order += count h.add_parent(opener) count = count + 1 handlers.append(h) opener.add_handler(h) return handlers
Create MockHandlers and add them to an OpenerDirector. meth_spec: list of lists of tuples and strings defining methods to define on handlers. eg: [["http_error", "ftp_open"], ["http_open"]] defines methods .http_error() and .ftp_open() on one handler, and .http_open() on another. These methods just record their arguments and return None. Using a tuple instead of a string causes the method to perform some action (see MockHandler.handle()), eg: [["http_error"], [("http_open", "return request")]] defines .http_error() on one handler (which simply returns None), and .http_open() on another handler, which returns a Request object.
add_ordered_mock_handlers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def test_http_closed(self): """Test the connection is cleaned up when the response is closed""" for (transfer, data) in ( ("Connection: close", b"data"), ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"), ("Content-Length: 4", b"data"), ): header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer) conn = test_urllib.fakehttp(header.encode() + data) handler = urllib.request.AbstractHTTPHandler() req = Request("http://dummy/") req.timeout = None with handler.do_open(conn, req) as resp: resp.read() self.assertTrue(conn.fakesock.closed, "Connection not closed with {!r}".format(transfer))
Test the connection is cleaned up when the response is closed
test_http_closed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def test_invalid_closed(self): """Test the connection is cleaned up after an invalid response""" conn = test_urllib.fakehttp(b"") handler = urllib.request.AbstractHTTPHandler() req = Request("http://dummy/") req.timeout = None with self.assertRaises(http.client.BadStatusLine): handler.do_open(conn, req) self.assertTrue(conn.fakesock.closed, "Connection not closed")
Test the connection is cleaned up after an invalid response
test_invalid_closed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def test_HTTPError_interface(self): """ Issue 13211 reveals that HTTPError didn't implement the URLError interface even though HTTPError is a subclass of URLError. """ msg = 'something bad happened' url = code = fp = None hdrs = 'Content-Length: 42' err = urllib.error.HTTPError(url, code, msg, hdrs, fp) self.assertTrue(hasattr(err, 'reason')) self.assertEqual(err.reason, 'something bad happened') self.assertTrue(hasattr(err, 'headers')) self.assertEqual(err.headers, 'Content-Length: 42') expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg) self.assertEqual(str(err), expected_errmsg) expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg) self.assertEqual(repr(err), expected_errmsg)
Issue 13211 reveals that HTTPError didn't implement the URLError interface even though HTTPError is a subclass of URLError.
test_HTTPError_interface
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_urllib2.py
MIT
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" self._threading_key = support.threading_setup() logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers())
Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelToName.clear() logging._levelToName.update(self.saved_level_to_name) logging._nameToLevel.clear() logging._nameToLevel.update(self.saved_name_to_level) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list manager = logging.getLogger().manager manager.disable = 0 loggerDict = manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) logger_states = self.logger_states for name in self.logger_states: if logger_states[name] is not None: self.saved_loggers[name].disabled = logger_states[name] finally: logging._releaseLock() self.doCleanups() support.threading_cleanup(*self._threading_key)
Remove our logging stream, and restore the original logging level.
tearDown
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def assert_log_lines(self, expected_values, stream=None, pat=None): """Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.""" stream = stream or self.stream pat = re.compile(pat or self.expected_log_pat) actual_lines = stream.getvalue().splitlines() self.assertEqual(len(actual_lines), len(expected_values)) for actual, expected in zip(actual_lines, expected_values): match = pat.search(actual) if not match: self.fail("Log line does not match expected pattern:\n" + actual) self.assertEqual(tuple(match.groups()), expected) s = stream.read() if s: self.fail("Remaining output at end of log stream:\n" + s)
Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.
assert_log_lines
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def next_message(self): """Generate a message consisting solely of an auto-incrementing integer.""" self.message_num += 1 return "%d" % self.message_num
Generate a message consisting solely of an auto-incrementing integer.
next_message
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_regression_22386(self): """See issue #22386 for more information.""" self.assertEqual(logging.getLevelName('INFO'), logging.INFO) self.assertEqual(logging.getLevelName(logging.INFO), 'INFO')
See issue #22386 for more information.
test_regression_22386
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_regression_29220(self): """See issue #29220 for more information.""" logging.addLevelName(logging.INFO, '') self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') self.assertEqual(logging.getLevelName(logging.INFO), '')
See issue #29220 for more information.
test_regression_29220
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_path_objects(self): """ Test that Path objects are accepted as filename arguments to handlers. See Issue #27493. """ fd, fn = tempfile.mkstemp() os.close(fd) os.unlink(fn) pfn = pathlib.Path(fn) cases = ( (logging.FileHandler, (pfn, 'w')), (logging.handlers.RotatingFileHandler, (pfn, 'a')), (logging.handlers.TimedRotatingFileHandler, (pfn, 'h')), ) if sys.platform in ('linux', 'darwin'): cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),) for cls, args in cases: h = cls(*args) self.assertTrue(os.path.exists(fn)) h.close() os.unlink(fn)
Test that Path objects are accepted as filename arguments to handlers. See Issue #27493.
test_path_objects
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_post_fork_child_no_deadlock(self): """Ensure child logging locks are not held; bpo-6721 & bpo-36533.""" class _OurHandler(logging.Handler): def __init__(self): super().__init__() self.sub_handler = logging.StreamHandler( stream=open('/dev/null', 'wt')) def emit(self, record): self.sub_handler.acquire() try: self.sub_handler.emit(record) finally: self.sub_handler.release() self.assertEqual(len(logging._handlers), 0) refed_h = _OurHandler() self.addCleanup(refed_h.sub_handler.stream.close) refed_h.name = 'because we need at least one for this test' self.assertGreater(len(logging._handlers), 0) self.assertGreater(len(logging._at_fork_reinit_lock_weakset), 1) test_logger = logging.getLogger('test_post_fork_child_no_deadlock') test_logger.addHandler(refed_h) test_logger.setLevel(logging.DEBUG) locks_held__ready_to_fork = threading.Event() fork_happened__release_locks_and_end_thread = threading.Event() def lock_holder_thread_fn(): logging._acquireLock() try: refed_h.acquire() try: # Tell the main thread to do the fork. locks_held__ready_to_fork.set() # If the deadlock bug exists, the fork will happen # without dealing with the locks we hold, deadlocking # the child. # Wait for a successful fork or an unreasonable amount of # time before releasing our locks. To avoid a timing based # test we'd need communication from os.fork() as to when it # has actually happened. Given this is a regression test # for a fixed issue, potentially less reliably detecting # regression via timing is acceptable for simplicity. # The test will always take at least this long. :( fork_happened__release_locks_and_end_thread.wait(0.5) finally: refed_h.release() finally: logging._releaseLock() lock_holder_thread = threading.Thread( target=lock_holder_thread_fn, name='test_post_fork_child_no_deadlock lock holder') lock_holder_thread.start() locks_held__ready_to_fork.wait() pid = os.fork() if pid == 0: # Child. try: test_logger.info(r'Child process did not deadlock. \o/') finally: os._exit(0) else: # Parent. test_logger.info(r'Parent process returned from fork. \o/') fork_happened__release_locks_and_end_thread.set() lock_holder_thread.join() start_time = time.monotonic() while True: test_logger.debug('Waiting for child process.') waited_pid, status = os.waitpid(pid, os.WNOHANG) if waited_pid == pid: break # child process exited. if time.monotonic() - start_time > 7: break # so long? implies child deadlock. time.sleep(0.05) test_logger.debug('Done waiting.') if waited_pid != pid: os.kill(pid, signal.SIGKILL) waited_pid, status = os.waitpid(pid, 0) self.fail("child process deadlocked.") self.assertEqual(status, 0, msg="child process error")
Ensure child logging locks are not held; bpo-6721 & bpo-36533.
test_post_fork_child_no_deadlock
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_stream_setting(self): """ Test setting the handler's stream """ h = logging.StreamHandler() stream = io.StringIO() old = h.setStream(stream) self.assertIs(old, sys.stderr) actual = h.setStream(old) self.assertIs(actual, stream) # test that setting to existing value returns None actual = h.setStream(old) self.assertIsNone(actual)
Test setting the handler's stream
test_stream_setting
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def process_message(self, peer, mailfrom, rcpttos, data): """ Delegates to the handler passed in to the server's constructor. Typically, this will be a test case method. :param peer: The client (host, port) tuple. :param mailfrom: The address of the sender. :param rcpttos: The addresses of the recipients. :param data: The message. """ self._handler(peer, mailfrom, rcpttos, data)
Delegates to the handler passed in to the server's constructor. Typically, this will be a test case method. :param peer: The client (host, port) tuple. :param mailfrom: The address of the sender. :param rcpttos: The addresses of the recipients. :param data: The message.
process_message
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def start(self): """ Start the server running on a separate daemon thread. """ self._thread = t = threading.Thread(target=self.serve_forever, args=(self.poll_interval,)) t.setDaemon(True) t.start()
Start the server running on a separate daemon thread.
start
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def serve_forever(self, poll_interval): """ Run the :mod:`asyncore` loop until normal termination conditions arise. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`. """ asyncore.loop(poll_interval, map=self._map)
Run the :mod:`asyncore` loop until normal termination conditions arise. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`.
serve_forever
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def stop(self, timeout=None): """ Stop the thread by closing the server instance. Wait for the server thread to terminate. :param timeout: How long to wait for the server thread to terminate. """ self.close() support.join_thread(self._thread, timeout) self._thread = None asyncore.close_all(map=self._map, ignore_all=True)
Stop the thread by closing the server instance. Wait for the server thread to terminate. :param timeout: How long to wait for the server thread to terminate.
stop
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def start(self): """ Create a daemon thread to run the server, and start it. """ self._thread = t = threading.Thread(target=self.serve_forever, args=(self.poll_interval,)) t.setDaemon(True) t.start()
Create a daemon thread to run the server, and start it.
start
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def serve_forever(self, poll_interval): """ Run the server. Set the ready flag before entering the service loop. """ self.ready.set() super(ControlMixin, self).serve_forever(poll_interval)
Run the server. Set the ready flag before entering the service loop.
serve_forever
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def stop(self, timeout=None): """ Tell the server thread to stop, and wait for it to do so. :param timeout: How long to wait for the server thread to terminate. """ self.shutdown() if self._thread is not None: support.join_thread(self._thread, timeout) self._thread = None self.server_close() self.ready.clear()
Tell the server thread to stop, and wait for it to do so. :param timeout: How long to wait for the server thread to terminate.
stop
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_flush_on_close(self): """ Test that the flush-on-close configuration works as expected. """ self.mem_logger.debug(self.next_message()) self.assert_log_lines([]) self.mem_logger.info(self.next_message()) self.assert_log_lines([]) self.mem_logger.removeHandler(self.mem_hdlr) # Default behaviour is to flush on close. Check that it happens. self.mem_hdlr.close() lines = [ ('DEBUG', '1'), ('INFO', '2'), ] self.assert_log_lines(lines) # Now configure for flushing not to be done on close. self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, self.root_hdlr, False) self.mem_logger.addHandler(self.mem_hdlr) self.mem_logger.debug(self.next_message()) self.assert_log_lines(lines) # no change self.mem_logger.info(self.next_message()) self.assert_log_lines(lines) # no change self.mem_logger.removeHandler(self.mem_hdlr) self.mem_hdlr.close() # assert that no new lines have been added self.assert_log_lines(lines) # no change
Test that the flush-on-close configuration works as expected.
test_flush_on_close
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_defaults_do_no_interpolation(self): """bpo-33802 defaults should not get interpolated""" ini = textwrap.dedent(""" [formatters] keys=default [formatter_default] [handlers] keys=console [handler_console] class=logging.StreamHandler args=tuple() [loggers] keys=root [logger_root] formatter=default handlers=console """).strip() fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.ini') try: os.write(fd, ini.encode('ascii')) os.close(fd) logging.config.fileConfig( fn, defaults=dict( version=1, disable_existing_loggers=False, formatters={ "generic": { "format": "%(asctime)s [%(process)d] [%(levelname)s] %(message)s", "datefmt": "[%Y-%m-%d %H:%M:%S %z]", "class": "logging.Formatter" }, }, ) ) finally: os.unlink(fn)
bpo-33802 defaults should not get interpolated
test_defaults_do_no_interpolation
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setUp(self): """Set up a TCP server to receive log messages, and a SocketHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sock_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_socket, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.SocketHandler if isinstance(server.server_address, tuple): self.sock_hdlr = hcls('localhost', server.port) else: self.sock_hdlr = hcls(server.server_address, None) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sock_hdlr) self.handled = threading.Semaphore(0)
Set up a TCP server to receive log messages, and a SocketHandler pointing to that server's address and port.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def tearDown(self): """Shutdown the TCP server.""" try: if self.sock_hdlr: self.root_logger.removeHandler(self.sock_hdlr) self.sock_hdlr.close() if self.server: self.server.stop(2.0) finally: BaseTest.tearDown(self)
Shutdown the TCP server.
tearDown
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setUp(self): """Set up a UDP server to receive log messages, and a DatagramHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sock_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_datagram, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.DatagramHandler if isinstance(server.server_address, tuple): self.sock_hdlr = hcls('localhost', server.port) else: self.sock_hdlr = hcls(server.server_address, None) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sock_hdlr) self.handled = threading.Event()
Set up a UDP server to receive log messages, and a DatagramHandler pointing to that server's address and port.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def tearDown(self): """Shutdown the UDP server.""" try: if self.server: self.server.stop(2.0) if self.sock_hdlr: self.root_logger.removeHandler(self.sock_hdlr) self.sock_hdlr.close() finally: BaseTest.tearDown(self)
Shutdown the UDP server.
tearDown
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setUp(self): """Set up a UDP server to receive log messages, and a SysLogHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sl_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_datagram, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.SysLogHandler if isinstance(server.server_address, tuple): self.sl_hdlr = hcls((server.server_address[0], server.port)) else: self.sl_hdlr = hcls(server.server_address) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sl_hdlr) self.handled = threading.Event()
Set up a UDP server to receive log messages, and a SysLogHandler pointing to that server's address and port.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def tearDown(self): """Shutdown the server.""" try: if self.server: self.server.stop(2.0) if self.sl_hdlr: self.root_logger.removeHandler(self.sl_hdlr) self.sl_hdlr.close() finally: BaseTest.tearDown(self)
Shutdown the server.
tearDown
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setUp(self): """Set up an HTTP server to receive log messages, and a HTTPHandler pointing to that server's address and port.""" BaseTest.setUp(self) self.handled = threading.Event()
Set up an HTTP server to receive log messages, and a HTTPHandler pointing to that server's address and port.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setUp(self): """Create a dict to remember potentially destroyed objects.""" BaseTest.setUp(self) self._survivors = {}
Create a dict to remember potentially destroyed objects.
setUp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def _watch_for_survival(self, *args): """Watch the given objects for survival, by creating weakrefs to them.""" for obj in args: key = id(obj), repr(obj) self._survivors[key] = weakref.ref(obj)
Watch the given objects for survival, by creating weakrefs to them.
_watch_for_survival
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def _assertTruesurvival(self): """Assert that all objects watched for survival have survived.""" # Trigger cycle breaking. gc.collect() dead = [] for (id_, repr_), ref in self._survivors.items(): if ref() is None: dead.append(repr_) if dead: self.fail("%d objects should have survived " "but have been destroyed: %s" % (len(dead), ", ".join(dead)))
Assert that all objects watched for survival have survived.
_assertTruesurvival
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def setup_and_log(log_queue, ident): """ Creates a logger with a QueueHandler that logs to a queue read by a QueueListener. Starts the listener, logs five messages, and stops the listener. """ logger = logging.getLogger('test_logger_with_id_%s' % ident) logger.setLevel(logging.DEBUG) handler = logging.handlers.QueueHandler(log_queue) logger.addHandler(handler) listener = logging.handlers.QueueListener(log_queue) listener.start() logger.info('one') logger.info('two') logger.info('three') logger.info('four') logger.info('five') listener.stop() logger.removeHandler(handler) handler.close()
Creates a logger with a QueueHandler that logs to a queue read by a QueueListener. Starts the listener, logs five messages, and stops the listener.
setup_and_log
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_no_messages_in_queue_after_stop(self): """ Five messages are logged then the QueueListener is stopped. This test then gets everything off the queue. Failure of this test indicates that messages were not registered on the queue until _after_ the QueueListener stopped. """ # Issue 28668: The multiprocessing (mp) module is not functional # when the mp.synchronize module cannot be imported. support.import_module('multiprocessing.synchronize') for i in range(self.repeat): queue = multiprocessing.Queue() self.setup_and_log(queue, '%s_%s' %(self.id(), i)) # time.sleep(1) items = list(self.get_all_from_queue(queue)) queue.close() queue.join_thread() expected = [[], [logging.handlers.QueueListener._sentinel]] self.assertIn(items, expected, 'Found unexpected messages in queue: %s' % ( [m.msg if isinstance(m, logging.LogRecord) else m for m in items]))
Five messages are logged then the QueueListener is stopped. This test then gets everything off the queue. Failure of this test indicates that messages were not registered on the queue until _after_ the QueueListener stopped.
test_no_messages_in_queue_after_stop
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def handle(self, record): """Keep track of all the emitted records.""" self.records.append(record)
Keep track of all the emitted records.
handle
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_logging.py
MIT
def test_telnet(reads=(), cls=TelnetAlike): ''' return a telnetlib.Telnet object that uses a SocketStub with reads queued up to be read ''' for x in reads: assert type(x) is bytes, x with test_socket(reads): telnet = cls('dummy', 0) telnet._messages = '' # debuglevel output return telnet
return a telnetlib.Telnet object that uses a SocketStub with reads queued up to be read
test_telnet
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def test_read_until(self): """ read_until(expected, timeout=None) test the blocking version of read_util """ want = [b'xxxmatchyyy'] telnet = test_telnet(want) data = telnet.read_until(b'match') self.assertEqual(data, b'xxxmatch', msg=(telnet.cookedq, telnet.rawq, telnet.sock.reads)) reads = [b'x' * 50, b'match', b'y' * 50] expect = b''.join(reads[:-1]) telnet = test_telnet(reads) data = telnet.read_until(b'match') self.assertEqual(data, expect)
read_until(expected, timeout=None) test the blocking version of read_util
test_read_until
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def test_read_all(self): """ read_all() Read all data until EOF; may block. """ reads = [b'x' * 500, b'y' * 500, b'z' * 500] expect = b''.join(reads) telnet = test_telnet(reads) data = telnet.read_all() self.assertEqual(data, expect) return
read_all() Read all data until EOF; may block.
test_read_all
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def test_read_some(self): """ read_some() Read at least one byte or EOF; may block. """ # test 'at least one byte' telnet = test_telnet([b'x' * 500]) data = telnet.read_some() self.assertTrue(len(data) >= 1) # test EOF telnet = test_telnet() data = telnet.read_some() self.assertEqual(b'', data)
read_some() Read at least one byte or EOF; may block.
test_read_some
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def _read_eager(self, func_name): """ read_*_eager() Read all data available already queued or on the socket, without blocking. """ want = b'x' * 100 telnet = test_telnet([want]) func = getattr(telnet, func_name) telnet.sock.block = True self.assertEqual(b'', func()) telnet.sock.block = False data = b'' while True: try: data += func() except EOFError: break self.assertEqual(data, want)
read_*_eager() Read all data available already queued or on the socket, without blocking.
_read_eager
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def _test_command(self, data): """ helper for testing IAC + cmd """ telnet = test_telnet(data) data_len = len(b''.join(data)) nego = nego_collector() telnet.set_option_negotiation_callback(nego.do_nego) txt = telnet.read_all() cmd = nego.seen self.assertTrue(len(cmd) > 0) # we expect at least one command self.assertIn(cmd[:1], self.cmds) self.assertEqual(cmd[1:2], tl.NOOPT) self.assertEqual(data_len, len(txt + cmd)) nego.sb_getter = None # break the nego => telnet cycle
helper for testing IAC + cmd
_test_command
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def test_expect(self): """ expect(expected, [timeout]) Read until the expected string has been seen, or a timeout is hit (default is no timeout); may block. """ want = [b'x' * 10, b'match', b'y' * 10] telnet = test_telnet(want) (_,_,data) = telnet.expect([b'match']) self.assertEqual(data, b''.join(want[:-1]))
expect(expected, [timeout]) Read until the expected string has been seen, or a timeout is hit (default is no timeout); may block.
test_expect
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_telnetlib.py
MIT
def _readline(fd): """Read one line. May block forever if no newline is read.""" reader = io.FileIO(fd, mode='rb', closefd=False) return reader.readline()
Read one line. May block forever if no newline is read.
_readline
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
MIT
def test__copy_to_each(self): """Test the normal data case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] # Feed data. Smaller than PIPEBUF. These writes will not block. os.write(masters[1], b'from master') os.write(write_to_stdin_fd, b'from stdin') # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) self.select_rfds_lengths.append(2) with self.assertRaises(IndexError): pty._copy(masters[0]) # Test that the right data went to the right places. rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0] self.assertEqual([read_from_stdout_fd, masters[1]], rfds) self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master') self.assertEqual(os.read(masters[1], 20), b'from stdin')
Test the normal data case on both master_fd and stdin.
test__copy_to_each
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
MIT
def test__copy_eof_on_all(self): """Test the empty read EOF case on both master_fd and stdin.""" read_from_stdout_fd, mock_stdout_fd = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd mock_stdin_fd, write_to_stdin_fd = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] socketpair[1].close() os.close(write_to_stdin_fd) # Expect two select calls, the last one will cause IndexError pty.select = self._mock_select self.select_rfds_lengths.append(2) self.select_rfds_results.append([mock_stdin_fd, masters[0]]) # We expect that both fds were removed from the fds list as they # both encountered an EOF before the second select call. self.select_rfds_lengths.append(0) with self.assertRaises(IndexError): pty._copy(masters[0])
Test the empty read EOF case on both master_fd and stdin.
test__copy_eof_on_all
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_pty.py
MIT
def sign(x): """Return -1.0 for negatives, including -0.0, otherwise +1.0.""" return math.copysign(1, x)
Return -1.0 for negatives, including -0.0, otherwise +1.0.
sign
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 _nan_equal(a, b): """Return True if a and b are both the same kind of NAN. >>> _nan_equal(Decimal('NAN'), Decimal('NAN')) True >>> _nan_equal(Decimal('sNAN'), Decimal('sNAN')) True >>> _nan_equal(Decimal('NAN'), Decimal('sNAN')) False >>> _nan_equal(Decimal(42), Decimal('NAN')) False >>> _nan_equal(float('NAN'), float('NAN')) True >>> _nan_equal(float('NAN'), 0.5) False >>> _nan_equal(float('NAN'), Decimal('NAN')) False NAN payloads are not compared. """ if type(a) is not type(b): return False if isinstance(a, float): return math.isnan(a) and math.isnan(b) aexp = a.as_tuple()[2] bexp = b.as_tuple()[2] return (aexp == bexp) and (aexp in ('n', 'N')) # Both NAN or both sNAN.
Return True if a and b are both the same kind of NAN. >>> _nan_equal(Decimal('NAN'), Decimal('NAN')) True >>> _nan_equal(Decimal('sNAN'), Decimal('sNAN')) True >>> _nan_equal(Decimal('NAN'), Decimal('sNAN')) False >>> _nan_equal(Decimal(42), Decimal('NAN')) False >>> _nan_equal(float('NAN'), float('NAN')) True >>> _nan_equal(float('NAN'), 0.5) False >>> _nan_equal(float('NAN'), Decimal('NAN')) False NAN payloads are not compared.
_nan_equal
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 _calc_errors(actual, expected): """Return the absolute and relative errors between two numbers. >>> _calc_errors(100, 75) (25, 0.25) >>> _calc_errors(100, 100) (0, 0.0) Returns the (absolute error, relative error) between the two arguments. """ base = max(abs(actual), abs(expected)) abs_err = abs(actual - expected) rel_err = abs_err/base if base else float('inf') return (abs_err, rel_err)
Return the absolute and relative errors between two numbers. >>> _calc_errors(100, 75) (25, 0.25) >>> _calc_errors(100, 100) (0, 0.0) Returns the (absolute error, relative error) between the two arguments.
_calc_errors
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 approx_equal(x, y, tol=1e-12, rel=1e-7): """approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is approximately equal to y if the difference between them is less than an absolute error tol or a relative error rel, whichever is bigger. If given, both tol and rel must be finite, non-negative numbers. If not given, default values are tol=1e-12 and rel=1e-7. >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0) True >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0) False Absolute error is defined as abs(x-y); if that is less than or equal to tol, x and y are considered approximately equal. Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is smaller, provided x or y are not zero. If that figure is less than or equal to rel, x and y are considered approximately equal. Complex numbers are not directly supported. If you wish to compare to complex numbers, extract their real and imaginary parts and compare them individually. NANs always compare unequal, even with themselves. Infinities compare approximately equal if they have the same sign (both positive or both negative). Infinities with different signs compare unequal; so do comparisons of infinities with finite numbers. """ if tol < 0 or rel < 0: raise ValueError('error tolerances must be non-negative') # NANs are never equal to anything, approximately or otherwise. if math.isnan(x) or math.isnan(y): return False # Numbers which compare equal also compare approximately equal. if x == y: # This includes the case of two infinities with the same sign. return True if math.isinf(x) or math.isinf(y): # This includes the case of two infinities of opposite sign, or # one infinity and one finite number. return False # Two finite numbers. actual_error = abs(x - y) allowed_error = max(tol, rel*max(abs(x), abs(y))) return actual_error <= allowed_error
approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is approximately equal to y if the difference between them is less than an absolute error tol or a relative error rel, whichever is bigger. If given, both tol and rel must be finite, non-negative numbers. If not given, default values are tol=1e-12 and rel=1e-7. >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0) True >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0) False Absolute error is defined as abs(x-y); if that is less than or equal to tol, x and y are considered approximately equal. Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is smaller, provided x or y are not zero. If that figure is less than or equal to rel, x and y are considered approximately equal. Complex numbers are not directly supported. If you wish to compare to complex numbers, extract their real and imaginary parts and compare them individually. NANs always compare unequal, even with themselves. Infinities compare approximately equal if they have the same sign (both positive or both negative). Infinities with different signs compare unequal; so do comparisons of infinities with finite numbers.
approx_equal
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 assertApproxEqual( self, first, second, tol=None, rel=None, msg=None ): """Test passes if ``first`` and ``second`` are approximately equal. This test passes if ``first`` and ``second`` are equal to within ``tol``, an absolute error, or ``rel``, a relative error. If either ``tol`` or ``rel`` are None or not given, they default to test attributes of the same name (by default, 0). The objects may be either numbers, or sequences of numbers. Sequences are tested element-by-element. >>> class MyTest(NumericTestCase): ... def test_number(self): ... x = 1.0/6 ... y = sum([x]*6) ... self.assertApproxEqual(y, 1.0, tol=1e-15) ... def test_sequence(self): ... a = [1.001, 1.001e-10, 1.001e10] ... b = [1.0, 1e-10, 1e10] ... self.assertApproxEqual(a, b, rel=1e-3) ... >>> import unittest >>> from io import StringIO # Suppress test runner output. >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest) >>> unittest.TextTestRunner(stream=StringIO()).run(suite) <unittest.runner.TextTestResult run=2 errors=0 failures=0> """ if tol is None: tol = self.tol if rel is None: rel = self.rel if ( isinstance(first, collections.abc.Sequence) and isinstance(second, collections.abc.Sequence) ): check = self._check_approx_seq else: check = self._check_approx_num check(first, second, tol, rel, msg)
Test passes if ``first`` and ``second`` are approximately equal. This test passes if ``first`` and ``second`` are equal to within ``tol``, an absolute error, or ``rel``, a relative error. If either ``tol`` or ``rel`` are None or not given, they default to test attributes of the same name (by default, 0). The objects may be either numbers, or sequences of numbers. Sequences are tested element-by-element. >>> class MyTest(NumericTestCase): ... def test_number(self): ... x = 1.0/6 ... y = sum([x]*6) ... self.assertApproxEqual(y, 1.0, tol=1e-15) ... def test_sequence(self): ... a = [1.001, 1.001e-10, 1.001e10] ... b = [1.0, 1e-10, 1e10] ... self.assertApproxEqual(a, b, rel=1e-3) ... >>> import unittest >>> from io import StringIO # Suppress test runner output. >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest) >>> unittest.TextTestRunner(stream=StringIO()).run(suite) <unittest.runner.TextTestResult run=2 errors=0 failures=0>
assertApproxEqual
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 generate_substrings(self, first, second, tol, rel, idx): """Return substrings we expect to see in error messages.""" abs_err, rel_err = _calc_errors(first, second) substrings = [ 'tol=%r' % tol, 'rel=%r' % rel, 'absolute error = %r' % abs_err, 'relative error = %r' % rel_err, ] if idx is not None: substrings.append('differ at index %d' % idx) return substrings
Return substrings we expect to see in error messages.
generate_substrings
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 assertCoerceTo(self, A, B): """Assert that type A coerces to B.""" self.assertIs(statistics._coerce(A, B), B) self.assertIs(statistics._coerce(B, A), B)
Assert that type A coerces to B.
assertCoerceTo
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 check_coerce_to(self, A, B): """Checks that type A coerces to B, including subclasses.""" # Assert that type A is coerced to B. self.assertCoerceTo(A, B) # Subclasses of A are also coerced to B. class SubclassOfA(A): pass self.assertCoerceTo(SubclassOfA, B) # A, and subclasses of A, are coerced to subclasses of B. class SubclassOfB(B): pass self.assertCoerceTo(A, SubclassOfB) self.assertCoerceTo(SubclassOfA, SubclassOfB)
Checks that type A coerces to B, including subclasses.
check_coerce_to
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 assertCoerceRaises(self, A, B): """Assert that coercing A to B, or vice versa, raises TypeError.""" self.assertRaises(TypeError, statistics._coerce, (A, B)) self.assertRaises(TypeError, statistics._coerce, (B, A))
Assert that coercing A to B, or vice versa, raises TypeError.
assertCoerceRaises
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 check_type_coercions(self, T): """Check that type T coerces correctly with subclasses of itself.""" assert T is not bool # Coercing a type with itself returns the same type. self.assertIs(statistics._coerce(T, T), T) # Coercing a type with a subclass of itself returns the subclass. class U(T): pass class V(T): pass class W(U): pass for typ in (U, V, W): self.assertCoerceTo(T, typ) self.assertCoerceTo(U, W) # Coercing two subclasses that aren't parent/child is an error. self.assertCoerceRaises(U, V) self.assertCoerceRaises(V, W)
Check that type T coerces correctly with subclasses of itself.
check_type_coercions
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 check_exact_equal(self, x, y): """Check that x equals y, and has the same type as well.""" self.assertEqual(x, y) self.assertIs(type(x), type(y))
Check that x equals y, and has the same type as well.
check_exact_equal
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 prepare_data(self): """Return int data for various tests.""" data = list(range(10)) while data == sorted(data): random.shuffle(data) return data
Return int data for various tests.
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 prepare_types_for_conservation_test(self): """Return the types which are expected to be conserved.""" class MyFloat(float): def __truediv__(self, other): return type(self)(super().__truediv__(other)) def __rtruediv__(self, other): return type(self)(super().__rtruediv__(other)) def __sub__(self, other): return type(self)(super().__sub__(other)) def __rsub__(self, other): return type(self)(super().__rsub__(other)) def __pow__(self, other): return type(self)(super().__pow__(other)) def __add__(self, other): return type(self)(super().__add__(other)) __radd__ = __add__ return (float, Decimal, Fraction, MyFloat)
Return the types which are expected to be conserved.
prepare_types_for_conservation_test
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 check_infinity(self, x, inf): """Check x is an infinity of the same type and sign as inf.""" self.assertTrue(math.isinf(x)) self.assertIs(type(x), type(inf)) self.assertEqual(x > 0, inf > 0) assert x == inf
Check x is an infinity of the same type and sign as inf.
check_infinity
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 prepare_data(self): """Overload method from UnivariateCommonMixin.""" data = super().prepare_data() if len(data)%2 != 1: data.append(2) return data
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 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