j fD@s\dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZmZmZmZdZdZGdd d eZGd d d eZGd d d eZGdddeZddZddZddZddZddZ GdddZ!ddZ"ddZ#Gd d!d!e!Z$Gd"d#d#e$Z%Gd$d%d%e$Z&e j'd&d'd(gZ(Gd)d*d*ej)Z*Gd+d,d,e!Z+Gd-d.d.eZ,Gd/d0d0e,Z-Gd1d2d2e,Z.dS)3zTest 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@seZdZdZdS)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__rr2/opt/alt/python34/lib64/python3.4/unittest/case.pyr s r c@seZdZdZdS) _ShouldStopz The test should stop. N)r r r r rrrrr!s rc@seZdZdZdS)_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! N)r r r r rrrrr&s rc@s7eZdZdddZejdddZdS)_OutcomeNcCsLd|_||_t|d|_d|_g|_d|_g|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessskippedexpectedFailureerrors)selfrrrr__init__-s     z_Outcome.__init__Fccs#|j}d|_zy dVWntk r5Yntk r~}z*d|_|jj|t|fWYdd}~Xntk rYnytj}|j r||_ nd|_|j j||fd}Yn,X|j r|jr|j j|dfnWd|jo||_XdS)NTF) rKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTestZ old_successer!rrrtestPartExecutor6s*     .      z_Outcome.testPartExecutor)r r r r contextlibcontextmanagerr%rrrrr,s  rcCs|S)Nr)objrrr_idTsr)csfdd}|S)z& Unconditionally skip a test. csOt|ts9tj|fdd}|}nd|_|_|S)NcstdS)N)r )argskwargs)reasonrr skip_wrapper]sz-skip..decorator..skip_wrapperT) isinstancetype functoolswraps__unittest_skip____unittest_skip_why__) test_itemr-)r,rr decorator[s !   zskip..decoratorr)r,r5r)r,rskipWs r6cCs|rt|StS)z/ Skip a test if the condition is true. )r6r)) conditionr,rrrskipIfgs r8cCs|st|StS)z3 Skip a test unless the condition is true. )r6r))r7r,rrr skipUnlessos r9cCs d|_|S)NT)__unittest_expecting_failure__)r4rrrrws rc@s(eZdZddZddZdS)_BaseTestCaseContextcCs ||_dS)N)r")rr"rrrr~sz_BaseTestCaseContext.__init__cCs.|jj|j|}|jj|dS)N)r"_formatMessagemsgfailureException)r standardMsgr=rrr _raiseFailuresz"_BaseTestCaseContext._raiseFailureN)r r r rr@rrrrr;|s  r;cCs!dtjkrt|StSdS)a Non-standard/downstream-only decorator for marking a specific unit test to be skipped when run within the %check of an rpmbuild. Specifically, this takes effect when WITHIN_PYTHON_RPM_BUILD is set within the environment, and has no effect otherwise. WITHIN_PYTHON_RPM_BUILDN)osenvironr6r))r,rrr_skipInRpmBuilds rDcs%tjfdd}|S)a  Non-standard/downstream-only decorator for marking a specific unit test as expected to fail within the %check of an rpmbuild. Specifically, this takes effect when WITHIN_PYTHON_RPM_BUILD is set within the environment, and has no effect otherwise. c sadtjkrPy||Wn$tk rFttjYnXtn ||dS)NrA)rBrC ExceptionZ_ExpectedFailurer r!r)r*r+)funcrrwrappers  z+_expectedFailureInRpmBuild..wrapper)r0r1)rFrGr)rFr_expectedFailureInRpmBuilds! rHc@s.eZdZddddZddZdS)_AssertRaisesBaseContextNc Cstj||||_||_|dk rey|j|_Wqntk rat||_YqnXn d|_|dk rtj |}n||_ d|_ dS)N) r;rexpectedr"r obj_nameAttributeErrorrrecompileexpected_regexr=)rrJr" callable_objrOrrrrs       z!_AssertRaisesBaseContext.__init__c CsC|dkr%|jdd|_|S||||WdQXdS)z If callable_obj is None, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If callable_obj is not None, call it passing args and kwargs. Nr=)popr=)rnamerPr*r+rrrhandles  z_AssertRaisesBaseContext.handle)r r r rrSrrrrrIs rIc@s.eZdZdZddZddZdS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.cCs|S)Nr)rrrr __enter__sz_AssertRaisesContext.__enter__c Cs|dkry|jj}Wn!tk r?t|j}YnX|jrh|jdj||jq|jdj|n tj|t ||jsdS|j d|_ |j dkrdS|j }|j t|s |jdj|jt|ndS)Nz{} not raised by {}z {} not raisedFTz"{}" does not match "{}")rJr rLrrKr@format traceback clear_frames issubclasswith_tracebackZ exceptionrOsearchpattern)rexc_type exc_valuetbexc_namerOrrr__exit__s(      z_AssertRaisesContext.__exit__N)r r r r rUrarrrrrTs  rTc@s.eZdZdZddZddZdS)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.cCsvx5tjjD]$}t|ddri|_qqWtjdd|_|jj|_tj d|j |S)N__warningregistry__recordTalways) r modulesvaluesgetattrrcwarningscatch_warningswarnings_managerrU simplefilterrJ)rvrrrrUsz_AssertWarnsContext.__enter__c Csp|jj||||dk r&dSy|jj}Wn!tk rYt|j}YnXd}x|jD]}|j}t||jsqjn|dkr|}n|j dk r|j j t| rqjn||_ |j |_ |j |_ dSW|dk r.|jdj|j jt|n|jrV|jdj||jn|jdj|dS)Nz"{}" does not match "{}"z{} not triggered by {}z{} not triggered)rkrarJr rLrrimessager.rOr[Zwarningfilenamelinenor@rVr\rK)rr]r^r_r`Zfirst_matchingmwrrrras8           z_AssertWarnsContext.__exit__N)r r r r rUrarrrrrbs  rb_LoggingWatcherrecordsoutputc@s:eZdZdZddZddZddZdS) _CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cCs&tjj|tgg|_dS)N)loggingHandlerrrswatcher)rrrrr(sz_CapturingHandler.__init__cCsdS)Nr)rrrrflush,sz_CapturingHandler.flushcCs9|jjj||j|}|jjj|dS)N)ryrtrrVru)rrdr=rrremit/sz_CapturingHandler.emitN)r r r r rrzr{rrrrrv#s   rvc@s@eZdZdZdZddZddZddZd S) _AssertLogsContextz:A context manager used to implement TestCase.assertLogs().z"%(levelname)s:%(name)s:%(message)scCsStj||||_|r:tjj|||_n tj|_d|_dS)N) r;r logger_namerwZ _nameToLevelgetlevelINFOr=)rr"r}rrrrr;s   z_AssertLogsContext.__init__cCst|jtjr(|j}|_ntj|j}|_tj|j}t}|j ||j |_ |j dd|_ |j |_|j|_|g|_ |j|j d|_|j S)NF)r.r}rwZLoggerloggerZ getLoggerZ FormatterLOGGING_FORMATrvZ setFormatterryhandlers old_handlersr old_level propagate old_propagatesetLevel)rrZ formatterZhandlerrrrrUDs       z_AssertLogsContext.__enter__cCs|j|j_|j|j_|jj|j|dk rAdSt|jj dkr|j dj t j |j|jjndS)NFrz-no logs of level {} or higher triggered on {})rrrrrrrlenryrtr@rVrwZ getLevelNamerrR)rr]r^r_rrrraUs z_AssertLogsContext.__exit__N)r r r r rrrUrarrrrr|6s  r|c@sMeZdZdZeZdZdZdZdZ dd d Z d d Z d dZ ddZ ddZeddZeddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zejd)d*d+Zd,d-Zd.d/Zd0d1Z d)d2d3Z!d4d5Z"d6d7Z#d8d9Z$d:d;Z%d)d<d=Z&d)d>d?Z'd)d@dAZ(dBdCZ)d)dDdEZ*d)dFdGZ+d)d)dHdIZ,dJdKZ-d)dLdMZ.d)dNdOZ/d)dPdQZ0d)d)d)dRdSZ1d)d)d)dTdUZ2d)d)dVdWZ3dXdYZ4d)dZd[Z5d)d\d]Z6d)d^d_Z7d)d`daZ8d)dbdcZ9d)dddeZ:d)dfdgZ;d)dhdiZ<d)djdkZ=d)dldmZ>d)dndoZ?d)dpdqZ@d)drdsZAd)dtduZBd)dvdwZCd)dxdyZDd)dzd{ZEd)d|d}ZFd)d~dZGd)ddZHd)ddZId)ddZJd)ddZKddZLeLe/ZMZNeLe0ZOZPeLe1ZQZReLe2ZSZTeLe(ZUZVeLe*ZWeLe'ZXeLeHZYeLeJZZd)S)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. TPFrunTestc Cs||_d|_d|_yt||}Wn:tk rj|dkrftd|j|fnYn X|j|_g|_d|_ i|_ |j t d|j t d|j td|j td|j td|j 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_testMethodDocrhrL ValueError __class__r _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictlisttupleset frozensetr)rZ methodName testMethodrrrrs&         zTestCase.__init__cCs||j|)rrr)rrrr__repr__szTestCase.__repr__cCsRt|dd}|dk r.|||n tjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reportedr)rhriwarnRuntimeWarning addSuccess)rrr"r,rrrr_addSkips    zTestCase._addSkipNcks|jjsdVdS|j}|dkr<tj|}n|jj|}t||||_zy|jj|jdd dVWdQX|jj s|jj }|dk r|j rt qn|jj rt nWd||_XdS)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. Nr#T)rrr collectionsChainMapparams new_child_SubTestr%rrZfailfastrr)rr=rparentZ params_maprrrrsubTests$         zTestCase.subTestcCsx|D]|\}}t|tr;|j|j||q|dk rt|d|jrp|j||q|j||qqWdS)Nr)r.rrr"rYr> addFailureZaddError)rrrtestr!rrr_feedErrorsToResult$s zTestCase._feedErrorsToResultc CsPy |j}Wn/tk r>tjdt|j|YnX|||dS)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerLrirrr)rrr!rrrr_addExpectedFailure.s   zTestCase._addExpectedFailurecCsxy |j}WnZtk ritjdty tdWn(tk rd|j|tjYnXYn X||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrLrirrrrr r!)rrrrrr_addUnexpectedSuccess8s      zTestCase._addUnexpectedSuccessc %Cs|}|dkrI|j}t|dd}|dk rI|qIn|j|t||j}t|jddst|ddrz>t|jddpt|dd}|j|||Wd|j|XdSt|dd}t|dd}|p|}t|} z*| |_| j ||j WdQX| j r|| _ | j |dd |WdQXd| _ | j ||j WdQXn|jx*| jD]\} } |j|| | qW|j|| j| j rC|r3| jr#|j|| jq@|j|qC|j|n|SWd|j||dkrt|d d} | dk r| qn| jjd| _d|_XdS) N startTestRunr2Fr3r:r#T stopTestRun)rrhZ startTestrrrZstopTestrrr%rrrr doCleanupsrrrrrrrclear) rrZ orig_resultrrZskip_whyZexpecting_failure_methodZexpecting_failure_classroutcomerr,rrrrrunGsh                       z TestCase.runc Csd|jpt}xH|jr\|jj\}}}|j||||WdQXqW|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrrQr%r)rrrr*r+rrrrs  zTestCase.doCleanupscOs|j||S)N)r)rr*kwdsrrr__call__szTestCase.__call__cCsc|jt||j|jx5|jr^|jjd\}}}|||q*WdS)z6Run the test without collecting errors in a TestResultrN)rrhrrrrQ)rrr*r+rrrdebugs    zTestCase.debugcCst|dS)zSkip this test.N)r )rr,rrrskipTestszTestCase.skipTestcCs|j|dS)z)Fail immediately, with the given message.N)r>)rr=rrrfailsz TestCase.failcCs8|r4|j|dt|}|j|ndS)z#Check that the expression is false.z%s is not falseN)r<rr>)rexprr=rrr assertFalseszTestCase.assertFalsecCs8|s4|j|dt|}|j|ndS)z"Check that the expression is true.z%s is not trueN)r<rr>)rrr=rrr assertTrueszTestCase.assertTruec Csh|js|p|S|dkr#|Syd||fSWn,tk rcdt|t|fSYnXdS)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=r?rrrr<s    zTestCase._formatMessagecOs(t|||}|jd|||S)a,Fail unless an exception of class excClass is raised by callableObj when invoked with arguments args and keyword arguments kwargs. 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 callableObj omitted or None, 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) assertRaises)rTrS)rZexcClassZ callableObjr*r+contextrrrrszTestCase.assertRaisescOs(t|||}|jd|||S)aFail unless a warning of class warnClass is triggered by callable_obj when invoked with arguments args and keyword arguments kwargs. 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 callable_obj omitted or None, 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) assertWarns)rbrS)rexpected_warningrPr*r+rrrrrszTestCase.assertWarnscCst|||S)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|)rrrrrr assertLogs szTestCase.assertLogscCskt|t|krd|jjt|}|dk rdt|tr]t||}n|Sn|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)r/rr~r.rrh_baseAssertEqual)rfirstsecondZasserterrrr_getAssertEqualityFunc s zTestCase._getAssertEqualityFunccCsG||ksCdt||}|j||}|j|ndS)z:The default assertEqual implementation, not type specific.z%s != %sN)rr<r>)rrrr=r?rrrr:s zTestCase._baseAssertEqualcCs)|j||}|||d|dS)z[Fail if the two objects are unequal as determined by the '==' operator. r=N)r)rrrr=Zassertion_funcrrr assertEqualAszTestCase.assertEqualcCsJ||ksF|j|dt|t|f}|j|ndS)zYFail if the two objects are equal as determined by the '!=' operator. z%s == %sN)r<rr>)rrrr=rrrassertNotEqualHs zTestCase.assertNotEqualcCs||krdS|dk r7|dk r7tdn|dk rt|||kr]dSdt|t|t|f}nW|dkrd}ntt|||dkrdSdt|t||f}|j||}|j|dS)aFail 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 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 signficant digit). If the two objects compare equal then they will automatically compare almost equal. Nz specify delta or places not bothz%s != %s within %s deltarz%s != %s within %r places) TypeErrorabsrroundr<r>)rrrplacesr=deltar?rrrassertAlmostEqualQs&         zTestCase.assertAlmostEqualcCs |dk r'|dk r'tdn|dk r||k rZt|||krZdSdt|t|t|f}nd|dkrd}n||k rtt|||dkrdSdt|t||f}|j||}|j|dS)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 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 signficant digit). Objects that are equal automatically fail. Nz specify delta or places not bothz%s == %s within %s deltarrz%s == %s within %r places)rrrrr<r>)rrrrr=rr?rrrassertNotAlmostEqualxs"  #    ,   zTestCase.assertNotAlmostEqualc&Cs|dk rz|j}t||sF|jd|t|fnt||s|jd|t|fqnd}d}yt|}Wn"ttfk rd|}YnX|dkryt|}Wqttfk rd|}YqXn|dkr%||krdSd|jft||}xt t ||D]} y|| } Wn0tt tfk r|d| |f7}PYnXy|| } Wn0tt tfk r|d | |f7}PYnX| | krQ|d | | | f7}PqQqQW||kr8|dkr8t |t |kr8dS||kr|d |||f7}y|d |||f7}Wq"tt tfk r|d ||f7}Yq"Xq%||kr%|d|||f7}y|d |||f7}Wq"tt tfk r|d||f7}Yq"Xq%n|} ddj tjtj|jtj|j} |j| | } |j|| }|j|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: %sZsequencez(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 r.r>rrrNotImplementedError capitalizerrangemin IndexErrorr/joindifflibndiffpprintpformat splitlines_truncateMessager<r)rZseq1Zseq2r=seq_typeZ seq_type_nameZ differingZlen1Zlen2iZitem1Zitem2r?diffMsgrrrassertSequenceEquals             zTestCase.assertSequenceEqualcCsA|j}|dks't||kr/||S|tt|S)N)maxDiffr DIFF_OMITTED)rrndiffZmax_diffrrrrs zTestCase._truncateMessagecCs|j|||dtdS)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)rZlist1Zlist2r=rrrrs zTestCase.assertListEqualcCs|j|||dtdS)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)rZtuple1Ztuple2r=rrrrs zTestCase.assertTupleEqualc Csy|j|}Wnktk rK}z|jd|WYdd}~Xn6tk r}z|jd|WYdd}~XnXy|j|}Wnktk r}z|jd|WYdd}~Xn6tk r}z|jd|WYdd}~XnX|p |sdSg}|rR|jdx$|D]}|jt|q2Wn|r|jdx$|D]}|jt|qlWndj|} |j|j|| 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) differencerrrLrreprrr<) rZset1Zset2r=Z difference1r$Z difference2linesitemr?rrrrs2 #$#$     zTestCase.assertSetEqualcCsH||krDdt|t|f}|j|j||ndS)zDJust like self.assertTrue(a in b), but with a nicer default message.z%s not found in %sN)rrr<)rmember containerr=r?rrrassertInDs  zTestCase.assertIncCsH||krDdt|t|f}|j|j||ndS)zHJust like self.assertTrue(a not in b), but with a nicer default message.z%s unexpectedly found in %sN)rrr<)rr r r=r?rrr assertNotInKs  zTestCase.assertNotIncCsH||k rDdt|t|f}|j|j||ndS)zDJust like self.assertTrue(a is b), but with a nicer default message.z %s is not %sN)rrr<)rexpr1expr2r=r?rrrassertIsRs  zTestCase.assertIscCs?||kr;dt|f}|j|j||ndS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: %sN)rrr<)rr rr=r?rrr assertIsNotYs zTestCase.assertIsNotcCs|j|td|j|td||krdt||}ddjtjtj|jtj|j}|j ||}|j |j ||ndS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryz%s != %sr) assertIsInstancerrrrrrrrrrr<)rZd1Zd2r=r?rrrrr_s zTestCase.assertDictEqualc Cs'tjdtg}g}xy|jD]k\}}||krQ|j|q)|||kr)|jdt|t|t||fq)q)W|p|sdSd}|rddjdd|D}n|r |r|d 7}n|d dj|7}n|j|j||dS) z2Checks whether dictionary is a superset of subset.z&assertDictContainsSubset is deprecatedz%s, expected: %s, actual: %sNrz Missing: %s,css|]}t|VqdS)N)r).0rqrrr ~sz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) rirDeprecationWarningitemsrrrrr<) rZsubsetZ dictionaryr=ZmissingZ mismatchedkeyvaluer?rrrassertDictContainsSubsetks,     z!TestCase.assertDictContainsSubsetc Cst|t|}}y"tj|}tj|}Wn!tk r^t||}Yn X||krodSt||}|rd}dd|D}dj|} |j|| }|j||}|j |ndS)aAn unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times. 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)rrrrr s z-TestCase.assertCountEqual..r) rrCounterrrrrrr<r) rrrr=Z first_seqZ second_seqZ differencesr?rrrrrassertCountEquals   zTestCase.assertCountEqualcCs>|j|td|j|td||kr:t||jks\t||jkrr|j|||n|jdd}|jdd}t|dkr|jd|kr|dg}|dg}ndt||}dd jt j ||}|j ||}|j |j ||nd S) z-Assert that two multi-line strings are equal.zFirst argument is not a stringzSecond argument is not a stringkeependsTrz rz%s != %srN)rrr_diffThresholdrrrrrrrrrr<)rrrr=Z firstlinesZ secondlinesr?rrrrrs ' zTestCase.assertMultiLineEqualcCsH||ksDdt|t|f}|j|j||ndS)zCJust like self.assertTrue(a < b), but with a nicer default message.z%s not less than %sN)rrr<)rabr=r?rrr assertLesss zTestCase.assertLesscCsH||ksDdt|t|f}|j|j||ndS)zDJust like self.assertTrue(a <= b), but with a nicer default message.z%s not less than or equal to %sN)rrr<)rrr r=r?rrrassertLessEquals zTestCase.assertLessEqualcCsH||ksDdt|t|f}|j|j||ndS)zCJust like self.assertTrue(a > b), but with a nicer default message.z%s not greater than %sN)rrr<)rrr r=r?rrr assertGreaters zTestCase.assertGreatercCsH||ksDdt|t|f}|j|j||ndS)zDJust like self.assertTrue(a >= b), but with a nicer default message.z"%s not greater than or equal to %sN)rrr<)rrr r=r?rrrassertGreaterEquals zTestCase.assertGreaterEqualcCs?|dk r;dt|f}|j|j||ndS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz%s is not None)rrr<)rr(r=r?rrr assertIsNones zTestCase.assertIsNonecCs2|dkr.d}|j|j||ndS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rr<)rr(r=r?rrrassertIsNotNones zTestCase.assertIsNotNonecCsEt||sAdt||f}|j|j||ndS)zTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.z%s is not an instance of %rN)r.rrr<)rr(rr=r?rrrrszTestCase.assertIsInstancecCsEt||rAdt||f}|j|j||ndS)z,Included for symmetry with assertIsInstance.z%s is an instance of %rN)r.rrr<)rr(rr=r?rrrassertNotIsInstanceszTestCase.assertNotIsInstancecOs+t||||}|jd|||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. callable_obj: Function to be called. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. args: Extra args. kwargs: Extra kwargs. assertRaisesRegex)rTrS)rZexpected_exceptionrOrPr*r+rrrrr(s  zTestCase.assertRaisesRegexcOs+t||||}|jd|||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. callable_obj: Function to be called. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. args: Extra args. kwargs: Extra kwargs. assertWarnsRegex)rbrS)rrrOrPr*r+rrrrr)s  zTestCase.assertWarnsRegexcCsnt|ttfr'tj|}n|j|sj|p?d}d||j|f}|j|ndS)z=Fail the test unless the text matches the regular expression.zRegex didn't matchz%s: %r not found in %rN)r.rbytesrMrNr[r\r>)rtextrOr=rrr assertRegexs  zTestCase.assertRegexcCst|ttfr'tj|}n|j|}|r|pEd}d|||j|j|j|f}|j |ndS)z9Fail the test if the text matches the regular expression.z Regex matchedz%s: %r matches %r in %rN) r.rr*rMrNr[startendr\r>)rr+Zunexpected_regexr=matchrrrassertNotRegex s  zTestCase.assertNotRegexcsfdd}|S)Ncs,tjdjjtd||S)NzPlease use {0} instead.r)rirrVr r)r*r+) original_funcrrdeprecated_func/s z,TestCase._deprecate..deprecated_funcr)r1r2r)r1r _deprecate.szTestCase._deprecateii)[r r r r AssertionErrorr>rrrZ_classSetupFailedrrrrr classmethodrrrrrrrrrrrr&r'rrrrrrrrrrrrr<rrrrrrrrrrrrrrr r rrrrrrr!r"r#r$r%r&rr'r(r)r,r0r3ZfailUnlessEqualZ assertEqualsZ failIfEqualZassertNotEqualsZfailUnlessAlmostEqualZassertAlmostEqualsZfailIfAlmostEqualZassertNotAlmostEqualsZ failUnlessZassert_ZfailUnlessRaisesZfailIfZassertRaisesRegexpZassertRegexpMatchesrrrrrbs              E     & c   + !     rcseZdZdZdddfddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ S)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|j||_||_||_||_dS)N)superr6r _setUpFunc _tearDownFunc _testFunc _description)rZtestFuncrrZ description)rrrrLs    zFunctionTestCase.__init__cCs |jdk r|jndS)N)r8)rrrrrSszFunctionTestCase.setUpcCs |jdk r|jndS)N)r9)rrrrrWszFunctionTestCase.tearDowncCs|jdS)N)r:)rrrrr[szFunctionTestCase.runTestcCs |jjS)N)r:r )rrrrr^szFunctionTestCase.idcCs\t||jstS|j|jko[|j|jko[|j|jko[|j|jkS)N)r.rrr8r9r:r;)rrrrrras zFunctionTestCase.__eq__cCs+tt||j|j|j|jfS)N)rr/r8r9r:r;)rrrrrjszFunctionTestCase.__hash__cCsdt|j|jjfS)Nz%s (%s))rrr:r )rrrrrnszFunctionTestCase.__str__cCsdt|j|jfS)Nz <%s tec=%s>)rrr:)rrrrrrszFunctionTestCase.__repr__cCsE|jdk r|jS|jj}|rA|jddjpDdS)Nrr)r;r:r rr)rrrrrrvs z!FunctionTestCase.shortDescription)r r r r rrrrrrrrrrrr)rrr6Cs        r6cs^eZdZfddZddZddZddZd d Zd d ZS) rcs8tj||_||_||_|j|_dS)N)r7r_messager"rr>)rr"rnr)rrrrs     z_SubTest.__init__cCstddS)Nzsubtests cannot be run directly)r)rrrrrsz_SubTest.runTestcCsg}|jr+|jdj|jn|jrxdjddt|jjD}|jdj|ndj|pdS)Nz[{}]z, css'|]\}}dj||VqdS)z{}={!r}N)rV)rkrmrrrrsz+_SubTest._subDescription..z({}) z ())r<rrVrrsortedr)rpartsZ params_descrrr_subDescriptions   z_SubTest._subDescriptioncCsdj|jj|jS)Nz{} {})rVr"rrA)rrrrrsz _SubTest.idcCs |jjS)zlReturns a one-line description of the subtest, or None if no description has been provided. )r"r)rrrrrsz_SubTest.shortDescriptioncCsdj|j|jS)Nz{} {})rVr"rA)rrrrrsz_SubTest.__str__) r r r rrrArrrrr)rrr}s    r)/r r r0rrBrwrrMrirr&rWrrutilrrrrrZ __unittestrrEr rrobjectrr)r6r8r9rr;rDrHrIrTrb namedtuplersrxrvr|rr6rrrrrsP           ((       "2 ,: