3 y^c@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZmZmZmZdZeZdZGdd d eZGd d d eZGd d d eZGdddeZddZddZddZddZ ddZ!ddZ"GdddZ#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@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/lib64/python3.6/unittest/case.pyr sr c@r) _ShouldStopz The test should stop. Nr rrrrr"rc@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_failurerZhasattrresult_supports_subtestssuccessskippedexpectedFailureerrors)selfrrrr__init__.s z_Outcome.__init__Fccs|j}d|_zy dVWntk r.Yntk rh}z d|_|jj|t|fWYdd}~Xnjtk rzYnXtj}|j r||_ nd|_|j j||fd}YnX|j r|jr|j j|dfWd|jo||_XdS)NTF) rZKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTestZ old_successer!rrrtestPartExecutor7s* $  z_Outcome.testPartExecutorN)F)r r r r contextlibcontextmanagerr%rrrrr-s rcC|Sr&r)objrrr_idUr+cfdd}|S)z& Unconditionally skip a test. cs4t|ts$tj|fdd}|}d|_|_|S)Ncs tdSr&r argskwargsreasonrr skip_wrapper^z-skip..decorator..skip_wrapperT) isinstancetype functoolsZwraps__unittest_skip____unittest_skip_why__) test_itemr4r2rr decorator\s  zskip..decoratorr)r3r<rr2rskipXs r=cCs|r t|StS)z/ Skip a test if the condition is true. r=r+Z conditionr3rrrskipIfhr@cCs|s t|StS)z3 Skip a test unless the condition is true. r>r?rrr skipUnlessprArBcCs d|_|S)NT)__unittest_expecting_failure__)r;rrrrxsrcs4t|tr tfdd|DSt|to2t|S)Nc3s|]}t|VqdSr&) _is_subtype).0r$basetyperr ~z_is_subtype..)r6tupleZallr7 issubclass)expectedrGrrFrrD|s rDc@seZdZddZddZdS)_BaseTestCaseContextcCs ||_dSr&)r")rr"rrrrr,z_BaseTestCaseContext.__init__cCs |jj|j|}|jj|dSr&)r"_formatMessagemsgfailureException)r standardMsgrOrrr _raiseFailurez"_BaseTestCaseContext._raiseFailureN)r r r rrRrrrrrMsrMcCsdtjkrt|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. ZWITHIN_PYTHON_RPM_BUILDN)osZenvironr=r+r2rrr_skipInRpmBuilds rUc@seZdZdddZddZdS)_AssertRaisesBaseContextNcCs@tj||||_||_|dk r*tj|}||_d|_d|_dSr&) rMrrLr"recompileexpected_regexobj_namerO)rrLr"rYrrrrs  z!_AssertRaisesBaseContext.__init__cCszt|j|js"td||jf|rD|ddkrDtjdtdf}|sx|jdd|_ |rttjdt t |td|S|^}}y |j |_ Wntk rt||_ YnX||||WdQRXWdd}XdS)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 %srNzcallable is NoneirOz3%r is an invalid keyword argument for this function)rDrL _base_type TypeError_base_type_strwarningswarnDeprecationWarningpoprOZnextZiterr rZAttributeErrorr)rnamer0r1Z callable_objrrrhandles.  z_AssertRaisesBaseContext.handler&)r r r rrdrrrrrVs rVc@(eZdZdZeZdZddZddZdS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typescCr)r&rrrrr __enter__r,z_AssertRaisesContext.__enter__c Cs|dkrby |jj}Wntk r2t|j}YnX|jrP|jdj||jql|jdj|n tj|t ||js|dS|j d|_ |j dkrdS|j }|j t|s|jdj|jt|dS)Nz{} not raised by {}z {} not raisedFT"{}" does not match "{}")rLr rbrrZrRformat tracebackZ clear_framesrKZwith_tracebackZ exceptionrYsearchpattern)rexc_type exc_valuetbexc_namerYrrr__exit__s(       z_AssertRaisesContext.__exit__N) r r r rZ BaseExceptionr[r]rhrrrrrrrfs rfc@re)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.z(a warning type or tuple of warning typescCsRx$tjjD]}t|ddr i|_q Wtjdd|_|jj|_tj d|j |S)N__warningregistry__T)recordZalways) r ZmodulesZvaluesgetattrrtr^Zcatch_warningswarnings_managerrhZ simplefilterrL)rvrrrrhs   z_AssertWarnsContext.__enter__c Cs|jj||||dk rdSy |jj}Wntk rFt|j}YnXd}xd|jD]Z}|j}t||jslqT|dkrx|}|j dk r|j j t| rqT||_ |j |_ |j |_ dSW|dk r|jdj|j jt||jr|jdj||jn|jdj|dS)Nriz{} not triggered by {}z{} not triggered)rwrrrLr rbrr^messager6rYrlZwarningZfilenameZlinenorRrjrmrZ)rrnrorprqZfirst_matchingmZwrrrrrs8      z_AssertWarnsContext.__exit__N) r r r rZWarningr[r]rhrrrrrrrss  rs_LoggingWatcherrecordsoutputc@s(eZdZdZddZddZddZdS) _CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cCstjj|tgg|_dSr&)loggingHandlerrr{watcherrgrrrr,s z_CapturingHandler.__init__cCsdSr&rrgrrrflush0r,z_CapturingHandler.flushcCs*|jjj||j|}|jjj|dSr&)rr|rrjr})rrurOrrremit3s z_CapturingHandler.emitN)r r r rrrrrrrrr~'sr~c@s,eZdZdZdZddZddZddZd S) _AssertLogsContextz:A context manager used to implement TestCase.assertLogs().z"%(levelname)s:%(name)s:%(message)scCs:tj||||_|r(tjj|||_ntj|_d|_dSr&) rMr logger_namerZ _nameToLevelgetlevelZINFOrO)rr"rrrrrr?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)r6rrZLoggerloggerZ getLoggerZ FormatterLOGGING_FORMATr~Z setFormatterrhandlers old_handlersr old_level propagate old_propagatesetLevel)rrZ formatterZhandlerrrrrhHs   z_AssertLogsContext.__enter__cCs`|j|j_|j|j_|jj|j|dk r.dSt|jj dkr\|j dj t j |j|jjdS)NFrz-no logs of level {} or higher triggered on {})rrrrrrrlenrr|rRrjrZ getLevelNamerrc)rrnrorprrrrrYs  z_AssertLogsContext.__exit__N)r r r rrrrhrrrrrrr:s  rc@seZdZdZeZdZdZdZdZ dd d Z d d Z d dZ ddZ ddZeddZeddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zejefd)d*Zd+d,Zd-d.Z d/d0Z!dd2d3Z"d4d5Z#d6d7Z$d8d9Z%d:d;Z&ddd?Z(dd@dAZ)dBdCZ*dDdEZ+dFdGZ,ddHdIZ-dJdKZ.ddLdMZ/ddNdOZ0ddPdQZ1ddRdSZ2ddTdUZ3ddVdWZ4dXdYZ5ddZd[Z6dd\d]Z7dd^d_Z8dd`daZ9ddbdcZ:ddddeZ;ddfdgZddldmZ?ddndoZ@ddpdqZAddrdsZBddtduZCddvdwZDddxdyZEddzd{ZFdd|d}ZGdd~dZHddZIddZJdddZKdddZLddZMeMe0ZNZOeMe1ZPZQeMe2ZRZSeMe3ZTZUeMe)ZVZWeMe+ZXeMe(ZYeMeIZZeMeKZ[eMeLZ\d1S)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. TiPiiFrunTestc Cs||_d|_d|_yt||}Wn.tk rN|dkrJtd|j|fYn 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_testMethodDocrvrbZ ValueError __class__r _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictlistrJZsetZ frozensetr)rZ methodName testMethodrrrrs&     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)rZtypeobjfunctionrrrrs zTestCase.addTypeEqualityFunccOs|jj|||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)rrrrr0r1rrr addCleanupszTestCase.addCleanupcCdS)zAHook method for setting up the test fixture before exercising it.NrrgrrrsetUpr5zTestCase.setUpcCr)zAHook method for deconstructing the test fixture after testing it.NrrgrrrtearDownr5zTestCase.tearDowncCr)zKHook method for setting up class fixture before running tests in the class.Nrclsrrr setUpClasszTestCase.setUpClasscCr)zVHook method for deconstructing the class fixture after running all tests in the class.Nrrrrr tearDownClassrzTestCase.tearDownClasscCr)NrrrgrrrcountTestCasesr,zTestCase.countTestCasescCstjSr&)rZ TestResultrgrrrdefaultTestResultr,zTestCase.defaultTestResultcCs |j}|r|jddjpdS)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)rsplitstriprZdocrrrshortDescriptionszTestCase.shortDescriptioncCdt|j|jfS)Nz%s.%srrrrgrrridr,z TestCase.idcCs t|t|k rtS|j|jkSr&)r7NotImplementedrrZotherrrr__eq__szTestCase.__eq__cCstt||jfSr&)hashr7rrgrrr__hash__r,zTestCase.__hash__cCsd|jt|jfSNz%s (%s))rrrrgrrr__str__r,zTestCase.__str__cCr)Nz<%s testMethod=%s>rrgrrr__repr__szTestCase.__repr__cCs<t|dd}|dk r |||ntjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reportedr)rvr^r_RuntimeWarning addSuccess)rrr"r3rrrr_addSkips   zTestCase._addSkipcks|jdks|jj rdVdS|j}|dkr8tj|}n |jj|}t||||_zX|jj|jdd dVWdQRX|jj s|jj }|dk r|j rt n |jj rt Wd||_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. NTr#)rrr collectionsZChainMapparamsZ new_child_SubTestr%rrZfailfastrr)rrOrZparentZ params_maprrrrsubTest s$  zTestCase.subTestcCsdx^|D]V\}}t|tr*|j|j||q|dk rt|d|jrP|j||q|j||qWdS)Nr)r6rrr"rKrP addFailureZaddError)rrrtestr!rrr_feedErrorsToResult(s zTestCase._feedErrorsToResultc CsDy |j}Wn*tk r4tjdt|j|Yn X|||dS)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerbr^r_rr)rrr!rrrr_addExpectedFailure2s zTestCase._addExpectedFailurecCshy |j}WnPtk rZtjdty tdWn$tk rT|j|tjYnXYn X||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrbr^r_rrrr r!)rrrrrr_addUnexpectedSuccess<s  zTestCase._addUnexpectedSuccessNc (Cs|}|dkr.|j}t|dd}|dk r.||j|t||j}t|jdds^t|ddrz,t|jddpxt|dd}|j|||Wd|j|XdSt|dd}t|dd}|p|}t|} z| |_| j ||j WdQRX| j r<|| _ | j |dd |WdQRXd| _ | j ||j WdQRX|jx"| jD]\} } |j|| | qLW|j|| j| j r|r| jr|j|| jn |j|n |j||S|j||dkrt|d d} | dk r| | jjd| _d|_XdS) N startTestRunr9Fr:rCTr stopTestRun)rrvZ startTestrrrZstopTestrrr%rrrr doCleanupsrrrrrrrZclear) rrZ orig_resultrrZskip_whyZexpecting_failure_methodZexpecting_failure_classroutcomerr3rrrrrunKsh               z TestCase.runc CsN|jp t}x:|jrF|jj\}}}|j||||WdQRXqW|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrrar%r)rrrr0r1rrrrs   zTestCase.doCleanupscOs |j||Sr&)r)rr0Zkwdsrrr__call__r,zTestCase.__call__cCsJ|jt||j|jx&|jrD|jjd\}}}|||q WdS)z6Run the test without collecting errors in a TestResultrNi)rrvrrrrarrrrdebugs zTestCase.debugcCs t|dS)zSkip this test.Nr.)rr3rrrskipTestr5zTestCase.skipTestcCs|j|dS)z)Fail immediately, with the given message.N)rP)rrOrrrfailr5z TestCase.failcCs&|r"|j|dt|}|j|dS)z#Check that the expression is false.z%s is not falseNrNrrPrZexprrOrrr assertFalsezTestCase.assertFalsecCs&|s"|j|dt|}|j|dS)z"Check that the expression is true.z%s is not trueNrrrrr assertTruerzTestCase.assertTruec CsP|js|p |S|dkr|Sy d||fStk rJdt|t|fSXdS)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) longMessageZUnicodeDecodeErrorr)rrOrQrrrrNs  zTestCase._formatMessagec Os$t||}z|jd||Sd}XdS)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) assertRaisesNrfrd)rexpected_exceptionr0r1contextrrrrs zTestCase.assertRaisescOst||}|jd||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) assertWarnsrsrd)rexpected_warningr0r1rrrrrs zTestCase.assertWarnscCs t|||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 assertLogsszTestCase.assertLogscCsFt|t|kr@|jjt|}|dk r@t|trt|||kr>dSdt|t|t|f}nF|dkrfd}||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 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. Nrz%s == %s within %s deltarrz%s == %s within %r placesrrrrrassertNotAlmostEquals"   zTestCase.assertNotAlmostEqualc'Cs|dk rP|j}t||s.|jd|t|ft||sT|jd|t|fnd}d}y t|}Wn ttfk rd|}YnX|dkry t|}Wn ttfk rd|}YnX|dkr||krdSd|jft||}xt t ||D]} y || } Wn.tt tfk r8|d| |f7}PYnXy || } Wn.tt tfk rt|d | |f7}PYnX| | kr|d | ft| | 7}PqW||kr|dkrt |t |krdS||kr0|d |||f7}y|d |t||f7}Wn,tt tfk r,|d ||f7}YnXnh||kr|d|||f7}y|d |t||f7}Wn,tt tfk r|d||f7}YnX|} 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 r6rPrrr\NotImplementedErrorZ capitalizerZrangeZminZ IndexErrorr7joindifflibndiffpprintpformat splitlines_truncateMessagerNr)rZseq1Zseq2rOseq_typeZ seq_type_nameZ differingZlen1Zlen2ZiZitem1Zitem2rQdiffMsgrrrassertSequenceEquals               zTestCase.assertSequenceEqualcCs2|j}|dkst||kr"||S|tt|Sr&)maxDiffr DIFF_OMITTED)rrydiffZmax_diffrrrrszTestCase._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. rN)rr)rZlist1Zlist2rOrrrr s 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. rN)rrJ)rZtuple1Ztuple2rOrrrrs zTestCase.assertTupleEqualc Cshy|j|}Wn^tk r>}z|jd|WYdd}~Xn0tk rl}z|jd|WYdd}~XnXy|j|}Wn^tk r}z|jd|WYdd}~Xn0tk r}z|jd|WYdd}~XnX|p|sdSg}|r|jdx|D]}|jt|qW|rH|jdx|D]}|jt|q0Wdj|} |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)Z differencer\rrbrZreprrrN) rZset1Zset2rOZ difference1r$Z difference2linesZitemrQrrrr"s2        zTestCase.assertSetEqualcCs2||kr.dt|t|f}|j|j||dS)zDJust like self.assertTrue(a in b), but with a nicer default message.z%s not found in %sNrrrNrZmemberZ containerrOrQrrrassertInM zTestCase.assertIncCs2||kr.dt|t|f}|j|j||dS)zHJust like self.assertTrue(a not in b), but with a nicer default message.z%s unexpectedly found in %sNrrrrr assertNotInTr zTestCase.assertNotIncCs2||k r.dt|t|f}|j|j||dS)zDJust like self.assertTrue(a is b), but with a nicer default message.z %s is not %sNrrZexpr1Zexpr2rOrQrrrassertIs[r zTestCase.assertIscCs,||kr(dt|f}|j|j||dS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: %sNrr rrr assertIsNotbzTestCase.assertIsNotcCs~|j|td|j|td||krzdt||}ddjtjtj|jtj|j}|j ||}|j |j ||dS)Nz"First argument is not a dictionaryz#Second argument is not a dictionaryrr) assertIsInstancerrrrrrrrrrrN)rZd1Zd2rOrQrrrrrhs   zTestCase.assertDictEqualc Cstjdtg}g}xX|jD]L\}}||kr:|j|q|||kr|jdt|t|t||fqW|pt|szdSd}|rddjdd|D}|r|r|d 7}|d dj|7}|j|j||dS) z2Checks whether dictionary is a superset of subset.z&assertDictContainsSubset is deprecatedz%s, expected: %s, actual: %sNrz Missing: %sz,css|]}t|VqdSr&)r)rErzrrrrHrIz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) r^r_r`itemsrrrrrN) rZsubsetZ dictionaryrOZmissingZ mismatchedZkeyZvaluerQrrrassertDictContainsSubsetts,     z!TestCase.assertDictContainsSubsetc Cst|t|}}ytj|}tj|}Wntk rHt||}YnX||krVdSt||}|rd}dd|D}dj|} |j|| }|j||}|j |dS)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)rErrrrz sz-TestCase.assertCountEqual..r) rrZCounterr\rrrrrNr) rrrrOZ first_seqZ second_seqZ differencesrQrrrrrassertCountEquals      zTestCase.assertCountEqualcCs|j|td|j|td||krt||jks@t||jkrN|j||||jdd}|jdd}t|dkr|jd|kr|dg}|dg}dt||}dd jt j ||}|j ||}|j |j ||d S) z-Assert that two multi-line strings are equal.zFirst argument is not a stringzSecond argument is not a stringT)Zkeependsrz rrrN)rrr_diffThresholdrrrrrrrrrrN)rrrrOZ firstlinesZ secondlinesrQrrrrrs     zTestCase.assertMultiLineEqualcCs2||ks.dt|t|f}|j|j||dS)zCJust like self.assertTrue(a < b), but with a nicer default message.z%s not less than %sNrrZaZbrOrQrrr assertLesszTestCase.assertLesscCs2||ks.dt|t|f}|j|j||dS)zDJust like self.assertTrue(a <= b), but with a nicer default message.z%s not less than or equal to %sNrrrrrassertLessEqualrzTestCase.assertLessEqualcCs2||ks.dt|t|f}|j|j||dS)zCJust like self.assertTrue(a > b), but with a nicer default message.z%s not greater than %sNrrrrr assertGreaterrzTestCase.assertGreatercCs2||ks.dt|t|f}|j|j||dS)zDJust like self.assertTrue(a >= b), but with a nicer default message.z"%s not greater than or equal to %sNrrrrrassertGreaterEqualrzTestCase.assertGreaterEqualcCs,|dk r(dt|f}|j|j||dS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz%s is not Nonerrr*rOrQrrr assertIsNonerzTestCase.assertIsNonecCs"|dkrd}|j|j||dS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rrNrrrrassertIsNotNoneszTestCase.assertIsNotNonecCs0t||s,dt||f}|j|j||dS)zTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.z%s is not an instance of %rNr6rrrNrr*rrOrQrrrrs zTestCase.assertIsInstancecCs0t||r,dt||f}|j|j||dS)z,Included for symmetry with assertIsInstance.z%s is an instance of %rNrrrrrassertNotIsInstances zTestCase.assertNotIsInstancecOt|||}|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. 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)rrrYr0r1rrrrr"s 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)rrrYr0r1rrrrr#s zTestCase.assertWarnsRegexcCsJt|ttfrtj|}|j|sFd|j|f}|j||}|j|dS)z=Fail the test unless the text matches the regular expression.z&Regex didn't match: %r not found in %rN) r6rbytesrWrXrlrmrNrP)rtextrYrOrQrrr assertRegexs    zTestCase.assertRegexcCs`t|ttfrtj|}|j|}|r\d||j|j|j|f}|j ||}|j |dS)z9Fail the test if the text matches the regular expression.z"Regex matched: %r matches %r in %rN) r6rr$rWrXrlZstartZendrmrNrP)rr%Zunexpected_regexrOZmatchrQrrrassertNotRegex&s   zTestCase.assertNotRegexcr-)Ncs tjdjjtd||S)NzPlease use {0} instead.r)r^r_rjr r`r/ original_funcrrdeprecated_func6s z,TestCase._deprecate..deprecated_funcr)r)r*rr(r _deprecate5s zTestCase._deprecateii)rr&r&r&r&NNr&r&r&NNNr-r,r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&r&)]r r r rZAssertionErrorrPrrrZ_classSetupFailedrrrrrZ classmethodrrrrrrrrrrrr'r(_subtest_msg_sentinelrrrrrrrrrrrrrNrrrrrrrrrrrrrrr r r rrrrrrrrrrrrr r"r#r&r'r+ZfailUnlessEqualZ assertEqualsZ failIfEqualZassertNotEqualsZfailUnlessAlmostEqualZassertAlmostEqualsZfailIfAlmostEqualZassertNotAlmostEqualsZ failUnlessZassert_ZfailUnlessRaisesZfailIfZassertRaisesRegexpZassertRegexpMatchesZassertNotRegexpMatchesrrrrrfs        E     !     ' 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|j||_||_||_||_dSr&)superr/r _setUpFunc _tearDownFunc _testFunc _description)rZtestFuncrrZ descriptionrrrrTs zFunctionTestCase.__init__cC|jdk r|jdSr&)r1rgrrrr[ zFunctionTestCase.setUpcCr6r&)r2rgrrrr_r7zFunctionTestCase.tearDowncCs |jdSr&)r3rgrrrrcr,zFunctionTestCase.runTestcCs|jjSr&)r3r rgrrrrfr,zFunctionTestCase.idcCs@t||jstS|j|jko>|j|jko>|j|jko>|j|jkSr&)r6rrr1r2r3r4rrrrris     zFunctionTestCase.__eq__cCstt||j|j|j|jfSr&)rr7r1r2r3r4rgrrrrrrSzFunctionTestCase.__hash__cCsdt|j|jjfSr)rrr3r rgrrrrvr7zFunctionTestCase.__str__cCr)Nz <%s tec=%s>)rrr3rgrrrrzr7zFunctionTestCase.__repr__cCs2|jdk r|jS|jj}|r.|jddjp0dS)Nrr)r4r3rrrrrrrr~s z!FunctionTestCase.shortDescriptionr-)r r r rrrrrrrrrrr __classcell__rrr5rr/Ks r/csDeZdZfddZddZddZddZd d Zd d ZZ S) rcs(tj||_||_||_|j|_dSr&)r0r_messager"rrP)rr"ryrr5rrrs  z_SubTest.__init__cCs tddS)Nzsubtests cannot be run directly)rrgrrrrr,z_SubTest.runTestcCsbg}|jtk r |jdj|j|jrTdjddt|jjD}|jdj|dj|p`dS)Nz[{}]z, css|]\}}dj||VqdS)z{}={!r}N)rj)rEZkrxrrrrHsz+_SubTest._subDescription..z({})z z ())r9r.rrjrrZsortedr)rZpartsZ params_descrrr_subDescriptions z_SubTest._subDescriptioncCsdj|jj|jSNz{} {})rjr"rr:rgrrrrr,z _SubTest.idcCs |jjS)zlReturns a one-line description of the subtest, or None if no description has been provided. )r"rrgrrrrsz_SubTest.shortDescriptioncCsdj|j|jSr;)rjr"r:rgrrrrr,z_SubTest.__str__) r r r rrr:rrrr8rrr5rrs   r)0rr r8rrTrrrWr^rr'rkrrZutilrrrrrZ __unittestZobjectr.rZ Exceptionr rrrr+r=r@rBrrDrMrUrVrfrsZ namedtupler{rr~rrr/rrrrrZsZ (  /%5 ,l: