Файловый менеджер - Редактировать - /var/www/html/support.zip
Ðазад
PK ! m�oin n testresult.pynu �[��� '''Test runner and result class for the regression test suite. ''' import functools import io import sys import time import traceback import unittest class RegressionTestResult(unittest.TextTestResult): USE_XML = False def __init__(self, stream, descriptions, verbosity): super().__init__(stream=stream, descriptions=descriptions, verbosity=2 if verbosity else 0) self.buffer = True if self.USE_XML: from xml.etree import ElementTree as ET from datetime import datetime self.__ET = ET self.__suite = ET.Element('testsuite') self.__suite.set('start', datetime.utcnow().isoformat(' ')) self.__e = None self.__start_time = None @classmethod def __getId(cls, test): try: test_id = test.id except AttributeError: return str(test) try: return test_id() except TypeError: return str(test_id) return repr(test) def startTest(self, test): super().startTest(test) if self.USE_XML: self.__e = e = self.__ET.SubElement(self.__suite, 'testcase') self.__start_time = time.perf_counter() def _add_result(self, test, capture=False, **args): if not self.USE_XML: return e = self.__e self.__e = None if e is None: return ET = self.__ET e.set('name', args.pop('name', self.__getId(test))) e.set('status', args.pop('status', 'run')) e.set('result', args.pop('result', 'completed')) if self.__start_time: e.set('time', f'{time.perf_counter() - self.__start_time:0.6f}') if capture: if self._stdout_buffer is not None: stdout = self._stdout_buffer.getvalue().rstrip() ET.SubElement(e, 'system-out').text = stdout if self._stderr_buffer is not None: stderr = self._stderr_buffer.getvalue().rstrip() ET.SubElement(e, 'system-err').text = stderr for k, v in args.items(): if not k or not v: continue e2 = ET.SubElement(e, k) if hasattr(v, 'items'): for k2, v2 in v.items(): if k2: e2.set(k2, str(v2)) else: e2.text = str(v2) else: e2.text = str(v) @classmethod def __makeErrorDict(cls, err_type, err_value, err_tb): if isinstance(err_type, type): if err_type.__module__ == 'builtins': typename = err_type.__name__ else: typename = f'{err_type.__module__}.{err_type.__name__}' else: typename = repr(err_type) msg = traceback.format_exception(err_type, err_value, None) tb = traceback.format_exception(err_type, err_value, err_tb) return { 'type': typename, 'message': ''.join(msg), '': ''.join(tb), } def addError(self, test, err): self._add_result(test, True, error=self.__makeErrorDict(*err)) super().addError(test, err) def addExpectedFailure(self, test, err): self._add_result(test, True, output=self.__makeErrorDict(*err)) super().addExpectedFailure(test, err) def addFailure(self, test, err): self._add_result(test, True, failure=self.__makeErrorDict(*err)) super().addFailure(test, err) def addSkip(self, test, reason): self._add_result(test, skipped=reason) super().addSkip(test, reason) def addSuccess(self, test): self._add_result(test) super().addSuccess(test) def addUnexpectedSuccess(self, test): self._add_result(test, outcome='UNEXPECTED_SUCCESS') super().addUnexpectedSuccess(test) def get_xml_element(self): if not self.USE_XML: raise ValueError("USE_XML is false") e = self.__suite e.set('tests', str(self.testsRun)) e.set('errors', str(len(self.errors))) e.set('failures', str(len(self.failures))) return e class QuietRegressionTestRunner: def __init__(self, stream, buffer=False): self.result = RegressionTestResult(stream, None, 0) self.result.buffer = buffer def run(self, test): test(self.result) return self.result def get_test_runner_class(verbosity, buffer=False): if verbosity: return functools.partial(unittest.TextTestRunner, resultclass=RegressionTestResult, buffer=buffer, verbosity=verbosity) return functools.partial(QuietRegressionTestRunner, buffer=buffer) def get_test_runner(stream, verbosity, capture_output=False): return get_test_runner_class(verbosity, capture_output)(stream) if __name__ == '__main__': import xml.etree.ElementTree as ET RegressionTestResult.USE_XML = True class TestTests(unittest.TestCase): def test_pass(self): pass def test_pass_slow(self): time.sleep(1.0) def test_fail(self): print('stdout', file=sys.stdout) print('stderr', file=sys.stderr) self.fail('failure message') def test_error(self): print('stdout', file=sys.stdout) print('stderr', file=sys.stderr) raise RuntimeError('error message') suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestTests)) stream = io.StringIO() runner_cls = get_test_runner_class(sum(a == '-v' for a in sys.argv)) runner = runner_cls(sys.stdout) result = runner.run(suite) print('Output:', stream.getvalue()) print('XML: ', end='') for s in ET.tostringlist(result.get_xml_element()): print(s.decode(), end='') print() PK ! %3z�� � logging_helper.pynu �[��� import logging.handlers class TestHandler(logging.handlers.BufferingHandler): def __init__(self, matcher): # BufferingHandler takes a "capacity" argument # so as to know when to flush. As we're overriding # shouldFlush anyway, we can set a capacity of zero. # You can call flush() manually to clear out the # buffer. logging.handlers.BufferingHandler.__init__(self, 0) self.matcher = matcher def shouldFlush(self): return False def emit(self, record): self.format(record) self.buffer.append(record.__dict__) def matches(self, **kwargs): """ Look for a saved dict whose keys/values match the supplied arguments. """ result = False for d in self.buffer: if self.matcher.matches(d, **kwargs): result = True break return result PK ! �%�, �, script_helper.pynu �[��� # Common utility functions used by various script execution tests # e.g. test_cmd_line, test_cmd_line_script and test_runpy import collections import importlib import sys import os import os.path import subprocess import py_compile import zipfile from importlib.util import source_from_cache from test import support from test.support.import_helper import make_legacy_pyc # Cached result of the expensive test performed in the function below. __cached_interp_requires_environment = None def interpreter_requires_environment(): """ Returns True if our sys.executable interpreter requires environment variables in order to be able to run at all. This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process. A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn't have an obvious home with Python's current home finding logic. Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start. """ global __cached_interp_requires_environment if __cached_interp_requires_environment is None: # If PYTHONHOME is set, assume that we need it if 'PYTHONHOME' in os.environ: __cached_interp_requires_environment = True return True # Try running an interpreter with -E to see if it works or not. try: subprocess.check_call([sys.executable, '-E', '-c', 'import sys; sys.exit(0)']) except subprocess.CalledProcessError: __cached_interp_requires_environment = True else: __cached_interp_requires_environment = False return __cached_interp_requires_environment class _PythonRunResult(collections.namedtuple("_PythonRunResult", ("rc", "out", "err"))): """Helper for reporting Python subprocess run results""" def fail(self, cmd_line): """Provide helpful details about failed subcommand runs""" # Limit to 80 lines to ASCII characters maxlen = 80 * 100 out, err = self.out, self.err if len(out) > maxlen: out = b'(... truncated stdout ...)' + out[-maxlen:] if len(err) > maxlen: err = b'(... truncated stderr ...)' + err[-maxlen:] out = out.decode('ascii', 'replace').rstrip() err = err.decode('ascii', 'replace').rstrip() raise AssertionError("Process return code is %d\n" "command line: %r\n" "\n" "stdout:\n" "---\n" "%s\n" "---\n" "\n" "stderr:\n" "---\n" "%s\n" "---" % (self.rc, cmd_line, out, err)) # Executing the interpreter in a subprocess def run_python_until_end(*args, **env_vars): env_required = interpreter_requires_environment() cwd = env_vars.pop('__cwd', None) if '__isolated' in env_vars: isolated = env_vars.pop('__isolated') else: isolated = not env_vars and not env_required cmd_line = [sys.executable, '-X', 'faulthandler'] if isolated: # isolated mode: ignore Python environment variables, ignore user # site-packages, and don't add the current directory to sys.path cmd_line.append('-I') elif not env_vars and not env_required: # ignore Python environment variables cmd_line.append('-E') # But a special flag that can be set to override -- in this case, the # caller is responsible to pass the full environment. if env_vars.pop('__cleanenv', None): env = {} if sys.platform == 'win32': # Windows requires at least the SYSTEMROOT environment variable to # start Python. env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] # Other interesting environment variables, not copied currently: # COMSPEC, HOME, PATH, TEMP, TMPDIR, TMP. else: # Need to preserve the original environment, for in-place testing of # shared library builds. env = os.environ.copy() # set TERM='' unless the TERM environment variable is passed explicitly # see issues #11390 and #18300 if 'TERM' not in env_vars: env['TERM'] = '' env.update(env_vars) cmd_line.extend(args) proc = subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd) with proc: try: out, err = proc.communicate() finally: proc.kill() subprocess._cleanup() rc = proc.returncode return _PythonRunResult(rc, out, err), cmd_line def _assert_python(expected_success, /, *args, **env_vars): res, cmd_line = run_python_until_end(*args, **env_vars) if (res.rc and expected_success) or (not res.rc and not expected_success): res.fail(cmd_line) return res def assert_python_ok(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` succeeds (rc == 0) and return a (return code, stdout, stderr) tuple. If the __cleanenv keyword is set, env_vars is used as a fresh environment. Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False. """ return _assert_python(True, *args, **env_vars) def assert_python_failure(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` fails (rc != 0) and return a (return code, stdout, stderr) tuple. See assert_python_ok() for more options. """ return _assert_python(False, *args, **env_vars) def spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): """Run a Python subprocess with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. """ cmd_line = [sys.executable] if not interpreter_requires_environment(): cmd_line.append('-E') cmd_line.extend(args) # Under Fedora (?), GNU readline can output junk on stderr when initialized, # depending on the TERM setting. Setting TERM=vt100 is supposed to disable # that. References: # - http://reinout.vanrees.org/weblog/2009/08/14/readline-invisible-character-hack.html # - http://stackoverflow.com/questions/15760712/python-readline-module-prints-escape-character-during-import # - http://lists.gnu.org/archive/html/bug-readline/2007-08/msg00004.html env = kw.setdefault('env', dict(os.environ)) env['TERM'] = 'vt100' return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw) def kill_python(p): """Run the given Popen process until completion and return stdout.""" p.stdin.close() data = p.stdout.read() p.stdout.close() # try to cleanup the child so we don't appear to leak when running # with regrtest -R. p.wait() subprocess._cleanup() return data def make_script(script_dir, script_basename, source, omit_suffix=False): script_filename = script_basename if not omit_suffix: script_filename += os.extsep + 'py' script_name = os.path.join(script_dir, script_filename) # The script should be encoded to UTF-8, the default string encoding with open(script_name, 'w', encoding='utf-8') as script_file: script_file.write(source) importlib.invalidate_caches() return script_name def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) with zipfile.ZipFile(zip_name, 'w') as zip_file: if name_in_zip is None: parts = script_name.split(os.sep) if len(parts) >= 2 and parts[-2] == '__pycache__': legacy_pyc = make_legacy_pyc(source_from_cache(script_name)) name_in_zip = os.path.basename(legacy_pyc) script_name = legacy_pyc else: name_in_zip = os.path.basename(script_name) zip_file.write(script_name, name_in_zip) #if test.support.verbose: # with zipfile.ZipFile(zip_name, 'r') as zip_file: # print 'Contents of %r:' % zip_name # zip_file.printdir() return zip_name, os.path.join(zip_name, name_in_zip) def make_pkg(pkg_dir, init_source=''): os.mkdir(pkg_dir) make_script(pkg_dir, '__init__', init_source) def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False): unlink = [] init_name = make_script(zip_dir, '__init__', '') unlink.append(init_name) init_basename = os.path.basename(init_name) script_name = make_script(zip_dir, script_basename, source) unlink.append(script_name) if compiled: init_name = py_compile.compile(init_name, doraise=True) script_name = py_compile.compile(script_name, doraise=True) unlink.extend((init_name, script_name)) pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)] script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) with zipfile.ZipFile(zip_name, 'w') as zip_file: for name in pkg_names: init_name_in_zip = os.path.join(name, init_basename) zip_file.write(init_name, init_name_in_zip) zip_file.write(script_name, script_name_in_zip) for name in unlink: os.unlink(name) #if test.support.verbose: # with zipfile.ZipFile(zip_name, 'r') as zip_file: # print 'Contents of %r:' % zip_name # zip_file.printdir() return zip_name, os.path.join(zip_name, script_name_in_zip) def run_test_script(script): # use -u to try to get the full output if the test hangs or crash if support.verbose: def title(text): return f"===== {text} ======" name = f"script {os.path.basename(script)}" print() print(title(name), flush=True) # In verbose mode, the child process inherit stdout and stdout, # to see output in realtime and reduce the risk of losing output. args = [sys.executable, "-E", "-X", "faulthandler", "-u", script, "-v"] proc = subprocess.run(args) print(title(f"{name} completed: exit code {proc.returncode}"), flush=True) if proc.returncode: raise AssertionError(f"{name} failed") else: assert_python_ok("-u", script, "-v") PK ! e�N�8 8 import_helper.pynu �[��� import contextlib import importlib import importlib.util import os import shutil import sys import unittest import warnings from .os_helper import unlink @contextlib.contextmanager def _ignore_deprecated_imports(ignore=True): """Context manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect. """ if ignore: with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".+ (module|package)", DeprecationWarning) yield else: yield def unload(name): try: del sys.modules[name] except KeyError: pass def forget(modname): """'Forget' a module was ever imported. This removes the module from sys.modules and deletes any PEP 3147/488 or legacy .pyc files. """ unload(modname) for dirname in sys.path: source = os.path.join(dirname, modname + '.py') # It doesn't matter if they exist or not, unlink all possible # combinations of PEP 3147/488 and legacy pyc files. unlink(source + 'c') for opt in ('', 1, 2): unlink(importlib.util.cache_from_source(source, optimization=opt)) def make_legacy_pyc(source): """Move a PEP 3147/488 pyc file to its legacy pyc location. :param source: The file system path to the source file. The source file does not need to exist, however the PEP 3147/488 pyc file must exist. :return: The file system path to the legacy pyc file. """ pyc_file = importlib.util.cache_from_source(source) up_one = os.path.dirname(os.path.abspath(source)) legacy_pyc = os.path.join(up_one, source + 'c') shutil.move(pyc_file, legacy_pyc) return legacy_pyc def import_module(name, deprecated=False, *, required_on=()): """Import and return the module to be tested, raising SkipTest if it is not available. If deprecated is True, any module or package deprecation messages will be suppressed. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform. """ with _ignore_deprecated_imports(deprecated): try: return importlib.import_module(name) except ImportError as msg: if sys.platform.startswith(tuple(required_on)): raise raise unittest.SkipTest(str(msg)) def _save_and_remove_modules(names): orig_modules = {} prefixes = tuple(name + '.' for name in names) for modname in list(sys.modules): if modname in names or modname.startswith(prefixes): orig_modules[modname] = sys.modules.pop(modname) return orig_modules def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): """Import and return a module, deliberately bypassing sys.modules. This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload, the original module is not affected by this operation. *fresh* is an iterable of additional module names that are also removed from the sys.modules cache before doing the import. If one of these modules can't be imported, None is returned. *blocked* is an iterable of module names that are replaced with None in the module cache during the import to ensure that attempts to import them raise ImportError. The named module and any modules named in the *fresh* and *blocked* parameters are saved before starting the import and then reinserted into sys.modules when the fresh import is complete. Module and package deprecation messages are suppressed during this import if *deprecated* is True. This function will raise ImportError if the named module cannot be imported. """ # NOTE: test_heapq, test_json and test_warnings include extra sanity checks # to make sure that this utility function is working as expected with _ignore_deprecated_imports(deprecated): # Keep track of modules saved for later restoration as well # as those which just need a blocking entry removed fresh = list(fresh) blocked = list(blocked) names = {name, *fresh, *blocked} orig_modules = _save_and_remove_modules(names) for modname in blocked: sys.modules[modname] = None try: # Return None when one of the "fresh" modules can not be imported. try: for modname in fresh: __import__(modname) except ImportError: return None return importlib.import_module(name) finally: _save_and_remove_modules(names) sys.modules.update(orig_modules) class CleanImport(object): """Context manager to force import to return a new module reference. This is useful for testing module-level behaviours, such as the emission of a DeprecationWarning on import. Use like this: with CleanImport("foo"): importlib.import_module("foo") # new reference """ def __init__(self, *module_names): self.original_modules = sys.modules.copy() for module_name in module_names: if module_name in sys.modules: module = sys.modules[module_name] # It is possible that module_name is just an alias for # another module (e.g. stub for modules renamed in 3.x). # In that case, we also need delete the real module to clear # the import cache. if module.__name__ != module_name: del sys.modules[module.__name__] del sys.modules[module_name] def __enter__(self): return self def __exit__(self, *ignore_exc): sys.modules.update(self.original_modules) class DirsOnSysPath(object): """Context manager to temporarily add directories to sys.path. This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends. Note that *all* sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block. """ def __init__(self, *paths): self.original_value = sys.path[:] self.original_object = sys.path sys.path.extend(paths) def __enter__(self): return self def __exit__(self, *ignore_exc): sys.path = self.original_object sys.path[:] = self.original_value def modules_setup(): return sys.modules.copy(), def modules_cleanup(oldmodules): # Encoders/decoders are registered permanently within the internal # codec cache. If we destroy the corresponding modules their # globals will be set to None which will trip up the cached functions. encodings = [(k, v) for k, v in sys.modules.items() if k.startswith('encodings.')] sys.modules.clear() sys.modules.update(encodings) # XXX: This kind of problem can affect more than just encodings. # In particular extension modules (such as _ssl) don't cope # with reloading properly. Really, test modules should be cleaning # out the test specific modules they know they added (ala test_runpy) # rather than relying on this function (as test_importhooks and test_pkg # do currently). Implicitly imported *real* modules should be left alone # (see issue 10556). sys.modules.update(oldmodules) PK ! �^d��, �, socket_helper.pynu �[��� import contextlib import errno import socket import unittest import sys from .. import support HOST = "localhost" HOSTv4 = "127.0.0.1" HOSTv6 = "::1" def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): """Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned. Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl's s_server mode). Always prefer bind_port() over find_unused_port() where possible. Hard coded ports should *NEVER* be used. As soon as a server socket is bound to a hard coded port, the ability to run multiple instances of the test simultaneously on the same host is compromised, which makes the test a ticking time bomb in a buildbot environment. On Unix buildbots, this may simply manifest as a failed test, which can be recovered from without intervention in most cases, but on Windows, the entire python process can completely and utterly wedge, requiring someone to log in to the buildbot and manually kill the affected process. (This is easy to reproduce on Windows, unfortunately, and can be traced to the SO_REUSEADDR socket option having different semantics on Windows versus Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, listen and then accept connections on identical host/ports. An EADDRINUSE OSError will be raised at some point (depending on the platform and the order bind and listen were called on each socket). However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE will ever be raised when attempting to bind two identical host/ports. When accept() is called on each socket, the second caller's process will steal the port from the first caller, leaving them both in an awkwardly wedged state where they'll no longer respond to any signals or graceful kills, and must be forcibly killed via OpenProcess()/TerminateProcess(). The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option instead of SO_REUSEADDR, which effectively affords the same semantics as SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open Source world compared to Windows ones, this is a common mistake. A quick look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when openssl.exe is called with the 's_server' option, for example. See http://bugs.python.org/issue2550 for more info. The following site also has a very thorough description about the implications of both REUSEADDR and EXCLUSIVEADDRUSE on Windows: https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse XXX: although this approach is a vast improvement on previous attempts to elicit unused ports, it rests heavily on the assumption that the ephemeral port returned to us by the OS won't immediately be dished back out to some other process when we close and delete our temporary socket but before our calling code has a chance to bind the returned port. We can deal with this issue if/when we come across it. """ with socket.socket(family, socktype) as tempsock: port = bind_port(tempsock) del tempsock return port def bind_port(sock, host=HOST): """Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. """ if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: if hasattr(socket, 'SO_REUSEADDR'): if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: raise support.TestFailed("tests should never set the " "SO_REUSEADDR socket option on " "TCP/IP sockets!") if hasattr(socket, 'SO_REUSEPORT'): try: if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: raise support.TestFailed("tests should never set the " "SO_REUSEPORT socket option on " "TCP/IP sockets!") except OSError: # Python's socket module was compiled using modern headers # thus defining SO_REUSEPORT but this process is running # under an older kernel that does not support SO_REUSEPORT. pass if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) sock.bind((host, 0)) port = sock.getsockname()[1] return port def bind_unix_socket(sock, addr): """Bind a unix socket, raising SkipTest if PermissionError is raised.""" assert sock.family == socket.AF_UNIX try: sock.bind(addr) except PermissionError: sock.close() raise unittest.SkipTest('cannot bind AF_UNIX sockets') def _is_ipv6_enabled(): """Check whether IPv6 is enabled on this host.""" if socket.has_ipv6: sock = None try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind((HOSTv6, 0)) return True except OSError: pass finally: if sock: sock.close() return False IPV6_ENABLED = _is_ipv6_enabled() _bind_nix_socket_error = None def skip_unless_bind_unix_socket(test): """Decorator for tests requiring a functional bind() for unix sockets.""" if not hasattr(socket, 'AF_UNIX'): return unittest.skip('No UNIX Sockets')(test) global _bind_nix_socket_error if _bind_nix_socket_error is None: from .os_helper import TESTFN, unlink path = TESTFN + "can_bind_unix_socket" with socket.socket(socket.AF_UNIX) as sock: try: sock.bind(path) _bind_nix_socket_error = False except OSError as e: _bind_nix_socket_error = e finally: unlink(path) if _bind_nix_socket_error: msg = 'Requires a functional unix bind(): %s' % _bind_nix_socket_error return unittest.skip(msg)(test) else: return test def get_socket_conn_refused_errs(): """ Get the different socket error numbers ('errno') which can be received when a connection is refused. """ errors = [errno.ECONNREFUSED] if hasattr(errno, 'ENETUNREACH'): # On Solaris, ENETUNREACH is returned sometimes instead of ECONNREFUSED errors.append(errno.ENETUNREACH) if hasattr(errno, 'EADDRNOTAVAIL'): # bpo-31910: socket.create_connection() fails randomly # with EADDRNOTAVAIL on Travis CI errors.append(errno.EADDRNOTAVAIL) if hasattr(errno, 'EHOSTUNREACH'): # bpo-37583: The destination host cannot be reached errors.append(errno.EHOSTUNREACH) if not IPV6_ENABLED: errors.append(errno.EAFNOSUPPORT) return errors _NOT_SET = object() @contextlib.contextmanager def transient_internet(resource_name, *, timeout=_NOT_SET, errnos=()): """Return a context manager that raises ResourceDenied when various issues with the internet connection manifest themselves as exceptions.""" import nntplib import urllib.error if timeout is _NOT_SET: timeout = support.INTERNET_TIMEOUT default_errnos = [ ('ECONNREFUSED', 111), ('ECONNRESET', 104), ('EHOSTUNREACH', 113), ('ENETUNREACH', 101), ('ETIMEDOUT', 110), # socket.create_connection() fails randomly with # EADDRNOTAVAIL on Travis CI. ('EADDRNOTAVAIL', 99), ] default_gai_errnos = [ ('EAI_AGAIN', -3), ('EAI_FAIL', -4), ('EAI_NONAME', -2), ('EAI_NODATA', -5), # Encountered when trying to resolve IPv6-only hostnames ('WSANO_DATA', 11004), ] denied = support.ResourceDenied("Resource %r is not available" % resource_name) captured_errnos = errnos gai_errnos = [] if not captured_errnos: captured_errnos = [getattr(errno, name, num) for (name, num) in default_errnos] gai_errnos = [getattr(socket, name, num) for (name, num) in default_gai_errnos] def filter_error(err): n = getattr(err, 'errno', None) if (isinstance(err, TimeoutError) or (isinstance(err, socket.gaierror) and n in gai_errnos) or (isinstance(err, urllib.error.HTTPError) and 500 <= err.code <= 599) or (isinstance(err, urllib.error.URLError) and (("ConnectionRefusedError" in err.reason) or ("TimeoutError" in err.reason) or ("EOFError" in err.reason))) or n in captured_errnos): if not support.verbose: sys.stderr.write(denied.args[0] + "\n") raise denied from err old_timeout = socket.getdefaulttimeout() try: if timeout is not None: socket.setdefaulttimeout(timeout) yield except nntplib.NNTPTemporaryError as err: if support.verbose: sys.stderr.write(denied.args[0] + "\n") raise denied from err except OSError as err: # urllib can wrap original socket errors multiple times (!), we must # unwrap to get at the original error. while True: a = err.args if len(a) >= 1 and isinstance(a[0], OSError): err = a[0] # The error can also be wrapped as args[1]: # except socket.error as msg: # raise OSError('socket error', msg).with_traceback(sys.exc_info()[2]) elif len(a) >= 2 and isinstance(a[1], OSError): err = a[1] else: break filter_error(err) raise # XXX should we catch generic exceptions and look for their # __cause__ or __context__? finally: socket.setdefaulttimeout(old_timeout) PK ! ��Ü% �% ) __pycache__/socket_helper.cpython-310.pycnu �[��� o p̦i�, � @ s� d dl Z d dlZd dlZd dlZd dlZddlmZ dZdZdZ ej ejfdd�Zefd d �Z dd� Zd d� Ze� Zdadd� Zdd� Ze� Ze jedd�dd��ZdS )� N� )�support� localhostz 127.0.0.1z::1c C s>