o w[eP@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZmZmZmZdZeZdZGdd d eZGd d d eZGd d d eZGdddeZddZgZddZddZddZ ddZ!ddZ"ddZ#ddZ$Gd d!d!Z%Gd"d#d#e%Z&Gd$d%d%e&Z'Gd&d'd'e&Z(Gd(d)d)ej)Z*Gd*d+d+eZ+Gd,d-d-e+Z,Gd.d/d/e+Z-dS)0zTest 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.c@eZdZdZdS)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__rr$/usr/lib/python3.10/unittest/case.pyr r c@r ) _ShouldStopz The test should stop. Nr rrrrr!rrc@r )_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! Nr rrrrr&rrc@s&eZdZdddZejdddZdS) _OutcomeNcCs4d|_||_t|d|_d|_g|_d|_g|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessskippedexpectedFailureerrors)selfrrrr__init__-s  z_Outcome.__init__Fc cs|j}d|_zgzdVWnJtyty3}zd|_|j|t|fWYd}~n7d}~wty;Yn+t}|j rI||_ n d|_|j ||fd}Yn|j rf|jrf|j |dfW|jok||_dS|jos||_w)NTF) rKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTest old_successer$rrrtestPartExecutor6s0     z_Outcome.testPartExecutorN)F)r r rr contextlibcontextmanagerr)rrrrr,s  rcC|Sr*r)objrrr_idTr/cOst|||fdS)znSame as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule).N)_module_cleanupsr!)functionargskwargsrrraddModuleCleanupYsr5c Cslg}tr.t\}}}z ||i|Wnty+}z ||WYd}~nd}~wwts|r4|ddS)zWExecute all module cleanup functions. Normally called for you after tearDownModule.Nr)r1pop Exceptionr!) exceptionsr2r3r4excrrrdoModuleCleanups_sr:cs,fdd}ttjr}d||S|S)z& Unconditionally skip a test. cs4t|tst|fdd}|}d|_|_|S)Ncstr*r r3r4reasonrr skip_wrapperuz-skip..decorator..skip_wrapperT) isinstancetype functoolswraps__unittest_skip____unittest_skip_why__) test_itemr?r=rr decoratorss zskip..decorator)rAtypes FunctionType)r>rHrGrr=rskipos  rLcCs|rt|StS)z/ Skip a test if the condition is true. rLr/ conditionr>rrrskipIfrPcCs|st|StS)z3 Skip a test unless the condition is true. rMrNrrr skipUnlessrQrRcCs d|_|S)NT)__unittest_expecting_failure__)rGrrrrsrcs4t|trtfdd|DSt|tot|S)Nc3s|]}t|VqdSr*) _is_subtype).0r(basetyperr sz_is_subtype..)rAtupleallrB issubclass)expectedrWrrVrrTs rTc@seZdZddZddZdS)_BaseTestCaseContextcCs ||_dSr*)r%)rr%rrrr z_BaseTestCaseContext.__init__cCs|j|j|}|j|r*)r%_formatMessagemsgfailureException)r standardMsgr`rrr _raiseFailures z"_BaseTestCaseContext._raiseFailureN)r r rrrcrrrrr]s r]c@seZdZdddZddZdS)_AssertRaisesBaseContextNcCs@t||||_||_|durt|}||_d|_d|_dSr*) r]rr\r%recompileexpected_regexobj_namer`)rr\r%rgrrrrs   z!_AssertRaisesBaseContext.__init__cCszgt|j|jstd||jf|s,|dd|_|r'tdtt|f|Wd}S|^}}z|j |_ Wnt yDt ||_ Ynw|||i|Wdn 1sYwYWd}dSWd}dSd}w)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%s() arg 1 must be %sr`Nz3%r is an invalid keyword argument for this function) rTr\ _base_type TypeError_base_type_strr6r`nextiterr rhAttributeErrorr")rnamer3r4 callable_objrrrhandles2    z_AssertRaisesBaseContext.handler*)r r rrrqrrrrrds  rdc@s2eZdZdZeZdZddZddZe e j Z dS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typescCr-r*rrrrr __enter__r0z_AssertRaisesContext.__enter__cCs|dur0z|jj}Wntyt|j}Ynw|jr'|d||jn|d|nt|t ||js=dS| d|_ |j durJdS|j }| t|s`|d|jt|dS)Nz{} not raised by {}z {} not raisedFT"{}" does not match "{}")r\r rnr"rhrcformat traceback clear_framesr[with_traceback exceptionrgsearchpattern)rexc_type exc_valuetbexc_namergrrr__exit__s.        z_AssertRaisesContext.__exit__N) r r rr BaseExceptionrirkrtr classmethodrJ GenericAlias__class_getitem__rrrrrrsrrc@s(eZdZdZeZdZddZddZdS)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.z(a warning type or tuple of warning typescCsRttjD] }t|ddri|_qtjdd|_|j |_t d|j |S)N__warningregistry__T)recordalways) listr#modulesvaluesgetattrrwarningscatch_warningswarnings_managerrt simplefilterr\)rvrrrrts  z_AssertWarnsContext.__enter__cCs|j||||durdSz|jj}Wnty"t|j}Ynwd}|jD]-}|j}t||js4q(|dur:|}|j durH|j t|sHq(||_ |j |_ |j |_ dS|durg|d|j jt||jrv|d||jdS|d|dS)Nruz{} not triggered by {}z{} not triggered)rrr\r rnr"rmessagerArgr{warningfilenamelinenorcrvr|rh)rr}r~rrfirst_matchingmwrrrrs@        z_AssertWarnsContext.__exit__N) r r rrWarningrirkrtrrrrrrs  rc@seZdZddZdS)_OrderedChainMapccs:t}|jD]}|D]}||vr|||Vq qdSr*)setmapsadd)rseenmappingkrrr__iter__+s  z_OrderedChainMap.__iter__N)r r rrrrrrr*s rcs2eZdZdZeZdZdZdZfddZ ddd Z d d Z d d Z e ddZddZddZe ddZe ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zejefd*d+Zd,d-Z d.d/Z!d0d1Z"d2d3Z#d4d5Z$d6d7Z%d8d9Zⅆd<Z'd=d>Z(e d?d@Z)dAdBZ*dCdDZ+dEdFZ,ddGdHZ-ddIdJZ.ddKdLZ/dMdNZ0dOdPZ1dQdRZ2ddSdTZ3ddUdVZ4dWdXZ5ddYdZZ6dd[d\Z7dd]d^Z8 : :dd_d`Z9 : :ddadbZ:ddcddZ;dedfZddkdlZ?ddmdnZ@ddodpZAddqdrZBddsdtZCddudvZDddwdxZEddydzZFdd{d|ZGdd}d~ZHdddZIdddZJdddZKdddZLdddZMdddZNdddZOddZPddZQdddZRdddZSddZTeTe7ZUZVeTe8ZWZXeTe9ZYZZeTe:Z[Z\eTe/Z]Z^eTe1Z_eTe.Z`eTePZaeTeRZbeTeSZcZdS)TestCaseaWA 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. Tiics"d|_g|_tj|i|dS)NF)_classSetupFailed_class_cleanupssuper__init_subclass__)clsr3r4 __class__rrr_szTestCase.__init_subclass__runTestcCs||_d|_d|_zt||}Wnty&|dkr$td|j|fYnw|j|_g|_d|_ i|_ | t d| t d| td| td| td| td 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 %s: %sassertDictEqualassertListEqualassertTupleEqualassertSetEqualassertMultiLineEqual)_testMethodName_outcome_testMethodDocrrn ValueErrorrr _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictrrYr frozensetr")r methodName testMethodrrrres,      zTestCase.__init__cCs||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)rtypeobjr2rrrrs zTestCase.addTypeEqualityFunccO|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)rr!rr2r3r4rrr addCleanupszTestCase.addCleanupcOr)zpSame as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).N)rr!rr2r3r4rrraddClassCleanupszTestCase.addClassCleanupcCdS)zAHook method for setting up the test fixture before exercising it.NrrsrrrsetUpzTestCase.setUpcCr)zAHook method for deconstructing the test fixture after testing it.NrrsrrrtearDownrzTestCase.tearDowncCr)zKHook method for setting up class fixture before running tests in the class.Nrrrrr setUpClasszTestCase.setUpClasscCr)zVHook method for deconstructing the class fixture after running all tests in the class.Nrrrrr tearDownClassrzTestCase.tearDownClasscCr)NrrrsrrrcountTestCasesr0zTestCase.countTestCasescCstSr*)r TestResultrsrrrdefaultTestResultzTestCase.defaultTestResultcCs$|j}|r|ddSdS)zReturns 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.  rN)rstripsplitrdocrrrshortDescriptionszTestCase.shortDescriptioncCdt|j|jfS)Nz%s.%srrrrsrrridz TestCase.idcCs t|t|ur tS|j|jkSr*)rBNotImplementedrrotherrrr__eq__s zTestCase.__eq__cCstt||jfSr*)hashrBrrsrrr__hash__zTestCase.__hash__cCsd|jt|jfSNz%s (%s))rrrrsrrr__str__rzTestCase.__str__cCr)Nz<%s testMethod=%s>rrsrrr__repr__szTestCase.__repr__cCs>t|dd}|dur|||dStdtd||dS)NaddSkipz4TestResult has no addSkip method, skips not reported)rrwarnRuntimeWarning addSuccess)rrr%r>rrrr_addSkips zTestCase._addSkipcks|jdus |jjsdVdS|j}|durt|}n|j|}t||||_z@|jj|jdd dVWdn1s@wY|jjsW|jj }|durV|j rVt n |jj r]t W||_dSW||_dS||_w)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. NTr&) rrrrparams new_child_SubTestr)rrfailfastrr)rr`rparent params_maprrrrsubTests0   zTestCase.subTestcCs`|D]+\}}t|tr||j||q|dur-t|d|jr'|||q|||qdS)Nr)rArrr%r[ra addFailureaddError)rrrtestr$rrr_feedErrorsToResults   zTestCase._feedErrorsToResultcCsDz|j}Wntytdt||YdSw|||dS)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurernrrrr)rrr$rrrr_addExpectedFailures  zTestCase._addExpectedFailurec Cs`z|j}Wn$ty)tdtztdty(||tYYdSww||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrnrrrrrr#r$)rrrrrr_addUnexpectedSuccesss    zTestCase._addUnexpectedSuccesscC |dSr*)rrsrrr _callSetUp! zTestCase._callSetUpcCs |dSr*r)rmethodrrr_callTestMethod$r^zTestCase._callTestMethodcCrr*)rrsrrr _callTearDown'rzTestCase._callTearDowncOs||i|dSr*rrrrr _callCleanup*rzTestCase._callCleanupNc Csh|dur|}t|dd}t|dd}|dur|nd}||zt||j}t|jdds8t|ddr\t|jddpDt|dd}|||||W|||dur[|SSt|ddpgt|dd}t|}z||_| | | Wdn1swY|j r||_ |j |dd  | |Wdn1swYd|_ | | |Wdn1swY||jD] \}} |||| q|||j|j r|r|jr|||jn ||n|||W|jd|_d|_W|||dur|SS|jd|_d|_w|||dur3|ww) N startTestRun stopTestRunrEFrFrIrSTr)rr startTestrrrstopTestrrr)rrrrr doCleanupsrrrrrrrclear) rrrrrskip_whyroutcomerr>rrrrun-s       ,              z TestCase.runcCsp|jpt}|jr5|j\}}}|||j|g|Ri|Wdn1s-wY|js |jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrr6r)rr)rrr2r3r4rrrrps  zTestCase.doCleanupscCs`g|_|jr.|j\}}}z ||i|Wnty(|jtYnw|jsdSdS)zYExecute all class cleanup functions. Normally called for you after tearDownClass.N)tearDown_exceptionsrr6r7r!r#r$rrrrdoClassCleanups}s zTestCase.doClassCleanupscOs|j|i|Sr*)r)rr3kwdsrrr__call__szTestCase.__call__cCst||j}t|jddst|ddr$t|jddpt|dd}t||||||jrM|j\}}}|j |g|Ri||js4dSdS)z6Run the test without collecting errors in a TestResultrEFrFrIN) rrrr rrrrr6r)rrrr2r3r4rrrdebugs    zTestCase.debugcCst|)zSkip this test.r;)rr>rrrskipTestr@zTestCase.skipTestcCs ||)z)Fail immediately, with the given message.)ra)rr`rrrfails z TestCase.failcCs&|r||dt|}||dS)z#Check that the expression is false.z%s is not falseNr_rrarexprr`rrr assertFalse zTestCase.assertFalsecCs&|s||dt|}||dS)z"Check that the expression is true.z%s is not trueNrrrrr assertTruerzTestCase.assertTruecCsP|js|p|S|dur |Szd||fWSty'dt|t|fYSw)aHonour 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 Nz%s : %s) longMessageUnicodeDecodeErrorr)rr`rbrrrr_s  zTestCase._formatMessagecOs&t||}z |d||Wd}Sd}w)a=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) assertRaisesNrrrq)rexpected_exceptionr3r4contextrrrrs  zTestCase.assertRaisescOst||}|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) assertWarnsrrq)rexpected_warningr3r4rrrrrs zTestCase.assertWarnscCddlm}||||ddS)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_logr!rloggerlevelr!rrr assertLogss zTestCase.assertLogscCr)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. rr Tr"r$r&rrr assertNoLogss zTestCase.assertNoLogscCsFt|t|ur |jt|}|dur 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. N)rBrgetrAr"r_baseAssertEqual)rfirstsecondasserterrrr_getAssertEqualityFunc's  zTestCase._getAssertEqualityFunccCs0||ksdt||}|||}||dS)z:The default assertEqual implementation, not type specific.%s != %sN)rr_ra)rr-r.r`rbrrrr,As   zTestCase._baseAssertEqualcCs|||}||||ddS)z[Fail if the two objects are unequal as determined by the '==' operator. )r`N)r0)rr-r.r`assertion_funcrrr assertEqualHs zTestCase.assertEqualcCs2||ks||dt|t|f}||dS)zYFail if the two objects are equal as determined by the '!=' operator. z%s == %sNr)rr-r.r`rrrassertNotEqualOs  zTestCase.assertNotEqualcCs||krdS|dur|durtdt||}|dur3||kr"dSdt|t|t|t|f}n|dur9d}t||dkrBdSdt|t||t|f}|||}||)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(%s != %s within %s delta (%s difference)rz)%s != %s within %r places (%s difference)rjabsrroundr_rarr-r.placesr`deltadiffrbrrrassertAlmostEqualXs4   zTestCase.assertAlmostEqualcCs|dur |dur tdt||}|dur1||ks ||kr dSdt|t|t|t|f}n|dur7d}||ksDt||dkrDdSdt|t||f}|||}||)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. Nr5z(%s == %s within %s delta (%s difference)r6rz%s == %s within %r placesr7r:rrrassertNotAlmostEquals,    zTestCase.assertNotAlmostEqualc Cs|dur(|j}t||s|d|t|ft||s'|d|t|fnd}d}zt|}WnttfyAd|}Ynw|dur\zt|}Wnttfy[d|}Ynw|dur?||krgdSd|ft||}t t ||D]L} z|| } Wntt tfy|d| |f7}YnBwz|| } Wntt tfy|d | |f7}Yn&w| | kr|d | ft| | 7}nqz||kr|durt |t |krdS||kr |d |||f7}z|d |t||f7}WnHtt tfy |d ||f7}Yn4w||kr?|d|||f7}z|d |t||f7}Wntt tfy>|d||f7}Ynw|} dd tt|t|} || | } ||| }||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 %s: %szSecond sequence is not a %s: %ssequencez(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 rArarlenrjNotImplementedError capitalizerrangemin IndexErrorrBjoindifflibndiffpprintpformat splitlines_truncateMessager_r)rseq1seq2r`seq_type seq_type_name differinglen1len2iitem1item2rbdiffMsgrrrassertSequenceEquals                    zTestCase.assertSequenceEqualcCs2|j}|dus t||kr||S|tt|Sr*)maxDiffrA DIFF_OMITTED)rrr=max_diffrrrrM szTestCase._truncateMessagecC|j|||tddS)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. rPN)rYr)rlist1list2r`rrrrs zTestCase.assertListEqualcCr])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. r^N)rYrY)rtuple1tuple2r`rrrrs zTestCase.assertTupleEqualc Cs`z||}Wn1ty }z |d|WYd}~nd}~wty8}z |d|WYd}~nd}~wwz||}Wn1tyY}z |d|WYd}~nd}~wtyq}z |d|WYd}~nd}~ww|sx|sxdSg}|r|d|D] }|t|q|r|d|D] }|t|qd|} |||| 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) differencerjrrnr!reprrGr_) rset1set2r` difference1r( difference2linesitemrbrrrr(s>    zTestCase.assertSetEqualcCs6||vrdt|t|f}||||dSdS)zDJust like self.assertTrue(a in b), but with a nicer default message.z%s not found in %sNrrr_rmember containerr`rbrrrassertInS zTestCase.assertIncCs6||vrdt|t|f}||||dSdS)zHJust like self.assertTrue(a not in b), but with a nicer default message.z%s unexpectedly found in %sNrkrlrrr assertNotInZrpzTestCase.assertNotIncCs6||urdt|t|f}||||dSdS)zDJust like self.assertTrue(a is b), but with a nicer default message.z %s is not %sNrkrexpr1expr2r`rbrrrassertIsarpzTestCase.assertIscCs0||urdt|f}||||dSdS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: %sNrkrrrrr assertIsNothzTestCase.assertIsNotc Cs||td||td||kr?dt||}ddtt|t|}| ||}| | ||dSdS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryr1r) assertIsInstancerrrGrHrIrJrKrLrMrr_)rd1d2r`rbr=rrrrns    zTestCase.assertDictEqualc Cstjdtddg}g}|D]&\}}||vr||q|||kr6|dt|t|t||fq|s=|s=dSd}|rMddd d |D}|r^|rU|d 7}|d d|7}||||dS) z2Checks whether dictionary is a superset of subset.z&assertDictContainsSubset is deprecatedr) stacklevelz%s, expected: %s, actual: %sNrIz Missing: %s,css|]}t|VqdSr*)r)rUrrrrrXsz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) rrDeprecationWarningitemsr!rrGrr_) rsubset dictionaryr`missing mismatchedkeyvaluerbrrrassertDictContainsSubsetzs8      z!TestCase.assertDictContainsSubsetc Cst|t|}}z t|}t|}Wnty#t||}Yn w||kr*dSt||}|rRd}dd|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: cSsg|]}d|qS)z First has %d, Second has %d: %rr)rUr=rrr sz-TestCase.assertCountEqual..r) r collectionsCounterrjrrrGrMr_r) rr-r.r` first_seq second_seq differencesrbrirXrrrassertCountEquals$       zTestCase.assertCountEqualcCs||td||td||krmt||jks t||jkr'|||||jdd}|jdd}t|dkrJ|d|krJ|dg}|dg}dt||}dd t ||}| ||}| | ||d Sd S) z-Assert that two multi-line strings are equal.zFirst argument is not a stringzSecond argument is not a stringT)keependsrz rr1rIN)rxr"rA_diffThresholdr,rLrrrGrHrIrMrr_)rr-r.r` firstlines secondlinesrbr=rrrrs      zTestCase.assertMultiLineEqualcCs6||ksdt|t|f}||||dSdS)zCJust like self.assertTrue(a < b), but with a nicer default message.z%s not less than %sNrkrabr`rbrrr assertLesszTestCase.assertLesscCs6||ksdt|t|f}||||dSdS)zDJust like self.assertTrue(a <= b), but with a nicer default message.z%s not less than or equal to %sNrkrrrrassertLessEqualrzTestCase.assertLessEqualcCs6||ksdt|t|f}||||dSdS)zCJust like self.assertTrue(a > b), but with a nicer default message.z%s not greater than %sNrkrrrr assertGreaterrzTestCase.assertGreatercCs6||ksdt|t|f}||||dSdS)zDJust like self.assertTrue(a >= b), but with a nicer default message.z"%s not greater than or equal to %sNrkrrrrassertGreaterEqualrzTestCase.assertGreaterEqualcCs0|durdt|f}||||dSdS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz%s is not Nonerkrr.r`rbrrr assertIsNonerwzTestCase.assertIsNonecCs&|durd}||||dSdS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rr_rrrrassertIsNotNoneszTestCase.assertIsNotNonecCs4t||sdt||f}||||dSdS)zTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.z%s is not an instance of %rNrArrr_rr.rr`rbrrrrxs zTestCase.assertIsInstancecCs4t||rdt||f}||||dSdS)z,Included for symmetry with assertIsInstance.z%s is an instance of %rNrrrrrassertNotIsInstances zTestCase.assertNotIsInstancecOt|||}|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)rrrgr3r4rrrrrs zTestCase.assertRaisesRegexcOr)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. assertWarnsRegexr)rrrgr3r4rrrrr s zTestCase.assertWarnsRegexcCsVt|ttfr|s Jdt|}||s)d|j|f}|||}||dS)z=Fail the test unless the text matches the regular expression.z!expected_regex must not be empty.z&Regex didn't match: %r not found in %rN) rAr"bytesrerfr{r|r_ra)rtextrgr`rbrrr assertRegex s     zTestCase.assertRegexcCs`t|ttfr t|}||}|r.d||||j|f}| ||}| |dS)z9Fail the test if the text matches the regular expression.z"Regex matched: %r matches %r in %rN) rAr"rrerfr{startendr|r_ra)rrunexpected_regexr`matchrbrrrassertNotRegex,s    zTestCase.assertNotRegexcsfdd}|S)Ncs$tdjtd|i|S)NzPlease use {0} instead.r)rrrvr r}r< original_funcrrdeprecated_func<s  z,TestCase._deprecate..deprecated_funcr)rrrrr _deprecate;s zTestCase._deprecate)rr*)NNNNN)er r rrAssertionErrorrarrZrrrrrrrrrrrrrrrrrrrrr+r,_subtest_msg_sentinelrrrrrrrrrrr r r rrrrr_rrr)r*r0r,r3r4r>r?rYrMrrrrorqrurvrrrrrrrrrrrxrrrrrrfailUnlessEqual assertEquals failIfEqualassertNotEqualsfailUnlessAlmostEqualassertAlmostEqualsfailIfAlmostEqualassertNotAlmostEquals failUnlessassert_failUnlessRaisesfailIfassertRaisesRegexpassertRegexpMatchesassertNotRegexpMatches __classcell__rrrrr4s            C     !       - #c  +                   rcsjeZdZdZdfdd ZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ZS)FunctionTestCaseaIA 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. Ncs*tt|||_||_||_||_dSr*)rrr _setUpFunc _tearDownFunc _testFunc _description)rtestFuncrr descriptionrrrrZs  zFunctionTestCase.__init__cC|jdur |dSdSr*)rrsrrrra  zFunctionTestCase.setUpcCrr*)rrsrrrrerzFunctionTestCase.tearDowncCrr*)rrsrrrrirzFunctionTestCase.runTestcCs|jjSr*)rr rsrrrrlrzFunctionTestCase.idcCs@t||jstS|j|jko|j|jko|j|jko|j|jkSr*)rArrrrrrrrrrros     zFunctionTestCase.__eq__cCstt||j|j|j|jfSr*)rrBrrrrrsrrrrxszFunctionTestCase.__hash__cCsdt|j|jjfSr)rrrr rsrrrr|s zFunctionTestCase.__str__cCr)Nz <%s tec=%s>)rrrrsrrrrs zFunctionTestCase.__repr__cCs2|jdur|jS|jj}|r|ddpdS)Nrr)rrrrrrrrrrs z!FunctionTestCase.shortDescriptionr)r r rrrrrrrrrrrrrrrrrrQs rcsDeZdZfddZddZddZddZd d Zd d ZZ S) rcs(t||_||_||_|j|_dSr*)rr_messager%rra)rr%rrrrrrs  z_SubTest.__init__cCstd)Nzsubtests cannot be run directly)rBrsrrrrrz_SubTest.runTestcCs^g}|jtur|d|j|jr(ddd|jD}|d|d|p.dS)Nz[{}]z, css |] \}}d||VqdS)z{}={!r}N)rv)rUrrrrrrXs  z+_SubTest._subDescription..z({}) z ())rrr!rvrrGr~)rparts params_descrrr_subDescriptions  z_SubTest._subDescriptioncCsd|j|SNz{} {})rvr%rrrsrrrrsz _SubTest.idcCs |jS)zlReturns a one-line description of the subtest, or None if no description has been provided. )r%rrsrrrrs z_SubTest.shortDescriptioncCsd|j|Sr)rvr%rrsrrrrrz_SubTest.__str__) r r rrrrrrrrrrrrrs  r).rr#rCrHrJrerrr+rwrJrIrutilrrrrr __unittestobjectrr[r7r rrrr/r1r5r:rLrPrRrrTr]rdrrrChainMaprrrrrrrrsZ ( *'4 %: