asda?‰PNG  IHDR ? f ??C1 sRGB ??é gAMA ±? üa pHYs ? ??o¨d GIDATx^íüL”÷e÷Y?a?("Bh?_ò???¢§?q5k?*:t0A-o??¥]VkJ¢M??f?±8\k2íll£1]q?ù???T loader.py000064400000054010151030032340006353 0ustar00"""Loading unittests.""" import os import re import sys import traceback import types import functools import warnings from fnmatch import fnmatch, fnmatchcase from . import case, suite, util __unittest = True # what about .pyc (etc) # we would need to avoid loading the same tests multiple times # from '.py', *and* '.pyc' VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) class _FailedTest(case.TestCase): _testMethodName = None def __init__(self, method_name, exception): self._exception = exception super(_FailedTest, self).__init__(method_name) def __getattr__(self, name): if name != self._testMethodName: return super(_FailedTest, self).__getattr__(name) def testFailure(): raise self._exception return testFailure def _make_failed_import_test(name, suiteClass): message = 'Failed to import test module: %s\n%s' % ( name, traceback.format_exc()) return _make_failed_test(name, ImportError(message), suiteClass, message) def _make_failed_load_tests(name, exception, suiteClass): message = 'Failed to call load_tests:\n%s' % (traceback.format_exc(),) return _make_failed_test( name, exception, suiteClass, message) def _make_failed_test(methodname, exception, suiteClass, message): test = _FailedTest(methodname, exception) return suiteClass((test,)), message def _make_skipped_test(methodname, exception, suiteClass): @case.skip(str(exception)) def testSkipped(self): pass attrs = {methodname: testSkipped} TestClass = type("ModuleSkipped", (case.TestCase,), attrs) return suiteClass((TestClass(methodname),)) def _jython_aware_splitext(path): if path.lower().endswith('$py.class'): return path[:-9] return os.path.splitext(path)[0] class TestLoader(object): """ This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ testMethodPrefix = 'test' sortTestMethodsUsing = staticmethod(util.three_way_cmp) testNamePatterns = None suiteClass = suite.TestSuite _top_level_dir = None def __init__(self): super(TestLoader, self).__init__() self.errors = [] # Tracks packages which we have called into via load_tests, to # avoid infinite re-entrancy. self._loading_packages = set() def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all test cases contained in testCaseClass""" if issubclass(testCaseClass, suite.TestSuite): raise TypeError("Test cases should not be derived from " "TestSuite. Maybe you meant to derive from " "TestCase?") if testCaseClass in (case.TestCase, case.FunctionTestCase): # We don't load any tests from base types that should not be loaded. testCaseNames = [] else: testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) return loaded_suite # XXX After Python 3.5, remove backward compatibility hacks for # use_load_tests deprecation via *args and **kws. See issue 16662. def loadTestsFromModule(self, module, *args, pattern=None, **kws): """Return a suite of all test cases contained in the given module""" # This method used to take an undocumented and unofficial # use_load_tests argument. For backward compatibility, we still # accept the argument (which can also be the first position) but we # ignore it and issue a deprecation warning if it's present. if len(args) > 0 or 'use_load_tests' in kws: warnings.warn('use_load_tests is deprecated and ignored', DeprecationWarning) kws.pop('use_load_tests', None) if len(args) > 1: # Complain about the number of arguments, but don't forget the # required `module` argument. complaint = len(args) + 1 raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint)) if len(kws) != 0: # Since the keyword arguments are unsorted (see PEP 468), just # pick the alphabetically sorted first argument to complain about, # if multiple were given. At least the error message will be # predictable. complaint = sorted(kws)[0] raise TypeError("loadTestsFromModule() got an unexpected keyword argument '{}'".format(complaint)) tests = [] for name in dir(module): obj = getattr(module, name) if ( isinstance(obj, type) and issubclass(obj, case.TestCase) and obj not in (case.TestCase, case.FunctionTestCase) ): tests.append(self.loadTestsFromTestCase(obj)) load_tests = getattr(module, 'load_tests', None) tests = self.suiteClass(tests) if load_tests is not None: try: return load_tests(self, tests, pattern) except Exception as e: error_case, error_message = _make_failed_load_tests( module.__name__, e, self.suiteClass) self.errors.append(error_message) return error_case return tests def loadTestsFromName(self, name, module=None): """Return a suite of all test cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. """ parts = name.split('.') error_case, error_message = None, None if module is None: parts_copy = parts[:] while parts_copy: try: module_name = '.'.join(parts_copy) module = __import__(module_name) break except ImportError: next_attribute = parts_copy.pop() # Last error so we can give it to the user if needed. error_case, error_message = _make_failed_import_test( next_attribute, self.suiteClass) if not parts_copy: # Even the top level import failed: report that error. self.errors.append(error_message) return error_case parts = parts[1:] obj = module for part in parts: try: parent, obj = obj, getattr(obj, part) except AttributeError as e: # We can't traverse some part of the name. if (getattr(obj, '__path__', None) is not None and error_case is not None): # This is a package (no __path__ per importlib docs), and we # encountered an error importing something. We cannot tell # the difference between package.WrongNameTestClass and # package.wrong_module_name so we just report the # ImportError - it is more informative. self.errors.append(error_message) return error_case else: # Otherwise, we signal that an AttributeError has occurred. error_case, error_message = _make_failed_test( part, e, self.suiteClass, 'Failed to access attribute:\n%s' % ( traceback.format_exc(),)) self.errors.append(error_message) return error_case if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) elif ( isinstance(obj, type) and issubclass(obj, case.TestCase) and obj not in (case.TestCase, case.FunctionTestCase) ): return self.loadTestsFromTestCase(obj) elif (isinstance(obj, types.FunctionType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): name = parts[-1] inst = parent(name) # static methods follow a different path if not isinstance(getattr(inst, name), types.FunctionType): return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj if callable(obj): test = obj() if isinstance(test, suite.TestSuite): return test elif isinstance(test, case.TestCase): return self.suiteClass([test]) else: raise TypeError("calling %s returned %s, not a test" % (obj, test)) else: raise TypeError("don't know how to make test from: %s" % obj) def loadTestsFromNames(self, names, module=None): """Return a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. """ suites = [self.loadTestsFromName(name, module) for name in names] return self.suiteClass(suites) def getTestCaseNames(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass """ def shouldIncludeMethod(attrname): if not attrname.startswith(self.testMethodPrefix): return False testFunc = getattr(testCaseClass, attrname) if not callable(testFunc): return False fullName = f'%s.%s.%s' % ( testCaseClass.__module__, testCaseClass.__qualname__, attrname ) return self.testNamePatterns is None or \ any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns) testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass))) if self.sortTestMethodsUsing: testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing)) return testFnNames def discover(self, start_dir, pattern='test*.py', top_level_dir=None): """Find and return all test modules from the specified start directory, recursing into subdirectories to find them and return all tests found within them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with (loader, tests, pattern) unless the package has already had load_tests called from the same discovery invocation, in which case the package module object is not scanned for tests - this ensures that when a package uses discover to further discover child tests that infinite recursion does not happen. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). Paths are sorted before being imported to ensure reproducible execution order even on filesystems with non-alphabetical ordering like ext3/4. """ set_implicit_top = False if top_level_dir is None and self._top_level_dir is not None: # make top_level_dir optional if called from load_tests in a package top_level_dir = self._top_level_dir elif top_level_dir is None: set_implicit_top = True top_level_dir = start_dir top_level_dir = os.path.abspath(top_level_dir) if not top_level_dir in sys.path: # all test modules must be importable from the top level directory # should we *unconditionally* put the start directory in first # in sys.path to minimise likelihood of conflicts between installed # modules and development versions? sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False if os.path.isdir(os.path.abspath(start_dir)): start_dir = os.path.abspath(start_dir) if start_dir != top_level_dir: is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) else: # support for discovery from dotted module names try: __import__(start_dir) except ImportError: is_not_importable = True else: the_module = sys.modules[start_dir] top_part = start_dir.split('.')[0] try: start_dir = os.path.abspath( os.path.dirname((the_module.__file__))) except AttributeError: if the_module.__name__ in sys.builtin_module_names: # builtin module raise TypeError('Can not use builtin modules ' 'as dotted module names') from None else: raise TypeError( f"don't know how to discover from {the_module!r}" ) from None if set_implicit_top: self._top_level_dir = self._get_directory_containing_module(top_part) sys.path.remove(top_level_dir) if is_not_importable: raise ImportError('Start directory is not importable: %r' % start_dir) tests = list(self._find_tests(start_dir, pattern)) return self.suiteClass(tests) def _get_directory_containing_module(self, module_name): module = sys.modules[module_name] full_path = os.path.abspath(module.__file__) if os.path.basename(full_path).lower().startswith('__init__.py'): return os.path.dirname(os.path.dirname(full_path)) else: # here we have been given a module rather than a package - so # all we can do is search the *same* directory the module is in # should an exception be raised instead return os.path.dirname(full_path) def _get_name_from_path(self, path): if path == self._top_level_dir: return '.' path = _jython_aware_splitext(os.path.normpath(path)) _relpath = os.path.relpath(path, self._top_level_dir) assert not os.path.isabs(_relpath), "Path must be within the project" assert not _relpath.startswith('..'), "Path must be within the project" name = _relpath.replace(os.path.sep, '.') return name def _get_module_from_name(self, name): __import__(name) return sys.modules[name] def _match_path(self, path, full_path, pattern): # override this method to use alternative matching strategy return fnmatch(path, pattern) def _find_tests(self, start_dir, pattern): """Used by discovery. Yields test suites it loads.""" # Handle the __init__ in this package name = self._get_name_from_path(start_dir) # name is '.' when start_dir == top_level_dir (and top_level_dir is by # definition not a package). if name != '.' and name not in self._loading_packages: # name is in self._loading_packages while we have called into # loadTestsFromModule with name. tests, should_recurse = self._find_test_path(start_dir, pattern) if tests is not None: yield tests if not should_recurse: # Either an error occurred, or load_tests was used by the # package. return # Handle the contents. paths = sorted(os.listdir(start_dir)) for path in paths: full_path = os.path.join(start_dir, path) tests, should_recurse = self._find_test_path(full_path, pattern) if tests is not None: yield tests if should_recurse: # we found a package that didn't use load_tests. name = self._get_name_from_path(full_path) self._loading_packages.add(name) try: yield from self._find_tests(full_path, pattern) finally: self._loading_packages.discard(name) def _find_test_path(self, full_path, pattern): """Used by discovery. Loads tests from a single file, or a directories' __init__.py when passed the directory. Returns a tuple (None_or_tests_from_file, should_recurse). """ basename = os.path.basename(full_path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(basename): # valid Python identifiers only return None, False if not self._match_path(basename, full_path, pattern): return None, False # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except case.SkipTest as e: return _make_skipped_test(name, e, self.suiteClass), False except: error_case, error_message = \ _make_failed_import_test(name, self.suiteClass) self.errors.append(error_message) return error_case, False else: mod_file = os.path.abspath( getattr(module, '__file__', full_path)) realpath = _jython_aware_splitext( os.path.realpath(mod_file)) fullpath_noext = _jython_aware_splitext( os.path.realpath(full_path)) if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = _jython_aware_splitext( os.path.basename(full_path)) expected_dir = os.path.dirname(full_path) msg = ("%r module incorrectly imported from %r. Expected " "%r. Is this module globally installed?") raise ImportError( msg % (mod_name, module_dir, expected_dir)) return self.loadTestsFromModule(module, pattern=pattern), False elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): return None, False load_tests = None tests = None name = self._get_name_from_path(full_path) try: package = self._get_module_from_name(name) except case.SkipTest as e: return _make_skipped_test(name, e, self.suiteClass), False except: error_case, error_message = \ _make_failed_import_test(name, self.suiteClass) self.errors.append(error_message) return error_case, False else: load_tests = getattr(package, 'load_tests', None) # Mark this package as being in load_tests (possibly ;)) self._loading_packages.add(name) try: tests = self.loadTestsFromModule(package, pattern=pattern) if load_tests is not None: # loadTestsFromModule(package) has loaded tests for us. return tests, False return tests, True finally: self._loading_packages.discard(name) else: return None, False defaultTestLoader = TestLoader() # These functions are considered obsolete for long time. # They will be removed in Python 3.13. def _makeLoader(prefix, sortUsing, suiteClass=None, testNamePatterns=None): loader = TestLoader() loader.sortTestMethodsUsing = sortUsing loader.testMethodPrefix = prefix loader.testNamePatterns = testNamePatterns if suiteClass: loader.suiteClass = suiteClass return loader def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp, testNamePatterns=None): import warnings warnings.warn( "unittest.getTestCaseNames() is deprecated and will be removed in Python 3.13. " "Please use unittest.TestLoader.getTestCaseNames() instead.", DeprecationWarning, stacklevel=2 ) return _makeLoader(prefix, sortUsing, testNamePatterns=testNamePatterns).getTestCaseNames(testCaseClass) def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): import warnings warnings.warn( "unittest.makeSuite() is deprecated and will be removed in Python 3.13. " "Please use unittest.TestLoader.loadTestsFromTestCase() instead.", DeprecationWarning, stacklevel=2 ) return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase( testCaseClass) def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): import warnings warnings.warn( "unittest.findTestCases() is deprecated and will be removed in Python 3.13. " "Please use unittest.TestLoader.loadTestsFromModule() instead.", DeprecationWarning, stacklevel=2 ) return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\ module) util.py000064400000012137151030032340006066 0ustar00"""Various utility functions.""" from collections import namedtuple, Counter from os.path import commonprefix __unittest = True _MAX_LENGTH = 80 _PLACEHOLDER_LEN = 12 _MIN_BEGIN_LEN = 5 _MIN_END_LEN = 5 _MIN_COMMON_LEN = 5 _MIN_DIFF_LEN = _MAX_LENGTH - \ (_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + _PLACEHOLDER_LEN + _MIN_END_LEN) assert _MIN_DIFF_LEN >= 0 def _shorten(s, prefixlen, suffixlen): skip = len(s) - prefixlen - suffixlen if skip > _PLACEHOLDER_LEN: s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:]) return s def _common_shorten_repr(*args): args = tuple(map(safe_repr, args)) maxlen = max(map(len, args)) if maxlen <= _MAX_LENGTH: return args prefix = commonprefix(args) prefixlen = len(prefix) common_len = _MAX_LENGTH - \ (maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN) if common_len > _MIN_COMMON_LEN: assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \ (maxlen - prefixlen) < _MAX_LENGTH prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len) return tuple(prefix + s[prefixlen:] for s in args) prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN) return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN) for s in args) def safe_repr(obj, short=False): try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + ' [truncated]...' def strclass(cls): return "%s.%s" % (cls.__module__, cls.__qualname__) def sorted_list_difference(expected, actual): """Finds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the second contains those elements in the "actual" list but not in the "expected" list. Duplicate elements in either input list are ignored. """ i = j = 0 missing = [] unexpected = [] while True: try: e = expected[i] a = actual[j] if e < a: missing.append(e) i += 1 while expected[i] == e: i += 1 elif e > a: unexpected.append(a) j += 1 while actual[j] == a: j += 1 else: i += 1 try: while expected[i] == e: i += 1 finally: j += 1 while actual[j] == a: j += 1 except IndexError: missing.extend(expected[i:]) unexpected.extend(actual[j:]) break return missing, unexpected def unorderable_list_difference(expected, actual): """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance.""" missing = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) # anything left in actual is unexpected return missing, actual def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y) _Mismatch = namedtuple('Mismatch', 'actual expected value') def _count_diff_all_purpose(actual, expected): 'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ' # elements need not be hashable s, t = list(actual), list(expected) m, n = len(s), len(t) NULL = object() result = [] for i, elem in enumerate(s): if elem is NULL: continue cnt_s = cnt_t = 0 for j in range(i, m): if s[j] == elem: cnt_s += 1 s[j] = NULL for j, other_elem in enumerate(t): if other_elem == elem: cnt_t += 1 t[j] = NULL if cnt_s != cnt_t: diff = _Mismatch(cnt_s, cnt_t, elem) result.append(diff) for i, elem in enumerate(t): if elem is NULL: continue cnt_t = 0 for j in range(i, n): if t[j] == elem: cnt_t += 1 t[j] = NULL diff = _Mismatch(0, cnt_t, elem) result.append(diff) return result def _count_diff_hashable(actual, expected): 'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ' # elements must be hashable s, t = Counter(actual), Counter(expected) result = [] for elem, cnt_s in s.items(): cnt_t = t.get(elem, 0) if cnt_s != cnt_t: diff = _Mismatch(cnt_s, cnt_t, elem) result.append(diff) for elem, cnt_t in t.items(): if elem not in s: diff = _Mismatch(0, cnt_t, elem) result.append(diff) return result result.py000064400000020506151030032340006426 0ustar00"""Test result object""" import io import sys import traceback from . import util from functools import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): self.stop() return method(self, *args, **kw) return inner STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' class TestResult(object): """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. """ _previousTestClass = None _testRunEntered = False _moduleSetUpFailed = False def __init__(self, stream=None, descriptions=None, verbosity=None): self.failfast = False self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False self.buffer = False self.tb_locals = False self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr self._mirrorOutput = False def printErrors(self): "Called by TestRunner after test run" def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout() def _setupStdout(self): if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = io.StringIO() self._stdout_buffer = io.StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False def _restoreStdout(self): if self.buffer: if self._mirrorOutput: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """ @failfast def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True @failfast def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSubTest(self, test, subtest, err): """Called at the end of a subtest. 'err' is None if the subtest ended successfully, otherwise it's a tuple of values as returned by sys.exc_info(). """ # By default, we don't do anything with successful subtests, but # more sophisticated test results might want to record them. if err is not None: if getattr(self, 'failfast', False): self.stop() if issubclass(err[0], test.failureException): errors = self.failures else: errors = self.errors errors.append((subtest, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSuccess(self, test): "Called when a test has completed successfully" pass def addSkip(self, test, reason): """Called when a test is skipped.""" self.skipped.append((test, reason)) def addExpectedFailure(self, test, err): """Called when an expected failure/error occurred.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test))) @failfast def addUnexpectedSuccess(self, test): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" # The hasattr check is for test_result's OldResult test. That # way this method works on objects that lack the attribute. # (where would such result instances come from? old stored pickles?) return ((len(self.failures) == len(self.errors) == 0) and (not hasattr(self, 'unexpectedSuccesses') or len(self.unexpectedSuccesses) == 0)) def stop(self): """Indicates that the tests should be aborted.""" self.shouldStop = True def _exc_info_to_string(self, err, test): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err tb = self._clean_tracebacks(exctype, value, tb, test) tb_e = traceback.TracebackException( exctype, value, tb, capture_locals=self.tb_locals, compact=True) msgLines = list(tb_e.format()) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines) def _clean_tracebacks(self, exctype, value, tb, test): ret = None first = True excs = [(exctype, value, tb)] seen = {id(value)} # Detect loops in chained exceptions. while excs: (exctype, value, tb) = excs.pop() # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next # Skip assert*() traceback levels if exctype is test.failureException: self._remove_unittest_tb_frames(tb) if first: ret = tb first = False else: value.__traceback__ = tb if value is not None: for c in (value.__cause__, value.__context__): if c is not None and id(c) not in seen: excs.append((type(c), c, c.__traceback__)) seen.add(id(c)) return ret def _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _remove_unittest_tb_frames(self, tb): '''Truncates usercode tb at the first unittest frame. If the first frame of the traceback is in user code, the prefix up to the first unittest frame is returned. If the first frame is already in the unittest module, the traceback is not modified. ''' prev = None while tb and not self._is_relevant_tb_level(tb): prev = tb tb = tb.tb_next if prev is not None: prev.tb_next = None def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures))) __main__.py000064400000000730151030032340006625 0ustar00"""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): import os.path # We change sys.argv[0] to make help message more useful # use executable without path, unquoted # (it's just a hint anyway) # (if you have spaces in your executable you get what you deserve!) executable = os.path.basename(sys.executable) sys.argv[0] = executable + " -m unittest" del os __unittest = True from .main import main main(module=None) suite.py000064400000032310151030032340006235 0ustar00"""TestSuite""" import sys from . import case from . import util __unittest = True def _call_if_exists(parent, attr): func = getattr(parent, attr, lambda: None) func() class BaseTestSuite(object): """A simple test suite that doesn't provide class or module shared fixtures. """ _cleanup = True def __init__(self, tests=()): self._tests = [] self._removed_tests = 0 self.addTests(tests) def __repr__(self): return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return list(self) == list(other) def __iter__(self): return iter(self._tests) def countTestCases(self): cases = self._removed_tests for test in self: if test: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not callable(test): raise TypeError("{} is not callable".format(repr(test))) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): raise TypeError("TestCases and TestSuites must be instantiated " "before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, str): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for index, test in enumerate(self): if result.shouldStop: break test(result) if self._cleanup: self._removeTestAtIndex(index) return result def _removeTestAtIndex(self, index): """Stop holding a reference to the TestCase at index.""" try: test = self._tests[index] except TypeError: # support for suite implementations that have overridden self._tests pass else: # Some unittest tests add non TestCase/TestSuite objects to # the suite. if hasattr(test, 'countTestCases'): self._removed_tests += test.countTestCases() self._tests[index] = None def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the tests without collecting errors in a TestResult""" for test in self: test.debug() class TestSuite(BaseTestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ def run(self, result, debug=False): topLevel = False if getattr(result, '_testRunEntered', False) is False: result._testRunEntered = topLevel = True for index, test in enumerate(self): if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue if not debug: test(result) else: test.debug() if self._cleanup: self._removeTestAtIndex(index) if topLevel: self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) result._testRunEntered = False return result def debug(self): """Run the tests without collecting errors in a TestResult""" debug = _DebugResult() self.run(debug, True) ################################ def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__", False): return failed = False try: currentClass._classSetupFailed = False except TypeError: # test may actually be a function # so its class will be a builtin-type pass setUpClass = getattr(currentClass, 'setUpClass', None) doClassCleanups = getattr(currentClass, 'doClassCleanups', None) if setUpClass is not None: _call_if_exists(result, '_setupStdout') try: try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise failed = True try: currentClass._classSetupFailed = True except TypeError: pass className = util.strclass(currentClass) self._createClassOrModuleLevelException(result, e, 'setUpClass', className) if failed and doClassCleanups is not None: doClassCleanups() for exc_info in currentClass.tearDown_exceptions: self._createClassOrModuleLevelException( result, exc_info[1], 'setUpClass', className, info=exc_info) finally: _call_if_exists(result, '_restoreStdout') def _get_previous_module(self, result): previousModule = None previousClass = getattr(result, '_previousTestClass', None) if previousClass is not None: previousModule = previousClass.__module__ return previousModule def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: module = sys.modules[currentModule] except KeyError: return setUpModule = getattr(module, 'setUpModule', None) if setUpModule is not None: _call_if_exists(result, '_setupStdout') try: try: setUpModule() except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True self._createClassOrModuleLevelException(result, e, 'setUpModule', currentModule) if result._moduleSetUpFailed: try: case.doModuleCleanups() except Exception as e: self._createClassOrModuleLevelException(result, e, 'setUpModule', currentModule) finally: _call_if_exists(result, '_restoreStdout') def _createClassOrModuleLevelException(self, result, exc, method_name, parent, info=None): errorName = f'{method_name} ({parent})' self._addClassOrModuleLevelException(result, exc, errorName, info) def _addClassOrModuleLevelException(self, result, exception, errorName, info=None): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: if not info: result.addError(error, sys.exc_info()) else: result.addError(error, info) def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except KeyError: return _call_if_exists(result, '_setupStdout') try: tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise self._createClassOrModuleLevelException(result, e, 'tearDownModule', previousModule) try: case.doModuleCleanups() except Exception as e: if isinstance(result, _DebugResult): raise self._createClassOrModuleLevelException(result, e, 'tearDownModule', previousModule) finally: _call_if_exists(result, '_restoreStdout') def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass or previousClass is None: return if getattr(previousClass, '_classSetupFailed', False): return if getattr(result, '_moduleSetUpFailed', False): return if getattr(previousClass, "__unittest_skip__", False): return tearDownClass = getattr(previousClass, 'tearDownClass', None) doClassCleanups = getattr(previousClass, 'doClassCleanups', None) if tearDownClass is None and doClassCleanups is None: return _call_if_exists(result, '_setupStdout') try: if tearDownClass is not None: try: tearDownClass() except Exception as e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) self._createClassOrModuleLevelException(result, e, 'tearDownClass', className) if doClassCleanups is not None: doClassCleanups() for exc_info in previousClass.tearDown_exceptions: if isinstance(result, _DebugResult): raise exc_info[1] className = util.strclass(previousClass) self._createClassOrModuleLevelException(result, exc_info[1], 'tearDownClass', className, info=exc_info) finally: _call_if_exists(result, '_restoreStdout') class _ErrorHolder(object): """ Placeholder for a TestCase inside a result. As far as a TestResult is concerned, this looks exactly like a unit test. Used to insert arbitrary errors into a test suite run. """ # Inspired by the ErrorHolder from Twisted: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py # attribute used by TestResult._exc_info_to_string failureException = None def __init__(self, description): self.description = description def id(self): return self.description def shortDescription(self): return None def __repr__(self): return "" % (self.description,) def __str__(self): return self.id() def run(self, result): # could call result.addError(...) - but this test-like object # shouldn't be run anyway pass def __call__(self, result): return self.run(result) def countTestCases(self): return 0 def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class _DebugResult(object): "Used by the TestSuite to hold previous class when running in debug." _previousTestClass = None _moduleSetUpFailed = False shouldStop = False async_case.py000064400000012531151030032340007217 0ustar00import asyncio import contextvars import inspect import warnings from .case import TestCase class IsolatedAsyncioTestCase(TestCase): # Names intentionally have a long prefix # to reduce a chance of clashing with user-defined attributes # from inherited test case # # The class doesn't call loop.run_until_complete(self.setUp()) and family # but uses a different approach: # 1. create a long-running task that reads self.setUp() # awaitable from queue along with a future # 2. await the awaitable object passing in and set the result # into the future object # 3. Outer code puts the awaitable and the future object into a queue # with waiting for the future # The trick is necessary because every run_until_complete() call # creates a new task with embedded ContextVar context. # To share contextvars between setUp(), test and tearDown() we need to execute # them inside the same task. # Note: the test case modifies event loop policy if the policy was not instantiated # yet. # asyncio.get_event_loop_policy() creates a default policy on demand but never # returns None # I believe this is not an issue in user level tests but python itself for testing # should reset a policy in every test module # by calling asyncio.set_event_loop_policy(None) in tearDownModule() def __init__(self, methodName='runTest'): super().__init__(methodName) self._asyncioRunner = None self._asyncioTestContext = contextvars.copy_context() async def asyncSetUp(self): pass async def asyncTearDown(self): pass def addAsyncCleanup(self, func, /, *args, **kwargs): # A trivial trampoline to addCleanup() # the function exists because it has a different semantics # and signature: # addCleanup() accepts regular functions # but addAsyncCleanup() accepts coroutines # # We intentionally don't add inspect.iscoroutinefunction() check # for func argument because there is no way # to check for async function reliably: # 1. It can be "async def func()" itself # 2. Class can implement "async def __call__()" method # 3. Regular "def func()" that returns awaitable object self.addCleanup(*(func, *args), **kwargs) async def enterAsyncContext(self, cm): """Enters the supplied asynchronous context manager. If successful, also adds its __aexit__ method as a cleanup function and returns the result of the __aenter__ method. """ # We look up the special methods on the type to match the with # statement. cls = type(cm) try: enter = cls.__aenter__ exit = cls.__aexit__ except AttributeError: raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does " f"not support the asynchronous context manager protocol" ) from None result = await enter(cm) self.addAsyncCleanup(exit, cm, None, None, None) return result def _callSetUp(self): # Force loop to be initialized and set as the current loop # so that setUp functions can use get_event_loop() and get the # correct loop instance. self._asyncioRunner.get_loop() self._asyncioTestContext.run(self.setUp) self._callAsync(self.asyncSetUp) def _callTestMethod(self, method): if self._callMaybeAsync(method) is not None: warnings.warn(f'It is deprecated to return a value that is not None from a ' f'test case ({method})', DeprecationWarning, stacklevel=4) def _callTearDown(self): self._callAsync(self.asyncTearDown) self._asyncioTestContext.run(self.tearDown) def _callCleanup(self, function, *args, **kwargs): self._callMaybeAsync(function, *args, **kwargs) def _callAsync(self, func, /, *args, **kwargs): assert self._asyncioRunner is not None, 'asyncio runner is not initialized' assert inspect.iscoroutinefunction(func), f'{func!r} is not an async function' return self._asyncioRunner.run( func(*args, **kwargs), context=self._asyncioTestContext ) def _callMaybeAsync(self, func, /, *args, **kwargs): assert self._asyncioRunner is not None, 'asyncio runner is not initialized' if inspect.iscoroutinefunction(func): return self._asyncioRunner.run( func(*args, **kwargs), context=self._asyncioTestContext, ) else: return self._asyncioTestContext.run(func, *args, **kwargs) def _setupAsyncioRunner(self): assert self._asyncioRunner is None, 'asyncio runner is already initialized' runner = asyncio.Runner(debug=True) self._asyncioRunner = runner def _tearDownAsyncioRunner(self): runner = self._asyncioRunner runner.close() def run(self, result=None): self._setupAsyncioRunner() try: return super().run(result) finally: self._tearDownAsyncioRunner() def debug(self): self._setupAsyncioRunner() super().debug() self._tearDownAsyncioRunner() def __del__(self): if self._asyncioRunner is not None: self._tearDownAsyncioRunner() runner.py000064400000022312151030032340006416 0ustar00"""Running tests""" import sys import time import warnings from . import result from .case import _SubTest from .signals import registerResult __unittest = True class _WritelnDecorator(object): """Used to decorate file-like objects with a handy 'writeln' method""" def __init__(self,stream): self.stream = stream def __getattr__(self, attr): if attr in ('stream', '__getstate__'): raise AttributeError(attr) return getattr(self.stream,attr) def writeln(self, arg=None): if arg: self.write(arg) self.write('\n') # text-mode streams translate to \r\n if needed class TextTestResult(result.TestResult): """A test result class that can print formatted text results to a stream. Used by TextTestRunner. """ separator1 = '=' * 70 separator2 = '-' * 70 def __init__(self, stream, descriptions, verbosity): super(TextTestResult, self).__init__(stream, descriptions, verbosity) self.stream = stream self.showAll = verbosity > 1 self.dots = verbosity == 1 self.descriptions = descriptions self._newline = True def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return '\n'.join((str(test), doc_first_line)) else: return str(test) def startTest(self, test): super(TextTestResult, self).startTest(test) if self.showAll: self.stream.write(self.getDescription(test)) self.stream.write(" ... ") self.stream.flush() self._newline = False def _write_status(self, test, status): is_subtest = isinstance(test, _SubTest) if is_subtest or self._newline: if not self._newline: self.stream.writeln() if is_subtest: self.stream.write(" ") self.stream.write(self.getDescription(test)) self.stream.write(" ... ") self.stream.writeln(status) self.stream.flush() self._newline = True def addSubTest(self, test, subtest, err): if err is not None: if self.showAll: if issubclass(err[0], subtest.failureException): self._write_status(subtest, "FAIL") else: self._write_status(subtest, "ERROR") elif self.dots: if issubclass(err[0], subtest.failureException): self.stream.write('F') else: self.stream.write('E') self.stream.flush() super(TextTestResult, self).addSubTest(test, subtest, err) def addSuccess(self, test): super(TextTestResult, self).addSuccess(test) if self.showAll: self._write_status(test, "ok") elif self.dots: self.stream.write('.') self.stream.flush() def addError(self, test, err): super(TextTestResult, self).addError(test, err) if self.showAll: self._write_status(test, "ERROR") elif self.dots: self.stream.write('E') self.stream.flush() def addFailure(self, test, err): super(TextTestResult, self).addFailure(test, err) if self.showAll: self._write_status(test, "FAIL") elif self.dots: self.stream.write('F') self.stream.flush() def addSkip(self, test, reason): super(TextTestResult, self).addSkip(test, reason) if self.showAll: self._write_status(test, "skipped {0!r}".format(reason)) elif self.dots: self.stream.write("s") self.stream.flush() def addExpectedFailure(self, test, err): super(TextTestResult, self).addExpectedFailure(test, err) if self.showAll: self.stream.writeln("expected failure") self.stream.flush() elif self.dots: self.stream.write("x") self.stream.flush() def addUnexpectedSuccess(self, test): super(TextTestResult, self).addUnexpectedSuccess(test) if self.showAll: self.stream.writeln("unexpected success") self.stream.flush() elif self.dots: self.stream.write("u") self.stream.flush() def printErrors(self): if self.dots or self.showAll: self.stream.writeln() self.stream.flush() self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) unexpectedSuccesses = getattr(self, 'unexpectedSuccesses', ()) if unexpectedSuccesses: self.stream.writeln(self.separator1) for test in unexpectedSuccesses: self.stream.writeln(f"UNEXPECTED SUCCESS: {self.getDescription(test)}") self.stream.flush() def printErrorList(self, flavour, errors): for test, err in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln("%s" % err) self.stream.flush() class TextTestRunner(object): """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. """ resultclass = TextTestResult def __init__(self, stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False): """Construct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. """ if stream is None: stream = sys.stderr self.stream = _WritelnDecorator(stream) self.descriptions = descriptions self.verbosity = verbosity self.failfast = failfast self.buffer = buffer self.tb_locals = tb_locals self.warnings = warnings if resultclass is not None: self.resultclass = resultclass def _makeResult(self): return self.resultclass(self.stream, self.descriptions, self.verbosity) def run(self, test): "Run the given test case or test suite." result = self._makeResult() registerResult(result) result.failfast = self.failfast result.buffer = self.buffer result.tb_locals = self.tb_locals with warnings.catch_warnings(): if self.warnings: # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ['default', 'always']: warnings.filterwarnings('module', category=DeprecationWarning, message=r'Please use assert\w+ instead.') startTime = time.perf_counter() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() try: test(result) finally: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() stopTime = time.perf_counter() timeTaken = stopTime - startTime result.printErrors() if hasattr(result, 'separator2'): self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() expectedFails = unexpectedSuccesses = skipped = 0 try: results = map(len, (result.expectedFailures, result.unexpectedSuccesses, result.skipped)) except AttributeError: pass else: expectedFails, unexpectedSuccesses, skipped = results infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") failed, errored = len(result.failures), len(result.errors) if failed: infos.append("failures=%d" % failed) if errored: infos.append("errors=%d" % errored) else: self.stream.write("OK") if skipped: infos.append("skipped=%d" % skipped) if expectedFails: infos.append("expected failures=%d" % expectedFails) if unexpectedSuccesses: infos.append("unexpected successes=%d" % unexpectedSuccesses) if infos: self.stream.writeln(" (%s)" % (", ".join(infos),)) else: self.stream.write("\n") self.stream.flush() return result signals.py000064400000004543151030032340006553 0ustar00import signal import weakref from functools import wraps __unittest = True class _InterruptHandler(object): def __init__(self, default_handler): self.called = False self.original_handler = default_handler if isinstance(default_handler, int): if default_handler == signal.SIG_DFL: # Pretend it's signal.default_int_handler instead. default_handler = signal.default_int_handler elif default_handler == signal.SIG_IGN: # Not quite the same thing as SIG_IGN, but the closest we # can make it: do nothing. def default_handler(unused_signum, unused_frame): pass else: raise TypeError("expected SIGINT signal handler to be " "signal.SIG_IGN, signal.SIG_DFL, or a " "callable object") self.default_handler = default_handler def __call__(self, signum, frame): installed_handler = signal.getsignal(signal.SIGINT) if installed_handler is not self: # if we aren't the installed handler, then delegate immediately # to the default handler self.default_handler(signum, frame) if self.called: self.default_handler(signum, frame) self.called = True for result in _results.keys(): result.stop() _results = weakref.WeakKeyDictionary() def registerResult(result): _results[result] = 1 def removeResult(result): return bool(_results.pop(result, None)) _interrupt_handler = None def installHandler(): global _interrupt_handler if _interrupt_handler is None: default_handler = signal.getsignal(signal.SIGINT) _interrupt_handler = _InterruptHandler(default_handler) signal.signal(signal.SIGINT, _interrupt_handler) def removeHandler(method=None): if method is not None: @wraps(method) def inner(*args, **kwargs): initial = signal.getsignal(signal.SIGINT) removeHandler() try: return method(*args, **kwargs) finally: signal.signal(signal.SIGINT, initial) return inner global _interrupt_handler if _interrupt_handler is not None: signal.signal(signal.SIGINT, _interrupt_handler.original_handler) mock.py000064400000313510151030032340006041 0ustar00# mock.py # Test tools for mocking and patching. # Maintained by Michael Foord # Backport for other versions of Python available from # https://pypi.org/project/mock __all__ = ( 'Mock', 'MagicMock', 'patch', 'sentinel', 'DEFAULT', 'ANY', 'call', 'create_autospec', 'AsyncMock', 'FILTER_DIR', 'NonCallableMock', 'NonCallableMagicMock', 'mock_open', 'PropertyMock', 'seal', ) import asyncio import contextlib import io import inspect import pprint import sys import builtins import pkgutil from asyncio import iscoroutinefunction from types import CodeType, ModuleType, MethodType from unittest.util import safe_repr from functools import wraps, partial from threading import RLock class InvalidSpecError(Exception): """Indicates that an invalid value was used as a mock spec.""" _builtins = {name for name in dir(builtins) if not name.startswith('_')} FILTER_DIR = True # Workaround for issue #12370 # Without this, the __class__ properties wouldn't be set correctly _safe_super = super def _is_async_obj(obj): if _is_instance_mock(obj) and not isinstance(obj, AsyncMock): return False if hasattr(obj, '__func__'): obj = getattr(obj, '__func__') return iscoroutinefunction(obj) or inspect.isawaitable(obj) def _is_async_func(func): if getattr(func, '__code__', None): return iscoroutinefunction(func) else: return False def _is_instance_mock(obj): # can't use isinstance on Mock objects because they override __class__ # The base class for all mocks is NonCallableMock return issubclass(type(obj), NonCallableMock) def _is_exception(obj): return ( isinstance(obj, BaseException) or isinstance(obj, type) and issubclass(obj, BaseException) ) def _extract_mock(obj): # Autospecced functions will return a FunctionType with "mock" attribute # which is the actual mock object that needs to be used. if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'): return obj.mock else: return obj def _get_signature_object(func, as_instance, eat_self): """ Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. """ if isinstance(func, type) and not as_instance: # If it's a type and should be modelled as a type, use __init__. func = func.__init__ # Skip the `self` argument in __init__ eat_self = True elif isinstance(func, (classmethod, staticmethod)): if isinstance(func, classmethod): # Skip the `cls` argument of a class method eat_self = True # Use the original decorated method to extract the correct function signature func = func.__func__ elif not isinstance(func, FunctionTypes): # If we really want to model an instance of the passed type, # __call__ should be looked up, not __init__. try: func = func.__call__ except AttributeError: return None if eat_self: sig_func = partial(func, None) else: sig_func = func try: return func, inspect.signature(sig_func) except ValueError: # Certain callable types are not supported by inspect.signature() return None def _check_signature(func, mock, skipfirst, instance=False): sig = _get_signature_object(func, instance, skipfirst) if sig is None: return func, sig = sig def checksig(self, /, *args, **kwargs): sig.bind(*args, **kwargs) _copy_func_details(func, checksig) type(mock)._mock_check_sig = checksig type(mock).__signature__ = sig def _copy_func_details(func, funcopy): # we explicitly don't copy func.__dict__ into this copy as it would # expose original attributes that should be mocked for attribute in ( '__name__', '__doc__', '__text_signature__', '__module__', '__defaults__', '__kwdefaults__', ): try: setattr(funcopy, attribute, getattr(func, attribute)) except AttributeError: pass def _callable(obj): if isinstance(obj, type): return True if isinstance(obj, (staticmethod, classmethod, MethodType)): return _callable(obj.__func__) if getattr(obj, '__call__', None) is not None: return True return False def _is_list(obj): # checks for list or tuples # XXXX badly named! return type(obj) in (list, tuple) def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, type): # already an instance return getattr(obj, '__call__', None) is not None # *could* be broken by a class overriding __mro__ or __dict__ via # a metaclass for base in (obj,) + obj.__mro__: if base.__dict__.get('__call__') is not None: return True return False def _set_signature(mock, original, instance=False): # creates a function with signature (*args, **kwargs) that delegates to a # mock. It still does signature checking by calling a lambda with the same # signature as the original. skipfirst = isinstance(original, type) result = _get_signature_object(original, instance, skipfirst) if result is None: return mock func, sig = result def checksig(*args, **kwargs): sig.bind(*args, **kwargs) _copy_func_details(func, checksig) name = original.__name__ if not name.isidentifier(): name = 'funcopy' context = {'_checksig_': checksig, 'mock': mock} src = """def %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)""" % name exec (src, context) funcopy = context[name] _setup_func(funcopy, mock, sig) return funcopy def _setup_func(funcopy, mock, sig): funcopy.mock = mock def assert_called_with(*args, **kwargs): return mock.assert_called_with(*args, **kwargs) def assert_called(*args, **kwargs): return mock.assert_called(*args, **kwargs) def assert_not_called(*args, **kwargs): return mock.assert_not_called(*args, **kwargs) def assert_called_once(*args, **kwargs): return mock.assert_called_once(*args, **kwargs) def assert_called_once_with(*args, **kwargs): return mock.assert_called_once_with(*args, **kwargs) def assert_has_calls(*args, **kwargs): return mock.assert_has_calls(*args, **kwargs) def assert_any_call(*args, **kwargs): return mock.assert_any_call(*args, **kwargs) def reset_mock(): funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() mock.reset_mock() ret = funcopy.return_value if _is_instance_mock(ret) and not ret is mock: ret.reset_mock() funcopy.called = False funcopy.call_count = 0 funcopy.call_args = None funcopy.call_args_list = _CallList() funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() funcopy.return_value = mock.return_value funcopy.side_effect = mock.side_effect funcopy._mock_children = mock._mock_children funcopy.assert_called_with = assert_called_with funcopy.assert_called_once_with = assert_called_once_with funcopy.assert_has_calls = assert_has_calls funcopy.assert_any_call = assert_any_call funcopy.reset_mock = reset_mock funcopy.assert_called = assert_called funcopy.assert_not_called = assert_not_called funcopy.assert_called_once = assert_called_once funcopy.__signature__ = sig mock._mock_delegate = funcopy def _setup_async_mock(mock): mock._is_coroutine = asyncio.coroutines._is_coroutine mock.await_count = 0 mock.await_args = None mock.await_args_list = _CallList() # Mock is not configured yet so the attributes are set # to a function and then the corresponding mock helper function # is called when the helper is accessed similar to _setup_func. def wrapper(attr, /, *args, **kwargs): return getattr(mock.mock, attr)(*args, **kwargs) for attribute in ('assert_awaited', 'assert_awaited_once', 'assert_awaited_with', 'assert_awaited_once_with', 'assert_any_await', 'assert_has_awaits', 'assert_not_awaited'): # setattr(mock, attribute, wrapper) causes late binding # hence attribute will always be the last value in the loop # Use partial(wrapper, attribute) to ensure the attribute is bound # correctly. setattr(mock, attribute, partial(wrapper, attribute)) def _is_magic(name): return '__%s__' % name[2:-2] == name class _SentinelObject(object): "A unique, named, sentinel object." def __init__(self, name): self.name = name def __repr__(self): return 'sentinel.%s' % self.name def __reduce__(self): return 'sentinel.%s' % self.name class _Sentinel(object): """Access attributes to return a named object, usable as a sentinel.""" def __init__(self): self._sentinels = {} def __getattr__(self, name): if name == '__bases__': # Without this help(unittest.mock) raises an exception raise AttributeError return self._sentinels.setdefault(name, _SentinelObject(name)) def __reduce__(self): return 'sentinel' sentinel = _Sentinel() DEFAULT = sentinel.DEFAULT _missing = sentinel.MISSING _deleted = sentinel.DELETED _allowed_names = { 'return_value', '_mock_return_value', 'side_effect', '_mock_side_effect', '_mock_parent', '_mock_new_parent', '_mock_name', '_mock_new_name' } def _delegating_property(name): _allowed_names.add(name) _the_name = '_mock_' + name def _get(self, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: return getattr(self, _the_name) return getattr(sig, name) def _set(self, value, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: self.__dict__[_the_name] = value else: setattr(sig, name, value) return property(_get, _set) class _CallList(list): def __contains__(self, value): if not isinstance(value, list): return list.__contains__(self, value) len_value = len(value) len_self = len(self) if len_value > len_self: return False for i in range(0, len_self - len_value + 1): sub_list = self[i:i+len_value] if sub_list == value: return True return False def __repr__(self): return pprint.pformat(list(self)) def _check_and_set_parent(parent, value, name, new_name): value = _extract_mock(value) if not _is_instance_mock(value): return False if ((value._mock_name or value._mock_new_name) or (value._mock_parent is not None) or (value._mock_new_parent is not None)): return False _parent = parent while _parent is not None: # setting a mock (value) as a child or return value of itself # should not modify the mock if _parent is value: return False _parent = _parent._mock_new_parent if new_name: value._mock_new_parent = parent value._mock_new_name = new_name if name: value._mock_parent = parent value._mock_name = name return True # Internal class to identify if we wrapped an iterator object or not. class _MockIter(object): def __init__(self, obj): self.obj = iter(obj) def __next__(self): return next(self.obj) class Base(object): _mock_return_value = DEFAULT _mock_side_effect = None def __init__(self, /, *args, **kwargs): pass class NonCallableMock(Base): """A non-callable version of `Mock`""" # Store a mutex as a class attribute in order to protect concurrent access # to mock attributes. Using a class attribute allows all NonCallableMock # instances to share the mutex for simplicity. # # See https://github.com/python/cpython/issues/98624 for why this is # necessary. _lock = RLock() def __new__(cls, /, *args, **kw): # every instance has its own class # so we can create magic methods on the # class without stomping on other mocks bases = (cls,) if not issubclass(cls, AsyncMockMixin): # Check if spec is an async object or function bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments spec_arg = bound_args.get('spec_set', bound_args.get('spec')) if spec_arg is not None and _is_async_obj(spec_arg): bases = (AsyncMockMixin, cls) new = type(cls.__name__, bases, {'__doc__': cls.__doc__}) instance = _safe_super(NonCallableMock, cls).__new__(new) return instance def __init__( self, spec=None, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs ): if _new_parent is None: _new_parent = parent __dict__ = self.__dict__ __dict__['_mock_parent'] = parent __dict__['_mock_name'] = name __dict__['_mock_new_name'] = _new_name __dict__['_mock_new_parent'] = _new_parent __dict__['_mock_sealed'] = False if spec_set is not None: spec = spec_set spec_set = True if _eat_self is None: _eat_self = parent is not None self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self) __dict__['_mock_children'] = {} __dict__['_mock_wraps'] = wraps __dict__['_mock_delegate'] = None __dict__['_mock_called'] = False __dict__['_mock_call_args'] = None __dict__['_mock_call_count'] = 0 __dict__['_mock_call_args_list'] = _CallList() __dict__['_mock_mock_calls'] = _CallList() __dict__['method_calls'] = _CallList() __dict__['_mock_unsafe'] = unsafe if kwargs: self.configure_mock(**kwargs) _safe_super(NonCallableMock, self).__init__( spec, wraps, name, spec_set, parent, _spec_state ) def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" inner_mock = _extract_mock(mock) inner_mock._mock_parent = None inner_mock._mock_new_parent = None inner_mock._mock_name = '' inner_mock._mock_new_name = None setattr(self, attribute, mock) def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, _eat_self=False): if _is_instance_mock(spec): raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec!r}]') _spec_class = None _spec_signature = None _spec_asyncs = [] for attr in dir(spec): if iscoroutinefunction(getattr(spec, attr, None)): _spec_asyncs.append(attr) if spec is not None and not _is_list(spec): if isinstance(spec, type): _spec_class = spec else: _spec_class = type(spec) res = _get_signature_object(spec, _spec_as_instance, _eat_self) _spec_signature = res and res[1] spec = dir(spec) __dict__ = self.__dict__ __dict__['_spec_class'] = _spec_class __dict__['_spec_set'] = spec_set __dict__['_spec_signature'] = _spec_signature __dict__['_mock_methods'] = spec __dict__['_spec_asyncs'] = _spec_asyncs def __get_return_value(self): ret = self._mock_return_value if self._mock_delegate is not None: ret = self._mock_delegate.return_value if ret is DEFAULT and self._mock_wraps is None: ret = self._get_child_mock( _new_parent=self, _new_name='()' ) self.return_value = ret return ret def __set_return_value(self, value): if self._mock_delegate is not None: self._mock_delegate.return_value = value else: self._mock_return_value = value _check_and_set_parent(self, value, None, '()') __return_value_doc = "The value to be returned when the mock is called." return_value = property(__get_return_value, __set_return_value, __return_value_doc) @property def __class__(self): if self._spec_class is None: return type(self) return self._spec_class called = _delegating_property('called') call_count = _delegating_property('call_count') call_args = _delegating_property('call_args') call_args_list = _delegating_property('call_args_list') mock_calls = _delegating_property('mock_calls') def __get_side_effect(self): delegated = self._mock_delegate if delegated is None: return self._mock_side_effect sf = delegated.side_effect if (sf is not None and not callable(sf) and not isinstance(sf, _MockIter) and not _is_exception(sf)): sf = _MockIter(sf) delegated.side_effect = sf return sf def __set_side_effect(self, value): value = _try_iter(value) delegated = self._mock_delegate if delegated is None: self._mock_side_effect = value else: delegated.side_effect = value side_effect = property(__get_side_effect, __set_side_effect) def reset_mock(self, visited=None,*, return_value=False, side_effect=False): "Restore the mock object to its initial state." if visited is None: visited = [] if id(self) in visited: return visited.append(id(self)) self.called = False self.call_args = None self.call_count = 0 self.mock_calls = _CallList() self.call_args_list = _CallList() self.method_calls = _CallList() if return_value: self._mock_return_value = DEFAULT if side_effect: self._mock_side_effect = None for child in self._mock_children.values(): if isinstance(child, _SpecState) or child is _deleted: continue child.reset_mock(visited, return_value=return_value, side_effect=side_effect) ret = self._mock_return_value if _is_instance_mock(ret) and ret is not self: ret.reset_mock(visited) def configure_mock(self, /, **kwargs): """Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)""" for arg, val in sorted(kwargs.items(), # we sort on the number of dots so that # attributes are set before we set attributes on # attributes key=lambda entry: entry[0].count('.')): args = arg.split('.') final = args.pop() obj = self for entry in args: obj = getattr(obj, entry) setattr(obj, final, val) def __getattr__(self, name): if name in {'_mock_methods', '_mock_unsafe'}: raise AttributeError(name) elif self._mock_methods is not None: if name not in self._mock_methods or name in _all_magics: raise AttributeError("Mock object has no attribute %r" % name) elif _is_magic(name): raise AttributeError(name) if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods): if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')): raise AttributeError( f"{name!r} is not a valid assertion. Use a spec " f"for the mock if {name!r} is meant to be an attribute.") with NonCallableMock._lock: result = self._mock_children.get(name) if result is _deleted: raise AttributeError(name) elif result is None: wraps = None if self._mock_wraps is not None: # XXXX should we get the attribute without triggering code # execution? wraps = getattr(self._mock_wraps, name) result = self._get_child_mock( parent=self, name=name, wraps=wraps, _new_name=name, _new_parent=self ) self._mock_children[name] = result elif isinstance(result, _SpecState): try: result = create_autospec( result.spec, result.spec_set, result.instance, result.parent, result.name ) except InvalidSpecError: target_name = self.__dict__['_mock_name'] or self raise InvalidSpecError( f'Cannot autospec attr {name!r} from target ' f'{target_name!r} as it has already been mocked out. ' f'[target={self!r}, attr={result.spec!r}]') self._mock_children[name] = result return result def _extract_mock_name(self): _name_list = [self._mock_new_name] _parent = self._mock_new_parent last = self dot = '.' if _name_list == ['()']: dot = '' while _parent is not None: last = _parent _name_list.append(_parent._mock_new_name + dot) dot = '.' if _parent._mock_new_name == '()': dot = '' _parent = _parent._mock_new_parent _name_list = list(reversed(_name_list)) _first = last._mock_name or 'mock' if len(_name_list) > 1: if _name_list[1] not in ('()', '().'): _first += '.' _name_list[0] = _first return ''.join(_name_list) def __repr__(self): name = self._extract_mock_name() name_string = '' if name not in ('mock', 'mock.'): name_string = ' name=%r' % name spec_string = '' if self._spec_class is not None: spec_string = ' spec=%r' if self._spec_set: spec_string = ' spec_set=%r' spec_string = spec_string % self._spec_class.__name__ return "<%s%s%s id='%s'>" % ( type(self).__name__, name_string, spec_string, id(self) ) def __dir__(self): """Filter the output of `dir(mock)` to only useful members.""" if not FILTER_DIR: return object.__dir__(self) extras = self._mock_methods or [] from_type = dir(type(self)) from_dict = list(self.__dict__) from_child_mocks = [ m_name for m_name, m_value in self._mock_children.items() if m_value is not _deleted] from_type = [e for e in from_type if not e.startswith('_')] from_dict = [e for e in from_dict if not e.startswith('_') or _is_magic(e)] return sorted(set(extras + from_type + from_dict + from_child_mocks)) def __setattr__(self, name, value): if name in _allowed_names: # property setters go through here return object.__setattr__(self, name, value) elif (self._spec_set and self._mock_methods is not None and name not in self._mock_methods and name not in self.__dict__): raise AttributeError("Mock object has no attribute '%s'" % name) elif name in _unsupported_magics: msg = 'Attempting to set unsupported magic method %r.' % name raise AttributeError(msg) elif name in _all_magics: if self._mock_methods is not None and name not in self._mock_methods: raise AttributeError("Mock object has no attribute '%s'" % name) if not _is_instance_mock(value): setattr(type(self), name, _get_method(name, value)) original = value value = lambda *args, **kw: original(self, *args, **kw) else: # only set _new_name and not name so that mock_calls is tracked # but not method calls _check_and_set_parent(self, value, None, name) setattr(type(self), name, value) self._mock_children[name] = value elif name == '__class__': self._spec_class = value return else: if _check_and_set_parent(self, value, name, name): self._mock_children[name] = value if self._mock_sealed and not hasattr(self, name): mock_name = f'{self._extract_mock_name()}.{name}' raise AttributeError(f'Cannot set {mock_name}') return object.__setattr__(self, name, value) def __delattr__(self, name): if name in _all_magics and name in type(self).__dict__: delattr(type(self), name) if name not in self.__dict__: # for magic methods that are still MagicProxy objects and # not set on the instance itself return obj = self._mock_children.get(name, _missing) if name in self.__dict__: _safe_super(NonCallableMock, self).__delattr__(name) elif obj is _deleted: raise AttributeError(name) if obj is not _missing: del self._mock_children[name] self._mock_children[name] = _deleted def _format_mock_call_signature(self, args, kwargs): name = self._mock_name or 'mock' return _format_call_signature(name, args, kwargs) def _format_mock_failure_message(self, args, kwargs, action='call'): message = 'expected %s not found.\nExpected: %s\n Actual: %s' expected_string = self._format_mock_call_signature(args, kwargs) call_args = self.call_args actual_string = self._format_mock_call_signature(*call_args) return message % (action, expected_string, actual_string) def _get_call_signature_from_name(self, name): """ * If call objects are asserted against a method/function like obj.meth1 then there could be no name for the call object to lookup. Hence just return the spec_signature of the method/function being asserted against. * If the name is not empty then remove () and split by '.' to get list of names to iterate through the children until a potential match is found. A child mock is created only during attribute access so if we get a _SpecState then no attributes of the spec were accessed and can be safely exited. """ if not name: return self._spec_signature sig = None names = name.replace('()', '').split('.') children = self._mock_children for name in names: child = children.get(name) if child is None or isinstance(child, _SpecState): break else: # If an autospecced object is attached using attach_mock the # child would be a function with mock object as attribute from # which signature has to be derived. child = _extract_mock(child) children = child._mock_children sig = child._spec_signature return sig def _call_matcher(self, _call): """ Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. """ if isinstance(_call, tuple) and len(_call) > 2: sig = self._get_call_signature_from_name(_call[0]) else: sig = self._spec_signature if sig is not None: if len(_call) == 2: name = '' args, kwargs = _call else: name, args, kwargs = _call try: bound_call = sig.bind(*args, **kwargs) return call(name, bound_call.args, bound_call.kwargs) except TypeError as e: return e.with_traceback(None) else: return _call def assert_not_called(self): """assert that the mock was never called. """ if self.call_count != 0: msg = ("Expected '%s' to not have been called. Called %s times.%s" % (self._mock_name or 'mock', self.call_count, self._calls_repr())) raise AssertionError(msg) def assert_called(self): """assert that the mock was called at least once """ if self.call_count == 0: msg = ("Expected '%s' to have been called." % (self._mock_name or 'mock')) raise AssertionError(msg) def assert_called_once(self): """assert that the mock was called only once. """ if not self.call_count == 1: msg = ("Expected '%s' to have been called once. Called %s times.%s" % (self._mock_name or 'mock', self.call_count, self._calls_repr())) raise AssertionError(msg) def assert_called_with(self, /, *args, **kwargs): """assert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) actual = 'not called.' error_message = ('expected call not found.\nExpected: %s\n Actual: %s' % (expected, actual)) raise AssertionError(error_message) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher(_Call((args, kwargs), two=True)) actual = self._call_matcher(self.call_args) if actual != expected: cause = expected if isinstance(expected, Exception) else None raise AssertionError(_error_message()) from cause def assert_called_once_with(self, /, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times.%s" % (self._mock_name or 'mock', self.call_count, self._calls_repr())) raise AssertionError(msg) return self.assert_called_with(*args, **kwargs) def assert_has_calls(self, calls, any_order=False): """assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.""" expected = [self._call_matcher(c) for c in calls] cause = next((e for e in expected if isinstance(e, Exception)), None) all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) if not any_order: if expected not in all_calls: if cause is None: problem = 'Calls not found.' else: problem = ('Error processing expected calls.\n' 'Errors: {}').format( [e if isinstance(e, Exception) else None for e in expected]) raise AssertionError( f'{problem}\n' f'Expected: {_CallList(calls)}' f'{self._calls_repr(prefix=" Actual").rstrip(".")}' ) from cause return all_calls = list(all_calls) not_found = [] for kall in expected: try: all_calls.remove(kall) except ValueError: not_found.append(kall) if not_found: raise AssertionError( '%r does not contain all of %r in its call list, ' 'found %r instead' % (self._mock_name or 'mock', tuple(not_found), all_calls) ) from cause def assert_any_call(self, /, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" expected = self._call_matcher(_Call((args, kwargs), two=True)) cause = expected if isinstance(expected, Exception) else None actual = [self._call_matcher(c) for c in self.call_args_list] if cause or expected not in _AnyComparer(actual): expected_string = self._format_mock_call_signature(args, kwargs) raise AssertionError( '%s call not found' % expected_string ) from cause def _get_child_mock(self, /, **kw): """Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).""" if self._mock_sealed: attribute = f".{kw['name']}" if "name" in kw else "()" mock_name = self._extract_mock_name() + attribute raise AttributeError(mock_name) _new_name = kw.get("_new_name") if _new_name in self.__dict__['_spec_asyncs']: return AsyncMock(**kw) _type = type(self) if issubclass(_type, MagicMock) and _new_name in _async_method_magics: # Any asynchronous magic becomes an AsyncMock klass = AsyncMock elif issubclass(_type, AsyncMockMixin): if (_new_name in _all_sync_magics or self._mock_methods and _new_name in self._mock_methods): # Any synchronous method on AsyncMock becomes a MagicMock klass = MagicMock else: klass = AsyncMock elif not issubclass(_type, CallableMixin): if issubclass(_type, NonCallableMagicMock): klass = MagicMock elif issubclass(_type, NonCallableMock): klass = Mock else: klass = _type.__mro__[1] return klass(**kw) def _calls_repr(self, prefix="Calls"): """Renders self.mock_calls as a string. Example: "\nCalls: [call(1), call(2)]." If self.mock_calls is empty, an empty string is returned. The output will be truncated if very long. """ if not self.mock_calls: return "" return f"\n{prefix}: {safe_repr(self.mock_calls)}." _MOCK_SIG = inspect.signature(NonCallableMock.__init__) class _AnyComparer(list): """A list which checks if it contains a call which may have an argument of ANY, flipping the components of item and self from their traditional locations so that ANY is guaranteed to be on the left.""" def __contains__(self, item): for _call in self: assert len(item) == len(_call) if all([ expected == actual for expected, actual in zip(item, _call) ]): return True return False def _try_iter(obj): if obj is None: return obj if _is_exception(obj): return obj if _callable(obj): return obj try: return iter(obj) except TypeError: # XXXX backwards compatibility # but this will blow up on first call - so maybe we should fail early? return obj class CallableMixin(Base): def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, **kwargs): self.__dict__['_mock_return_value'] = return_value _safe_super(CallableMixin, self).__init__( spec, wraps, name, spec_set, parent, _spec_state, _new_name, _new_parent, **kwargs ) self.side_effect = side_effect def _mock_check_sig(self, /, *args, **kwargs): # stub method that can be replaced with one with a specific signature pass def __call__(self, /, *args, **kwargs): # can't use self in-case a function / method we are mocking uses self # in the signature self._mock_check_sig(*args, **kwargs) self._increment_mock_call(*args, **kwargs) return self._mock_call(*args, **kwargs) def _mock_call(self, /, *args, **kwargs): return self._execute_mock_call(*args, **kwargs) def _increment_mock_call(self, /, *args, **kwargs): self.called = True self.call_count += 1 # handle call_args # needs to be set here so assertions on call arguments pass before # execution in the case of awaited calls _call = _Call((args, kwargs), two=True) self.call_args = _call self.call_args_list.append(_call) # initial stuff for method_calls: do_method_calls = self._mock_parent is not None method_call_name = self._mock_name # initial stuff for mock_calls: mock_call_name = self._mock_new_name is_a_call = mock_call_name == '()' self.mock_calls.append(_Call(('', args, kwargs))) # follow up the chain of mocks: _new_parent = self._mock_new_parent while _new_parent is not None: # handle method_calls: if do_method_calls: _new_parent.method_calls.append(_Call((method_call_name, args, kwargs))) do_method_calls = _new_parent._mock_parent is not None if do_method_calls: method_call_name = _new_parent._mock_name + '.' + method_call_name # handle mock_calls: this_mock_call = _Call((mock_call_name, args, kwargs)) _new_parent.mock_calls.append(this_mock_call) if _new_parent._mock_new_name: if is_a_call: dot = '' else: dot = '.' is_a_call = _new_parent._mock_new_name == '()' mock_call_name = _new_parent._mock_new_name + dot + mock_call_name # follow the parental chain: _new_parent = _new_parent._mock_new_parent def _execute_mock_call(self, /, *args, **kwargs): # separate from _increment_mock_call so that awaited functions are # executed separately from their call, also AsyncMock overrides this method effect = self.side_effect if effect is not None: if _is_exception(effect): raise effect elif not _callable(effect): result = next(effect) if _is_exception(result): raise result else: result = effect(*args, **kwargs) if result is not DEFAULT: return result if self._mock_return_value is not DEFAULT: return self.return_value if self._mock_delegate and self._mock_delegate.return_value is not DEFAULT: return self.return_value if self._mock_wraps is not None: return self._mock_wraps(*args, **kwargs) return self.return_value class Mock(CallableMixin, NonCallableMock): """ Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an `AttributeError`. If `spec` is an object (rather than a list of strings) then `mock.__class__` returns the class of the spec object. This allows mocks to pass `isinstance` tests. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as `spec_set` will raise an `AttributeError`. * `side_effect`: A function to be called whenever the Mock is called. See the `side_effect` attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns `DEFAULT`, the return value of this function is used as the return value. If `side_effect` is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned. * `return_value`: The value returned when the mock is called. By default this is a new Mock (created on first access). See the `return_value` attribute. * `unsafe`: By default, accessing any attribute whose name starts with *assert*, *assret*, *asert*, *aseert* or *assrt* will raise an AttributeError. Passing `unsafe=True` will allow access to these attributes. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an `AttributeError`). If the mock has an explicit `return_value` set then calls are not passed to the wrapped object and the `return_value` is returned instead. * `name`: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks. Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. """ # _check_spec_arg_typos takes kwargs from commands like patch and checks that # they don't contain common misspellings of arguments related to autospeccing. def _check_spec_arg_typos(kwargs_to_check): typos = ("autospect", "auto_spec", "set_spec") for typo in typos: if typo in kwargs_to_check: raise RuntimeError( f"{typo!r} might be a typo; use unsafe=True if this is intended" ) class _patch(object): attribute_name = None _active_patches = [] def __init__( self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs, *, unsafe=False ): if new_callable is not None: if new is not DEFAULT: raise ValueError( "Cannot use 'new' and 'new_callable' together" ) if autospec is not None: raise ValueError( "Cannot use 'autospec' and 'new_callable' together" ) if not unsafe: _check_spec_arg_typos(kwargs) if _is_instance_mock(spec): raise InvalidSpecError( f'Cannot spec attr {attribute!r} as the spec ' f'has already been mocked out. [spec={spec!r}]') if _is_instance_mock(spec_set): raise InvalidSpecError( f'Cannot spec attr {attribute!r} as the spec_set ' f'target has already been mocked out. [spec_set={spec_set!r}]') self.getter = getter self.attribute = attribute self.new = new self.new_callable = new_callable self.spec = spec self.create = create self.has_local = False self.spec_set = spec_set self.autospec = autospec self.kwargs = kwargs self.additional_patchers = [] def copy(self): patcher = _patch( self.getter, self.attribute, self.new, self.spec, self.create, self.spec_set, self.autospec, self.new_callable, self.kwargs ) patcher.attribute_name = self.attribute_name patcher.additional_patchers = [ p.copy() for p in self.additional_patchers ] return patcher def __call__(self, func): if isinstance(func, type): return self.decorate_class(func) if inspect.iscoroutinefunction(func): return self.decorate_async_callable(func) return self.decorate_callable(func) def decorate_class(self, klass): for attr in dir(klass): if not attr.startswith(patch.TEST_PREFIX): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue patcher = self.copy() setattr(klass, attr, patcher(attr_value)) return klass @contextlib.contextmanager def decoration_helper(self, patched, args, keywargs): extra_args = [] with contextlib.ExitStack() as exit_stack: for patching in patched.patchings: arg = exit_stack.enter_context(patching) if patching.attribute_name is not None: keywargs.update(arg) elif patching.new is DEFAULT: extra_args.append(arg) args += tuple(extra_args) yield (args, keywargs) def decorate_callable(self, func): # NB. Keep the method in sync with decorate_async_callable() if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) def patched(*args, **keywargs): with self.decoration_helper(patched, args, keywargs) as (newargs, newkeywargs): return func(*newargs, **newkeywargs) patched.patchings = [self] return patched def decorate_async_callable(self, func): # NB. Keep the method in sync with decorate_callable() if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) async def patched(*args, **keywargs): with self.decoration_helper(patched, args, keywargs) as (newargs, newkeywargs): return await func(*newargs, **newkeywargs) patched.patchings = [self] return patched def get_original(self): target = self.getter() name = self.attribute original = DEFAULT local = False try: original = target.__dict__[name] except (AttributeError, KeyError): original = getattr(target, name, DEFAULT) else: local = True if name in _builtins and isinstance(target, ModuleType): self.create = True if not self.create and original is DEFAULT: raise AttributeError( "%s does not have the attribute %r" % (target, name) ) return original, local def __enter__(self): """Perform the patch.""" new, spec, spec_set = self.new, self.spec, self.spec_set autospec, kwargs = self.autospec, self.kwargs new_callable = self.new_callable self.target = self.getter() # normalise False to None if spec is False: spec = None if spec_set is False: spec_set = None if autospec is False: autospec = None if spec is not None and autospec is not None: raise TypeError("Can't specify spec and autospec") if ((spec is not None or autospec is not None) and spec_set not in (True, None)): raise TypeError("Can't provide explicit spec_set *and* spec or autospec") original, local = self.get_original() if new is DEFAULT and autospec is None: inherit = False if spec is True: # set spec to the object we are replacing spec = original if spec_set is True: spec_set = original spec = None elif spec is not None: if spec_set is True: spec_set = spec spec = None elif spec_set is True: spec_set = original if spec is not None or spec_set is not None: if original is DEFAULT: raise TypeError("Can't use 'spec' with create=True") if isinstance(original, type): # If we're patching out a class and there is a spec inherit = True if spec is None and _is_async_obj(original): Klass = AsyncMock else: Klass = MagicMock _kwargs = {} if new_callable is not None: Klass = new_callable elif spec is not None or spec_set is not None: this_spec = spec if spec_set is not None: this_spec = spec_set if _is_list(this_spec): not_callable = '__call__' not in this_spec else: not_callable = not callable(this_spec) if _is_async_obj(this_spec): Klass = AsyncMock elif not_callable: Klass = NonCallableMagicMock if spec is not None: _kwargs['spec'] = spec if spec_set is not None: _kwargs['spec_set'] = spec_set # add a name to mocks if (isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) new = Klass(**_kwargs) if inherit and _is_instance_mock(new): # we can only tell if the instance should be callable if the # spec is not a list this_spec = spec if spec_set is not None: this_spec = spec_set if (not _is_list(this_spec) and not _instance_callable(this_spec)): Klass = NonCallableMagicMock _kwargs.pop('name') new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) elif autospec is not None: # spec is ignored, new *must* be default, spec_set is treated # as a boolean. Should we check spec is not None and that spec_set # is a bool? if new is not DEFAULT: raise TypeError( "autospec creates the mock for you. Can't specify " "autospec and new." ) if original is DEFAULT: raise TypeError("Can't use 'autospec' with create=True") spec_set = bool(spec_set) if autospec is True: autospec = original if _is_instance_mock(self.target): raise InvalidSpecError( f'Cannot autospec attr {self.attribute!r} as the patch ' f'target has already been mocked out. ' f'[target={self.target!r}, attr={autospec!r}]') if _is_instance_mock(autospec): target_name = getattr(self.target, '__name__', self.target) raise InvalidSpecError( f'Cannot autospec attr {self.attribute!r} from target ' f'{target_name!r} as it has already been mocked out. ' f'[target={self.target!r}, attr={autospec!r}]') new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) elif kwargs: # can't set keyword args when we aren't creating the mock # XXXX If new is a Mock we could call new.configure_mock(**kwargs) raise TypeError("Can't pass kwargs to a mock we aren't creating") new_attr = new self.temp_original = original self.is_local = local self._exit_stack = contextlib.ExitStack() try: setattr(self.target, self.attribute, new_attr) if self.attribute_name is not None: extra_args = {} if self.new is DEFAULT: extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = self._exit_stack.enter_context(patching) if patching.new is DEFAULT: extra_args.update(arg) return extra_args return new except: if not self.__exit__(*sys.exc_info()): raise def __exit__(self, *exc_info): """Undo the patch.""" if self.is_local and self.temp_original is not DEFAULT: setattr(self.target, self.attribute, self.temp_original) else: delattr(self.target, self.attribute) if not self.create and (not hasattr(self.target, self.attribute) or self.attribute in ('__doc__', '__module__', '__defaults__', '__annotations__', '__kwdefaults__')): # needed for proxy objects like django settings setattr(self.target, self.attribute, self.temp_original) del self.temp_original del self.is_local del self.target exit_stack = self._exit_stack del self._exit_stack return exit_stack.__exit__(*exc_info) def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.append(self) return result def stop(self): """Stop an active patch.""" try: self._active_patches.remove(self) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__(None, None, None) def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError, AttributeError): raise TypeError( f"Need a valid target to patch. You supplied: {target!r}") return partial(pkgutil.resolve_name, target), attribute def _patch_object( target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs ): """ patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ if type(target) is str: raise TypeError( f"{target!r} must be the actual object to be patched, not a str" ) getter = lambda: target return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs, unsafe=unsafe ) def _patch_multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs): """Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ if type(target) is str: getter = partial(pkgutil.resolve_name, target) else: getter = lambda: target if not kwargs: raise ValueError( 'Must supply at least one keyword argument with patch.multiple' ) # need to wrap in a list for python 3, where items is a view items = list(kwargs.items()) attribute, new = items[0] patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) patcher.attribute_name = attribute for attribute, new in items[1:]: this_patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) this_patcher.attribute_name = attribute patcher.additional_patchers.append(this_patcher) return patcher def patch( target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs ): """ `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with an `AsyncMock if the patched object is an async function or a `MagicMock` otherwise. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `AsyncMock` is used for async functions and `MagicMock` for the rest. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. Patch will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `patch` takes arbitrary keyword arguments. These will be passed to `AsyncMock` if the patched object is asynchronous, to `MagicMock` otherwise or to `new_callable` if specified. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. """ getter, attribute = _get_target(target) return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs, unsafe=unsafe ) class _patch_dict(object): """ Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ def __init__(self, in_dict, values=(), clear=False, **kwargs): self.in_dict = in_dict # support any argument supported by dict(...) constructor self.values = dict(values) self.values.update(kwargs) self.clear = clear self._original = None def __call__(self, f): if isinstance(f, type): return self.decorate_class(f) if inspect.iscoroutinefunction(f): return self.decorate_async_callable(f) return self.decorate_callable(f) def decorate_callable(self, f): @wraps(f) def _inner(*args, **kw): self._patch_dict() try: return f(*args, **kw) finally: self._unpatch_dict() return _inner def decorate_async_callable(self, f): @wraps(f) async def _inner(*args, **kw): self._patch_dict() try: return await f(*args, **kw) finally: self._unpatch_dict() return _inner def decorate_class(self, klass): for attr in dir(klass): attr_value = getattr(klass, attr) if (attr.startswith(patch.TEST_PREFIX) and hasattr(attr_value, "__call__")): decorator = _patch_dict(self.in_dict, self.values, self.clear) decorated = decorator(attr_value) setattr(klass, attr, decorated) return klass def __enter__(self): """Patch the dict.""" self._patch_dict() return self.in_dict def _patch_dict(self): values = self.values if isinstance(self.in_dict, str): self.in_dict = pkgutil.resolve_name(self.in_dict) in_dict = self.in_dict clear = self.clear try: original = in_dict.copy() except AttributeError: # dict like object with no copy method # must support iteration over keys original = {} for key in in_dict: original[key] = in_dict[key] self._original = original if clear: _clear_dict(in_dict) try: in_dict.update(values) except AttributeError: # dict like object with no update method for key in values: in_dict[key] = values[key] def _unpatch_dict(self): in_dict = self.in_dict original = self._original _clear_dict(in_dict) try: in_dict.update(original) except AttributeError: for key in original: in_dict[key] = original[key] def __exit__(self, *args): """Unpatch the dict.""" if self._original is not None: self._unpatch_dict() return False def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() _patch._active_patches.append(self) return result def stop(self): """Stop an active patch.""" try: _patch._active_patches.remove(self) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__(None, None, None) def _clear_dict(in_dict): try: in_dict.clear() except AttributeError: keys = list(in_dict) for key in keys: del in_dict[key] def _patch_stopall(): """Stop all active patches. LIFO to unroll nested patches.""" for patch in reversed(_patch._active_patches): patch.stop() patch.object = _patch_object patch.dict = _patch_dict patch.multiple = _patch_multiple patch.stopall = _patch_stopall patch.TEST_PREFIX = 'test' magic_methods = ( "lt le gt ge eq ne " "getitem setitem delitem " "len contains iter " "hash str sizeof " "enter exit " # we added divmod and rdivmod here instead of numerics # because there is no idivmod "divmod rdivmod neg pos abs invert " "complex int float index " "round trunc floor ceil " "bool next " "fspath " "aiter " ) numerics = ( "add sub mul matmul truediv floordiv mod lshift rshift and xor or pow" ) inplace = ' '.join('i%s' % n for n in numerics.split()) right = ' '.join('r%s' % n for n in numerics.split()) # not including __prepare__, __instancecheck__, __subclasscheck__ # (as they are metaclass methods) # __del__ is not supported at all as it causes problems if it exists _non_defaults = { '__get__', '__set__', '__delete__', '__reversed__', '__missing__', '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__', '__getstate__', '__setstate__', '__getformat__', '__repr__', '__dir__', '__subclasses__', '__format__', '__getnewargs_ex__', } def _get_method(name, func): "Turns a callable object (like a mock) into a real function" def method(self, /, *args, **kw): return func(self, *args, **kw) method.__name__ = name return method _magics = { '__%s__' % method for method in ' '.join([magic_methods, numerics, inplace, right]).split() } # Magic methods used for async `with` statements _async_method_magics = {"__aenter__", "__aexit__", "__anext__"} # Magic methods that are only used with async calls but are synchronous functions themselves _sync_async_magics = {"__aiter__"} _async_magics = _async_method_magics | _sync_async_magics _all_sync_magics = _magics | _non_defaults _all_magics = _all_sync_magics | _async_magics _unsupported_magics = { '__getattr__', '__setattr__', '__init__', '__new__', '__prepare__', '__instancecheck__', '__subclasscheck__', '__del__' } _calculate_return_value = { '__hash__': lambda self: object.__hash__(self), '__str__': lambda self: object.__str__(self), '__sizeof__': lambda self: object.__sizeof__(self), '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}", } _return_values = { '__lt__': NotImplemented, '__gt__': NotImplemented, '__le__': NotImplemented, '__ge__': NotImplemented, '__int__': 1, '__contains__': False, '__len__': 0, '__exit__': False, '__complex__': 1j, '__float__': 1.0, '__bool__': True, '__index__': 1, '__aexit__': False, } def _get_eq(self): def __eq__(other): ret_val = self.__eq__._mock_return_value if ret_val is not DEFAULT: return ret_val if self is other: return True return NotImplemented return __eq__ def _get_ne(self): def __ne__(other): if self.__ne__._mock_return_value is not DEFAULT: return DEFAULT if self is other: return False return NotImplemented return __ne__ def _get_iter(self): def __iter__(): ret_val = self.__iter__._mock_return_value if ret_val is DEFAULT: return iter([]) # if ret_val was already an iterator, then calling iter on it should # return the iterator unchanged return iter(ret_val) return __iter__ def _get_async_iter(self): def __aiter__(): ret_val = self.__aiter__._mock_return_value if ret_val is DEFAULT: return _AsyncIterator(iter([])) return _AsyncIterator(iter(ret_val)) return __aiter__ _side_effect_methods = { '__eq__': _get_eq, '__ne__': _get_ne, '__iter__': _get_iter, '__aiter__': _get_async_iter } def _set_return_value(mock, method, name): fixed = _return_values.get(name, DEFAULT) if fixed is not DEFAULT: method.return_value = fixed return return_calculator = _calculate_return_value.get(name) if return_calculator is not None: return_value = return_calculator(mock) method.return_value = return_value return side_effector = _side_effect_methods.get(name) if side_effector is not None: method.side_effect = side_effector(mock) class MagicMixin(Base): def __init__(self, /, *args, **kw): self._mock_set_magics() # make magic work for kwargs in init _safe_super(MagicMixin, self).__init__(*args, **kw) self._mock_set_magics() # fix magic broken by upper level init def _mock_set_magics(self): orig_magics = _magics | _async_method_magics these_magics = orig_magics if getattr(self, "_mock_methods", None) is not None: these_magics = orig_magics.intersection(self._mock_methods) remove_magics = set() remove_magics = orig_magics - these_magics for entry in remove_magics: if entry in type(self).__dict__: # remove unneeded magic methods delattr(self, entry) # don't overwrite existing attributes if called a second time these_magics = these_magics - set(type(self).__dict__) _type = type(self) for entry in these_magics: setattr(_type, entry, MagicProxy(entry, self)) class NonCallableMagicMock(MagicMixin, NonCallableMock): """A version of `MagicMock` that isn't callable.""" def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics() class AsyncMagicMixin(MagicMixin): def __init__(self, /, *args, **kw): self._mock_set_magics() # make magic work for kwargs in init _safe_super(AsyncMagicMixin, self).__init__(*args, **kw) self._mock_set_magics() # fix magic broken by upper level init class MagicMock(MagicMixin, Mock): """ MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. """ def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics() class MagicProxy(Base): def __init__(self, name, parent): self.name = name self.parent = parent def create_mock(self): entry = self.name parent = self.parent m = parent._get_child_mock(name=entry, _new_name=entry, _new_parent=parent) setattr(parent, entry, m) _set_return_value(parent, m, entry) return m def __get__(self, obj, _type=None): return self.create_mock() class AsyncMockMixin(Base): await_count = _delegating_property('await_count') await_args = _delegating_property('await_args') await_args_list = _delegating_property('await_args_list') def __init__(self, /, *args, **kwargs): super().__init__(*args, **kwargs) # iscoroutinefunction() checks _is_coroutine property to say if an # object is a coroutine. Without this check it looks to see if it is a # function/method, which in this case it is not (since it is an # AsyncMock). # It is set through __dict__ because when spec_set is True, this # attribute is likely undefined. self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine self.__dict__['_mock_await_count'] = 0 self.__dict__['_mock_await_args'] = None self.__dict__['_mock_await_args_list'] = _CallList() code_mock = NonCallableMock(spec_set=CodeType) code_mock.co_flags = ( inspect.CO_COROUTINE + inspect.CO_VARARGS + inspect.CO_VARKEYWORDS ) code_mock.co_argcount = 0 code_mock.co_varnames = ('args', 'kwargs') code_mock.co_posonlyargcount = 0 code_mock.co_kwonlyargcount = 0 self.__dict__['__code__'] = code_mock self.__dict__['__name__'] = 'AsyncMock' self.__dict__['__defaults__'] = tuple() self.__dict__['__kwdefaults__'] = {} self.__dict__['__annotations__'] = None async def _execute_mock_call(self, /, *args, **kwargs): # This is nearly just like super(), except for special handling # of coroutines _call = _Call((args, kwargs), two=True) self.await_count += 1 self.await_args = _call self.await_args_list.append(_call) effect = self.side_effect if effect is not None: if _is_exception(effect): raise effect elif not _callable(effect): try: result = next(effect) except StopIteration: # It is impossible to propagate a StopIteration # through coroutines because of PEP 479 raise StopAsyncIteration if _is_exception(result): raise result elif iscoroutinefunction(effect): result = await effect(*args, **kwargs) else: result = effect(*args, **kwargs) if result is not DEFAULT: return result if self._mock_return_value is not DEFAULT: return self.return_value if self._mock_wraps is not None: if iscoroutinefunction(self._mock_wraps): return await self._mock_wraps(*args, **kwargs) return self._mock_wraps(*args, **kwargs) return self.return_value def assert_awaited(self): """ Assert that the mock was awaited at least once. """ if self.await_count == 0: msg = f"Expected {self._mock_name or 'mock'} to have been awaited." raise AssertionError(msg) def assert_awaited_once(self): """ Assert that the mock was awaited exactly once. """ if not self.await_count == 1: msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." f" Awaited {self.await_count} times.") raise AssertionError(msg) def assert_awaited_with(self, /, *args, **kwargs): """ Assert that the last await was with the specified arguments. """ if self.await_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError(f'Expected await: {expected}\nNot awaited') def _error_message(): msg = self._format_mock_failure_message(args, kwargs, action='await') return msg expected = self._call_matcher(_Call((args, kwargs), two=True)) actual = self._call_matcher(self.await_args) if actual != expected: cause = expected if isinstance(expected, Exception) else None raise AssertionError(_error_message()) from cause def assert_awaited_once_with(self, /, *args, **kwargs): """ Assert that the mock was awaited exactly once and with the specified arguments. """ if not self.await_count == 1: msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." f" Awaited {self.await_count} times.") raise AssertionError(msg) return self.assert_awaited_with(*args, **kwargs) def assert_any_await(self, /, *args, **kwargs): """ Assert the mock has ever been awaited with the specified arguments. """ expected = self._call_matcher(_Call((args, kwargs), two=True)) cause = expected if isinstance(expected, Exception) else None actual = [self._call_matcher(c) for c in self.await_args_list] if cause or expected not in _AnyComparer(actual): expected_string = self._format_mock_call_signature(args, kwargs) raise AssertionError( '%s await not found' % expected_string ) from cause def assert_has_awaits(self, calls, any_order=False): """ Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be sequential. There can be extra calls before or after the specified awaits. If `any_order` is True then the awaits can be in any order, but they must all appear in :attr:`await_args_list`. """ expected = [self._call_matcher(c) for c in calls] cause = next((e for e in expected if isinstance(e, Exception)), None) all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list) if not any_order: if expected not in all_awaits: if cause is None: problem = 'Awaits not found.' else: problem = ('Error processing expected awaits.\n' 'Errors: {}').format( [e if isinstance(e, Exception) else None for e in expected]) raise AssertionError( f'{problem}\n' f'Expected: {_CallList(calls)}\n' f'Actual: {self.await_args_list}' ) from cause return all_awaits = list(all_awaits) not_found = [] for kall in expected: try: all_awaits.remove(kall) except ValueError: not_found.append(kall) if not_found: raise AssertionError( '%r not all found in await list' % (tuple(not_found),) ) from cause def assert_not_awaited(self): """ Assert that the mock was never awaited. """ if self.await_count != 0: msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited." f" Awaited {self.await_count} times.") raise AssertionError(msg) def reset_mock(self, /, *args, **kwargs): """ See :func:`.Mock.reset_mock()` """ super().reset_mock(*args, **kwargs) self.await_count = 0 self.await_args = None self.await_args_list = _CallList() class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): """ Enhance :class:`Mock` with features allowing to mock an async function. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable: >>> mock = AsyncMock() >>> iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) True The result of ``mock()`` is an async function which will have the outcome of ``side_effect`` or ``return_value``: - if ``side_effect`` is a function, the async function will return the result of that function, - if ``side_effect`` is an exception, the async function will raise the exception, - if ``side_effect`` is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, ``StopIteration`` is raised immediately, - if ``side_effect`` is not defined, the async function will return the value defined by ``return_value``, hence, by default, the async function returns a new :class:`AsyncMock` object. If the outcome of ``side_effect`` or ``return_value`` is an async function, the mock async function obtained when the mock object is called will be this async function itself (and not an async function returning an async function). The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`Mock` object behavior is the same as with an :class:`.Mock` object: the wrapped object may have methods defined as async function functions. Based on Martin Richard's asynctest project. """ class _ANY(object): "A helper object that compares equal to everything." def __eq__(self, other): return True def __ne__(self, other): return False def __repr__(self): return '' ANY = _ANY() def _format_call_signature(name, args, kwargs): message = '%s(%%s)' % name formatted_args = '' args_string = ', '.join([repr(arg) for arg in args]) kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in kwargs.items() ]) if args_string: formatted_args = args_string if kwargs_string: if formatted_args: formatted_args += ', ' formatted_args += kwargs_string return message % formatted_args class _Call(tuple): """ A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to a tuple without those values. This makes comparisons less verbose:: _Call(('name', (), {})) == ('name',) _Call(('name', (1,), {})) == ('name', (1,)) _Call(((), {'a': 'b'})) == ({'a': 'b'},) The `_Call` object provides a useful shortcut for comparing with call:: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) If the _Call has no name then it will match any name. """ def __new__(cls, value=(), name='', parent=None, two=False, from_kall=True): args = () kwargs = {} _len = len(value) if _len == 3: name, args, kwargs = value elif _len == 2: first, second = value if isinstance(first, str): name = first if isinstance(second, tuple): args = second else: kwargs = second else: args, kwargs = first, second elif _len == 1: value, = value if isinstance(value, str): name = value elif isinstance(value, tuple): args = value else: kwargs = value if two: return tuple.__new__(cls, (args, kwargs)) return tuple.__new__(cls, (name, args, kwargs)) def __init__(self, value=(), name=None, parent=None, two=False, from_kall=True): self._mock_name = name self._mock_parent = parent self._mock_from_kall = from_kall def __eq__(self, other): try: len_other = len(other) except TypeError: return NotImplemented self_name = '' if len(self) == 2: self_args, self_kwargs = self else: self_name, self_args, self_kwargs = self if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None) and self._mock_parent != other._mock_parent): return False other_name = '' if len_other == 0: other_args, other_kwargs = (), {} elif len_other == 3: other_name, other_args, other_kwargs = other elif len_other == 1: value, = other if isinstance(value, tuple): other_args = value other_kwargs = {} elif isinstance(value, str): other_name = value other_args, other_kwargs = (), {} else: other_args = () other_kwargs = value elif len_other == 2: # could be (name, args) or (name, kwargs) or (args, kwargs) first, second = other if isinstance(first, str): other_name = first if isinstance(second, tuple): other_args, other_kwargs = second, {} else: other_args, other_kwargs = (), second else: other_args, other_kwargs = first, second else: return False if self_name and other_name != self_name: return False # this order is important for ANY to work! return (other_args, other_kwargs) == (self_args, self_kwargs) __ne__ = object.__ne__ def __call__(self, /, *args, **kwargs): if self._mock_name is None: return _Call(('', args, kwargs), name='()') name = self._mock_name + '()' return _Call((self._mock_name, args, kwargs), name=name, parent=self) def __getattr__(self, attr): if self._mock_name is None: return _Call(name=attr, from_kall=False) name = '%s.%s' % (self._mock_name, attr) return _Call(name=name, parent=self, from_kall=False) def __getattribute__(self, attr): if attr in tuple.__dict__: raise AttributeError return tuple.__getattribute__(self, attr) def _get_call_arguments(self): if len(self) == 2: args, kwargs = self else: name, args, kwargs = self return args, kwargs @property def args(self): return self._get_call_arguments()[0] @property def kwargs(self): return self._get_call_arguments()[1] def __repr__(self): if not self._mock_from_kall: name = self._mock_name or 'call' if name.startswith('()'): name = 'call%s' % name return name if len(self) == 2: name = 'call' args, kwargs = self else: name, args, kwargs = self if not name: name = 'call' elif not name.startswith('()'): name = 'call.%s' % name else: name = 'call%s' % name return _format_call_signature(name, args, kwargs) def call_list(self): """For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.""" vals = [] thing = self while thing is not None: if thing._mock_from_kall: vals.append(thing) thing = thing._mock_parent return _CallList(reversed(vals)) call = _Call(from_kall=False) def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, *, unsafe=False, **kwargs): """Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.""" if _is_list(spec): # can't pass a list instance to the mock constructor as it will be # interpreted as a list of strings spec = type(spec) is_type = isinstance(spec, type) if _is_instance_mock(spec): raise InvalidSpecError(f'Cannot autospec a Mock object. ' f'[object={spec!r}]') is_async_func = _is_async_func(spec) _kwargs = {'spec': spec} if spec_set: _kwargs = {'spec_set': spec} elif spec is None: # None we mock with a normal mock without a spec _kwargs = {} if _kwargs and instance: _kwargs['_spec_as_instance'] = True if not unsafe: _check_spec_arg_typos(kwargs) _kwargs.update(kwargs) Klass = MagicMock if inspect.isdatadescriptor(spec): # descriptors don't have a spec # because we don't know what type they return _kwargs = {} elif is_async_func: if instance: raise RuntimeError("Instance can not be True when create_autospec " "is mocking an async function") Klass = AsyncMock elif not _callable(spec): Klass = NonCallableMagicMock elif is_type and instance and not _instance_callable(spec): Klass = NonCallableMagicMock _name = _kwargs.pop('name', _name) _new_name = _name if _parent is None: # for a top level object no _new_name should be set _new_name = '' mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, name=_name, **_kwargs) if isinstance(spec, FunctionTypes): # should only happen at the top level because we don't # recurse for functions mock = _set_signature(mock, spec) if is_async_func: _setup_async_mock(mock) else: _check_signature(spec, mock, is_type, instance) if _parent is not None and not instance: _parent._mock_children[_name] = mock wrapped = kwargs.get('wraps') if is_type and not instance and 'return_value' not in kwargs: mock.return_value = create_autospec(spec, spec_set, instance=True, _name='()', _parent=mock, wraps=wrapped) for entry in dir(spec): if _is_magic(entry): # MagicMock already does the useful magic methods for us continue # XXXX do we need a better way of getting attributes without # triggering code execution (?) Probably not - we need the actual # object to mock it so we would rather trigger a property than mock # the property descriptor. Likewise we want to mock out dynamically # provided attributes. # XXXX what about attributes that raise exceptions other than # AttributeError on being fetched? # we could be resilient against it, or catch and propagate the # exception when the attribute is fetched from the mock try: original = getattr(spec, entry) except AttributeError: continue kwargs = {'spec': original} # Wrap child attributes also. if wrapped and hasattr(wrapped, entry): kwargs.update(wraps=original) if spec_set: kwargs = {'spec_set': original} if not isinstance(original, FunctionTypes): new = _SpecState(original, spec_set, mock, entry, instance) mock._mock_children[entry] = new else: parent = mock if isinstance(spec, FunctionTypes): parent = mock.mock skipfirst = _must_skip(spec, entry, is_type) kwargs['_eat_self'] = skipfirst if iscoroutinefunction(original): child_klass = AsyncMock else: child_klass = MagicMock new = child_klass(parent=parent, name=entry, _new_name=entry, _new_parent=parent, **kwargs) mock._mock_children[entry] = new _check_signature(original, new, skipfirst=skipfirst) # so functions created with _set_signature become instance attributes, # *plus* their underlying mock exists in _mock_children of the parent # mock. Adding to _mock_children may be unnecessary where we are also # setting as an instance attribute? if isinstance(new, FunctionTypes): setattr(mock, entry, new) return mock def _must_skip(spec, entry, is_type): """ Return whether we should skip the first argument on spec's `entry` attribute. """ if not isinstance(spec, type): if entry in getattr(spec, '__dict__', {}): # instance attribute - shouldn't skip return False spec = spec.__class__ for klass in spec.__mro__: result = klass.__dict__.get(entry, DEFAULT) if result is DEFAULT: continue if isinstance(result, (staticmethod, classmethod)): return False elif isinstance(result, FunctionTypes): # Normal method => skip if looked up on type # (if looked up on instance, self is already skipped) return is_type else: return False # function is a dynamically provided attribute return is_type class _SpecState(object): def __init__(self, spec, spec_set=False, parent=None, name=None, ids=None, instance=False): self.spec = spec self.ids = ids self.spec_set = spec_set self.parent = parent self.instance = instance self.name = name FunctionTypes = ( # python function type(create_autospec), # instance method type(ANY.__eq__), ) file_spec = None open_spec = None def _to_stream(read_data): if isinstance(read_data, bytes): return io.BytesIO(read_data) else: return io.StringIO(read_data) def mock_open(mock=None, read_data=''): """ A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. """ _read_data = _to_stream(read_data) _state = [_read_data, None] def _readlines_side_effect(*args, **kwargs): if handle.readlines.return_value is not None: return handle.readlines.return_value return _state[0].readlines(*args, **kwargs) def _read_side_effect(*args, **kwargs): if handle.read.return_value is not None: return handle.read.return_value return _state[0].read(*args, **kwargs) def _readline_side_effect(*args, **kwargs): yield from _iter_side_effect() while True: yield _state[0].readline(*args, **kwargs) def _iter_side_effect(): if handle.readline.return_value is not None: while True: yield handle.readline.return_value for line in _state[0]: yield line def _next_side_effect(): if handle.readline.return_value is not None: return handle.readline.return_value return next(_state[0]) global file_spec if file_spec is None: import _io file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) global open_spec if open_spec is None: import _io open_spec = list(set(dir(_io.open))) if mock is None: mock = MagicMock(name='open', spec=open_spec) handle = MagicMock(spec=file_spec) handle.__enter__.return_value = handle handle.write.return_value = None handle.read.return_value = None handle.readline.return_value = None handle.readlines.return_value = None handle.read.side_effect = _read_side_effect _state[1] = _readline_side_effect() handle.readline.side_effect = _state[1] handle.readlines.side_effect = _readlines_side_effect handle.__iter__.side_effect = _iter_side_effect handle.__next__.side_effect = _next_side_effect def reset_data(*args, **kwargs): _state[0] = _to_stream(read_data) if handle.readline.side_effect == _state[1]: # Only reset the side effect if the user hasn't overridden it. _state[1] = _readline_side_effect() handle.readline.side_effect = _state[1] return DEFAULT mock.side_effect = reset_data mock.return_value = handle return mock class PropertyMock(Mock): """ A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. Fetching a `PropertyMock` instance from an object calls the mock, with no args. Setting it calls the mock with the value being set. """ def _get_child_mock(self, /, **kwargs): return MagicMock(**kwargs) def __get__(self, obj, obj_type=None): return self() def __set__(self, obj, val): self(val) def seal(mock): """Disable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. The operation recursively seals the mock passed in, meaning that the mock itself, any mocks generated by accessing one of its attributes, and all assigned mocks without a name or spec will be sealed. """ mock._mock_sealed = True for attr in dir(mock): try: m = getattr(mock, attr) except AttributeError: continue if not isinstance(m, NonCallableMock): continue if isinstance(m._mock_children.get(attr), _SpecState): continue if m._mock_new_parent is mock: seal(m) class _AsyncIterator: """ Wraps an iterator in an asynchronous iterator. """ def __init__(self, iterator): self.iterator = iterator code_mock = NonCallableMock(spec_set=CodeType) code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE self.__dict__['__code__'] = code_mock async def __anext__(self): try: return next(self.iterator) except StopIteration: pass raise StopAsyncIteration case.py000064400000162207151030032340006030 0ustar00"""Test case implementation""" import sys import functools import difflib import pprint import re import warnings import collections import contextlib import traceback import types from . import result from .util import (strclass, safe_repr, _count_diff_all_purpose, _count_diff_hashable, _common_shorten_repr) __unittest = True _subtest_msg_sentinel = object() DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') class SkipTest(Exception): """ Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. """ class _ShouldStop(Exception): """ The test should stop. """ class _UnexpectedSuccess(Exception): """ The test was supposed to fail, but it didn't! """ class _Outcome(object): def __init__(self, result=None): self.expecting_failure = False self.result = result self.result_supports_subtests = hasattr(result, "addSubTest") self.success = True self.expectedFailure = None @contextlib.contextmanager def testPartExecutor(self, test_case, subTest=False): old_success = self.success self.success = True try: yield except KeyboardInterrupt: raise except SkipTest as e: self.success = False _addSkip(self.result, test_case, str(e)) except _ShouldStop: pass except: exc_info = sys.exc_info() if self.expecting_failure: self.expectedFailure = exc_info else: self.success = False if subTest: self.result.addSubTest(test_case.test_case, test_case, exc_info) else: _addError(self.result, test_case, exc_info) # explicitly break a reference cycle: # exc_info -> frame -> exc_info exc_info = None else: if subTest and self.success: self.result.addSubTest(test_case.test_case, test_case, None) finally: self.success = self.success and old_success def _addSkip(result, test_case, reason): addSkip = getattr(result, 'addSkip', None) if addSkip is not None: addSkip(test_case, reason) else: warnings.warn("TestResult has no addSkip method, skips not reported", RuntimeWarning, 2) result.addSuccess(test_case) def _addError(result, test, exc_info): if result is not None and exc_info is not None: if issubclass(exc_info[0], test.failureException): result.addFailure(test, exc_info) else: result.addError(test, exc_info) def _id(obj): return obj def _enter_context(cm, addcleanup): # We look up the special methods on the type to match the with # statement. cls = type(cm) try: enter = cls.__enter__ exit = cls.__exit__ except AttributeError: raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does " f"not support the context manager protocol") from None result = enter(cm) addcleanup(exit, cm, None, None, None) return result _module_cleanups = [] def addModuleCleanup(function, /, *args, **kwargs): """Same as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule).""" _module_cleanups.append((function, args, kwargs)) def enterModuleContext(cm): """Same as enterContext, but module-wide.""" return _enter_context(cm, addModuleCleanup) def doModuleCleanups(): """Execute all module cleanup functions. Normally called for you after tearDownModule.""" exceptions = [] while _module_cleanups: function, args, kwargs = _module_cleanups.pop() try: function(*args, **kwargs) except Exception as exc: exceptions.append(exc) if exceptions: # Swallows all but first exception. If a multi-exception handler # gets written we should use that here instead. raise exceptions[0] def skip(reason): """ Unconditionally skip a test. """ def decorator(test_item): if not isinstance(test_item, type): @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) test_item = skip_wrapper test_item.__unittest_skip__ = True test_item.__unittest_skip_why__ = reason return test_item if isinstance(reason, types.FunctionType): test_item = reason reason = '' return decorator(test_item) return decorator def skipIf(condition, reason): """ Skip a test if the condition is true. """ if condition: return skip(reason) return _id def skipUnless(condition, reason): """ Skip a test unless the condition is true. """ if not condition: return skip(reason) return _id def expectedFailure(test_item): test_item.__unittest_expecting_failure__ = True return test_item def _is_subtype(expected, basetype): if isinstance(expected, tuple): return all(_is_subtype(e, basetype) for e in expected) return isinstance(expected, type) and issubclass(expected, basetype) class _BaseTestCaseContext: def __init__(self, test_case): self.test_case = test_case def _raiseFailure(self, standardMsg): msg = self.test_case._formatMessage(self.msg, standardMsg) raise self.test_case.failureException(msg) class _AssertRaisesBaseContext(_BaseTestCaseContext): def __init__(self, expected, test_case, expected_regex=None): _BaseTestCaseContext.__init__(self, test_case) self.expected = expected self.test_case = test_case if expected_regex is not None: expected_regex = re.compile(expected_regex) self.expected_regex = expected_regex self.obj_name = None self.msg = None def handle(self, name, args, kwargs): """ If args is empty, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If args is not empty, call a callable passing positional and keyword arguments. """ try: if not _is_subtype(self.expected, self._base_type): raise TypeError('%s() arg 1 must be %s' % (name, self._base_type_str)) if not args: self.msg = kwargs.pop('msg', None) if kwargs: raise TypeError('%r is an invalid keyword argument for ' 'this function' % (next(iter(kwargs)),)) return self callable_obj, *args = args try: self.obj_name = callable_obj.__name__ except AttributeError: self.obj_name = str(callable_obj) with self: callable_obj(*args, **kwargs) finally: # bpo-23890: manually break a reference cycle self = None class _AssertRaisesContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertRaises* methods.""" _base_type = BaseException _base_type_str = 'an exception type or tuple of exception types' def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) if self.obj_name: self._raiseFailure("{} not raised by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not raised".format(exc_name)) else: traceback.clear_frames(tb) if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False # store exception, without traceback, for later retrieval self.exception = exc_value.with_traceback(None) if self.expected_regex is None: return True expected_regex = self.expected_regex if not expected_regex.search(str(exc_value)): self._raiseFailure('"{}" does not match "{}"'.format( expected_regex.pattern, str(exc_value))) return True __class_getitem__ = classmethod(types.GenericAlias) class _AssertWarnsContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertWarns* methods.""" _base_type = Warning _base_type_str = 'a warning type or tuple of warning types' def __enter__(self): # The __warningregistry__'s need to be in a pristine state for tests # to work properly. for v in list(sys.modules.values()): if getattr(v, '__warningregistry__', None): v.__warningregistry__ = {} self.warnings_manager = warnings.catch_warnings(record=True) self.warnings = self.warnings_manager.__enter__() warnings.simplefilter("always", self.expected) return self def __exit__(self, exc_type, exc_value, tb): self.warnings_manager.__exit__(exc_type, exc_value, tb) if exc_type is not None: # let unexpected exceptions pass through return try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) first_matching = None for m in self.warnings: w = m.message if not isinstance(w, self.expected): continue if first_matching is None: first_matching = w if (self.expected_regex is not None and not self.expected_regex.search(str(w))): continue # store warning for later retrieval self.warning = w self.filename = m.filename self.lineno = m.lineno return # Now we simply try to choose a helpful failure message if first_matching is not None: self._raiseFailure('"{}" does not match "{}"'.format( self.expected_regex.pattern, str(first_matching))) if self.obj_name: self._raiseFailure("{} not triggered by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not triggered".format(exc_name)) class _OrderedChainMap(collections.ChainMap): def __iter__(self): seen = set() for mapping in self.maps: for k in mapping: if k not in seen: seen.add(k) yield k class TestCase(object): """A class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. """ failureException = AssertionError longMessage = True maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 def __init_subclass__(cls, *args, **kwargs): # Attribute used by TestSuite for classSetUp cls._classSetupFailed = False cls._class_cleanups = [] super().__init_subclass__(*args, **kwargs) def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ self._testMethodName = methodName self._outcome = None self._testMethodDoc = 'No test' try: testMethod = getattr(self, methodName) except AttributeError: if methodName != 'runTest': # we allow instantiation with no explicit method name # but not an *incorrect* or missing method name raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) else: self._testMethodDoc = testMethod.__doc__ self._cleanups = [] self._subtest = None # Map types to custom assertEqual functions that will compare # instances of said type in more detail to generate a more useful # error message. self._type_equality_funcs = {} self.addTypeEqualityFunc(dict, 'assertDictEqual') self.addTypeEqualityFunc(list, 'assertListEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') self.addTypeEqualityFunc(str, 'assertMultiLineEqual') def addTypeEqualityFunc(self, typeobj, function): """Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. """ self._type_equality_funcs[typeobj] = function def addCleanup(self, function, /, *args, **kwargs): """Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).""" self._cleanups.append((function, args, kwargs)) def enterContext(self, cm): """Enters the supplied context manager. If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method. """ return _enter_context(cm, self.addCleanup) @classmethod def addClassCleanup(cls, function, /, *args, **kwargs): """Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).""" cls._class_cleanups.append((function, args, kwargs)) @classmethod def enterClassContext(cls, cm): """Same as enterContext, but class-wide.""" return _enter_context(cm, cls.addClassCleanup) def setUp(self): "Hook method for setting up the test fixture before exercising it." pass def tearDown(self): "Hook method for deconstructing the test fixture after testing it." pass @classmethod def setUpClass(cls): "Hook method for setting up class fixture before running tests in the class." @classmethod def tearDownClass(cls): "Hook method for deconstructing the class fixture after running all tests in the class." def countTestCases(self): return 1 def defaultTestResult(self): return result.TestResult() def shortDescription(self): """Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method's docstring. """ doc = self._testMethodDoc return doc.strip().split("\n")[0].strip() if doc else None def id(self): return "%s.%s" % (strclass(self.__class__), self._testMethodName) def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self._testMethodName == other._testMethodName def __hash__(self): return hash((type(self), self._testMethodName)) def __str__(self): return "%s (%s.%s)" % (self._testMethodName, strclass(self.__class__), self._testMethodName) def __repr__(self): return "<%s testMethod=%s>" % \ (strclass(self.__class__), self._testMethodName) @contextlib.contextmanager def subTest(self, msg=_subtest_msg_sentinel, **params): """Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed. """ if self._outcome is None or not self._outcome.result_supports_subtests: yield return parent = self._subtest if parent is None: params_map = _OrderedChainMap(params) else: params_map = parent.params.new_child(params) self._subtest = _SubTest(self, msg, params_map) try: with self._outcome.testPartExecutor(self._subtest, subTest=True): yield if not self._outcome.success: result = self._outcome.result if result is not None and result.failfast: raise _ShouldStop elif self._outcome.expectedFailure: # If the test is expecting a failure, we really want to # stop now and register the expected failure. raise _ShouldStop finally: self._subtest = parent def _addExpectedFailure(self, result, exc_info): try: addExpectedFailure = result.addExpectedFailure except AttributeError: warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", RuntimeWarning) result.addSuccess(self) else: addExpectedFailure(self, exc_info) def _addUnexpectedSuccess(self, result): try: addUnexpectedSuccess = result.addUnexpectedSuccess except AttributeError: warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure", RuntimeWarning) # We need to pass an actual exception and traceback to addFailure, # otherwise the legacy result can choke. try: raise _UnexpectedSuccess from None except _UnexpectedSuccess: result.addFailure(self, sys.exc_info()) else: addUnexpectedSuccess(self) def _callSetUp(self): self.setUp() def _callTestMethod(self, method): if method() is not None: warnings.warn(f'It is deprecated to return a value that is not None from a ' f'test case ({method})', DeprecationWarning, stacklevel=3) def _callTearDown(self): self.tearDown() def _callCleanup(self, function, /, *args, **kwargs): function(*args, **kwargs) def run(self, result=None): if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) stopTestRun = getattr(result, 'stopTestRun', None) if startTestRun is not None: startTestRun() else: stopTestRun = None result.startTest(self) try: testMethod = getattr(self, self._testMethodName) if (getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) _addSkip(result, self, skip_why) return result expecting_failure = ( getattr(self, "__unittest_expecting_failure__", False) or getattr(testMethod, "__unittest_expecting_failure__", False) ) outcome = _Outcome(result) try: self._outcome = outcome with outcome.testPartExecutor(self): self._callSetUp() if outcome.success: outcome.expecting_failure = expecting_failure with outcome.testPartExecutor(self): self._callTestMethod(testMethod) outcome.expecting_failure = False with outcome.testPartExecutor(self): self._callTearDown() self.doCleanups() if outcome.success: if expecting_failure: if outcome.expectedFailure: self._addExpectedFailure(result, outcome.expectedFailure) else: self._addUnexpectedSuccess(result) else: result.addSuccess(self) return result finally: # explicitly break reference cycle: # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure outcome.expectedFailure = None outcome = None # clear the outcome, no more needed self._outcome = None finally: result.stopTest(self) if stopTestRun is not None: stopTestRun() def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" outcome = self._outcome or _Outcome() while self._cleanups: function, args, kwargs = self._cleanups.pop() with outcome.testPartExecutor(self): self._callCleanup(function, *args, **kwargs) # return this for backwards compatibility # even though we no longer use it internally return outcome.success @classmethod def doClassCleanups(cls): """Execute all class cleanup functions. Normally called for you after tearDownClass.""" cls.tearDown_exceptions = [] while cls._class_cleanups: function, args, kwargs = cls._class_cleanups.pop() try: function(*args, **kwargs) except Exception: cls.tearDown_exceptions.append(sys.exc_info()) def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the test without collecting errors in a TestResult""" testMethod = getattr(self, self._testMethodName) if (getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) raise SkipTest(skip_why) self._callSetUp() self._callTestMethod(testMethod) self._callTearDown() while self._cleanups: function, args, kwargs = self._cleanups.pop() self._callCleanup(function, *args, **kwargs) def skipTest(self, reason): """Skip this test.""" raise SkipTest(reason) def fail(self, msg=None): """Fail immediately, with the given message.""" raise self.failureException(msg) def assertFalse(self, expr, msg=None): """Check that the expression is false.""" if expr: msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) raise self.failureException(msg) def assertTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) raise self.failureException(msg) def _formatMessage(self, msg, standardMsg): """Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus ' : ' and the explicit message """ if not self.longMessage: return msg or standardMsg if msg is None: return standardMsg try: # don't switch to '{}' formatting in Python 2.X # it changes the way unicode input is handled return '%s : %s' % (standardMsg, msg) except UnicodeDecodeError: return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg)) def assertRaises(self, expected_exception, *args, **kwargs): """Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertRaises(SomeException): do_something() An optional keyword argument 'msg' can be provided when assertRaises is used as a context object. The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) """ context = _AssertRaisesContext(expected_exception, self) try: return context.handle('assertRaises', args, kwargs) finally: # bpo-23890: manually break a reference cycle context = None def assertWarns(self, expected_warning, *args, **kwargs): """Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) """ context = _AssertWarnsContext(expected_warning, self) return context.handle('assertWarns', args, kwargs) def assertLogs(self, logger=None, level=None): """Fail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. This method must be used as a context manager, and will yield a recording object with two attributes: `output` and `records`. At the end of the context manager, the `output` attribute will be a list of the matching formatted log messages and the `records` attribute will be a list of the corresponding LogRecord objects. Example:: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) """ # Lazy import to avoid importing logging if it is not needed. from ._log import _AssertLogsContext return _AssertLogsContext(self, logger, level, no_logs=False) def assertNoLogs(self, logger=None, level=None): """ Fail unless no log messages of level *level* or higher are emitted on *logger_name* or its children. This method must be used as a context manager. """ from ._log import _AssertLogsContext return _AssertLogsContext(self, logger, level, no_logs=True) def _getAssertEqualityFunc(self, first, second): """Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. """ # # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) # and vice versa. I opted for the conservative approach in case # subclasses are not intended to be compared in detail to their super # class instances using a type equality func. This means testing # subtypes won't automagically use the detailed comparison. Callers # should use their type specific assertSpamEqual method to compare # subclasses if the detailed comparison is desired and appropriate. # See the discussion in http://bugs.python.org/issue2578. # if type(first) is type(second): asserter = self._type_equality_funcs.get(type(first)) if asserter is not None: if isinstance(asserter, str): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: standardMsg = '%s != %s' % _common_shorten_repr(first, second) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg) def assertNotEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '!=' operator. """ if not first != second: msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), safe_repr(second))) raise self.failureException(msg) def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). If the two objects compare equal then they will automatically compare almost equal. """ if first == second: # shortcut return if delta is not None and places is not None: raise TypeError("specify delta or places not both") diff = abs(first - second) if delta is not None: if diff <= delta: return standardMsg = '%s != %s within %s delta (%s difference)' % ( safe_repr(first), safe_repr(second), safe_repr(delta), safe_repr(diff)) else: if places is None: places = 7 if round(diff, places) == 0: return standardMsg = '%s != %s within %r places (%s difference)' % ( safe_repr(first), safe_repr(second), places, safe_repr(diff)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). Objects that are equal automatically fail. """ if delta is not None and places is not None: raise TypeError("specify delta or places not both") diff = abs(first - second) if delta is not None: if not (first == second) and diff > delta: return standardMsg = '%s == %s within %s delta (%s difference)' % ( safe_repr(first), safe_repr(second), safe_repr(delta), safe_repr(diff)) else: if places is None: places = 7 if not (first == second) and round(diff, places) != 0: return standardMsg = '%s == %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. """ if seq_type is not None: seq_type_name = seq_type.__name__ if not isinstance(seq1, seq_type): raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))) if not isinstance(seq2, seq_type): raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2))) else: seq_type_name = "sequence" differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = 'First %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = 'Second %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: if seq1 == seq2: return differing = '%ss differ: %s != %s\n' % ( (seq_type_name.capitalize(),) + _common_shorten_repr(seq1, seq2)) for i in range(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if item1 != item2: differing += ('\nFirst differing element %d:\n%s\n%s\n' % ((i,) + _common_shorten_repr(item1, item2))) break else: if (len1 == len2 and seq_type is None and type(seq1) != type(seq2)): # The sequences are the same, but have differing types. return if len1 > len2: differing += ('\nFirst %s contains %d additional ' 'elements.\n' % (seq_type_name, len1 - len2)) try: differing += ('First extra element %d:\n%s\n' % (len2, safe_repr(seq1[len2]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of first %s\n' % (len2, seq_type_name)) elif len1 < len2: differing += ('\nSecond %s contains %d additional ' 'elements.\n' % (seq_type_name, len2 - len1)) try: differing += ('First extra element %d:\n%s\n' % (len1, safe_repr(seq2[len1]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = '\n' + '\n'.join( difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def _truncateMessage(self, message, diff): max_diff = self.maxDiff if max_diff is None or len(diff) <= max_diff: return message + diff return message + (DIFF_OMITTED % len(diff)) def assertListEqual(self, list1, list2, msg=None): """A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(list1, list2, msg, seq_type=list) def assertTupleEqual(self, tuple1, tuple2, msg=None): """A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) def assertSetEqual(self, set1, set2, msg=None): """A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). """ try: difference1 = set1.difference(set2) except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as e: self.fail('second argument does not support set difference: %s' % e) if not (difference1 or difference2): return lines = [] if difference1: lines.append('Items in the first set but not the second:') for item in difference1: lines.append(repr(item)) if difference2: lines.append('Items in the second set but not the first:') for item in difference2: lines.append(repr(item)) standardMsg = '\n'.join(lines) self.fail(self._formatMessage(msg, standardMsg)) def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b), but with a nicer default message.""" if member not in container: standardMsg = '%s not found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIn(self, member, container, msg=None): """Just like self.assertTrue(a not in b), but with a nicer default message.""" if member in container: standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertIs(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is b), but with a nicer default message.""" if expr1 is not expr2: standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNot(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is not b), but with a nicer default message.""" if expr1 is expr2: standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) self.fail(self._formatMessage(msg, standardMsg)) def assertDictEqual(self, d1, d2, msg=None): self.assertIsInstance(d1, dict, 'First argument is not a dictionary') self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') if d1 != d2: standardMsg = '%s != %s' % _common_shorten_repr(d1, d2) diff = ('\n' + '\n'.join(difflib.ndiff( pprint.pformat(d1).splitlines(), pprint.pformat(d2).splitlines()))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertDictContainsSubset(self, subset, dictionary, msg=None): """Checks whether dictionary is a superset of subset.""" warnings.warn('assertDictContainsSubset is deprecated', DeprecationWarning) missing = [] mismatched = [] for key, value in subset.items(): if key not in dictionary: missing.append(key) elif value != dictionary[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(dictionary[key]))) if not (missing or mismatched): return standardMsg = '' if missing: standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += 'Mismatched values: %s' % ','.join(mismatched) self.fail(self._formatMessage(msg, standardMsg)) def assertCountEqual(self, first, second, msg=None): """Asserts that two iterables have the same elements, the same number of times, without regard to order. self.assertEqual(Counter(list(first)), Counter(list(second))) Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(first), list(second) try: first = collections.Counter(first_seq) second = collections.Counter(second_seq) except TypeError: # Handle case with unhashable elements differences = _count_diff_all_purpose(first_seq, second_seq) else: if first == second: return differences = _count_diff_hashable(first_seq, second_seq) if differences: standardMsg = 'Element counts were not equal:\n' lines = ['First has %d, Second has %d: %r' % diff for diff in differences] diffMsg = '\n'.join(lines) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, str, 'First argument is not a string') self.assertIsInstance(second, str, 'Second argument is not a string') if first != second: # don't use difflib if the strings are too long if (len(first) > self._diffThreshold or len(second) > self._diffThreshold): self._baseAssertEqual(first, second, msg) firstlines = first.splitlines(keepends=True) secondlines = second.splitlines(keepends=True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % _common_shorten_repr(first, second) diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertLess(self, a, b, msg=None): """Just like self.assertTrue(a < b), but with a nicer default message.""" if not a < b: standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertLessEqual(self, a, b, msg=None): """Just like self.assertTrue(a <= b), but with a nicer default message.""" if not a <= b: standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreater(self, a, b, msg=None): """Just like self.assertTrue(a > b), but with a nicer default message.""" if not a > b: standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreaterEqual(self, a, b, msg=None): """Just like self.assertTrue(a >= b), but with a nicer default message.""" if not a >= b: standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNone(self, obj, msg=None): """Same as self.assertTrue(obj is None), with a nicer default message.""" if obj is not None: standardMsg = '%s is not None' % (safe_repr(obj),) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNotNone(self, obj, msg=None): """Included for symmetry with assertIsNone.""" if obj is None: standardMsg = 'unexpectedly None' self.fail(self._formatMessage(msg, standardMsg)) def assertIsInstance(self, obj, cls, msg=None): """Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.""" if not isinstance(obj, cls): standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIsInstance(self, obj, cls, msg=None): """Included for symmetry with assertIsInstance.""" if isinstance(obj, cls): standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs): """Asserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. """ context = _AssertRaisesContext(expected_exception, self, expected_regex) return context.handle('assertRaisesRegex', args, kwargs) def assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs): """Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. Args: expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. """ context = _AssertWarnsContext(expected_warning, self, expected_regex) return context.handle('assertWarnsRegex', args, kwargs) def assertRegex(self, text, expected_regex, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regex, (str, bytes)): assert expected_regex, "expected_regex must not be empty." expected_regex = re.compile(expected_regex) if not expected_regex.search(text): standardMsg = "Regex didn't match: %r not found in %r" % ( expected_regex.pattern, text) # _formatMessage ensures the longMessage option is respected msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertNotRegex(self, text, unexpected_regex, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regex, (str, bytes)): unexpected_regex = re.compile(unexpected_regex) match = unexpected_regex.search(text) if match: standardMsg = 'Regex matched: %r matches %r in %r' % ( text[match.start() : match.end()], unexpected_regex.pattern, text) # _formatMessage ensures the longMessage option is respected msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def _deprecate(original_func): def deprecated_func(*args, **kwargs): warnings.warn( 'Please use {0} instead.'.format(original_func.__name__), DeprecationWarning, 2) return original_func(*args, **kwargs) return deprecated_func # see #9424 failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) assertNotRegexpMatches = _deprecate(assertNotRegex) class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the unittest framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): super(FunctionTestCase, self).__init__() self._setUpFunc = setUp self._tearDownFunc = tearDown self._testFunc = testFunc self._description = description def setUp(self): if self._setUpFunc is not None: self._setUpFunc() def tearDown(self): if self._tearDownFunc is not None: self._tearDownFunc() def runTest(self): self._testFunc() def id(self): return self._testFunc.__name__ def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self._setUpFunc == other._setUpFunc and \ self._tearDownFunc == other._tearDownFunc and \ self._testFunc == other._testFunc and \ self._description == other._description def __hash__(self): return hash((type(self), self._setUpFunc, self._tearDownFunc, self._testFunc, self._description)) def __str__(self): return "%s (%s)" % (strclass(self.__class__), self._testFunc.__name__) def __repr__(self): return "<%s tec=%s>" % (strclass(self.__class__), self._testFunc) def shortDescription(self): if self._description is not None: return self._description doc = self._testFunc.__doc__ return doc and doc.split("\n")[0].strip() or None class _SubTest(TestCase): def __init__(self, test_case, message, params): super().__init__() self._message = message self.test_case = test_case self.params = params self.failureException = test_case.failureException def runTest(self): raise NotImplementedError("subtests cannot be run directly") def _subDescription(self): parts = [] if self._message is not _subtest_msg_sentinel: parts.append("[{}]".format(self._message)) if self.params: params_desc = ', '.join( "{}={!r}".format(k, v) for (k, v) in self.params.items()) parts.append("({})".format(params_desc)) return " ".join(parts) or '()' def id(self): return "{} {}".format(self.test_case.id(), self._subDescription()) def shortDescription(self): """Returns a one-line description of the subtest, or None if no description has been provided. """ return self.test_case.shortDescription() def __str__(self): return "{} {}".format(self.test_case, self._subDescription()) __pycache__/util.cpython-311.opt-2.pyc000064400000016545151030032340013375 0ustar00 !A?h_ ddlmZmZddlmZdZdZdZdZdZ dZ eeeze zeze zz Z dZ dZ dd Zd Zd Zd ZdZeddZdZdZdS)) namedtupleCounter) commonprefixTP ct||z |z }|tkr(d|d|||t||z dfz}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlen suffixlenskips &/usr/lib64/python3.11/unittest/util.py_shortenrsW q66I  )D  *9* tQs1vv 7I7J7J5KL L Hcttt|}ttt|}|t kr|St |t t |z tztzz }|tkr2tt|tfd|DSttttfd|DS)Nc32K|]}|dzVdSN.0r prefixr s r z'_common_shorten_repr..'s0::Va m+::::::rc3dK|]*}t|dttzV+dSr)r _MIN_DIFF_LEN _MIN_END_LENrs rrz'_common_shorten_repr..*sP  (1YZZ=-NNN      r) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENr)argsmaxlen common_lenrr s @@r_common_shorten_reprr(s Y%% & &D S$ F  $  FF I9$~58HHJJO##&.*==:::::T:::::: fno > >F            rFc t|}n*#t$rt|}YnwxYw|rt |t kr|S|dt dzS)Nz [truncated]...)repr Exceptionobject__repr__r r")objshortresults rr r -sv&c &&&%%& CKK+-- ,;, "3 33s $99c$|jd|jS)N.) __module__ __qualname__)clss rstrclassr66snnnc&6&6 77rc dx}}g}g} ||}||}||kr8|||dz }|||kr|dz }|||kn||kr8|||dz }|||kr|dz }|||knm|dz } |||kr|dz }|||k|dz }|||kr|dz }|||kn'#|dz }|||kr|dz }|||kwxYwnJ#t$r=|||d|||dYnwxYwG||fS)NrT)append IndexErrorextend)expectedactualijmissing unexpectedeas rsorted_list_differencerD9s IAGJ  Aq A1uuq!!!QqkQ&&FAqkQ&&Q!!!$$$QQi1nnFAQi1nnQ"1+**Q#1+**FA )q..Q!)q..FA )q..Q!)q......    NN8ABB< ( ( (   fQRRj ) ) ) E /6 J s+BDC;#D$DDAE  E c g}|rR|} ||n%#t$r||YnwxYw|R||fSr)popremove ValueErrorr9)r<r=r@items runorderable_list_differencerJbs G !||~~ ! MM$     ! ! ! NN4  ! ! F?s1AAc ||k||kz Srr)xys r three_way_cmprNss8 Ea!e rMismatchzactual expected valuec t|t|}}t|t|}}t}g}t|D]\}} | |ur dx} } t ||D]} || | kr | dz } ||| <t|D]\} } | | kr | dz } ||| <| | kr&t | | | }||t|D][\}} | |ur d} t ||D]} || | kr | dz } ||| <t d| | }||\|S)Nrr8)listr r, enumeraterange _Mismatchr9)r=r<r tmnNULLr0r>elemcnt_scnt_tr? other_elemdiffs r_count_diff_all_purposer^ysN <<hqA q663q66qA 88D FQ<<  4 4<< q!  Att|| !&q\\  MAzT!! ! E>>UE400D MM$   Q<<  4 4<< q!  Att|| !E4(( d Mrc t|t|}}g}|D]G\}}||d}||kr&t|||}||H|D]/\}}||vr&td||}||0|S)Nr)ritemsgetrTr9) r=r<r rUr0rYrZr[r]s r_count_diff_hashablerbsN 6??GH--qA Fwwyy  edA E>>UE400D MM$   wwyy  e q==Qt,,D MM$    MrN)F) collectionsrros.pathr __unittestr"r r#rr$rrr(r r6rDrJrNrTr^rbrrrrfs% ++++++++    !11OC !#/01       *4444888&&&R" Jz#: ; ; !!!Fr__pycache__/runner.cpython-311.opt-2.pyc000064400000037005151030032340013723 0ustar00 !A?h$ ddlZddlZddlZddlmZddlmZddlmZdZ Gdde Z Gd d ej Z Gd d e ZdS) N)result)_SubTest)registerResultTc$eZdZ dZdZddZdS)_WritelnDecoratorc||_dSN)stream)selfr s (/usr/lib64/python3.11/unittest/runner.py__init__z_WritelnDecorator.__init__s  cR|dvrt|t|j|S)N)r __getstate__)AttributeErrorgetattrr )r attrs r __getattr__z_WritelnDecorator.__getattr__s. - - - && &t{4(((rNc^|r|||ddSN )write)r args r writelnz_WritelnDecorator.writelns1   JJsOOO 4rr )__name__ __module__ __qualname__rrrrr rrsIJ))) rrceZdZ dZdZfdZdZfdZdZfdZ fdZ fd Z fd Z fd Z fd Zfd ZdZdZxZS)TextTestResultzF======================================================================zF----------------------------------------------------------------------ctt||||||_|dk|_|dk|_||_d|_dS)NrT)superr!rr showAlldots descriptions_newline)r r r& verbosity __class__s r rzTextTestResult.__init__&sU nd##,,V\9MMM  1} N ( rc|}|jr&|r$dt||fSt|Sr)shortDescriptionr&joinstr)r testdoc_first_lines r getDescriptionzTextTestResult.getDescription.sN..00    99c$ii899 9t99 rc8tt|||jri|j|||jd|jd|_dSdS)N ... F) r#r! startTestr$r rr0flushr'r r.r)s r r3zTextTestResult.startTest5s nd##--d333 < " K  d11$77 8 8 8 K  g & & & K     !DMMM  " "rct|t}|s|jr|js|j|r|jd|j|||jd|j||jd|_dS)Nz r2T) isinstancerr'r rrr0r4)r r.status is_subtests r _write_statuszTextTestResult._write_status=sh//  ' '= & ##%%% ( !!$''' K  d11$77 8 8 8 K  g & & & F###  rc||jrIt|d|jr||dn||dnp|jrit|d|jr|jdn|jd|jtt| |||dS)NrFAILERRORFE) r$ issubclassfailureExceptionr:r%r rr4r#r! addSubTest)r r.subtesterrr)s r rBzTextTestResult.addSubTestJs ?| $c!fg&>??9&&w7777&&w8888 $c!fg&>??+K%%c****K%%c*** !!### nd##..tWcBBBBBrctt|||jr||ddS|jr5|jd|jdSdS)Nok.) r#r! addSuccessr$r:r%r rr4r5s r rHzTextTestResult.addSuccessYs nd##..t444 <   tT * * * * * Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr=r?) r#r!addErrorr$r:r%r rr4r r.rDr)s r rJzTextTestResult.addErroras nd##,,T3777 <   tW - - - - - Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr<r>) r#r! addFailurer$r:r%r rr4rKs r rMzTextTestResult.addFailureis nd##..tS999 <   tV , , , , , Y K  c " " " K         rc6tt||||jr+||d|dS|jr5|jd|j dSdS)Nz skipped {0!r}s) r#r!addSkipr$r:formatr%r rr4)r r.reasonr)s r rPzTextTestResult.addSkipqs nd##++D&999 <   t_%;%;F%C%C D D D D D Y K  c " " " K         rcJtt||||jr5|jd|jdS|jr5|jd|jdSdS)Nzexpected failurex) r#r!addExpectedFailurer$r rr4r%rrKs r rUz!TextTestResult.addExpectedFailureys nd##66tSAAA < K   2 3 3 3 K        Y K  c " " " K         rcHtt|||jr5|jd|jdS|jr5|jd|jdSdS)Nzunexpected successu) r#r!addUnexpectedSuccessr$r rr4r%rr5s r rXz#TextTestResult.addUnexpectedSuccesss nd##88>>> < K   4 5 5 5 K        Y K  c " " " K         rc|js|jr2|j|j|d|j|d|jt|dd}|ro|j|j |D]2}|jd| |3|jdSdS)Nr=r<unexpectedSuccessesrzUNEXPECTED SUCCESS: ) r%r$r rr4printErrorListerrorsfailuresr separator1r0)r rZr.s r printErrorszTextTestResult.printErrorss 9   K   ! ! ! K      GT[111 FDM222%d,A2FF  K   0 0 0+ X X ##$V4;N;Nt;T;T$V$VWWWW K          rcb|D]\}}|j|j|j|d|||j|j|jd|z|jdS)Nz: z%s)r rr^r0 separator2r4)r flavourr\r.rDs r r[zTextTestResult.printErrorLists  ID# K   0 0 0 K  GGGD4G4G4M4M4M N O O O K   0 0 0 K  s + + + K         r)rrrr^rarr0r3r:rBrHrJrMrPrUrXr_r[ __classcell__)r)s@r r!r!sRJJ"""""    C C C C C                                         rr!c2eZdZ eZ d dddZdZdZdS) TextTestRunnerNTrF) tb_localsc | tj}t||_||_||_||_||_||_||_ | ||_ dSdSr ) sysstderrrr r&r(failfastbufferrfwarnings resultclass) r r r&r(rjrkrmrlrfs r rzTextTestRunner.__init__sk >ZF'// ("   "   "*D    # "rcN||j|j|jSr )rmr r&r()r s r _makeResultzTextTestRunner._makeResults! T->OOOrc |}t||j|_|j|_|j|_t j5|jr>t j|j|jdvrt jdtdtj }t|dd}| | ||t|dd}| |n##t|dd}| |wwxYwtj }dddn #1swxYwY||z }|j t|dr|j|j|j}|jd||d krd pd |fz|jd x} x} } t't(|j|j|jf} | \} } } n#t0$rYnwxYwg} |jsw|jd t)|jt)|j}}|r| d|z|r| d|zn|jd| r| d| z| r| d| z| r| d| z| r2|jdd| dn|jd|j|S)N)defaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRun stopTestRunrazRan %d test%s in %.3fsrrOrFAILEDz failures=%dz errors=%dOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (z, )r) rorrjrkrfrlcatch_warnings simplefilterfilterwarningsDeprecationWarningtime perf_counterrr_hasattrr rratestsRunmaplenexpectedFailuresrZskippedr wasSuccessfulrr]r\appendr,r4)r r.r startTimervrwstopTime timeTakenrun expectedFailsrZrresultsinfosfailederroreds r rzTextTestRunner.runs0!!##v-  >  $ & & + +} F%dm444 =$999+H%7$DFFFF)++I"6>4@@L'  "V %fmTBB *KMMM&fmTBB *KMMMM+(**H/ + + + + + + + + + + + + + + +0y(  6< ( ( 3 K   1 2 2 2o 4 #("2s"8b)DE F F F 899 9+g B# 7 & : & 011G ;B 7M.    D  #v#%% $ K  h ' ' '!&/22C 4F4FGF 5 ]V3444 4 [72333 K  d # # #  1 LL/ 0 0 0  A LL/-? @ @ @  J LL25HH I I I  $ K   499U+;+;+;+; = > > > > K  d # # #  s=A6D> C<D>< DD>>EE'H HH)NTrFFNN)rrrr!rmrrorrrr reresm !KABJN+#+++++(PPPGGGGGrre)rhrrlrxrcasersignalsr __unittestobjectr TestResultr!rerrr rs ######           @ @ @ @ @ V&@ @ @ FfffffVfffffr__pycache__/mock.cpython-311.pyc000064400000374246151030032340012416 0ustar00 !A?hH`dZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZddlmZmZddlmZGdd eZd eeDZd ZeZd Zd ZdZdZdZ dZ!dydZ"dZ#dZ$dZ%dZ&dydZ'dZ(dZ)dZ*Gdde+Z,Gdde+Z-e-Z.e.j/Z/e.j0Z1e.j2Z3hd Z4d!Z5Gd"d#e6Z7d$Z8Gd%d&e+Z9Gd'd(e+Z:Gd)d*e:Z;ej<e;j=Z>Gd+d,e6Z?d-Z@Gd.d/e:ZAGd0d1eAe;ZBd2ZCGd3d4e+ZDd5ZEe/dddddfdd6d7ZF dzd8ZGe/dddddfdd6d9ZHGd:d;e+ZId<ZJd=ZKeFeH_+eIeH_LeGeH_MeKeH_Nd>eH_Od?ZPd@ZQdARdBeQSDZTdARdCeQSDZUhdDZVdEZWdFdARePeQeTeUgSDZXhdGZYdHhZZeYeZzZ[eXeVzZ\e\e[zZ]hdIZ^dJdKdLdMdNZ_e`e`e`e`dOddddPdQd dOddR ZadSZbdTZcdUZddVZeebecedeedWZfdXZgGdYdZe:ZhGd[d\ehe;ZiGd]d^ehZjGd_d`eheBZkGdadbe:ZlGdcdde:ZmGdedfemejeBZnGdgdhe+ZoeoZpdiZqGdjdkerZsesdlZt d{dd6dmZudnZvGdodpe+ZwexeuexepjyfZzda{da|dqZ}d|dsZ~GdtdueBZdvZGdwdxZdS)})Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartial)RLockceZdZdZdS)InvalidSpecErrorz8Indicates that an invalid value was used as a mock spec.N__name__ __module__ __qualname____doc__&/usr/lib64/python3.11/unittest/mock.pyrr)sBBBBr"rc<h|]}|d|S_ startswith).0names r# r+-s) H H Hd4??33G3G HT H H Hr"Tct|rt|tsdSt|drt |d}t |pt j|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspect isawaitableobjs r# _is_async_objr65sgji&@&@usJ'c:&& s # # ?w':3'?'??r"cFt|ddrt|SdS)N__code__F)r1r)funcs r#_is_async_funcr:=s)tZ&&"4(((ur"cFtt|tSN) issubclasstyper r4s r#r.r.Ds d3ii 1 11r"ct|tp)t|tot|tSr<)r/ BaseExceptionr>r=r4s r# _is_exceptionrAJs63 && A3@*S-"@"@r"c^t|trt|dr|jS|SNmock)r/ FunctionTypesr0rDr4s r# _extract_mockrFQs3#}%%'#v*>*>x r"ct|tr |s |j}d}njt|ttfrt|trd}|j}n/t|t s |j}n#t$rYdSwxYw|rt|d}n|} |tj |fS#t$rYdSwxYw)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. TN) r/r>__init__ classmethod staticmethodr-rE__call__AttributeErrorrr2 signature ValueError)r9 as_instanceeat_selfsig_funcs r#_get_signature_objectrRZs $k} D; 5 6 6  dK ( ( H} m , , =DD   44 4&&W&x0000 tts$3A;; B B "B88 CCFct|||dS\}fd}t|||t|_t|_dS)Nc"j|i|dSr<bind)selfargskwargssigs r#checksigz"_check_signature..checksig $!&!!!!!r")rR_copy_func_detailsr>_mock_check_sig __signature__)r9rD skipfirstinstancer[rZs @r#_check_signaturerb}sr h : :C {ID#"""""tX&&&!)DJJ"DJJr"c pdD]2} t||t||##t$rY/wxYwdS)N)rr __text_signature__r __defaults____kwdefaults__)setattrr1rL)r9funcopy attributes r#r]r]sa   GYi(@(@ A A A A    D  s & 33ct|trdSt|tttfrt |jSt|dddSdS)NTrKF)r/r>rJrIr _callabler-r1r4s r#rkrks^#tt# k:>??'&&&sJ%%1t 5r"c<t|ttfvSr<)r>listtupler4s r#_is_listros 99u %%r"ct|tst|ddduS|f|jzD]}|jddS dS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.rKNTF)r/r>r1__mro____dict__get)r5bases r#_instance_callablerusn c4 :sJ--T99$ =  Z ( ( 444 5 5r"c0 t|t}t|||}||S|\} fd}t|||j}|sd}||d}d|z} t | |||} t| | | S)Nc"j|i|dSr<rU)rXrYrZs r#r[z _set_signature..checksigr\r"rh) _checksig_rDzYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r/r>rRr]r isidentifierexec _setup_func) rDoriginalrar`resultr9r[r*contextsrcrhrZs @r#_set_signaturers 8T**I "8Xy A AF ~ ID#"""""tX&&&  D     %t44G $&* +C #wdmGs### Nr"c_fd}fd}fd}fd}fd}fd}fd} fd} d _d _d_t _t _t _j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS) Ncj|i|Sr<)assert_called_withrXrYrDs r#rz'_setup_func..assert_called_with&t&7777r"cj|i|Sr<) assert_calledrs r#rz"_setup_func..assert_calleds!t!426222r"cj|i|Sr<)assert_not_calledrs r#rz&_setup_func..assert_not_calleds%t%t6v666r"cj|i|Sr<)assert_called_oncers r#rz'_setup_func..assert_called_oncerr"cj|i|Sr<)assert_called_once_withrs r#rz,_setup_func..assert_called_once_withs+t+T.assert_has_callss$t$d5f555r"cj|i|Sr<)assert_any_callrs r#rz$_setup_func..assert_any_calls#t#T4V444r"ct_t_j}t |r|ur|dSdSdSr<) _CallList method_calls mock_calls reset_mock return_valuer.)retrhrDs r#rz_setup_func..reset_mockso({{&[[ " S ! ! #++ NN       ++r"Fr)rDcalled call_count call_argsrcall_args_listrrr side_effect_mock_childrenrrrrrrrrr__mock_delegate) rhrDrZrrrrrrrrs `` r#r{r{sGL88888333337777788888=====6666655555GNGG&[[G$;;G"G,G*G!0G!3G&=G#/G-G#G)G 1G!3GG!Dr"c tjj_d_d_t _fd}dD]!}t|t||"dS)Nrc:tj||i|Sr<)r1rD)attrrXrYrDs r#wrapperz"_setup_async_mock..wrapper s$'wty$''8888r")assert_awaitedassert_awaited_onceassert_awaited_withassert_awaited_once_withassert_any_awaitassert_has_awaitsassert_not_awaited) asyncio coroutines _is_coroutine await_count await_argsrawait_args_listrgr)rDrris` r#_setup_async_mockrs +9DDDO$;;D 99999, > >  i)! >r"c$d|ddz|kS)N__%s__r!r*s r# _is_magicrs d1R4j D ((r"c$eZdZdZdZdZdZdS)_SentinelObjectz!A unique, named, sentinel object.c||_dSr<rrWr*s r#rHz_SentinelObject.__init__"s  r"cd|jzSNz sentinel.%srrWs r#__repr__z_SentinelObject.__repr__%ty((r"cd|jzSrrrs r# __reduce__z_SentinelObject.__reduce__(rr"N)rrrr rHrrr!r"r#rr sG''))))))))r"rc$eZdZdZdZdZdZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.ci|_dSr<) _sentinelsrs r#rHz_Sentinel.__init__.s r"cl|dkrt|j|t|S)N __bases__)rLr setdefaultrrs r# __getattr__z_Sentinel.__getattr__1s3 ;   ))$0E0EFFFr"cdS)Nrr!rs r#rz_Sentinel.__reduce__7szr"N)rrrr rHrrr!r"r#rr,sJKKGGG r"r> _mock_namer _mock_parentr_mock_new_name_mock_new_parent_mock_side_effect_mock_return_valuecxt|d|z}||fd}||fd}t||S)N_mock_cT|j}|t||St||Sr<)rr1)rWr* _the_namerZs r#_getz"_delegating_property.._getLs/! ;4++ +sD!!!r"cR|j}| ||j|<dSt|||dSr<)rrrrg)rWvaluer*rrZs r#_setz"_delegating_property.._setQs9! ;',DM) $ $ $ Cu % % % % %r")_allowed_namesaddproperty)r*rrrs r#_delegating_propertyrIset4I """" $y&&&& D$  r"ceZdZdZdZdS)rct|tst||St|}t|}||krdSt d||z dzD]}||||z}||krdSdS)NFrT)r/rm __contains__lenrange)rWr len_valuelen_selfisub_lists r#rz_CallList.__contains__^s%&& 2$$T511 1JJ t99 x  5q(Y.233  AAa kM*H5  tt!ur"cDtjt|Sr<)pprintpformatrmrs r#rz_CallList.__repr__ls~d4jj)))r"N)rrrrrr!r"r#rr\s2   *****r"rct|}t|sdS|js|js|j|jdS|}|||urdS|j}||r||_||_|r||_||_dS)NFT)rFr.rrrr)parentrr*new_name_parents r#_check_and_set_parentrps % E U # #u  U1   '   +uG   e  5*  (!''  # 4r"ceZdZdZdZdS) _MockIterc.t||_dSr<)iterr5)rWr5s r#rHz_MockIter.__init__s99r"c*t|jSr<)nextr5rs r#__next__z_MockIter.__next__sDH~~r"N)rrrrHrr!r"r#rrs2r"rceZdZeZdZdZdS)BaseNcdSr<r!rWrXrYs r#rHz Base.__init__s r")rrrrrrrHr!r"r#rrs/      r"rceZdZdZeZdZ d-dZdZd.dZ d/d Z d Z d Z d Z ee e e Zed ZedZedZedZedZedZdZdZeeeZd0ddddZdZdZdZdZdZdZ dZ!dZ"d1d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d'Z*d.d(Z+d)Z,d*Z-d2d,Z.dS)3r z A non-callable version of `Mock`cz|f}t|ts]tj|g|Ri|j}|d|d}|t |r t|f}t|j|d|j i}tt| |}|S)Nspec_setspecr ) r=AsyncMockMixin _MOCK_SIG bind_partial argumentsrsr6r>rr _safe_superr __new__)clsrXkwbases bound_argsspec_argnewras r#rzNonCallableMock.__new__s#~.. ."/AdAAAbAAKJ!~~j*..2H2HIIH# h(?(?#'-3<CK(@AA44<rRrr) rWrrrrr&r(r*rresrrs r#rzNonCallableMock._mock_add_specs' T " " T"#R#R#R#RSS S  II * *D"74t#<#<== *##D)))  HTNN $%% )" "4jj '(99FFC!nc!fOt99D="- (&5"#$(!#/   r"c|j}|j |jj}|tur%|j||d}||_|S)N()rr)rrrrr_get_child_mock)rWrs r#__get_return_valuez"NonCallableMock.__get_return_values]%   *%2C '>>d.6&& D'C!$D  r"cb|j||j_dS||_t||dddS)Nr/)rrrr)rWrs r#__set_return_valuez"NonCallableMock.__set_return_value%s>   */4D  , , ,&+D # !$tT : : : : :r"z1The value to be returned when the mock is called.c<|jt|S|jSr<)r&r>rs r# __class__zNonCallableMock.__class__1s   #:: r"rrrrrc|j}||jS|j}|It|s:t |t s%t |st |}||_|Sr<)rrrcallabler/rrA)rW delegatedsfs r#__get_side_effectz!NonCallableMock.__get_side_effect>sj'  ) )  " N8B<>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)c8|ddS)Nr.)count)entrys r#z0NonCallableMock.configure_mock..sq1D1Dr")keyrIN)sorteditemssplitpopr1rg)rWrYargvalrXfinalr5rKs r#rzNonCallableMock.configure_mockrsv||~~$E#D FFF % %HC 99S>>DHHJJEC * *c5)) C $ $ $ $ % %r"c |dvrt||j%||jvs |tvrtd|znt|rt||js:|jr ||jvr*|drt|d|dt j5|j |}|turt||Cd}|j t|j |}| |||||}||j|<nt|trv t!|j|j|j|j|j}n>#t,$r1|jdp|}t-d|d |d |d |jd wxYw||j|<dddn #1swxYwY|S) N>rr)zMock object has no attribute %r)assertassretasertaseertassrtz6 is not a valid assertion. Use a spec for the mock if z is meant to be an attribute.)rr*rrrrCannot autospec attr from target , as it has already been mocked out. [target=, attr=r%)rLr) _all_magicsrrr(r _lockrrsrDrr1r1r/rCr rrrarr*rrr)rWr*r}r target_names r#rzNonCallableMock.__getattr__s 4 4 4 && &   +4---1D1D$%F%MNNN2E t__ ' && &  N$*< NDL^@^@^OPP N$MM'+MMMNNN " 4 4(,,T22F!!$T***#/$D$4d;;E--d%4 $..4#D))FJ// 4 D, V_fo v{FF(DDD"&- "="EK*CCC&CC#'CC28+CCCDDDD .4#D); 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4> s++B F:9,E&%F:&;F!! F::F>F>cn|jg}|j}|}d}|dgkrd}|7|}||j|zd}|jdkrd}|j}|7tt |}|jpd}t |dkr|ddvr|dz }||d<d|S)NrIr/r rDr)r/z().r)rrr,rmreversedrrjoin)rW _name_listrlastdot_firsts r#_extract_mock_namez"NonCallableMock._extract_mock_names)* ' $  C!D   g4s: ; ; ;C%--.G!(:..// *F z??Q  !}M11#  1 wwz"""r"c|}d}|dvrd|z}d}|jd}|jrd}||jjz}dt |j||dt |dS) Nr )rDzmock.z name=%rz spec=%rz spec_set=%r)rir&r'rr>rA)rWr* name_string spec_strings r#rzNonCallableMock.__repr__s&&(( ( ( ($t+K   '$K~ -, %(8(AAK JJ   K KK tHHHH   r"cvtst|S|jpg}t t |}t |j}d|j D}d|D}d|D}tt||z|z|zS)z8Filter the output of `dir(mock)` to only useful members.c*g|]\}}|tu|Sr!)rD)r)m_namem_values r# z+NonCallableMock.__dir__..s1(((&vwh&& &&&r"c<g|]}|d|Sr%r'r)es r#rrz+NonCallableMock.__dir__..s)CCC1c1B1BCQCCCr"cZg|](}|drt|&|)Sr%)r(rrts r#rrz+NonCallableMock.__dir__..sE###1c1B1B#q\\#Q###r") r object__dir__r)r+r>rmrrrrOrNset)rWextras from_type from_dictfrom_child_mockss r#rxzNonCallableMock.__dir__s (>>$'' '#)rT OO '' ((*.*=*C*C*E*E(((DC CCC ## ### c&9,y8;KKLLMMMr"cT|tvrt||Sjr+j$|jvr|jvrt d|z|tvrd|z}t ||tvrj|jvrt d|zt|s5tt|t|||fd}nft|d|tt|||j|<n+|dkr |_dSt|||r |j|<jr;t#|s+d|}t d|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.cg|Ri|Sr<r!)rXrr|rWs r#rLz-NonCallableMock.__setattr__.. s!HHT,GD,G,G,GB,G,Gr"r6rIz Cannot set )rrw __setattr__r'r)rrrL_unsupported_magicsr_r.rgr> _get_methodrrr&r r0ri)rWr*rmsg mock_namer|s` @r#rzNonCallableMock.__setattr__s > ! !%%dD%88 8n 2!3!? * * *  % % !Dt!KLL L ( ( (BTIC %% % [ !-$d>P2P2P$%H4%OPPP$U++ 2T D+dE*B*BCCC GGGGG&dE4>>>T D%000,1#D)) [ $D  F$T5$== 2,1#D)   |t|jvr(tt||||jvrdS|j|t }||jvr)tt| |n|turt||t ur|j|=t|j|<dSr<) r_r>rrdelattrrrs_missingrr __delattr__rDrL)rWr*r5s r#rzNonCallableMock.__delattr__!s ;  44::+>#>#> DJJ % % %4=((!%%dH55 4=  . . : :4 @ @ @ @ H__ && & h  #D)$,D!!!r"c6|jpd}t|||SrC)r_format_call_signaturerWrXrYr*s r#_format_mock_call_signaturez+NonCallableMock._format_mock_call_signature3s (&%dD&999r"rcdd}|||}|j}|j|}||||fzS)Nz0expected %s not found. Expected: %s Actual: %s)rr)rWrXrYactionmessageexpected_stringr actual_strings r#_format_mock_failure_messagez,NonCallableMock._format_mock_failure_message8sDF::4HHN 88)D &/=AAAr"c|s|jSd}|ddd}|j}|D]M}||}|t |t rnt|}|j}|j}N|S)aH * If call objects are asserted against a method/function like obj.meth1 then there could be no name for the call object to lookup. Hence just return the spec_signature of the method/function being asserted against. * If the name is not empty then remove () and split by '.' to get list of names to iterate through the children until a potential match is found. A child mock is created only during attribute access so if we get a _SpecState then no attributes of the spec were accessed and can be safely exited. Nr/r rI)r(replacerPrrsr/rCrF)rWr*rZnameschildrenrFs r#_get_call_signature_from_namez-NonCallableMock._get_call_signature_from_name@s (' ' T2&&,,S11& , ,DLL&&E} 5* = =} &e,, /+ r"ct|tr/t|dkr||d}n|j}|vt|dkrd}|\}}n|\}}} |j|i|}t ||j|jS#t$r}| dcYd}~Sd}~wwxYw|S)a Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. rrNr ) r/rnrrr(rVrrXrY TypeErrorwith_traceback)rW_callrZr*rXrY bound_callrus r# _call_matcherzNonCallableMock._call_matcheras eU # # 'E Q44U1X>>CC&C ?5zzQ$ ff%*"dF .%SXt6v66 D*/:3DEEE . . .''-------- .Ls0'B C"B<6C<Cc|jdkr8d|jpdd|jd|}t|dS)z/assert that the mock was never called. r Expected 'rDz"' to not have been called. Called  times.Nrr _calls_reprAssertionErrorrWrs r#rz!NonCallableMock.assert_not_called|s^ ?a   o///ooo&&(((*C!%% % r"cR|jdkrd|jpdz}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.rDN)rrrrs r#rzNonCallableMock.assert_calleds; ?a  7O-v/C %% % r"c|jdks8d|jpdd|jd|}t|dS)z3assert that the mock was called only once. rrrDz#' to have been called once. Called rNrrs r#rz"NonCallableMock.assert_called_onces^!###o///ooo&&(((*C!%% % $#r"ctj/}d}d|d|}t|fd}t fd}j}||kr1t |t r|nd}t||dS)zassert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.Nz not called.z#expected call not found. Expected: z Actual: c4}|Sr<rrrXrYrWs r#_error_messagez:NonCallableMock.assert_called_with.._error_messages33D&AACJr"Ttwo)rrrr_Callr/ Exception)rWrXrYexpectedactual error_messagercauses``` r#rz"NonCallableMock.assert_called_withs > !77fEEH"FFxx)M // /       %%eT6N&E&E&EFF##DN33 X   *8Y ? ?IHHTE !1!122 =  r"c|jdks8d|jpdd|jd|}t||j|i|S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rrrDz' to be called once. Called r)rrrrrrWrXrYrs r#rz'NonCallableMock.assert_called_once_withsn!###o///ooo&&(((*C!%% %&t&7777r"cfd|D}td|Dd}tfdjD}|su||vro|d}ndd|D}t |dt|d d |dSt|}g}|D]=} ||#t$r| |Y:wxYw|r-t j pd d t|d|d|dS)aassert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.c:g|]}|Sr!rr)crWs r#rrz4NonCallableMock.assert_has_calls..'999aD&&q))999r"c3DK|]}t|t|VdSr<r/rrts r# z3NonCallableMock.assert_has_calls..1FFAZ9-E-EFaFFFFFFr"Nc3BK|]}|VdSr<rrs r#rz3NonCallableMock.assert_has_calls..s1MMd0033MMMMMMr"zCalls not found.z+Error processing expected calls. Errors: {}c@g|]}t|tr|ndSr<rrts r#rrz4NonCallableMock.assert_has_calls..;$7$7$7()*4Ay)A)A$KAAt$7$7$7r" Expected: z Actual)prefixrIrDz does not contain all of z in its call list, found z instead) rrrformatrrrstriprmremoverNr,rrn) rWcalls any_orderrr all_callsproblem not_foundkalls ` r#rz NonCallableMock.assert_has_callss:9995999FFFFFMMMMMMT_MMMMM  y((=0GG ,-3V$7$7-5$7$7$7.8.8%II!*5!1!1I''z'::AA#FFII  FOO   ' 'D '  &&&& ' ' '  &&&&& '   &*o&?&?&?&+I&6&6&6&6 C    sC--DDc$t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)zassert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.TrNc:g|]}|Sr!rrs r#rrz3NonCallableMock.assert_any_call..s'EEEA$$$Q''EEEr"z%s call not found)rrr/rr _AnyComparerrrrWrXrYrrrrs` r#rzNonCallableMock.assert_any_calls %%eT6N&E&E&EFF&x;;EEEEE1DEEE  HL$8$888">>tVLLO #o5 98r"c |jr7d|vr d|dnd}||z}t||d}||jdvr t di|St |}t|tr|tvrt }nt|tr)|tvs|j r||j vrt}ndt }n\t|ts:t|trt}n*t|trt }n |jd}|di|S)aPCreate the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).r*rIr/rr*rr!)r rirLrsrrr r>r=r_async_method_magicsr_all_sync_magicsr) CallableMixinr r rrq)rWrrirr_typeklasss r#r1zNonCallableMock._get_child_mocks[   ,,2bLL(BvJ(((dI//11I=I ++ +FF;''  n5 5 5??r?? "T  eY ' ' %I9M,M,MEE ~ . . %---&.+48J+J+J!!E=11 %%!566 !E?33 M!$Eu{{r{{r"CallscJ|jsdSd|dt|jdS)zRenders self.mock_calls as a string. Example: " Calls: [call(1), call(2)]." If self.mock_calls is empty, an empty string is returned. The output will be truncated if very long. r  z: rI)rr)rWrs r#rzNonCallableMock._calls_reprs6 2;F;;i88;;;;r") NNNNNNr NFNFF)FFr<)r)r)/rrrr rr`rrHrr#r"_NonCallableMock__get_return_value"_NonCallableMock__set_return_value"_NonCallableMock__return_value_docrrr6rrrrrr!_NonCallableMock__get_side_effect!_NonCallableMock__set_side_effectrrrrrirrxrrrrrrrrrrrrrr1rr!r"r#r r s** EGGE   ">BEI   ;;;M8.0B.00L  X " !( + +F%%l33J$$[11I))*:;;N%%l33J   ***(,.?@@K$u%$$$$$<%%%,---`###6   *NNN$$5$5$5N---$::: BBBBB6&&&&&&&&&>>>, 8 8 8****Z    ###L < < < < < .5s1$HfF"r"TF)rallzip)rWitemrs r#rz_AnyComparer.__contains__2s{  Et99E ****(+D%(8(8 tt   ur"N)rrrr rr!r"r#rr-s-r"rc||St|r|St|r|S t|S#t$r|cYSwxYwr<)rArkrrr4s r#r=r==sk { S ~~ Cyy  s7 AAc HeZdZddedddddddf dZdZdZdZdZdZ dS) rNr c x||jd<tt|j||||||| | fi| ||_dS)Nr)rrrrrHr) rWrrrrr*rrrrrrYs r#rHzCallableMixin.__init__Nsa/; *+1 M4((1 %x K  39   'r"cdSr<r!rs r#r^zCallableMixin._mock_check_sigZs r"cP|j|i||j|i||j|i|Sr<)r^_increment_mock_call _mock_callrs r#rKzCallableMixin.__call___sK d-f---!!426222t////r"c|j|i|Sr<)_execute_mock_callrs r#rzCallableMixin._mock_callgs&t&7777r"c~d|_|xjdz c_t||fd}||_|j||jdu}|j}|j}|dk}|j td||f|j }||rB|j t|||f|jdu}|r |jdz|z}t|||f} |j | |jr|rd} nd} |jdk}|j| z|z}|j }|dSdS)NTrrr/r rI) rrrrrr,rrrrrr) rWrXrYrdo_method_callsmethod_call_namemock_call_name is_a_callrthis_mock_callrgs r#rz"CallableMixin._increment_mock_calljs  1 tVn$/// ""5)))+47?,"d*  ub$%788999+ % W(//7Gv6V0W0WXXX"-":$"F"W'2'='CFV'V$#ND&#ABBN  " ) ). 9 9 9) SCCC'6$> !,!;c!AN!R&6K-%%%%%r"c^|j}|Tt|r|t|s!t|}t|r|n||i|}|tur|S|jtur|jS|jr|jjtur|jS|j |j|i|S|jSr<) rrArkrrrrrr)rWrXrYeffectr}s r#rz CallableMixin._execute_mock_calls!  V$$ 1 v&& 1f ((! L! 000W$$  "' 1 1$ $   %4#6#C7#R#R$ $   '#4#T4V44 4  r") rrrrrHr^rKrrrr!r"r#rrLs d$d!RT ' ' ' '   000888,7,7,7\!!!!!r"rceZdZdZdS)ra Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an `AttributeError`. If `spec` is an object (rather than a list of strings) then `mock.__class__` returns the class of the spec object. This allows mocks to pass `isinstance` tests. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as `spec_set` will raise an `AttributeError`. * `side_effect`: A function to be called whenever the Mock is called. See the `side_effect` attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns `DEFAULT`, the return value of this function is used as the return value. If `side_effect` is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned. * `return_value`: The value returned when the mock is called. By default this is a new Mock (created on first access). See the `return_value` attribute. * `unsafe`: By default, accessing any attribute whose name starts with *assert*, *assret*, *asert*, *aseert* or *assrt* will raise an AttributeError. Passing `unsafe=True` will allow access to these attributes. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an `AttributeError`). If the mock has an explicit `return_value` set then calls are not passed to the wrapped object and the `return_value` is returned instead. * `name`: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks. Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. Nrr!r"r#rrs5555r"rc@d}|D]}||vrt|ddS)N) autospect auto_specset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)kwargs_to_checktypostypos r#_check_spec_arg_typosrsN 2E ? " "PPP  #r"c~eZdZdZgZdddZdZdZdZe j dZ d Z d Z d Zd Zd ZdZdZdS)_patchNFrc |)|turtd|td| st| t|rt d|d|dt|rt d|d|d||_||_||_||_||_ ||_ d|_ ||_ ||_ | |_g|_dS)Nz,Cannot use 'new' and 'new_callable' togetherz1Cannot use 'autospec' and 'new_callable' togetherzCannot spec attr z0 as the spec has already been mocked out. [spec=r%z? as the spec_set target has already been mocked out. [spec_set=F)rrNrr.rgetterrir  new_callablercreate has_localrautospecrYadditional_patchers) rWrrir rrrr rrYrs r#rHz_patch.__init__sV  #'!! B# G * !& ) ) ) T " " A"@I@@6:@@@AA A X & & P"OIOOAIOOOPP P "(       #%   r"c t|j|j|j|j|j|j|j|j|j }|j |_ d|j D|_ |S)Nc6g|]}|Sr!)copy)r)ps r#rrz_patch.copy..,s-' ' ' AFFHH' ' ' r") rrrir rrrr rrYattribute_namer )rWpatchers r#rz _patch.copy%sq K49 K M4,dk   "&!4' ' "6' ' ' #r"ct|tr||Stj|r||S||Sr<r/r>decorate_classr2rdecorate_async_callabledecorate_callable)rWr9s r#rKz_patch.__call__2sc dD ! ! -&&t,, ,  &t , , 6//55 5%%d+++r"ct|D]q}|tjs"t ||}t |dsC|}t||||r|SNrK)r+r(r TEST_PREFIXr1r0rrg)rWrr attr_valuers r#rz_patch.decorate_class:sJJ 6 6D??5#455  --J:z22 iikkG E4!4!4 5 5 5 5 r"c#TKg}tj5}|jD]W}||}|j||4|jtur||X|t|z }||fVddddS#1swxYwYdSr<) contextlib ExitStack patchings enter_contextrupdater rr,rn)rWpatchedrXkeywargs extra_args exit_stackpatchingrRs r#decoration_helperz_patch.decoration_helperHs  ! # # #z#- + + ..x88*6OOC((((\W,,%%c*** E*%% %D" " " " # # # # # # # # # # # # # # # # # #sA8BB!$B!ctdrjStfdg_S)Nrc|||5\}}|i|cdddS#1swxYwYdSr<r&rXr"newargs newkeywargsr9r!rWs r#r!z)_patch.decorate_callable..patched]s''(,(022 55Kg{tW4 44 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5s 155r0rr,rrWr9r!s``@r#rz_patch.decorate_callableWsv 4 % %  N ! !$ ' ' 'K t 5 5 5 5 5 5  5 "Fr"ctdrjStfdg_S)NrcK||5\}}|i|d{VcdddS#1swxYwYdSr<r)r*s r#r!z/_patch.decorate_async_callable..patchedns''(,(022 ;5Kg{!T7:k:::::::: ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;s 9==r-r.s``@r#rz_patch.decorate_async_callablehsv 4 % %  N ! !$ ' ' 'K t ; ; ; ; ; ;  ; "Fr"c`|}|j}t}d} |j|}d}n-#tt f$rt ||t}YnwxYw|tvrt|trd|_ |j s|turt |d|||fS)NFTz does not have the attribute ) rrirrrrLKeyErrorr1 _builtinsr/rr)rWtargetr*r|locals r# get_originalz_patch.get_originalys~ t,HEE) 6 6 6vtW55HHH 6 9  FJ!?!? DK{ x722 7=vvttD s 6'A A c |j|j|j}}}|j|j}}|j}||_|durd}|durd}|durd}||td|||dvrtd| \}}|tur|d} |dur |}|dur|}d}n| |dur|}d}n|dur|}||/|turtdt|trd} |t|rt} nt} i} ||} nN||J|} ||} t!| rd| v} nt#|  } t| rt} n | rt$} ||| d <||| d <t| tr&t'| t(r|jr |j| d <| || di| }| r_t/|rP|} ||} t!| st1| st$} | d | d|d d | |_n||turtd|turtdt7|}|dur|}t/|jr#t9d|jd|jd|dt/|rAt;|jd|j}t9d|jd|d|jd|d t=|f||jd|}n|rtd|}||_||_ tCj"|_# tI|j|j||j%ci}|jtur |||j%<|j&D]?}|j#'|}|jtur||@|S|S#|j(tSj*sYdSxYw)zPerform the patch.FNzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=TruerKrrr*r/r0zBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=Truer[z: as the patch target has already been mocked out. [target=r^r%rr\r])r_namez.Can't pass kwargs to a mock we aren't creatingr!)+r rrr rYrrr4rr6rr/r>r6r rror8r r=r rir r.rurQrboolrr1r temp_originalis_localrr _exit_stackrgrr r__exit__sysexc_info)rWr rrr rYrr|r5inheritKlass_kwargs this_spec not_callableranew_attrr#r%rRs r# __enter__z_patch.__enter__s"h 4=8T=$+&( kkmm  5==D u  H u  H   4=>> >  !5 L ( (TUU U++--% '>>h.Gt||t##'HD!t###HDT!!#8#7w&&#$GHHHh--#"G| h 7 7|!!G'$!X%9 ' (II&&;#-Y#>LL'/ ':':#:L ++1%EE!10E"&#&. #5$'' 15/22 17;~ 1"&. NN6 " " "%""'""C 4,S11 4! ' (I ++1&y1110E F####(5$4SD$4$4+2$4$4  !'!!(7"" GHHHH~~H4# -- D&CDNCC#{CC5=CCCDDD!** D%dk:t{KK &CDNCC"CC#{CC5=CCCDDD "(BX(,BB:@BBCC  NLMM M% %/11  DK : : :". 8w&&7:Jt23 $ 8//H*88BBC|w.."))#...!!J  4=#,..1    sBOOO<ch|jr/|jtur!t|j|j|jndt |j|j|jsCt|j|jr |jdvr t|j|j|j|`|`|`|j }|` |j |S)zUndo the patch.)r rre__annotations__rf) r;r:rrgr4rirrr0r<r=)rWr?r$s r#r=z_patch.__exit__#s = IT/w>> DK1C D D D D DK 0 0 0; I T^(L(L I+=== T^T5GHHH   M K%  "z"H--r"cb|}|j||Sz-Activate a patch, returning any created mock.)rF_active_patchesr,rWr}s r#startz _patch.start8s-!! ##D))) r"c |j|n#t$rYdSwxYw|dddSzStop an active patch.N)rKrrNr=rs r#stopz _patch.stop?s[   ' ' - - - -   44 }}T4...s  ++)rrrrrKrHrrKrrcontextmanagerr&rrr6rFr=rMrPr!r"r#rrsNOAF"&"&"&"&"&J   ,,,    # # #""0PPPd...*/////r"rc |dd\}}n-#tttf$rtd|wxYwt t j||fS)NrIrz,Need a valid target to patch. You supplied: )rsplitrrNrLrpkgutil resolve_name)r4ris r# _get_targetrVKsG"MM#q11 z> 2GGG E6 E EGG GG 7' 0 0) ;;s *Arc tturtdfd} t| |||||||| | S)a patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. z3 must be the actual object to be patched, not a strcSr<r!r4sr#rLz_patch_object..jsVr"r)r>strrr) r4rir rrrr rrrYrs ` r# _patch_objectr[Tsn$ F||s L L L   ^^^F  3f(L&   r"c tturttj}nfd}|st dt |}|d\} } t|| | |||||i } | | _ |ddD]=\} } t|| | |||||i } | | _ | j | >| S)aPerform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. cSr<r!rYsr#rLz!_patch_multiple..sr"z=Must supply at least one keyword argument with patch.multiplerrN) r>rZrrTrUrNrmrOrrr r,) r4rrrr rrYrrOrir r this_patchers ` r#_patch_multipler_qs , F||s-v66   K     E1XNIs 3fh,G'G)99 3 IsD&( lB  '0 ##**<8888 Nr"c Xt|\} } t| | |||||||| S)a: `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with an `AsyncMock if the patched object is an async function or a `MagicMock` otherwise. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `AsyncMock` is used for async functions and `MagicMock` for the rest. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. Patch will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `patch` takes arbitrary keyword arguments. These will be passed to `AsyncMock` if the patched object is asynchronous, to `MagicMock` otherwise or to `new_callable` if specified. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. r)rVr) r4r rrrr rrrYrris r#rrsDV$F++FI  3f(L&   r"cVeZdZdZddZdZdZdZdZd Z d Z d Z d Z d Z dZdS) _patch_dicta# Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. r!Fc ||_t||_|j|||_d|_dSr<)in_dictdictrBr clear _original)rWrdrBrfrYs r#rHz_patch_dict.__init__s> 6ll  6""" r"ct|tr||Stj|r||S||Sr<r)rWfs r#rKz_patch_dict.__call__sc a   *&&q)) )  &q ) ) 3//22 2%%a(((r"c@tfd}|S)Nc |i|S#wxYwr<rb _unpatch_dictrXrrirWs r#_innerz-_patch_dict.decorate_callable.._inner#sV       %q$~"~~""$$$$""$$$$s 3A rrWriros`` r#rz_patch_dict.decorate_callable"9 q % % % % %  % r"c@tfd}|S)NcK |i|d{V S#wxYwr<rlrns r#roz3_patch_dict.decorate_async_callable.._inner/so       %Q^^^+++++++""$$$$""$$$$s <Arprqs`` r#rz#_patch_dict.decorate_async_callable.rrr"c t|D]}}t||}|tjrLt |dr"/ ==DL,  -||~~HH - - -H - - '   - -  - "  !   + NN6 " " " " " + + + + +%c{  + + + +s$A$$BBB66CCc|j}|j}t| ||dS#t$r|D] }||||<YdSwxYwr<)rdrgrzr rL)rWrdr|rMs r#rmz_patch_dict._unpatch_dictgs,>G - NN8 $ $ $ $ $ - - - - -'}  - - - -s6AAc<|j|dS)zUnpatch the dict.NF)rgrm)rWrXs r#r=z_patch_dict.__exit__ts! > %    ur"cl|}tj||SrJ)rFrrKr,rLs r#rMz_patch_dict.start{s-!!%%d+++ r"c tj|n#t$rYdSwxYw|dddSrO)rrKrrNr=rs r#rPz_patch_dict.stops[   " ) )$ / / / /   44 }}T4...s " 00N)r!F)rrrr rHrKrrrrFrbrmr=rMrPr!r"r#rbrbs8)))       +++8 - - -/////r"rbc |dS#t$rt|}|D]}||=YdSwxYwr<)rfrLrm)rdkeysrMs r#rzrzse  G}}  C    s !==cfttjD]}|dS)z7Stop all active patches. LIFO to unroll nested patches.N)rcrrKrP)rs r#_patch_stopallrs5&011 r"testzlt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod rdivmod neg pos abs invert complex int float index round trunc floor ceil bool next fspath aiter zDadd sub mul matmul truediv floordiv mod lshift rshift and xor or pow c# K|] }d|zV dS)zi%sNr!r)ns r#rrs&77519777777r"c# K|] }d|zV dS)zr%sNr!rs r#rrs&55q555555r">rx__get____set__r __delete__ __format__r __missing__ __getstate__ __reversed__ __setstate__ __getformat__ __reduce_ex____getnewargs____subclasses____getinitargs____getnewargs_ex__c fd}||_|S)z:Turns a callable object (like a mock) into a real functionc|g|Ri|Sr<r!)rWrXrr9s r#methodz_get_method..methods#tD&4&&&2&&&r")r)r*r9rs ` r#rrs('''''FO Mr"ch|]}d|zS)rr!)r)rs r#r+r+s*    Hv   r"> __aexit__ __anext__ __aenter__ __aiter__>__del__rrHr __prepare__r__instancecheck____subclasscheck__c6t|Sr<)rw__hash__rs r#rLrLsV__T22r"c6t|Sr<)rw__str__rs r#rLrLsFNN400r"c6t|Sr<)rw __sizeof__rs r#rLrLsv0066r"cxt|jd|dt|S)N/)r>rrirArs r#rLrLs;$t**"5^^8O8O8Q8Q^^TVW[T\T\^^r")rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r= __complex__ __float____bool__ __index__rcfd}|S)NcLjj}|tur|S|urdStSNT)__eq__rrNotImplemented)otherret_valrWs r#rz_get_eq..__eq__s1+0 ' ! !N 5==4r"r!)rWrs` r#_get_eqrs# Mr"cfd}|S)NcRjjturtS|urdStSNF)__ne__rrr)rrWs r#rz_get_ne..__ne__s, ; ) 8 8N 5==5r"r!)rWrs` r#_get_ners# Mr"cfd}|S)Ncjjj}|turtgSt|Sr<)__iter__rrrrrWs r#rz_get_iter..__iter__s1-2 g  88OG}}r"r!)rWrs` r# _get_iterr s# Or"cfd}|S)Ncjj}|turtt gStt |Sr<)rrr_AsyncIteratorrrs r#rz"_get_async_iter..__aiter__s@.3 g  !$r((++ +d7mm,,,r"r!)rWrs` r#_get_async_iterrs$----- r")rrrrc&t|t}|tur ||_dSt|}|||}||_dSt |}||||_dSdSr<)_return_valuesrsrr_calculate_return_value_side_effect_methodsr)rDrr*fixedreturn_calculatorr side_effectors r#_set_return_valuer(s   tW - -E G#/33D99$((.. *(,,T22M *]400! r"ceZdZdZdZdS) MagicMixinc|tt|j|i||dSr<)_mock_set_magicsrrrHrWrXrs r#rHzMagicMixin.__init__;sN . J%%.;;;; r"c ttz}|}t|ddX||j}t }||z }|D](}|t |jvrt||)|t t |jz }t |}|D]!}t||t||"dS)Nr)) _magicsrr1 intersectionr)ryr>rrrrg MagicProxy)rW orig_magics these_magics remove_magicsrKrs r#rzMagicMixin._mock_set_magicsAs 44 " 4$ / / ;&33D4FGGLEEM',6M& ) )DJJ///D%((($c$t***=&>&>> T ! ; ;E E5*UD"9"9 : : : : ; ;r"N)rrrrHrr!r"r#rr:s2   ;;;;;r"rceZdZdZddZdS)r z-A version of `MagicMock` that isn't callable.FcZ||||dSr!rrr"s r#r#z"NonCallableMagicMock.mock_add_spec[2 D(+++ r"Nrrrrr r#r!r"r#r r Ys.77      r"r ceZdZdZdS)AsyncMagicMixinc|tt|j|i||dSr<)rrrrHrs r#rHzAsyncMagicMixin.__init__fsN 3 OT**3T@R@@@ r"NrrrrHr!r"r#rres#     r"rceZdZdZddZdS)ra MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. FcZ||||dSr!rr"s r#r#zMagicMock.mock_add_specvrr"Nrrr!r"r#rrks2        r"rc"eZdZdZdZddZdS)rc"||_||_dSr<r*r)rWr*rs r#rHzMagicProxy.__init__s  r"c|j}|j}||||}t|||t ||||S)N)r*rr)r*rr1rgr)rWrKrms r# create_mockzMagicProxy.create_mocksZ   " "/5 # 7 7q!!!&!U+++r"Nc*|Sr<)r)rWr5rs r#rzMagicProxy.__get__s!!!r"r<)rrrrHrrr!r"r#rrsF""""""r"rceZdZedZedZedZfdZdZdZ dZ dZ d Z d Z dd Zd ZfdZxZS)rrrrctj|i|tjj|jd<d|jd<d|jd<t |jd<tt}tj tj ztj z|_ d|_d|_d|_d|_||jd<d |jd <t%|jd <i|jd <d|jd <dS)Nrr_mock_await_count_mock_await_args_mock_await_args_listr)rXrYr8r rrerfrH)superrHrrrrrrr rr2 CO_COROUTINE CO_VARARGSCO_VARKEYWORDSco_flags co_argcount co_varnamesco_posonlyargcountco_kwonlyargcountrn)rWrXrY code_mockr6s r#rHzAsyncMockMixin.__init__s$)&)))*1);)I o&-. )*,0 ()1: -.#X666    !$ %  !"  2 '( $&' #$- j!$/ j!(- n%*, &'+/ '(((r"c`Kt||fd}|xjdz c_||_|j||j}|t |r|t|s8 t|}n#t$rtwxYwt |r|n&t|r||i|d{V}n||i|}|tur|S|j tur|jS|j4t|jr|j|i|d{VS|j|i|S|jS)NTrr)rrrrr,rrArkr StopIterationStopAsyncIterationrrrrr)rWrXrYrrr}s r#rz!AsyncMockMixin._execute_mock_callstVn$/// A ##E***!  V$$ 1 v&& 1-!&\\FF$----,-!((! L!$V,, 1%vt6v66666666000W$$  "' 1 1$ $   '"4#344 ?-T-t>v>>>>>>>>>#4#T4V44 4  s 1BBcT|jdkrd|jpdd}t|dS)zA Assert that the mock was awaited at least once. r Expected rDz to have been awaited.Nrrrrs r#rzAsyncMockMixin.assert_awaiteds?  q Odo7OOOC %% % ! r"cd|jdks$d|jpdd|jd}t|dS)z@ Assert that the mock was awaited exactly once. rrrD$ to have been awaited once. Awaited rNrrs r#rz"AsyncMockMixin.assert_awaited_oncesW1$$9t8&99#/999C %% %%$r"chj)}td|dfd}t fd}j}||kr1t |t r|nd}t||dS)zN Assert that the last await was with the specified arguments. NzExpected await: z Not awaitedc8d}|S)Nawait)rrrs r#rz:AsyncMockMixin.assert_awaited_with.._error_messages"33D&3QQCJr"Tr)rrrrrr/r)rWrXrYrrrrs``` r#rz"AsyncMockMixin.assert_awaited_withs ? "77fEEH !KH!K!K!KLL L       %%eT6N&E&E&EFF##DO44 X   *8Y ? ?IHHTE !1!122 =  r"cz|jdks$d|jpdd|jd}t||j|i|S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrrDr r)rrrrrs r#rz'AsyncMockMixin.assert_awaited_once_withsg 1$$9t8&99#/999C %% %'t'8888r"c$t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)zU Assert the mock has ever been awaited with the specified arguments. TrNc:g|]}|Sr!rrs r#rrz3AsyncMockMixin.assert_any_await.. s'FFFA$$$Q''FFFr"z%s await not found)rrr/rrrrrrs` r#rzAsyncMockMixin.assert_any_await s%%eT6N&E&E&EFF&x;;EFFFF1EFFF  HL$8$888">>tVLLO $6 98r"Fc*fd|D}td|Dd}tfdjD}|sT||vrN|d}ndd|D}t |dt|d j|dSt |}g}|D]=} ||#t$r||Y:wxYw|r t t|d |dS) a Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be sequential. There can be extra calls before or after the specified awaits. If `any_order` is True then the awaits can be in any order, but they must all appear in :attr:`await_args_list`. c:g|]}|Sr!rrs r#rrz4AsyncMockMixin.assert_has_awaits..# rr"c3DK|]}t|t|VdSr<rrts r#rz3AsyncMockMixin.assert_has_awaits..$ rr"Nc3BK|]}|VdSr<rrs r#rz3AsyncMockMixin.assert_has_awaits..% s1SSt11!44SSSSSSr"zAwaits not found.z,Error processing expected awaits. Errors: {}c@g|]}t|tr|ndSr<rrts r#rrz4AsyncMockMixin.assert_has_awaits..- rr"rz Actual: z not all found in await list) rrrrrrmrrNr,rn) rWrrrr all_awaitsrrrs ` r#rz AsyncMockMixin.assert_has_awaits s:9995999FFFFFMMSSSSd>RSSSSS  z))=1GG ,-3V$7$7-5$7$7$7.8.8%66!*5!1!166#366  F*%%   ' 'D '!!$'''' ' ' '  &&&&& '   49)4D4D4D4DF   s6C  C.-C.cd|jdkr$d|jpdd|jd}t|dS)z9 Assert that the mock was never awaited. rrrDz# to not have been awaited. Awaited rNrrs r#rz!AsyncMockMixin.assert_not_awaitedC sW  q 9t8&99#/999C %% % ! r"c|tj|i|d|_d|_t |_dS)z0 See :func:`.Mock.reset_mock()` rN)rrrrrr)rWrXrYr6s r#rzAsyncMockMixin.reset_mockL sB D+F+++({{r"r)rrrrrrrrHrrrrrrrrr __classcell__)r6s@r#rrs&&}55K%%l33J**+<==O000008&!&!&!P&&&&&&>>>$ 9 9 9   ****X&&&+++++++++r"rceZdZdZdS)r aY Enhance :class:`Mock` with features allowing to mock an async function. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable: >>> mock = AsyncMock() >>> iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) True The result of ``mock()`` is an async function which will have the outcome of ``side_effect`` or ``return_value``: - if ``side_effect`` is a function, the async function will return the result of that function, - if ``side_effect`` is an exception, the async function will raise the exception, - if ``side_effect`` is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, ``StopIteration`` is raised immediately, - if ``side_effect`` is not defined, the async function will return the value defined by ``return_value``, hence, by default, the async function returns a new :class:`AsyncMock` object. If the outcome of ``side_effect`` or ``return_value`` is an async function, the mock async function obtained when the mock object is called will be this async function itself (and not an async function returning an async function). The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`Mock` object behavior is the same as with an :class:`.Mock` object: the wrapped object may have methods defined as async function functions. Based on Martin Richard's asynctest project. Nrr!r"r#r r V s''''r"r c$eZdZdZdZdZdZdS)_ANYz2A helper object that compares equal to everything.cdSrr!rWrs r#rz _ANY.__eq__ str"cdSrr!rs r#rz _ANY.__ne__ sur"cdS)Nzr!rs r#rz _ANY.__repr__ swr"N)rrrr rrrr!r"r#rr sG88r"rcd|z}d}dd|D}dd|D}|r|}|r |r|dz }||z }||zS)Nz%s(%%s)r z, c,g|]}t|Sr!)repr)r)rRs r#rrz*_format_call_signature.. s7773T#YY777r"c"g|] \}}|d| S)=r!)r)rMrs r#rrz*_format_call_signature.. s4#-3333r")rdrO)r*rXrYrformatted_args args_string kwargs_strings r#rr s$GN))77$77788KII17M%$(  # d "N-' ^ ##r"ceZdZdZ ddZ ddZd ZejZd Z d Z d Z d Z e dZe dZdZdZdS)ra A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to a tuple without those values. This makes comparisons less verbose:: _Call(('name', (), {})) == ('name',) _Call(('name', (1,), {})) == ('name', (1,)) _Call(((), {'a': 'b'})) == ({'a': 'b'},) The `_Call` object provides a useful shortcut for comparing with call:: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) If the _Call has no name then it will match any name. r!r NFTcd}i}t|}|dkr|\}}}n~|dkr<|\} } t| tr| }t| tr| }nD| }nA| | }}n<|dkr6|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nr!rr)rr/rZrnr) rrr*rr from_kallrXrY_lenfirstseconds r#rz _Call.__new__ s5zz 199!& D$ QYY!ME6%%% -fe,,$!DD#FF$ff QYYFE%%% E5))   6==tVn55 5}}S4v"6777r"c0||_||_||_dSr<)rr_mock_from_kall)rWrr*rrr+s r#rHz_Call.__init__ s"(r"cr t|}n#t$r tcYSwxYwd}t|dkr|\}}n|\}}}t|ddr#t|ddr|j|jkrdSd}|dkrdi}}n|dkr|\}}}n|dkr?|\} t | t r| }i}nit | tr| }di}}nMd}| }nH|dkr@|\} } t | tr!| }t | t r| i}}n d| }}n| | }}ndS|r||krdS||f||fkS) Nr rrFrr!r*r)rrrr1rr/rnrZ) rWr len_other self_name self_args self_kwargs other_name other_args other_kwargsrr-r.s r#rz _Call.__eq__ s "E II " " "! ! ! ! " t99>>%) "I{{04 -Iy+ D.$ / / GE>SW4X4X %);;;5 >>')2 JJ !^^38 0J LL !^^FE%'' %" ! E3'' %" +-rL  $ !^^!ME6%%% 9" fe,,:/5r JJ/16 JJ+0&L 5  y005L)i-EEEs &&c|jtd||fdS|jdz}t|j||f||S)Nr r/rrrrrs r#rKz_Call.__call__ sN ? ""dF+$777 7%dotV44MMMMr"cn|jt|dS|jd|}t||dS)NF)r*r+rI)r*rr+r:)rWrr*s r#rz_Call.__getattr__ sD ? "de444 4///440$tu====r"cb|tjvrtt||Sr<)rnrrrL__getattribute__)rWrs r#r=z_Call.__getattribute__$ s+ 5> ! ! %%dD111r"cHt|dkr|\}}n|\}}}||fS)Nr)rrs r#_get_call_argumentsz_Call._get_call_arguments* s2 t99>>LD&&!% D$V|r"c6|dSNrr?rs r#rXz _Call.args2 ''))!,,r"c6|dS)NrrBrs r#rYz _Call.kwargs6 rCr"c|js%|jpd}|drd|z}|St|dkrd}|\}}n+|\}}}|sd}n |dsd|z}nd|z}t |||S)Nrr/zcall%srzcall.%s)r0rr(rr)rWr*rXrYs r#rz_Call.__repr__: s# ?,fDt$$ '$K t99>>DLD&&!% D$ '__T** ' 4'$%dD&999r"cg}|}|%|jr|||j}|%tt |S)zFor a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.)r0r,rrrc)rWvalsthings r# call_listz_Call.call_listO sW$ # E"""&E$(((r")r!r NFT)r!NNFT)rrrr rrHrrwrrKrr=r?rrXrYrrIr!r"r#rr s$:?8888@>C))))2F2F2Fj]FNNN>>>222 --X---X-:::* ) ) ) ) )r"r)r+c $t|rt|}t|t}t|rt d|dt |}d|i} |rd|i} n|i} | r|rd| d<|st || |t} tj |ri} nL|r|rtdt} n1t|st} n|r|rt|st} | d |}|} |d } | d||| |d | } t|t"r"t%| |} |rt'| nt)|| ||| |s | |j|<|d } |r |sd |vrt/||dd| | | _t3|D];}t5|r t7||}n#t8$rY1wxYwd|i}| r&t;| |r|||rd|i}t|t"st=||| ||}|| j|<n{| }t|t"r| j}tA|||}||d<tC|rt}nt}|d||||d|}|| j|<t)|||t|t"rtE| ||=| S)aCreate a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.z'Cannot autospec a Mock object. [object=r%rrNTrzJInstance can not be True when create_autospec is mocking an async functionr*r )rrrr*rrr/)rar8rrrpr)rr*rr)r`r!)#ror>r/r.rr:rr rr2isdatadescriptorrr rkr rurQrErrrbrrsr rr+rr1rLr0rCrD _must_skiprrg)rrrarr8rrYis_type is_async_funcrBrArrDwrappedrKr|r rr` child_klasss r#r r _ s.~~Dzzt$$G5 4*. 4 4 455 5"4((MtnGt$ ,8,'+#$ &f%%% NN6 E%% % %  ? >?? ? t__%$ %X%&8&>&>%$ KK & &EI 5 (W  ( (& ( (D$ &&8dD))  $ d # # #tWh7778(,u%jj!!G;x;N&$@$@+D(T2629;;;T3&3& U     tU++HH    H (#  *ww.. * MMM ) ) )  , (+F(M22 AXxuhGGC),D  & &F$ .. #"488I"+F; "8,, (' ' +(V%5*0(( &((C*-D  & Xsi @ @ @ @ c= ) ) & D% % % % Ks'G88 HHcDt|ts|t|divrdS|j}|jD]f}|j|t}|tur,t|ttfrdSt|tr|cSdS|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. rrF) r/r>r1r6rqrrrsrrJrIrE)rrKrMrr}s r#rLrL s dD ! ! GD*b11 1 15~  ##E733 W    f|[9 : : 55  . . NNN55 Nr"ceZdZ ddZdS)rCFNcZ||_||_||_||_||_||_dSr<)ridsrrrar*)rWrrrr*rTras r#rHz_SpecState.__init__ s0       r")FNNNFrr!r"r#rCrC s.48/4r"rCc|t|trtj|Stj|Sr<)r/bytesioBytesIOStringIO) read_datas r# _to_streamr[% s4)U##&z)$$${9%%%r"r c V t}|dg fd} fd} fd fd fd}tdddl}tt t |jt t |jat2ddl}tt t |j a |tdt }tt  j _ d j_ d j_ d j_ d j_ | j_ d < d  j_| j_ j_| j_ fd }||_ |_ |S) a A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. NcZjj jjSdj|i|SrA) readlinesrrXrY_statehandles r#_readlines_side_effectz)mock_open.._readlines_side_effect; s7   ( 4#0 0"vay"D3F333r"cZjj jjSdj|i|SrA)readrr_s r#_read_side_effectz$mock_open.._read_side_effect@ s4 ; # /;+ +vay~t.v...r"c?VKEd{V dj|i|VNTr)readline)rXrY_iter_side_effectr`s r#_readline_side_effectz(mock_open.._readline_side_effectE sT$$&&&&&&&&& 6$&)$d5f55 5 5 5 6r"c3bKjj jjVdD]}|VdSrg)rhr)liner`ras r#riz$mock_open.._iter_side_effectJ sU ? ' 3 3o2222 31I  DJJJJ  r"c^jj jjStdSrA)rhrr)r`rasr#_next_side_effectz$mock_open.._next_side_effectQ s) ? ' 3?/ /F1Ir"ropen)r*r)rrctd<jjdkrd<dj_tS)Nrr)r[rhrr)rXrYrjr`rarZs r# reset_datazmock_open..reset_dataq sMy))q ? &&) 3 3--//F1I*0)FO 'r")r[ file_spec_iormryr+ TextIOWrapperunionrX open_specrorrFrwriterdrhr^rrr) rDrZ _read_datarbrernrsrqrirjr`ras ` @@@@r#rr, sI&&J$ F444444 ////// 666666   S!23344::3s3;?O?O;P;PQQRR  S]]++,,  |f9555 I & & &F$*F! $FL#FK#'FO $(F!/FK%%''F1I"()FO#9F "3FO"3FO"DD Kr"c&eZdZdZdZddZdZdS)raW A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. Fetching a `PropertyMock` instance from an object calls the mock, with no args. Setting it calls the mock with the value being set. c tdi|S)Nr!)r)rWrYs r#r1zPropertyMock._get_child_mock s""6"""r"Nc|Sr<r!)rWr5obj_types r#rzPropertyMock.__get__ s tvv r"c||dSr<r!)rWr5rSs r#rzPropertyMock.__set__ s S r"r<)rrrr r1rrr!r"r#rr~ sP###r"rc4d|_t|D]} t||}n#t$rY wxYwt |t s:t |j|trh|j |urt|dS)aDisable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. The operation recursively seals the mock passed in, meaning that the mock itself, any mocks generated by accessing one of its attributes, and all assigned mocks without a name or spec will be sealed. TN) r r+r1rLr/r rrsrCrr)rDrrs r#rr sDD   d##AA    H !_--   a&**400* = =    % % GGG  s + 88ceZdZdZdZdZdS)rz8 Wraps an iterator in an asynchronous iterator. ct||_tt}tj|_||jd<dS)Nrr8)iteratorr rr2CO_ITERABLE_COROUTINErrr)rWrrs r#rHz_AsyncIterator.__init__ s6  #X666 $: $- j!!!r"c^K t|jS#t$rYnwxYwtr<)rrrrrs r#rz_AsyncIterator.__anext__ sA  && &    D   s  %%N)rrrr rHrr!r"r#rr s<... !!!!!r"rr)NFNNN)FFNN)Nr )__all__rrrWr2rr>builtinsrTrtypesrrr unittest.utilr functoolsrr threadingrrrr+r3r rrr6r:r.rArFrRrbr]rkrorurr{rrrwrrrrMISSINGrDELETEDrDrrrmrrrrr rMrHrrr=rrrrrVr[r_rrbrzrremultiplestopallr magic_methodsnumericsrdrPinplaceright _non_defaultsrrr_sync_async_magics _async_magicsrr_rrrrrrrrrrrr rrrrr rrrrnrrr rLrCr>rrErrrvr[rrrrr!r"r#rs5  &  ''''''2222222222######$$$$$$$$CCCCCyCCC I Hcc(mm H H H   @@@222    F # # # #   &&&   6."."."b>>>6))) ) ) ) ) )f ) ) )         9;;         &********(6      6   N <N <N <N <N       :         j        D   ,""""""""$@+@+@+@+@+T@+@+@+F((((((((V     6    dff$$$$v)v)v)v)v)Ev)v)v)r uuCGO*/OOOOOd8         DD     &&&OOOOd4$0!!!!!!!!!!r"__pycache__/async_case.cpython-311.pyc000064400000015511151030032340013560 0ustar00 !A?hYNddlZddlZddlZddlZddlmZGddeZdS)N)TestCaseceZdZdfd ZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdfd ZfdZdZxZS)IsolatedAsyncioTestCaserunTestct|d|_tj|_dSN)super__init___asyncioRunner contextvars copy_context_asyncioTestContext)self methodName __class__s ,/usr/lib64/python3.11/unittest/async_case.pyr z IsolatedAsyncioTestCase.__init__#s: $$$"#.#;#=#=   c KdSr rs r asyncSetUpz"IsolatedAsyncioTestCase.asyncSetUp(  rc KdSr rrs r asyncTearDownz%IsolatedAsyncioTestCase.asyncTearDown+rrc(|j|g|Ri|dSr ) addCleanuprfuncargskwargss raddAsyncCleanupz'IsolatedAsyncioTestCase.addAsyncCleanup.s) $1&11111rcKt|} |j}|j}n/#t$r"t d|jd|jddwxYw||d{V}|||ddd|S)zEnters the supplied asynchronous context manager. If successful, also adds its __aexit__ method as a cleanup function and returns the result of the __aenter__ method. '.zC' object does not support the asynchronous context manager protocolN)type __aenter__ __aexit__AttributeError TypeError __module__ __qualname__r")rcmclsenterexitresults renterAsyncContextz)IsolatedAsyncioTestCase.enterAsyncContext=s2hh 'NE=DD ' ' 'UUU1AUUU"& ' 'uRyy T2tT4888 s ",Ac|j|j|j||jdSr )r get_looprrunsetUp _callAsyncrrs r _callSetUpz"IsolatedAsyncioTestCase._callSetUpQsL $$&&&  $$TZ000 (((((rct||"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case ()) stacklevel)_callMaybeAsyncwarningswarnDeprecationWarning)rmethods r_callTestMethodz'IsolatedAsyncioTestCase._callTestMethodYsd    ' ' 3 M2(.2223ERS U U U U U U 4 3rcx||j|j|jdSr )r7rrr5tearDownrs r _callTearDownz%IsolatedAsyncioTestCase._callTearDown^s6 *+++  $$T]33333rc(|j|g|Ri|dSr )r=)rfunctionr r!s r _callCleanupz$IsolatedAsyncioTestCase._callCleanupbs+X777777777rc|j Jdtj|s J|d|j||i||jS)N!asyncio runner is not initializedz is not an async functioncontextr inspectiscoroutinefunctionr5rrs rr7z"IsolatedAsyncioTestCase._callAsyncesz"..0S...*400VVT2V2V2VVV0"&& D$ !& ! !,'   rc|j Jdtj|r'|j||i||jS|jj|g|Ri|S)NrJrKrMrs rr=z'IsolatedAsyncioTestCase._callMaybeAsyncms"..0S...  &t , , G&**d%f%%0+  04+/FtFFFvFF Frc`|j Jdtjd}||_dS)Nz%asyncio runner is already initializedT)debug)r asyncioRunnerrrunners r_setupAsyncioRunnerz+IsolatedAsyncioTestCase._setupAsyncioRunnerws:"**,S***d+++$rc<|j}|dSr )r closerUs r_tearDownAsyncioRunnerz.IsolatedAsyncioTestCase._tearDownAsyncioRunner|s$ rNc| t||S#|wxYwr )rWr r5rZ)rr1rs rr5zIsolatedAsyncioTestCase.runsZ   """ *77;;v&&  ' ' ) ) ) )D ' ' ) ) ) )s A A"c|t|dSr )rWr rRrZ)rrs rrRzIsolatedAsyncioTestCase.debugs>   """   ##%%%%%rc@|j|dSdSr )r rZrs r__del__zIsolatedAsyncioTestCase.__del__s+   *  ' ' ) ) ) ) ) + *r)rr )__name__r+r,r rrr"r2r8rBrErHr7r=rWrZr5rRr^ __classcell__)rs@rrr s=4>>>>>>        2 2 2()))UUU 444888   GGG%%% ******&&&&& *******rr)rSr rNr>caserrrrrrbs|E*E*E*E*E*hE*E*E*E*E*r__pycache__/async_case.cpython-311.opt-2.pyc000064400000014427151030032340014525 0ustar00 !A?hYNddlZddlZddlZddlZddlmZGddeZdS)N)TestCaseceZdZdfd ZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdfd ZfdZdZxZS)IsolatedAsyncioTestCaserunTestct|d|_tj|_dSN)super__init___asyncioRunner contextvars copy_context_asyncioTestContext)self methodName __class__s ,/usr/lib64/python3.11/unittest/async_case.pyr z IsolatedAsyncioTestCase.__init__#s: $$$"#.#;#=#=   c KdSr rs r asyncSetUpz"IsolatedAsyncioTestCase.asyncSetUp(  rc KdSr rrs r asyncTearDownz%IsolatedAsyncioTestCase.asyncTearDown+rrc(|j|g|Ri|dSr ) addCleanuprfuncargskwargss raddAsyncCleanupz'IsolatedAsyncioTestCase.addAsyncCleanup.s) $1&11111rcK t|} |j}|j}n/#t$r"t d|jd|jddwxYw||d{V}|||ddd|S)N'.zC' object does not support the asynchronous context manager protocol)type __aenter__ __aexit__AttributeError TypeError __module__ __qualname__r")rcmclsenterexitresults renterAsyncContextz)IsolatedAsyncioTestCase.enterAsyncContext=s 2hh 'NE=DD ' ' 'UUU1AUUU"& ' 'uRyy T2tT4888 s #,Ac|j|j|j||jdSr )r get_looprrunsetUp _callAsyncrrs r _callSetUpz"IsolatedAsyncioTestCase._callSetUpQsL $$&&&  $$TZ000 (((((rct||"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case ()) stacklevel)_callMaybeAsyncwarningswarnDeprecationWarning)rmethods r_callTestMethodz'IsolatedAsyncioTestCase._callTestMethodYsd    ' ' 3 M2(.2223ERS U U U U U U 4 3rcx||j|j|jdSr )r7rrr5tearDownrs r _callTearDownz%IsolatedAsyncioTestCase._callTearDown^s6 *+++  $$T]33333rc(|j|g|Ri|dSr )r=)rfunctionr r!s r _callCleanupz$IsolatedAsyncioTestCase._callCleanupbs+X777777777rcP|j||i||jSN)context)r r5rrs rr7z"IsolatedAsyncioTestCase._callAsynces<"&& D$ !& ! !,'   rctj|r'|j||i||jS|jj|g|Ri|SrJ)inspectiscoroutinefunctionr r5rrs rr=z'IsolatedAsyncioTestCase._callMaybeAsyncmsv  &t , , G&**d%f%%0+  04+/FtFFFvFF Frc>tjd}||_dS)NT)debug)asyncioRunnerr rrunners r_setupAsyncioRunnerz+IsolatedAsyncioTestCase._setupAsyncioRunnerws"d+++$rc<|j}|dSr )r closerSs r_tearDownAsyncioRunnerz.IsolatedAsyncioTestCase._tearDownAsyncioRunner|s$ rNc| t||S#|wxYwr )rUr r5rX)rr1rs rr5zIsolatedAsyncioTestCase.runsZ   """ *77;;v&&  ' ' ) ) ) )D ' ' ) ) ) )s A A"c|t|dSr )rUr rPrX)rrs rrPzIsolatedAsyncioTestCase.debugs>   """   ##%%%%%rc@|j|dSdSr )r rXrs r__del__zIsolatedAsyncioTestCase.__del__s+   *  ' ' ) ) ) ) ) + *r)rr )__name__r+r,r rrr"r2r8rBrErHr7r=rUrXr5rPr\ __classcell__)rs@rrr s=4>>>>>>        2 2 2()))UUU 444888   GGG%%% ******&&&&& *******rr)rQr rMr>caserrrrrr`s|E*E*E*E*E*hE*E*E*E*E*r__pycache__/mock.cpython-311.opt-2.pyc000064400000325271151030032340013350 0ustar00 !A?hH`dZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZddlmZmZddlmZGdd eZd eeDZd ZeZd Zd ZdZdZdZ dZ!dydZ"dZ#dZ$dZ%dZ&dydZ'dZ(dZ)dZ*Gdde+Z,Gdde+Z-e-Z.e.j/Z/e.j0Z1e.j2Z3hd Z4d!Z5Gd"d#e6Z7d$Z8Gd%d&e+Z9Gd'd(e+Z:Gd)d*e:Z;ej<e;j=Z>Gd+d,e6Z?d-Z@Gd.d/e:ZAGd0d1eAe;ZBd2ZCGd3d4e+ZDd5ZEe/dddddfdd6d7ZF dzd8ZGe/dddddfdd6d9ZHGd:d;e+ZId<ZJd=ZKeFeH_+eIeH_LeGeH_MeKeH_Nd>eH_Od?ZPd@ZQdARdBeQSDZTdARdCeQSDZUhdDZVdEZWdFdARePeQeTeUgSDZXhdGZYdHhZZeYeZzZ[eXeVzZ\e\e[zZ]hdIZ^dJdKdLdMdNZ_e`e`e`e`dOddddPdQd dOddR ZadSZbdTZcdUZddVZeebecedeedWZfdXZgGdYdZe:ZhGd[d\ehe;ZiGd]d^ehZjGd_d`eheBZkGdadbe:ZlGdcdde:ZmGdedfemejeBZnGdgdhe+ZoeoZpdiZqGdjdkerZsesdlZt d{dd6dmZudnZvGdodpe+ZwexeuexepjyfZzda{da|dqZ}d|dsZ~GdtdueBZdvZGdwdxZdS)})Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartial)RLockceZdZdS)InvalidSpecErrorN__name__ __module__ __qualname__&/usr/lib64/python3.11/unittest/mock.pyrr)sBBr!rc<h|]}|d|S_ startswith).0names r" r*-s) H H Hd4??33G3G HT H H Hr!Tct|rt|tsdSt|drt |d}t |pt j|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspect isawaitableobjs r" _is_async_objr55sgji&@&@usJ'c:&& s # # ?w':3'?'??r!cFt|ddrt|SdS)N__code__F)r0r)funcs r"_is_async_funcr9=s)tZ&&"4(((ur!cFtt|tSN) issubclasstyper r3s r"r-r-Ds d3ii 1 11r!ct|tp)t|tot|tSr;)r. BaseExceptionr=r<r3s r" _is_exceptionr@Js63 && A3@*S-"@"@r!c^t|trt|dr|jS|SNmock)r. FunctionTypesr/rCr3s r" _extract_mockrEQs3#}%%'#v*>*>x r!c t|tr |s |j}d}njt|ttfrt|trd}|j}n/t|t s |j}n#t$rYdSwxYw|rt|d}n|} |tj |fS#t$rYdSwxYwNT) r.r=__init__ classmethod staticmethodr,rD__call__AttributeErrorrr1 signature ValueError)r8 as_instanceeat_selfsig_funcs r"_get_signature_objectrRZs $k} D; 5 6 6  dK ( ( H} m , , =DD   44 4&&W&x0000 tts$4A<< B  B #B99 CCFct|||dS\}fd}t|||t|_t|_dS)Nc"j|i|dSr;bind)selfargskwargssigs r"checksigz"_check_signature..checksig $!&!!!!!r!)rR_copy_func_detailsr=_mock_check_sig __signature__)r8rC skipfirstinstancer[rZs @r"_check_signaturerb}sr h : :C {ID#"""""tX&&&!)DJJ"DJJr!c pdD]2} t||t||##t$rY/wxYwdS)N)r__doc____text_signature__r __defaults____kwdefaults__)setattrr0rL)r8funcopy attributes r"r]r]sa   GYi(@(@ A A A A    D  s & 33ct|trdSt|tttfrt |jSt|dddSdS)NTrKF)r.r=rJrIr _callabler,r0r3s r"rlrls^#tt# k:>??'&&&sJ%%1t 5r!c<t|ttfvSr;)r=listtupler3s r"_is_listrps 99u %%r!c t|tst|ddduS|f|jzD]}|jddS dS)NrKTF)r.r=r0__mro____dict__get)r4bases r"_instance_callablervsr@ c4 :sJ--T99$ =  Z ( ( 444 5 5r!c0 t|t}t|||}||S|\} fd}t|||j}|sd}||d}d|z} t | |||} t| | | S)Nc"j|i|dSr;rU)rXrYrZs r"r[z _set_signature..checksigr\r!ri) _checksig_rCzYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r.r=rRr]r isidentifierexec _setup_func) rCoriginalrar`resultr8r[r)contextsrcrirZs @r"_set_signaturers 8T**I "8Xy A AF ~ ID#"""""tX&&&  D     %t44G $&* +C #wdmGs### Nr!c_fd}fd}fd}fd}fd}fd}fd} fd} d _d _d_t _t _t _j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS) Ncj|i|Sr;)assert_called_withrXrYrCs r"rz'_setup_func..assert_called_with&t&7777r!cj|i|Sr;) assert_calledrs r"rz"_setup_func..assert_calleds!t!426222r!cj|i|Sr;)assert_not_calledrs r"rz&_setup_func..assert_not_calleds%t%t6v666r!cj|i|Sr;)assert_called_oncers r"rz'_setup_func..assert_called_oncerr!cj|i|Sr;)assert_called_once_withrs r"rz,_setup_func..assert_called_once_withs+t+T.assert_has_callss$t$d5f555r!cj|i|Sr;)assert_any_callrs r"rz$_setup_func..assert_any_calls#t#T4V444r!ct_t_j}t |r|ur|dSdSdSr;) _CallList method_calls mock_calls reset_mock return_valuer-)retrirCs r"rz_setup_func..reset_mockso({{&[[ " S ! ! #++ NN       ++r!Fr)rCcalled call_count call_argsrcall_args_listrrr side_effect_mock_childrenrrrrrrrrr__mock_delegate) rirCrZrrrrrrrrs `` r"r|r|sGL88888333337777788888=====6666655555GNGG&[[G$;;G"G,G*G!0G!3G&=G#/G-G#G)G 1G!3GG!Dr!c tjj_d_d_t _fd}dD]!}t|t||"dS)Nrc:tj||i|Sr;)r0rC)attrrXrYrCs r"wrapperz"_setup_async_mock..wrapper s$'wty$''8888r!)assert_awaitedassert_awaited_onceassert_awaited_withassert_awaited_once_withassert_any_awaitassert_has_awaitsassert_not_awaited) asyncio coroutines _is_coroutine await_count await_argsrawait_args_listrhr)rCrrjs` r"_setup_async_mockrs +9DDDO$;;D 99999, > >  i)! >r!c$d|ddz|kS)N__%s__r r)s r" _is_magicrs d1R4j D ((r!c"eZdZ dZdZdZdS)_SentinelObjectc||_dSr;rrWr)s r"rHz_SentinelObject.__init__"s  r!cd|jzSNz sentinel.%srrWs r"__repr__z_SentinelObject.__repr__%ty((r!cd|jzSrrrs r" __reduce__z_SentinelObject.__reduce__(rr!N)rrrrHrrr r!r"rr sD'))))))))r!rc"eZdZ dZdZdZdS) _Sentinelci|_dSr;) _sentinelsrs r"rHz_Sentinel.__init__.s r!cl|dkrt|j|t|S)N __bases__)rLr setdefaultrrs r" __getattr__z_Sentinel.__getattr__1s3 ;   ))$0E0EFFFr!cdS)Nrr rs r"rz_Sentinel.__reduce__7szr!N)rrrrHrrr r!r"rr,sGKGGG r!r> _mock_namer _mock_parentr_mock_new_name_mock_new_parent_mock_side_effect_mock_return_valuecxt|d|z}||fd}||fd}t||S)N_mock_cT|j}|t||St||Sr;)rr0)rWr) _the_namerZs r"_getz"_delegating_property.._getLs/! ;4++ +sD!!!r!cR|j}| ||j|<dSt|||dSr;)rrsrh)rWvaluer)rrZs r"_setz"_delegating_property.._setQs9! ;',DM) $ $ $ Cu % % % % %r!)_allowed_namesaddproperty)r)rrrs r"_delegating_propertyrIset4I """" $y&&&& D$  r!ceZdZdZdZdS)rct|tst||St|}t|}||krdSt d||z dzD]}||||z}||krdSdS)NFrT)r.rn __contains__lenrange)rWr len_valuelen_selfisub_lists r"rz_CallList.__contains__^s%&& 2$$T511 1JJ t99 x  5q(Y.233  AAa kM*H5  tt!ur!cDtjt|Sr;)pprintpformatrnrs r"rz_CallList.__repr__ls~d4jj)))r!N)rrrrrr r!r"rr\s2   *****r!rct|}t|sdS|js|js|j|jdS|}|||urdS|j}||r||_||_|r||_||_dS)NFT)rEr-rrrr)parentrr)new_name_parents r"_check_and_set_parentrps % E U # #u  U1   '   +uG   e  5*  (!''  # 4r!ceZdZdZdZdS) _MockIterc.t||_dSr;)iterr4)rWr4s r"rHz_MockIter.__init__s99r!c*t|jSr;)nextr4rs r"__next__z_MockIter.__next__sDH~~r!N)rrrrHrr r!r"rrs2r!rceZdZeZdZdZdS)BaseNcdSr;r rWrXrYs r"rHz Base.__init__s r!)rrrrrrrHr r!r"rrs/      r!rceZdZ eZdZ d,dZdZd-dZ d.dZ d Z d Z d Z e e e e Ze d Zed ZedZedZedZedZdZdZe eeZd/ddddZdZdZdZdZdZdZdZ dZ!d0dZ"d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d-d'Z*d(Z+d)Z,d1d+Z-dS)2r cz|f}t|ts]tj|g|Ri|j}|d|d}|t |r t|f}t|j|d|j i}tt| |}|S)Nspec_setspecrd) r<AsyncMockMixin _MOCK_SIG bind_partial argumentsrtr5r=rrd _safe_superr __new__)clsrXkwbases bound_argsspec_argnewras r"rzNonCallableMock.__new__s#~.. ."/AdAAAbAAKJ!~~j*..2H2HIIH# h(?(?#'-3<CK(@AA44<>d.6&& D'C!$D  r!cb|j||j_dS||_t||dddS)Nr0)rrrr)rWrs r"__set_return_valuez"NonCallableMock.__set_return_value%s>   */4D  , , ,&+D # !$tT : : : : :r!z1The value to be returned when the mock is called.c<|jt|S|jSr;)r'r=rs r" __class__zNonCallableMock.__class__1s   #:: r!rrrrrc|j}||jS|j}|It|s:t |t s%t |st |}||_|Sr;)rrrcallabler.rr@)rW delegatedsfs r"__get_side_effectz!NonCallableMock.__get_side_effect>sj'  ) )  " N8B<z0NonCallableMock.configure_mock..sq1D1Dr!)keyrJ)sorteditemssplitpopr0rh)rWrYargvalrXfinalr4rLs r"rzNonCallableMock.configure_mockrs ,v||~~$E#D FFF % %HC 99S>>DHHJJEC * *c5)) C $ $ $ $ % %r!c |dvrt||j%||jvs |tvrtd|znt|rt||js:|jr ||jvr*|drt|d|dt j5|j |}|turt||Cd}|j t|j |}| |||||}||j|<nt|trv t!|j|j|j|j|j}n>#t,$r1|jdp|}t-d|d |d |d |jd wxYw||j|<dddn #1swxYwY|S) N>rr*zMock object has no attribute %r)assertassretasertaseertassrtz6 is not a valid assertion. Use a spec for the mock if z is meant to be an attribute.)rr)rrrrCannot autospec attr from target , as it has already been mocked out. [target=, attr=r&)rLr* _all_magicsrrr'r _lockrrtrErr0r2r.rDr rrrarr)rrs)rWr)r~r target_names r"rzNonCallableMock.__getattr__s 4 4 4 && &   +4---1D1D$%F%MNNN2E t__ ' && &  N$*< NDL^@^@^OPP N$MM'+MMMNNN " 4 4(,,T22F!!$T***#/$D$4d;;E--d%4 $..4#D))FJ// 4 D, V_fo v{FF(DDD"&- "="EK*CCC&CC#'CC28+CCCDDDD .4#D); 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4> s++B F:9,E&%F:&;F!! F::F>F>cn|jg}|j}|}d}|dgkrd}|7|}||j|zd}|jdkrd}|j}|7tt |}|jpd}t |dkr|ddvr|dz }||d<d|S)NrJr0r rCr)r0z().r)rrr-rnreversedrrjoin)rW _name_listrlastdot_firsts r"_extract_mock_namez"NonCallableMock._extract_mock_names)* ' $  C!D   g4s: ; ; ;C%--.G!(:..// *F z??Q  !}M11#  1 wwz"""r!c|}d}|dvrd|z}d}|jd}|jrd}||jjz}dt |j||dt |dS) Nr )rCzmock.z name=%rz spec=%rz spec_set=%r)rjr'r(rr=rB)rWr) name_string spec_strings r"rzNonCallableMock.__repr__s&&(( ( ( ($t+K   '$K~ -, %(8(AAK JJ   K KK tHHHH   r!cx tst|S|jpg}t t |}t |j}d|j D}d|D}d|D}tt||z|z|zS)Nc*g|]\}}|tu|Sr )rE)r(m_namem_values r" z+NonCallableMock.__dir__..s1(((&vwh&& &&&r!c<g|]}|d|Sr$r&r(es r"rsz+NonCallableMock.__dir__..s)CCC1c1B1BCQCCCr!cZg|](}|drt|&|)Sr$)r'rrus r"rsz+NonCallableMock.__dir__..sE###1c1B1B#q\\#Q###r!) r object__dir__r*r,r=rnrsrrPrOset)rWextras from_type from_dictfrom_child_mockss r"ryzNonCallableMock.__dir__sF (>>$'' '#)rT OO '' ((*.*=*C*C*E*E(((DC CCC ## ### c&9,y8;KKLLMMMr!cT|tvrt||Sjr+j$|jvr|jvrt d|z|tvrd|z}t ||tvrj|jvrt d|zt|s5tt|t|||fd}nft|d|tt|||j|<n+|dkr |_dSt|||r |j|<jr;t#|s+d|}t d|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.cg|Ri|Sr;r )rXrr}rWs r"rMz-NonCallableMock.__setattr__.. s!HHT,GD,G,G,GB,G,Gr!r7rJz Cannot set )rrx __setattr__r(r*rsrL_unsupported_magicsr`r-rhr= _get_methodrrr'rr/rj)rWr)rmsg mock_namer}s` @r"rzNonCallableMock.__setattr__s > ! !%%dD%88 8n 2!3!? * * *  % % !Dt!KLL L ( ( (BTIC %% % [ !-$d>P2P2P$%H4%OPPP$U++ 2T D+dE*B*BCCC GGGGG&dE4>>>T D%000,1#D)) [ $D  F$T5$== 2,1#D)   |t|jvr(tt||||jvrdS|j|t }||jvr)tt| |n|turt||t ur|j|=t|j|<dSr;) r`r=rsdelattrrrt_missingrr __delattr__rErL)rWr)r4s r"rzNonCallableMock.__delattr__!s ;  44::+>#>#> DJJ % % %4=((!%%dH55 4=  . . : :4 @ @ @ @ H__ && & h  #D)$,D!!!r!c6|jpd}t|||SrB)r_format_call_signaturerWrXrYr)s r"_format_mock_call_signaturez+NonCallableMock._format_mock_call_signature3s (&%dD&999r!rcdd}|||}|j}|j|}||||fzS)Nz0expected %s not found. Expected: %s Actual: %s)rr)rWrXrYactionmessageexpected_stringr actual_strings r"_format_mock_failure_messagez,NonCallableMock._format_mock_failure_message8sDF::4HHN 88)D &/=AAAr!c |s|jSd}|ddd}|j}|D]M}||}|t |t rnt|}|j}|j}N|S)Nr0r rJ)r)replacerQrrtr.rDrE)rWr)rZnameschildrenrGs r"_get_call_signature_from_namez-NonCallableMock._get_call_signature_from_name@s  (' ' T2&&,,S11& , ,DLL&&E} 5* = =} &e,, /+ r!c t|tr/t|dkr||d}n|j}|vt|dkrd}|\}}n|\}}} |j|i|}t ||j|jS#t$r}| dcYd}~Sd}~wwxYw|S)Nrrr ) r.rorrr)rVrrXrY TypeErrorwith_traceback)rW_callrZr)rXrY bound_callrvs r" _call_matcherzNonCallableMock._call_matcheras  eU # # 'E Q44U1X>>CC&C ?5zzQ$ ff%*"dF .%SXt6v66 D*/:3DEEE . . .''-------- .Ls1'B C#B=7C=Cc |jdkr8d|jpdd|jd|}t|dS)Nr Expected 'rCz"' to not have been called. Called  times.rr _calls_reprAssertionErrorrWrs r"rz!NonCallableMock.assert_not_called|sa ?a   o///ooo&&(((*C!%% % r!cT |jdkrd|jpdz}t|dS)Nrz"Expected '%s' to have been called.rC)rrrrs r"rzNonCallableMock.assert_calleds> ?a  7O-v/C %% % r!c |jdks8d|jpdd|jd|}t|dS)NrrrCz#' to have been called once. Called rrrs r"rz"NonCallableMock.assert_called_oncesa !###o///ooo&&(((*C!%% % $#r!cv j/}d}d|d|}t|fd}t fd}j}||kr1t |t r|nd}t||dS)Nz not called.z#expected call not found. Expected: z Actual: c4}|Sr;rrrXrYrWs r"_error_messagez:NonCallableMock.assert_called_with.._error_messages33D&AACJr!Ttwo)rrrr_Callr. Exception)rWrXrYexpectedactual error_messagercauses``` r"rz"NonCallableMock.assert_called_withs 3 > !77fEEH"FFxx)M // /       %%eT6N&E&E&EFF##DN33 X   *8Y ? ?IHHTE !1!122 =  r!c |jdks8d|jpdd|jd|}t||j|i|S)NrrrCz' to be called once. Called r)rrrrrrWrXrYrs r"rz'NonCallableMock.assert_called_once_withsq )!###o///ooo&&(((*C!%% %&t&7777r!c fd|D}td|Dd}tfdjD}|su||vro|d}ndd|D}t |dt|d d |dSt|}g}|D]=} ||#t$r| |Y:wxYw|r-t j pd d t|d |d|dS)Nc:g|]}|Sr rr(crWs r"rsz4NonCallableMock.assert_has_calls..'999aD&&q))999r!c3DK|]}t|t|VdSr;r.rrus r" z3NonCallableMock.assert_has_calls..1FFAZ9-E-EFaFFFFFFr!c3BK|]}|VdSr;rrs r"rz3NonCallableMock.assert_has_calls..s1MMd0033MMMMMMr!zCalls not found.z+Error processing expected calls. Errors: {}c@g|]}t|tr|ndSr;rrus r"rsz4NonCallableMock.assert_has_calls..;$7$7$7()*4Ay)A)A$KAAt$7$7$7r! Expected: z Actual)prefixrJrCz does not contain all of z in its call list, found z instead) rrrformatrrrstriprnremoverNr-rro) rWcalls any_orderrr all_callsproblem not_foundkalls ` r"rz NonCallableMock.assert_has_callss 1:9995999FFFFFMMMMMMT_MMMMM  y((=0GG ,-3V$7$7-5$7$7$7.8.8%II!*5!1!1I''z'::AA#FFII  FOO   ' 'D '  &&&& ' ' '  &&&&& '   &*o&?&?&?&+I&6&6&6&6 C    sC..DDc& t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)NTrc:g|]}|Sr rrs r"rsz3NonCallableMock.assert_any_call..s'EEEA$$$Q''EEEr!z%s call not found)rrr.rr _AnyComparerrrrWrXrYrrrrs` r"rzNonCallableMock.assert_any_calls , %%eT6N&E&E&EFF&x;;EEEEE1DEEE  HL$8$888">>tVLLO #o5 98r!c  |jr7d|vr d|dnd}||z}t||d}||jdvr t di|St |}t|tr|tvrt }nt|tr)|tvs|j r||j vrt}ndt }n\t|ts:t|trt}n*t|trt }n |jd}|di|S)Nr)rJr0rr+rr )rrjrLrtrsr r=r<r_async_method_magicsr_all_sync_magicsr* CallableMixinr r rrr)rWrrjrr_typeklasss r"r2zNonCallableMock._get_child_mocks` !   ,,2bLL(BvJ(((dI//11I=I ++ +FF;''  n5 5 5??r?? "T  eY ' ' %I9M,M,MEE ~ . . %---&.+48J+J+J!!E=11 %%!566 !E?33 M!$Eu{{r{{r!CallscL |jsdSd|dt|jdS)Nr  z: rJ)rr)rWrs r"rzNonCallableMock._calls_reprs;  2;F;;i88;;;;r!) NNNNNNr NFNFF)FFr;)r)r).rrrrrarrHr!r$r"_NonCallableMock__get_return_value"_NonCallableMock__set_return_value"_NonCallableMock__return_value_docrrr7rrrrrr!_NonCallableMock__get_side_effect!_NonCallableMock__set_side_effectrrrrrjrryrrrrrrrrrrrrrr2rr r!r"r r s* EGGE   ">BEI   ;;;M8.0B.00L  X " !( + +F%%l33J$$[11I))*:;;N%%l33J   ***(,.?@@K$u%$$$$$<%%%,---`###6   *NNN$$5$5$5N---$::: BBBBB6&&&&&&&&&>>>, 8 8 8****Z    ###L < < < < < .5s1$HfF"r!TF)allzip)rWitemrs r"rz_AnyComparer.__contains__2s^  E(+D%(8(8 tt   ur!N)rrrrr r!r"rr-s(r!rc||St|r|St|r|S t|S#t$r|cYSwxYwr;)r@rlrrr3s r"r>r>=sk { S ~~ Cyy  s7 AAc HeZdZddedddddddf dZdZdZdZdZdZ dS) rNr c x||jd<tt|j||||||| | fi| ||_dS)Nr)rsrrrHr) rWrrrrr)rrrrrrYs r"rHzCallableMixin.__init__Nsa/; *+1 M4((1 %x K  39   'r!cdSr;r rs r"r^zCallableMixin._mock_check_sigZs r!cP|j|i||j|i||j|i|Sr;)r^_increment_mock_call _mock_callrs r"rKzCallableMixin.__call___sK d-f---!!426222t////r!c|j|i|Sr;)_execute_mock_callrs r"rzCallableMixin._mock_callgs&t&7777r!c~d|_|xjdz c_t||fd}||_|j||jdu}|j}|j}|dk}|j td||f|j }||rB|j t|||f|jdu}|r |jdz|z}t|||f} |j | |jr|rd} nd} |jdk}|j| z|z}|j }|dSdS)NTrrr0r rJ) rrrrrr-rrrrrr) rWrXrYrdo_method_callsmethod_call_namemock_call_name is_a_callrthis_mock_callrhs r"rz"CallableMixin._increment_mock_calljs  1 tVn$/// ""5)))+47?,"d*  ub$%788999+ % W(//7Gv6V0W0WXXX"-":$"F"W'2'='CFV'V$#ND&#ABBN  " ) ). 9 9 9) SCCC'6$> !,!;c!AN!R&6K-%%%%%r!c^|j}|Tt|r|t|s!t|}t|r|n||i|}|tur|S|jtur|jS|jr|jjtur|jS|j |j|i|S|jSr;) rr@rlrrrrrr)rWrXrYeffectr~s r"rz CallableMixin._execute_mock_calls!  V$$ 1 v&& 1f ((! L! 000W$$  "' 1 1$ $   %4#6#C7#R#R$ $   '#4#T4V44 4  r!) rrrrrHr^rKrrrr r!r"rrLs d$d!RT ' ' ' '   000888,7,7,7\!!!!!r!rceZdZdS)rNrr r!r"rrs55r!rc@d}|D]}||vrt|ddS)N) autospect auto_specset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)kwargs_to_checktypostypos r"_check_spec_arg_typosrsN 2E ? " "PPP  #r!c~eZdZdZgZdddZdZdZdZe j dZ d Z d Z d Zd Zd ZdZdZdS)_patchNFrc |)|turtd|td| st| t|rt d|d|dt|rt d|d|d||_||_||_||_||_ ||_ d|_ ||_ ||_ | |_g|_dS)Nz,Cannot use 'new' and 'new_callable' togetherz1Cannot use 'autospec' and 'new_callable' togetherzCannot spec attr z0 as the spec has already been mocked out. [spec=r&z? as the spec_set target has already been mocked out. [spec_set=F)rrNrr-rgetterrjr  new_callablercreate has_localrautospecrYadditional_patchers) rWrrjr rr rr rrYrs r"rHz_patch.__init__sV  #'!! B# G * !& ) ) ) T " " A"@I@@6:@@@AA A X & & P"OIOOAIOOOPP P "(       #%   r!c t|j|j|j|j|j|j|j|j|j }|j |_ d|j D|_ |S)Nc6g|]}|Sr )copy)r(ps r"rsz_patch.copy..,s-' ' ' AFFHH' ' ' r!) rrrjr rr rr rrYattribute_namer )rWpatchers r"rz _patch.copy%sq K49 K M4,dk   "&!4' ' "6' ' ' #r!ct|tr||Stj|r||S||Sr;r.r=decorate_classr1rdecorate_async_callabledecorate_callable)rWr8s r"rKz_patch.__call__2sc dD ! ! -&&t,, ,  &t , , 6//55 5%%d+++r!ct|D]q}|tjs"t ||}t |dsC|}t||||r|SNrK)r,r'r TEST_PREFIXr0r/rrh)rWrr attr_valuers r"rz_patch.decorate_class:sJJ 6 6D??5#455  --J:z22 iikkG E4!4!4 5 5 5 5 r!c#TKg}tj5}|jD]W}||}|j||4|jtur||X|t|z }||fVddddS#1swxYwYdSr;) contextlib ExitStack patchings enter_contextrupdater rr-ro)rWpatchedrXkeywargs extra_args exit_stackpatchingrSs r"decoration_helperz_patch.decoration_helperHs  ! # # #z#- + + ..x88*6OOC((((\W,,%%c*** E*%% %D" " " " # # # # # # # # # # # # # # # # # #sA8BB!$B!ctdrjStfdg_S)Nrc|||5\}}|i|cdddS#1swxYwYdSr;r'rXr#newargs newkeywargsr8r"rWs r"r"z)_patch.decorate_callable..patched]s''(,(022 55Kg{tW4 44 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5s 155r/rr-rrWr8r"s``@r"rz_patch.decorate_callableWsv 4 % %  N ! !$ ' ' 'K t 5 5 5 5 5 5  5 "Fr!ctdrjStfdg_S)NrcK||5\}}|i|d{VcdddS#1swxYwYdSr;r*r+s r"r"z/_patch.decorate_async_callable..patchedns''(,(022 ;5Kg{!T7:k:::::::: ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;s 9==r.r/s``@r"rz_patch.decorate_async_callablehsv 4 % %  N ! !$ ' ' 'K t ; ; ; ; ; ;  ; "Fr!c`|}|j}t}d} |j|}d}n-#tt f$rt ||t}YnwxYw|tvrt|trd|_ |j s|turt |d|||fS)NFTz does not have the attribute ) rrjrrsrLKeyErrorr0 _builtinsr.rr )rWtargetr)r}locals r" get_originalz_patch.get_originalys~ t,HEE) 6 6 6vtW55HHH 6 9  FJ!?!? DK{ x722 7=vvttD s 6'A A c  |j|j|j}}}|j|j}}|j}||_|durd}|durd}|durd}||td|||dvrtd| \}}|tur|d} |dur |}|dur|}d}n| |dur|}d}n|dur|}||/|turtdt|trd} |t|rt} nt} i} ||} nN||J|} ||} t!| rd| v} nt#|  } t| rt} n | rt$} ||| d<||| d <t| tr&t'| t(r|jr |j| d <| || di| }| r_t/|rP|} ||} t!| st1| st$} | d | d|d d | |_n||turtd |turtdt7|}|dur|}t/|jr#t9d|jd|jd|dt/|rAt;|jd|j}t9d|jd|d|jd|d t=|f||jd|}n|rtd|}||_||_ tCj"|_# tI|j|j||j%ci}|jtur |||j%<|j&D]?}|j#'|}|jtur||@|S|S#|j(tSj*sYdSxYw)NFzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=TruerKrrr)r0r1zBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=Truer\z: as the patch target has already been mocked out. [target=r_r&rr]r^)r_namez.Can't pass kwargs to a mock we aren't creatingr )+r rrr rYrrr5rr7rr.r=r5r rrpr9r r<r rjr!r-rvrRrboolrr0r temp_originalis_localrr _exit_stackrhrr r __exit__sysexc_info)rWr rrr rYrr}r6inheritKlass_kwargs this_spec not_callablerbnew_attrr$r&rSs r" __enter__z_patch.__enter__s "h 4=8T=$+&( kkmm  5==D u  H u  H   4=>> >  !5 L ( (TUU U++--% '>>h.Gt||t##'HD!t###HDT!!#8#7w&&#$GHHHh--#"G| h 7 7|!!G'$!X%9 ' (II&&;#-Y#>LL'/ ':':#:L ++1%EE!10E"&#&. #5$'' 15/22 17;~ 1"&. NN6 " " "%""'""C 4,S11 4! ' (I ++1&y1110E F####(5$4SD$4$4+2$4$4  !'!!(7"" GHHHH~~H4# -- D&CDNCC#{CC5=CCCDDD!** D%dk:t{KK &CDNCC"CC#{CC5=CCCDDD "(BX(,BB:@BBCC  NLMM M% %/11  DK : : :". 8w&&7:Jt23 $ 8//H*88BBC|w.."))#...!!J  4=#,..1    sBOOO=cj |jr/|jtur!t|j|j|jndt |j|j|jsCt|j|jr |jdvr t|j|j|j|`|`|`|j }|` |j |S)N)rdrrf__annotations__rg) r<r;rrhr5rjrr r/r=r>)rWr@r%s r"r>z_patch.__exit__#s = IT/w>> DK1C D D D D DK 0 0 0; I T^(L(L I+=== T^T5GHHH   M K%  "z"H--r!cd |}|j||Sr;)rG_active_patchesr-rWr~s r"startz _patch.start8s0;!! ##D))) r!c |j|n#t$rYdSwxYw|dddSr;)rKrrNr>rs r"stopz _patch.stop?s^#   ' ' - - - -   44 }}T4...s  ,,)rrrrrKrHrrKrrcontextmanagerr'rrr7rGr>rMrOr r!r"rrsNOAF"&"&"&"&"&J   ,,,    # # #""0PPPd...*/////r!rc |dd\}}n-#tttf$rtd|wxYwt t j||fS)NrJrz,Need a valid target to patch. You supplied: )rsplitrrNrLrpkgutil resolve_name)r5rjs r" _get_targetrUKsG"MM#q11 z> 2GGG E6 E EGG GG 7' 0 0) ;;s *Arc tturtdfd} t| |||||||| | S)Nz3 must be the actual object to be patched, not a strcSr;r r5sr"rMz_patch_object..jsVr!r)r=strrr) r5rjr rr rr rrrYrs ` r" _patch_objectrZTss  F||s L L L   ^^^F  3f(L&   r!c  tturttj}nfd}|st dt |}|d\} } t|| | |||||i } | | _ |ddD]=\} } t|| | |||||i } | | _ | j | >| S)NcSr;r rXsr"rMz!_patch_multiple..sr!z=Must supply at least one keyword argument with patch.multiplerr) r=rYrrSrTrNrnrPrrr r-) r5rr rr rrYrrPrjr r this_patchers ` r"_patch_multipler^qs( F||s-v66   K     E1XNIs 3fh,G'G)99 3 IsD&( lB  '0 ##**<8888 Nr!c Z t|\} } t| | |||||||| S)Nr)rUr) r5r rr rr rrrYrrjs r"rrsJFN$F++FI  3f(L&   r!cTeZdZ ddZdZdZdZdZdZd Z d Z d Z d Z d Z dS) _patch_dictr Fc ||_t||_|j|||_d|_dSr;)in_dictdictrCr!clear _original)rWrcrCrerYs r"rHz_patch_dict.__init__s> 6ll  6""" r!ct|tr||Stj|r||S||Sr;r)rWfs r"rKz_patch_dict.__call__sc a   *&&q)) )  &q ) ) 3//22 2%%a(((r!c@tfd}|S)Nc |i|S#wxYwr;ra _unpatch_dictrXrrhrWs r"_innerz-_patch_dict.decorate_callable.._inner#sV       %q$~"~~""$$$$""$$$$s 3A rrWrhrns`` r"rz_patch_dict.decorate_callable"9 q % % % % %  % r!c@tfd}|S)NcK |i|d{V S#wxYwr;rkrms r"rnz3_patch_dict.decorate_async_callable.._inner/so       %Q^^^+++++++""$$$$""$$$$s <Arorps`` r"rz#_patch_dict.decorate_async_callable.rqr!c t|D]}}t||}|tjrLt |dr"/ ==DL,  -||~~HH - - -H - - '   - -  - "  !   + NN6 " " " " " + + + + +%c{  + + + +s$A$$BBB66CCc|j}|j}t| ||dS#t$r|D] }||||<YdSwxYwr;)rcrfryr!rL)rWrcr}rNs r"rlz_patch_dict._unpatch_dictgs,>G - NN8 $ $ $ $ $ - - - - -'}  - - - -s6AAc> |j|dSNF)rfrl)rWrXs r"r>z_patch_dict.__exit__ts$ > %    ur!cn |}tj||Sr;)rGrrKr-rLs r"rMz_patch_dict.start{s0;!!%%d+++ r!c tj|n#t$rYdSwxYw|dddSr;)rrKrrNr>rs r"rOz_patch_dict.stops^#   " ) )$ / / / /   44 }}T4...s # 11N)r F)rrrrHrKrrrrGrarlr>rMrOr r!r"raras8)))       +++8 - - -/////r!rac |dS#t$rt|}|D]}||=YdSwxYwr;)rerLrn)rckeysrNs r"ryryse  G}}  C    s !==ch ttjD]}|dSr;)rdrrKrO)rs r"_patch_stopallrs8A&011 r!testzlt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod rdivmod neg pos abs invert complex int float index round trunc floor ceil bool next fspath aiter zDadd sub mul matmul truediv floordiv mod lshift rshift and xor or pow c# K|] }d|zV dS)zi%sNr r(ns r"rrs&77519777777r!c# K|] }d|zV dS)zr%sNr rs r"rrs&55q555555r!>ry__get____set__r __delete__ __format__r __missing__ __getstate__ __reversed__ __setstate__ __getformat__ __reduce_ex____getnewargs____subclasses____getinitargs____getnewargs_ex__c" fd}||_|S)Nc|g|Ri|Sr;r )rWrXrr8s r"methodz_get_method..methods#tD&4&&&2&&&r!)r)r)r8rs ` r"rrs+@'''''FO Mr!ch|]}d|zS)rr )r(rs r"r*r*s*    Hv   r!> __aexit__ __anext__ __aenter__ __aiter__>__del__rrHr __prepare__r__instancecheck____subclasscheck__c6t|Sr;)rx__hash__rs r"rMrMsV__T22r!c6t|Sr;)rx__str__rs r"rMrMsFNN400r!c6t|Sr;)rx __sizeof__rs r"rMrMsv0066r!cxt|jd|dt|S)N/)r=rrjrBrs r"rMrMs;$t**"5^^8O8O8Q8Q^^TVW[T\T\^^r!)rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r> __complex__ __float____bool__ __index__rcfd}|S)NcLjj}|tur|S|urdStSrG)__eq__rrNotImplemented)otherret_valrWs r"rz_get_eq..__eq__s1+0 ' ! !N 5==4r!r )rWrs` r"_get_eqrs# Mr!cfd}|S)NcRjjturtS|urdStSr|)__ne__rrr)rrWs r"rz_get_ne..__ne__s, ; ) 8 8N 5==5r!r )rWrs` r"_get_ners# Mr!cfd}|S)Ncjjj}|turtgSt|Sr;)__iter__rrrrrWs r"rz_get_iter..__iter__s1-2 g  88OG}}r!r )rWrs` r" _get_iterr s# Or!cfd}|S)Ncjj}|turtt gStt |Sr;)rrr_AsyncIteratorrrs r"rz"_get_async_iter..__aiter__s@.3 g  !$r((++ +d7mm,,,r!r )rWrs` r"_get_async_iterrs$----- r!)rrrrc&t|t}|tur ||_dSt|}|||}||_dSt |}||||_dSdSr;)_return_valuesrtrr_calculate_return_value_side_effect_methodsr)rCrr)fixedreturn_calculatorr side_effectors r"_set_return_valuer(s   tW - -E G#/33D99$((.. *(,,T22M *]400! r!ceZdZdZdZdS) MagicMixinc|tt|j|i||dSr;)_mock_set_magicsrrrHrWrXrs r"rHzMagicMixin.__init__;sN . J%%.;;;; r!c ttz}|}t|ddX||j}t }||z }|D](}|t |jvrt||)|t t |jz }t |}|D]!}t||t||"dS)Nr*) _magicsrr0 intersectionr*rzr=rsrrh MagicProxy)rW orig_magics these_magics remove_magicsrLrs r"rzMagicMixin._mock_set_magicsAs 44 " 4$ / / ;&33D4FGGLEEM',6M& ) )DJJ///D%((($c$t***=&>&>> T ! ; ;E E5*UD"9"9 : : : : ; ;r!N)rrrrHrr r!r"rr:s2   ;;;;;r!rceZdZ ddZdS)r Fc\ ||||dSr;rrr#s r"r$z"NonCallableMagicMock.mock_add_spec[8 N D(+++ r!Nrrrrr$r r!r"r r Ys+7      r!r ceZdZdZdS)AsyncMagicMixinc|tt|j|i||dSr;)rrrrHrs r"rHzAsyncMagicMixin.__init__fsN 3 OT**3T@R@@@ r!NrrrrHr r!r"rres#     r!rceZdZ ddZdS)rFc\ ||||dSr;rr#s r"r$zMagicMock.mock_add_specvrr!Nrrr r!r"rrks-       r!rc"eZdZdZdZddZdS)rc"||_||_dSr;r)r)rWr)rs r"rHzMagicProxy.__init__s  r!c|j}|j}||||}t|||t ||||S)N)r)rr)r)rr2rhr)rWrLrms r" create_mockzMagicProxy.create_mocksZ   " "/5 # 7 7q!!!&!U+++r!Nc*|Sr;)r)rWr4rs r"rzMagicProxy.__get__s!!!r!r;)rrrrHrrr r!r"rrsF""""""r!rceZdZedZedZedZfdZdZdZ dZ dZ d Z d Z dd Zd ZfdZxZS)rrrrctj|i|tjj|jd<d|jd<d|jd<t |jd<tt}tj tj ztj z|_ d|_d|_d|_d|_||jd<d |jd <t%|jd <i|jd <d|jd <dS)Nrr_mock_await_count_mock_await_args_mock_await_args_listr)rXrYr7r rrfrgrI)superrHrrrrsrr rr1 CO_COROUTINE CO_VARARGSCO_VARKEYWORDSco_flags co_argcount co_varnamesco_posonlyargcountco_kwonlyargcountro)rWrXrY code_mockr7s r"rHzAsyncMockMixin.__init__s$)&)))*1);)I o&-. )*,0 ()1: -.#X666    !$ %  !"  2 '( $&' #$- j!$/ j!(- n%*, &'+/ '(((r!c`Kt||fd}|xjdz c_||_|j||j}|t |r|t|s8 t|}n#t$rtwxYwt |r|n&t|r||i|d{V}n||i|}|tur|S|j tur|jS|j4t|jr|j|i|d{VS|j|i|S|jS)NTrr)rrrrr-rr@rlr StopIterationStopAsyncIterationrrrrr)rWrXrYrrr~s r"rz!AsyncMockMixin._execute_mock_callstVn$/// A ##E***!  V$$ 1 v&& 1-!&\\FF$----,-!((! L!$V,, 1%vt6v66666666000W$$  "' 1 1$ $   '"4#344 ?-T-t>v>>>>>>>>>#4#T4V44 4  s 1BBcV |jdkrd|jpdd}t|dS)Nr Expected rCz to have been awaited.rrrrs r"rzAsyncMockMixin.assert_awaitedsD   q Odo7OOOC %% % ! r!cf |jdks$d|jpdd|jd}t|dSNrrrCz$ to have been awaited once. Awaited rrrs r"rz"AsyncMockMixin.assert_awaited_onces\ 1$$9t8&99#/999C %% %%$r!cj j)}td|dfd}t fd}j}||kr1t |t r|nd}t||dS)NzExpected await: z Not awaitedc8d}|S)Nawait)rrrs r"rz:AsyncMockMixin.assert_awaited_with.._error_messages"33D&3QQCJr!Tr)rrrrrr.r)rWrXrYrrrrs``` r"rz"AsyncMockMixin.assert_awaited_withs  ? "77fEEH !KH!K!K!KLL L       %%eT6N&E&E&EFF##DO44 X   *8Y ? ?IHHTE !1!122 =  r!c| |jdks$d|jpdd|jd}t||j|i|Sr)rrrrrs r"rz'AsyncMockMixin.assert_awaited_once_withsl 1$$9t8&99#/999C %% %'t'8888r!c& t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)NTrc:g|]}|Sr rrs r"rsz3AsyncMockMixin.assert_any_await.. s'FFFA$$$Q''FFFr!z%s await not found)rrr.rrrrrrs` r"rzAsyncMockMixin.assert_any_await s %%eT6N&E&E&EFF&x;;EFFFF1EFFF  HL$8$888">>tVLLO $6 98r!Fc, fd|D}td|Dd}tfdjD}|sT||vrN|d}ndd|D}t |dt|dj|dSt |}g}|D]=} ||#t$r||Y:wxYw|r t t|d |dS) Nc:g|]}|Sr rrs r"rsz4AsyncMockMixin.assert_has_awaits..# rr!c3DK|]}t|t|VdSr;rrus r"rz3AsyncMockMixin.assert_has_awaits..$ rr!c3BK|]}|VdSr;rrs r"rz3AsyncMockMixin.assert_has_awaits..% s1SSt11!44SSSSSSr!zAwaits not found.z,Error processing expected awaits. Errors: {}c@g|]}t|tr|ndSr;rrus r"rsz4AsyncMockMixin.assert_has_awaits..- rr!rz Actual: z not all found in await list) rrrrrrnrrNr-ro) rWrrrr all_awaitsrrrs ` r"rz AsyncMockMixin.assert_has_awaits s :9995999FFFFFMMSSSSd>RSSSSS  z))=1GG ,-3V$7$7-5$7$7$7.8.8%66!*5!1!166#366  F*%%   ' 'D '!!$'''' ' ' '  &&&&& '   49)4D4D4D4DF   s7C  C/.C/cf |jdkr$d|jpdd|jd}t|dS)NrrrCz# to not have been awaited. Awaited rrrs r"rz!AsyncMockMixin.assert_not_awaitedC s\   q 9t8&99#/999C %% % ! r!c~ tj|i|d|_d|_t |_dSNr)rrrrrr)rWrXrYr7s r"rzAsyncMockMixin.reset_mockL sG  D+F+++({{r!r)rrrrrrrrHrrrrrrrrr __classcell__)r7s@r"rrs&&}55K%%l33J**+<==O000008&!&!&!P&&&&&&>>>$ 9 9 9   ****X&&&+++++++++r!rceZdZdS)r Nrr r!r"r r V s''r!r c"eZdZ dZdZdZdS)_ANYcdSrGr rWrs r"rz _ANY.__eq__ str!cdSr|r rs r"rz _ANY.__ne__ sur!cdS)Nzr rs r"rz _ANY.__repr__ swr!N)rrrrrrr r!r"rr sD8r!rcd|z}d}dd|D}dd|D}|r|}|r |r|dz }||z }||zS)Nz%s(%%s)r z, c,g|]}t|Sr )repr)r(rSs r"rsz*_format_call_signature.. s7773T#YY777r!c"g|] \}}|d| S)=r )r(rNrs r"rsz*_format_call_signature.. s4#-3333r!)rerP)r)rXrYrformatted_args args_string kwargs_strings r"rr s$GN))77$77788KII17M%$(  # d "N-' ^ ##r!ceZdZ ddZ ddZdZejZd Zd Z d Z d Z e d Z e dZdZdZdS)rr r NFTcd}i}t|}|dkr|\}}}n~|dkr<|\} } t| tr| }t| tr| }nD| }nA| | }}n<|dkr6|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nr rr)rr.rYror) rrr)rr from_kallrXrY_lenfirstseconds r"rz _Call.__new__ s5zz 199!& D$ QYY!ME6%%% -fe,,$!DD#FF$ff QYYFE%%% E5))   6==tVn55 5}}S4v"6777r!c0||_||_||_dSr;)rr_mock_from_kall)rWrr)rrr*s r"rHz_Call.__init__ s"(r!cr t|}n#t$r tcYSwxYwd}t|dkr|\}}n|\}}}t|ddr#t|ddr|j|jkrdSd}|dkrdi}}n|dkr|\}}}n|dkr?|\} t | t r| }i}nit | tr| }di}}nMd}| }nH|dkr@|\} } t | tr!| }t | t r| i}}n d| }}n| | }}ndS|r||krdS||f||fkS) Nr rrFrr r)r)rrrr0rr.rorY) rWr len_other self_name self_args self_kwargs other_name other_args other_kwargsrr,r-s r"rz _Call.__eq__ s "E II " " "! ! ! ! " t99>>%) "I{{04 -Iy+ D.$ / / GE>SW4X4X %);;;5 >>')2 JJ !^^38 0J LL !^^FE%'' %" ! E3'' %" +-rL  $ !^^!ME6%%% 9" fe,,:/5r JJ/16 JJ+0&L 5  y005L)i-EEEs &&c|jtd||fdS|jdz}t|j||f||S)Nr r0rrrrrs r"rKz_Call.__call__ sN ? ""dF+$777 7%dotV44MMMMr!cn|jt|dS|jd|}t||dS)NF)r)r*rJ)r)rr*r9)rWrr)s r"rz_Call.__getattr__ sD ? "de444 4///440$tu====r!cb|tjvrtt||Sr;)rorsrL__getattribute__)rWrs r"r<z_Call.__getattribute__$ s+ 5> ! ! %%dD111r!cHt|dkr|\}}n|\}}}||fS)Nr)rrs r"_get_call_argumentsz_Call._get_call_arguments* s2 t99>>LD&&!% D$V|r!c6|dSrr>rs r"rXz _Call.args2 ''))!,,r!c6|dS)Nrr@rs r"rYz _Call.kwargs6 rAr!c|js%|jpd}|drd|z}|St|dkrd}|\}}n+|\}}}|sd}n |dsd|z}nd|z}t |||S)Nrr0zcall%srzcall.%s)r/rr'rr)rWr)rXrYs r"rz_Call.__repr__: s# ?,fDt$$ '$K t99>>DLD&&!% D$ '__T** ' 4'$%dD&999r!c g}|}|%|jr|||j}|%tt |Sr;)r/r-rrrd)rWvalsthings r" call_listz_Call.call_listO s\ $ # E"""&E$(((r!)r r NFT)r NNFT)rrrrrHrrxrrKrr<r>rrXrYrrGr r!r"rr s$:?8888@>C))))2F2F2Fj]FNNN>>>222 --X---X-:::* ) ) ) ) )r!r)r*c & t|rt|}t|t}t|rt d|dt |}d|i} |rd|i} n|i} | r|rd| d<|st || |t} tj |ri} nL|r|rtdt} n1t|st} n|r|rt|st} | d|}|} |d } | d||| |d | } t|t"r"t%| |} |rt'| nt)|| ||| |s | |j|<|d } |r |sd |vrt/||dd | | | _t3|D];}t5|r t7||}n#t8$rY1wxYwd|i}| r&t;| |r|||rd|i}t|t"st=||| ||}|| j|<n{| }t|t"r| j}tA|||}||d<tC|rt}nt}|d||||d|}|| j|<t)|||t|t"rtE| ||=| S)Nz'Cannot autospec a Mock object. [object=r&rrTrzJInstance can not be True when create_autospec is mocking an async functionr)r )rrrr)rrr0)rar9rrror)rr)rr)r`r )#rpr=r.r-rr9rr!rr1isdatadescriptorrr rlr rvrRrDrrrbrrtr rr,rr0rLr/rDrC _must_skiprrh)rrrarr9rrYis_type is_async_funcrCrBrrCwrappedrLr}r rr` child_klasss r"r r _ s#,*~~Dzzt$$G5 4*. 4 4 455 5"4((MtnGt$ ,8,'+#$ &f%%% NN6 E%% % %  ? >?? ? t__%$ %X%&8&>&>%$ KK & &EI 5 (W  ( (& ( (D$ &&8dD))  $ d # # #tWh7778(,u%jj!!G;x;N&$@$@+D(T2629;;;T3&3& U     tU++HH    H (#  *ww.. * MMM ) ) )  , (+F(M22 AXxuhGGC),D  & &F$ .. #"488I"+F; "8,, (' ' +(V%5*0(( &((C*-D  & Xsi @ @ @ @ c= ) ) & D% % % % Ks(G99 HHcF t|ts|t|divrdS|j}|jD]f}|j|t}|tur,t|ttfrdSt|tr|cSdS|S)NrsF) r.r=r0r7rrrsrtrrJrIrD)rrLrKrr~s r"rJrJ s dD ! ! GD*b11 1 15~  ##E733 W    f|[9 : : 55  . . NNN55 Nr!ceZdZ ddZdS)rDFNcZ||_||_||_||_||_||_dSr;)ridsrrrar))rWrrrr)rRras r"rHz_SpecState.__init__ s0       r!)FNNNFrr r!r"rDrD s.48/4r!rDc|t|trtj|Stj|Sr;)r.bytesioBytesIOStringIO) read_datas r" _to_streamrY% s4)U##&z)$$${9%%%r!r c X t}|dg fd} fd} fd fd fd}tdddl}tt t |jt t |jat2ddl}tt t |j a |tdt}tt  j _ d j_ d j_ d j_ d j_ | j_ d < d  j_| j_ j_| j_ fd }||_ |_ |S) NcZjj jjSdj|i|Sr) readlinesrrXrY_statehandles r"_readlines_side_effectz)mock_open.._readlines_side_effect; s7   ( 4#0 0"vay"D3F333r!cZjj jjSdj|i|Sr)readrr]s r"_read_side_effectz$mock_open.._read_side_effect@ s4 ; # /;+ +vay~t.v...r!c?VKEd{V dj|i|VNTr)readline)rXrY_iter_side_effectr^s r"_readline_side_effectz(mock_open.._readline_side_effectE sT$$&&&&&&&&& 6$&)$d5f55 5 5 5 6r!c3bKjj jjVdD]}|VdSre)rfr)liner^r_s r"rgz$mock_open.._iter_side_effectJ sU ? ' 3 3o2222 31I  DJJJJ  r!c^jj jjStdSr)rfrr)r^r_sr"_next_side_effectz$mock_open.._next_side_effectQ s) ? ' 3?/ /F1Ir!ropen)r)r)rrctd<jjdkrd<dj_tS)Nrr)rYrfrr)rXrYrhr^r_rXs r" reset_datazmock_open..reset_dataq sMy))q ? &&) 3 3--//F1I*0)FO 'r!)rY file_spec_iornrzr, TextIOWrapperunionrV open_specrmrrGrwriterbrfr\rrr) rCrX _read_datar`rcrlrqrorgrhr^r_s ` @@@@r"rr, s I&&J$ F444444 ////// 666666   S!23344::3s3;?O?O;P;PQQRR  S]]++,,  |f9555 I & & &F$*F! $FL#FK#'FO $(F!/FK%%''F1I"()FO#9F "3FO"3FO"DD Kr!c$eZdZ dZddZdZdS)rc tdi|S)Nr )r)rWrYs r"r2zPropertyMock._get_child_mock s""6"""r!Nc|Sr;r )rWr4obj_types r"rzPropertyMock.__get__ s tvv r!c||dSr;r )rWr4rTs r"rzPropertyMock.__set__ s S r!r;)rrrr2rrr r!r"rr~ sK###r!rc6 d|_t|D]} t||}n#t$rY wxYwt |t s:t |j|trh|j |urt|dSrG) rr,r0rLr.r rrtrDrr)rCrrs r"rr sDD   d##AA    H !_--   a&**400* = =    % % GGG  s , 99ceZdZ dZdZdS)rct||_tt}tj|_||jd<dS)Nrr7)iteratorr rr1CO_ITERABLE_COROUTINErrs)rWrrs r"rHz_AsyncIterator.__init__ s6  #X666 $: $- j!!!r!c^K t|jS#t$rYnwxYwtr;)rrrrrs r"rz_AsyncIterator.__anext__ sA  && &    D   s  %%N)rrrrHrr r!r"rr s7... !!!!!r!rr)NFNNN)FFNNr)__all__rrrUr1rr?builtinsrSrtypesrrr unittest.utilr functoolsrr threadingrrrr,r4r rrr5r9r-r@rErRrbr]rlrprvrr|rrrxrrrrMISSINGrDELETEDrErrrnrrrrr rMrHrrr>rrrrrUrZr^rraryrrdmultiplestopallr magic_methodsnumericsrerQinplaceright _non_defaultsrrr_sync_async_magics _async_magicsrr`rrrrrrrrrrrr rrrrr rrrrorrr rJrDr=rrDrprtrYrrrrr r!r"rs5  &  ''''''2222222222######$$$$$$$$CCCCCyCCC I Hcc(mm H H H   @@@222    F # # # #   &&&   6."."."b>>>6))) ) ) ) ) )f ) ) )         9;;         &********(6      6   N <N <N <N <N       :         j        D   ,""""""""$@+@+@+@+@+T@+@+@+F((((((((V     6    dff$$$$v)v)v)v)v)Ev)v)v)r uuCGO*/OOOOOd8         DD     &&&OOOOd4$0!!!!!!!!!!r!__pycache__/case.cpython-311.pyc000064400000233240151030032340012364 0ustar00 !A?hBdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZmZmZmZdZeZdZGdd eZGd d eZGd d eZGddeZdZdZdZdZgZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(GddZ)Gdde)Z*Gd d!e*Z+Gd"d#e*Z,Gd$d%ej-Z.Gd&d'eZ/Gd(d)e/Z0Gd*d+e/Z1dS),zTest case implementationN)result)strclass safe_repr_count_diff_all_purpose_count_diff_hashable_common_shorten_reprTz@ Diff is %s characters long. Set self.maxDiff to None to see it.ceZdZdZdS)SkipTestz Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. N__name__ __module__ __qualname____doc__&/usr/lib64/python3.11/unittest/case.pyr r srr ceZdZdZdS) _ShouldStopz The test should stop. Nr rrrrr!rrceZdZdZdS)_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! Nr rrrrr&rrrc8eZdZddZejddZdS)_OutcomeNchd|_||_t|d|_d|_d|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessexpectedFailure)selfrs r__init__z_Outcome.__init__-s8!& (/ (E(E% #rFc#BK|j}d|_ dV|r(|jr!|j|j|dn#t$rt $r4}d|_t |j|t|Yd}~nzd}~wt$rYnktj }|j r||_ nAd|_|r"|j|j||nt|j||d}YnxYw|jo||_dS#|jo||_wxYw)NTF)r rr test_caseKeyboardInterruptr _addSkipstrrsysexc_inforr! _addError)r"r%subTest old_successer*s rtestPartExecutorz_Outcome.testPartExecutor4sql   8 EEE, M4< M &&y':ItLLL-!     5 5 5 DL T[)SVV 4 4 4 4 4 4 4 4    D |~~H% @'/$$$ @K**9+> 8TTTTdk9h???HHH  <7KDLLL4<7KDL 7 7 7 7s;A+DC;*B?D C;DA&C;9DDN)F)r rrr# contextlibcontextmanagerr/rrrrr,sL$$$$888888rrct|dd}||||dStjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reported)getattrwarningswarnRuntimeWarning addSuccess)rr%reasonr4s rr'r'Usffi..G 6""""" L$a ) ) ))$$$$$rc|C|Ct|d|jr|j||dS|j||dSdSdS)Nr) issubclassfailureException addFailureaddError)rtestr*s rr+r+^si h2 hqk4#8 9 9 , F dH - - - - - FOD( + + + + + 22rc|Sr0r)objs r_idrDes Jrct|} |j}|j}n/#t$r"t d|jd|jddwxYw||}|||ddd|S)N'.z6' object does not support the context manager protocol)type __enter____exit__AttributeError TypeErrorrr)cm addcleanupclsenterexitrs r_enter_contextrRis r((CO | OOODCNDDS-=DDDEEJN OOU2YYFJtRtT*** Ms  ,A c@t|||fdS)znSame as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule).N)_module_cleanupsappend)functionargskwargss raddModuleCleanuprYys%XtV455555rc,t|tS)z&Same as enterContext, but module-wide.)rRrY)rMs renterModuleContextr[~s ". / //rcg}trZt\}}} ||i|n,#t$r}||Yd}~nd}~wwxYwtZ|r|ddS)zWExecute all module cleanup functions. Normally called for you after tearDownModule.Nr)rTpop ExceptionrU) exceptionsrVrWrXexcs rdoModuleCleanupsrasJ #!1!5!5!7!7$ # Hd %f % % % % # # #   c " " " " " " " " # # ms1 AAAcdfd}ttjr}d||S|S)z& Unconditionally skip a test. ct|ts!tj|fd}|}d|_|_|S)Nc"tr0r )rWrXr;s r skip_wrapperz-skip..decorator..skip_wrappersv&&&rT) isinstancerH functoolswraps__unittest_skip____unittest_skip_why__) test_itemrfr;s r decoratorzskip..decorators^)T** % _Y ' ' ' ' ' '( ' '$I&* #*0 'r)rgtypes FunctionType)r;rmrls` rskiprqsS     &%,--$ y### rc2|rt|StS)z/ Skip a test if the condition is true. rqrD conditionr;s rskipIfrvsF|| Jrc2|st|StS)z3 Skip a test unless the condition is true. rsrts r skipUnlessrxs F|| Jrcd|_|S)NT)__unittest_expecting_failure__)rls rr!r!s/3I, rct|trtfd|DSt|tot |S)Nc38K|]}t|VdSr0) _is_subtype).0r.basetypes r z_is_subtype..s->>;q(++>>>>>>r)rgtupleallrHr=)expectedrs `rr}r}sW(E""?>>>>X>>>>>> h % % H*Xx*H*HHrceZdZdZdZdS)_BaseTestCaseContextc||_dSr0)r%)r"r%s rr#z_BaseTestCaseContext.__init__s "rcv|j|j|}|j|r0)r%_formatMessagemsgr>)r" standardMsgrs r _raiseFailurez"_BaseTestCaseContext._raiseFailures1n++DHkBBn--c222rN)r rrr#rrrrrrs2###33333rrceZdZddZdZdS)_AssertRaisesBaseContextNct||||_||_|t j|}||_d|_d|_dSr0) rr#rr%recompileexpected_regexobj_namer)r"rr%rs rr#z!_AssertRaisesBaseContext.__init__sU%%dI666  "  %Z77N, rc t|j|jst|d|j|sM|dd|_|r,ttt|d|d}S|^}} |j |_ n$#t$rt||_ YnwxYw|5||i|dddn #1swxYwYd}dS#d}wxYw)z If args is empty, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If args is not empty, call a callable passing positional and keyword arguments. z() arg 1 must be rNz1 is an invalid keyword argument for this function) r}r _base_typerL_base_type_strr]rnextiterr rrKr()r"namerWrX callable_objs rhandlez_AssertRaisesBaseContext.handlesz t}do>> =!%t':':!<=== !::eT22M#7;DLL7I7I7I7I%LMMMDD#' L4 2 , 5 ! 2 2 2 #L 1 1  2 . . d-f--- . . . . . . . . . . . . . . .DDD4DKKKKsZA?C C BC B74C 6B77C < C C CC CC C$r0)r rrr#rrrrrrs7rrcFeZdZdZeZdZdZdZe e j Z dS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typesc|Sr0rr"s rrIz_AssertRaisesContext.__enter__s rc| |jj}n$#t$rt|j}YnwxYw|jr/|d||jn=|d|ntj|t||jsdS| d|_ |j dS|j }| t|s;|d|jt|dS)Nz{} not raised by {}z {} not raisedFT"{}" does not match "{}")rr rKr(rrformat traceback clear_framesr=with_traceback exceptionrsearchpattern)r"exc_type exc_valuetbexc_namers rrJz_AssertRaisesContext.__exit__se   .=1! . . .t}-- .} E""#8#?#?@D $O$OPPPP""?#9#9(#C#CDDDD  "2 & & &(DM22 5"11$77   &4,$$S^^44 >   9@@#+S^^ = = > > >ts 22N) r rrr BaseExceptionrrrIrJ classmethodro GenericAlias__class_getitem__rrrrrsSMMJDN6$ E$677rrc&eZdZdZeZdZdZdZdS)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.z(a warning type or tuple of warning typesc6ttjD]}t |ddri|_t jd|_|j |_t j d|j |S)N__warningregistry__T)recordalways) listr)modulesvaluesr6rr7catch_warningswarnings_managerrI simplefilterr)r"vs rrIz_AssertWarnsContext.__enter__ sck((**++ + +Aq/66 +(*% ( 7t D D D-7799 h 666 rc|j||||dS |jj}n$#t$rt |j}YnwxYwd}|jD]s}|j}t||js||}|j (|j t |sR||_ |j |_ |j |_ dS|@|d|j jt ||jr0|d||jdS|d|dS)Nrz{} not triggered by {}z{} not triggered)rrJrr rKr(r7messagergrrwarningfilenamelinenorrrr)r"rrrrfirst_matchingmws rrJz_AssertWarnsContext.__exit__+s &&xB???   F *}-HH * * *4=))HHH *  A Aa// %!"#/'..s1vv660DLJDM(DK FF  %   9@@(0#n2E2E G G H H H = D   7>>x?C} N N O O O O O   188BB C C C C Cs /AAN) r rrrWarningrrrIrJrrrrrsGLLJ?N    D D D D DrrceZdZdZdS)_OrderedChainMapc#~Kt}|jD]$}|D]}||vr|||V %dSr0)setmapsadd)r"seenmappingks r__iter__z_OrderedChainMap.__iter__Os`uuy  G  D==HHQKKKGGG   rN)r rrrrrrrrNs#rrceZdZdZeZdZdZdZfdZ dOdZ dZ d Z d Z ed Zed Zd ZdZedZedZdZdZdZdZdZdZdZdZejefdZ dZ!dZ"dZ#dZ$dZ%dZ&dPd!Z'd"Z(ed#Z)d$Z*d%Z+d&Z,dPd'Z-dPd(Z.dPd)Z/d*Z0d+Z1d,Z2dQd-Z3dQd.Z4d/Z5dPd0Z6dPd1Z7dPd2Z8 dRd3Z9 dRd4Z:dQd5Z;d6ZdPd9Z?dPd:Z@dPd;ZAdPd<ZBdPd=ZCdPd>ZDdPd?ZEdPd@ZFdPdAZGdPdBZHdPdCZIdPdDZJdPdEZKdPdFZLdPdGZMdPdHZNdPdIZOdJZPdKZQdPdLZRdPdMZSdNZTeTe7xZUZVeTe8xZWZXeTe9xZYZZeTe:xZ[Z\eTe/xZ]Z^eTe1Z_eTe.Z`eTePZaeTeRZbeTeSZcxZdS)STestCaseaWA class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. TiicVd|_g|_tj|i|dS)NF)_classSetupFailed_class_cleanupssuper__init_subclass__)rOrWrX __class__s rrzTestCase.__init_subclass__s5 % !!42622222rrunTestc:||_d|_d|_ t||}|j|_n0#t $r#|dkrt d|jd|YnwxYwg|_d|_ i|_ | td| td| td| td | t d | t"d dS) zCreate an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. NzNo testrzno such test method in : assertDictEqualassertListEqualassertTupleEqualassertSetEqualassertMultiLineEqual)_testMethodName_outcome_testMethodDocr6rrK ValueErrorr _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictrrr frozensetr()r" methodName testMethods rr#zTestCase.__init__sA * ' 5 z22J#-"4D   4 4 4Y&&!j~~~zz"3444'& 4 %'!   '8999   '8999   (:;;;   &6777   ,<===   &<=====s4*A! A!c||j|<dS)a[Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. N)r)r"typeobjrVs rrzTestCase.addTypeEqualityFuncs.6!'***rc@|j|||fdS)aAdd a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).N)rrUr"rVrWrXs r addCleanupzTestCase.addCleanups' xv677777rc,t||jS)zEnters the supplied context manager. If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method. )rRr)r"rMs r enterContextzTestCase.enterContexts b$/222rc@|j|||fdS)zpSame as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).N)rrUrOrVrWrXs raddClassCleanupzTestCase.addClassCleanups( ""HdF#;<<<<t|jd|jS)NrGrrrrs ridz TestCase.ids#"4>2222D4H4HIIrclt|t|urtS|j|jkSr0)rHNotImplementedrr"others r__eq__zTestCase.__eq__s0 ::T%[[ ( (! !#u'<<rrs r__repr__zTestCase.__repr__s.(((($*>*>*>@ @rc+K|j |jjsdVdS|j}|t|}n|j|}t ||||_ |j|jd5dVdddn #1swxYwY|jjs|jj }||j rtn|jj rt||_dS#||_wxYw)aPReturn a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed. NT)r,) rrrrparams new_child_SubTestr/r rfailfastrr!)r"rr#parent params_maprs rr,zTestCase.subTestsI =  (N EEE F >)&11JJ0088J sJ77  #// t/LL                 =( "-%&/%%%. ""!"DMMMFDM " " " "s0&!C(B C(BC(B ?C(( C1c |j}|||dS#t$r.tjdt|j|YdSwxYw)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerKr7r8r9r:)r"rr*r*s r_addExpectedFailurezTestCase._addExpectedFailure&s~ /!'!:   tX . . . . .  $ $ $ M\( * * * F d # # # # # # $s4AAc |j}||dS#t$rXtjdt t d#t $r'|j|tjYYdSwxYwwxYw)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrKr7r8r9rr?r)r*)r"rr-s r_addUnexpectedSuccesszTestCase._addUnexpectedSuccess0s '#)#>  !  & & & & & 8 8 8 M_( * * * 8(d2% 8 8 8!!$ 7777777 8 8s&$A8A,A4/A83A44A8c.|dSr0)rrs r _callSetUpzTestCase._callSetUp?s rc^|"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case (r) stacklevel)r7r8DeprecationWarning)r"methods r_callTestMethodzTestCase._callTestMethodBs\ 688  M2(.2223ERS U U U U U U rc.|dSr0)rrs r _callTearDownzTestCase._callTearDownGs rc||i|dSr0rrs r _callCleanupzTestCase._callCleanupJs$!&!!!!!rNc|C|}t|dd}t|dd}| |nd}|j| t||j}t|jddst|ddrWt|jddpt|dd}t |||||j|| |SSt|ddpt|dd}t|} ||_| |5| dddn #1swxYwY|j r||_ | |5| |dddn #1swxYwYd|_ | |5|dddn #1swxYwY||j rK|r9|jr|||jn&||n|j||d|_d}d|_|j|| |SS#d|_d}d|_wxYw#|j|| |wwxYw)N startTestRun stopTestRunrjFrkrnrz)rr6 startTestrrr'stopTestrrr/r0r rr6r8 doCleanupsr!r+r.r:)r"rr<r=rskip_whyroutcomes rrunz TestCase.runMs >++--F"6>4@@L!&->>K' K2  t';<FFM $DeLL v&&G % ' --d33&&OO%%%&&&&&&&&&&&&&&&?-0AG- 11$7799,,Z88899999999999999905G- 11$77--**,,,---------------!!!?0(0"2? 44VW=TUUUU 66v>>>>))$///+/'!%  FOD ! ! !& '+/'!% $$$$ FOD ! ! !& 'sA5J(,1J(J:E JEJ"E#&J F+ J+F//J2F/3JG3' J3G77J:G7;A*J%J(J%%J((Kc |jp t}|jrb|j\}}}||5|j|g|Ri|dddn #1swxYwY|jb|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrr]r/r:r )r"rBrVrWrXs rr@zTestCase.doCleanupss--8::n =%)^%7%7%9%9 "HdF))$// = =!!(%> "HdF ?$)&)))) ? ? ?'..s|~~>>>>> ? ! ? ? ? ? ?s65A.-A.c|j|i|Sr0)rC)r"rWkwdss r__call__zTestCase.__call__stx&&&&rct||j}t|jddst|ddr6t|jddpt|dd}t||||||jr7|j\}}}|j |g|Ri||j5dSdS)z6Run the test without collecting errors in a TestResultrjFrkrnN) r6rrr r0r6r8rr]r:)r"rrArVrWrXs rdebugzTestCase.debugsT4#788 DN$7 ? ? % J 3U ; ; % 0GLLL":/FKK 8$$ $  Z((( n 9%)^%7%7%9%9 "HdF D h 8 8 8 8 8 8 8n 9 9 9 9 9rc t|)zSkip this test.re)r"r;s rskipTestzTestCase.skipTestsvrc,||)z)Fail immediately, with the given message.)r>)r"rs rfailz TestCase.fails##C(((rc|r;||dt|z}||dS)z#Check that the expression is false.z%s is not falseNrrr>r"exprrs r assertFalsezTestCase.assertFalsesI  -%%c+>.$??GGdGNNNNs+/cPt||}|d||S)aFail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) assertWarnsrr)r"expected_warningrWrXr_s rrazTestCase.assertWarnss*8&&6==~~mT6:::rc,ddlm}||||dS)aFail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. This method must be used as a context manager, and will yield a recording object with two attributes: `output` and `records`. At the end of the context manager, the `output` attribute will be a list of the matching formatted log messages and the `records` attribute will be a list of the corresponding LogRecord objects. Example:: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) r_AssertLogsContextFno_logs_logrfr"loggerlevelrfs r assertLogszTestCase.assertLogs"s0* -,,,,,!!$uEEEErc,ddlm}||||dS)z Fail unless no log messages of level *level* or higher are emitted on *logger_name* or its children. This method must be used as a context manager. rreTrgrirks r assertNoLogszTestCase.assertNoLogs:s0 -,,,,,!!$tDDDDrct|t|urP|jt|}|'t|trt ||}|S|jS)aGet a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. )rHrgetrgr(r6_baseAssertEqual)r"firstsecondasserters r_getAssertEqualityFunczTestCase._getAssertEqualityFuncCsl" ;;$v,, & &044T%[[AAH#h,,7&tX66H$$rc||ks>dt||z}|||}||dS)z:The default assertEqual implementation, not type specific.%s != %sN)r rr>)r"rtrurrs rrszTestCase._baseAssertEqual]sP$';E6'J'JJK%%c;77C'',, ,rcN|||}||||dS)z[Fail if the two objects are unequal as determined by the '==' operator. )rN)rw)r"rtrurassertion_funcs r assertEqualzTestCase.assertEqualds644UFCCuf#......rc||ksJ||t|dt|}||dS)zYFail if the two objects are equal as determined by the '!=' operator.  == NrR)r"rtrurs rassertNotEqualzTestCase.assertNotEqualkse%%c59I9I9I9I:CF:K:K:K,MNNC'',, ,rc ||krdS||tdt||z }|K||krdSt|dt|dt|dt|d}nO|d}t||dkrdSt|dt|d|d t|d}|||}||) a'Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). If the two objects compare equal then they will automatically compare almost equal. N specify delta or places not bothz !=  within  delta ( difference)rz places (rLabsrroundrr>r"rtruplacesrdeltadiffrs rassertAlmostEqualzTestCase.assertAlmostEqualts, F?? F  !3>?? ?56>""  u}}%    &!!!!%    $ !KK ~T6""a''%    &!!!!$ !K !!#{33##C(((rc ||tdt||z }|Q||ks||krdSt|dt|dt|dt|d}nE|d}||kst||dkrdSt|dt|d|d }|||}||) aFail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). Objects that are equal automatically fail. Nrr~rrrrrz placesrrs rassertNotAlmostEqualzTestCase.assertNotAlmostEquals  !3>?? ?56>""  VOO%    &!!!!%    $ !KK ~VOOtV)<)<)A)A9B59I9I9I9I9B69J9J9J9J9?AK!!#{33##C(((rc |x|j}t||s(|d|dt|t||s(|d|dt|nd}d} t |}n#t t f$rd|z}YnwxYw|- t |}n#t t f$rd|z}YnwxYw|||krdSd|ft||zz}tt||D]} || } n(#t tt f$r|d | |fzz }YnwxYw || } n(#t tt f$r|d | |fzz }YnQwxYw| | kr|d | ft| | zzz }n+||kr$|"t|t|krdS||krS|d |||z fzz } |d |t||fzz }n#t tt f$r |d||fzz }Yn]wxYw||krS|d|||z fzz } |d |t||fzz }n'#t tt f$r |d||fzz }YnwxYw|} dd tjt!j|t!j|z} || | } ||| }||dS)aAAn equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. NzFirst sequence is not a rzSecond sequence is not a sequencez(First %s has no length. Non-sequence?z)Second %s has no length. Non-sequence?z%ss differ: %s != %s z( Unable to index element %d of first %s z) Unable to index element %d of second %s z# First differing element %d: %s %s z+ First %s contains %d additional elements. zFirst extra element %d: %s z'Unable to index element %d of first %s z, Second %s contains %d additional elements. z(Unable to index element %d of second %s r )r rgr>rlenrLNotImplementedError capitalizer rangemin IndexErrorrHjoindifflibndiffpprintpformat splitlines_truncateMessagerrP)r"seq1seq2rseq_type seq_type_name differinglen1len2iitem1item2rdiffMsgs rassertSequenceEqualzTestCase.assertSequenceEquals  $-MdH-- L++++8==)D///-KLLLdH-- L++++8==)D///-KLLL L'M  #t99DD./ # # #B!#III #   '4yy23 ' ' 'G%'  '  t||0"--//1(t4456I3tT??++   GEE!:/BC"N"#]!3#45IEE  GEE!:/BC"O"#]!3#45IEE E>>"K#$$)=eU)K)K"K#MNIE" DLLX%5JJ$t**,,Fd{{+.;TD[-IJK K"A#'4:)>)>"?#@AII!:/BCKKK#259=4I#JKIIIK+.;TD[-IJK L"A#'4:)>)>"?#@AII!:/BCLLL#36:M5J#KLIIIL  M&...99;; ...99;; = =>>>++KAA !!#{33 #slBB)(B)/B??CC/D88!EE!E**!FF3H!H54H5 I**!J Jcx|j}|t||kr||zS|tt|zzSr0)maxDiffr DIFF_OMITTED)r"rrmax_diffs rrzTestCase._truncateMessage's?<  s4yyH44T> !,T233rcB||||tdS)aA list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. rN)rr)r"list1list2rs rrzTestCase.assertListEqual-s'   sT BBBBBrcB||||tdS)aA tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. rN)rr)r"tuple1tuple2rs rrzTestCase.assertTupleEqual9s'   u EEEEErcJ ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw|s|sdSg}|r<|d|D]$}|t |%|r<|d|D]$}|t |%d|} |||| dS)aA set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). z/invalid type when attempting set difference: %sNz2first argument does not support set difference: %sz3second argument does not support set difference: %sz*Items in the first set but not the second:z*Items in the second set but not the first:r ) differencerLrPrKrUreprrr) r"set1set2r difference1r. difference2linesitemrs rrzTestCase.assertSetEqualDs& P//$//KK M M M IIG!K L L L L L L L L P P P IIJQN O O O O O O O O P Q//$//KK M M M IIG!K L L L L L L L L Q Q Q IIKaO P P P P P P P P Q {  F  ) LLE F F F# ) ) T$ZZ((((  ) LLE F F F# ) ) T$ZZ((((ii&&  $%%c;7788888sB A.? A. A))A.2B CB// C<CCc||vrLt|dt|}||||dSdS)zDJust like self.assertTrue(a in b), but with a nicer default message. not found in NrrPrr"member containerrrs rassertInzTestCase.assertInosd  " "2;F2C2C2C2C2;I2F2F2FHK IId))#{;; < < < < < # "rc||vrLt|dt|}||||dSdS)zHJust like self.assertTrue(a not in b), but with a nicer default message.z unexpectedly found in Nrrs r assertNotInzTestCase.assertNotInvsd Y  ;DV;L;L;L;L8A)8L8L8LNK IId))#{;; < < < < <  rc||urLt|dt|}||||dSdS)zDJust like self.assertTrue(a is b), but with a nicer default message.z is not Nrr"expr1expr2rrs rassertIszTestCase.assertIs}sc   ,5e,<,<,<,<-6u-=-=-=?K IId))#{;; < < < < <  rc||ur=dt|}||||dSdS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: Nrrs r assertIsNotzTestCase.assertIsNotsO E>>>:CE:J:J:JLK IId))#{;; < < < < < >rc ||td||td||krdt||z}ddt jt j|t j|z}| ||}| | ||dSdS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryryr ) assertIsInstancerr rrrrrrrrPr)r"d1d2rrrs rrzTestCase.assertDictEquals b$(LMMM b$(MNNN 88$';B'C'CCK499W]!>"--88::!>"--88::&<&<===D// TBBK IId))#{;; < < < < < 8rc Htjdtg}g}|D]u\}}||vr|||||krJ|t |dt |dt ||v|s|sdSd}|r"ddd|Dz}|r"|r|d z }|d d|zz }||||dS) z2Checks whether dictionary is a superset of subset.z&assertDictContainsSubset is deprecatedz , expected: z , actual: Nrnz Missing: %s,c34K|]}t|VdSr0)r)r~rs rrz4TestCase.assertDictContainsSubset..s83=3=A9Q<<3=3=3=3=3=3=rz; zMismatched values: %s) r7r8r4itemsrUrrrPr) r"subset dictionaryrmissing mismatchedkeyvaluers rassertDictContainsSubsetz!TestCase.assertDictContainsSubsetsz >( * * *  ,,.. @ @JC*$$s####*S/))!!#,S>>>>9U3C3C3C3C#,Z_#=#=#=#?@@@ :  F  ='#((3=3=4;3=3=3=+=+==K  J $t# 2SXXj5I5II IK $%%c;7788888rct|t|}} tj|}tj|}||krdSt||}n #t$rt ||}YnwxYw|rfd}d|D}d|} ||| }|||}| |dSdS)a[Asserts that two iterables have the same elements, the same number of times, without regard to order. self.assertEqual(Counter(list(first)), Counter(list(second))) Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. NzElement counts were not equal: cg|]}d|zS)z First has %d, Second has %d: %rr)r~rs r z-TestCase.assertCountEqual..sWWW47$>WWWrr ) r collectionsCounterrrLrrrrrP) r"rtrur first_seq second_seq differencesrrrs rassertCountEqualzTestCase.assertCountEquals!%U T&\\:  F' 22E (44F .y*EEKK  I I I1)ZHHKKK I  =A>c||td||td||kr*t||jkst||jkr|||||d}|d}t|dkr%|d|kr |dzg}|dzg}dt||z}dd tj ||z}| ||}| | ||d Sd S) z-Assert that two multi-line strings are equal.zFirst argument is not a stringzSecond argument is not a stringT)keependsrz r ryrnN)rr(r_diffThresholdrsrr r rrrrrPr)r"rtrur firstlines secondlinesrrs rrzTestCase.assertMultiLineEqualsa eS*JKKK fc+LMMM F??E T000F d111%%eVS999))4)88J ++T+::K:!## F(;(;u(D(D#dl^ %}o $';E6'J'JJK"'''- K"H"HIIID// TBBK IId))#{;; < < < < < ?rc||ksLt|dt|}||||dSdS)zCJust like self.assertTrue(a < b), but with a nicer default message.z not less than Nrr"abrrs r assertLesszTestCase.assertLesssV1uu3 b), but with a nicer default message.z not greater than Nrrs r assertGreaterzTestCase.assertGreatersV1uu6?llllIaLLLQK IId))#{;; < < < < <urc||ksLt|dt|}||||dSdS)zDJust like self.assertTrue(a >= b), but with a nicer default message.z not greater than or equal to Nrrs rassertGreaterEqualzTestCase.assertGreaterEquals[AvvBKA,,,,PYZ[P\P\P\]K IId))#{;; < < < < <vrc|=t|d}||||dSdS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz is not Nonerr"rCrrs r assertIsNonezTestCase.assertIsNonesH ?.7nnnn>K IId))#{;; < < < < < ?rcd|-d}||||dSdS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rPrrs rassertIsNotNonezTestCase.assertIsNotNones; ;-K IId))#{;; < < < < < ;rct||s?t|d|}||||dSdS)zTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.z is not an instance of NrgrrPrr"rCrOrrs rrzTestCase.assertIsInstance s^#s## =;DS>>>>33OK IId))#{;; < < < < < = =rct||r?t|d|}||||dSdS)z,Included for symmetry with assertIsInstance.z is an instance of Nrrs rassertNotIsInstancezTestCase.assertNotIsInstances\ c3   =7@~~~~ssKK IId))#{;; < < < < < = =rcRt|||}|d||S)aAsserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. assertRaisesRegexr])r"r^rrWrXr_s rrzTestCase.assertRaisesRegexs-''94PP~~14@@@rcRt|||}|d||S)aAsserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. Args: expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. assertWarnsRegexrb)r"rcrrWrXr_s rrzTestCase.assertWarnsRegex(s- &&6nMM~~0$???rct|ttfr |s Jdtj|}||s8d|jd|}|||}||dS)z=Fail the test unless the text matches the regular expression.z!expected_regex must not be empty.zRegex didn't match: rN) rgr(bytesrrrrrr>)r"textrrrs r assertRegexzTestCase.assertRegex;s nsEl 3 3 8! F F#F F F>Z77N$$T** - -&&&.K%%c;77C'',, ,  - -rcbt|ttfrtj|}||}|rgd|||d|jd|}| ||}| |dS)z9Fail the test if the text matches the regular expression.zRegex matched: z matches z in N) rgr(rrrrstartendrrr>)r"runexpected_regexrmatchrs rassertNotRegexzTestCase.assertNotRegexGs &e 5 5 <!z*:;;  ''--  - -U[[]]UYY[[0111 (((K %%c;77C'',, , - -rcfd}|S)Ncztjdjtd|i|S)NzPlease use {0} instead.r5)r7r8rr r4)rWrX original_funcs rdeprecated_funcz,TestCase._deprecate..deprecated_funcWsG M)001GHH"A ' ' '!=$1&11 1rr)rrs` r _deprecatezTestCase._deprecateVs$ 2 2 2 2 2 r)rr0)NNNNN)er rrrAssertionErrorr>rYrrrr#rrrrrrrrrrrrrrrrrr!r1r2_subtest_msg_sentinelr,r+r.r0r6r8r:rCr@rGrJrLrNrPrUrWrr\rarnrprwrsr|rrrrrrrrrrrrrrrrrrrrrrrrrrrrrfailUnlessEqual assertEquals failIfEqualassertNotEqualsfailUnlessAlmostEqualassertAlmostEqualsfailIfAlmostEqualassertNotAlmostEquals failUnlessassert_failUnlessRaisesfailIfassertRaisesRegexpassertRegexpMatchesassertNotRegexpMatches __classcell__rs@rrrXs@&KGN33333 >>>>@ 6 6 6888333==[= 77[7      VV[Vaa[a###CCCJJJ=== 888eee@@@/####</// ' ' 'UUU """====~    ? ?[ ?'''999"))))---- ---- III*B;;;>FFFF0EEEE%%%4----////----AE $+)+)+)+)ZDH#'!)!)!)!)FaaaaF444 C C C C F F F F)9)9)9)9V================ = = = =9999:@====(==== ==== ==== ==== ==== ==== ======== AAA @@@& - - - - - - - -&0Z %<%<$>>K/1;)r"r%rr#rs rr#z_SubTest.__init__s?  " ) :rc td)Nzsubtests cannot be run directly)rrs rrz_SubTest.runTests!"CDDDrctg}|jtur-|d|j|jr^dd|jD}|d|d|pdS)Nz[{}]z, c3HK|]\}}d||VdS)z{}={!r}N)r)r~rrs rrz+_SubTest._subDescription..sJ$3$3Q  A&&$3$3$3$3$3$3rz({}) z ())r<rrUrr#rr)r"parts params_descs r_subDescriptionz_SubTest._subDescriptions = 5 5 5 LLt}55 6 6 6 ; 5))$3$3"k//11$3$3$333K LL{33 4 4 4xx/-/rcd|j|SNz{} {})rr%rrCrs rrz _SubTest.ids0~~dn//1143G3G3I3IJJJrc4|jS)zlReturns a one-line description of the subtest, or None if no description has been provided. )r%rrs rrz_SubTest.shortDescriptions~..000rc\d|j|SrE)rr%rCrs rrz_SubTest.__str__s$~~dnd.B.B.D.DEEEr) r rrr#rrCrrrr&r's@rr%r%s;;;;;EEE 0 0 0KKK111 FFFFFFFrr%)2rr)rhrrrr7rr1rrornrutilrrrrr __unittestobjectrrr^r rrrr'r+rDrRrTrYr[rarqrvrxr!r}rrrrChainMaprrr)r%rrrrLs   ?????????????? 7 y)  &8&8&8&8&8v&8&8&8R%%%,,,   666 000    (III 33333333'''''3'''T$8$8$8$8$83$8$8$8N1D1D1D1D1D21D1D1Dh{+P8P8P8P8P8vP8P8P8h 7:7:7:7:7:x7:7:7:t!F!F!F!F!Fx!F!F!F!F!Fr__pycache__/signals.cpython-311.pyc000064400000007447151030032340013121 0ustar00 !A?hc ~ddlZddlZddlmZdZGddeZejZdZ dZ da dZ d d Z dS) N)wrapsTceZdZdZdZdS)_InterruptHandlercd|_||_t|tr@|tjkr tj}n#|tjkrd}ntd||_ dS)NFcdSN) unused_signum unused_frames )/usr/lib64/python3.11/unittest/signals.pydefault_handlerz3_InterruptHandler.__init__..default_handlersDzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr )selfr s r __init__z_InterruptHandler.__init__ s / os + + 3&.00"("< FN22 !2333 /rctjtj}||ur||||jr|||d|_t D]}|dS)NT)r getsignalSIGINTr r_resultskeysstop)rsignumframeinstalled_handlerresults r __call__z_InterruptHandler.__call__s",V];; D ( (   / / / ; 0   / / / mmoo  F KKMMMM  rN)__name__ __module__ __qualname__rr$r rr rr s2///$     rrcdt|<dS)N)rr#s r registerResultr+*sHVrcRtt|dSr)boolrpopr*s r removeResultr/-s  VT** + ++rctStjtj}t |atjtjtdSdSr)_interrupt_handlerrrrr)r s r installHandlerr21sK! *6=99.?? fm%788888"!rctfd}|St+tjtjtjdSdS)Nctjtj}t |i|tjtj|S#tjtj|wxYwr)rrr removeHandler)argskwargsinitialmethods r innerzremoveHandler..inner;sf&v}55G OOO 6vt.v.. fmW5555 fmW5555s A!A7)rr1rrr)r9r:s` r r5r59sg  v 6 6 6 6  6 % fm%7%HIIIII&%rr)rweakref functoolsr __unittestobjectrWeakKeyDictionaryrr+r/r1r2r5r rr r@s   @ %7 $ & &,,,999JJJJJJr__pycache__/__main__.cpython-311.opt-2.pyc000064400000001162151030032340014125 0ustar00 !A?h ddlZejddr1ddlZejejZedzejd<[dZddl m Z e ddS)Nz __main__.pyz -m unittestT)main)module) sysargvendswithos.pathospathbasename executable __unittestr*/usr/lib64/python3.11/unittest/__main__.pyrs 8A; && NNN !!#.11J~-CHQK  Dr__pycache__/suite.cpython-311.pyc000064400000042714151030032340012606 0ustar00 !A?h4dZddlZddlmZddlmZdZdZGdd eZGd deZ Gd d eZ d Z GddeZ dS) TestSuiteN)case)utilTc>t||d}|dS)NcdSNr '/usr/lib64/python3.11/unittest/suite.pyz!_call_if_exists.. sr )getattr)parentattrfuncs r _call_if_existsr s$ 64 . .DDFFFFFr cZeZdZdZdZddZdZdZdZdZ d Z d Z d Z d Z d ZdZdS) BaseTestSuitezNA simple test suite that doesn't provide class or module shared fixtures. Tr cLg|_d|_||dSNr)_tests_removed_testsaddTests)selftestss r __init__zBaseTestSuite.__init__s)  er c\dtj|jdt|dS)N)rstrclass __class__listrs r __repr__zBaseTestSuite.__repr__s+"&-"?"?"?"?dLLr czt||jstSt|t|kSr ) isinstancer!NotImplementedr")rothers r __eq__zBaseTestSuite.__eq__s3%00 "! !DzzT%[[((r c*t|jSr )iterrr#s r __iter__zBaseTestSuite.__iter__"sDK   r cP|j}|D]}|r||z }|Sr )rcountTestCases)rcasestests r r.zBaseTestSuite.countTestCases%s=# / /D /,,... r c@t|s/tdt|t |t r0t |tjtfrtd|j |dS)Nz{} is not callablezNTestCases and TestSuites must be instantiated before passing them to addTest()) callable TypeErrorformatreprr&type issubclassrTestCaserrappendrr0s r addTestzBaseTestSuite.addTest,s~~ E077T CCDD D dD ! ! @j26-1K'M'M @?@@ @ 4     r ct|trtd|D]}||dS)Nz0tests must be an iterable of tests, not a string)r&strr3r;)rrr0s r rzBaseTestSuite.addTests6sR eS ! ! PNOO O  D LL      r ct|D]5\}}|jrn(|||jr||6|Sr ) enumerate shouldStop_cleanup_removeTestAtIndex)rresultindexr0s r runzBaseTestSuite.run<s\$T?? / /KE4   DLLL} /''... r c |j|}t|dr"|xj|z c_d|j|<dS#t$rYdSwxYw)z2Stop holding a reference to the TestCase at index.r.N)rhasattrrr.r3)rrDr0s r rBz BaseTestSuite._removeTestAtIndexEs~ &;u%Dt-.. =##t':':'<'<<##!%DK       DD s A AAc|j|i|Sr rE)rargskwdss r __call__zBaseTestSuite.__call__Sstx&&&&r c8|D]}|dS)7Run the tests without collecting errors in a TestResultN)debugr:s r rOzBaseTestSuite.debugVs*  D JJLLLL  r N)r )__name__ __module__ __qualname____doc__rArr$r)r,r.r;rrErBrLrOr r r rrsH MMM))) !!!!!!  & & &'''r rcReZdZdZd dZdZdZdZdZ dd Z dd Z d Z d Z dS)raA test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. Fcld}t|dddur dx|_}t|D]\}}|jrnt |rv||||||||||j|_ t|jddst|ddr|s ||n| |j r| ||r2|d|| |d|_|S)NF_testRunEnteredT_classSetupFailed_moduleSetUpFailed)rrVr?r@ _isnotsuite_tearDownPreviousClass_handleModuleFixture_handleClassSetUpr!_previousTestClassrOrArB_handleModuleTearDown)rrCrOtopLevelrDr0s r rEz TestSuite.runfsb 6,e 4 4 = =04 4F "X$T?? / /KE4  4   ++D&999))$777&&tV444,0N)DN,?GGF$8%@@ V  } /''...  +  ' 'f 5 5 5  & &v . . .%*F " r cNt}||ddS)rNTN) _DebugResultrE)rrOs r rOzTestSuite.debugs% r ct|dd}|j}||krdS|jrdSt|ddrdSd} d|_n#t$rYnwxYwt|dd}t|dd}|t |d |nt#t $rg}t|trd} d|_n#t$rYnwxYwtj |} | ||d| Yd}~nd}~wwxYw|r6|4||j D]"} | || dd| | #t |d dS#t |d wxYwdS) Nr]__unittest_skip__F setUpClassdoClassCleanups _setupStdoutTrinfo_restoreStdout) rr!rXrWr3r Exceptionr&rarr "_createClassOrModuleLevelExceptiontearDown_exceptions) rr0rC previousClass currentClassfailedrdree classNameexc_infos r r\zTestSuite._handleClassSetUps8(> !,0A4HH  ! FN 3 3 3 : GJLLLL G G G!&,77!F9= 66$ $ l ; ;I;;FAd}t|dd}||j}|S)Nr])rrQ)rrCpreviousModulerms r _get_previous_modulezTestSuite._get_previous_modules-(> * * * * * -s|~~66666t,,,,,r c|||}|dS|jrdS tj|}n#t$rYdSwxYwt |d t |dd}|Q |nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYw tj nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYwt |ddS#t |dwxYw)NrftearDownModuleri) rurXrxryrzrrrjr&rarkrr{)rrCrtr}rrps r r^zTestSuite._handleModuleTearDowns226::  ! F  $  F [0FF    FF  /// 6$V-=tDDN)L"N$$$$ LLL!&,77;;FACD) D.D D)DD))D;ct|dd}|j}||ks|dSt|ddrdSt|ddrdSt|ddrdSt|dd}t|dd}||dSt|d |e |nY#t$rL}t |t rt j|}|||d|Yd}~nd}~wwxYw|e||j D]S} t |t r| d t j|}||| d d|| Tt|d dS#t|d wxYw) Nr]rWFrXrc tearDownClassrerfrrgri) rr!rrjr&rarr rkrl) rr0rCrmrnrrerprqrrs r rZz TestSuite._tearDownPreviousClasss%(rs      IIIIIFIIIXi6i6i6i6i6 i6i6i6X$$$$$6$$$L6r __pycache__/runner.cpython-311.pyc000064400000040140151030032340012755 0ustar00 !A?h$dZddlZddlZddlZddlmZddlmZddlm Z dZ Gdd e Z Gd d ej ZGd d e ZdS)z Running testsN)result)_SubTest)registerResultTc&eZdZdZdZdZddZdS)_WritelnDecoratorz@Used to decorate file-like objects with a handy 'writeln' methodc||_dSN)stream)selfr s (/usr/lib64/python3.11/unittest/runner.py__init__z_WritelnDecorator.__init__s  cR|dvrt|t|j|S)N)r __getstate__)AttributeErrorgetattrr )r attrs r __getattr__z_WritelnDecorator.__getattr__s. - - - && &t{4(((rNc^|r|||ddSN )write)r args r writelnz_WritelnDecorator.writelns1   JJsOOO 4rr )__name__ __module__ __qualname____doc__rrrrr rrsLJJ))) rrceZdZdZdZdZfdZdZfdZdZ fdZ fd Z fd Z fd Z fd Zfd ZfdZdZdZxZS)TextTestResultzhA test result class that can print formatted text results to a stream. Used by TextTestRunner. zF======================================================================zF----------------------------------------------------------------------ctt||||||_|dk|_|dk|_||_d|_dS)NrT)superr"rr showAlldots descriptions_newline)r r r' verbosity __class__s r rzTextTestResult.__init__&sU nd##,,V\9MMM  1} N ( rc|}|jr&|r$dt||fSt|Sr)shortDescriptionr'joinstr)r testdoc_first_lines r getDescriptionzTextTestResult.getDescription.sN..00    99c$ii899 9t99 rc8tt|||jri|j|||jd|jd|_dSdS)N ... F) r$r" startTestr%r rr1flushr(r r/r*s r r4zTextTestResult.startTest5s nd##--d333 < " K  d11$77 8 8 8 K  g & & & K     !DMMM  " "rct|t}|s|jr|js|j|r|jd|j|||jd|j||jd|_dS)Nz r3T) isinstancerr(r rrr1r5)r r/status is_subtests r _write_statuszTextTestResult._write_status=sh//  ' '= & ##%%% ( !!$''' K  d11$77 8 8 8 K  g & & & F###  rc||jrIt|d|jr||dn||dnp|jrit|d|jr|jdn|jd|jtt| |||dS)NrFAILERRORFE) r% issubclassfailureExceptionr;r&r rr5r$r" addSubTest)r r/subtesterrr*s r rCzTextTestResult.addSubTestJs ?| $c!fg&>??9&&w7777&&w8888 $c!fg&>??+K%%c****K%%c*** !!### nd##..tWcBBBBBrctt|||jr||ddS|jr5|jd|jdSdS)Nok.) r$r" addSuccessr%r;r&r rr5r6s r rIzTextTestResult.addSuccessYs nd##..t444 <   tT * * * * * Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr>r@) r$r"addErrorr%r;r&r rr5r r/rEr*s r rKzTextTestResult.addErroras nd##,,T3777 <   tW - - - - - Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr=r?) r$r" addFailurer%r;r&r rr5rLs r rNzTextTestResult.addFailureis nd##..tS999 <   tV , , , , , Y K  c " " " K         rc6tt||||jr+||d|dS|jr5|jd|j dSdS)Nz skipped {0!r}s) r$r"addSkipr%r;formatr&r rr5)r r/reasonr*s r rQzTextTestResult.addSkipqs nd##++D&999 <   t_%;%;F%C%C D D D D D Y K  c " " " K         rcJtt||||jr5|jd|jdS|jr5|jd|jdSdS)Nzexpected failurex) r$r"addExpectedFailurer%r rr5r&rrLs r rVz!TextTestResult.addExpectedFailureys nd##66tSAAA < K   2 3 3 3 K        Y K  c " " " K         rcHtt|||jr5|jd|jdS|jr5|jd|jdSdS)Nzunexpected successu) r$r"addUnexpectedSuccessr%r rr5r&rr6s r rYz#TextTestResult.addUnexpectedSuccesss nd##88>>> < K   4 5 5 5 K        Y K  c " " " K         rc|js|jr2|j|j|d|j|d|jt|dd}|ro|j|j |D]2}|jd| |3|jdSdS)Nr>r=unexpectedSuccessesr zUNEXPECTED SUCCESS: ) r&r%r rr5printErrorListerrorsfailuresr separator1r1)r r[r/s r printErrorszTextTestResult.printErrorss 9   K   ! ! ! K      GT[111 FDM222%d,A2FF  K   0 0 0+ X X ##$V4;N;Nt;T;T$V$VWWWW K          rcb|D]\}}|j|j|j|d|||j|j|jd|z|jdS)Nz: z%s)r rr_r1 separator2r5)r flavourr]r/rEs r r\zTextTestResult.printErrorLists  ID# K   0 0 0 K  GGGD4G4G4M4M4M N O O O K   0 0 0 K  s + + + K         r)rrrrr_rbrr1r4r;rCrIrKrNrQrVrYr`r\ __classcell__)r*s@r r"r"sWJJ"""""    C C C C C                                         rr"c4eZdZdZeZ d dddZdZd ZdS) TextTestRunnerzA test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. NTrF) tb_localsc| tj}t||_||_||_||_||_||_||_ | ||_ dSdS)zConstruct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. N) sysstderrrr r'r)failfastbufferrgwarnings resultclass) r r r'r)rkrlrnrmrgs r rzTextTestRunner.__init__sf >ZF'// ("   "   "*D    # "rcN||j|j|jSr )rnr r'r))r s r _makeResultzTextTestRunner._makeResults! T->OOOrc|}t||j|_|j|_|j|_t j5|jr>t j|j|jdvrt jdtdtj }t|dd}| | ||t|dd}| |n##t|dd}| |wwxYwtj }dddn #1swxYwY||z }|j t|dr|j|j|j}|jd ||d krd pd |fz|jd x} x} } t't(|j|j|jf} | \} } } n#t0$rYnwxYwg} |jsw|jdt)|jt)|j}}|r| d|z|r| d|zn|jd| r| d| z| r| d| z| r| d| z| r2|jdd| dn|jd|j|S)z&Run the given test case or test suite.)defaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRunN stopTestRunrbzRan %d test%s in %.3fsrrPrFAILEDz failures=%dz errors=%dOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (z, )r) rprrkrlrgrmcatch_warnings simplefilterfilterwarningsDeprecationWarningtime perf_counterrr`hasattrr rrbtestsRunmaplenexpectedFailuresr[skippedr wasSuccessfulrr^r]appendr-r5)r r/r startTimerwrxstopTime timeTakenrun expectedFailsr[rresultsinfosfailederroreds r rzTextTestRunner.runs!!##v-  >  $ & & + +} F%dm444 =$999+H%7$DFFFF)++I"6>4@@L'  "V %fmTBB *KMMM&fmTBB *KMMMM+(**H/ + + + + + + + + + + + + + + +0y(  6< ( ( 3 K   1 2 2 2o 4 #("2s"8b)DE F F F 899 9+g B# 7 & : & 011G ;B 7M.    D  #v#%% $ K  h ' ' '!&/22C 4F4FGF 5 ]V3444 4 [72333 K  d # # #  1 LL/ 0 0 0  A LL/-? @ @ @  J LL25HH I I I  $ K   499U+;+;+;+; = > > > > K  d # # #  s=A6D= C;D=; DD==EE'H HH)NTrFFNN) rrrrr"rnrrprr rr rfrfsr !KABJN+#+++++(PPPGGGGGrrf)rrirrmryrcasersignalsr __unittestobjectr TestResultr"rfr rr rs ######           @ @ @ @ @ V&@ @ @ FfffffVfffffr__pycache__/_log.cpython-311.opt-1.pyc000064400000011313151030032340013323 0ustar00 !A?h ddlZddlZddlmZejdddgZGddejZGd d eZdS) N)_BaseTestCaseContext_LoggingWatcherrecordsoutputc$eZdZdZdZdZdZdS)_CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cntj|tgg|_dSN)loggingHandler__init__rwatcherselfs &/usr/lib64/python3.11/unittest/_log.pyrz_CapturingHandler.__init__s-  &&&&r2.. cdSr rs rflushz_CapturingHandler.flushs rc|jj|||}|jj|dSr )rrappendformatr)rrecordmsgs remitz_CapturingHandler.emitsK ##F+++kk&!! ""3'''''rN)__name__ __module__ __qualname____doc__rrrrrrr r sK///   (((((rr c(eZdZdZdZdZdZdZdS)_AssertLogsContextz6A context manager for assertLogs() and assertNoLogs() z"%(levelname)s:%(name)s:%(message)sctj||||_|r&tj|||_ntj|_d|_||_ dSr ) rr logger_namer _nameToLevelgetlevelINFOrno_logs)r test_caser$r'r)s rrz_AssertLogsContext.__init__!s\%dI666&  & -11%??DJJ DJ rc,t|jtjr|jx}|_n tj|jx}|_tj|j}t}| |j | ||j |_ |j dd|_|j |_|j|_|g|_ | |j d|_|jrdS|j S)NF) isinstancer$r Loggerlogger getLogger FormatterLOGGING_FORMATr setLevelr' setFormatterrhandlers old_handlers old_level propagate old_propagater))rr. formatterhandlers r __enter__z_AssertLogsContext.__enter__+s d& 7 7 G#'#3 3FT[[#*#4T5E#F#F FFT[%d&9:: #%%$$$Y''' "OAAA.#-") ###  <  Frc|j|j_|j|j_|j|j|dS|jrSt|j j dkr4| d |j j dSdSt|j j dkrL| d tj|j|jjdSdS)NFrzUnexpected logs found: {!r}z-no logs of level {} or higher triggered on {})r5r.r4r8r7r2r6r)lenrr _raiseFailurerrr getLevelNamer'name)rexc_type exc_valuetbs r__exit__z_AssertLogsContext.__exit__?s#0  $ 2  T^,,,  5 < Q4<'((1,,""188 +-,4<'((A--""CVG0<NOOQQQQQ.-rN)rrrr r1rr;rDrrrr"r"sQ@@9N(QQQQQrr") r collectionscaser namedtuplerr r r"rrrrHs&&&&&&)+():*3X)>@@(((((((($:Q:Q:Q:Q:Q-:Q:Q:Q:Q:Qr__pycache__/case.cpython-311.opt-2.pyc000064400000175570151030032340013337 0ustar00 !A?h@ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z mZmZmZmZdZeZdZGddeZGd d eZGd d eZGd deZdZdZdZdZgZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'GddZ(Gdde(Z)Gdd e)Z*Gd!d"e)Z+Gd#d$ej,Z-Gd%d&eZ.Gd'd(e.Z/Gd)d*e.Z0dS)+N)result)strclass safe_repr_count_diff_all_purpose_count_diff_hashable_common_shorten_reprTz@ Diff is %s characters long. Set self.maxDiff to None to see it.ceZdZdS)SkipTestN__name__ __module__ __qualname__&/usr/lib64/python3.11/unittest/case.pyr r srr ceZdZdS) _ShouldStopNr rrrrr!rrceZdZdS)_UnexpectedSuccessNr rrrrr&rrrc8eZdZddZejddZdS)_OutcomeNchd|_||_t|d|_d|_d|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessexpectedFailure)selfrs r__init__z_Outcome.__init__-s8!& (/ (E(E% #rFc#BK|j}d|_ dV|r(|jr!|j|j|dn#t$rt $r4}d|_t |j|t|Yd}~nzd}~wt$rYnktj }|j r||_ nAd|_|r"|j|j||nt|j||d}YnxYw|jo||_dS#|jo||_wxYw)NTF)rrr test_caseKeyboardInterruptr _addSkipstrrsysexc_inforr _addError)r!r$subTest old_successer)s rtestPartExecutorz_Outcome.testPartExecutor4sql   8 EEE, M4< M &&y':ItLLL-!     5 5 5 DL T[)SVV 4 4 4 4 4 4 4 4    D |~~H% @'/$$$ @K**9+> 8TTTTdk9h???HHH  <7KDLLL4<7KDL 7 7 7 7s;A+DC;*B?D C;DA&C;9DDN)F)r rrr" contextlibcontextmanagerr.rrrrr,sL$$$$888888rrct|dd}||||dStjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reported)getattrwarningswarnRuntimeWarning addSuccess)rr$reasonr3s rr&r&Usffi..G 6""""" L$a ) ) ))$$$$$rc|C|Ct|d|jr|j||dS|j||dSdSdSNr) issubclassfailureException addFailureaddError)rtestr)s rr*r*^si h2 hqk4#8 9 9 , F dH - - - - - FOD( + + + + + 22rc|Sr/r)objs r_idrDes Jrct|} |j}|j}n/#t$r"t d|jd|jddwxYw||}|||ddd|S)N'.z6' object does not support the context manager protocol)type __enter____exit__AttributeError TypeErrorrr)cm addcleanupclsenterexitrs r_enter_contextrRis r((CO | OOODCNDDS-=DDDEEJN OOU2YYFJtRtT*** Ms  ,A cB t|||fdSr/)_module_cleanupsappend)functionargskwargss raddModuleCleanuprYys(2XtV455555rc. t|tSr/)rRrY)rMs renterModuleContextr[~s0 ". / //rc g}trZt\}}} ||i|n,#t$r}||Yd}~nd}~wwxYwtZ|r|ddSr<)rTpop ExceptionrU) exceptionsrVrWrXexcs rdoModuleCleanupsrasJ #!1!5!5!7!7$ # Hd %f % % % % # # #   c " " " " " " " " # # ms2 AAAcf fd}ttjr}d||S|S)Nct|ts!tj|fd}|}d|_|_|S)Nc"tr/r )rWrXr:s r skip_wrapperz-skip..decorator..skip_wrappersv&&&rT) isinstancerH functoolswraps__unittest_skip____unittest_skip_why__) test_itemrfr:s r decoratorzskip..decorators^)T** % _Y ' ' ' ' ' '( ' '$I&* #*0 'r)rgtypes FunctionType)r:rmrls` rskiprqsX     &%,--$ y### rc4 |rt|StSr/rqrD conditionr:s rskipIfrvs"F|| Jrc4 |st|StSr/rsrts r skipUnlessrxs" F|| Jrcd|_|S)NT)__unittest_expecting_failure__)rls rr r s/3I, rct|trtfd|DSt|tot |S)Nc38K|]}t|VdSr/) _is_subtype).0r-basetypes r z_is_subtype..s->>;q(++>>>>>>r)rgtupleallrHr=)expectedrs `rr}r}sW(E""?>>>>X>>>>>> h % % H*Xx*H*HHrceZdZdZdZdS)_BaseTestCaseContextc||_dSr/)r$)r!r$s rr"z_BaseTestCaseContext.__init__s "rcv|j|j|}|j|r/)r$_formatMessagemsgr>)r! standardMsgrs r _raiseFailurez"_BaseTestCaseContext._raiseFailures1n++DHkBBn--c222rN)r rrr"rrrrrrs2###33333rrceZdZddZdZdS)_AssertRaisesBaseContextNct||||_||_|t j|}||_d|_d|_dSr/) rr"rr$recompileexpected_regexobj_namer)r!rr$rs rr"z!_AssertRaisesBaseContext.__init__sU%%dI666  "  %Z77N, rc t|j|jst|d|j|sM|dd|_|r,ttt|d|d}S|^}} |j |_ n$#t$rt||_ YnwxYw|5||i|dddn #1swxYwYd}dS#d}wxYw)Nz() arg 1 must be rz1 is an invalid keyword argument for this function) r}r _base_typerL_base_type_strr]rnextiterr rrKr')r!namerWrX callable_objs rhandlez_AssertRaisesBaseContext.handles  t}do>> =!%t':':!<=== !::eT22M#7;DLL7I7I7I7I%LMMMDD#' L4 2 , 5 ! 2 2 2 #L 1 1  2 . . d-f--- . . . . . . . . . . . . . . .DDD4DKKKKsZA?C!C! BC!B85C!7B88C!= C C!CC!CC!!C%r/)r rrr"rrrrrrs7rrcDeZdZ eZdZdZdZee j Z dS)_AssertRaisesContextz-an exception type or tuple of exception typesc|Sr/rr!s rrIz_AssertRaisesContext.__enter__s rc| |jj}n$#t$rt|j}YnwxYw|jr/|d||jn=|d|ntj|t||jsdS| d|_ |j dS|j }| t|s;|d|jt|dS)Nz{} not raised by {}z {} not raisedFT"{}" does not match "{}")rr rKr'rrformat traceback clear_framesr=with_traceback exceptionrsearchpattern)r!exc_type exc_valuetbexc_namers rrJz_AssertRaisesContext.__exit__se   .=1! . . .t}-- .} E""#8#?#?@D $O$OPPPP""?#9#9(#C#CDDDD  "2 & & &(DM22 5"11$77   &4,$$S^^44 >   9@@#+S^^ = = > > >ts 22N) r rr BaseExceptionrrrIrJ classmethodro GenericAlias__class_getitem__rrrrrsPMJDN6$ E$677rrc$eZdZ eZdZdZdZdS)_AssertWarnsContextz(a warning type or tuple of warning typesc6ttjD]}t |ddri|_t jd|_|j |_t j d|j |S)N__warningregistry__T)recordalways) listr(modulesvaluesr5rr6catch_warningswarnings_managerrI simplefilterr)r!vs rrIz_AssertWarnsContext.__enter__ sck((**++ + +Aq/66 +(*% ( 7t D D D-7799 h 666 rc|j||||dS |jj}n$#t$rt |j}YnwxYwd}|jD]s}|j}t||js||}|j (|j t |sR||_ |j |_ |j |_ dS|@|d|j jt ||jr0|d||jdS|d|dS)Nrz{} not triggered by {}z{} not triggered)rrJrr rKr'r6messagergrrwarningfilenamelinenorrrr)r!rrrrfirst_matchingmws rrJz_AssertWarnsContext.__exit__+s &&xB???   F *}-HH * * *4=))HHH *  A Aa// %!"#/'..s1vv660DLJDM(DK FF  %   9@@(0#n2E2E G G H H H = D   7>>x?C} N N O O O O O   188BB C C C C Cs /AAN)r rrWarningrrrIrJrrrrrsDLJ?N    D D D D DrrceZdZdZdS)_OrderedChainMapc#~Kt}|jD]$}|D]}||vr|||V %dSr/)setmapsadd)r!seenmappingks r__iter__z_OrderedChainMap.__iter__Os`uuy  G  D==HHQKKKGGG   rN)r rrrrrrrrNs#rrceZdZ eZdZdZdZfdZdNdZ dZ dZ d Z e d Ze d Zd Zd Ze dZe dZdZdZdZdZdZdZdZdZejefdZdZ dZ!dZ"dZ#dZ$dZ%dOd Z&d!Z'e d"Z(d#Z)d$Z*d%Z+dOd&Z,dOd'Z-dOd(Z.d)Z/d*Z0d+Z1dPd,Z2dPd-Z3d.Z4dOd/Z5dOd0Z6dOd1Z7 dQd2Z8 dQd3Z9dPd4Z:d5Z;dOd6ZdOd9Z?dOd:Z@dOd;ZAdOd<ZBdOd=ZCdOd>ZDdOd?ZEdOd@ZFdOdAZGdOdBZHdOdCZIdOdDZJdOdEZKdOdFZLdOdGZMdOdHZNdIZOdJZPdOdKZQdOdLZRdMZSeSe6xZTZUeSe7xZVZWeSe8xZXZYeSe9xZZZ[eSe.xZ\Z]eSe0Z^eSe-Z_eSeOZ`eSeQZaeSeRZbxZcS)RTestCaseTiicVd|_g|_tj|i|dS)NF)_classSetupFailed_class_cleanupssuper__init_subclass__)rOrWrX __class__s rrzTestCase.__init_subclass__s5 % !!42622222rrunTestc< ||_d|_d|_ t||}|j|_n0#t $r#|dkrt d|jd|YnwxYwg|_d|_ i|_ | td| td| td| td| t d| t"d dS) NzNo testrzno such test method in : assertDictEqualassertListEqualassertTupleEqualassertSetEqualassertMultiLineEqual)_testMethodName_outcome_testMethodDocr5__doc__rK ValueErrorr _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictrrr frozensetr')r! methodName testMethods rr"zTestCase.__init__sF  * ' 5 z22J#-"4D   4 4 4Y&&!j~~~zz"3444'& 4 %'!   '8999   '8999   (:;;;   &6777   ,<===   &<=====s5*A"!A"c ||j|<dSr/)r)r!typeobjrVs rrzTestCase.addTypeEqualityFuncs .6!'***rcB |j|||fdSr/)rrUr!rVrWrXs r addCleanupzTestCase.addCleanups- K xv677777rc. t||jSr/)rRr)r!rMs r enterContextzTestCase.enterContexts b$/222rcB |j|||fdSr/)rrUrOrVrWrXs raddClassCleanupzTestCase.addClassCleanups+ 4 ""HdF#;<<<<t|jd|jS)NrGrrrrs ridz TestCase.ids#"4>2222D4H4HIIrclt|t|urtS|j|jkSr/)rHNotImplementedrr!others r__eq__zTestCase.__eq__s0 ::T%[[ ( (! !#u'<<rrs r__repr__zTestCase.__repr__s.(((($*>*>*>@ @rc+K |j |jjsdVdS|j}|t|}n|j|}t ||||_ |j|jd5dVdddn #1swxYwY|jjs|jj }||j rtn|jj rt||_dS#||_wxYw)NT)r+) rrrrparams new_child_SubTestr.rrfailfastrr )r!rr$parent params_maprs rr+zTestCase.subTestsN =  (N EEE F >)&11JJ0088J sJ77  #// t/LL                 =( "-%&/%%%. ""!"DMMMFDM " " " "s0'!C)B C)BC) B!?C)) C2c |j}|||dS#t$r.tjdt|j|YdSwxYw)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerKr6r7r8r9)r!rr)r+s r_addExpectedFailurezTestCase._addExpectedFailure&s~ /!'!:   tX . . . . .  $ $ $ M\( * * * F d # # # # # # $s4AAc |j}||dS#t$rXtjdt t d#t $r'|j|tjYYdSwxYwwxYw)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrKr6r7r8rr?r(r))r!rr.s r_addUnexpectedSuccesszTestCase._addUnexpectedSuccess0s '#)#>  !  & & & & & 8 8 8 M_( * * * 8(d2% 8 8 8!!$ 7777777 8 8s&$A8A,A4/A83A44A8c.|dSr/)rrs r _callSetUpzTestCase._callSetUp?s rc^|"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case (r) stacklevel)r6r7DeprecationWarning)r!methods r_callTestMethodzTestCase._callTestMethodBs\ 688  M2(.2223ERS U U U U U U rc.|dSr/)rrs r _callTearDownzTestCase._callTearDownGs rc||i|dSr/rrs r _callCleanupzTestCase._callCleanupJs$!&!!!!!rNc|C|}t|dd}t|dd}| |nd}|j| t||j}t|jddst|ddrWt|jddpt|dd}t |||||j|| |SSt|ddpt|dd}t|} ||_| |5| dddn #1swxYwY|j r||_ | |5| |dddn #1swxYwYd|_ | |5|dddn #1swxYwY||j rK|r9|jr|||jn&||n|j||d|_d}d|_|j|| |SS#d|_d}d|_wxYw#|j|| |wwxYw)N startTestRun stopTestRunrjFrkrnrz)rr5 startTestrrr&stopTestrrr.r1rrr7r9 doCleanupsr r,r/r9)r!rr=r>rskip_whyroutcomes rrunz TestCase.runMs >++--F"6>4@@L!&->>K' K2  t';<FFM $DeLL v&&G % ' --d33&&OO%%%&&&&&&&&&&&&&&&?-0AG- 11$7799,,Z88899999999999999905G- 11$77--**,,,---------------!!!?0(0"2? 44VW=TUUUU 66v>>>>))$///+/'!%  FOD ! ! !& '+/'!% $$$$ FOD ! ! !& 'sA5J(,1J(J:E JEJ"E#&J F+ J+F//J2F/3JG3' J3G77J:G7;A*J%J(J%%J((Kc |jp t}|jrb|j\}}}||5|j|g|Ri|dddn #1swxYwY|jb|jSr/)rrrr]r.r;r)r!rCrVrWrXs rrAzTestCase.doCleanupss --8::n =%)^%7%7%9%9 "HdF))$// = =!!(%> "HdF ?$)&)))) ? ? ?'..s|~~>>>>> ? ! ? ? ? ? ?s75A/.A/c|j|i|Sr/)rD)r!rWkwdss r__call__zTestCase.__call__stx&&&&rc t||j}t|jddst|ddr6t|jddpt|dd}t||||||jr7|j\}}}|j |g|Ri||j5dSdS)NrjFrkrn) r5rrr r1r7r9rr]r;)r!rrBrVrWrXs rdebugzTestCase.debugsDT4#788 DN$7 ? ? % J 3U ; ; % 0GLLL":/FKK 8$$ $  Z((( n 9%)^%7%7%9%9 "HdF D h 8 8 8 8 8 8 8n 9 9 9 9 9rc" t|r/re)r!r:s rskipTestzTestCase.skipTestsvrc. ||r/)r>)r!rs rfailz TestCase.fails7##C(((rc |r;||dt|z}||dS)Nz%s is not falserrr>r!exprrs r assertFalsezTestCase.assertFalsesL1  -%%c+>.$??GGdGNNNNs,0cR t||}|d||S)N assertWarnsrr)r!expected_warningrWrXr`s rrbzTestCase.assertWarnss/ 6&&6==~~mT6:::rc. ddlm}||||dS)Nr_AssertLogsContextFno_logs_logrgr!loggerlevelrgs r assertLogszTestCase.assertLogs"s5 ( -,,,,,!!$uEEEErc. ddlm}||||dS)NrrfTrhrjrls r assertNoLogszTestCase.assertNoLogs:s5 -,,,,,!!$tDDDDrc t|t|urP|jt|}|'t|trt ||}|S|jSr/)rHrgetrgr'r5_baseAssertEqual)r!firstsecondasserters r_getAssertEqualityFunczTestCase._getAssertEqualityFuncCsq ;;$v,, & &044T%[[AAH#h,,7&tX66H$$rc ||ks>dt||z}|||}||dS)N%s != %s)r rr>)r!rurvrrs rrtzTestCase._baseAssertEqual]sSH$';E6'J'JJK%%c;77C'',, ,rcP |||}||||dS)N)r)rx)r!rurvrassertion_funcs r assertEqualzTestCase.assertEqualds; 44UFCCuf#......rc ||ksJ||t|dt|}||dS)N == rS)r!rurvrs rassertNotEqualzTestCase.assertNotEqualksj %%c59I9I9I9I:CF:K:K:K,MNNC'',, ,rc  ||krdS||tdt||z }|K||krdSt|dt|dt|dt|d}nO|d}t||dkrdSt|dt|d|dt|d}|||}||) N specify delta or places not bothz !=  within  delta ( difference)rz places (rLabsrroundrr>r!rurvplacesrdeltadiffrs rassertAlmostEqualzTestCase.assertAlmostEqualts1  F?? F  !3>?? ?56>""  u}}%    &!!!!%    $ !KK ~T6""a''%    &!!!!$ !K !!#{33##C(((rc  ||tdt||z }|Q||ks||krdSt|dt|dt|dt|d}nE|d}||kst||dkrdSt|dt|d|d}|||}||) Nrrrrrrrz placesrrs rassertNotAlmostEqualzTestCase.assertNotAlmostEquals#   !3>?? ?56>""  VOO%    &!!!!%    $ !KK ~VOOtV)<)<)A)A9B59I9I9I9I9B69J9J9J9J9?AK!!#{33##C(((rc  |x|j}t||s(|d|dt|t||s(|d|dt|nd}d} t |}n#t t f$rd|z}YnwxYw|- t |}n#t t f$rd|z}YnwxYw|||krdSd|ft||zz}tt||D]} || } n(#t tt f$r|d| |fzz }YnwxYw || } n(#t tt f$r|d | |fzz }YnQwxYw| | kr|d | ft| | zzz }n+||kr$|"t|t|krdS||krS|d |||z fzz } |d |t||fzz }n#t tt f$r |d ||fzz }Yn]wxYw||krS|d|||z fzz } |d |t||fzz }n'#t tt f$r |d||fzz }YnwxYw|} dd tjt!j|t!j|z} || | } ||| }||dS)NzFirst sequence is not a rzSecond sequence is not a sequencez(First %s has no length. Non-sequence?z)Second %s has no length. Non-sequence?z%ss differ: %s != %s z( Unable to index element %d of first %s z) Unable to index element %d of second %s z# First differing element %d: %s %s z+ First %s contains %d additional elements. zFirst extra element %d: %s z'Unable to index element %d of first %s z, Second %s contains %d additional elements. z(Unable to index element %d of second %s r )r rgr>rlenrLNotImplementedError capitalizer rangemin IndexErrorrHjoindifflibndiffpprintpformat splitlines_truncateMessagerrQ)r!seq1seq2rseq_type seq_type_name differinglen1len2iitem1item2rdiffMsgs rassertSequenceEqualzTestCase.assertSequenceEquals   $-MdH-- L++++8==)D///-KLLLdH-- L++++8==)D///-KLLL L'M  #t99DD./ # # #B!#III #   '4yy23 ' ' 'G%'  '  t||0"--//1(t4456I3tT??++   GEE!:/BC"N"#]!3#45IEE  GEE!:/BC"O"#]!3#45IEE E>>"K#$$)=eU)K)K"K#MNIE" DLLX%5JJ$t**,,Fd{{+.;TD[-IJK K"A#'4:)>)>"?#@AII!:/BCKKK#259=4I#JKIIIK+.;TD[-IJK L"A#'4:)>)>"?#@AII!:/BCLLL#36:M5J#KLIIIL  M&...99;; ...99;; = =>>>++KAA !!#{33 #slBB*)B*0CCC0D99!EE"E++!FF4H!H65H6 I++!JJcx|j}|t||kr||zS|tt|zzSr/)maxDiffr DIFF_OMITTED)r!rrmax_diffs rrzTestCase._truncateMessage's?<  s4yyH44T> !,T233rcD ||||tdSN)r)rr)r!list1list2rs rrzTestCase.assertListEqual-s,    sT BBBBBrcD ||||tdSr)rr)r!tuple1tuple2rs rrzTestCase.assertTupleEqual9s,    u EEEEErcL ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw|s|sdSg}|r<|d|D]$}|t |%|r<|d|D]$}|t |%d|} |||| dS)Nz/invalid type when attempting set difference: %sz2first argument does not support set difference: %sz3second argument does not support set difference: %sz*Items in the first set but not the second:z*Items in the second set but not the first:r ) differencerLrQrKrUreprrr) r!set1set2r difference1r- difference2linesitemrs rrzTestCase.assertSetEqualDs+  P//$//KK M M M IIG!K L L L L L L L L P P P IIJQN O O O O O O O O P Q//$//KK M M M IIG!K L L L L L L L L Q Q Q IIKaO P P P P P P P P Q {  F  ) LLE F F F# ) ) T$ZZ((((  ) LLE F F F# ) ) T$ZZ((((ii&&  $%%c;7788888sD A/A A/ A**A/3B CB00 C=CCc ||vrLt|dt|}||||dSdS)N not found in rrQrr!member containerrrs rassertInzTestCase.assertInosgR  " "2;F2C2C2C2C2;I2F2F2FHK IId))#{;; < < < < < # "rc ||vrLt|dt|}||||dSdS)Nz unexpectedly found in rrs r assertNotInzTestCase.assertNotInvsgV Y  ;DV;L;L;L;L8A)8L8L8LNK IId))#{;; < < < < <  rc ||urLt|dt|}||||dSdS)Nz is not rr!expr1expr2rrs rassertIszTestCase.assertIs}sfR   ,5e,<,<,<,<-6u-=-=-=?K IId))#{;; < < < < <  rc ||ur=dt|}||||dSdS)Nzunexpectedly identical: rrs r assertIsNotzTestCase.assertIsNotsRV E>>>:CE:J:J:JLK IId))#{;; < < < < < >rc ||td||td||krdt||z}ddt jt j|t j|z}| ||}| | ||dSdS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryrzr ) assertIsInstancerr rrrrrrrrQr)r!d1d2rrrs rrzTestCase.assertDictEquals b$(LMMM b$(MNNN 88$';B'C'CCK499W]!>"--88::!>"--88::&<&<===D// TBBK IId))#{;; < < < < < 8rc J tjdtg}g}|D]u\}}||vr|||||krJ|t |dt |dt ||v|s|sdSd}|r"ddd|Dz}|r"|r|dz }|d d|zz }||||dS) Nz&assertDictContainsSubset is deprecatedz , expected: z , actual: rnz Missing: %s,c34K|]}t|VdSr/)r)r~rs rrz4TestCase.assertDictContainsSubset..s83=3=A9Q<<3=3=3=3=3=3=rz; zMismatched values: %s) r6r7r5itemsrUrrrQr) r!subset dictionaryrmissing mismatchedkeyvaluers rassertDictContainsSubsetz!TestCase.assertDictContainsSubsets}@ >( * * *  ,,.. @ @JC*$$s####*S/))!!#,S>>>>9U3C3C3C3C#,Z_#=#=#=#?@@@ :  F  ='#((3=3=4;3=3=3=+=+==K  J $t# 2SXXj5I5II IK $%%c;7788888rc t|t|}} tj|}tj|}||krdSt||}n #t$rt ||}YnwxYw|rfd}d|D}d|} ||| }|||}| |dSdS)NzElement counts were not equal: cg|]}d|zS)z First has %d, Second has %d: %rr)r~rs r z-TestCase.assertCountEqual..sWWW47$>WWWrr ) r collectionsCounterrrLrrrrrQ) r!rurvr first_seq second_seq differencesrrrs rassertCountEqualzTestCase.assertCountEquals !%U T&\\:  F' 22E (44F .y*EEKK  I I I1)ZHHKKK I  A?c ||td||td||kr*t||jkst||jkr|||||d}|d}t|dkr%|d|kr |dzg}|dzg}dt||z}dd tj ||z}| ||}| | ||dSdS) NzFirst argument is not a stringzSecond argument is not a stringT)keependsrz r rzrn)rr'r_diffThresholdrtrr r rrrrrQr)r!rurvr firstlines secondlinesrrs rrzTestCase.assertMultiLineEqualsd; eS*JKKK fc+LMMM F??E T000F d111%%eVS999))4)88J ++T+::K:!## F(;(;u(D(D#dl^ %}o $';E6'J'JJK"'''- K"H"HIIID// TBBK IId))#{;; < < < < < ?rc ||ksLt|dt|}||||dSdS)Nz not less than rr!abrrs r assertLesszTestCase.assertLesssYQ1uu3K IId))#{;; < < < < < ?rcf |-d}||||dSdS)Nzunexpectedly None)rQrrs rassertIsNotNonezTestCase.assertIsNotNones>6 ;-K IId))#{;; < < < < < ;rc t||s?t|d|}||||dSdS)Nz is not an instance of rgrrQrr!rCrOrrs rrzTestCase.assertIsInstance sa #s## =;DS>>>>33OK IId))#{;; < < < < < = =rc t||r?t|d|}||||dSdS)Nz is an instance of rrs rassertNotIsInstancezTestCase.assertNotIsInstances_: c3   =7@~~~~ssKK IId))#{;; < < < < < = =rcT t|||}|d||S)NassertRaisesRegexr^)r!r_rrWrXr`s rrzTestCase.assertRaisesRegexs2 ''94PP~~14@@@rcT t|||}|d||S)NassertWarnsRegexrc)r!rdrrWrXr`s rrzTestCase.assertWarnsRegex(s2 &&6nMM~~0$???rc t|ttfrtj|}||s8d|jd|}|||}||dS)NzRegex didn't match: r) rgr'bytesrrrrrr>)r!textrrrs r assertRegexzTestCase.assertRegex;sK nsEl 3 3 8Z77N$$T** - -&&&.K%%c;77C'',, ,  - -rcd t|ttfrtj|}||}|rgd|||d|jd|}| ||}| |dS)NzRegex matched: z matches z in ) rgr'rrrrstartendrrr>)r!runexpected_regexrmatchrs rassertNotRegexzTestCase.assertNotRegexGsG &e 5 5 <!z*:;;  ''--  - -U[[]]UYY[[0111 (((K %%c;77C'',, , - -rcfd}|S)Ncztjdjtd|i|S)NzPlease use {0} instead.r4)r6r7rr r5)rWrX original_funcs rdeprecated_funcz,TestCase._deprecate..deprecated_funcWsG M)001GHH"A ' ' '!=$1&11 1rr)rrs` r _deprecatezTestCase._deprecateVs$ 2 2 2 2 2 r)rr/)NNNNN)dr rrAssertionErrorr>rZrrrr"rrrrrrrrrrrrrrrrrr"r0r1_subtest_msg_sentinelr+r,r/r1r7r9r;rDrArHrKrMrOrQrVrXrr]rbrorqrxrtr}rrrrrrrrrrrrrrrrrrrrrrrrrrr rrfailUnlessEqual assertEquals failIfEqualassertNotEqualsfailUnlessAlmostEqualassertAlmostEqualsfailIfAlmostEqualassertNotAlmostEquals failUnlessassert_failUnlessRaisesfailIfassertRaisesRegexpassertRegexpMatchesassertNotRegexpMatches __classcell__rs@rrrXs@&KGN33333 >>>>@ 6 6 6888333==[= 77[7      VV[Vaa[a###CCCJJJ=== 888eee@@@/####</// ' ' 'UUU """====~    ? ?[ ?'''999"))))---- ---- III*B;;;>FFFF0EEEE%%%4----////----AE $+)+)+)+)ZDH#'!)!)!)!)FaaaaF444 C C C C F F F F)9)9)9)9V================ = = = =9999:@====(==== ==== ==== ==== ==== ==== ======== AAA @@@& - - - - - - - -&0Z %<%<$>>K/1;)r!r$rr$rs rr"z_SubTest.__init__s?  " ) :rc td)Nzsubtests cannot be run directly)rrs rrz_SubTest.runTests!"CDDDrctg}|jtur-|d|j|jr^dd|jD}|d|d|pdS)Nz[{}]z, c3HK|]\}}d||VdS)z{}={!r}N)r)r~rrs rrz+_SubTest._subDescription..sJ$3$3Q  A&&$3$3$3$3$3$3rz({}) z ())r=rrUrr$rr)r!parts params_descs r_subDescriptionz_SubTest._subDescriptions = 5 5 5 LLt}55 6 6 6 ; 5))$3$3"k//11$3$3$333K LL{33 4 4 4xx/-/rcd|j|SNz{} {})rr$rrDrs rrz _SubTest.ids0~~dn//1143G3G3I3IJJJrc6 |jSr/)r$rrs rrz_SubTest.shortDescriptions ~..000rc\d|j|SrF)rr$rDrs rrz_SubTest.__str__s$~~dnd.B.B.D.DEEEr) r rrr"rrDrrrr'r(s@rr&r&s;;;;;EEE 0 0 0KKK111 FFFFFFFrr&)1r(rhrrrr6rr0rrornrutilrrrrr __unittestobjectrrr^r rrrr&r*rDrRrTrYr[rarqrvrxr r}rrrrChainMaprrr*r&rrrrMs   ?????????????? 7 y)  &8&8&8&8&8v&8&8&8R%%%,,,   666 000    (III 33333333'''''3'''T$8$8$8$8$83$8$8$8N1D1D1D1D1D21D1D1Dh{+P8P8P8P8P8vP8P8P8h 7:7:7:7:7:x7:7:7:t!F!F!F!F!Fx!F!F!F!F!Fr__pycache__/main.cpython-311.opt-1.pyc000064400000032750151030032340013337 0ustar00 !A?h,dZddlZddlZddlZddlZddlmZmZddlm Z dZ dZ dZ d Z d Zd ZGd d eZeZdS)zUnittest main programN)loaderrunner)installHandlerTaExamples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass %(prog)s module.Class.test_method - run specified test method %(prog)s path/to/test_file.py - run tests from test_file.py aFExamples: %(prog)s - run default set of tests %(prog)s MyTestSuite - run suite 'MyTestSuite' %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething %(prog)s MyTestCase - run all 'test*' test methods in MyTestCase cVtj|r|drtj|rstj|tj}tj|s|tj r|S|}tj |dd dd ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirnormpathreplace)namerel_paths &/usr/lib64/python3.11/unittest/main.py _convert_namers  w~~dP 5 5e < <P 7==   wtRY[[99Hw}}X&& (*=*=bi*H*H  Dw%%crc*224==EEc3OOO Kcd|DS)Nc,g|]}t|S)r).0rs r z"_convert_names../s 2 2 2DM$   2 2 2rr)namess r_convert_namesr#.s 2 2E 2 2 22rcd|vrd|z}|S)N*z*%s*r)patterns r_convert_select_patternr'2s '>>7" Nrc eZdZdZdZdZdxZxZxZxZ xZ Z dZ dddde jddddddf dddZdd Zd Zd Zdd Zd ZdZdZdZddZdZdS) TestProgramzA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. Nr__main__TF) tb_localsc Vt|trOt||_|dddD]} t |j| |_n||_| t j}||_||_ | |_ ||_ | |_ | |_ | t jsd|_n| |_||_||_||_t&j|d|_|||dS)Nr rdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr+ warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr1r=r5r>r?r6r9r7r8r:r<r+parts r__init__zTestProgram.__init__Bs fc " " !$V,,DK S))!""- 9 9%dk488  9!DK <8D   $" "  CO &DMM%DM&$$((a11  t rctjdt|rt||j||tjddS)NzHTestProgram.usageExit() is deprecated and will be removed in Python 3.13) r<warnDeprecationWarningprint_discovery_parser_initArgParsers _print_helpr4r6)rDmsgs r usageExitzTestProgram.usageExithsr 01C E E E   #JJJ  ! )  " " "   rcZ|j_t|jttd|jiz|jdSt|jttd|jizdS)Nprog) r1rK _main_parser format_help MAIN_EXAMPLESrArL print_helpMODULE_EXAMPLES)rDargskwargss rrNzTestProgram._print_helprs ;  $#//11 2 2 2 -64="99 : : :  " - - / / / / / $#//11 2 2 2 /VT]$;; < < < < !>""48,,,   ( (abb4 8 8 8: ""2&&&     ( (abb4 8 8 8 : 4+DJ77DN:%%"   %!DNN (# . . 4".0DNN!$"233DN rc^|jr|j|j_|r;||jn |}|j|j|j|j|_dS|j&|j|j |_dS|j |j|j |_dSN) testNamePatternsr?r[startr&toptestr`loadTestsFromModuler1loadTestsFromNames)rDfrom_discoveryLoaderrs rrczTestProgram.createTestss   E/3/DDO ,  H(.T__FFHHF' DL$(KKDIII ^ #;;DKHHDIII::4>;?;HHDIIIrc|}|||_|||_dSre)_getParentArgParser_getMainArgParserrS_getDiscoveryArgParserrL)rD parent_parsers rrMzTestProgram._initArgParserssE0022  22=AA!%!rTextTestRunnerr.r|r9r7r:r<r+ TypeErrorrunriresultr6r4 wasSuccessful)rDr>s rrCzTestProgram.runTestssY ?      ? "$3DO dot , , ) / I!%4>:>-8< :>-;?> "1"K"KJJ !III!%4>:>-8< :>-"1"I"IJJJI  / / /!__..  / J nnTY// 9 6 H22444 5 5 5 5 5 6 6s0 3A>=B<>7B85B<7B88B<<CCre)FN)ra __module__ __qualname____doc__r1r9r7r8r:rAr<rfrLrdefaultTestLoaderrFrPrNrBrcrMrorprqr]rCrrrr)r)8s> FINRRHRzRFRXR;K(d#0HTd$$>C$$$$$L===: H H H HLLL !!!F   * = = = =66666rr))rr4r}r r<rrsignalsr __unittestrUrWrr#r'objectr)mainrrrrs  ######    333 \6\6\6\6\6&\6\6\6|r__pycache__/signals.cpython-311.opt-1.pyc000064400000007447151030032340014060 0ustar00 !A?hc ~ddlZddlZddlmZdZGddeZejZdZ dZ da dZ d d Z dS) N)wrapsTceZdZdZdZdS)_InterruptHandlercd|_||_t|tr@|tjkr tj}n#|tjkrd}ntd||_ dS)NFcdSN) unused_signum unused_frames )/usr/lib64/python3.11/unittest/signals.pydefault_handlerz3_InterruptHandler.__init__..default_handlersDzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr )selfr s r __init__z_InterruptHandler.__init__ s / os + + 3&.00"("< FN22 !2333 /rctjtj}||ur||||jr|||d|_t D]}|dS)NT)r getsignalSIGINTr r_resultskeysstop)rsignumframeinstalled_handlerresults r __call__z_InterruptHandler.__call__s",V];; D ( (   / / / ; 0   / / / mmoo  F KKMMMM  rN)__name__ __module__ __qualname__rr$r rr rr s2///$     rrcdt|<dS)N)rr#s r registerResultr+*sHVrcRtt|dSr)boolrpopr*s r removeResultr/-s  VT** + ++rctStjtj}t |atjtjtdSdSr)_interrupt_handlerrrrr)r s r installHandlerr21sK! *6=99.?? fm%788888"!rctfd}|St+tjtjtjdSdS)Nctjtj}t |i|tjtj|S#tjtj|wxYwr)rrr removeHandler)argskwargsinitialmethods r innerzremoveHandler..inner;sf&v}55G OOO 6vt.v.. fmW5555 fmW5555s A!A7)rr1rrr)r9r:s` r r5r59sg  v 6 6 6 6  6 % fm%7%HIIIII&%rr)rweakref functoolsr __unittestobjectrWeakKeyDictionaryrr+r/r1r2r5r rr r@s   @ %7 $ & &,,,999JJJJJJr__pycache__/loader.cpython-311.opt-1.pyc000064400000064775151030032340013675 0ustar00 !A?hXldZddlZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z m Z m Z dZejdejZGdd e jZd Zd Zd Zd ZdZGddeZeZddZe jdfdZde je jfdZ de je jfdZ!dS)zLoading unittests.N)fnmatch fnmatchcase)casesuiteutilTz[_a-z]\w*\.py$c,eZdZdZfdZfdZxZS) _FailedTestNcf||_tt||dSN) _exceptionsuperr __init__)self method_name exception __class__s (/usr/lib64/python3.11/unittest/loader.pyrz_FailedTest.__init__s.# k4  ))+66666cz|jkr(tt|Sfd}|S)Ncjr )r rsr testFailurez,_FailedTest.__getattr__..testFailure!s / !r)_testMethodNamerr __getattr__)rnamerrs` rrz_FailedTest.__getattr__sO 4' ' 'd++77== = " " " " "r)__name__ __module__ __qualname__rrr __classcell__rs@rr r sVO77777rr crd|dtj}t|t|||S)NzFailed to import test module:  ) traceback format_exc_make_failed_test ImportError)r suiteClassmessages r_make_failed_import_testr*&s< i"$$$&G T;w#7#7W M MMrcRdtj}t||||S)NzFailed to call load_tests: )r$r%r&)rrr(r)s r_make_failed_load_testsr,+s32;2F2H2H2HJG  iW . ..rc>t||}||f|fSr )r ) methodnamerr(r)tests rr&r&0s( z9 - -D :tg   ''rctjt|d}||i}tdtjf|}|||fS)NcdSr rs r testSkippedz'_make_skipped_test..testSkipped5s r ModuleSkipped)rskipstrtypeTestCase)r.rr(r3attrs TestClasss r_make_skipped_testr;4si Ys9~~    %E_t}&6>>I :yy,,. / //rc|dr |ddStj|dS)Nz $py.classir)lowerendswithospathsplitext)r@s r_jython_aware_splitextrB<sI zz||[))CRCy 7  D ! !! $$rceZdZdZdZeejZdZ e j Z dZ fdZdZdddZddZdd Zd Zdd Zd ZdZdZdZdZdZxZS) TestLoaderz This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite r/Nctt|g|_t |_dSr )rrDrerrorsset_loading_packages)rrs rrzTestLoader.__init__Ms: j$((*** "%rc,t|tjrtd|tjtjfvrg}n*||}|st|drdg}| t||}|S)z;Return a suite of all test cases contained in testCaseClasszYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?runTest) issubclassr TestSuite TypeErrorrr8FunctionTestCasegetTestCaseNameshasattrr(map)r testCaseClass testCaseNames loaded_suites rloadTestsFromTestCasez TestLoader.loadTestsFromTestCaseTs mU_ 5 5 )()) ) T]D,AB B BMM 11-@@M  ,W]I%F%F ,!* s=-'H'HII rpatternct|dksd|vr0tjdt|ddt|dkr4t|dz}t d|t|dkr7t|d}t d|g}t|D]}t||}t|tr\t|tjrB|tjtjfvr(|||t|dd} ||}| _ | |||S#t&$rD} t)|j| |j\} } |j| | cYd} ~ Sd} ~ wwxYw|S) z>Return a suite of all test cases contained in the given moduleruse_load_testsz(use_load_tests is deprecated and ignoredNrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpoprMformatsorteddirgetattr isinstancer7rKrr8rNappendrUr( Exceptionr,rrF) rmodulerWargskws complainttestsrobjrZe error_case error_messages rloadTestsFromModulezTestLoader.loadTestsFromModulefs t99q==,33 MD, . . . GG$d + + + t99q==D A Iahhirsstt t s88q== s AI[bbclmmnn nKK > >D&$''C3%% >sDM22 > t/DEEE T77<<===V\488 &&  ! "!z$w777 " " ",COQ-9-9) M ""=111!!!!!!!  "  s F$$ G2.9G-'G2-G2c v|d}d\}}||dd}|r d|}t|}n^#t$rO|}t ||j\}}|s|j||cYSYnwxYw||dd}|} |D]} | t| | } } #t$r} t| dd%|#|j||cYd} ~ cSt| | |jdtj \}}|j||cYd} ~ cSd} ~ wwxYwt| tjr|| St| t$rIt'| t(jr/| t(jt(jfvr|| St| tjrt| t$rlt'| t(jrR|d}| |} tt| |tjs|| gSnt| t2jr| St7| rl| }t|t2jr|St|t(jr||gSt9d| d |d t9d | z) aSReturn a suite of all test cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. .NNNr__path__zFailed to access attribute: zcalling z returned z , not a testz$don't know how to make test from: %s)splitjoin __import__r'r_r*r(rFrercAttributeErrorr&r$r%rdtypes ModuleTyperpr7rKrr8rNrU FunctionTyperrLcallablerM)rrrgpartsrnro parts_copy module_namenext_attributerlpartparentrminstr/s rloadTestsFromNamezTestLoader.loadTestsFromNames 3$.! M >qqqJ * *"%((:"6"6K' 44F"***%/^^%5%5N0H&1919-J %* **=999))))** *  *!""IE & &D &!73#5#5! & & &CT22>". K&&}555%%%%%%%%%1Ba%022251616-J K&&}555%%%%%%%%%% &( c5+ , , ++C00 0 sD ! ! 3 .. DM4+@AAA--c22 2e011 && // 9D6$<C E'.E" E'A E"E'"E'cNfd|D}|S)zReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. c<g|]}|Sr2)r).0rrgrs r z1TestLoader.loadTestsFromNames..s)III4$((v66IIIr)r()rnamesrgsuitess` ` rloadTestsFromNameszTestLoader.loadTestsFromNamess5JIIII5IIIv&&&rcfd}tt|t}jr-|t jj|S)zLReturn a sorted sequence of method names found within testCaseClass c|jsdSt|}t|sdSdjj|fzjduptfdjDS)NFz%s.%s.%sc38K|]}t|VdSr )r)rrWfullNames r zKTestLoader.getTestCaseNames..shouldIncludeMethod..s-XXwK'22XXXXXXr) startswithtestMethodPrefixrcr}rrtestNamePatternsany)attrnametestFuncrrrRs @rshouldIncludeMethodz8TestLoader.getTestCaseNames..shouldIncludeMethods&&t'<== u}h77HH%% u"(-*Dh&H(D0YXXXX$BWXXXXX Yr)key)listfilterrbsortTestMethodsUsingsort functools cmp_to_key)rrRr testFnNamess`` rrOzTestLoader.getTestCaseNamess Y Y Y Y Y Y6"5s=7I7IJJKK  $ R   !5d6O!P!P  Q Q Qrtest*.pycd}||j|j}n|d}|}tj|}|tjvr tjd|||_d}tjtj|retj|}||kr>tjtj|d }n t|tj |}| dd} tjtj |j }nD#t$r7|jtjvrt#ddt#d|dwxYw|r9|||_tj|n#t($rd}YnwxYw|rt)d |zt+|||}||S) a%Find and return all test modules from the specified start directory, recursing into subdirectories to find them and return all tests found within them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with (loader, tests, pattern) unless the package has already had load_tests called from the same discovery invocation, in which case the package module object is not scanned for tests - this ensures that when a package uses discover to further discover child tests that infinite recursion does not happen. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). Paths are sorted before being imported to ensure reproducible execution order even on filesystems with non-alphabetical ordering like ext3/4. FNTr __init__.pyrrz2Can not use builtin modules as dotted module namesz don't know how to discover from z%Start directory is not importable: %r)_top_level_dirr?r@abspathsysinsertisdirisfilerwrxmodulesrvdirname__file__ryrbuiltin_module_namesrM _get_directory_containing_moduleremover'r _find_testsr() r start_dirrW top_level_dirset_implicit_topis_not_importable the_moduletop_partrks rdiscoverzTestLoader.discoverse8!  T%8%D /MM  "# %M 66 (( HOOA} - - -+! 7==33 4 4 3 22IM))(*rw||I}7]7](^(^$^! 39%%%![3 $??3//2 ( ")<>>!@!@II%(((!*c.FFF')ABBGKL(MzMM#'( ($3*.*O*OPX*Y*YD'HOOM222) ) ) )$(!!! ),  SE QRR RT%%i99::u%%%s HAFAG H H ctj|}tj|j}tj|dr> > 7??9-- -rc ||jkrdSttj|}tj||j}|tjjd}|S)Nrr)rrBr?r@normpathrelpathreplacesep)rr@_relpathrs r_get_name_from_pathzTestLoader._get_name_from_path]sj 4& & &3%bg&6&6t&<&<==7??4)<== S11 rcDt|tj|Sr )rxrr)rrs r_get_module_from_namez TestLoader._get_module_from_nameis4{4  rc"t||Sr )r)rr@rrWs r _match_pathzTestLoader._match_pathmstW%%%rc#rK||}|dkr,||jvr#|||\}}||V|sdStt j|}|D]}tj||}|||\}}||V|r||}|j| | ||Ed{V|j |#|j |wxYwdS)z/Used by discovery. Yields test suites it loads.rrN) rrH_find_test_pathrar?listdirr@rwaddrdiscard) rrrWrrkshould_recursepathsr@rs rrzTestLoader._find_testsqsv'' 22 3;;4t'===%)$8$8G$L$L !E>  ! rz),,-- 9 9D Y55I$($8$8G$L$L !E>   9// ::&**40009#// 7CCCCCCCCC*2248888D*2248888 9 9 9s DD3ctj|}tj|rt|sdS||||sdS||} ||}tj t|d|}ttj |}ttj |}| | krtj|} ttj|} tj|} d} t| | | | fz|||dfS#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwtj|rztjtj|dsdSd}d}||} ||}t|dd}|j| |||}||df|j|S|d f|j|S#|j|wxYw#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwdS) zUsed by discovery. Loads tests from a single file, or a directories' __init__.py when passed the directory. Returns a tuple (None_or_tests_from_file, should_recurse). )NFrzW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?rVFNrrZT)r?r@rrVALID_MODULE_NAMEmatchrrrrrcrBrealpathr=rr'rprSkipTestr;r(r*rFrerrwrHrr)rrrWrrrgmod_filerfullpath_noext module_dirmod_name expected_dirmsgrmrnrorZrkpackages rrzTestLoader._find_test_paths7##I.. 7>>) $ $? $**844 #"{##HiAA #"{++I66D P33D997??FJ ::<<1G$$X..00!7G$$Y//"1"1>>##~';';'='===!#!:!:J5((33 5 5H#%7??9#=#=LDC%x\BBDDD///HH%OO/= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5(((($W]]9 % % 7>>"',,y-"H"HII #"{JE++I66D 944T::%WlDAA &**40009 44Wg4NNE!-$e|*2248888!$;*2248888D*2248888%= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5((((;sN G**I9HI;INM%M%%NO-N0*O-0;O-r )rN)rrr__doc__r staticmethodr three_way_cmprrrrLr(rrrUrprrrOrrrrrrrr r!s@rrDrDBsX'<(:;;JN'''''$:>*****XPJPJPJPJd''''&Q&Q&Q&Q&f . . .   !!!&&&999@HHHHHHHrrDc^t}||_||_||_|r||_|Sr )rDrrrr()prefix sortUsingr(rloaders r _makeLoaderrs8 \\F"+F$F.F'& Mrcddl}|jdtdt||||S)Nrzunittest.getTestCaseNames() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.getTestCaseNames() instead. stacklevel)r)r\r]r^rrO)rRrrrr\s rrOrOsXOOOHM Eq vy;K L L L ] ]^k l llrr/cddl}|jdtdt||||S)Nrzunittest.makeSuite() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromTestCase() instead.rr)r\r]r^rrU)rRrrr(r\s r makeSuitersZOOOHM Jq vy* 5 5 K K  rcddl}|jdtdt||||S)Nrzunittest.findTestCases() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromModule() instead.rr)r\r]r^rrp)rgrrr(r\s r findTestCasesrsZOOOHM Hq vy* 5 5 I I  rrs)"rr?rerr$rzrr\rrrrr __unittestcompile IGNORECASErr8r r*r,r&r;rBobjectrDdefaultTestLoaderrrrOrLrrr2rrrs  ((((((((  BJ0"-@@     $-   NNN ... (((000%%% WWWWWWWWt JLL 7;6H[_mmmm%+d6H    "(43E"_      r__pycache__/result.cpython-311.opt-1.pyc000064400000031250151030032340013723 0ustar00 !A?hF!hdZddlZddlZddlZddlmZddlmZdZdZ dZ d Z Gd d e Z dS) zTest result objectN)utilwrapsTc<tfd}|S)Ncft|ddr||g|Ri|S)NfailfastF)getattrstop)selfargskwmethods (/usr/lib64/python3.11/unittest/result.pyinnerzfailfast..inner sD 4U + +  IIKKKvd(T(((R(((r)rrs` rr r s3 6]]))))]) Lrz Stdout: %sz Stderr: %sceZdZdZdZdZdZddZdZdZ dZ dZ d Z d Z d Zed Zed ZdZdZdZdZedZdZdZdZdZdZdZdZdS) TestResultaHolder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. NFcd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ tj |_tj|_d|_dS)NFr)r failureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)r stream descriptions verbositys r__init__zTestResult.__init__&s|     "#%  "" #  # "rcdS)z#Called by TestRunner after test runNr s r printErrorszTestResult.printErrors7rc\|xjdz c_d|_|dS)z-Called when the given test is about to be runrFN)rr& _setupStdoutr tests r startTestzTestResult.startTest:s2  " rc|jr[|j0tj|_tj|_|jt _|jt _dSdS)N)rr ioStringIOrr!r"r$r-s rr1zTestResult._setupStdout@sS ; -"*&(kmm#&(kmm#,CJ,CJJJ  - -rcdS)zpCalled once before any tests are executed. See startTest for a method called before each test. Nr,r-s r startTestRunzTestResult.startTestRunHr/rc<|d|_dS)z'Called when the given test has been runFN)_restoreStdoutr&r2s rstopTestzTestResult.stopTestNs" "rc|jrI|jrtj}tj}|r<|ds|dz }|jt|z|r<|ds|dz }|j t|z|jt_|j t_|j d|j |j d|jdSdS)N r)rr&r!r"getvaluer$endswithr#write STDOUT_LINEr% STDERR_LINErseektruncater )r outputerrors rr;zTestResult._restoreStdoutSs> ; +! E,,.. ++--F!??400'$)// f0DEEEE >>$//& )// e0CDDD.CJ.CJ   $ $Q ' ' '   ( ( * * *   $ $Q ' ' '   ( ( * * * * *% + +rcdS)zmCalled once after all tests are executed. See stopTest for a method called after each test. Nr,r-s r stopTestRunzTestResult.stopTestRunhr/rct|j||||fd|_dS)zmCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). TN)rappend_exc_info_to_stringr&r r3errs raddErrorzTestResult.addErrorns= D$":":3"E"EFGGG!rct|j||||fd|_dS)zdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().TN)rrKrLr&rMs r addFailurezTestResult.addFailurevs= dD$<$|j||fdS)zCalled when a test is skipped.N)rrK)r r3reasons raddSkipzTestResult.addSkips" T6N+++++rcf|j||||fdS)z/Called when an expected failure/error occurred.N)rrKrLrMs raddExpectedFailurezTestResult.addExpectedFailures? $$ 4++C66 7 9 9 9 9 9rc:|j|dS)z5Called when a test was expected to fail, but succeed.N)rrKr2s raddUnexpectedSuccesszTestResult.addUnexpectedSuccesss!  ''-----rct|jt|jcxkodknco(t|d pt|jdkS)z/Tells whether or not this result was a success.rr)lenrrhasattrrr-s r wasSuccessfulzTestResult.wasSuccessfulsj T]##s4;'7'7<<<<1<<<<5T#89994T-..!3 6rcd|_dS)z+Indicates that the tests should be aborted.TN)rr-s rr zTestResult.stops rcP|\}}}|||||}tj||||jd}t |}|jrtj }tj } |r7| ds|dz }| t|z| r7| ds| dz } | t| zd|S)z>Converts a sys.exc_info()-style tuple of values into a string.T)capture_localscompactr>)_clean_tracebacks tracebackTracebackExceptionrlistformatrr!r"r?r$r@rKrBrCjoin) r rNr3exctypevaluetbtb_emsgLinesrFrGs rrLzTestResult._exc_info_to_strings   # #GUB = =+ UB>4999 && ; 5Z((**FJ''))E 6t,,#dNF f 4555 5~~d++"TME e 3444wwx   rcd}d}|||fg}t|h}|r|\}}}|r3||r|j}|r||||jur|||r|}d}n||_|p|j|jfD]a} | ]t| |vrL| t| | | jf| t| b||S)NTF) idpop_is_relevant_tb_leveltb_nextrT_remove_unittest_tb_frames __traceback__ __cause__ __context__rKtypeadd) r rorprqr3retfirstexcsseencs rrizTestResult._clean_tracebackssC%$%5 { (#'88:: WeR 33B77 Z 33B77 $/////333 )&(# /5+<=((A}Ad):): T!WWa$ABBBA) (* rcd|jjvS)N __unittest)tb_frame f_globals)r rqs rrwz TestResult._is_relevant_tb_levelsr{444rcd}|r5||s |}|j}|r|| | d|_dSdS)aTruncates usercode tb at the first unittest frame. If the first frame of the traceback is in user code, the prefix up to the first unittest frame is returned. If the first frame is already in the unittest module, the traceback is not modified. N)rwrx)r rqprevs rryz%TestResult._remove_unittest_tb_framessl 33B77 DB 33B77   DLLL  rcdtj|j|jt |jt |jfzS)Nz!<%s run=%i errors=%i failures=%i>)rstrclass __class__rrarrr-s r__repr__zTestResult.__repr__s@3 dn--t}c$+>N>NDM""$$ %r)NNN)__name__ __module__ __qualname____doc___previousTestClass_testRunEntered_moduleSetUpFailedr*r.r4r1r9r<r;rIr rOrQrVrXr[r]r_rcr rLrirwryrr,rrrrs  O####"... ---   ### +++*   ""X"""X" &&&"   ,,,999 ..X.666!!!,8555    %%%%%rr)rr6r!rjrhr functoolsrrr rBrCobjectrr,rrrs     \%\%\%\%\%\%\%\%\%\%r__pycache__/main.cpython-311.pyc000064400000032750151030032340012400 0ustar00 !A?h,dZddlZddlZddlZddlZddlmZmZddlm Z dZ dZ dZ d Z d Zd ZGd d eZeZdS)zUnittest main programN)loaderrunner)installHandlerTaExamples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass %(prog)s module.Class.test_method - run specified test method %(prog)s path/to/test_file.py - run tests from test_file.py aFExamples: %(prog)s - run default set of tests %(prog)s MyTestSuite - run suite 'MyTestSuite' %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething %(prog)s MyTestCase - run all 'test*' test methods in MyTestCase cVtj|r|drtj|rstj|tj}tj|s|tj r|S|}tj |dd dd ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirnormpathreplace)namerel_paths &/usr/lib64/python3.11/unittest/main.py _convert_namers  w~~dP 5 5e < <P 7==   wtRY[[99Hw}}X&& (*=*=bi*H*H  Dw%%crc*224==EEc3OOO Kcd|DS)Nc,g|]}t|S)r).0rs r z"_convert_names../s 2 2 2DM$   2 2 2rr)namess r_convert_namesr#.s 2 2E 2 2 22rcd|vrd|z}|S)N*z*%s*r)patterns r_convert_select_patternr'2s '>>7" Nrc eZdZdZdZdZdxZxZxZxZ xZ Z dZ dddde jddddddf dddZdd Zd Zd Zdd Zd ZdZdZdZddZdZdS) TestProgramzA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. Nr__main__TF) tb_localsc Vt|trOt||_|dddD]} t |j| |_n||_| t j}||_||_ | |_ ||_ | |_ | |_ | t jsd|_n| |_||_||_||_t&j|d|_|||dS)Nr rdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr+ warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr1r=r5r>r?r6r9r7r8r:r<r+parts r__init__zTestProgram.__init__Bs fc " " !$V,,DK S))!""- 9 9%dk488  9!DK <8D   $" "  CO &DMM%DM&$$((a11  t rctjdt|rt||j||tjddS)NzHTestProgram.usageExit() is deprecated and will be removed in Python 3.13) r<warnDeprecationWarningprint_discovery_parser_initArgParsers _print_helpr4r6)rDmsgs r usageExitzTestProgram.usageExithsr 01C E E E   #JJJ  ! )  " " "   rcZ|j_t|jttd|jiz|jdSt|jttd|jizdS)Nprog) r1rK _main_parser format_help MAIN_EXAMPLESrArL print_helpMODULE_EXAMPLES)rDargskwargss rrNzTestProgram._print_helprs ;  $#//11 2 2 2 -64="99 : : :  " - - / / / / / $#//11 2 2 2 /VT]$;; < < < < !>""48,,,   ( (abb4 8 8 8: ""2&&&     ( (abb4 8 8 8 : 4+DJ77DN:%%"   %!DNN (# . . 4".0DNN!$"233DN rc^|jr|j|j_|r;||jn |}|j|j|j|j|_dS|j&|j|j |_dS|j |j|j |_dSN) testNamePatternsr?r[startr&toptestr`loadTestsFromModuler1loadTestsFromNames)rDfrom_discoveryLoaderrs rrczTestProgram.createTestss   E/3/DDO ,  H(.T__FFHHF' DL$(KKDIII ^ #;;DKHHDIII::4>;?;HHDIIIrc|}|||_|||_dSre)_getParentArgParser_getMainArgParserrS_getDiscoveryArgParserrL)rD parent_parsers rrMzTestProgram._initArgParserssE0022  22=AA!%!rTextTestRunnerr.r|r9r7r:r<r+ TypeErrorrunriresultr6r4 wasSuccessful)rDr>s rrCzTestProgram.runTestssY ?      ? "$3DO dot , , ) / I!%4>:>-8< :>-;?> "1"K"KJJ !III!%4>:>-8< :>-"1"I"IJJJI  / / /!__..  / J nnTY// 9 6 H22444 5 5 5 5 5 6 6s0 3A>=B<>7B85B<7B88B<<CCre)FN)ra __module__ __qualname____doc__r1r9r7r8r:rAr<rfrLrdefaultTestLoaderrFrPrNrBrcrMrorprqr]rCrrrr)r)8s> FINRRHRzRFRXR;K(d#0HTd$$>C$$$$$L===: H H H HLLL !!!F   * = = = =66666rr))rr4r}r r<rrsignalsr __unittestrUrWrr#r'objectr)mainrrrrs  ######    333 \6\6\6\6\6&\6\6\6|r__pycache__/result.cpython-311.pyc000064400000031250151030032340012764 0ustar00 !A?hF!hdZddlZddlZddlZddlmZddlmZdZdZ dZ d Z Gd d e Z dS) zTest result objectN)utilwrapsTc<tfd}|S)Ncft|ddr||g|Ri|S)NfailfastF)getattrstop)selfargskwmethods (/usr/lib64/python3.11/unittest/result.pyinnerzfailfast..inner sD 4U + +  IIKKKvd(T(((R(((r)rrs` rr r s3 6]]))))]) Lrz Stdout: %sz Stderr: %sceZdZdZdZdZdZddZdZdZ dZ dZ d Z d Z d Zed Zed ZdZdZdZdZedZdZdZdZdZdZdZdZdS) TestResultaHolder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. NFcd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ tj |_tj|_d|_dS)NFr)r failureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)r stream descriptions verbositys r__init__zTestResult.__init__&s|     "#%  "" #  # "rcdS)z#Called by TestRunner after test runNr s r printErrorszTestResult.printErrors7rc\|xjdz c_d|_|dS)z-Called when the given test is about to be runrFN)rr& _setupStdoutr tests r startTestzTestResult.startTest:s2  " rc|jr[|j0tj|_tj|_|jt _|jt _dSdS)N)rr ioStringIOrr!r"r$r-s rr1zTestResult._setupStdout@sS ; -"*&(kmm#&(kmm#,CJ,CJJJ  - -rcdS)zpCalled once before any tests are executed. See startTest for a method called before each test. Nr,r-s r startTestRunzTestResult.startTestRunHr/rc<|d|_dS)z'Called when the given test has been runFN)_restoreStdoutr&r2s rstopTestzTestResult.stopTestNs" "rc|jrI|jrtj}tj}|r<|ds|dz }|jt|z|r<|ds|dz }|j t|z|jt_|j t_|j d|j |j d|jdSdS)N r)rr&r!r"getvaluer$endswithr#write STDOUT_LINEr% STDERR_LINErseektruncater )r outputerrors rr;zTestResult._restoreStdoutSs> ; +! E,,.. ++--F!??400'$)// f0DEEEE >>$//& )// e0CDDD.CJ.CJ   $ $Q ' ' '   ( ( * * *   $ $Q ' ' '   ( ( * * * * *% + +rcdS)zmCalled once after all tests are executed. See stopTest for a method called after each test. Nr,r-s r stopTestRunzTestResult.stopTestRunhr/rct|j||||fd|_dS)zmCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). TN)rappend_exc_info_to_stringr&r r3errs raddErrorzTestResult.addErrorns= D$":":3"E"EFGGG!rct|j||||fd|_dS)zdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().TN)rrKrLr&rMs r addFailurezTestResult.addFailurevs= dD$<$|j||fdS)zCalled when a test is skipped.N)rrK)r r3reasons raddSkipzTestResult.addSkips" T6N+++++rcf|j||||fdS)z/Called when an expected failure/error occurred.N)rrKrLrMs raddExpectedFailurezTestResult.addExpectedFailures? $$ 4++C66 7 9 9 9 9 9rc:|j|dS)z5Called when a test was expected to fail, but succeed.N)rrKr2s raddUnexpectedSuccesszTestResult.addUnexpectedSuccesss!  ''-----rct|jt|jcxkodknco(t|d pt|jdkS)z/Tells whether or not this result was a success.rr)lenrrhasattrrr-s r wasSuccessfulzTestResult.wasSuccessfulsj T]##s4;'7'7<<<<1<<<<5T#89994T-..!3 6rcd|_dS)z+Indicates that the tests should be aborted.TN)rr-s rr zTestResult.stops rcP|\}}}|||||}tj||||jd}t |}|jrtj }tj } |r7| ds|dz }| t|z| r7| ds| dz } | t| zd|S)z>Converts a sys.exc_info()-style tuple of values into a string.T)capture_localscompactr>)_clean_tracebacks tracebackTracebackExceptionrlistformatrr!r"r?r$r@rKrBrCjoin) r rNr3exctypevaluetbtb_emsgLinesrFrGs rrLzTestResult._exc_info_to_strings   # #GUB = =+ UB>4999 && ; 5Z((**FJ''))E 6t,,#dNF f 4555 5~~d++"TME e 3444wwx   rcd}d}|||fg}t|h}|r|\}}}|r3||r|j}|r||||jur|||r|}d}n||_|p|j|jfD]a} | ]t| |vrL| t| | | jf| t| b||S)NTF) idpop_is_relevant_tb_leveltb_nextrT_remove_unittest_tb_frames __traceback__ __cause__ __context__rKtypeadd) r rorprqr3retfirstexcsseencs rrizTestResult._clean_tracebackssC%$%5 { (#'88:: WeR 33B77 Z 33B77 $/////333 )&(# /5+<=((A}Ad):): T!WWa$ABBBA) (* rcd|jjvS)N __unittest)tb_frame f_globals)r rqs rrwz TestResult._is_relevant_tb_levelsr{444rcd}|r5||s |}|j}|r|| | d|_dSdS)aTruncates usercode tb at the first unittest frame. If the first frame of the traceback is in user code, the prefix up to the first unittest frame is returned. If the first frame is already in the unittest module, the traceback is not modified. N)rwrx)r rqprevs rryz%TestResult._remove_unittest_tb_framessl 33B77 DB 33B77   DLLL  rcdtj|j|jt |jt |jfzS)Nz!<%s run=%i errors=%i failures=%i>)rstrclass __class__rrarrr-s r__repr__zTestResult.__repr__s@3 dn--t}c$+>N>NDM""$$ %r)NNN)__name__ __module__ __qualname____doc___previousTestClass_testRunEntered_moduleSetUpFailedr*r.r4r1r9r<r;rIr rOrQrVrXr[r]r_rcr rLrirwryrr,rrrrs  O####"... ---   ### +++*   ""X"""X" &&&"   ,,,999 ..X.666!!!,8555    %%%%%rr)rr6r!rjrhr functoolsrrr rBrCobjectrr,rrrs     \%\%\%\%\%\%\%\%\%\%r__pycache__/main.cpython-311.opt-2.pyc000064400000032466151030032340013344 0ustar00 !A?h, ddlZddlZddlZddlZddlmZmZddlmZdZ dZ dZ dZ d Z d ZGd d eZeZdS) N)loaderrunner)installHandlerTaExamples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass %(prog)s module.Class.test_method - run specified test method %(prog)s path/to/test_file.py - run tests from test_file.py aFExamples: %(prog)s - run default set of tests %(prog)s MyTestSuite - run suite 'MyTestSuite' %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething %(prog)s MyTestCase - run all 'test*' test methods in MyTestCase cVtj|r|drtj|rstj|tj}tj|s|tj r|S|}tj |dd dd ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirnormpathreplace)namerel_paths &/usr/lib64/python3.11/unittest/main.py _convert_namers  w~~dP 5 5e < <P 7==   wtRY[[99Hw}}X&& (*=*=bi*H*H  Dw%%crc*224==EEc3OOO Kcd|DS)Nc,g|]}t|S)r).0rs r z"_convert_names../s 2 2 2DM$   2 2 2rr)namess r_convert_namesr#.s 2 2E 2 2 22rcd|vrd|z}|S)N*z*%s*r)patterns r_convert_select_patternr'2s '>>7" Nrc eZdZ dZdZdxZxZxZxZxZ Z dZ dddde j ddddddf dddZddZd Zd Zdd Zd Zd ZdZdZddZdZdS) TestProgramNr__main__TF) tb_localsc Vt|trOt||_|dddD]} t |j| |_n||_| t j}||_||_ | |_ ||_ | |_ | |_ | t jsd|_n| |_||_||_||_t&j|d|_|||dS)Nr rdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr+ warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr1r=r5r>r?r6r9r7r8r:r<r+parts r__init__zTestProgram.__init__Bs fc " " !$V,,DK S))!""- 9 9%dk488  9!DK <8D   $" "  CO &DMM%DM&$$((a11  t rctjdt|rt||j||tjddS)NzHTestProgram.usageExit() is deprecated and will be removed in Python 3.13) r<warnDeprecationWarningprint_discovery_parser_initArgParsers _print_helpr4r6)rDmsgs r usageExitzTestProgram.usageExithsr 01C E E E   #JJJ  ! )  " " "   rcZ|j_t|jttd|jiz|jdSt|jttd|jizdS)Nprog) r1rK _main_parser format_help MAIN_EXAMPLESrArL print_helpMODULE_EXAMPLES)rDargskwargss rrNzTestProgram._print_helprs ;  $#//11 2 2 2 -64="99 : : :  " - - / / / / / $#//11 2 2 2 /VT]$;; < < < < !>""48,,,   ( (abb4 8 8 8: ""2&&&     ( (abb4 8 8 8 : 4+DJ77DN:%%"   %!DNN (# . . 4".0DNN!$"233DN rc^|jr|j|j_|r;||jn |}|j|j|j|j|_dS|j&|j|j |_dS|j |j|j |_dSN) testNamePatternsr?r[startr&toptestr`loadTestsFromModuler1loadTestsFromNames)rDfrom_discoveryLoaderrs rrczTestProgram.createTestss   E/3/DDO ,  H(.T__FFHHF' DL$(KKDIII ^ #;;DKHHDIII::4>;?;HHDIIIrc|}|||_|||_dSre)_getParentArgParser_getMainArgParserrS_getDiscoveryArgParserrL)rD parent_parsers rrMzTestProgram._initArgParserssE0022  22=AA!%!rTextTestRunnerr.r|r9r7r:r<r+ TypeErrorrunriresultr6r4 wasSuccessful)rDr>s rrCzTestProgram.runTestssY ?      ? "$3DO dot , , ) / I!%4>:>-8< :>-;?> "1"K"KJJ !III!%4>:>-8< :>-"1"I"IJJJI  / / /!__..  / J nnTY// 9 6 H22444 5 5 5 5 5 6 6s0 3A>=B<>7B85B<7B88B<<CCre)FN)ra __module__ __qualname__r1r9r7r8r:rAr<rfrLrdefaultTestLoaderrFrPrNrBrcrMrorprqr]rCrrrr)r)8s9 FINRRHRzRFRXR;K(d#0HTd$$>C$$$$$L===: H H H HLLL !!!F   * = = = =66666rr))r4r}r r<rrsignalsr __unittestrUrWrr#r'objectr)mainrrrrs  ######    333 \6\6\6\6\6&\6\6\6|r__pycache__/suite.cpython-311.opt-1.pyc000064400000042714151030032340013545 0ustar00 !A?h4dZddlZddlmZddlmZdZdZGdd eZGd deZ Gd d eZ d Z GddeZ dS) TestSuiteN)case)utilTc>t||d}|dS)NcdSNr '/usr/lib64/python3.11/unittest/suite.pyz!_call_if_exists.. sr )getattr)parentattrfuncs r _call_if_existsr s$ 64 . .DDFFFFFr cZeZdZdZdZddZdZdZdZdZ d Z d Z d Z d Z d ZdZdS) BaseTestSuitezNA simple test suite that doesn't provide class or module shared fixtures. Tr cLg|_d|_||dSNr)_tests_removed_testsaddTests)selftestss r __init__zBaseTestSuite.__init__s)  er c\dtj|jdt|dS)N)rstrclass __class__listrs r __repr__zBaseTestSuite.__repr__s+"&-"?"?"?"?dLLr czt||jstSt|t|kSr ) isinstancer!NotImplementedr")rothers r __eq__zBaseTestSuite.__eq__s3%00 "! !DzzT%[[((r c*t|jSr )iterrr#s r __iter__zBaseTestSuite.__iter__"sDK   r cP|j}|D]}|r||z }|Sr )rcountTestCases)rcasestests r r.zBaseTestSuite.countTestCases%s=# / /D /,,... r c@t|s/tdt|t |t r0t |tjtfrtd|j |dS)Nz{} is not callablezNTestCases and TestSuites must be instantiated before passing them to addTest()) callable TypeErrorformatreprr&type issubclassrTestCaserrappendrr0s r addTestzBaseTestSuite.addTest,s~~ E077T CCDD D dD ! ! @j26-1K'M'M @?@@ @ 4     r ct|trtd|D]}||dS)Nz0tests must be an iterable of tests, not a string)r&strr3r;)rrr0s r rzBaseTestSuite.addTests6sR eS ! ! PNOO O  D LL      r ct|D]5\}}|jrn(|||jr||6|Sr ) enumerate shouldStop_cleanup_removeTestAtIndex)rresultindexr0s r runzBaseTestSuite.run<s\$T?? / /KE4   DLLL} /''... r c |j|}t|dr"|xj|z c_d|j|<dS#t$rYdSwxYw)z2Stop holding a reference to the TestCase at index.r.N)rhasattrrr.r3)rrDr0s r rBz BaseTestSuite._removeTestAtIndexEs~ &;u%Dt-.. =##t':':'<'<<##!%DK       DD s A AAc|j|i|Sr rE)rargskwdss r __call__zBaseTestSuite.__call__Sstx&&&&r c8|D]}|dS)7Run the tests without collecting errors in a TestResultN)debugr:s r rOzBaseTestSuite.debugVs*  D JJLLLL  r N)r )__name__ __module__ __qualname____doc__rArr$r)r,r.r;rrErBrLrOr r r rrsH MMM))) !!!!!!  & & &'''r rcReZdZdZd dZdZdZdZdZ dd Z dd Z d Z d Z dS)raA test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. Fcld}t|dddur dx|_}t|D]\}}|jrnt |rv||||||||||j|_ t|jddst|ddr|s ||n| |j r| ||r2|d|| |d|_|S)NF_testRunEnteredT_classSetupFailed_moduleSetUpFailed)rrVr?r@ _isnotsuite_tearDownPreviousClass_handleModuleFixture_handleClassSetUpr!_previousTestClassrOrArB_handleModuleTearDown)rrCrOtopLevelrDr0s r rEz TestSuite.runfsb 6,e 4 4 = =04 4F "X$T?? / /KE4  4   ++D&999))$777&&tV444,0N)DN,?GGF$8%@@ V  } /''...  +  ' 'f 5 5 5  & &v . . .%*F " r cNt}||ddS)rNTN) _DebugResultrE)rrOs r rOzTestSuite.debugs% r ct|dd}|j}||krdS|jrdSt|ddrdSd} d|_n#t$rYnwxYwt|dd}t|dd}|t |d |nt#t $rg}t|trd} d|_n#t$rYnwxYwtj |} | ||d| Yd}~nd}~wwxYw|r6|4||j D]"} | || dd| | #t |d dS#t |d wxYwdS) Nr]__unittest_skip__F setUpClassdoClassCleanups _setupStdoutTrinfo_restoreStdout) rr!rXrWr3r Exceptionr&rarr "_createClassOrModuleLevelExceptiontearDown_exceptions) rr0rC previousClass currentClassfailedrdree classNameexc_infos r r\zTestSuite._handleClassSetUps8(> !,0A4HH  ! FN 3 3 3 : GJLLLL G G G!&,77!F9= 66$ $ l ; ;I;;FAd}t|dd}||j}|S)Nr])rrQ)rrCpreviousModulerms r _get_previous_modulezTestSuite._get_previous_modules-(> * * * * * -s|~~66666t,,,,,r c|||}|dS|jrdS tj|}n#t$rYdSwxYwt |d t |dd}|Q |nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYw tj nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYwt |ddS#t |dwxYw)NrftearDownModuleri) rurXrxryrzrrrjr&rarkrr{)rrCrtr}rrps r r^zTestSuite._handleModuleTearDowns226::  ! F  $  F [0FF    FF  /// 6$V-=tDDN)L"N$$$$ LLL!&,77;;FACD) D.D D)DD))D;ct|dd}|j}||ks|dSt|ddrdSt|ddrdSt|ddrdSt|dd}t|dd}||dSt|d |e |nY#t$rL}t |t rt j|}|||d|Yd}~nd}~wwxYw|e||j D]S} t |t r| d t j|}||| d d|| Tt|d dS#t|d wxYw) Nr]rWFrXrc tearDownClassrerfrrgri) rr!rrjr&rarr rkrl) rr0rCrmrnrrerprqrrs r rZz TestSuite._tearDownPreviousClasss%(rs      IIIIIFIIIXi6i6i6i6i6 i6i6i6X$$$$$6$$$L6r __pycache__/mock.cpython-311.opt-1.pyc000064400000374100151030032340013342 0ustar00 !A?hH`dZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZddlmZmZddlmZGdd eZd eeDZd ZeZd Zd ZdZdZdZ dZ!dydZ"dZ#dZ$dZ%dZ&dydZ'dZ(dZ)dZ*Gdde+Z,Gdde+Z-e-Z.e.j/Z/e.j0Z1e.j2Z3hd Z4d!Z5Gd"d#e6Z7d$Z8Gd%d&e+Z9Gd'd(e+Z:Gd)d*e:Z;ej<e;j=Z>Gd+d,e6Z?d-Z@Gd.d/e:ZAGd0d1eAe;ZBd2ZCGd3d4e+ZDd5ZEe/dddddfdd6d7ZF dzd8ZGe/dddddfdd6d9ZHGd:d;e+ZId<ZJd=ZKeFeH_+eIeH_LeGeH_MeKeH_Nd>eH_Od?ZPd@ZQdARdBeQSDZTdARdCeQSDZUhdDZVdEZWdFdARePeQeTeUgSDZXhdGZYdHhZZeYeZzZ[eXeVzZ\e\e[zZ]hdIZ^dJdKdLdMdNZ_e`e`e`e`dOddddPdQd dOddR ZadSZbdTZcdUZddVZeebecedeedWZfdXZgGdYdZe:ZhGd[d\ehe;ZiGd]d^ehZjGd_d`eheBZkGdadbe:ZlGdcdde:ZmGdedfemejeBZnGdgdhe+ZoeoZpdiZqGdjdkerZsesdlZt d{dd6dmZudnZvGdodpe+ZwexeuexepjyfZzda{da|dqZ}d|dsZ~GdtdueBZdvZGdwdxZdS)})Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartial)RLockceZdZdZdS)InvalidSpecErrorz8Indicates that an invalid value was used as a mock spec.N__name__ __module__ __qualname____doc__&/usr/lib64/python3.11/unittest/mock.pyrr)sBBBBr"rc<h|]}|d|S_ startswith).0names r# r+-s) H H Hd4??33G3G HT H H Hr"Tct|rt|tsdSt|drt |d}t |pt j|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspect isawaitableobjs r# _is_async_objr65sgji&@&@usJ'c:&& s # # ?w':3'?'??r"cFt|ddrt|SdS)N__code__F)r1r)funcs r#_is_async_funcr:=s)tZ&&"4(((ur"cFtt|tSN) issubclasstyper r4s r#r.r.Ds d3ii 1 11r"ct|tp)t|tot|tSr<)r/ BaseExceptionr>r=r4s r# _is_exceptionrAJs63 && A3@*S-"@"@r"c^t|trt|dr|jS|SNmock)r/ FunctionTypesr0rDr4s r# _extract_mockrFQs3#}%%'#v*>*>x r"ct|tr |s |j}d}njt|ttfrt|trd}|j}n/t|t s |j}n#t$rYdSwxYw|rt|d}n|} |tj |fS#t$rYdSwxYw)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. TN) r/r>__init__ classmethod staticmethodr-rE__call__AttributeErrorrr2 signature ValueError)r9 as_instanceeat_selfsig_funcs r#_get_signature_objectrRZs $k} D; 5 6 6  dK ( ( H} m , , =DD   44 4&&W&x0000 tts$3A;; B B "B88 CCFct|||dS\}fd}t|||t|_t|_dS)Nc"j|i|dSr<bind)selfargskwargssigs r#checksigz"_check_signature..checksig $!&!!!!!r")rR_copy_func_detailsr>_mock_check_sig __signature__)r9rD skipfirstinstancer[rZs @r#_check_signaturerb}sr h : :C {ID#"""""tX&&&!)DJJ"DJJr"c pdD]2} t||t||##t$rY/wxYwdS)N)rr __text_signature__r __defaults____kwdefaults__)setattrr1rL)r9funcopy attributes r#r]r]sa   GYi(@(@ A A A A    D  s & 33ct|trdSt|tttfrt |jSt|dddSdS)NTrKF)r/r>rJrIr _callabler-r1r4s r#rkrks^#tt# k:>??'&&&sJ%%1t 5r"c<t|ttfvSr<)r>listtupler4s r#_is_listros 99u %%r"ct|tst|ddduS|f|jzD]}|jddS dS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.rKNTF)r/r>r1__mro____dict__get)r5bases r#_instance_callablerusn c4 :sJ--T99$ =  Z ( ( 444 5 5r"c0 t|t}t|||}||S|\} fd}t|||j}|sd}||d}d|z} t | |||} t| | | S)Nc"j|i|dSr<rU)rXrYrZs r#r[z _set_signature..checksigr\r"rh) _checksig_rDzYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r/r>rRr]r isidentifierexec _setup_func) rDoriginalrar`resultr9r[r*contextsrcrhrZs @r#_set_signaturers 8T**I "8Xy A AF ~ ID#"""""tX&&&  D     %t44G $&* +C #wdmGs### Nr"c_fd}fd}fd}fd}fd}fd}fd} fd} d _d _d_t _t _t _j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS) Ncj|i|Sr<)assert_called_withrXrYrDs r#rz'_setup_func..assert_called_with&t&7777r"cj|i|Sr<) assert_calledrs r#rz"_setup_func..assert_calleds!t!426222r"cj|i|Sr<)assert_not_calledrs r#rz&_setup_func..assert_not_calleds%t%t6v666r"cj|i|Sr<)assert_called_oncers r#rz'_setup_func..assert_called_oncerr"cj|i|Sr<)assert_called_once_withrs r#rz,_setup_func..assert_called_once_withs+t+T.assert_has_callss$t$d5f555r"cj|i|Sr<)assert_any_callrs r#rz$_setup_func..assert_any_calls#t#T4V444r"ct_t_j}t |r|ur|dSdSdSr<) _CallList method_calls mock_calls reset_mock return_valuer.)retrhrDs r#rz_setup_func..reset_mockso({{&[[ " S ! ! #++ NN       ++r"Fr)rDcalled call_count call_argsrcall_args_listrrr side_effect_mock_childrenrrrrrrrrr__mock_delegate) rhrDrZrrrrrrrrs `` r#r{r{sGL88888333337777788888=====6666655555GNGG&[[G$;;G"G,G*G!0G!3G&=G#/G-G#G)G 1G!3GG!Dr"c tjj_d_d_t _fd}dD]!}t|t||"dS)Nrc:tj||i|Sr<)r1rD)attrrXrYrDs r#wrapperz"_setup_async_mock..wrapper s$'wty$''8888r")assert_awaitedassert_awaited_onceassert_awaited_withassert_awaited_once_withassert_any_awaitassert_has_awaitsassert_not_awaited) asyncio coroutines _is_coroutine await_count await_argsrawait_args_listrgr)rDrris` r#_setup_async_mockrs +9DDDO$;;D 99999, > >  i)! >r"c$d|ddz|kS)N__%s__r!r*s r# _is_magicrs d1R4j D ((r"c$eZdZdZdZdZdZdS)_SentinelObjectz!A unique, named, sentinel object.c||_dSr<rrWr*s r#rHz_SentinelObject.__init__"s  r"cd|jzSNz sentinel.%srrWs r#__repr__z_SentinelObject.__repr__%ty((r"cd|jzSrrrs r# __reduce__z_SentinelObject.__reduce__(rr"N)rrrr rHrrr!r"r#rr sG''))))))))r"rc$eZdZdZdZdZdZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.ci|_dSr<) _sentinelsrs r#rHz_Sentinel.__init__.s r"cl|dkrt|j|t|S)N __bases__)rLr setdefaultrrs r# __getattr__z_Sentinel.__getattr__1s3 ;   ))$0E0EFFFr"cdS)Nrr!rs r#rz_Sentinel.__reduce__7szr"N)rrrr rHrrr!r"r#rr,sJKKGGG r"r> _mock_namer _mock_parentr_mock_new_name_mock_new_parent_mock_side_effect_mock_return_valuecxt|d|z}||fd}||fd}t||S)N_mock_cT|j}|t||St||Sr<)rr1)rWr* _the_namerZs r#_getz"_delegating_property.._getLs/! ;4++ +sD!!!r"cR|j}| ||j|<dSt|||dSr<)rrrrg)rWvaluer*rrZs r#_setz"_delegating_property.._setQs9! ;',DM) $ $ $ Cu % % % % %r")_allowed_namesaddproperty)r*rrrs r#_delegating_propertyrIset4I """" $y&&&& D$  r"ceZdZdZdZdS)rct|tst||St|}t|}||krdSt d||z dzD]}||||z}||krdSdS)NFrT)r/rm __contains__lenrange)rWr len_valuelen_selfisub_lists r#rz_CallList.__contains__^s%&& 2$$T511 1JJ t99 x  5q(Y.233  AAa kM*H5  tt!ur"cDtjt|Sr<)pprintpformatrmrs r#rz_CallList.__repr__ls~d4jj)))r"N)rrrrrr!r"r#rr\s2   *****r"rct|}t|sdS|js|js|j|jdS|}|||urdS|j}||r||_||_|r||_||_dS)NFT)rFr.rrrr)parentrr*new_name_parents r#_check_and_set_parentrps % E U # #u  U1   '   +uG   e  5*  (!''  # 4r"ceZdZdZdZdS) _MockIterc.t||_dSr<)iterr5)rWr5s r#rHz_MockIter.__init__s99r"c*t|jSr<)nextr5rs r#__next__z_MockIter.__next__sDH~~r"N)rrrrHrr!r"r#rrs2r"rceZdZeZdZdZdS)BaseNcdSr<r!rWrXrYs r#rHz Base.__init__s r")rrrrrrrHr!r"r#rrs/      r"rceZdZdZeZdZ d-dZdZd.dZ d/d Z d Z d Z d Z ee e e Zed ZedZedZedZedZedZdZdZeeeZd0ddddZdZdZdZdZdZdZ dZ!dZ"d1d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)d'Z*d.d(Z+d)Z,d*Z-d2d,Z.dS)3r z A non-callable version of `Mock`cz|f}t|ts]tj|g|Ri|j}|d|d}|t |r t|f}t|j|d|j i}tt| |}|S)Nspec_setspecr ) r=AsyncMockMixin _MOCK_SIG bind_partial argumentsrsr6r>rr _safe_superr __new__)clsrXkwbases bound_argsspec_argnewras r#rzNonCallableMock.__new__s#~.. ."/AdAAAbAAKJ!~~j*..2H2HIIH# h(?(?#'-3<CK(@AA44<rRrr) rWrrrrr&r(r*rresrrs r#rzNonCallableMock._mock_add_specs' T " " T"#R#R#R#RSS S  II * *D"74t#<#<== *##D)))  HTNN $%% )" "4jj '(99FFC!nc!fOt99D="- (&5"#$(!#/   r"c|j}|j |jj}|tur%|j||d}||_|S)N()rr)rrrrr_get_child_mock)rWrs r#__get_return_valuez"NonCallableMock.__get_return_values]%   *%2C '>>d.6&& D'C!$D  r"cb|j||j_dS||_t||dddS)Nr/)rrrr)rWrs r#__set_return_valuez"NonCallableMock.__set_return_value%s>   */4D  , , ,&+D # !$tT : : : : :r"z1The value to be returned when the mock is called.c<|jt|S|jSr<)r&r>rs r# __class__zNonCallableMock.__class__1s   #:: r"rrrrrc|j}||jS|j}|It|s:t |t s%t |st |}||_|Sr<)rrrcallabler/rrA)rW delegatedsfs r#__get_side_effectz!NonCallableMock.__get_side_effect>sj'  ) )  " N8B<>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)c8|ddS)Nr.)count)entrys r#z0NonCallableMock.configure_mock..sq1D1Dr")keyrIN)sorteditemssplitpopr1rg)rWrYargvalrXfinalr5rKs r#rzNonCallableMock.configure_mockrsv||~~$E#D FFF % %HC 99S>>DHHJJEC * *c5)) C $ $ $ $ % %r"c |dvrt||j%||jvs |tvrtd|znt|rt||js:|jr ||jvr*|drt|d|dt j5|j |}|turt||Cd}|j t|j |}| |||||}||j|<nt|trv t!|j|j|j|j|j}n>#t,$r1|jdp|}t-d|d |d |d |jd wxYw||j|<dddn #1swxYwY|S) N>rr)zMock object has no attribute %r)assertassretasertaseertassrtz6 is not a valid assertion. Use a spec for the mock if z is meant to be an attribute.)rr*rrrrCannot autospec attr from target , as it has already been mocked out. [target=, attr=r%)rLr) _all_magicsrrr(r _lockrrsrDrr1r1r/rCr rrrarr*rrr)rWr*r}r target_names r#rzNonCallableMock.__getattr__s 4 4 4 && &   +4---1D1D$%F%MNNN2E t__ ' && &  N$*< NDL^@^@^OPP N$MM'+MMMNNN " 4 4(,,T22F!!$T***#/$D$4d;;E--d%4 $..4#D))FJ// 4 D, V_fo v{FF(DDD"&- "="EK*CCC&CC#'CC28+CCCDDDD .4#D); 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4> s++B F:9,E&%F:&;F!! F::F>F>cn|jg}|j}|}d}|dgkrd}|7|}||j|zd}|jdkrd}|j}|7tt |}|jpd}t |dkr|ddvr|dz }||d<d|S)NrIr/r rDr)r/z().r)rrr,rmreversedrrjoin)rW _name_listrlastdot_firsts r#_extract_mock_namez"NonCallableMock._extract_mock_names)* ' $  C!D   g4s: ; ; ;C%--.G!(:..// *F z??Q  !}M11#  1 wwz"""r"c|}d}|dvrd|z}d}|jd}|jrd}||jjz}dt |j||dt |dS) Nr )rDzmock.z name=%rz spec=%rz spec_set=%r)rir&r'rr>rA)rWr* name_string spec_strings r#rzNonCallableMock.__repr__s&&(( ( ( ($t+K   '$K~ -, %(8(AAK JJ   K KK tHHHH   r"cvtst|S|jpg}t t |}t |j}d|j D}d|D}d|D}tt||z|z|zS)z8Filter the output of `dir(mock)` to only useful members.c*g|]\}}|tu|Sr!)rD)r)m_namem_values r# z+NonCallableMock.__dir__..s1(((&vwh&& &&&r"c<g|]}|d|Sr%r'r)es r#rrz+NonCallableMock.__dir__..s)CCC1c1B1BCQCCCr"cZg|](}|drt|&|)Sr%)r(rrts r#rrz+NonCallableMock.__dir__..sE###1c1B1B#q\\#Q###r") r object__dir__r)r+r>rmrrrrOrNset)rWextras from_type from_dictfrom_child_mockss r#rxzNonCallableMock.__dir__s (>>$'' '#)rT OO '' ((*.*=*C*C*E*E(((DC CCC ## ### c&9,y8;KKLLMMMr"cT|tvrt||Sjr+j$|jvr|jvrt d|z|tvrd|z}t ||tvrj|jvrt d|zt|s5tt|t|||fd}nft|d|tt|||j|<n+|dkr |_dSt|||r |j|<jr;t#|s+d|}t d|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.cg|Ri|Sr<r!)rXrr|rWs r#rLz-NonCallableMock.__setattr__.. s!HHT,GD,G,G,GB,G,Gr"r6rIz Cannot set )rrw __setattr__r'r)rrrL_unsupported_magicsr_r.rgr> _get_methodrrr&r r0ri)rWr*rmsg mock_namer|s` @r#rzNonCallableMock.__setattr__s > ! !%%dD%88 8n 2!3!? * * *  % % !Dt!KLL L ( ( (BTIC %% % [ !-$d>P2P2P$%H4%OPPP$U++ 2T D+dE*B*BCCC GGGGG&dE4>>>T D%000,1#D)) [ $D  F$T5$== 2,1#D)   |t|jvr(tt||||jvrdS|j|t }||jvr)tt| |n|turt||t ur|j|=t|j|<dSr<) r_r>rrdelattrrrs_missingrr __delattr__rDrL)rWr*r5s r#rzNonCallableMock.__delattr__!s ;  44::+>#>#> DJJ % % %4=((!%%dH55 4=  . . : :4 @ @ @ @ H__ && & h  #D)$,D!!!r"c6|jpd}t|||SrC)r_format_call_signaturerWrXrYr*s r#_format_mock_call_signaturez+NonCallableMock._format_mock_call_signature3s (&%dD&999r"rcdd}|||}|j}|j|}||||fzS)Nz0expected %s not found. Expected: %s Actual: %s)rr)rWrXrYactionmessageexpected_stringr actual_strings r#_format_mock_failure_messagez,NonCallableMock._format_mock_failure_message8sDF::4HHN 88)D &/=AAAr"c|s|jSd}|ddd}|j}|D]M}||}|t |t rnt|}|j}|j}N|S)aH * If call objects are asserted against a method/function like obj.meth1 then there could be no name for the call object to lookup. Hence just return the spec_signature of the method/function being asserted against. * If the name is not empty then remove () and split by '.' to get list of names to iterate through the children until a potential match is found. A child mock is created only during attribute access so if we get a _SpecState then no attributes of the spec were accessed and can be safely exited. Nr/r rI)r(replacerPrrsr/rCrF)rWr*rZnameschildrenrFs r#_get_call_signature_from_namez-NonCallableMock._get_call_signature_from_name@s (' ' T2&&,,S11& , ,DLL&&E} 5* = =} &e,, /+ r"ct|tr/t|dkr||d}n|j}|vt|dkrd}|\}}n|\}}} |j|i|}t ||j|jS#t$r}| dcYd}~Sd}~wwxYw|S)a Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. rrNr ) r/rnrrr(rVrrXrY TypeErrorwith_traceback)rW_callrZr*rXrY bound_callrus r# _call_matcherzNonCallableMock._call_matcheras eU # # 'E Q44U1X>>CC&C ?5zzQ$ ff%*"dF .%SXt6v66 D*/:3DEEE . . .''-------- .Ls0'B C"B<6C<Cc|jdkr8d|jpdd|jd|}t|dS)z/assert that the mock was never called. r Expected 'rDz"' to not have been called. Called  times.Nrr _calls_reprAssertionErrorrWrs r#rz!NonCallableMock.assert_not_called|s^ ?a   o///ooo&&(((*C!%% % r"cR|jdkrd|jpdz}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.rDN)rrrrs r#rzNonCallableMock.assert_calleds; ?a  7O-v/C %% % r"c|jdks8d|jpdd|jd|}t|dS)z3assert that the mock was called only once. rrrDz#' to have been called once. Called rNrrs r#rz"NonCallableMock.assert_called_onces^!###o///ooo&&(((*C!%% % $#r"ctj/}d}d|d|}t|fd}t fd}j}||kr1t |t r|nd}t||dS)zassert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.Nz not called.z#expected call not found. Expected: z Actual: c4}|Sr<rrrXrYrWs r#_error_messagez:NonCallableMock.assert_called_with.._error_messages33D&AACJr"Ttwo)rrrr_Callr/ Exception)rWrXrYexpectedactual error_messagercauses``` r#rz"NonCallableMock.assert_called_withs > !77fEEH"FFxx)M // /       %%eT6N&E&E&EFF##DN33 X   *8Y ? ?IHHTE !1!122 =  r"c|jdks8d|jpdd|jd|}t||j|i|S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rrrDz' to be called once. Called r)rrrrrrWrXrYrs r#rz'NonCallableMock.assert_called_once_withsn!###o///ooo&&(((*C!%% %&t&7777r"cfd|D}td|Dd}tfdjD}|su||vro|d}ndd|D}t |dt|d d |dSt|}g}|D]=} ||#t$r| |Y:wxYw|r-t j pd d t|d|d|dS)aassert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.c:g|]}|Sr!rr)crWs r#rrz4NonCallableMock.assert_has_calls..'999aD&&q))999r"c3DK|]}t|t|VdSr<r/rrts r# z3NonCallableMock.assert_has_calls..1FFAZ9-E-EFaFFFFFFr"Nc3BK|]}|VdSr<rrs r#rz3NonCallableMock.assert_has_calls..s1MMd0033MMMMMMr"zCalls not found.z+Error processing expected calls. Errors: {}c@g|]}t|tr|ndSr<rrts r#rrz4NonCallableMock.assert_has_calls..;$7$7$7()*4Ay)A)A$KAAt$7$7$7r" Expected: z Actual)prefixrIrDz does not contain all of z in its call list, found z instead) rrrformatrrrstriprmremoverNr,rrn) rWcalls any_orderrr all_callsproblem not_foundkalls ` r#rz NonCallableMock.assert_has_callss:9995999FFFFFMMMMMMT_MMMMM  y((=0GG ,-3V$7$7-5$7$7$7.8.8%II!*5!1!1I''z'::AA#FFII  FOO   ' 'D '  &&&& ' ' '  &&&&& '   &*o&?&?&?&+I&6&6&6&6 C    sC--DDc$t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)zassert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.TrNc:g|]}|Sr!rrs r#rrz3NonCallableMock.assert_any_call..s'EEEA$$$Q''EEEr"z%s call not found)rrr/rr _AnyComparerrrrWrXrYrrrrs` r#rzNonCallableMock.assert_any_calls %%eT6N&E&E&EFF&x;;EEEEE1DEEE  HL$8$888">>tVLLO #o5 98r"c |jr7d|vr d|dnd}||z}t||d}||jdvr t di|St |}t|tr|tvrt }nt|tr)|tvs|j r||j vrt}ndt }n\t|ts:t|trt}n*t|trt }n |jd}|di|S)aPCreate the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).r*rIr/rr*rr!)r rirLrsrrr r>r=r_async_method_magicsr_all_sync_magicsr) CallableMixinr r rrq)rWrrirr_typeklasss r#r1zNonCallableMock._get_child_mocks[   ,,2bLL(BvJ(((dI//11I=I ++ +FF;''  n5 5 5??r?? "T  eY ' ' %I9M,M,MEE ~ . . %---&.+48J+J+J!!E=11 %%!566 !E?33 M!$Eu{{r{{r"CallscJ|jsdSd|dt|jdS)zRenders self.mock_calls as a string. Example: " Calls: [call(1), call(2)]." If self.mock_calls is empty, an empty string is returned. The output will be truncated if very long. r  z: rI)rr)rWrs r#rzNonCallableMock._calls_reprs6 2;F;;i88;;;;r") NNNNNNr NFNFF)FFr<)r)r)/rrrr rr`rrHrr#r"_NonCallableMock__get_return_value"_NonCallableMock__set_return_value"_NonCallableMock__return_value_docrrr6rrrrrr!_NonCallableMock__get_side_effect!_NonCallableMock__set_side_effectrrrrrirrxrrrrrrrrrrrrrr1rr!r"r#r r s** EGGE   ">BEI   ;;;M8.0B.00L  X " !( + +F%%l33J$$[11I))*:;;N%%l33J   ***(,.?@@K$u%$$$$$<%%%,---`###6   *NNN$$5$5$5N---$::: BBBBB6&&&&&&&&&>>>, 8 8 8****Z    ###L < < < < < .5s1$HfF"r"TF)allzip)rWitemrs r#rz_AnyComparer.__contains__2s^  E(+D%(8(8 tt   ur"N)rrrr rr!r"r#rr-s-r"rc||St|r|St|r|S t|S#t$r|cYSwxYwr<)rArkrrr4s r#r=r==sk { S ~~ Cyy  s7 AAc HeZdZddedddddddf dZdZdZdZdZdZ dS) rNr c x||jd<tt|j||||||| | fi| ||_dS)Nr)rrrrrHr) rWrrrrr*rrrrrrYs r#rHzCallableMixin.__init__Nsa/; *+1 M4((1 %x K  39   'r"cdSr<r!rs r#r^zCallableMixin._mock_check_sigZs r"cP|j|i||j|i||j|i|Sr<)r^_increment_mock_call _mock_callrs r#rKzCallableMixin.__call___sK d-f---!!426222t////r"c|j|i|Sr<)_execute_mock_callrs r#rzCallableMixin._mock_callgs&t&7777r"c~d|_|xjdz c_t||fd}||_|j||jdu}|j}|j}|dk}|j td||f|j }||rB|j t|||f|jdu}|r |jdz|z}t|||f} |j | |jr|rd} nd} |jdk}|j| z|z}|j }|dSdS)NTrrr/r rI) rrrrrr,rrrrrr) rWrXrYrdo_method_callsmethod_call_namemock_call_name is_a_callrthis_mock_callrgs r#rz"CallableMixin._increment_mock_calljs  1 tVn$/// ""5)))+47?,"d*  ub$%788999+ % W(//7Gv6V0W0WXXX"-":$"F"W'2'='CFV'V$#ND&#ABBN  " ) ). 9 9 9) SCCC'6$> !,!;c!AN!R&6K-%%%%%r"c^|j}|Tt|r|t|s!t|}t|r|n||i|}|tur|S|jtur|jS|jr|jjtur|jS|j |j|i|S|jSr<) rrArkrrrrrr)rWrXrYeffectr}s r#rz CallableMixin._execute_mock_calls!  V$$ 1 v&& 1f ((! L! 000W$$  "' 1 1$ $   %4#6#C7#R#R$ $   '#4#T4V44 4  r") rrrrrHr^rKrrrr!r"r#rrLs d$d!RT ' ' ' '   000888,7,7,7\!!!!!r"rceZdZdZdS)ra Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an `AttributeError`. If `spec` is an object (rather than a list of strings) then `mock.__class__` returns the class of the spec object. This allows mocks to pass `isinstance` tests. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as `spec_set` will raise an `AttributeError`. * `side_effect`: A function to be called whenever the Mock is called. See the `side_effect` attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns `DEFAULT`, the return value of this function is used as the return value. If `side_effect` is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned. * `return_value`: The value returned when the mock is called. By default this is a new Mock (created on first access). See the `return_value` attribute. * `unsafe`: By default, accessing any attribute whose name starts with *assert*, *assret*, *asert*, *aseert* or *assrt* will raise an AttributeError. Passing `unsafe=True` will allow access to these attributes. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an `AttributeError`). If the mock has an explicit `return_value` set then calls are not passed to the wrapped object and the `return_value` is returned instead. * `name`: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks. Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. Nrr!r"r#rrs5555r"rc@d}|D]}||vrt|ddS)N) autospect auto_specset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)kwargs_to_checktypostypos r#_check_spec_arg_typosrsN 2E ? " "PPP  #r"c~eZdZdZgZdddZdZdZdZe j dZ d Z d Z d Zd Zd ZdZdZdS)_patchNFrc |)|turtd|td| st| t|rt d|d|dt|rt d|d|d||_||_||_||_||_ ||_ d|_ ||_ ||_ | |_g|_dS)Nz,Cannot use 'new' and 'new_callable' togetherz1Cannot use 'autospec' and 'new_callable' togetherzCannot spec attr z0 as the spec has already been mocked out. [spec=r%z? as the spec_set target has already been mocked out. [spec_set=F)rrNrr.rgetterrir  new_callablercreate has_localrautospecrYadditional_patchers) rWrrir rrrr rrYrs r#rHz_patch.__init__sV  #'!! B# G * !& ) ) ) T " " A"@I@@6:@@@AA A X & & P"OIOOAIOOOPP P "(       #%   r"c t|j|j|j|j|j|j|j|j|j }|j |_ d|j D|_ |S)Nc6g|]}|Sr!)copy)r)ps r#rrz_patch.copy..,s-' ' ' AFFHH' ' ' r") rrrir rrrr rrYattribute_namer )rWpatchers r#rz _patch.copy%sq K49 K M4,dk   "&!4' ' "6' ' ' #r"ct|tr||Stj|r||S||Sr<r/r>decorate_classr2rdecorate_async_callabledecorate_callable)rWr9s r#rKz_patch.__call__2sc dD ! ! -&&t,, ,  &t , , 6//55 5%%d+++r"ct|D]q}|tjs"t ||}t |dsC|}t||||r|SNrK)r+r(r TEST_PREFIXr1r0rrg)rWrr attr_valuers r#rz_patch.decorate_class:sJJ 6 6D??5#455  --J:z22 iikkG E4!4!4 5 5 5 5 r"c#TKg}tj5}|jD]W}||}|j||4|jtur||X|t|z }||fVddddS#1swxYwYdSr<) contextlib ExitStack patchings enter_contextrupdater rr,rn)rWpatchedrXkeywargs extra_args exit_stackpatchingrRs r#decoration_helperz_patch.decoration_helperHs  ! # # #z#- + + ..x88*6OOC((((\W,,%%c*** E*%% %D" " " " # # # # # # # # # # # # # # # # # #sA8BB!$B!ctdrjStfdg_S)Nrc|||5\}}|i|cdddS#1swxYwYdSr<r&rXr"newargs newkeywargsr9r!rWs r#r!z)_patch.decorate_callable..patched]s''(,(022 55Kg{tW4 44 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5s 155r0rr,rrWr9r!s``@r#rz_patch.decorate_callableWsv 4 % %  N ! !$ ' ' 'K t 5 5 5 5 5 5  5 "Fr"ctdrjStfdg_S)NrcK||5\}}|i|d{VcdddS#1swxYwYdSr<r)r*s r#r!z/_patch.decorate_async_callable..patchedns''(,(022 ;5Kg{!T7:k:::::::: ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;s 9==r-r.s``@r#rz_patch.decorate_async_callablehsv 4 % %  N ! !$ ' ' 'K t ; ; ; ; ; ;  ; "Fr"c`|}|j}t}d} |j|}d}n-#tt f$rt ||t}YnwxYw|tvrt|trd|_ |j s|turt |d|||fS)NFTz does not have the attribute ) rrirrrrLKeyErrorr1 _builtinsr/rr)rWtargetr*r|locals r# get_originalz_patch.get_originalys~ t,HEE) 6 6 6vtW55HHH 6 9  FJ!?!? DK{ x722 7=vvttD s 6'A A c |j|j|j}}}|j|j}}|j}||_|durd}|durd}|durd}||td|||dvrtd| \}}|tur|d} |dur |}|dur|}d}n| |dur|}d}n|dur|}||/|turtdt|trd} |t|rt} nt} i} ||} nN||J|} ||} t!| rd| v} nt#|  } t| rt} n | rt$} ||| d <||| d <t| tr&t'| t(r|jr |j| d <| || di| }| r_t/|rP|} ||} t!| st1| st$} | d | d|d d | |_n||turtd|turtdt7|}|dur|}t/|jr#t9d|jd|jd|dt/|rAt;|jd|j}t9d|jd|d|jd|d t=|f||jd|}n|rtd|}||_||_ tCj"|_# tI|j|j||j%ci}|jtur |||j%<|j&D]?}|j#'|}|jtur||@|S|S#|j(tSj*sYdSxYw)zPerform the patch.FNzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=TruerKrrr*r/r0zBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=Truer[z: as the patch target has already been mocked out. [target=r^r%rr\r])r_namez.Can't pass kwargs to a mock we aren't creatingr!)+r rrr rYrrr4rr6rr/r>r6r rror8r r=r rir r.rurQrboolrr1r temp_originalis_localrr _exit_stackrgrr r__exit__sysexc_info)rWr rrr rYrr|r5inheritKlass_kwargs this_spec not_callableranew_attrr#r%rRs r# __enter__z_patch.__enter__s"h 4=8T=$+&( kkmm  5==D u  H u  H   4=>> >  !5 L ( (TUU U++--% '>>h.Gt||t##'HD!t###HDT!!#8#7w&&#$GHHHh--#"G| h 7 7|!!G'$!X%9 ' (II&&;#-Y#>LL'/ ':':#:L ++1%EE!10E"&#&. #5$'' 15/22 17;~ 1"&. NN6 " " "%""'""C 4,S11 4! ' (I ++1&y1110E F####(5$4SD$4$4+2$4$4  !'!!(7"" GHHHH~~H4# -- D&CDNCC#{CC5=CCCDDD!** D%dk:t{KK &CDNCC"CC#{CC5=CCCDDD "(BX(,BB:@BBCC  NLMM M% %/11  DK : : :". 8w&&7:Jt23 $ 8//H*88BBC|w.."))#...!!J  4=#,..1    sBOOO<ch|jr/|jtur!t|j|j|jndt |j|j|jsCt|j|jr |jdvr t|j|j|j|`|`|`|j }|` |j |S)zUndo the patch.)r rre__annotations__rf) r;r:rrgr4rirrr0r<r=)rWr?r$s r#r=z_patch.__exit__#s = IT/w>> DK1C D D D D DK 0 0 0; I T^(L(L I+=== T^T5GHHH   M K%  "z"H--r"cb|}|j||Sz-Activate a patch, returning any created mock.)rF_active_patchesr,rWr}s r#startz _patch.start8s-!! ##D))) r"c |j|n#t$rYdSwxYw|dddSzStop an active patch.N)rKrrNr=rs r#stopz _patch.stop?s[   ' ' - - - -   44 }}T4...s  ++)rrrrrKrHrrKrrcontextmanagerr&rrr6rFr=rMrPr!r"r#rrsNOAF"&"&"&"&"&J   ,,,    # # #""0PPPd...*/////r"rc |dd\}}n-#tttf$rtd|wxYwt t j||fS)NrIrz,Need a valid target to patch. You supplied: )rsplitrrNrLrpkgutil resolve_name)r4ris r# _get_targetrVKsG"MM#q11 z> 2GGG E6 E EGG GG 7' 0 0) ;;s *Arc tturtdfd} t| |||||||| | S)a patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. z3 must be the actual object to be patched, not a strcSr<r!r4sr#rLz_patch_object..jsVr"r)r>strrr) r4rir rrrr rrrYrs ` r# _patch_objectr[Tsn$ F||s L L L   ^^^F  3f(L&   r"c tturttj}nfd}|st dt |}|d\} } t|| | |||||i } | | _ |ddD]=\} } t|| | |||||i } | | _ | j | >| S)aPerform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. cSr<r!rYsr#rLz!_patch_multiple..sr"z=Must supply at least one keyword argument with patch.multiplerrN) r>rZrrTrUrNrmrOrrr r,) r4rrrr rrYrrOrir r this_patchers ` r#_patch_multipler_qs , F||s-v66   K     E1XNIs 3fh,G'G)99 3 IsD&( lB  '0 ##**<8888 Nr"c Xt|\} } t| | |||||||| S)a: `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with an `AsyncMock if the patched object is an async function or a `MagicMock` otherwise. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `AsyncMock` is used for async functions and `MagicMock` for the rest. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. Patch will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `patch` takes arbitrary keyword arguments. These will be passed to `AsyncMock` if the patched object is asynchronous, to `MagicMock` otherwise or to `new_callable` if specified. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. r)rVr) r4r rrrr rrrYrris r#rrsDV$F++FI  3f(L&   r"cVeZdZdZddZdZdZdZdZd Z d Z d Z d Z d Z dZdS) _patch_dicta# Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. r!Fc ||_t||_|j|||_d|_dSr<)in_dictdictrBr clear _original)rWrdrBrfrYs r#rHz_patch_dict.__init__s> 6ll  6""" r"ct|tr||Stj|r||S||Sr<r)rWfs r#rKz_patch_dict.__call__sc a   *&&q)) )  &q ) ) 3//22 2%%a(((r"c@tfd}|S)Nc |i|S#wxYwr<rb _unpatch_dictrXrrirWs r#_innerz-_patch_dict.decorate_callable.._inner#sV       %q$~"~~""$$$$""$$$$s 3A rrWriros`` r#rz_patch_dict.decorate_callable"9 q % % % % %  % r"c@tfd}|S)NcK |i|d{V S#wxYwr<rlrns r#roz3_patch_dict.decorate_async_callable.._inner/so       %Q^^^+++++++""$$$$""$$$$s <Arprqs`` r#rz#_patch_dict.decorate_async_callable.rrr"c t|D]}}t||}|tjrLt |dr"/ ==DL,  -||~~HH - - -H - - '   - -  - "  !   + NN6 " " " " " + + + + +%c{  + + + +s$A$$BBB66CCc|j}|j}t| ||dS#t$r|D] }||||<YdSwxYwr<)rdrgrzr rL)rWrdr|rMs r#rmz_patch_dict._unpatch_dictgs,>G - NN8 $ $ $ $ $ - - - - -'}  - - - -s6AAc<|j|dS)zUnpatch the dict.NF)rgrm)rWrXs r#r=z_patch_dict.__exit__ts! > %    ur"cl|}tj||SrJ)rFrrKr,rLs r#rMz_patch_dict.start{s-!!%%d+++ r"c tj|n#t$rYdSwxYw|dddSrO)rrKrrNr=rs r#rPz_patch_dict.stops[   " ) )$ / / / /   44 }}T4...s " 00N)r!F)rrrr rHrKrrrrFrbrmr=rMrPr!r"r#rbrbs8)))       +++8 - - -/////r"rbc |dS#t$rt|}|D]}||=YdSwxYwr<)rfrLrm)rdkeysrMs r#rzrzse  G}}  C    s !==cfttjD]}|dS)z7Stop all active patches. LIFO to unroll nested patches.N)rcrrKrP)rs r#_patch_stopallrs5&011 r"testzlt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod rdivmod neg pos abs invert complex int float index round trunc floor ceil bool next fspath aiter zDadd sub mul matmul truediv floordiv mod lshift rshift and xor or pow c# K|] }d|zV dS)zi%sNr!r)ns r#rrs&77519777777r"c# K|] }d|zV dS)zr%sNr!rs r#rrs&55q555555r">rx__get____set__r __delete__ __format__r __missing__ __getstate__ __reversed__ __setstate__ __getformat__ __reduce_ex____getnewargs____subclasses____getinitargs____getnewargs_ex__c fd}||_|S)z:Turns a callable object (like a mock) into a real functionc|g|Ri|Sr<r!)rWrXrr9s r#methodz_get_method..methods#tD&4&&&2&&&r")r)r*r9rs ` r#rrs('''''FO Mr"ch|]}d|zS)rr!)r)rs r#r+r+s*    Hv   r"> __aexit__ __anext__ __aenter__ __aiter__>__del__rrHr __prepare__r__instancecheck____subclasscheck__c6t|Sr<)rw__hash__rs r#rLrLsV__T22r"c6t|Sr<)rw__str__rs r#rLrLsFNN400r"c6t|Sr<)rw __sizeof__rs r#rLrLsv0066r"cxt|jd|dt|S)N/)r>rrirArs r#rLrLs;$t**"5^^8O8O8Q8Q^^TVW[T\T\^^r")rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r= __complex__ __float____bool__ __index__rcfd}|S)NcLjj}|tur|S|urdStSNT)__eq__rrNotImplemented)otherret_valrWs r#rz_get_eq..__eq__s1+0 ' ! !N 5==4r"r!)rWrs` r#_get_eqrs# Mr"cfd}|S)NcRjjturtS|urdStSNF)__ne__rrr)rrWs r#rz_get_ne..__ne__s, ; ) 8 8N 5==5r"r!)rWrs` r#_get_ners# Mr"cfd}|S)Ncjjj}|turtgSt|Sr<)__iter__rrrrrWs r#rz_get_iter..__iter__s1-2 g  88OG}}r"r!)rWrs` r# _get_iterr s# Or"cfd}|S)Ncjj}|turtt gStt |Sr<)rrr_AsyncIteratorrrs r#rz"_get_async_iter..__aiter__s@.3 g  !$r((++ +d7mm,,,r"r!)rWrs` r#_get_async_iterrs$----- r")rrrrc&t|t}|tur ||_dSt|}|||}||_dSt |}||||_dSdSr<)_return_valuesrsrr_calculate_return_value_side_effect_methodsr)rDrr*fixedreturn_calculatorr side_effectors r#_set_return_valuer(s   tW - -E G#/33D99$((.. *(,,T22M *]400! r"ceZdZdZdZdS) MagicMixinc|tt|j|i||dSr<)_mock_set_magicsrrrHrWrXrs r#rHzMagicMixin.__init__;sN . J%%.;;;; r"c ttz}|}t|ddX||j}t }||z }|D](}|t |jvrt||)|t t |jz }t |}|D]!}t||t||"dS)Nr)) _magicsrr1 intersectionr)ryr>rrrrg MagicProxy)rW orig_magics these_magics remove_magicsrKrs r#rzMagicMixin._mock_set_magicsAs 44 " 4$ / / ;&33D4FGGLEEM',6M& ) )DJJ///D%((($c$t***=&>&>> T ! ; ;E E5*UD"9"9 : : : : ; ;r"N)rrrrHrr!r"r#rr:s2   ;;;;;r"rceZdZdZddZdS)r z-A version of `MagicMock` that isn't callable.FcZ||||dSr!rrr"s r#r#z"NonCallableMagicMock.mock_add_spec[2 D(+++ r"Nrrrrr r#r!r"r#r r Ys.77      r"r ceZdZdZdS)AsyncMagicMixinc|tt|j|i||dSr<)rrrrHrs r#rHzAsyncMagicMixin.__init__fsN 3 OT**3T@R@@@ r"NrrrrHr!r"r#rres#     r"rceZdZdZddZdS)ra MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. FcZ||||dSr!rr"s r#r#zMagicMock.mock_add_specvrr"Nrrr!r"r#rrks2        r"rc"eZdZdZdZddZdS)rc"||_||_dSr<r*r)rWr*rs r#rHzMagicProxy.__init__s  r"c|j}|j}||||}t|||t ||||S)N)r*rr)r*rr1rgr)rWrKrms r# create_mockzMagicProxy.create_mocksZ   " "/5 # 7 7q!!!&!U+++r"Nc*|Sr<)r)rWr5rs r#rzMagicProxy.__get__s!!!r"r<)rrrrHrrr!r"r#rrsF""""""r"rceZdZedZedZedZfdZdZdZ dZ dZ d Z d Z dd Zd ZfdZxZS)rrrrctj|i|tjj|jd<d|jd<d|jd<t |jd<tt}tj tj ztj z|_ d|_d|_d|_d|_||jd<d |jd <t%|jd <i|jd <d|jd <dS)Nrr_mock_await_count_mock_await_args_mock_await_args_listr)rXrYr8r rrerfrH)superrHrrrrrrr rr2 CO_COROUTINE CO_VARARGSCO_VARKEYWORDSco_flags co_argcount co_varnamesco_posonlyargcountco_kwonlyargcountrn)rWrXrY code_mockr6s r#rHzAsyncMockMixin.__init__s$)&)))*1);)I o&-. )*,0 ()1: -.#X666    !$ %  !"  2 '( $&' #$- j!$/ j!(- n%*, &'+/ '(((r"c`Kt||fd}|xjdz c_||_|j||j}|t |r|t|s8 t|}n#t$rtwxYwt |r|n&t|r||i|d{V}n||i|}|tur|S|j tur|jS|j4t|jr|j|i|d{VS|j|i|S|jS)NTrr)rrrrr,rrArkr StopIterationStopAsyncIterationrrrrr)rWrXrYrrr}s r#rz!AsyncMockMixin._execute_mock_callstVn$/// A ##E***!  V$$ 1 v&& 1-!&\\FF$----,-!((! L!$V,, 1%vt6v66666666000W$$  "' 1 1$ $   '"4#344 ?-T-t>v>>>>>>>>>#4#T4V44 4  s 1BBcT|jdkrd|jpdd}t|dS)zA Assert that the mock was awaited at least once. r Expected rDz to have been awaited.Nrrrrs r#rzAsyncMockMixin.assert_awaiteds?  q Odo7OOOC %% % ! r"cd|jdks$d|jpdd|jd}t|dS)z@ Assert that the mock was awaited exactly once. rrrD$ to have been awaited once. Awaited rNrrs r#rz"AsyncMockMixin.assert_awaited_oncesW1$$9t8&99#/999C %% %%$r"chj)}td|dfd}t fd}j}||kr1t |t r|nd}t||dS)zN Assert that the last await was with the specified arguments. NzExpected await: z Not awaitedc8d}|S)Nawait)rrrs r#rz:AsyncMockMixin.assert_awaited_with.._error_messages"33D&3QQCJr"Tr)rrrrrr/r)rWrXrYrrrrs``` r#rz"AsyncMockMixin.assert_awaited_withs ? "77fEEH !KH!K!K!KLL L       %%eT6N&E&E&EFF##DO44 X   *8Y ? ?IHHTE !1!122 =  r"cz|jdks$d|jpdd|jd}t||j|i|S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrrDr r)rrrrrs r#rz'AsyncMockMixin.assert_awaited_once_withsg 1$$9t8&99#/999C %% %'t'8888r"c$t||fd}t|tr|nd}fdjD}|s|t |vr)||}td|z|dS)zU Assert the mock has ever been awaited with the specified arguments. TrNc:g|]}|Sr!rrs r#rrz3AsyncMockMixin.assert_any_await.. s'FFFA$$$Q''FFFr"z%s await not found)rrr/rrrrrrs` r#rzAsyncMockMixin.assert_any_await s%%eT6N&E&E&EFF&x;;EFFFF1EFFF  HL$8$888">>tVLLO $6 98r"Fc*fd|D}td|Dd}tfdjD}|sT||vrN|d}ndd|D}t |dt|d j|dSt |}g}|D]=} ||#t$r||Y:wxYw|r t t|d |dS) a Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be sequential. There can be extra calls before or after the specified awaits. If `any_order` is True then the awaits can be in any order, but they must all appear in :attr:`await_args_list`. c:g|]}|Sr!rrs r#rrz4AsyncMockMixin.assert_has_awaits..# rr"c3DK|]}t|t|VdSr<rrts r#rz3AsyncMockMixin.assert_has_awaits..$ rr"Nc3BK|]}|VdSr<rrs r#rz3AsyncMockMixin.assert_has_awaits..% s1SSt11!44SSSSSSr"zAwaits not found.z,Error processing expected awaits. Errors: {}c@g|]}t|tr|ndSr<rrts r#rrz4AsyncMockMixin.assert_has_awaits..- rr"rz Actual: z not all found in await list) rrrrrrmrrNr,rn) rWrrrr all_awaitsrrrs ` r#rz AsyncMockMixin.assert_has_awaits s:9995999FFFFFMMSSSSd>RSSSSS  z))=1GG ,-3V$7$7-5$7$7$7.8.8%66!*5!1!166#366  F*%%   ' 'D '!!$'''' ' ' '  &&&&& '   49)4D4D4D4DF   s6C  C.-C.cd|jdkr$d|jpdd|jd}t|dS)z9 Assert that the mock was never awaited. rrrDz# to not have been awaited. Awaited rNrrs r#rz!AsyncMockMixin.assert_not_awaitedC sW  q 9t8&99#/999C %% % ! r"c|tj|i|d|_d|_t |_dS)z0 See :func:`.Mock.reset_mock()` rN)rrrrrr)rWrXrYr6s r#rzAsyncMockMixin.reset_mockL sB D+F+++({{r"r)rrrrrrrrHrrrrrrrrr __classcell__)r6s@r#rrs&&}55K%%l33J**+<==O000008&!&!&!P&&&&&&>>>$ 9 9 9   ****X&&&+++++++++r"rceZdZdZdS)r aY Enhance :class:`Mock` with features allowing to mock an async function. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable: >>> mock = AsyncMock() >>> iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) True The result of ``mock()`` is an async function which will have the outcome of ``side_effect`` or ``return_value``: - if ``side_effect`` is a function, the async function will return the result of that function, - if ``side_effect`` is an exception, the async function will raise the exception, - if ``side_effect`` is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, ``StopIteration`` is raised immediately, - if ``side_effect`` is not defined, the async function will return the value defined by ``return_value``, hence, by default, the async function returns a new :class:`AsyncMock` object. If the outcome of ``side_effect`` or ``return_value`` is an async function, the mock async function obtained when the mock object is called will be this async function itself (and not an async function returning an async function). The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`Mock` object behavior is the same as with an :class:`.Mock` object: the wrapped object may have methods defined as async function functions. Based on Martin Richard's asynctest project. Nrr!r"r#r r V s''''r"r c$eZdZdZdZdZdZdS)_ANYz2A helper object that compares equal to everything.cdSrr!rWrs r#rz _ANY.__eq__ str"cdSrr!rs r#rz _ANY.__ne__ sur"cdS)Nzr!rs r#rz _ANY.__repr__ swr"N)rrrr rrrr!r"r#rr sG88r"rcd|z}d}dd|D}dd|D}|r|}|r |r|dz }||z }||zS)Nz%s(%%s)r z, c,g|]}t|Sr!)repr)r)rRs r#rrz*_format_call_signature.. s7773T#YY777r"c"g|] \}}|d| S)=r!)r)rMrs r#rrz*_format_call_signature.. s4#-3333r")rdrO)r*rXrYrformatted_args args_string kwargs_strings r#rr s$GN))77$77788KII17M%$(  # d "N-' ^ ##r"ceZdZdZ ddZ ddZd ZejZd Z d Z d Z d Z e dZe dZdZdZdS)ra A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to a tuple without those values. This makes comparisons less verbose:: _Call(('name', (), {})) == ('name',) _Call(('name', (1,), {})) == ('name', (1,)) _Call(((), {'a': 'b'})) == ({'a': 'b'},) The `_Call` object provides a useful shortcut for comparing with call:: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) If the _Call has no name then it will match any name. r!r NFTcd}i}t|}|dkr|\}}}n~|dkr<|\} } t| tr| }t| tr| }nD| }nA| | }}n<|dkr6|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nr!rr)rr/rZrnr) rrr*rr from_kallrXrY_lenfirstseconds r#rz _Call.__new__ s5zz 199!& D$ QYY!ME6%%% -fe,,$!DD#FF$ff QYYFE%%% E5))   6==tVn55 5}}S4v"6777r"c0||_||_||_dSr<)rr_mock_from_kall)rWrr*rrr+s r#rHz_Call.__init__ s"(r"cr t|}n#t$r tcYSwxYwd}t|dkr|\}}n|\}}}t|ddr#t|ddr|j|jkrdSd}|dkrdi}}n|dkr|\}}}n|dkr?|\} t | t r| }i}nit | tr| }di}}nMd}| }nH|dkr@|\} } t | tr!| }t | t r| i}}n d| }}n| | }}ndS|r||krdS||f||fkS) Nr rrFrr!r*r)rrrr1rr/rnrZ) rWr len_other self_name self_args self_kwargs other_name other_args other_kwargsrr-r.s r#rz _Call.__eq__ s "E II " " "! ! ! ! " t99>>%) "I{{04 -Iy+ D.$ / / GE>SW4X4X %);;;5 >>')2 JJ !^^38 0J LL !^^FE%'' %" ! E3'' %" +-rL  $ !^^!ME6%%% 9" fe,,:/5r JJ/16 JJ+0&L 5  y005L)i-EEEs &&c|jtd||fdS|jdz}t|j||f||S)Nr r/rrrrrs r#rKz_Call.__call__ sN ? ""dF+$777 7%dotV44MMMMr"cn|jt|dS|jd|}t||dS)NF)r*r+rI)r*rr+r:)rWrr*s r#rz_Call.__getattr__ sD ? "de444 4///440$tu====r"cb|tjvrtt||Sr<)rnrrrL__getattribute__)rWrs r#r=z_Call.__getattribute__$ s+ 5> ! ! %%dD111r"cHt|dkr|\}}n|\}}}||fS)Nr)rrs r#_get_call_argumentsz_Call._get_call_arguments* s2 t99>>LD&&!% D$V|r"c6|dSNrr?rs r#rXz _Call.args2 ''))!,,r"c6|dS)NrrBrs r#rYz _Call.kwargs6 rCr"c|js%|jpd}|drd|z}|St|dkrd}|\}}n+|\}}}|sd}n |dsd|z}nd|z}t |||S)Nrr/zcall%srzcall.%s)r0rr(rr)rWr*rXrYs r#rz_Call.__repr__: s# ?,fDt$$ '$K t99>>DLD&&!% D$ '__T** ' 4'$%dD&999r"cg}|}|%|jr|||j}|%tt |S)zFor a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.)r0r,rrrc)rWvalsthings r# call_listz_Call.call_listO sW$ # E"""&E$(((r")r!r NFT)r!NNFT)rrrr rrHrrwrrKrr=r?rrXrYrrIr!r"r#rr s$:?8888@>C))))2F2F2Fj]FNNN>>>222 --X---X-:::* ) ) ) ) )r"r)r+c $t|rt|}t|t}t|rt d|dt |}d|i} |rd|i} n|i} | r|rd| d<|st || |t} tj |ri} nL|r|rtdt} n1t|st} n|r|rt|st} | d |}|} |d } | d||| |d | } t|t"r"t%| |} |rt'| nt)|| ||| |s | |j|<|d } |r |sd |vrt/||dd| | | _t3|D];}t5|r t7||}n#t8$rY1wxYwd|i}| r&t;| |r|||rd|i}t|t"st=||| ||}|| j|<n{| }t|t"r| j}tA|||}||d<tC|rt}nt}|d||||d|}|| j|<t)|||t|t"rtE| ||=| S)aCreate a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.z'Cannot autospec a Mock object. [object=r%rrNTrzJInstance can not be True when create_autospec is mocking an async functionr*r )rrrr*rrr/)rar8rrrpr)rr*rr)r`r!)#ror>r/r.rr:rr rr2isdatadescriptorrr rkr rurQrErrrbrrsr rr+rr1rLr0rCrD _must_skiprrg)rrrarr8rrYis_type is_async_funcrBrArrDwrappedrKr|r rr` child_klasss r#r r _ s.~~Dzzt$$G5 4*. 4 4 455 5"4((MtnGt$ ,8,'+#$ &f%%% NN6 E%% % %  ? >?? ? t__%$ %X%&8&>&>%$ KK & &EI 5 (W  ( (& ( (D$ &&8dD))  $ d # # #tWh7778(,u%jj!!G;x;N&$@$@+D(T2629;;;T3&3& U     tU++HH    H (#  *ww.. * MMM ) ) )  , (+F(M22 AXxuhGGC),D  & &F$ .. #"488I"+F; "8,, (' ' +(V%5*0(( &((C*-D  & Xsi @ @ @ @ c= ) ) & D% % % % Ks'G88 HHcDt|ts|t|divrdS|j}|jD]f}|j|t}|tur,t|ttfrdSt|tr|cSdS|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. rrF) r/r>r1r6rqrrrsrrJrIrE)rrKrMrr}s r#rLrL s dD ! ! GD*b11 1 15~  ##E733 W    f|[9 : : 55  . . NNN55 Nr"ceZdZ ddZdS)rCFNcZ||_||_||_||_||_||_dSr<)ridsrrrar*)rWrrrr*rTras r#rHz_SpecState.__init__ s0       r")FNNNFrr!r"r#rCrC s.48/4r"rCc|t|trtj|Stj|Sr<)r/bytesioBytesIOStringIO) read_datas r# _to_streamr[% s4)U##&z)$$${9%%%r"r c V t}|dg fd} fd} fd fd fd}tdddl}tt t |jt t |jat2ddl}tt t |j a |tdt }tt  j _ d j_ d j_ d j_ d j_ | j_ d < d  j_| j_ j_| j_ fd }||_ |_ |S) a A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. NcZjj jjSdj|i|SrA) readlinesrrXrY_statehandles r#_readlines_side_effectz)mock_open.._readlines_side_effect; s7   ( 4#0 0"vay"D3F333r"cZjj jjSdj|i|SrA)readrr_s r#_read_side_effectz$mock_open.._read_side_effect@ s4 ; # /;+ +vay~t.v...r"c?VKEd{V dj|i|VNTr)readline)rXrY_iter_side_effectr`s r#_readline_side_effectz(mock_open.._readline_side_effectE sT$$&&&&&&&&& 6$&)$d5f55 5 5 5 6r"c3bKjj jjVdD]}|VdSrg)rhr)liner`ras r#riz$mock_open.._iter_side_effectJ sU ? ' 3 3o2222 31I  DJJJJ  r"c^jj jjStdSrA)rhrr)r`rasr#_next_side_effectz$mock_open.._next_side_effectQ s) ? ' 3?/ /F1Ir"ropen)r*r)rrctd<jjdkrd<dj_tS)Nrr)r[rhrr)rXrYrjr`rarZs r# reset_datazmock_open..reset_dataq sMy))q ? &&) 3 3--//F1I*0)FO 'r")r[ file_spec_iormryr+ TextIOWrapperunionrX open_specrorrFrwriterdrhr^rrr) rDrZ _read_datarbrernrsrqrirjr`ras ` @@@@r#rr, sI&&J$ F444444 ////// 666666   S!23344::3s3;?O?O;P;PQQRR  S]]++,,  |f9555 I & & &F$*F! $FL#FK#'FO $(F!/FK%%''F1I"()FO#9F "3FO"3FO"DD Kr"c&eZdZdZdZddZdZdS)raW A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. Fetching a `PropertyMock` instance from an object calls the mock, with no args. Setting it calls the mock with the value being set. c tdi|S)Nr!)r)rWrYs r#r1zPropertyMock._get_child_mock s""6"""r"Nc|Sr<r!)rWr5obj_types r#rzPropertyMock.__get__ s tvv r"c||dSr<r!)rWr5rSs r#rzPropertyMock.__set__ s S r"r<)rrrr r1rrr!r"r#rr~ sP###r"rc4d|_t|D]} t||}n#t$rY wxYwt |t s:t |j|trh|j |urt|dS)aDisable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. The operation recursively seals the mock passed in, meaning that the mock itself, any mocks generated by accessing one of its attributes, and all assigned mocks without a name or spec will be sealed. TN) r r+r1rLr/r rrsrCrr)rDrrs r#rr sDD   d##AA    H !_--   a&**400* = =    % % GGG  s + 88ceZdZdZdZdZdS)rz8 Wraps an iterator in an asynchronous iterator. ct||_tt}tj|_||jd<dS)Nrr8)iteratorr rr2CO_ITERABLE_COROUTINErrr)rWrrs r#rHz_AsyncIterator.__init__ s6  #X666 $: $- j!!!r"c^K t|jS#t$rYnwxYwtr<)rrrrrs r#rz_AsyncIterator.__anext__ sA  && &    D   s  %%N)rrrr rHrr!r"r#rr s<... !!!!!r"rr)NFNNN)FFNN)Nr )__all__rrrWr2rr>builtinsrTrtypesrrr unittest.utilr functoolsrr threadingrrrr+r3r rrr6r:r.rArFrRrbr]rkrorurr{rrrwrrrrMISSINGrDELETEDrDrrrmrrrrr rMrHrrr=rrrrrVr[r_rrbrzrremultiplestopallr magic_methodsnumericsrdrPinplaceright _non_defaultsrrr_sync_async_magics _async_magicsrr_rrrrrrrrrrrr rrrrr rrrrnrrr rLrCr>rrErrrvr[rrrrr!r"r#rs5  &  ''''''2222222222######$$$$$$$$CCCCCyCCC I Hcc(mm H H H   @@@222    F # # # #   &&&   6."."."b>>>6))) ) ) ) ) )f ) ) )         9;;         &********(6      6   N <N <N <N <N       :         j        D   ,""""""""$@+@+@+@+@+T@+@+@+F((((((((V     6    dff$$$$v)v)v)v)v)Ev)v)v)r uuCGO*/OOOOOd8         DD     &&&OOOOd4$0!!!!!!!!!!r"__pycache__/_log.cpython-311.opt-2.pyc000064400000011052151030032340013324 0ustar00 !A?h ddlZddlZddlmZejdddgZGddejZGd d eZdS) N)_BaseTestCaseContext_LoggingWatcherrecordsoutputc"eZdZ dZdZdZdS)_CapturingHandlercntj|tgg|_dSN)loggingHandler__init__rwatcherselfs &/usr/lib64/python3.11/unittest/_log.pyrz_CapturingHandler.__init__s-  &&&&r2.. cdSr rs rflushz_CapturingHandler.flushs rc|jj|||}|jj|dSr )rrappendformatr)rrecordmsgs remitz_CapturingHandler.emitsK ##F+++kk&!! ""3'''''rN)__name__ __module__ __qualname__rrrrrrr r sF///   (((((rr c&eZdZ dZdZdZdZdS)_AssertLogsContextz"%(levelname)s:%(name)s:%(message)sctj||||_|r&tj|||_ntj|_d|_||_ dSr ) rr logger_namer _nameToLevelgetlevelINFOrno_logs)r test_caser#r&r(s rrz_AssertLogsContext.__init__!s\%dI666&  & -11%??DJJ DJ rc,t|jtjr|jx}|_n tj|jx}|_tj|j}t}| |j | ||j |_ |j dd|_|j |_|j|_|g|_ | |j d|_|jrdS|j S)NF) isinstancer#r Loggerlogger getLogger FormatterLOGGING_FORMATr setLevelr& setFormatterrhandlers old_handlers old_level propagate old_propagater()rr- formatterhandlers r __enter__z_AssertLogsContext.__enter__+s d& 7 7 G#'#3 3FT[[#*#4T5E#F#F FFT[%d&9:: #%%$$$Y''' "OAAA.#-") ###  <  Frc|j|j_|j|j_|j|j|dS|jrSt|j j dkr4| d |j j dSdSt|j j dkrL| d tj|j|jjdSdS)NFrzUnexpected logs found: {!r}z-no logs of level {} or higher triggered on {})r4r-r3r7r6r1r5r(lenrr _raiseFailurerrr getLevelNamer&name)rexc_type exc_valuetbs r__exit__z_AssertLogsContext.__exit__?s#0  $ 2  T^,,,  5 < Q4<'((1,,""188 +-,4<'((A--""CVG0<NOOQQQQQ.-rN)rrrr0rr:rCrrrr!r!sN@9N(QQQQQrr!) r collectionscaser namedtuplerr r r!rrrrGs&&&&&&)+():*3X)>@@(((((((($:Q:Q:Q:Q:Q-:Q:Q:Q:Q:Qr__pycache__/_log.cpython-311.pyc000064400000011313151030032340012364 0ustar00 !A?h ddlZddlZddlmZejdddgZGddejZGd d eZdS) N)_BaseTestCaseContext_LoggingWatcherrecordsoutputc$eZdZdZdZdZdZdS)_CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cntj|tgg|_dSN)loggingHandler__init__rwatcherselfs &/usr/lib64/python3.11/unittest/_log.pyrz_CapturingHandler.__init__s-  &&&&r2.. cdSr rs rflushz_CapturingHandler.flushs rc|jj|||}|jj|dSr )rrappendformatr)rrecordmsgs remitz_CapturingHandler.emitsK ##F+++kk&!! ""3'''''rN)__name__ __module__ __qualname____doc__rrrrrrr r sK///   (((((rr c(eZdZdZdZdZdZdZdS)_AssertLogsContextz6A context manager for assertLogs() and assertNoLogs() z"%(levelname)s:%(name)s:%(message)sctj||||_|r&tj|||_ntj|_d|_||_ dSr ) rr logger_namer _nameToLevelgetlevelINFOrno_logs)r test_caser$r'r)s rrz_AssertLogsContext.__init__!s\%dI666&  & -11%??DJJ DJ rc,t|jtjr|jx}|_n tj|jx}|_tj|j}t}| |j | ||j |_ |j dd|_|j |_|j|_|g|_ | |j d|_|jrdS|j S)NF) isinstancer$r Loggerlogger getLogger FormatterLOGGING_FORMATr setLevelr' setFormatterrhandlers old_handlers old_level propagate old_propagater))rr. formatterhandlers r __enter__z_AssertLogsContext.__enter__+s d& 7 7 G#'#3 3FT[[#*#4T5E#F#F FFT[%d&9:: #%%$$$Y''' "OAAA.#-") ###  <  Frc|j|j_|j|j_|j|j|dS|jrSt|j j dkr4| d |j j dSdSt|j j dkrL| d tj|j|jjdSdS)NFrzUnexpected logs found: {!r}z-no logs of level {} or higher triggered on {})r5r.r4r8r7r2r6r)lenrr _raiseFailurerrr getLevelNamer'name)rexc_type exc_valuetbs r__exit__z_AssertLogsContext.__exit__?s#0  $ 2  T^,,,  5 < Q4<'((1,,""188 +-,4<'((A--""CVG0<NOOQQQQQ.-rN)rrrr r1rr;rDrrrr"r"sQ@@9N(QQQQQrr") r collectionscaser namedtuplerr r r"rrrrHs&&&&&&)+():*3X)>@@(((((((($:Q:Q:Q:Q:Q-:Q:Q:Q:Q:Qr__pycache__/__init__.cpython-311.pyc000064400000010210151030032340013176 0ustar00 !A?h^dZgdZegddZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZmZdd lmZmZdd lmZmZdd lmZmZmZm Z dd lm!Z!m"Z"m#Z#eZ$d Z%dZ&dZ'dS)a Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework (used with permission). This module contains the core framework classes that form the basis of specific test cases and suites (TestCase, TestSuite etc.), and also a text-based utility class for running the tests and reporting the results (TextTestRunner). Simple usage: import unittest class IntegerArithmeticTestCase(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main() Further information is available in the bundled documentation, and from http://docs.python.org/library/unittest.html Copyright (c) 1999-2003 Steve Purcell Copyright (c) 2003-2010 Python Software Foundation This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. ) TestResultTestCaseIsolatedAsyncioTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandleraddModuleCleanupdoModuleCleanupsenterModuleContext)getTestCaseNames makeSuite findTestCasesT)r) rrrr r r rrrr) BaseTestSuiter)rr ) TestProgramr )rr)rrrr)rrrcvddl}|jt}|||S)N) start_dirpattern)os.pathpathdirname__file__discover)loadertestsr!osthis_dirs */usr/lib64/python3.11/unittest/__init__.py load_testsr,Os4NNNwx((H ??Xw? ? ??cJtdhzS)Nr)globalskeysr-r+__dir__r2Zs 99>>  89 99r-c\|dkr ddlmatStdtd|)Nrr)rzmodule z has no attribute ) async_caserAttributeError__name__)names r+ __getattr__r8]sE (((777777&& I8IIII J JJr-N)(__doc____all__extend __unittestresultrcaserrrr r r rrrrsuiterrr'rr r rrunnerrrsignalsrrrrrrr_TextTestResultr,r2r8r1r-r+rCs,,\ I I IAAABBB  '''''''''''''''''''''''',+++++++11111111########22222222PPPPPPPPPPPP>>>>>>>>>>! @@@:::KKKKKr-__pycache__/result.cpython-311.opt-2.pyc000064400000025656151030032340013741 0ustar00 !A?hF!f ddlZddlZddlZddlmZddlmZdZdZdZ dZ Gd d e Z dS) N)utilwrapsTc<tfd}|S)Ncft|ddr||g|Ri|S)NfailfastF)getattrstop)selfargskwmethods (/usr/lib64/python3.11/unittest/result.pyinnerzfailfast..inner sD 4U + +  IIKKKvd(T(((R(((r)rrs` rr r s3 6]]))))]) Lrz Stdout: %sz Stderr: %sceZdZ dZdZdZddZdZdZdZ dZ dZ d Z d Z ed Zed Zd ZdZdZdZedZdZdZdZdZdZdZdZdS) TestResultNFcd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ tj |_tj|_d|_dS)NFr)r failureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)r stream descriptions verbositys r__init__zTestResult.__init__&s|     "#%  "" #  # "rcdSNr s r printErrorszTestResult.printErrors7s--rc^ |xjdz c_d|_|dS)NrF)rr& _setupStdoutr tests r startTestzTestResult.startTest:s57  " rc|jr[|j0tj|_tj|_|jt _|jt _dSdSr,)rr ioStringIOrr!r"r$r.s rr1zTestResult._setupStdout@sS ; -"*&(kmm#&(kmm#,CJ,CJJJ  - -rcdSr,r-r.s r startTestRunzTestResult.startTestRunH   rc> |d|_dS)NF)_restoreStdoutr&r2s rstopTestzTestResult.stopTestNs%5 "rc|jrI|jrtj}tj}|r<|ds|dz }|jt|z|r<|ds|dz }|j t|z|jt_|j t_|j d|j |j d|jdSdS)N r)rr&r!r"getvaluer$endswithr#write STDOUT_LINEr% STDERR_LINErseektruncater )r outputerrors rr<zTestResult._restoreStdoutSs> ; +! E,,.. ++--F!??400'$)// f0DEEEE >>$//& )// e0CDDD.CJ.CJ   $ $Q ' ' '   ( ( * * *   $ $Q ' ' '   ( ( * * * * *% + +rcdSr,r-r.s r stopTestRunzTestResult.stopTestRunhr:rcv |j||||fd|_dSNT)rappend_exc_info_to_stringr&r r3errs raddErrorzTestResult.addErrornsB  D$":":3"E"EFGGG!rcv |j||||fd|_dSrL)rrMrNr&rOs r addFailurezTestResult.addFailurevs@ ' dD$<$4999 && ; 5Z((**FJ''))E 6t,,#dNF f 4555 5~~d++"TME e 3444wwx   rcd}d}|||fg}t|h}|r|\}}}|r3||r|j}|r||||jur|||r|}d}n||_|p|j|jfD]a} | ]t| |vrL| t| | | jf| t| b||S)NTF) idpop_is_relevant_tb_leveltb_nextrV_remove_unittest_tb_frames __traceback__ __cause__ __context__rMtypeadd) r rqrrrsr3retfirstexcsseencs rrkzTestResult._clean_tracebackssC%$%5 { (#'88:: WeR 33B77 Z 33B77 $/////333 )&(# /5+<=((A}Ad):): T!WWa$ABBBA) (* rcd|jjvS)N __unittest)tb_frame f_globals)r rss rryz TestResult._is_relevant_tb_levelsr{444rc d}|r5||s |}|j}|r|| | d|_dSdSr,)ryrz)r rsprevs rr{z%TestResult._remove_unittest_tb_framessq  33B77 DB 33B77   DLLL  rcdtj|j|jt |jt |jfzS)Nz!<%s run=%i errors=%i failures=%i>)rstrclass __class__rrcrrr.s r__repr__zTestResult.__repr__s@3 dn--t}c$+>N>NDM""$$ %r)NNN)__name__ __module__ __qualname___previousTestClass_testRunEntered_moduleSetUpFailedr*r/r4r1r9r=r<rJr rQrSrXrZr]r_rarer rNrkryr{rr-rrrrs O####"... ---   ### +++*   ""X"""X" &&&"   ,,,999 ..X.666!!!,8555    %%%%%rr) r6r!rlrjr functoolsrrr rCrDobjectrr-rrrs     \%\%\%\%\%\%\%\%\%\%r__pycache__/case.cpython-311.opt-1.pyc000064400000233121151030032340013321 0ustar00 !A?hBdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZmZmZmZdZeZdZGdd eZGd d eZGd d eZGddeZdZdZdZdZgZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(GddZ)Gdde)Z*Gd d!e*Z+Gd"d#e*Z,Gd$d%ej-Z.Gd&d'eZ/Gd(d)e/Z0Gd*d+e/Z1dS),zTest case implementationN)result)strclass safe_repr_count_diff_all_purpose_count_diff_hashable_common_shorten_reprTz@ Diff is %s characters long. Set self.maxDiff to None to see it.ceZdZdZdS)SkipTestz Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. N__name__ __module__ __qualname____doc__&/usr/lib64/python3.11/unittest/case.pyr r srr ceZdZdZdS) _ShouldStopz The test should stop. Nr rrrrr!rrceZdZdZdS)_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! Nr rrrrr&rrrc8eZdZddZejddZdS)_OutcomeNchd|_||_t|d|_d|_d|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessexpectedFailure)selfrs r__init__z_Outcome.__init__-s8!& (/ (E(E% #rFc#BK|j}d|_ dV|r(|jr!|j|j|dn#t$rt $r4}d|_t |j|t|Yd}~nzd}~wt$rYnktj }|j r||_ nAd|_|r"|j|j||nt|j||d}YnxYw|jo||_dS#|jo||_wxYw)NTF)r rr test_caseKeyboardInterruptr _addSkipstrrsysexc_inforr! _addError)r"r%subTest old_successer*s rtestPartExecutorz_Outcome.testPartExecutor4sql   8 EEE, M4< M &&y':ItLLL-!     5 5 5 DL T[)SVV 4 4 4 4 4 4 4 4    D |~~H% @'/$$$ @K**9+> 8TTTTdk9h???HHH  <7KDLLL4<7KDL 7 7 7 7s;A+DC;*B?D C;DA&C;9DDN)F)r rrr# contextlibcontextmanagerr/rrrrr,sL$$$$888888rrct|dd}||||dStjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reported)getattrwarningswarnRuntimeWarning addSuccess)rr%reasonr4s rr'r'Usffi..G 6""""" L$a ) ) ))$$$$$rc|C|Ct|d|jr|j||dS|j||dSdSdS)Nr) issubclassfailureException addFailureaddError)rtestr*s rr+r+^si h2 hqk4#8 9 9 , F dH - - - - - FOD( + + + + + 22rc|Sr0r)objs r_idrDes Jrct|} |j}|j}n/#t$r"t d|jd|jddwxYw||}|||ddd|S)N'.z6' object does not support the context manager protocol)type __enter____exit__AttributeError TypeErrorrr)cm addcleanupclsenterexitrs r_enter_contextrRis r((CO | OOODCNDDS-=DDDEEJN OOU2YYFJtRtT*** Ms  ,A c@t|||fdS)znSame as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule).N)_module_cleanupsappend)functionargskwargss raddModuleCleanuprYys%XtV455555rc,t|tS)z&Same as enterContext, but module-wide.)rRrY)rMs renterModuleContextr[~s ". / //rcg}trZt\}}} ||i|n,#t$r}||Yd}~nd}~wwxYwtZ|r|ddS)zWExecute all module cleanup functions. Normally called for you after tearDownModule.Nr)rTpop ExceptionrU) exceptionsrVrWrXexcs rdoModuleCleanupsrasJ #!1!5!5!7!7$ # Hd %f % % % % # # #   c " " " " " " " " # # ms1 AAAcdfd}ttjr}d||S|S)z& Unconditionally skip a test. ct|ts!tj|fd}|}d|_|_|S)Nc"tr0r )rWrXr;s r skip_wrapperz-skip..decorator..skip_wrappersv&&&rT) isinstancerH functoolswraps__unittest_skip____unittest_skip_why__) test_itemrfr;s r decoratorzskip..decorators^)T** % _Y ' ' ' ' ' '( ' '$I&* #*0 'r)rgtypes FunctionType)r;rmrls` rskiprqsS     &%,--$ y### rc2|rt|StS)z/ Skip a test if the condition is true. rqrD conditionr;s rskipIfrvsF|| Jrc2|st|StS)z3 Skip a test unless the condition is true. rsrts r skipUnlessrxs F|| Jrcd|_|S)NT)__unittest_expecting_failure__)rls rr!r!s/3I, rct|trtfd|DSt|tot |S)Nc38K|]}t|VdSr0) _is_subtype).0r.basetypes r z_is_subtype..s->>;q(++>>>>>>r)rgtupleallrHr=)expectedrs `rr}r}sW(E""?>>>>X>>>>>> h % % H*Xx*H*HHrceZdZdZdZdS)_BaseTestCaseContextc||_dSr0)r%)r"r%s rr#z_BaseTestCaseContext.__init__s "rcv|j|j|}|j|r0)r%_formatMessagemsgr>)r" standardMsgrs r _raiseFailurez"_BaseTestCaseContext._raiseFailures1n++DHkBBn--c222rN)r rrr#rrrrrrs2###33333rrceZdZddZdZdS)_AssertRaisesBaseContextNct||||_||_|t j|}||_d|_d|_dSr0) rr#rr%recompileexpected_regexobj_namer)r"rr%rs rr#z!_AssertRaisesBaseContext.__init__sU%%dI666  "  %Z77N, rc t|j|jst|d|j|sM|dd|_|r,ttt|d|d}S|^}} |j |_ n$#t$rt||_ YnwxYw|5||i|dddn #1swxYwYd}dS#d}wxYw)z If args is empty, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If args is not empty, call a callable passing positional and keyword arguments. z() arg 1 must be rNz1 is an invalid keyword argument for this function) r}r _base_typerL_base_type_strr]rnextiterr rrKr()r"namerWrX callable_objs rhandlez_AssertRaisesBaseContext.handlesz t}do>> =!%t':':!<=== !::eT22M#7;DLL7I7I7I7I%LMMMDD#' L4 2 , 5 ! 2 2 2 #L 1 1  2 . . d-f--- . . . . . . . . . . . . . . .DDD4DKKKKsZA?C C BC B74C 6B77C < C C CC CC C$r0)r rrr#rrrrrrs7rrcFeZdZdZeZdZdZdZe e j Z dS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typesc|Sr0rr"s rrIz_AssertRaisesContext.__enter__s rc| |jj}n$#t$rt|j}YnwxYw|jr/|d||jn=|d|ntj|t||jsdS| d|_ |j dS|j }| t|s;|d|jt|dS)Nz{} not raised by {}z {} not raisedFT"{}" does not match "{}")rr rKr(rrformat traceback clear_framesr=with_traceback exceptionrsearchpattern)r"exc_type exc_valuetbexc_namers rrJz_AssertRaisesContext.__exit__se   .=1! . . .t}-- .} E""#8#?#?@D $O$OPPPP""?#9#9(#C#CDDDD  "2 & & &(DM22 5"11$77   &4,$$S^^44 >   9@@#+S^^ = = > > >ts 22N) r rrr BaseExceptionrrrIrJ classmethodro GenericAlias__class_getitem__rrrrrsSMMJDN6$ E$677rrc&eZdZdZeZdZdZdZdS)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.z(a warning type or tuple of warning typesc6ttjD]}t |ddri|_t jd|_|j |_t j d|j |S)N__warningregistry__T)recordalways) listr)modulesvaluesr6rr7catch_warningswarnings_managerrI simplefilterr)r"vs rrIz_AssertWarnsContext.__enter__ sck((**++ + +Aq/66 +(*% ( 7t D D D-7799 h 666 rc|j||||dS |jj}n$#t$rt |j}YnwxYwd}|jD]s}|j}t||js||}|j (|j t |sR||_ |j |_ |j |_ dS|@|d|j jt ||jr0|d||jdS|d|dS)Nrz{} not triggered by {}z{} not triggered)rrJrr rKr(r7messagergrrwarningfilenamelinenorrrr)r"rrrrfirst_matchingmws rrJz_AssertWarnsContext.__exit__+s &&xB???   F *}-HH * * *4=))HHH *  A Aa// %!"#/'..s1vv660DLJDM(DK FF  %   9@@(0#n2E2E G G H H H = D   7>>x?C} N N O O O O O   188BB C C C C Cs /AAN) r rrrWarningrrrIrJrrrrrsGLLJ?N    D D D D DrrceZdZdZdS)_OrderedChainMapc#~Kt}|jD]$}|D]}||vr|||V %dSr0)setmapsadd)r"seenmappingks r__iter__z_OrderedChainMap.__iter__Os`uuy  G  D==HHQKKKGGG   rN)r rrrrrrrrNs#rrceZdZdZeZdZdZdZfdZ dOdZ dZ d Z d Z ed Zed Zd ZdZedZedZdZdZdZdZdZdZdZdZejefdZ dZ!dZ"dZ#dZ$dZ%dZ&dPd!Z'd"Z(ed#Z)d$Z*d%Z+d&Z,dPd'Z-dPd(Z.dPd)Z/d*Z0d+Z1d,Z2dQd-Z3dQd.Z4d/Z5dPd0Z6dPd1Z7dPd2Z8 dRd3Z9 dRd4Z:dQd5Z;d6ZdPd9Z?dPd:Z@dPd;ZAdPd<ZBdPd=ZCdPd>ZDdPd?ZEdPd@ZFdPdAZGdPdBZHdPdCZIdPdDZJdPdEZKdPdFZLdPdGZMdPdHZNdPdIZOdJZPdKZQdPdLZRdPdMZSdNZTeTe7xZUZVeTe8xZWZXeTe9xZYZZeTe:xZ[Z\eTe/xZ]Z^eTe1Z_eTe.Z`eTePZaeTeRZbeTeSZcxZdS)STestCaseaWA class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. TiicVd|_g|_tj|i|dS)NF)_classSetupFailed_class_cleanupssuper__init_subclass__)rOrWrX __class__s rrzTestCase.__init_subclass__s5 % !!42622222rrunTestc:||_d|_d|_ t||}|j|_n0#t $r#|dkrt d|jd|YnwxYwg|_d|_ i|_ | td| td| td| td | t d | t"d dS) zCreate an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. NzNo testrzno such test method in : assertDictEqualassertListEqualassertTupleEqualassertSetEqualassertMultiLineEqual)_testMethodName_outcome_testMethodDocr6rrK ValueErrorr _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictrrr frozensetr()r" methodName testMethods rr#zTestCase.__init__sA * ' 5 z22J#-"4D   4 4 4Y&&!j~~~zz"3444'& 4 %'!   '8999   '8999   (:;;;   &6777   ,<===   &<=====s4*A! A!c||j|<dS)a[Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. N)r)r"typeobjrVs rrzTestCase.addTypeEqualityFuncs.6!'***rc@|j|||fdS)aAdd a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).N)rrUr"rVrWrXs r addCleanupzTestCase.addCleanups' xv677777rc,t||jS)zEnters the supplied context manager. If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method. )rRr)r"rMs r enterContextzTestCase.enterContexts b$/222rc@|j|||fdS)zpSame as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).N)rrUrOrVrWrXs raddClassCleanupzTestCase.addClassCleanups( ""HdF#;<<<<t|jd|jS)NrGrrrrs ridz TestCase.ids#"4>2222D4H4HIIrclt|t|urtS|j|jkSr0)rHNotImplementedrr"others r__eq__zTestCase.__eq__s0 ::T%[[ ( (! !#u'<<rrs r__repr__zTestCase.__repr__s.(((($*>*>*>@ @rc+K|j |jjsdVdS|j}|t|}n|j|}t ||||_ |j|jd5dVdddn #1swxYwY|jjs|jj }||j rtn|jj rt||_dS#||_wxYw)aPReturn a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed. NT)r,) rrrrparams new_child_SubTestr/r rfailfastrr!)r"rr#parent params_maprs rr,zTestCase.subTestsI =  (N EEE F >)&11JJ0088J sJ77  #// t/LL                 =( "-%&/%%%. ""!"DMMMFDM " " " "s0&!C(B C(BC(B ?C(( C1c |j}|||dS#t$r.tjdt|j|YdSwxYw)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerKr7r8r9r:)r"rr*r*s r_addExpectedFailurezTestCase._addExpectedFailure&s~ /!'!:   tX . . . . .  $ $ $ M\( * * * F d # # # # # # $s4AAc |j}||dS#t$rXtjdt t d#t $r'|j|tjYYdSwxYwwxYw)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrKr7r8r9rr?r)r*)r"rr-s r_addUnexpectedSuccesszTestCase._addUnexpectedSuccess0s '#)#>  !  & & & & & 8 8 8 M_( * * * 8(d2% 8 8 8!!$ 7777777 8 8s&$A8A,A4/A83A44A8c.|dSr0)rrs r _callSetUpzTestCase._callSetUp?s rc^|"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case (r) stacklevel)r7r8DeprecationWarning)r"methods r_callTestMethodzTestCase._callTestMethodBs\ 688  M2(.2223ERS U U U U U U rc.|dSr0)rrs r _callTearDownzTestCase._callTearDownGs rc||i|dSr0rrs r _callCleanupzTestCase._callCleanupJs$!&!!!!!rNc|C|}t|dd}t|dd}| |nd}|j| t||j}t|jddst|ddrWt|jddpt|dd}t |||||j|| |SSt|ddpt|dd}t|} ||_| |5| dddn #1swxYwY|j r||_ | |5| |dddn #1swxYwYd|_ | |5|dddn #1swxYwY||j rK|r9|jr|||jn&||n|j||d|_d}d|_|j|| |SS#d|_d}d|_wxYw#|j|| |wwxYw)N startTestRun stopTestRunrjFrkrnrz)rr6 startTestrrr'stopTestrrr/r0r rr6r8 doCleanupsr!r+r.r:)r"rr<r=rskip_whyroutcomes rrunz TestCase.runMs >++--F"6>4@@L!&->>K' K2  t';<FFM $DeLL v&&G % ' --d33&&OO%%%&&&&&&&&&&&&&&&?-0AG- 11$7799,,Z88899999999999999905G- 11$77--**,,,---------------!!!?0(0"2? 44VW=TUUUU 66v>>>>))$///+/'!%  FOD ! ! !& '+/'!% $$$$ FOD ! ! !& 'sA5J(,1J(J:E JEJ"E#&J F+ J+F//J2F/3JG3' J3G77J:G7;A*J%J(J%%J((Kc |jp t}|jrb|j\}}}||5|j|g|Ri|dddn #1swxYwY|jb|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrr]r/r:r )r"rBrVrWrXs rr@zTestCase.doCleanupss--8::n =%)^%7%7%9%9 "HdF))$// = =!!(%> "HdF ?$)&)))) ? ? ?'..s|~~>>>>> ? ! ? ? ? ? ?s65A.-A.c|j|i|Sr0)rC)r"rWkwdss r__call__zTestCase.__call__stx&&&&rct||j}t|jddst|ddr6t|jddpt|dd}t||||||jr7|j\}}}|j |g|Ri||j5dSdS)z6Run the test without collecting errors in a TestResultrjFrkrnN) r6rrr r0r6r8rr]r:)r"rrArVrWrXs rdebugzTestCase.debugsT4#788 DN$7 ? ? % J 3U ; ; % 0GLLL":/FKK 8$$ $  Z((( n 9%)^%7%7%9%9 "HdF D h 8 8 8 8 8 8 8n 9 9 9 9 9rc t|)zSkip this test.re)r"r;s rskipTestzTestCase.skipTestsvrc,||)z)Fail immediately, with the given message.)r>)r"rs rfailz TestCase.fails##C(((rc|r;||dt|z}||dS)z#Check that the expression is false.z%s is not falseNrrr>r"exprrs r assertFalsezTestCase.assertFalsesI  -%%c+>.$??GGdGNNNNs+/cPt||}|d||S)aFail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) assertWarnsrr)r"expected_warningrWrXr_s rrazTestCase.assertWarnss*8&&6==~~mT6:::rc,ddlm}||||dS)aFail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. This method must be used as a context manager, and will yield a recording object with two attributes: `output` and `records`. At the end of the context manager, the `output` attribute will be a list of the matching formatted log messages and the `records` attribute will be a list of the corresponding LogRecord objects. Example:: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) r_AssertLogsContextFno_logs_logrfr"loggerlevelrfs r assertLogszTestCase.assertLogs"s0* -,,,,,!!$uEEEErc,ddlm}||||dS)z Fail unless no log messages of level *level* or higher are emitted on *logger_name* or its children. This method must be used as a context manager. rreTrgrirks r assertNoLogszTestCase.assertNoLogs:s0 -,,,,,!!$tDDDDrct|t|urP|jt|}|'t|trt ||}|S|jS)aGet a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. )rHrgetrgr(r6_baseAssertEqual)r"firstsecondasserters r_getAssertEqualityFunczTestCase._getAssertEqualityFuncCsl" ;;$v,, & &044T%[[AAH#h,,7&tX66H$$rc||ks>dt||z}|||}||dS)z:The default assertEqual implementation, not type specific.%s != %sN)r rr>)r"rtrurrs rrszTestCase._baseAssertEqual]sP$';E6'J'JJK%%c;77C'',, ,rcN|||}||||dS)z[Fail if the two objects are unequal as determined by the '==' operator. )rN)rw)r"rtrurassertion_funcs r assertEqualzTestCase.assertEqualds644UFCCuf#......rc||ksJ||t|dt|}||dS)zYFail if the two objects are equal as determined by the '!=' operator.  == NrR)r"rtrurs rassertNotEqualzTestCase.assertNotEqualkse%%c59I9I9I9I:CF:K:K:K,MNNC'',, ,rc ||krdS||tdt||z }|K||krdSt|dt|dt|dt|d}nO|d}t||dkrdSt|dt|d|d t|d}|||}||) a'Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). If the two objects compare equal then they will automatically compare almost equal. N specify delta or places not bothz !=  within  delta ( difference)rz places (rLabsrroundrr>r"rtruplacesrdeltadiffrs rassertAlmostEqualzTestCase.assertAlmostEqualts, F?? F  !3>?? ?56>""  u}}%    &!!!!%    $ !KK ~T6""a''%    &!!!!$ !K !!#{33##C(((rc ||tdt||z }|Q||ks||krdSt|dt|dt|dt|d}nE|d}||kst||dkrdSt|dt|d|d }|||}||) aFail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). Objects that are equal automatically fail. Nrr~rrrrrz placesrrs rassertNotAlmostEqualzTestCase.assertNotAlmostEquals  !3>?? ?56>""  VOO%    &!!!!%    $ !KK ~VOOtV)<)<)A)A9B59I9I9I9I9B69J9J9J9J9?AK!!#{33##C(((rc |x|j}t||s(|d|dt|t||s(|d|dt|nd}d} t |}n#t t f$rd|z}YnwxYw|- t |}n#t t f$rd|z}YnwxYw|||krdSd|ft||zz}tt||D]} || } n(#t tt f$r|d | |fzz }YnwxYw || } n(#t tt f$r|d | |fzz }YnQwxYw| | kr|d | ft| | zzz }n+||kr$|"t|t|krdS||krS|d |||z fzz } |d |t||fzz }n#t tt f$r |d||fzz }Yn]wxYw||krS|d|||z fzz } |d |t||fzz }n'#t tt f$r |d||fzz }YnwxYw|} dd tjt!j|t!j|z} || | } ||| }||dS)aAAn equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. NzFirst sequence is not a rzSecond sequence is not a sequencez(First %s has no length. Non-sequence?z)Second %s has no length. Non-sequence?z%ss differ: %s != %s z( Unable to index element %d of first %s z) Unable to index element %d of second %s z# First differing element %d: %s %s z+ First %s contains %d additional elements. zFirst extra element %d: %s z'Unable to index element %d of first %s z, Second %s contains %d additional elements. z(Unable to index element %d of second %s r )r rgr>rlenrLNotImplementedError capitalizer rangemin IndexErrorrHjoindifflibndiffpprintpformat splitlines_truncateMessagerrP)r"seq1seq2rseq_type seq_type_name differinglen1len2iitem1item2rdiffMsgs rassertSequenceEqualzTestCase.assertSequenceEquals  $-MdH-- L++++8==)D///-KLLLdH-- L++++8==)D///-KLLL L'M  #t99DD./ # # #B!#III #   '4yy23 ' ' 'G%'  '  t||0"--//1(t4456I3tT??++   GEE!:/BC"N"#]!3#45IEE  GEE!:/BC"O"#]!3#45IEE E>>"K#$$)=eU)K)K"K#MNIE" DLLX%5JJ$t**,,Fd{{+.;TD[-IJK K"A#'4:)>)>"?#@AII!:/BCKKK#259=4I#JKIIIK+.;TD[-IJK L"A#'4:)>)>"?#@AII!:/BCLLL#36:M5J#KLIIIL  M&...99;; ...99;; = =>>>++KAA !!#{33 #slBB)(B)/B??CC/D88!EE!E**!FF3H!H54H5 I**!J Jcx|j}|t||kr||zS|tt|zzSr0)maxDiffr DIFF_OMITTED)r"rrmax_diffs rrzTestCase._truncateMessage's?<  s4yyH44T> !,T233rcB||||tdS)aA list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. rN)rr)r"list1list2rs rrzTestCase.assertListEqual-s'   sT BBBBBrcB||||tdS)aA tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. rN)rr)r"tuple1tuple2rs rrzTestCase.assertTupleEqual9s'   u EEEEErcJ ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw ||}nY#t$r"}|d|zYd}~n2d}~wt$r"}|d|zYd}~nd}~wwxYw|s|sdSg}|r<|d|D]$}|t |%|r<|d|D]$}|t |%d|} |||| dS)aA set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). z/invalid type when attempting set difference: %sNz2first argument does not support set difference: %sz3second argument does not support set difference: %sz*Items in the first set but not the second:z*Items in the second set but not the first:r ) differencerLrPrKrUreprrr) r"set1set2r difference1r. difference2linesitemrs rrzTestCase.assertSetEqualDs& P//$//KK M M M IIG!K L L L L L L L L P P P IIJQN O O O O O O O O P Q//$//KK M M M IIG!K L L L L L L L L Q Q Q IIKaO P P P P P P P P Q {  F  ) LLE F F F# ) ) T$ZZ((((  ) LLE F F F# ) ) T$ZZ((((ii&&  $%%c;7788888sB A.? A. A))A.2B CB// C<CCc||vrLt|dt|}||||dSdS)zDJust like self.assertTrue(a in b), but with a nicer default message. not found in NrrPrr"member containerrrs rassertInzTestCase.assertInosd  " "2;F2C2C2C2C2;I2F2F2FHK IId))#{;; < < < < < # "rc||vrLt|dt|}||||dSdS)zHJust like self.assertTrue(a not in b), but with a nicer default message.z unexpectedly found in Nrrs r assertNotInzTestCase.assertNotInvsd Y  ;DV;L;L;L;L8A)8L8L8LNK IId))#{;; < < < < <  rc||urLt|dt|}||||dSdS)zDJust like self.assertTrue(a is b), but with a nicer default message.z is not Nrr"expr1expr2rrs rassertIszTestCase.assertIs}sc   ,5e,<,<,<,<-6u-=-=-=?K IId))#{;; < < < < <  rc||ur=dt|}||||dSdS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: Nrrs r assertIsNotzTestCase.assertIsNotsO E>>>:CE:J:J:JLK IId))#{;; < < < < < >rc ||td||td||krdt||z}ddt jt j|t j|z}| ||}| | ||dSdS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryryr ) assertIsInstancerr rrrrrrrrPr)r"d1d2rrrs rrzTestCase.assertDictEquals b$(LMMM b$(MNNN 88$';B'C'CCK499W]!>"--88::!>"--88::&<&<===D// TBBK IId))#{;; < < < < < 8rc Htjdtg}g}|D]u\}}||vr|||||krJ|t |dt |dt ||v|s|sdSd}|r"ddd|Dz}|r"|r|d z }|d d|zz }||||dS) z2Checks whether dictionary is a superset of subset.z&assertDictContainsSubset is deprecatedz , expected: z , actual: Nrnz Missing: %s,c34K|]}t|VdSr0)r)r~rs rrz4TestCase.assertDictContainsSubset..s83=3=A9Q<<3=3=3=3=3=3=rz; zMismatched values: %s) r7r8r4itemsrUrrrPr) r"subset dictionaryrmissing mismatchedkeyvaluers rassertDictContainsSubsetz!TestCase.assertDictContainsSubsetsz >( * * *  ,,.. @ @JC*$$s####*S/))!!#,S>>>>9U3C3C3C3C#,Z_#=#=#=#?@@@ :  F  ='#((3=3=4;3=3=3=+=+==K  J $t# 2SXXj5I5II IK $%%c;7788888rct|t|}} tj|}tj|}||krdSt||}n #t$rt ||}YnwxYw|rfd}d|D}d|} ||| }|||}| |dSdS)a[Asserts that two iterables have the same elements, the same number of times, without regard to order. self.assertEqual(Counter(list(first)), Counter(list(second))) Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. NzElement counts were not equal: cg|]}d|zS)z First has %d, Second has %d: %rr)r~rs r z-TestCase.assertCountEqual..sWWW47$>WWWrr ) r collectionsCounterrrLrrrrrP) r"rtrur first_seq second_seq differencesrrrs rassertCountEqualzTestCase.assertCountEquals!%U T&\\:  F' 22E (44F .y*EEKK  I I I1)ZHHKKK I  =A>c||td||td||kr*t||jkst||jkr|||||d}|d}t|dkr%|d|kr |dzg}|dzg}dt||z}dd tj ||z}| ||}| | ||d Sd S) z-Assert that two multi-line strings are equal.zFirst argument is not a stringzSecond argument is not a stringT)keependsrz r ryrnN)rr(r_diffThresholdrsrr r rrrrrPr)r"rtrur firstlines secondlinesrrs rrzTestCase.assertMultiLineEqualsa eS*JKKK fc+LMMM F??E T000F d111%%eVS999))4)88J ++T+::K:!## F(;(;u(D(D#dl^ %}o $';E6'J'JJK"'''- K"H"HIIID// TBBK IId))#{;; < < < < < ?rc||ksLt|dt|}||||dSdS)zCJust like self.assertTrue(a < b), but with a nicer default message.z not less than Nrr"abrrs r assertLesszTestCase.assertLesssV1uu3 b), but with a nicer default message.z not greater than Nrrs r assertGreaterzTestCase.assertGreatersV1uu6?llllIaLLLQK IId))#{;; < < < < <urc||ksLt|dt|}||||dSdS)zDJust like self.assertTrue(a >= b), but with a nicer default message.z not greater than or equal to Nrrs rassertGreaterEqualzTestCase.assertGreaterEquals[AvvBKA,,,,PYZ[P\P\P\]K IId))#{;; < < < < <vrc|=t|d}||||dSdS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz is not Nonerr"rCrrs r assertIsNonezTestCase.assertIsNonesH ?.7nnnn>K IId))#{;; < < < < < ?rcd|-d}||||dSdS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rPrrs rassertIsNotNonezTestCase.assertIsNotNones; ;-K IId))#{;; < < < < < ;rct||s?t|d|}||||dSdS)zTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.z is not an instance of NrgrrPrr"rCrOrrs rrzTestCase.assertIsInstance s^#s## =;DS>>>>33OK IId))#{;; < < < < < = =rct||r?t|d|}||||dSdS)z,Included for symmetry with assertIsInstance.z is an instance of Nrrs rassertNotIsInstancezTestCase.assertNotIsInstances\ c3   =7@~~~~ssKK IId))#{;; < < < < < = =rcRt|||}|d||S)aAsserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. assertRaisesRegexr])r"r^rrWrXr_s rrzTestCase.assertRaisesRegexs-''94PP~~14@@@rcRt|||}|d||S)aAsserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. Args: expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. assertWarnsRegexrb)r"rcrrWrXr_s rrzTestCase.assertWarnsRegex(s- &&6nMM~~0$???rct|ttfrtj|}||s8d|jd|}|||}||dS)z=Fail the test unless the text matches the regular expression.zRegex didn't match: rN) rgr(bytesrrrrrr>)r"textrrrs r assertRegexzTestCase.assertRegex;s nsEl 3 3 8Z77N$$T** - -&&&.K%%c;77C'',, ,  - -rcbt|ttfrtj|}||}|rgd|||d|jd|}| ||}| |dS)z9Fail the test if the text matches the regular expression.zRegex matched: z matches z in N) rgr(rrrrstartendrrr>)r"runexpected_regexrmatchrs rassertNotRegexzTestCase.assertNotRegexGs &e 5 5 <!z*:;;  ''--  - -U[[]]UYY[[0111 (((K %%c;77C'',, , - -rcfd}|S)Ncztjdjtd|i|S)NzPlease use {0} instead.r5)r7r8rr r4)rWrX original_funcs rdeprecated_funcz,TestCase._deprecate..deprecated_funcWsG M)001GHH"A ' ' '!=$1&11 1rr)rrs` r _deprecatezTestCase._deprecateVs$ 2 2 2 2 2 r)rr0)NNNNN)er rrrAssertionErrorr>rYrrrr#rrrrrrrrrrrrrrrrrr!r1r2_subtest_msg_sentinelr,r+r.r0r6r8r:rCr@rGrJrLrNrPrUrWrr\rarnrprwrsr|rrrrrrrrrrrrrrrrrrrrrrrrrrrrrfailUnlessEqual assertEquals failIfEqualassertNotEqualsfailUnlessAlmostEqualassertAlmostEqualsfailIfAlmostEqualassertNotAlmostEquals failUnlessassert_failUnlessRaisesfailIfassertRaisesRegexpassertRegexpMatchesassertNotRegexpMatches __classcell__rs@rrrXs@&KGN33333 >>>>@ 6 6 6888333==[= 77[7      VV[Vaa[a###CCCJJJ=== 888eee@@@/####</// ' ' 'UUU """====~    ? ?[ ?'''999"))))---- ---- III*B;;;>FFFF0EEEE%%%4----////----AE $+)+)+)+)ZDH#'!)!)!)!)FaaaaF444 C C C C F F F F)9)9)9)9V================ = = = =9999:@====(==== ==== ==== ==== ==== ==== ======== AAA @@@& - - - - - - - -&0Z %<%<$>>K/1;)r"r%rr#rs rr#z_SubTest.__init__s?  " ) :rc td)Nzsubtests cannot be run directly)rrs rrz_SubTest.runTests!"CDDDrctg}|jtur-|d|j|jr^dd|jD}|d|d|pdS)Nz[{}]z, c3HK|]\}}d||VdS)z{}={!r}N)r)r~rrs rrz+_SubTest._subDescription..sJ$3$3Q  A&&$3$3$3$3$3$3rz({}) z ())r<rrUrr#rr)r"parts params_descs r_subDescriptionz_SubTest._subDescriptions = 5 5 5 LLt}55 6 6 6 ; 5))$3$3"k//11$3$3$333K LL{33 4 4 4xx/-/rcd|j|SNz{} {})rr%rrCrs rrz _SubTest.ids0~~dn//1143G3G3I3IJJJrc4|jS)zlReturns a one-line description of the subtest, or None if no description has been provided. )r%rrs rrz_SubTest.shortDescriptions~..000rc\d|j|SrE)rr%rCrs rrz_SubTest.__str__s$~~dnd.B.B.D.DEEEr) r rrr#rrCrrrr&r's@rr%r%s;;;;;EEE 0 0 0KKK111 FFFFFFFrr%)2rr)rhrrrr7rr1rrornrutilrrrrr __unittestobjectrrr^r rrrr'r+rDrRrTrYr[rarqrvrxr!r}rrrrChainMaprrr)r%rrrrLs   ?????????????? 7 y)  &8&8&8&8&8v&8&8&8R%%%,,,   666 000    (III 33333333'''''3'''T$8$8$8$8$83$8$8$8N1D1D1D1D1D21D1D1Dh{+P8P8P8P8P8vP8P8P8h 7:7:7:7:7:x7:7:7:t!F!F!F!F!Fx!F!F!F!F!Fr__pycache__/loader.cpython-311.opt-2.pyc000064400000057660151030032340013671 0ustar00 !A?hXj ddlZddlZddlZddlZddlZddlZddlZddlmZmZddl m Z m Z m Z dZ ejdejZGdde jZd Zd Zd Zd Zd ZGddeZeZddZe jdfdZde je jfdZde je jfdZ dS)N)fnmatch fnmatchcase)casesuiteutilTz[_a-z]\w*\.py$c,eZdZdZfdZfdZxZS) _FailedTestNcf||_tt||dSN) _exceptionsuperr __init__)self method_name exception __class__s (/usr/lib64/python3.11/unittest/loader.pyrz_FailedTest.__init__s.# k4  ))+66666cz|jkr(tt|Sfd}|S)Ncjr )r rsr testFailurez,_FailedTest.__getattr__..testFailure!s / !r)_testMethodNamerr __getattr__)rnamerrs` rrz_FailedTest.__getattr__sO 4' ' 'd++77== = " " " " "r)__name__ __module__ __qualname__rrr __classcell__rs@rr r sVO77777rr crd|dtj}t|t|||S)NzFailed to import test module:  ) traceback format_exc_make_failed_test ImportError)r suiteClassmessages r_make_failed_import_testr*&s< i"$$$&G T;w#7#7W M MMrcRdtj}t||||S)NzFailed to call load_tests: )r$r%r&)rrr(r)s r_make_failed_load_testsr,+s32;2F2H2H2HJG  iW . ..rc>t||}||f|fSr )r ) methodnamerr(r)tests rr&r&0s( z9 - -D :tg   ''rctjt|d}||i}tdtjf|}|||fS)NcdSr rs r testSkippedz'_make_skipped_test..testSkipped5s r ModuleSkipped)rskipstrtypeTestCase)r.rr(r3attrs TestClasss r_make_skipped_testr;4si Ys9~~    %E_t}&6>>I :yy,,. / //rc|dr |ddStj|dS)Nz $py.classir)lowerendswithospathsplitext)r@s r_jython_aware_splitextrB<sI zz||[))CRCy 7  D ! !! $$rceZdZ dZeejZdZe j Z dZ fdZ dZdddZddZddZd Zdd Zd Zd ZdZdZdZdZxZS) TestLoaderr/Nctt|g|_t |_dSr )rrDrerrorsset_loading_packages)rrs rrzTestLoader.__init__Ms: j$((*** "%rc. t|tjrtd|tjtjfvrg}n*||}|st|drdg}| t||}|S)NzYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?runTest) issubclassr TestSuite TypeErrorrr8FunctionTestCasegetTestCaseNameshasattrr(map)r testCaseClass testCaseNames loaded_suites rloadTestsFromTestCasez TestLoader.loadTestsFromTestCaseTsI mU_ 5 5 )()) ) T]D,AB B BMM 11-@@M  ,W]I%F%F ,!* s=-'H'HII rpatternc t|dksd|vr0tjdt|ddt|dkr4t|dz}t d|t|dkr7t|d}t d|g}t|D]}t||}t|tr\t|tjrB|tjtjfvr(|||t|dd} ||}| _ | |||S#t&$rD} t)|j| |j\} } |j| | cYd} ~ Sd} ~ wwxYw|S)Nruse_load_testsz(use_load_tests is deprecated and ignoredrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpoprMformatsorteddirgetattr isinstancer7rKrr8rNappendrUr( Exceptionr,rrF) rmodulerWargskws complainttestsrobjrZe error_case error_messages rloadTestsFromModulezTestLoader.loadTestsFromModulefsL t99q==,33 MD, . . . GG$d + + + t99q==D A Iahhirsstt t s88q== s AI[bbclmmnn nKK > >D&$''C3%% >sDM22 > t/DEEE T77<<===V\488 &&  ! "!z$w777 " " ",COQ-9-9) M ""=111!!!!!!!  "  s F%% G3/9G.(G3.G3c x |d}d\}}||dd}|r d|}t|}n^#t$rO|}t ||j\}}|s|j||cYSYnwxYw||dd}|} |D]} | t| | } } #t$r} t| dd%|#|j||cYd} ~ cSt| | |jdtj \}}|j||cYd} ~ cSd} ~ wwxYwt| tjr|| St| t$rIt'| t(jr/| t(jt(jfvr|| St| tjrt| t$rlt'| t(jrR|d}| |} tt| |tjs|| gSnt| t2jr| St7| rl| }t|t2jr|St|t(jr||gSt9d| d|d t9d | z) N.NNr__path__zFailed to access attribute: zcalling z returned z , not a testz$don't know how to make test from: %s)splitjoin __import__r'r_r*r(rFrercAttributeErrorr&r$r%rdtypes ModuleTyperpr7rKrr8rNrU FunctionTyperrLcallablerM)rrrgpartsrnro parts_copy module_namenext_attributerlpartparentrminstr/s rloadTestsFromNamezTestLoader.loadTestsFromNames  3$.! M >qqqJ * *"%((:"6"6K' 44F"***%/^^%5%5N0H&1919-J %* **=999))))** *  *!""IE & &D &!73#5#5! & & &CT22>". K&&}555%%%%%%%%%1Ba%022251616-J K&&}555%%%%%%%%%% &( c5+ , , ++C00 0 sD ! ! 3 .. DM4+@AAA--c22 2e011 && // 9D6$<z1TestLoader.loadTestsFromNames..s)III4$((v66IIIr)r()rnamesrgsuitess` ` rloadTestsFromNameszTestLoader.loadTestsFromNamess: JIIII5IIIv&&&rc fd}tt|t}jr-|t jj|S)Nc|jsdSt|}t|sdSdjj|fzjduptfdjDS)NFz%s.%s.%sc38K|]}t|VdSr )r)rrWfullNames r zKTestLoader.getTestCaseNames..shouldIncludeMethod..s-XXwK'22XXXXXXr) startswithtestMethodPrefixrcr}rrtestNamePatternsany)attrnametestFuncrrrRs @rshouldIncludeMethodz8TestLoader.getTestCaseNames..shouldIncludeMethods&&t'<== u}h77HH%% u"(-*Dh&H(D0YXXXX$BWXXXXX Yr)key)listfilterrbsortTestMethodsUsingsort functools cmp_to_key)rrRr testFnNamess`` rrOzTestLoader.getTestCaseNamess  Y Y Y Y Y Y6"5s=7I7IJJKK  $ R   !5d6O!P!P  Q Q Qrtest*.pyc d}||j|j}n|d}|}tj|}|tjvr tjd|||_d}tjtj|retj|}||kr>tjtj|d }n t|tj |}| dd} tjtj |j }nD#t$r7|jtjvrt#ddt#d|dwxYw|r9|||_tj|n#t($rd}YnwxYw|rt)d|zt+|||}||S) NFTr __init__.pyrrz2Can not use builtin modules as dotted module namesz don't know how to discover from z%Start directory is not importable: %r)_top_level_dirr?r@abspathsysinsertisdirisfilerwrxmodulesrvdirname__file__ryrbuiltin_module_namesrM _get_directory_containing_moduleremover'r _find_testsr() r start_dirrW top_level_dirset_implicit_topis_not_importable the_moduletop_partrks rdiscoverzTestLoader.discoversj 6!  T%8%D /MM  "# %M 66 (( HOOA} - - -+! 7==33 4 4 3 22IM))(*rw||I}7]7](^(^$^! 39%%%![3 $??3//2 ( ")<>>!@!@II%(((!*c.FFF')ABBGKL(MzMM#'( ($3*.*O*OPX*Y*YD'HOOM222) ) ) )$(!!! ),  SE QRR RT%%i99::u%%%s HAFAG H! H!ctj|}tj|j}tj|dr> > 7??9-- -rc ||jkrdSttj|}tj||j}|tjjd}|SNrr)rrBr?r@normpathrelpathreplacesep)rr@_relpathrs r_get_name_from_pathzTestLoader._get_name_from_path]sj 4& & &3%bg&6&6t&<&<==7??4)<== S11 rcDt|tj|Sr )rxrr)rrs r_get_module_from_namez TestLoader._get_module_from_nameis4{4  rc"t||Sr )r)rr@rrWs r _match_pathzTestLoader._match_pathmstW%%%rc#tK ||}|dkr,||jvr#|||\}}||V|sdStt j|}|D]}tj||}|||\}}||V|r||}|j| | ||Ed{V|j |#|j |wxYwdSr) rrH_find_test_pathrar?listdirr@rwaddrdiscard) rrrWrrkshould_recursepathsr@rs rrzTestLoader._find_testsqsw='' 22 3;;4t'===%)$8$8G$L$L !E>  ! rz),,-- 9 9D Y55I$($8$8G$L$L !E>   9// ::&**40009#// 7CCCCCCCCC*2248888D*2248888 9 9 9s !DD4c tj|}tj|rt|sdS||||sdS||} ||}tj t|d|}ttj |}ttj |}| | krtj|} ttj|} tj|} d} t| | | | fz|||dfS#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwtj|rztjtj|dsdSd}d}||} ||}t|dd}|j| |||}||df|j|S|df|j|S#|j|wxYw#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwdS) N)NFrzW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?rVFrrZT)r?r@rrVALID_MODULE_NAMEmatchrrrrrcrBrealpathr=rr'rprSkipTestr;r(r*rFrerrwrHrr)rrrWrrrgmod_filerfullpath_noext module_dirmod_name expected_dirmsgrmrnrorZrkpackages rrzTestLoader._find_test_paths 7##I.. 7>>) $ $? $**844 #"{##HiAA #"{++I66D P33D997??FJ ::<<1G$$X..00!7G$$Y//"1"1>>##~';';'='===!#!:!:J5((33 5 5H#%7??9#=#=LDC%x\BBDDD///HH%OO/= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5(((($W]]9 % % 7>>"',,y-"H"HII #"{JE++I66D 944T::%WlDAA &**40009 44Wg4NNE!-$e|*2248888!$;*2248888D*2248888%= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5((((;sN G++I:HI;INM&M&&NO.N1+O.1;O.r )rN)rrrr staticmethodr three_way_cmprrrrLr(rrrUrprrrOrrrrrrrr r!s@rrDrDBsS'<(:;;JN'''''$:>*****XPJPJPJPJd''''&Q&Q&Q&Q&f . . .   !!!&&&999@HHHHHHHrrDc^t}||_||_||_|r||_|Sr )rDrrrr()prefix sortUsingr(rloaders r _makeLoaderrs8 \\F"+F$F.F'& Mrcddl}|jdtdt||||S)Nrzunittest.getTestCaseNames() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.getTestCaseNames() instead. stacklevel)r)r\r]r^rrO)rRrrrr\s rrOrOsXOOOHM Eq vy;K L L L ] ]^k l llrr/cddl}|jdtdt||||S)Nrzunittest.makeSuite() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromTestCase() instead.rr)r\r]r^rrU)rRrrr(r\s r makeSuitersZOOOHM Jq vy* 5 5 K K  rcddl}|jdtdt||||S)Nrzunittest.findTestCases() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromModule() instead.rr)r\r]r^rrp)rgrrr(r\s r findTestCasesrsZOOOHM Hq vy* 5 5 I I  rrs)!r?rerr$rzrr\rrrrr __unittestcompile IGNORECASErr8r r*r,r&r;rBobjectrDdefaultTestLoaderrrrOrLrrr2rrrs  ((((((((  BJ0"-@@     $-   NNN ... (((000%%% WWWWWWWWt JLL 7;6H[_mmmm%+d6H    "(43E"_      r__pycache__/util.cpython-311.opt-1.pyc000064400000020023151030032340013356 0ustar00 !A?h_dZddlmZmZddlmZdZdZdZdZ dZ dZ ee eze zeze zz Z dZ d Zdd Zd Zd ZdZdZeddZdZdZdS)zVarious utility functions.) namedtupleCounter) commonprefixTP ct||z |z }|tkr(d|d|||t||z dfz}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlen suffixlenskips &/usr/lib64/python3.11/unittest/util.py_shortenrsW q66I  )D  *9* tQs1vv 7I7J7J5KL L Hcttt|}ttt|}|t kr|St |t t |z tztzz }|tkr2tt|tfd|DSttttfd|DS)Nc32K|]}|dzVdSN.0r prefixr s r z'_common_shorten_repr..'s0::Va m+::::::rc3dK|]*}t|dttzV+dSr)r _MIN_DIFF_LEN _MIN_END_LENrs rrz'_common_shorten_repr..*sP  (1YZZ=-NNN      r) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENr)argsmaxlen common_lenrr s @@r_common_shorten_reprr(s Y%% & &D S$ F  $  FF I9$~58HHJJO##&.*==:::::T:::::: fno > >F            rFc t|}n*#t$rt|}YnwxYw|rt |t kr|S|dt dzS)Nz [truncated]...)repr Exceptionobject__repr__r r")objshortresults rr r -sv&c &&&%%& CKK+-- ,;, "3 33s $99c$|jd|jS)N.) __module__ __qualname__)clss rstrclassr66snnnc&6&6 77rcdx}}g}g} ||}||}||kr8|||dz }|||kr|dz }|||kn||kr8|||dz }|||kr|dz }|||knm|dz } |||kr|dz }|||k|dz }|||kr|dz }|||kn'#|dz }|||kr|dz }|||kwxYwnJ#t$r=|||d|||dYnwxYwG||fS)arFinds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the second contains those elements in the "actual" list but not in the "expected" list. Duplicate elements in either input list are ignored. rTN)append IndexErrorextend)expectedactualijmissing unexpectedeas rsorted_list_differencerD9s IAGJ  Aq A1uuq!!!QqkQ&&FAqkQ&&Q!!!$$$QQi1nnFAQi1nnQ"1+**Q#1+**FA )q..Q!)q..FA )q..Q!)q......    NN8ABB< ( ( (   fQRRj ) ) ) E /6 J s+BDC:#D$DDAE  E cg}|rR|} ||n%#t$r||YnwxYw|R||fS)zSame behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance.)popremove ValueErrorr9)r<r=r@items runorderable_list_differencerJbs G !||~~ ! MM$     ! ! ! NN4  ! ! F?s0AAc||k||kz S)z.Return -1 if x < y, 0 if x == y and 1 if x > yr)xys r three_way_cmprNss Ea!e rMismatchzactual expected valuect|t|}}t|t|}}t}g}t|D]\}} | |ur dx} } t ||D]} || | kr | dz } ||| <t|D]\} } | | kr | dz } ||| <| | kr&t | | | }||t|D][\}} | |ur d} t ||D]} || | kr | dz } ||| <t d| | }||\|S)HReturns list of (cnt_act, cnt_exp, elem) triples where the counts differrr8)listr r, enumeraterange _Mismatchr9)r=r<r tmnNULLr0r>elemcnt_scnt_tr? other_elemdiffs r_count_diff_all_purposer_ys <<hqA q663q66qA 88D FQ<<  4 4<< q!  Att|| !&q\\  MAzT!! ! E>>UE400D MM$   Q<<  4 4<< q!  Att|| !E4(( d Mrct|t|}}g}|D]G\}}||d}||kr&t|||}||H|D]/\}}||vr&td||}||0|S)rQr)ritemsgetrUr9) r=r<r rVr0rZr[r\r^s r_count_diff_hashablercs 6??GH--qA Fwwyy  edA E>>UE400D MM$   wwyy  e q==Qt,,D MM$    MrN)F)__doc__ collectionsrros.pathr __unittestr"r r#rr$rrr(r r6rDrJrNrUr_rcrrrrhs( ++++++++    !11OC !#/01       *4444888&&&R" Jz#: ; ; !!!Fr__pycache__/__init__.cpython-311.opt-1.pyc000064400000010210151030032340014135 0ustar00 !A?h^dZgdZegddZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZmZdd lmZmZdd lmZmZdd lmZmZmZm Z dd lm!Z!m"Z"m#Z#eZ$d Z%dZ&dZ'dS)a Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework (used with permission). This module contains the core framework classes that form the basis of specific test cases and suites (TestCase, TestSuite etc.), and also a text-based utility class for running the tests and reporting the results (TextTestRunner). Simple usage: import unittest class IntegerArithmeticTestCase(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main() Further information is available in the bundled documentation, and from http://docs.python.org/library/unittest.html Copyright (c) 1999-2003 Steve Purcell Copyright (c) 2003-2010 Python Software Foundation This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. ) TestResultTestCaseIsolatedAsyncioTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandleraddModuleCleanupdoModuleCleanupsenterModuleContext)getTestCaseNames makeSuite findTestCasesT)r) rrrr r r rrrr) BaseTestSuiter)rr ) TestProgramr )rr)rrrr)rrrcvddl}|jt}|||S)N) start_dirpattern)os.pathpathdirname__file__discover)loadertestsr!osthis_dirs */usr/lib64/python3.11/unittest/__init__.py load_testsr,Os4NNNwx((H ??Xw? ? ??cJtdhzS)Nr)globalskeysr-r+__dir__r2Zs 99>>  89 99r-c\|dkr ddlmatStdtd|)Nrr)rzmodule z has no attribute ) async_caserAttributeError__name__)names r+ __getattr__r8]sE (((777777&& I8IIII J JJr-N)(__doc____all__extend __unittestresultrcaserrrr r r rrrrsuiterrr'rr r rrunnerrrsignalsrrrrrrr_TextTestResultr,r2r8r1r-r+rCs,,\ I I IAAABBB  '''''''''''''''''''''''',+++++++11111111########22222222PPPPPPPPPPPP>>>>>>>>>>! @@@:::KKKKKr-__pycache__/async_case.cpython-311.opt-1.pyc000064400000014722151030032340014522 0ustar00 !A?hYNddlZddlZddlZddlZddlmZGddeZdS)N)TestCaseceZdZdfd ZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdfd ZfdZdZxZS)IsolatedAsyncioTestCaserunTestct|d|_tj|_dSN)super__init___asyncioRunner contextvars copy_context_asyncioTestContext)self methodName __class__s ,/usr/lib64/python3.11/unittest/async_case.pyr z IsolatedAsyncioTestCase.__init__#s: $$$"#.#;#=#=   c KdSr rs r asyncSetUpz"IsolatedAsyncioTestCase.asyncSetUp(  rc KdSr rrs r asyncTearDownz%IsolatedAsyncioTestCase.asyncTearDown+rrc(|j|g|Ri|dSr ) addCleanuprfuncargskwargss raddAsyncCleanupz'IsolatedAsyncioTestCase.addAsyncCleanup.s) $1&11111rcKt|} |j}|j}n/#t$r"t d|jd|jddwxYw||d{V}|||ddd|S)zEnters the supplied asynchronous context manager. If successful, also adds its __aexit__ method as a cleanup function and returns the result of the __aenter__ method. '.zC' object does not support the asynchronous context manager protocolN)type __aenter__ __aexit__AttributeError TypeError __module__ __qualname__r")rcmclsenterexitresults renterAsyncContextz)IsolatedAsyncioTestCase.enterAsyncContext=s2hh 'NE=DD ' ' 'UUU1AUUU"& ' 'uRyy T2tT4888 s ",Ac|j|j|j||jdSr )r get_looprrunsetUp _callAsyncrrs r _callSetUpz"IsolatedAsyncioTestCase._callSetUpQsL $$&&&  $$TZ000 (((((rct||"tjd|dtddSdS)NzFIt is deprecated to return a value that is not None from a test case ()) stacklevel)_callMaybeAsyncwarningswarnDeprecationWarning)rmethods r_callTestMethodz'IsolatedAsyncioTestCase._callTestMethodYsd    ' ' 3 M2(.2223ERS U U U U U U 4 3rcx||j|j|jdSr )r7rrr5tearDownrs r _callTearDownz%IsolatedAsyncioTestCase._callTearDown^s6 *+++  $$T]33333rc(|j|g|Ri|dSr )r=)rfunctionr r!s r _callCleanupz$IsolatedAsyncioTestCase._callCleanupbs+X777777777rcP|j||i||jSN)context)r r5rrs rr7z"IsolatedAsyncioTestCase._callAsynces<"&& D$ !& ! !,'   rctj|r'|j||i||jS|jj|g|Ri|SrJ)inspectiscoroutinefunctionr r5rrs rr=z'IsolatedAsyncioTestCase._callMaybeAsyncmsv  &t , , G&**d%f%%0+  04+/FtFFFvFF Frc>tjd}||_dS)NT)debug)asyncioRunnerr rrunners r_setupAsyncioRunnerz+IsolatedAsyncioTestCase._setupAsyncioRunnerws"d+++$rc<|j}|dSr )r closerSs r_tearDownAsyncioRunnerz.IsolatedAsyncioTestCase._tearDownAsyncioRunner|s$ rNc| t||S#|wxYwr )rUr r5rX)rr1rs rr5zIsolatedAsyncioTestCase.runsZ   """ *77;;v&&  ' ' ) ) ) )D ' ' ) ) ) )s A A"c|t|dSr )rUr rPrX)rrs rrPzIsolatedAsyncioTestCase.debugs>   """   ##%%%%%rc@|j|dSdSr )r rXrs r__del__zIsolatedAsyncioTestCase.__del__s+   *  ' ' ) ) ) ) ) + *r)rr )__name__r+r,r rrr"r2r8rBrErHr7r=rUrXr5rPr\ __classcell__)rs@rrr s=4>>>>>>        2 2 2()))UUU 444888   GGG%%% ******&&&&& *******rr)rQr rMr>caserrrrrr`s|E*E*E*E*E*hE*E*E*E*E*r__pycache__/loader.cpython-311.pyc000064400000065402151030032340012722 0ustar00 !A?hXldZddlZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z m Z m Z dZejdejZGdd e jZd Zd Zd Zd ZdZGddeZeZddZe jdfdZde je jfdZ de je jfdZ!dS)zLoading unittests.N)fnmatch fnmatchcase)casesuiteutilTz[_a-z]\w*\.py$c,eZdZdZfdZfdZxZS) _FailedTestNcf||_tt||dSN) _exceptionsuperr __init__)self method_name exception __class__s (/usr/lib64/python3.11/unittest/loader.pyrz_FailedTest.__init__s.# k4  ))+66666cz|jkr(tt|Sfd}|S)Ncjr )r rsr testFailurez,_FailedTest.__getattr__..testFailure!s / !r)_testMethodNamerr __getattr__)rnamerrs` rrz_FailedTest.__getattr__sO 4' ' 'd++77== = " " " " "r)__name__ __module__ __qualname__rrr __classcell__rs@rr r sVO77777rr crd|dtj}t|t|||S)NzFailed to import test module:  ) traceback format_exc_make_failed_test ImportError)r suiteClassmessages r_make_failed_import_testr*&s< i"$$$&G T;w#7#7W M MMrcRdtj}t||||S)NzFailed to call load_tests: )r$r%r&)rrr(r)s r_make_failed_load_testsr,+s32;2F2H2H2HJG  iW . ..rc>t||}||f|fSr )r ) methodnamerr(r)tests rr&r&0s( z9 - -D :tg   ''rctjt|d}||i}tdtjf|}|||fS)NcdSr rs r testSkippedz'_make_skipped_test..testSkipped5s r ModuleSkipped)rskipstrtypeTestCase)r.rr(r3attrs TestClasss r_make_skipped_testr;4si Ys9~~    %E_t}&6>>I :yy,,. / //rc|dr |ddStj|dS)Nz $py.classir)lowerendswithospathsplitext)r@s r_jython_aware_splitextrB<sI zz||[))CRCy 7  D ! !! $$rceZdZdZdZeejZdZ e j Z dZ fdZdZdddZddZdd Zd Zdd Zd ZdZdZdZdZdZxZS) TestLoaderz This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite r/Nctt|g|_t |_dSr )rrDrerrorsset_loading_packages)rrs rrzTestLoader.__init__Ms: j$((*** "%rc,t|tjrtd|tjtjfvrg}n*||}|st|drdg}| t||}|S)z;Return a suite of all test cases contained in testCaseClasszYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?runTest) issubclassr TestSuite TypeErrorrr8FunctionTestCasegetTestCaseNameshasattrr(map)r testCaseClass testCaseNames loaded_suites rloadTestsFromTestCasez TestLoader.loadTestsFromTestCaseTs mU_ 5 5 )()) ) T]D,AB B BMM 11-@@M  ,W]I%F%F ,!* s=-'H'HII rpatternct|dksd|vr0tjdt|ddt|dkr4t|dz}t d|t|dkr7t|d}t d|g}t|D]}t||}t|tr\t|tjrB|tjtjfvr(|||t|dd} ||}| _ | |||S#t&$rD} t)|j| |j\} } |j| | cYd} ~ Sd} ~ wwxYw|S) z>Return a suite of all test cases contained in the given moduleruse_load_testsz(use_load_tests is deprecated and ignoredNrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpoprMformatsorteddirgetattr isinstancer7rKrr8rNappendrUr( Exceptionr,rrF) rmodulerWargskws complainttestsrobjrZe error_case error_messages rloadTestsFromModulezTestLoader.loadTestsFromModulefs t99q==,33 MD, . . . GG$d + + + t99q==D A Iahhirsstt t s88q== s AI[bbclmmnn nKK > >D&$''C3%% >sDM22 > t/DEEE T77<<===V\488 &&  ! "!z$w777 " " ",COQ-9-9) M ""=111!!!!!!!  "  s F$$ G2.9G-'G2-G2c v|d}d\}}||dd}|r d|}t|}n^#t$rO|}t ||j\}}|s|j||cYSYnwxYw||dd}|} |D]} | t| | } } #t$r} t| dd%|#|j||cYd} ~ cSt| | |jdtj \}}|j||cYd} ~ cSd} ~ wwxYwt| tjr|| St| t$rIt'| t(jr/| t(jt(jfvr|| St| tjrt| t$rlt'| t(jrR|d}| |} tt| |tjs|| gSnt| t2jr| St7| rl| }t|t2jr|St|t(jr||gSt9d| d |d t9d | z) aSReturn a suite of all test cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. .NNNr__path__zFailed to access attribute: zcalling z returned z , not a testz$don't know how to make test from: %s)splitjoin __import__r'r_r*r(rFrercAttributeErrorr&r$r%rdtypes ModuleTyperpr7rKrr8rNrU FunctionTyperrLcallablerM)rrrgpartsrnro parts_copy module_namenext_attributerlpartparentrminstr/s rloadTestsFromNamezTestLoader.loadTestsFromNames 3$.! M >qqqJ * *"%((:"6"6K' 44F"***%/^^%5%5N0H&1919-J %* **=999))))** *  *!""IE & &D &!73#5#5! & & &CT22>". K&&}555%%%%%%%%%1Ba%022251616-J K&&}555%%%%%%%%%% &( c5+ , , ++C00 0 sD ! ! 3 .. DM4+@AAA--c22 2e011 && // 9D6$<C E'.E" E'A E"E'"E'cNfd|D}|S)zReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. c<g|]}|Sr2)r).0rrgrs r z1TestLoader.loadTestsFromNames..s)III4$((v66IIIr)r()rnamesrgsuitess` ` rloadTestsFromNameszTestLoader.loadTestsFromNamess5JIIII5IIIv&&&rcfd}tt|t}jr-|t jj|S)zLReturn a sorted sequence of method names found within testCaseClass c|jsdSt|}t|sdSdjj|fzjduptfdjDS)NFz%s.%s.%sc38K|]}t|VdSr )r)rrWfullNames r zKTestLoader.getTestCaseNames..shouldIncludeMethod..s-XXwK'22XXXXXXr) startswithtestMethodPrefixrcr}rrtestNamePatternsany)attrnametestFuncrrrRs @rshouldIncludeMethodz8TestLoader.getTestCaseNames..shouldIncludeMethods&&t'<== u}h77HH%% u"(-*Dh&H(D0YXXXX$BWXXXXX Yr)key)listfilterrbsortTestMethodsUsingsort functools cmp_to_key)rrRr testFnNamess`` rrOzTestLoader.getTestCaseNamess Y Y Y Y Y Y6"5s=7I7IJJKK  $ R   !5d6O!P!P  Q Q Qrtest*.pycd}||j|j}n|d}|}tj|}|tjvr tjd|||_d}tjtj|retj|}||kr>tjtj|d }n t|tj |}| dd} tjtj |j }nD#t$r7|jtjvrt#ddt#d|dwxYw|r9|||_tj|n#t($rd}YnwxYw|rt)d |zt+|||}||S) a%Find and return all test modules from the specified start directory, recursing into subdirectories to find them and return all tests found within them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with (loader, tests, pattern) unless the package has already had load_tests called from the same discovery invocation, in which case the package module object is not scanned for tests - this ensures that when a package uses discover to further discover child tests that infinite recursion does not happen. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). Paths are sorted before being imported to ensure reproducible execution order even on filesystems with non-alphabetical ordering like ext3/4. FNTr __init__.pyrrz2Can not use builtin modules as dotted module namesz don't know how to discover from z%Start directory is not importable: %r)_top_level_dirr?r@abspathsysinsertisdirisfilerwrxmodulesrvdirname__file__ryrbuiltin_module_namesrM _get_directory_containing_moduleremover'r _find_testsr() r start_dirrW top_level_dirset_implicit_topis_not_importable the_moduletop_partrks rdiscoverzTestLoader.discoverse8!  T%8%D /MM  "# %M 66 (( HOOA} - - -+! 7==33 4 4 3 22IM))(*rw||I}7]7](^(^$^! 39%%%![3 $??3//2 ( ")<>>!@!@II%(((!*c.FFF')ABBGKL(MzMM#'( ($3*.*O*OPX*Y*YD'HOOM222) ) ) )$(!!! ),  SE QRR RT%%i99::u%%%s HAFAG H H ctj|}tj|j}tj|dr> > 7??9-- -rc||jkrdSttj|}tj||j}tj|r Jd|dr Jd|tjj d}|S)NrrzPath must be within the projectz..) rrBr?r@normpathrelpathisabsrreplacesep)rr@_relpathrs r_get_name_from_pathzTestLoader._get_name_from_path]s 4& & &3%bg&6&6t&<&<==7??4)<==7==**MM,MMM*&&t,,OO.OOO, S11 rcDt|tj|Sr )rxrr)rrs r_get_module_from_namez TestLoader._get_module_from_nameis4{4  rc"t||Sr )r)rr@rrWs r _match_pathzTestLoader._match_pathmstW%%%rc#rK||}|dkr,||jvr#|||\}}||V|sdStt j|}|D]}tj||}|||\}}||V|r||}|j| | ||Ed{V|j |#|j |wxYwdS)z/Used by discovery. Yields test suites it loads.rrN) rrH_find_test_pathrar?listdirr@rwaddrdiscard) rrrWrrkshould_recursepathsr@rs rrzTestLoader._find_testsqsv'' 22 3;;4t'===%)$8$8G$L$L !E>  ! rz),,-- 9 9D Y55I$($8$8G$L$L !E>   9// ::&**40009#// 7CCCCCCCCC*2248888D*2248888 9 9 9s DD3ctj|}tj|rt|sdS||||sdS||} ||}tj t|d|}ttj |}ttj |}| | krtj|} ttj|} tj|} d} t| | | | fz|||dfS#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwtj|rztjtj|dsdSd}d}||} ||}t|dd}|j| |||}||df|j|S|d f|j|S#|j|wxYw#t"j$r"} t'|| |jdfcYd} ~ Sd} ~ wt+||j\}}|j||dfcYSxYwdS) zUsed by discovery. Loads tests from a single file, or a directories' __init__.py when passed the directory. Returns a tuple (None_or_tests_from_file, should_recurse). )NFrzW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?rVFNrrZT)r?r@rrVALID_MODULE_NAMEmatchrrrrrcrBrealpathr=rr'rprSkipTestr;r(r*rFrerrwrHrr)rrrWrrrgmod_filerfullpath_noext module_dirmod_name expected_dirmsgrmrnrorZrkpackages rrzTestLoader._find_test_paths7##I.. 7>>) $ $? $**844 #"{##HiAA #"{++I66D P33D997??FJ ::<<1G$$X..00!7G$$Y//"1"1>>##~';';'='===!#!:!:J5((33 5 5H#%7??9#=#=LDC%x\BBDDD///HH%OO/= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5(((($W]]9 % % 7>>"',,y-"H"HII #"{JE++I66D 944T::%WlDAA &**40009 44Wg4NNE!-$e|*2248888!$;*2248888D*2248888%= K K K)$4?CCUJJJJJJJ ),T4?CC* M ""=111!5((((;sN G**I9HI;INM%M%%NO-N0*O-0;O-r )rN)rrr__doc__r staticmethodr three_way_cmprrrrLr(rrrUrprrrOrrrrrrrr r!s@rrDrDBsX'<(:;;JN'''''$:>*****XPJPJPJPJd''''&Q&Q&Q&Q&f . . .   !!!&&&999@HHHHHHHrrDc^t}||_||_||_|r||_|Sr )rDrrrr()prefix sortUsingr(rloaders r _makeLoaderrs8 \\F"+F$F.F'& Mrcddl}|jdtdt||||S)Nrzunittest.getTestCaseNames() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.getTestCaseNames() instead. stacklevel)r)r\r]r^rrO)rRrrrr\s rrOrOsXOOOHM Eq vy;K L L L ] ]^k l llrr/cddl}|jdtdt||||S)Nrzunittest.makeSuite() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromTestCase() instead.rr)r\r]r^rrU)rRrrr(r\s r makeSuitersZOOOHM Jq vy* 5 5 K K  rcddl}|jdtdt||||S)Nrzunittest.findTestCases() is deprecated and will be removed in Python 3.13. Please use unittest.TestLoader.loadTestsFromModule() instead.rr)r\r]r^rrp)rgrrr(r\s r findTestCasesrsZOOOHM Hq vy* 5 5 I I  rrs)"rr?rerr$rzrr\rrrrr __unittestcompile IGNORECASErr8r r*r,r&r;rBobjectrDdefaultTestLoaderrrrOrLrrr2rrrs  ((((((((  BJ0"-@@     $-   NNN ... (((000%%% WWWWWWWWt JLL 7;6H[_mmmm%+d6H    "(43E"_      r__pycache__/runner.cpython-311.opt-1.pyc000064400000040140151030032340013714 0ustar00 !A?h$dZddlZddlZddlZddlmZddlmZddlm Z dZ Gdd e Z Gd d ej ZGd d e ZdS)z Running testsN)result)_SubTest)registerResultTc&eZdZdZdZdZddZdS)_WritelnDecoratorz@Used to decorate file-like objects with a handy 'writeln' methodc||_dSN)stream)selfr s (/usr/lib64/python3.11/unittest/runner.py__init__z_WritelnDecorator.__init__s  cR|dvrt|t|j|S)N)r __getstate__)AttributeErrorgetattrr )r attrs r __getattr__z_WritelnDecorator.__getattr__s. - - - && &t{4(((rNc^|r|||ddSN )write)r args r writelnz_WritelnDecorator.writelns1   JJsOOO 4rr )__name__ __module__ __qualname____doc__rrrrr rrsLJJ))) rrceZdZdZdZdZfdZdZfdZdZ fdZ fd Z fd Z fd Z fd Zfd ZfdZdZdZxZS)TextTestResultzhA test result class that can print formatted text results to a stream. Used by TextTestRunner. zF======================================================================zF----------------------------------------------------------------------ctt||||||_|dk|_|dk|_||_d|_dS)NrT)superr"rr showAlldots descriptions_newline)r r r' verbosity __class__s r rzTextTestResult.__init__&sU nd##,,V\9MMM  1} N ( rc|}|jr&|r$dt||fSt|Sr)shortDescriptionr'joinstr)r testdoc_first_lines r getDescriptionzTextTestResult.getDescription.sN..00    99c$ii899 9t99 rc8tt|||jri|j|||jd|jd|_dSdS)N ... F) r$r" startTestr%r rr1flushr(r r/r*s r r4zTextTestResult.startTest5s nd##--d333 < " K  d11$77 8 8 8 K  g & & & K     !DMMM  " "rct|t}|s|jr|js|j|r|jd|j|||jd|j||jd|_dS)Nz r3T) isinstancerr(r rrr1r5)r r/status is_subtests r _write_statuszTextTestResult._write_status=sh//  ' '= & ##%%% ( !!$''' K  d11$77 8 8 8 K  g & & & F###  rc||jrIt|d|jr||dn||dnp|jrit|d|jr|jdn|jd|jtt| |||dS)NrFAILERRORFE) r% issubclassfailureExceptionr;r&r rr5r$r" addSubTest)r r/subtesterrr*s r rCzTextTestResult.addSubTestJs ?| $c!fg&>??9&&w7777&&w8888 $c!fg&>??+K%%c****K%%c*** !!### nd##..tWcBBBBBrctt|||jr||ddS|jr5|jd|jdSdS)Nok.) r$r" addSuccessr%r;r&r rr5r6s r rIzTextTestResult.addSuccessYs nd##..t444 <   tT * * * * * Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr>r@) r$r"addErrorr%r;r&r rr5r r/rEr*s r rKzTextTestResult.addErroras nd##,,T3777 <   tW - - - - - Y K  c " " " K         rctt||||jr||ddS|jr5|jd|jdSdS)Nr=r?) r$r" addFailurer%r;r&r rr5rLs r rNzTextTestResult.addFailureis nd##..tS999 <   tV , , , , , Y K  c " " " K         rc6tt||||jr+||d|dS|jr5|jd|j dSdS)Nz skipped {0!r}s) r$r"addSkipr%r;formatr&r rr5)r r/reasonr*s r rQzTextTestResult.addSkipqs nd##++D&999 <   t_%;%;F%C%C D D D D D Y K  c " " " K         rcJtt||||jr5|jd|jdS|jr5|jd|jdSdS)Nzexpected failurex) r$r"addExpectedFailurer%r rr5r&rrLs r rVz!TextTestResult.addExpectedFailureys nd##66tSAAA < K   2 3 3 3 K        Y K  c " " " K         rcHtt|||jr5|jd|jdS|jr5|jd|jdSdS)Nzunexpected successu) r$r"addUnexpectedSuccessr%r rr5r&rr6s r rYz#TextTestResult.addUnexpectedSuccesss nd##88>>> < K   4 5 5 5 K        Y K  c " " " K         rc|js|jr2|j|j|d|j|d|jt|dd}|ro|j|j |D]2}|jd| |3|jdSdS)Nr>r=unexpectedSuccessesr zUNEXPECTED SUCCESS: ) r&r%r rr5printErrorListerrorsfailuresr separator1r1)r r[r/s r printErrorszTextTestResult.printErrorss 9   K   ! ! ! K      GT[111 FDM222%d,A2FF  K   0 0 0+ X X ##$V4;N;Nt;T;T$V$VWWWW K          rcb|D]\}}|j|j|j|d|||j|j|jd|z|jdS)Nz: z%s)r rr_r1 separator2r5)r flavourr]r/rEs r r\zTextTestResult.printErrorLists  ID# K   0 0 0 K  GGGD4G4G4M4M4M N O O O K   0 0 0 K  s + + + K         r)rrrrr_rbrr1r4r;rCrIrKrNrQrVrYr`r\ __classcell__)r*s@r r"r"sWJJ"""""    C C C C C                                         rr"c4eZdZdZeZ d dddZdZd ZdS) TextTestRunnerzA test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. NTrF) tb_localsc| tj}t||_||_||_||_||_||_||_ | ||_ dSdS)zConstruct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. N) sysstderrrr r'r)failfastbufferrgwarnings resultclass) r r r'r)rkrlrnrmrgs r rzTextTestRunner.__init__sf >ZF'// ("   "   "*D    # "rcN||j|j|jSr )rnr r'r))r s r _makeResultzTextTestRunner._makeResults! T->OOOrc|}t||j|_|j|_|j|_t j5|jr>t j|j|jdvrt jdtdtj }t|dd}| | ||t|dd}| |n##t|dd}| |wwxYwtj }dddn #1swxYwY||z }|j t|dr|j|j|j}|jd ||d krd pd |fz|jd x} x} } t't(|j|j|jf} | \} } } n#t0$rYnwxYwg} |jsw|jdt)|jt)|j}}|r| d|z|r| d|zn|jd| r| d| z| r| d| z| r| d| z| r2|jdd| dn|jd|j|S)z&Run the given test case or test suite.)defaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRunN stopTestRunrbzRan %d test%s in %.3fsrrPrFAILEDz failures=%dz errors=%dOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (z, )r) rprrkrlrgrmcatch_warnings simplefilterfilterwarningsDeprecationWarningtime perf_counterrr`hasattrr rrbtestsRunmaplenexpectedFailuresr[skippedr wasSuccessfulrr^r]appendr-r5)r r/r startTimerwrxstopTime timeTakenrun expectedFailsr[rresultsinfosfailederroreds r rzTextTestRunner.runs!!##v-  >  $ & & + +} F%dm444 =$999+H%7$DFFFF)++I"6>4@@L'  "V %fmTBB *KMMM&fmTBB *KMMMM+(**H/ + + + + + + + + + + + + + + +0y(  6< ( ( 3 K   1 2 2 2o 4 #("2s"8b)DE F F F 899 9+g B# 7 & : & 011G ;B 7M.    D  #v#%% $ K  h ' ' '!&/22C 4F4FGF 5 ]V3444 4 [72333 K  d # # #  1 LL/ 0 0 0  A LL/-? @ @ @  J LL25HH I I I  $ K   499U+;+;+;+; = > > > > K  d # # #  s=A6D= C;D=; DD==EE'H HH)NTrFFNN) rrrrr"rnrrprr rr rfrfsr !KABJN+#+++++(PPPGGGGGrrf)rrirrmryrcasersignalsr __unittestobjectr TestResultr"rfr rr rs ######           @ @ @ @ @ V&@ @ @ FfffffVfffffr__pycache__/__init__.cpython-311.opt-2.pyc000064400000004646151030032340014156 0ustar00 !A?h^ gdZegddZddlmZddlmZmZmZm Z m Z m Z m Z m Z mZmZddlmZmZddlmZmZddlmZmZdd lmZmZdd lmZmZmZmZdd lm Z m!Z!m"Z"eZ#d Z$d Z%dZ&dS)) TestResultTestCaseIsolatedAsyncioTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandleraddModuleCleanupdoModuleCleanupsenterModuleContext)getTestCaseNames makeSuite findTestCasesT)r) rrrr r r rrrr) BaseTestSuiter)rr ) TestProgramr )rr)rrrr)rrrcvddl}|jt}|||S)N) start_dirpattern)os.pathpathdirname__file__discover)loadertestsr!osthis_dirs */usr/lib64/python3.11/unittest/__init__.py load_testsr,Os4NNNwx((H ??Xw? ? ??cJtdhzS)Nr)globalskeysr-r+__dir__r2Zs 99>>  89 99r-c\|dkr ddlmatStdtd|)Nrr)rzmodule z has no attribute ) async_caserAttributeError__name__)names r+ __getattr__r8]sE (((777777&& I8IIII J JJr-N)'__all__extend __unittestresultrcaserrrr r r rrrrsuiterrr'rr r rrunnerrrsignalsrrrrrrr_TextTestResultr,r2r8r1r-r+rBs,\ I I IAAABBB  '''''''''''''''''''''''',+++++++11111111########22222222PPPPPPPPPPPP>>>>>>>>>>! @@@:::KKKKKr-__pycache__/__main__.cpython-311.pyc000064400000001222151030032340013162 0ustar00 !A?hdZddlZejddr1ddlZejejZedzejd<[dZ ddl m Z e ddS) zMain entry pointNz __main__.pyz -m unittestT)main)module) __doc__sysargvendswithos.pathospathbasename executable __unittestr*/usr/lib64/python3.11/unittest/__main__.pyrs 8A; && NNN !!#.11J~-CHQK  Dr__pycache__/suite.cpython-311.opt-2.pyc000064400000040750151030032340013544 0ustar00 !A?h4 ddlZddlmZddlmZdZdZGddeZGd d eZGd d eZ d Z GddeZ dS)N)case)utilTc>t||d}|dS)NcdSNr '/usr/lib64/python3.11/unittest/suite.pyz!_call_if_exists.. sr )getattr)parentattrfuncs r _call_if_existsr s$ 64 . .DDFFFFFr cXeZdZ dZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdS) BaseTestSuiteTr cLg|_d|_||dSNr)_tests_removed_testsaddTests)selftestss r __init__zBaseTestSuite.__init__s)  er c\dtj|jdt|dS)N)rstrclass __class__listrs r __repr__zBaseTestSuite.__repr__s+"&-"?"?"?"?dLLr czt||jstSt|t|kSr) isinstancer NotImplementedr!)rothers r __eq__zBaseTestSuite.__eq__s3%00 "! !DzzT%[[((r c*t|jSr)iterrr"s r __iter__zBaseTestSuite.__iter__"sDK   r cP|j}|D]}|r||z }|Sr)rcountTestCases)rcasestests r r-zBaseTestSuite.countTestCases%s=# / /D /,,... r c@t|s/tdt|t |t r0t |tjtfrtd|j |dS)Nz{} is not callablezNTestCases and TestSuites must be instantiated before passing them to addTest()) callable TypeErrorformatreprr%type issubclassrTestCase TestSuiterappendrr/s r addTestzBaseTestSuite.addTest,s~~ E077T CCDD D dD ! ! @j26-1K'M'M @?@@ @ 4     r ct|trtd|D]}||dS)Nz0tests must be an iterable of tests, not a string)r%strr2r;)rrr/s r rzBaseTestSuite.addTests6sR eS ! ! PNOO O  D LL      r ct|D]5\}}|jrn(|||jr||6|Sr) enumerate shouldStop_cleanup_removeTestAtIndex)rresultindexr/s r runzBaseTestSuite.run<s\$T?? / /KE4   DLLL} /''... r c |j|}t|dr"|xj|z c_d|j|<dS#t$rYdSwxYw)Nr-)rhasattrrr-r2)rrDr/s r rBz BaseTestSuite._removeTestAtIndexEs@ &;u%Dt-.. =##t':':'<'<<##!%DK       DD s A AAc|j|i|SrrE)rargskwdss r __call__zBaseTestSuite.__call__Sstx&&&&r c: |D]}|dSr)debugr:s r rNzBaseTestSuite.debugVs-E  D JJLLLL  r N)r )__name__ __module__ __qualname__rArr#r(r+r-r;rrErBrLrNr r r rrsH MMM))) !!!!!!  & & &'''r rcPeZdZ d dZdZdZdZdZ d dZ d d Z d Z d Z dS)r8Fcld}t|dddur dx|_}t|D]\}}|jrnt |rv||||||||||j|_ t|jddst|ddr|s ||n| |j r| ||r2|d|| |d|_|S)NF_testRunEnteredT_classSetupFailed_moduleSetUpFailed)r rTr?r@ _isnotsuite_tearDownPreviousClass_handleModuleFixture_handleClassSetUpr _previousTestClassrNrArB_handleModuleTearDown)rrCrNtopLevelrDr/s r rEz TestSuite.runfsb 6,e 4 4 = =04 4F "X$T?? / /KE4  4   ++D&999))$777&&tV444,0N)DN,?GGF$8%@@ V  } /''...  +  ' 'f 5 5 5  & &v . . .%*F " r cP t}||ddS)NT) _DebugResultrE)rrNs r rNzTestSuite.debugs(E r ct|dd}|j}||krdS|jrdSt|ddrdSd} d|_n#t$rYnwxYwt|dd}t|dd}|t |d |nt#t $rg}t|trd} d|_n#t$rYnwxYwtj |} | ||d| Yd}~nd}~wwxYw|r6|4||j D]"} | || dd| | #t |d dS#t |d wxYwdS) Nr[__unittest_skip__F setUpClassdoClassCleanups _setupStdoutTrinfo_restoreStdout) r r rVrUr2r Exceptionr%r_rr"_createClassOrModuleLevelExceptiontearDown_exceptions) rr/rC previousClass currentClassfailedrbrce classNameexc_infos r rZzTestSuite._handleClassSetUps8(> !,0A4HH  ! FN 3 3 3 : GJLLLL G G G!&,77!F9= 66$ $ l ; ;I;;FAd}t|dd}||j}|S)Nr[)r rP)rrCpreviousModulerks r _get_previous_modulezTestSuite._get_previous_modules-(> * * * * * -s|~~66666t,,,,,r c|||}|dS|jrdS tj|}n#t$rYdSwxYwt |d t |dd}|Q |nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYw tj nE#t$r8}t|tr| ||d|Yd}~nd}~wwxYwt |ddS#t |dwxYw)NrdtearDownModulerg) rsrVrvrwrxrr rhr%r_rirry)rrCrrr{rrns r r\zTestSuite._handleModuleTearDowns226::  ! F  $  F [0FF    FF  /// 6$V-=tDDN)L"N$$$$ LLL!&,77;;FACD) D.D D)DD))D;ct|dd}|j}||ks|dSt|ddrdSt|ddrdSt|ddrdSt|dd}t|dd}||dSt|d |e |nY#t$rL}t |t rt j|}|||d|Yd}~nd}~wwxYw|e||j D]S} t |t r| d t j|}||| d d|| Tt|d dS#t|d wxYw) Nr[rUFrVra tearDownClassrcrdrrerg) r r rrhr%r_rrrirj) rr/rCrkrlrrcrnrorps r rXz TestSuite._tearDownPreviousClasss%(E T tt 5s  !!ceZdZ dZdZdZdS)r_NF)rOrPrQr[rVr@r r r r_r_ws"IJJJr r_) rvrr __unittestrobjectrr8rrWr_r r r rs      IIIIIFIIIXi6i6i6i6i6 i6i6i6X$$$$$6$$$L6r __pycache__/signals.cpython-311.opt-2.pyc000064400000007447151030032340014061 0ustar00 !A?hc ~ddlZddlZddlmZdZGddeZejZdZ dZ da dZ d d Z dS) N)wrapsTceZdZdZdZdS)_InterruptHandlercd|_||_t|tr@|tjkr tj}n#|tjkrd}ntd||_ dS)NFcdSN) unused_signum unused_frames )/usr/lib64/python3.11/unittest/signals.pydefault_handlerz3_InterruptHandler.__init__..default_handlersDzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr )selfr s r __init__z_InterruptHandler.__init__ s / os + + 3&.00"("< FN22 !2333 /rctjtj}||ur||||jr|||d|_t D]}|dS)NT)r getsignalSIGINTr r_resultskeysstop)rsignumframeinstalled_handlerresults r __call__z_InterruptHandler.__call__s",V];; D ( (   / / / ; 0   / / / mmoo  F KKMMMM  rN)__name__ __module__ __qualname__rr$r rr rr s2///$     rrcdt|<dS)N)rr#s r registerResultr+*sHVrcRtt|dSr)boolrpopr*s r removeResultr/-s  VT** + ++rctStjtj}t |atjtjtdSdSr)_interrupt_handlerrrrr)r s r installHandlerr21sK! *6=99.?? fm%788888"!rctfd}|St+tjtjtjdSdS)Nctjtj}t |i|tjtj|S#tjtj|wxYwr)rrr removeHandler)argskwargsinitialmethods r innerzremoveHandler..inner;sf&v}55G OOO 6vt.v.. fmW5555 fmW5555s A!A7)rr1rrr)r9r:s` r r5r59sg  v 6 6 6 6  6 % fm%7%HIIIII&%rr)rweakref functoolsr __unittestobjectrWeakKeyDictionaryrr+r/r1r2r5r rr r@s   @ %7 $ & &,,,999JJJJJJr__pycache__/util.cpython-311.pyc000064400000020266151030032340012430 0ustar00 !A?h_dZddlmZmZddlmZdZdZdZdZ dZ dZ ee eze zeze zz Z e dksJdZ d Zdd Zd Zd ZdZdZeddZdZdZdS)zVarious utility functions.) namedtupleCounter) commonprefixTP ct||z |z }|tkr(d|d|||t||z dfz}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlen suffixlenskips &/usr/lib64/python3.11/unittest/util.py_shortenrsW q66I  )D  *9* tQs1vv 7I7J7J5KL L HcVttt|}ttt|}|t kr|St |t t |z tztzz }|tkrZttztz|z zt ksJtt|tfd|DSttttfd|DS)Nc32K|]}|dzVdSN.0r prefixr s r z'_common_shorten_repr..'s0::Va m+::::::rc3dK|]*}t|dttzV+dSr)r _MIN_DIFF_LEN _MIN_END_LENrs rrz'_common_shorten_repr..*sP  (1YZZ=-NNN      r) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENr)argsmaxlen common_lenrr s @@r_common_shorten_reprr(s8 Y%% & &D S$ F  $  FF I9$~58HHJJO## 00?B"$&12222&.*==:::::T:::::: fno > >F            rFc t|}n*#t$rt|}YnwxYw|rt |t kr|S|dt dzS)Nz [truncated]...)repr Exceptionobject__repr__r r")objshortresults rr r -sv&c &&&%%& CKK+-- ,;, "3 33s $99c$|jd|jS)N.) __module__ __qualname__)clss rstrclassr66snnnc&6&6 77rcdx}}g}g} ||}||}||kr8|||dz }|||kr|dz }|||kn||kr8|||dz }|||kr|dz }|||knm|dz } |||kr|dz }|||k|dz }|||kr|dz }|||kn'#|dz }|||kr|dz }|||kwxYwnJ#t$r=|||d|||dYnwxYwG||fS)arFinds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the second contains those elements in the "actual" list but not in the "expected" list. Duplicate elements in either input list are ignored. rTN)append IndexErrorextend)expectedactualijmissing unexpectedeas rsorted_list_differencerD9s IAGJ  Aq A1uuq!!!QqkQ&&FAqkQ&&Q!!!$$$QQi1nnFAQi1nnQ"1+**Q#1+**FA )q..Q!)q..FA )q..Q!)q......    NN8ABB< ( ( (   fQRRj ) ) ) E /6 J s+BDC:#D$DDAE  E cg}|rR|} ||n%#t$r||YnwxYw|R||fS)zSame behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance.)popremove ValueErrorr9)r<r=r@items runorderable_list_differencerJbs G !||~~ ! MM$     ! ! ! NN4  ! ! F?s0AAc||k||kz S)z.Return -1 if x < y, 0 if x == y and 1 if x > yr)xys r three_way_cmprNss Ea!e rMismatchzactual expected valuect|t|}}t|t|}}t}g}t|D]\}} | |ur dx} } t ||D]} || | kr | dz } ||| <t|D]\} } | | kr | dz } ||| <| | kr&t | | | }||t|D][\}} | |ur d} t ||D]} || | kr | dz } ||| <t d| | }||\|S)HReturns list of (cnt_act, cnt_exp, elem) triples where the counts differrr8)listr r, enumeraterange _Mismatchr9)r=r<r tmnNULLr0r>elemcnt_scnt_tr? other_elemdiffs r_count_diff_all_purposer_ys <<hqA q663q66qA 88D FQ<<  4 4<< q!  Att|| !&q\\  MAzT!! ! E>>UE400D MM$   Q<<  4 4<< q!  Att|| !E4(( d Mrct|t|}}g}|D]G\}}||d}||kr&t|||}||H|D]/\}}||vr&td||}||0|S)rQr)ritemsgetrUr9) r=r<r rVr0rZr[r\r^s r_count_diff_hashablercs 6??GH--qA Fwwyy  edA E>>UE400D MM$   wwyy  e q==Qt,,D MM$    MrN)F)__doc__ collectionsrros.pathr __unittestr"r r#rr$rrr(r r6rDrJrNrUr_rcrrrrhs; ++++++++    !11OC !#/01       *4444888&&&R" Jz#: ; ; !!!Fr__pycache__/__main__.cpython-311.opt-1.pyc000064400000001222151030032340014121 0ustar00 !A?hdZddlZejddr1ddlZejejZedzejd<[dZ ddl m Z e ddS) zMain entry pointNz __main__.pyz -m unittestT)main)module) __doc__sysargvendswithos.pathospathbasename executable __unittestr*/usr/lib64/python3.11/unittest/__main__.pyrs 8A; && NNN !!#.11J~-CHQK  Dr_log.py000064400000005272151030032340006033 0ustar00import logging import collections from .case import _BaseTestCaseContext _LoggingWatcher = collections.namedtuple("_LoggingWatcher", ["records", "output"]) class _CapturingHandler(logging.Handler): """ A logging handler capturing all (raw and formatted) logging output. """ def __init__(self): logging.Handler.__init__(self) self.watcher = _LoggingWatcher([], []) def flush(self): pass def emit(self, record): self.watcher.records.append(record) msg = self.format(record) self.watcher.output.append(msg) class _AssertLogsContext(_BaseTestCaseContext): """A context manager for assertLogs() and assertNoLogs() """ LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s" def __init__(self, test_case, logger_name, level, no_logs): _BaseTestCaseContext.__init__(self, test_case) self.logger_name = logger_name if level: self.level = logging._nameToLevel.get(level, level) else: self.level = logging.INFO self.msg = None self.no_logs = no_logs def __enter__(self): if isinstance(self.logger_name, logging.Logger): logger = self.logger = self.logger_name else: logger = self.logger = logging.getLogger(self.logger_name) formatter = logging.Formatter(self.LOGGING_FORMAT) handler = _CapturingHandler() handler.setLevel(self.level) handler.setFormatter(formatter) self.watcher = handler.watcher self.old_handlers = logger.handlers[:] self.old_level = logger.level self.old_propagate = logger.propagate logger.handlers = [handler] logger.setLevel(self.level) logger.propagate = False if self.no_logs: return return handler.watcher def __exit__(self, exc_type, exc_value, tb): self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.no_logs: # assertNoLogs if len(self.watcher.records) > 0: self._raiseFailure( "Unexpected logs found: {!r}".format( self.watcher.output ) ) else: # assertLogs if len(self.watcher.records) == 0: self._raiseFailure( "no logs of level {} or higher triggered on {}" .format(logging.getLevelName(self.level), self.logger.name)) main.py000064400000026227151030032340006042 0ustar00"""Unittest main program""" import sys import argparse import os import warnings from . import loader, runner from .signals import installHandler __unittest = True MAIN_EXAMPLES = """\ Examples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass %(prog)s module.Class.test_method - run specified test method %(prog)s path/to/test_file.py - run tests from test_file.py """ MODULE_EXAMPLES = """\ Examples: %(prog)s - run default set of tests %(prog)s MyTestSuite - run suite 'MyTestSuite' %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething %(prog)s MyTestCase - run all 'test*' test methods in MyTestCase """ def _convert_name(name): # on Linux / Mac OS X 'foo.PY' is not importable, but on # Windows it is. Simpler to do a case insensitive match # a better check would be to check that the name is a # valid Python module name. if os.path.isfile(name) and name.lower().endswith('.py'): if os.path.isabs(name): rel_path = os.path.relpath(name, os.getcwd()) if os.path.isabs(rel_path) or rel_path.startswith(os.pardir): return name name = rel_path # on Windows both '\' and '/' are used as path # separators. Better to replace both than rely on os.path.sep return os.path.normpath(name)[:-3].replace('\\', '.').replace('/', '.') return name def _convert_names(names): return [_convert_name(name) for name in names] def _convert_select_pattern(pattern): if not '*' in pattern: pattern = '*%s*' % pattern return pattern class TestProgram(object): """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ # defaults for testing module=None verbosity = 1 failfast = catchbreak = buffer = progName = warnings = testNamePatterns = None _discovery_parser = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None, *, tb_locals=False): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.exit = exit self.failfast = failfast self.catchbreak = catchbreak self.verbosity = verbosity self.buffer = buffer self.tb_locals = tb_locals if warnings is None and not sys.warnoptions: # even if DeprecationWarnings are ignored by default # print them anyway unless other warnings settings are # specified by the warnings arg or the -W python flag self.warnings = 'default' else: # here self.warnings is set either to the value passed # to the warnings args or to None. # If the user didn't pass a value self.warnings will # be None. This means that the behavior is unchanged # and depends on the values passed to -W. self.warnings = warnings self.defaultTest = defaultTest self.testRunner = testRunner self.testLoader = testLoader self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.runTests() def usageExit(self, msg=None): warnings.warn("TestProgram.usageExit() is deprecated and will be" " removed in Python 3.13", DeprecationWarning) if msg: print(msg) if self._discovery_parser is None: self._initArgParsers() self._print_help() sys.exit(2) def _print_help(self, *args, **kwargs): if self.module is None: print(self._main_parser.format_help()) print(MAIN_EXAMPLES % {'prog': self.progName}) self._discovery_parser.print_help() else: print(self._main_parser.format_help()) print(MODULE_EXAMPLES % {'prog': self.progName}) def parseArgs(self, argv): self._initArgParsers() if self.module is None: if len(argv) > 1 and argv[1].lower() == 'discover': self._do_discovery(argv[2:]) return self._main_parser.parse_args(argv[1:], self) if not self.tests: # this allows "python -m unittest -v" to still work for # test discovery. self._do_discovery([]) return else: self._main_parser.parse_args(argv[1:], self) if self.tests: self.testNames = _convert_names(self.tests) if __name__ == '__main__': # to support python -m unittest ... self.module = None elif self.defaultTest is None: # createTests will load tests from self.module self.testNames = None elif isinstance(self.defaultTest, str): self.testNames = (self.defaultTest,) else: self.testNames = list(self.defaultTest) self.createTests() def createTests(self, from_discovery=False, Loader=None): if self.testNamePatterns: self.testLoader.testNamePatterns = self.testNamePatterns if from_discovery: loader = self.testLoader if Loader is None else Loader() self.test = loader.discover(self.start, self.pattern, self.top) elif self.testNames is None: self.test = self.testLoader.loadTestsFromModule(self.module) else: self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module) def _initArgParsers(self): parent_parser = self._getParentArgParser() self._main_parser = self._getMainArgParser(parent_parser) self._discovery_parser = self._getDiscoveryArgParser(parent_parser) def _getParentArgParser(self): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-v', '--verbose', dest='verbosity', action='store_const', const=2, help='Verbose output') parser.add_argument('-q', '--quiet', dest='verbosity', action='store_const', const=0, help='Quiet output') parser.add_argument('--locals', dest='tb_locals', action='store_true', help='Show local variables in tracebacks') if self.failfast is None: parser.add_argument('-f', '--failfast', dest='failfast', action='store_true', help='Stop on first fail or error') self.failfast = False if self.catchbreak is None: parser.add_argument('-c', '--catch', dest='catchbreak', action='store_true', help='Catch Ctrl-C and display results so far') self.catchbreak = False if self.buffer is None: parser.add_argument('-b', '--buffer', dest='buffer', action='store_true', help='Buffer stdout and stderr during tests') self.buffer = False if self.testNamePatterns is None: parser.add_argument('-k', dest='testNamePatterns', action='append', type=_convert_select_pattern, help='Only run tests which match the given substring') self.testNamePatterns = [] return parser def _getMainArgParser(self, parent): parser = argparse.ArgumentParser(parents=[parent]) parser.prog = self.progName parser.print_help = self._print_help parser.add_argument('tests', nargs='*', help='a list of any number of test modules, ' 'classes and test methods.') return parser def _getDiscoveryArgParser(self, parent): parser = argparse.ArgumentParser(parents=[parent]) parser.prog = '%s discover' % self.progName parser.epilog = ('For test discovery all test modules must be ' 'importable from the top level directory of the ' 'project.') parser.add_argument('-s', '--start-directory', dest='start', help="Directory to start discovery ('.' default)") parser.add_argument('-p', '--pattern', dest='pattern', help="Pattern to match tests ('test*.py' default)") parser.add_argument('-t', '--top-level-directory', dest='top', help='Top level directory of project (defaults to ' 'start directory)') for arg in ('start', 'pattern', 'top'): parser.add_argument(arg, nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) return parser def _do_discovery(self, argv, Loader=None): self.start = '.' self.pattern = 'test*.py' self.top = None if argv is not None: # handle command line args for test discovery if self._discovery_parser is None: # for testing self._initArgParsers() self._discovery_parser.parse_args(argv, self) self.createTests(from_discovery=True, Loader=Loader) def runTests(self): if self.catchbreak: installHandler() if self.testRunner is None: self.testRunner = runner.TextTestRunner if isinstance(self.testRunner, type): try: try: testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer, warnings=self.warnings, tb_locals=self.tb_locals) except TypeError: # didn't accept the tb_locals argument testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer, warnings=self.warnings) except TypeError: # didn't accept the verbosity, buffer or failfast arguments testRunner = self.testRunner() else: # it is assumed to be a TestRunner instance testRunner = self.testRunner self.result = testRunner.run(self.test) if self.exit: sys.exit(not self.result.wasSuccessful()) main = TestProgram __init__.py000064400000007536151030032340006657 0ustar00""" Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework (used with permission). This module contains the core framework classes that form the basis of specific test cases and suites (TestCase, TestSuite etc.), and also a text-based utility class for running the tests and reporting the results (TextTestRunner). Simple usage: import unittest class IntegerArithmeticTestCase(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main() Further information is available in the bundled documentation, and from http://docs.python.org/library/unittest.html Copyright (c) 1999-2003 Steve Purcell Copyright (c) 2003-2010 Python Software Foundation This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. """ __all__ = ['TestResult', 'TestCase', 'IsolatedAsyncioTestCase', 'TestSuite', 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', 'expectedFailure', 'TextTestResult', 'installHandler', 'registerResult', 'removeResult', 'removeHandler', 'addModuleCleanup', 'doModuleCleanups', 'enterModuleContext'] # Expose obsolete functions for backwards compatibility # bpo-5846: Deprecated in Python 3.11, scheduled for removal in Python 3.13. __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) __unittest = True from .result import TestResult from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip, skipIf, skipUnless, expectedFailure, doModuleCleanups, enterModuleContext) from .suite import BaseTestSuite, TestSuite from .loader import TestLoader, defaultTestLoader from .main import TestProgram, main from .runner import TextTestRunner, TextTestResult from .signals import installHandler, registerResult, removeResult, removeHandler # IsolatedAsyncioTestCase will be imported lazily. from .loader import makeSuite, getTestCaseNames, findTestCases # deprecated _TextTestResult = TextTestResult # There are no tests here, so don't try to run anything discovered from # introspecting the symbols (e.g. FunctionTestCase). Instead, all our # tests come from within unittest.test. def load_tests(loader, tests, pattern): import os.path # top level directory cached on loader instance this_dir = os.path.dirname(__file__) return loader.discover(start_dir=this_dir, pattern=pattern) # Lazy import of IsolatedAsyncioTestCase from .async_case # It imports asyncio, which is relatively heavy, but most tests # do not need it. def __dir__(): return globals().keys() | {'IsolatedAsyncioTestCase'} def __getattr__(name): if name == 'IsolatedAsyncioTestCase': global IsolatedAsyncioTestCase from .async_case import IsolatedAsyncioTestCase return IsolatedAsyncioTestCase raise AttributeError(f"module {__name__!r} has no attribute {name!r}")