File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/support.zip
Back
PK nd�Ze�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 nd�Zm�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 nd�Z�+�o o bytecode_helper.pynu �[��� """bytecode_helper - support tools for testing correct bytecode generation""" import unittest import dis import io _UNSPECIFIED = object() class BytecodeTestCase(unittest.TestCase): """Custom assertion methods for inspecting bytecode.""" def get_disassembly_as_string(self, co): s = io.StringIO() dis.dis(co, file=s) return s.getvalue() def assertInBytecode(self, x, opname, argval=_UNSPECIFIED): """Returns instr if opname is found, otherwise throws AssertionError""" for instr in dis.get_instructions(x): if instr.opname == opname: if argval is _UNSPECIFIED or instr.argval == argval: return instr disassembly = self.get_disassembly_as_string(x) if argval is _UNSPECIFIED: msg = '%s not found in bytecode:\n%s' % (opname, disassembly) else: msg = '(%s,%r) not found in bytecode:\n%s' msg = msg % (opname, argval, disassembly) self.fail(msg) def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): """Throws AssertionError if opname is found""" for instr in dis.get_instructions(x): if instr.opname == opname: disassembly = self.get_disassembly_as_string(x) if argval is _UNSPECIFIED: msg = '%s occurs in bytecode:\n%s' % (opname, disassembly) self.fail(msg) elif instr.argval == argval: msg = '(%s,%r) occurs in bytecode:\n%s' msg = msg % (opname, argval, disassembly) self.fail(msg) PK nd�ZQ�5� � ) __pycache__/import_helper.cpython-310.pycnu �[��� o }�5h8 � @ s� d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZddlm Z e j ddd��Zdd� Zd d � Z dd� Zddd�dd�Zdd� Zd dd�ZG dd� de�ZG dd� de�Zdd� Zdd� ZdS )!� N� )�unlinkTc c sR � | r$t �� � t �ddt� dV W d � dS 1 sw Y dS dV dS )z�Context manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect. �ignorez.+ (module|package)N)�warnings�catch_warnings�filterwarnings�DeprecationWarning)r � r �1/usr/lib/python3.10/test/support/import_helper.py�_ignore_deprecated_imports s � �"� r c C s$ zt j| = W d S ty Y d S w �N)�sys�modules�KeyError)�namer r r �unload s �r c C sT t | � tjD ] }tj�|| d �}t|d � dD ]}ttjj||d�� qqdS )z�'Forget' a module was ever imported. This removes the module from sys.modules and deletes any PEP 3147/488 or legacy .pyc files. z.py�c)� r � )�optimizationN) r r �path�os�joinr � importlib�util�cache_from_source)�modname�dirname�source�optr r r �forget$ s ��r c C sB t j�| �}tj�tj�| ��}tj�|| d �}t� ||� |S )a 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. r ) r r r r r r �abspathr �shutil�move)r �pyc_file�up_one� legacy_pycr r r �make_legacy_pyc4 s r'