PK!&%__pycache__/util.cpython-36.pycnu[3 \9@sdZddlmZmZddlmZdZdZdZdZ dZ dZ ee ee ee Z e dks\t dd Zd d Zd d dZddZddZddZddZeddZddZddZddZdS)!zVarious utility functions.) namedtuple OrderedDict) commonprefixTP cCsBt|||}|tkr>d|d|||t||df}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlenZ suffixlenskipr %/usr/lib64/python3.6/unittest/util.py_shortens&rcsttt|}ttt|}|tkr(|St|tt|tt}|t krttt |tkspt t t|tfdd|DSt tt tfdd|DS)Nc3s|]}|dVqdS)Nr ).0r )prefixr r r 'sz'_common_shorten_repr..c3s&|]}t|dttVqdS)N)r _MIN_DIFF_LEN _MIN_END_LEN)rr )rr r rr*s) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENAssertionErrorr)argsmaxlenZ common_lenr )rr r_common_shorten_reprs    rFc CsRy t|}Wntk r*tj|}YnX| s>t|tkrB|S|dtdS)Nz [truncated]...)repr Exceptionobject__repr__rr)objZshortresultr r rr-s rcCsd|j|jfS)Nz%s.%s) __module__ __qualname__)clsr r rstrclass6sr)cCs*d}}g}g}xy||}||}||kr\|j||d7}x|||krX|d7}qBWn||kr|j||d7}xf|||kr|d7}qxWnL|d7}zx|||kr|d7}qWWd|d7}x|||kr|d7}qWXWqtk r|j||d|j||dPYqXqW||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. rN)append IndexErrorextend)expectedactualijmissingZ unexpectedear r rsorted_list_difference9s:   r5c CsLg}x>|rB|j}y|j|Wqtk r>|j|YqXqW||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 ValueErrorr+)r.r/r2itemr r runorderable_list_differencebsr:cCs||k||kS)z.Return -1 if x < y, 0 if x == y and 1 if x > yr )xyr r r three_way_cmpssr=ZMismatchzactual expected valuecCsDt|t|}}t|t|}}t}g}xt|D]\}} | |krJq8d} } x.t||D] } || | kr^| d7} ||| <q^Wx,t|D] \} } | | kr| d7} ||| <qW| | kr8t| | | }|j|q8Wxlt|D]`\}} | |krqd} x2t||D]$} || | kr| d7} ||| <qWtd| | }|j|qW|S)zHReturns list of (cnt_act, cnt_exp, elem) triples where the counts differrr*)listrr" enumeraterange _Mismatchr+)r/r.r tmnZNULLr%r0elemcnt_scnt_tr1Z other_elemdiffr r r_count_diff_all_purposeys<     rIcCs,t}x |D]}|j|dd||<q W|S)z@Return dict of element counts, in the order they were first seenrr*)rget)iterablecrEr r r_ordered_counts rMc Cst|t|}}g}x>|jD]2\}}|j|d}||kr t|||}|j|q Wx2|jD]&\}}||kr`td||}|j|q`W|S)zHReturns list of (cnt_act, cnt_exp, elem) triples where the counts differr)rMitemsrJrAr+) r/r.r rBr%rErFrGrHr r r_count_diff_hashables   rON)F)__doc__ collectionsrrZos.pathrZ __unittestrr rrrrrrrrr)r5r:r=rArIrMrOr r r rs,   ) #PK!99 )__pycache__/__init__.cpython-36.opt-1.pycnu[3 fk @sdZddddddddd d d d d dddddgZejdddgdZddlmZddlmZmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZmZmZddlmZmZddlmZmZddlmZmZm Z m!Z!eZ"dd Z#d!S)"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. TestResultTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandlergetTestCaseNames makeSuite findTestCasesT)r)rrr r r r r _skipInRpmBuild) BaseTestSuiter)rrrrr) TestProgramr)rr)rrrrcCs"ddl}|jjt}|j||dS)N)Z start_dirpattern)Zos.pathpathdirname__file__Zdiscover)loaderZtestsrosZthis_dirr!)/usr/lib64/python3.6/unittest/__init__.py load_testsKs r#N)$__doc____all__extendZ __unittestresultrZcaserrr r r r r rZsuiterrrrrrrrrrZrunnerrrZsignalsrrrrZ_TextTestResultr#r!r!r!r"-s    (PK!d)__pycache__/__init__.cpython-36.opt-2.pycnu[3 fk @sdddddddddd d d d d ddddgZejdddgdZddlmZddlmZmZmZm Z m Z m Z m Z m Z ddlmZmZddlmZmZmZmZmZddlmZmZddlmZmZddlmZmZmZm Z eZ!ddZ"d S)! TestResultTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandlergetTestCaseNames makeSuite findTestCasesT)r)rrr r r r r _skipInRpmBuild) BaseTestSuiter)rrrrr) TestProgramr)rr)rrrrcCs"ddl}|jjt}|j||dS)N)Z start_dirpattern)Zos.pathpathdirname__file__Zdiscover)loaderZtestsrosZthis_dirr!)/usr/lib64/python3.6/unittest/__init__.py load_testsKs r#N)#__all__extendZ __unittestresultrZcaserrr r r r r rZsuiterrrrrrrrrrZrunnerrrZsignalsrrrrZ_TextTestResultr#r!r!r!r"/s   (PK!99 #__pycache__/__init__.cpython-36.pycnu[3 fk @sdZddddddddd d d d d dddddgZejdddgdZddlmZddlmZmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZmZmZddlmZmZddlmZmZddlmZmZm Z m!Z!eZ"dd Z#d!S)"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. TestResultTestCase TestSuiteTextTestRunner TestLoaderFunctionTestCasemaindefaultTestLoaderSkipTestskipskipIf skipUnlessexpectedFailureTextTestResultinstallHandlerregisterResult removeResult removeHandlergetTestCaseNames makeSuite findTestCasesT)r)rrr r r r r _skipInRpmBuild) BaseTestSuiter)rrrrr) TestProgramr)rr)rrrrcCs"ddl}|jjt}|j||dS)N)Z start_dirpattern)Zos.pathpathdirname__file__Zdiscover)loaderZtestsrosZthis_dirr!)/usr/lib64/python3.6/unittest/__init__.py load_testsKs r#N)$__doc____all__extendZ __unittestresultrZcaserrr r r r r rZsuiterrrrrrrrrrZrunnerrrZsignalsrrrrZ_TextTestResultr#r!r!r!r"-s    (PK!v?)__pycache__/__main__.cpython-36.opt-1.pycnu[3 \@sddZddlZejdjdrBddlZejjejZedejd<[dZ ddl m Z m Z e dddS) zMain entry pointNz __main__.pyz -m unittestT)main TestProgram)module) __doc__sysargvendswithZos.pathospathbasename executableZ __unittestrrrr)/usr/lib64/python3.6/unittest/__main__.pysPK!ݥ~~)__pycache__/__main__.cpython-36.opt-2.pycnu[3 \@s`ddlZejdjdr>ddlZejjejZedejd<[dZddl m Z m Z e dddS)Nz __main__.pyz -m unittestT)main TestProgram)module) sysargvendswithZos.pathospathbasename executableZ __unittestrrr r )/usr/lib64/python3.6/unittest/__main__.pysPK!v?#__pycache__/__main__.cpython-36.pycnu[3 \@sddZddlZejdjdrBddlZejjejZedejd<[dZ ddl m Z m Z e dddS) zMain entry pointNz __main__.pyz -m unittestT)main TestProgram)module) __doc__sysargvendswithZos.pathospathbasename executableZ __unittestrrrr)/usr/lib64/python3.6/unittest/__main__.pysPK!qĻĻ%__pycache__/case.cpython-36.opt-1.pycnu[3 f@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@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__rr%/usr/lib64/python3.6/unittest/case.pyr sr c@seZdZdZdS) _ShouldStopz The test should stop. N)r r r r rrrrr"src@seZdZdZdS)_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! N)r r r r rrrrr'src@s&eZdZdddZejdddZdS) _OutcomeNcCs4d|_||_t|d|_d|_g|_d|_g|_dS)NF addSubTestT)expecting_failurerhasattrresult_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) rKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTestZ old_successer!rrrtestPartExecutor7s* $  z_Outcome.testPartExecutor)N)F)r r r r contextlibcontextmanagerr%rrrrr-s rcCs|S)Nr)objrrr_idUsr)csfdd}|S)z& Unconditionally skip a test. cs4t|ts$tj|fdd}|}d|_|_|S)Ncs tdS)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,rskipXs r6cCs|r t|StS)z/ Skip a test if the condition is true. )r6r)) conditionr,rrrskipIfhsr8cCs|s t|StS)z3 Skip a test unless the condition is true. )r6r))r7r,rrr skipUnlesspsr9cCs d|_|S)NT)__unittest_expecting_failure__)r4rrrrxsrcs4t|tr tfdd|DSt|to2t|S)Nc3s|]}t|VqdS)N) _is_subtype).0r$)basetyperr ~sz_is_subtype..)r.tupleallr/ issubclass)expectedr=r)r=rr;|s r;c@seZdZddZddZdS)_BaseTestCaseContextcCs ||_dS)N)r")rr"rrrrsz_BaseTestCaseContext.__init__cCs |jj|j|}|jj|dS)N)r"_formatMessagemsgfailureException)r standardMsgrErrr _raiseFailuresz"_BaseTestCaseContext._raiseFailureN)r r r rrHrrrrrCsrCcCsdtjkrt|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)osenvironr6r))r,rrr_skipInRpmBuilds rKc@seZdZdddZddZdS)_AssertRaisesBaseContextNcCs@tj||||_||_|dk r*tj|}||_d|_d|_dS)N) rCrrBr"recompileexpected_regexobj_namerE)rrBr"rOrrrrs  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 NonerEz3%r is an invalid keyword argument for this function)r;rB _base_type TypeError_base_type_strwarningswarnDeprecationWarningpoprEnextiterr rPAttributeErrorr)rnamer*r+Z callable_objrrrhandles.  z_AssertRaisesBaseContext.handle)N)r r r rr]rrrrrLs rLc@s(eZdZdZeZdZddZddZdS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typescCs|S)Nr)rrrr __enter__sz_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 raisedFTz"{}" does not match "{}")rBr r[rrPrHformat traceback clear_framesrAwith_tracebackZ exceptionrOsearchpattern)rexc_type exc_valuetbexc_namerOrrr__exit__s(       z_AssertRaisesContext.__exit__N) r r r r BaseExceptionrRrTr_rjrrrrr^s r^c@s(eZdZdZeZdZddZddZdS)_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)recordalways) r modulesvaluesgetattrrmrUcatch_warningswarnings_managerr_ simplefilterrB)rvrrrr_s   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)Nz"{}" does not match "{}"z{} not triggered by {}z{} not triggered)rtrjrBr r[rrUmessager.rOrdZwarningfilenamelinenorHr`rerP)rrfrgrhriZfirst_matchingmwrrrrjs8      z_AssertWarnsContext.__exit__N) r r r r WarningrRrTr_rjrrrrrls  rl_LoggingWatcherrecordsoutputc@s(eZdZdZddZddZddZdS) _CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cCstjj|tgg|_dS)N)loggingHandlerrr}watcher)rrrrr,s z_CapturingHandler.__init__cCsdS)Nr)rrrrflush0sz_CapturingHandler.flushcCs*|jjj||j|}|jjj|dS)N)rr~rr`r)rrnrErrremit3s z_CapturingHandler.emitN)r r r r rrrrrrrr'src@s,eZdZdZdZddZddZddZd S) _AssertLogsContextz:A context manager used to implement TestCase.assertLogs().z"%(levelname)s:%(name)s:%(message)scCs:tj||||_|r(tjj|||_ntj|_d|_dS)N) rCr logger_namerZ _nameToLevelgetlevelINFOrE)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)r.rrZLoggerloggerZ getLoggerZ FormatterLOGGING_FORMATrZ setFormatterrhandlers old_handlersr old_level propagate old_propagatesetLevel)rrZ formatterZhandlerrrrr_Hs   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~rHr`rZ getLevelNamerr\)rrfrgrhrrrrjYs  z_AssertLogsContext.__exit__N)r r r r rrr_rjrrrrr: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. TPFrunTestc 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_testMethodDocrrr[ ValueError __class__r _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictlistr?set 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)rr)rrr*r+rrr addCleanupszTestCase.addCleanupcCsdS)zAHook method for setting up the test fixture before exercising it.Nr)rrrrsetUpszTestCase.setUpcCsdS)zAHook method for deconstructing the test fixture after testing it.Nr)rrrrtearDownszTestCase.tearDowncCsdS)zKHook method for setting up class fixture before running tests in the class.Nr)clsrrr setUpClassszTestCase.setUpClasscCsdS)zVHook method for deconstructing the class fixture after running all tests in the class.Nr)rrrr tearDownClassszTestCase.tearDownClasscCsdS)Nrr)rrrrcountTestCasesszTestCase.countTestCasescCstjS)N)rZ TestResult)rrrrdefaultTestResultszTestCase.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)rsplitstrip)rdocrrrshortDescriptionszTestCase.shortDescriptioncCsdt|j|jfS)Nz%s.%s)rrr)rrrridsz TestCase.idcCs t|t|k rtS|j|jkS)N)r/NotImplementedr)rotherrrr__eq__szTestCase.__eq__cCstt||jfS)N)hashr/r)rrrr__hash__szTestCase.__hash__cCsd|jt|jfS)Nz%s (%s))rrr)rrrr__str__szTestCase.__str__cCsdt|j|jfS)Nz<%s testMethod=%s>)rrr)rrrr__repr__szTestCase.__repr__cCs<t|dd}|dk r |||ntjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reportedr)rrrUrVRuntimeWarning addSuccess)rrr"r,rrrr_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. NT)r#)rrr collectionsChainMapparams new_child_SubTestr%rrZfailfastrr)rrErparentZ params_maprrrrsubTest s$  zTestCase.subTestcCsdx^|D]V\}}t|tr*|j|j||q|dk rt|d|jrP|j||q|j||qWdS)Nr)r.rrr"rArF 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)addExpectedFailurer[rUrVrr)rrr!rrrr_addExpectedFailure2s zTestCase._addExpectedFailurecCshy |j}WnPtk rZtjdty tdWn$tk rT|j|tjYnXYn X||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessr[rUrVrrrr 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 startTestRunr2Fr3r:T)r# stopTestRun)rrrZ startTestrrrZstopTestrrr%rrrr doCleanupsrrrrrrrclear) rrZ orig_resultrrZskip_whyZexpecting_failure_methodZexpecting_failure_classroutcomerr,rrrrrunKsh               z TestCase.runc CsN|jp t}x:|jrF|jj\}}}|j||||WdQRXqW|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrrXr%r)rrrr*r+rrrrs   zTestCase.doCleanupscOs |j||S)N)r)rr*kwdsrrr__call__szTestCase.__call__cCsJ|jt||j|jx&|jrD|jjd\}}}|||q WdS)z6Run the test without collecting errors in a TestResultrN)rrrrrrrX)rrr*r+rrrdebugs zTestCase.debugcCs t|dS)zSkip this test.N)r )rr,rrrskipTestszTestCase.skipTestcCs|j|dS)z)Fail immediately, with the given message.N)rF)rrErrrfailsz TestCase.failcCs&|r"|j|dt|}|j|dS)z#Check that the expression is false.z%s is not falseN)rDrrF)rexprrErrr assertFalseszTestCase.assertFalsecCs&|s"|j|dt|}|j|dS)z"Check that the expression is true.z%s is not trueN)rDrrF)rrrErrr assertTrueszTestCase.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) longMessageUnicodeDecodeErrorr)rrErGrrrrDs  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) assertRaisesN)r^r])rexpected_exceptionr*r+contextrrrrs 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) assertWarns)rlr])rexpected_warningr*r+rrrrrs 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. Nz specify delta or places not bothz%s == %s within %s deltarrz%s == %s within %r places)rSrrrrDrF)rrrrrErrGrrrassertNotAlmostEquals"   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 r.rFrrrSNotImplementedError capitalizerrangemin IndexErrorr/joindifflibndiffpprintpformat splitlines_truncateMessagerDr)rZseq1Zseq2rEseq_typeZ seq_type_nameZ differingZlen1Zlen2iZitem1Zitem2rGdiffMsgrrrassertSequenceEquals               zTestCase.assertSequenceEqualcCs2|j}|dkst||kr"||S|tt|S)N)maxDiffr DIFF_OMITTED)rrwdiffZmax_diffrrrrszTestCase._truncateMessagecCs|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)r r)rZlist1Zlist2rErrrr s zTestCase.assertListEqualcCs|j|||tddS)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)r r?)rZtuple1Ztuple2rErrrrs 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) differencerSrr[rreprrrD) rZset1Zset2rEZ difference1r$Z difference2linesitemrGrrrr"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 %sN)rrrD)rmember containerrErGrrrassertInMs 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 %sN)rrrD)rrrrErGrrr assertNotInTs 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 %sN)rrrD)rexpr1expr2rErGrrrassertIs[s zTestCase.assertIscCs,||kr(dt|f}|j|j||dS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: %sN)rrrD)rrrrErGrrr assertIsNotbszTestCase.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 dictionaryz%s != %sr) assertIsInstancerrrrrrrrrrrD)rZd1Zd2rErGr rrrrhs   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: %s,css|]}t|VqdS)N)r)r<rzrrrr>sz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) rUrVrWitemsrrrrrD) rZsubsetZ dictionaryrEZmissingZ mismatchedkeyvaluerGrrrassertDictContainsSubsetts,     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)r<r rrr sz-TestCase.assertCountEqual..r) rrCounterrSrrrrrDr) rrrrEZ first_seqZ second_seqZ differencesrGrrrrrassertCountEquals      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)keependsrz rz%s != %srN)rrr_diffThresholdrrrrrrrrrrD)rrrrEZ firstlinesZ secondlinesrGr rrrrs     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 %sN)rrrD)rabrErGrrr assertLessszTestCase.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 %sN)rrrD)rr$r%rErGrrrassertLessEqualszTestCase.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 %sN)rrrD)rr$r%rErGrrr assertGreaterszTestCase.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 %sN)rrrD)rr$r%rErGrrrassertGreaterEqualszTestCase.assertGreaterEqualcCs,|dk r(dt|f}|j|j||dS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz%s is not None)rrrD)rr(rErGrrr assertIsNoneszTestCase.assertIsNonecCs"|dkrd}|j|j||dS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rrD)rr(rErGrrrassertIsNotNoneszTestCase.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 %rN)r.rrrD)rr(rrErGrrrrs zTestCase.assertIsInstancecCs0t||r,dt||f}|j|j||dS)z,Included for symmetry with assertIsInstance.z%s is an instance of %rN)r.rrrD)rr(rrErGrrrassertNotIsInstances zTestCase.assertNotIsInstancecOst|||}|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. assertRaisesRegex)r^r])rrrOr*r+rrrrr-s zTestCase.assertRaisesRegexcOst|||}|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. 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. assertWarnsRegex)rlr])rrrOr*r+rrrrr.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) r.rbytesrMrNrdrerDrF)rtextrOrErGrrr 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) r.rr/rMrNrdstartendrerDrF)rr0Zunexpected_regexrEmatchrGrrrassertNotRegex&s   zTestCase.assertNotRegexcsfdd}|S)Ncs tjdjjtd||S)NzPlease use {0} instead.r)rUrVr`r rW)r*r+) original_funcrrdeprecated_func6s z,TestCase._deprecate..deprecated_funcr)r6r7r)r6r _deprecate5s zTestCase._deprecateii)r)N)N)N)N)NN)N)N)N)NNN)NNN)NN)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)]r r r r AssertionErrorrFrr r#Z_classSetupFailedrrrrr classmethodrrrrrrrrrrrr&r'_subtest_msg_sentinelrrrrrrrrrrrrrDrrrrrrrrrr rrrrrrrrrrr!rr&r'r(r)r*r+rr,r-r.r1r5r8ZfailUnlessEqualZ 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||_||_||_||_dS)N)superr<r _setUpFunc _tearDownFunc _testFunc _description)rZtestFuncrrZ description)rrrrTs zFunctionTestCase.__init__cCs|jdk r|jdS)N)r>)rrrrr[s zFunctionTestCase.setUpcCs|jdk r|jdS)N)r?)rrrrr_s zFunctionTestCase.tearDowncCs |jdS)N)r@)rrrrrcszFunctionTestCase.runTestcCs|jjS)N)r@r )rrrrrfszFunctionTestCase.idcCs@t||jstS|j|jko>|j|jko>|j|jko>|j|jkS)N)r.rrr>r?r@rA)rrrrrris     zFunctionTestCase.__eq__cCstt||j|j|j|jfS)N)rr/r>r?r@rA)rrrrrrszFunctionTestCase.__hash__cCsdt|j|jjfS)Nz%s (%s))rrr@r )rrrrrvs zFunctionTestCase.__str__cCsdt|j|jfS)Nz <%s tec=%s>)rrr@)rrrrrzs zFunctionTestCase.__repr__cCs2|jdk r|jS|jj}|r.|jddjp0dS)Nrr)rAr@r rr)rrrrrr~s z!FunctionTestCase.shortDescription)NNN)r r r r rrrrrrrrrr __classcell__rr)rrr<Ks r<csDeZdZfddZddZddZddZd d Zd d ZZ S) rcs(tj||_||_||_|j|_dS)N)r=r_messager"rrF)rr"rwr)rrrrs  z_SubTest.__init__cCs tddS)Nzsubtests cannot be run directly)r)rrrrrsz_SubTest.runTestcCsbg}|jtk r |jdj|j|jrTdjddt|jjD}|jdj|dj|p`dS)Nz[{}]z, css|]\}}dj||VqdS)z{}={!r}N)r`)r<krvrrrr>sz+_SubTest._subDescription..z({}) z ())rCr;rr`rrsortedr)rpartsZ params_descrrr_subDescriptions z_SubTest._subDescriptioncCsdj|jj|jS)Nz{} {})r`r"rrH)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{} {})r`r"rH)rrrrrsz_SubTest.__str__) r r r rrrHrrrrBrr)rrrs   r)0r r r0rrIrrrMrUrr&rarrutilrrrrrZ __unittestobjectr;r  Exceptionr rrrr)r6r8r9rr;rCrKrLr^rl namedtupler}rrrrr<rrrrrsZ (  /%5 ,l:PK!W%__pycache__/case.cpython-36.opt-2.pycnu[3 f@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZmZmZmZdZeZdZGdddeZGd d d eZGd d d eZGd ddeZddZddZddZddZddZ ddZ!GdddZ"ddZ#Gdd d e"Z$Gd!d"d"e$Z%Gd#d$d$e$Z&ej'd%d&d'gZ(Gd(d)d)ej)Z*Gd*d+d+e"Z+Gd,d-d-eZ,Gd.d/d/e,Z-Gd0d1d1e,Z.dS)2N)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@s eZdZdS)SkipTestN)__name__ __module__ __qualname__r r %/usr/lib64/python3.6/unittest/case.pyr sr c@s eZdZdS) _ShouldStopN)r r r r r r rr"src@s eZdZdS)_UnexpectedSuccessN)r r r r r r rr'src@s&eZdZdddZejdddZdS) _OutcomeNcCs4d|_||_t|d|_d|_g|_d|_g|_dS)NF addSubTestT)expecting_failurerhasattrresult_supports_subtestssuccessskippedexpectedFailureerrors)selfrr r r__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) rKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTestZ old_successer r r rtestPartExecutor7s* $  z_Outcome.testPartExecutor)N)F)r r r r contextlibcontextmanagerr$r r r rr-s rcCs|S)Nr )objr r r_idUsr(csfdd}|S)Ncs4t|ts$tj|fdd}|}d|_|_|S)Ncs tdS)N)r )argskwargs)reasonr r skip_wrapper^sz-skip..decorator..skip_wrapperT) isinstancetype functoolswraps__unittest_skip____unittest_skip_why__) test_itemr,)r+r r decorator\s  zskip..decoratorr )r+r4r )r+rskipXs r5cCs|r t|StS)N)r5r() conditionr+r r rskipIfhsr7cCs|s t|StS)N)r5r()r6r+r r r skipUnlesspsr8cCs d|_|S)NT)__unittest_expecting_failure__)r3r r rrxsrcs4t|tr tfdd|DSt|to2t|S)Nc3s|]}t|VqdS)N) _is_subtype).0r#)basetyper r ~sz_is_subtype..)r-tupleallr. issubclass)expectedr<r )r<rr:|s r:c@seZdZddZddZdS)_BaseTestCaseContextcCs ||_dS)N)r!)rr!r r rrsz_BaseTestCaseContext.__init__cCs |jj|j|}|jj|dS)N)r!_formatMessagemsgfailureException)r standardMsgrDr r r _raiseFailuresz"_BaseTestCaseContext._raiseFailureN)r r r rrGr r r rrBsrBcCsdtjkrt|StSdS)NZWITHIN_PYTHON_RPM_BUILD)osenvironr5r()r+r r r_skipInRpmBuilds rJc@seZdZdddZddZdS)_AssertRaisesBaseContextNcCs@tj||||_||_|dk r*tj|}||_d|_d|_dS)N) rBrrAr!recompileexpected_regexobj_namerD)rrAr!rNr r rrs  z!_AssertRaisesBaseContext.__init__cCszt|j|js"td||jf|rD|ddkrDtjdtdf}|sx|jdd|_ |rttjdt t |td|S|^}}y |j |_ Wntk rt||_ YnX||||WdQRXWdd}XdS)Nz%s() arg 1 must be %srzcallable is NonerDz3%r is an invalid keyword argument for this function)r:rA _base_type TypeError_base_type_strwarningswarnDeprecationWarningpoprDnextiterr rOAttributeErrorr)rnamer)r*Z callable_objr r rhandles.  z_AssertRaisesBaseContext.handle)N)r r r rr\r r r rrKs rKc@s$eZdZeZdZddZddZdS)_AssertRaisesContextz-an exception type or tuple of exception typescCs|S)Nr )rr r r __enter__sz_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 raisedFTz"{}" does not match "{}")rAr rZrrOrGformat traceback clear_framesr@with_tracebackZ exceptionrNsearchpattern)rexc_type exc_valuetbexc_namerNr r r__exit__s(       z_AssertRaisesContext.__exit__N)r r r BaseExceptionrQrSr^rir r r rr]sr]c@s$eZdZeZdZddZddZdS)_AssertWarnsContextz(a warning type or tuple of warning typescCsRx$tjjD]}t|ddr i|_q Wtjdd|_|jj|_tj d|j |S)N__warningregistry__T)recordalways) rmodulesvaluesgetattrrlrTcatch_warningswarnings_managerr^ simplefilterrA)rvr r rr^s   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)Nz"{}" does not match "{}"z{} not triggered by {}z{} not triggered)rsrirAr rZrrTmessager-rNrcZwarningfilenamelinenorGr_rdrO)rrerfrgrhZfirst_matchingmwr r rris8      z_AssertWarnsContext.__exit__N)r r r WarningrQrSr^rir r r rrks rk_LoggingWatcherrecordsoutputc@s$eZdZddZddZddZdS)_CapturingHandlercCstjj|tgg|_dS)N)loggingHandlerrr|watcher)rr r rr,s z_CapturingHandler.__init__cCsdS)Nr )rr r rflush0sz_CapturingHandler.flushcCs*|jjj||j|}|jjj|dS)N)rr}rr_r~)rrmrDr r remit3s z_CapturingHandler.emitN)r r r rrrr r r rr'src@s(eZdZdZddZddZddZdS) _AssertLogsContextz"%(levelname)s:%(name)s:%(message)scCs:tj||||_|r(tjj|||_ntj|_d|_dS)N) rBr logger_namerZ _nameToLevelgetlevelINFOrD)rr!rrr r rr?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-rrZLoggerloggerZ getLoggerZ FormatterLOGGING_FORMATrZ setFormatterrhandlers old_handlersr old_level propagate old_propagatesetLevel)rrZ formatterZhandlerr r rr^Hs   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}rGr_rZ getLevelNamerr[)rrerfrgr r rriYs  z_AssertLogsContext.__exit__N)r r r rrr^rir r r rr:s rc@seZdZeZdZdZdZdZddd Z d d Z d d Z ddZ ddZ eddZeddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zejefd(d)Zd*d+Zd,d-Zd.d/Z dd1d2Z!d3d4Z"d5d6Z#d7d8Z$d9d:Z%dd;d<Z&dd=d>Z'dd?d@Z(dAdBZ)dCdDZ*dEdFZ+ddGdHZ,dIdJZ-ddKdLZ.ddMdNZ/ddOdPZ0ddQdRZ1ddSdTZ2ddUdVZ3dWdXZ4ddYdZZ5dd[d\Z6dd]d^Z7dd_d`Z8ddadbZ9ddcddZ:ddedfZ;ddgdhZddmdnZ?ddodpZ@ddqdrZAddsdtZBddudvZCddwdxZDddydzZEdd{d|ZFdd}d~ZGddZHddZIdddZJdddZKddZLeLe/ZMZNeLe0ZOZPeLe1ZQZReLe2ZSZTeLe(ZUZVeLe*ZWeLe'ZXeLeHZYeLeJZZeLeKZ[d0S)TestCaseTPFrunTestc 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 tddS) NzNo testrzno such test method in %s: %sassertDictEqualassertListEqualassertTupleEqualassertSetEqualassertMultiLineEqual)_testMethodName_outcome_testMethodDocrqrZ ValueError __class____doc__ _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictlistr>set frozensetr)rZ methodName testMethodr r rrs&     zTestCase.__init__cCs||j|<dS)N)r)rZtypeobjfunctionr r rrs zTestCase.addTypeEqualityFunccOs|jj|||fdS)N)rr)rrr)r*r r r addCleanupszTestCase.addCleanupcCsdS)Nr )rr r rsetUpszTestCase.setUpcCsdS)Nr )rr r rtearDownszTestCase.tearDowncCsdS)Nr )clsr r r setUpClassszTestCase.setUpClasscCsdS)Nr )rr r r tearDownClassszTestCase.tearDownClasscCsdS)Nrr )rr r rcountTestCasesszTestCase.countTestCasescCstjS)N)rZ TestResult)rr r rdefaultTestResultszTestCase.defaultTestResultcCs |j}|r|jddjpdS)N r)rsplitstrip)rdocr r rshortDescriptionszTestCase.shortDescriptioncCsdt|j|jfS)Nz%s.%s)rrr)rr r ridsz TestCase.idcCs t|t|k rtS|j|jkS)N)r.NotImplementedr)rotherr r r__eq__szTestCase.__eq__cCstt||jfS)N)hashr.r)rr r r__hash__szTestCase.__hash__cCsd|jt|jfS)Nz%s (%s))rrr)rr r r__str__szTestCase.__str__cCsdt|j|jfS)Nz<%s testMethod=%s>)rrr)rr r r__repr__szTestCase.__repr__cCs<t|dd}|dk r |||ntjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reportedr)rqrTrURuntimeWarning addSuccess)rrr!r+rr r r_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)NT)r")rrr collectionsChainMapparams new_child_SubTestr$rrZfailfastrr)rrDrparentZ params_maprr r rsubTest s$  zTestCase.subTestcCsdx^|D]V\}}t|tr*|j|j||q|dk rt|d|jrP|j||q|j||qWdS)Nr)r-rrr!r@rE addFailureZaddError)rrrtestr r r r_feedErrorsToResult(s zTestCase._feedErrorsToResultc CsDy |j}Wn*tk r4tjdt|j|Yn X|||dS)Nz@TestResult has no addExpectedFailure method, reporting as passes)addExpectedFailurerZrTrUrr)rrr rr r r_addExpectedFailure2s zTestCase._addExpectedFailurecCshy |j}WnPtk rZtjdty tdWn$tk rT|j|tjYnXYn X||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessrZrTrUrrrrr )rrrr r r_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 startTestRunr1Fr2r9T)r" stopTestRun)rrqZ startTestrrrZstopTestrrr$rrrr doCleanupsrrrrrrrclear) rrZ orig_resultrrZskip_whyZexpecting_failure_methodZexpecting_failure_classroutcomerr+rr r rrunKsh               z TestCase.runc CsN|jp t}x:|jrF|jj\}}}|j||||WdQRXqW|jS)N)rrrrWr$r)rrrr)r*r r rrs   zTestCase.doCleanupscOs |j||S)N)r)rr)kwdsr r r__call__szTestCase.__call__cCsJ|jt||j|jx&|jrD|jjd\}}}|||q WdS)Nr)rrqrrrrW)rrr)r*r r rdebugs zTestCase.debugcCs t|dS)N)r )rr+r r rskipTestszTestCase.skipTestcCs|j|dS)N)rE)rrDr r rfailsz TestCase.failcCs&|r"|j|dt|}|j|dS)Nz%s is not false)rCrrE)rexprrDr r r assertFalseszTestCase.assertFalsecCs&|s"|j|dt|}|j|dS)Nz%s is not true)rCrrE)rrrDr r r assertTrueszTestCase.assertTruec CsP|js|p |S|dkr|Sy d||fStk rJdt|t|fSXdS)Nz%s : %s) longMessageUnicodeDecodeErrorr)rrDrFr r rrCs  zTestCase._formatMessagec Os$t||}z|jd||Sd}XdS)N assertRaises)r]r\)rexpected_exceptionr)r*contextr r rrs zTestCase.assertRaisescOst||}|jd||S)N assertWarns)rkr\)rexpected_warningr)r*rr r rrs zTestCase.assertWarnscCs t|||S)N)r)rrrr r r assertLogsszTestCase.assertLogscCsFt|t|kr@|jjt|}|dk r@t|trt|||kr>dSdt|t|t|f}nF|dkrfd}||k rtt|||dkrdSdt|t||f}|j||}|j|dS)Nz specify delta or places not bothz%s == %s within %s deltarrz%s == %s within %r places)rRrrrrCrE)rrrrrDrrFr r rassertNotAlmostEquals"   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)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-rErrrRNotImplementedError capitalizerrangemin IndexErrorr.joindifflibndiffpprintpformat splitlines_truncateMessagerCr)rZseq1Zseq2rDseq_typeZ seq_type_nameZ differingZlen1Zlen2iZitem1Zitem2rFdiffMsgr r rassertSequenceEquals               zTestCase.assertSequenceEqualcCs2|j}|dkst||kr"||S|tt|S)N)maxDiffr DIFF_OMITTED)rrvdiffZmax_diffr r rrszTestCase._truncateMessagecCs|j|||tddS)N)r)r r)rZlist1Zlist2rDr r rr s zTestCase.assertListEqualcCs|j|||tddS)N)r)r r>)rZtuple1Ztuple2rDr r rrs 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)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) differencerRrrZrreprrrC) rZset1Zset2rDZ difference1r#Z difference2linesitemrFr r rr"s2        zTestCase.assertSetEqualcCs2||kr.dt|t|f}|j|j||dS)Nz%s not found in %s)rrrC)rmember containerrDrFr r rassertInMs zTestCase.assertIncCs2||kr.dt|t|f}|j|j||dS)Nz%s unexpectedly found in %s)rrrC)rrrrDrFr r r assertNotInTs zTestCase.assertNotIncCs2||k r.dt|t|f}|j|j||dS)Nz %s is not %s)rrrC)rexpr1expr2rDrFr r rassertIs[s zTestCase.assertIscCs,||kr(dt|f}|j|j||dS)Nzunexpectedly identical: %s)rrrC)rrrrDrFr r r assertIsNotbszTestCase.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 dictionaryz%s != %sr) assertIsInstancerrrrrrrrrrrC)rZd1Zd2rDrFr r r rrhs   zTestCase.assertDictEqualc Cstjdtg}g}xX|jD]L\}}||kr:|j|q|||kr|jdt|t|t||fqW|pt|szdSd}|rddjdd|D}|r|r|d7}|d dj|7}|j|j||dS) Nz&assertDictContainsSubset is deprecatedz%s, expected: %s, actual: %srz Missing: %s,css|]}t|VqdS)N)r)r;ryr r rr=sz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) rTrUrVitemsrrrrrC) rZsubsetZ dictionaryrDZmissingZ mismatchedkeyvaluerFr r rassertDictContainsSubsetts,     z!TestCase.assertDictContainsSubsetc Cst|t|}}ytj|}tj|}Wntk rHt||}YnX||krVdSt||}|rd}dd|D}dj|} |j|| }|j||}|j |dS)NzElement counts were not equal: cSsg|] }d|qS)z First has %d, Second has %d: %rr )r;r r r r sz-TestCase.assertCountEqual..r) rrCounterrRrrrrrCr) rrrrDZ first_seqZ second_seqZ differencesrFrrr r rassertCountEquals      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 ||dS) NzFirst argument is not a stringzSecond argument is not a stringT)keependsrz rz%s != %sr)rrr_diffThresholdrrrrrrrrrrC)rrrrDZ firstlinesZ secondlinesrFr r r rrs     zTestCase.assertMultiLineEqualcCs2||ks.dt|t|f}|j|j||dS)Nz%s not less than %s)rrrC)rabrDrFr r r assertLessszTestCase.assertLesscCs2||ks.dt|t|f}|j|j||dS)Nz%s not less than or equal to %s)rrrC)rr$r%rDrFr r rassertLessEqualszTestCase.assertLessEqualcCs2||ks.dt|t|f}|j|j||dS)Nz%s not greater than %s)rrrC)rr$r%rDrFr r r assertGreaterszTestCase.assertGreatercCs2||ks.dt|t|f}|j|j||dS)Nz"%s not greater than or equal to %s)rrrC)rr$r%rDrFr r rassertGreaterEqualszTestCase.assertGreaterEqualcCs,|dk r(dt|f}|j|j||dS)Nz%s is not None)rrrC)rr'rDrFr r r assertIsNoneszTestCase.assertIsNonecCs"|dkrd}|j|j||dS)Nzunexpectedly None)rrC)rr'rDrFr r rassertIsNotNoneszTestCase.assertIsNotNonecCs0t||s,dt||f}|j|j||dS)Nz%s is not an instance of %r)r-rrrC)rr'rrDrFr r rrs zTestCase.assertIsInstancecCs0t||r,dt||f}|j|j||dS)Nz%s is an instance of %r)r-rrrC)rr'rrDrFr r rassertNotIsInstances zTestCase.assertNotIsInstancecOst|||}|jd||S)NassertRaisesRegex)r]r\)rrrNr)r*rr r rr-s zTestCase.assertRaisesRegexcOst|||}|jd||S)NassertWarnsRegex)rkr\)rrrNr)r*rr r rr.s zTestCase.assertWarnsRegexcCsJt|ttfrtj|}|j|sFd|j|f}|j||}|j|dS)Nz&Regex didn't match: %r not found in %r) r-rbytesrLrMrcrdrCrE)rtextrNrDrFr r r assertRegexs    zTestCase.assertRegexcCs`t|ttfrtj|}|j|}|r\d||j|j|j|f}|j ||}|j |dS)Nz"Regex matched: %r matches %r in %r) r-rr/rLrMrcstartendrdrCrE)rr0Zunexpected_regexrDmatchrFr r rassertNotRegex&s   zTestCase.assertNotRegexcsfdd}|S)Ncs tjdjjtd||S)NzPlease use {0} instead.r)rTrUr_r rV)r)r*) original_funcr rdeprecated_func6s z,TestCase._deprecate..deprecated_funcr )r6r7r )r6r _deprecate5s zTestCase._deprecateii)r)N)N)N)N)NN)N)N)N)NNN)NNN)NN)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)\r r r AssertionErrorrErr r#Z_classSetupFailedrrrrr classmethodrrrrrrrrrrrr%r&_subtest_msg_sentinelrrrrrrrrrrrrrCrrrrrrrrrr rrrrrrrrrrr!rr&r'r(r)r*r+rr,r-r.r1r5r8ZfailUnlessEqualZ assertEqualsZ failIfEqualZassertNotEqualsZfailUnlessAlmostEqualZassertAlmostEqualsZfailIfAlmostEqualZassertNotAlmostEqualsZ failUnlessZassert_ZfailUnlessRaisesZfailIfZassertRaisesRegexpZassertRegexpMatchesZassertNotRegexpMatchesr r r rrfs!        E     !     ' c +      !               rcsfeZdZdfdd ZddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ Z S)FunctionTestCaseNcs*tt|j||_||_||_||_dS)N)superr<r _setUpFunc _tearDownFunc _testFunc _description)rZtestFuncrrZ description)rr rrTs zFunctionTestCase.__init__cCs|jdk r|jdS)N)r>)rr r rr[s zFunctionTestCase.setUpcCs|jdk r|jdS)N)r?)rr r rr_s zFunctionTestCase.tearDowncCs |jdS)N)r@)rr r rrcszFunctionTestCase.runTestcCs|jjS)N)r@r )rr r rrfszFunctionTestCase.idcCs@t||jstS|j|jko>|j|jko>|j|jko>|j|jkS)N)r-rrr>r?r@rA)rrr r rris     zFunctionTestCase.__eq__cCstt||j|j|j|jfS)N)rr.r>r?r@rA)rr r rrrszFunctionTestCase.__hash__cCsdt|j|jjfS)Nz%s (%s))rrr@r )rr r rrvs zFunctionTestCase.__str__cCsdt|j|jfS)Nz <%s tec=%s>)rrr@)rr r rrzs zFunctionTestCase.__repr__cCs2|jdk r|jS|jj}|r.|jddjp0dS)Nrr)rAr@rrr)rrr r rr~s z!FunctionTestCase.shortDescription)NNN)r r r rrrrrrrrrr __classcell__r r )rrr<Ks  r<csDeZdZfddZddZddZddZd d Zd d ZZ S) rcs(tj||_||_||_|j|_dS)N)r=r_messager!rrE)rr!rvr)rr rrs  z_SubTest.__init__cCs tddS)Nzsubtests cannot be run directly)r)rr r rrsz_SubTest.runTestcCsbg}|jtk r |jdj|j|jrTdjddt|jjD}|jdj|dj|p`dS)Nz[{}]z, css|]\}}dj||VqdS)z{}={!r}N)r_)r;krur r rr=sz+_SubTest._subDescription..z({}) z ())rCr;rr_rrsortedr)rpartsZ params_descr r r_subDescriptions z_SubTest._subDescriptioncCsdj|jj|jS)Nz{} {})r_r!rrH)rr r rrsz _SubTest.idcCs |jjS)N)r!r)rr r rrsz_SubTest.shortDescriptioncCsdj|j|jS)Nz{} {})r_r!rH)rr r rrsz_SubTest.__str__) r r r rrrHrrrrBr r )rrrs   r)/rr/rrHrrrLrTrr%r`rrutilrrrrrZ __unittestobjectr;r  Exceptionr rrrr(r5r7r8rr:rBrJrKr]rk namedtupler|rrrrr<rr r r rsX (  /%5 ,l:PK!7"__pycache__/case.cpython-36.pycnu[3 f@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@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__rr%/usr/lib64/python3.6/unittest/case.pyr sr c@seZdZdZdS) _ShouldStopz The test should stop. N)r r r r rrrrr"src@seZdZdZdS)_UnexpectedSuccessz7 The test was supposed to fail, but it didn't! N)r r r r rrrrr'src@s&eZdZdddZejdddZdS) _OutcomeNcCs4d|_||_t|d|_d|_g|_d|_g|_dS)NF addSubTestT)expecting_failurerhasattrresult_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) rKeyboardInterruptr rappendstrrsysexc_inforrrr)r test_caseisTestZ old_successer!rrrtestPartExecutor7s* $  z_Outcome.testPartExecutor)N)F)r r r r contextlibcontextmanagerr%rrrrr-s rcCs|S)Nr)objrrr_idUsr)csfdd}|S)z& Unconditionally skip a test. cs4t|ts$tj|fdd}|}d|_|_|S)Ncs tdS)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,rskipXs r6cCs|r t|StS)z/ Skip a test if the condition is true. )r6r)) conditionr,rrrskipIfhsr8cCs|s t|StS)z3 Skip a test unless the condition is true. )r6r))r7r,rrr skipUnlesspsr9cCs d|_|S)NT)__unittest_expecting_failure__)r4rrrrxsrcs4t|tr tfdd|DSt|to2t|S)Nc3s|]}t|VqdS)N) _is_subtype).0r$)basetyperr ~sz_is_subtype..)r.tupleallr/ issubclass)expectedr=r)r=rr;|s r;c@seZdZddZddZdS)_BaseTestCaseContextcCs ||_dS)N)r")rr"rrrrsz_BaseTestCaseContext.__init__cCs |jj|j|}|jj|dS)N)r"_formatMessagemsgfailureException)r standardMsgrErrr _raiseFailuresz"_BaseTestCaseContext._raiseFailureN)r r r rrHrrrrrCsrCcCsdtjkrt|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)osenvironr6r))r,rrr_skipInRpmBuilds rKc@seZdZdddZddZdS)_AssertRaisesBaseContextNcCs@tj||||_||_|dk r*tj|}||_d|_d|_dS)N) rCrrBr"recompileexpected_regexobj_namerE)rrBr"rOrrrrs  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 NonerEz3%r is an invalid keyword argument for this function)r;rB _base_type TypeError_base_type_strwarningswarnDeprecationWarningpoprEnextiterr rPAttributeErrorr)rnamer*r+Z callable_objrrrhandles.  z_AssertRaisesBaseContext.handle)N)r r r rr]rrrrrLs rLc@s(eZdZdZeZdZddZddZdS)_AssertRaisesContextzCA context manager used to implement TestCase.assertRaises* methods.z-an exception type or tuple of exception typescCs|S)Nr)rrrr __enter__sz_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 raisedFTz"{}" does not match "{}")rBr r[rrPrHformat traceback clear_framesrAwith_tracebackZ exceptionrOsearchpattern)rexc_type exc_valuetbexc_namerOrrr__exit__s(       z_AssertRaisesContext.__exit__N) r r r r BaseExceptionrRrTr_rjrrrrr^s r^c@s(eZdZdZeZdZddZddZdS)_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)recordalways) r modulesvaluesgetattrrmrUcatch_warningswarnings_managerr_ simplefilterrB)rvrrrr_s   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)Nz"{}" does not match "{}"z{} not triggered by {}z{} not triggered)rtrjrBr r[rrUmessager.rOrdZwarningfilenamelinenorHr`rerP)rrfrgrhriZfirst_matchingmwrrrrjs8      z_AssertWarnsContext.__exit__N) r r r r WarningrRrTr_rjrrrrrls  rl_LoggingWatcherrecordsoutputc@s(eZdZdZddZddZddZdS) _CapturingHandlerzM A logging handler capturing all (raw and formatted) logging output. cCstjj|tgg|_dS)N)loggingHandlerrr}watcher)rrrrr,s z_CapturingHandler.__init__cCsdS)Nr)rrrrflush0sz_CapturingHandler.flushcCs*|jjj||j|}|jjj|dS)N)rr~rr`r)rrnrErrremit3s z_CapturingHandler.emitN)r r r r rrrrrrrr'src@s,eZdZdZdZddZddZddZd S) _AssertLogsContextz:A context manager used to implement TestCase.assertLogs().z"%(levelname)s:%(name)s:%(message)scCs:tj||||_|r(tjj|||_ntj|_d|_dS)N) rCr logger_namerZ _nameToLevelgetlevelINFOrE)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)r.rrZLoggerloggerZ getLoggerZ FormatterLOGGING_FORMATrZ setFormatterrhandlers old_handlersr old_level propagate old_propagatesetLevel)rrZ formatterZhandlerrrrr_Hs   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~rHr`rZ getLevelNamerr\)rrfrgrhrrrrjYs  z_AssertLogsContext.__exit__N)r r r r rrr_rjrrrrr: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. TPFrunTestc 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_testMethodDocrrr[ ValueError __class__r _cleanups_subtest_type_equality_funcsaddTypeEqualityFuncdictlistr?set 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)rr)rrr*r+rrr addCleanupszTestCase.addCleanupcCsdS)zAHook method for setting up the test fixture before exercising it.Nr)rrrrsetUpszTestCase.setUpcCsdS)zAHook method for deconstructing the test fixture after testing it.Nr)rrrrtearDownszTestCase.tearDowncCsdS)zKHook method for setting up class fixture before running tests in the class.Nr)clsrrr setUpClassszTestCase.setUpClasscCsdS)zVHook method for deconstructing the class fixture after running all tests in the class.Nr)rrrr tearDownClassszTestCase.tearDownClasscCsdS)Nrr)rrrrcountTestCasesszTestCase.countTestCasescCstjS)N)rZ TestResult)rrrrdefaultTestResultszTestCase.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)rsplitstrip)rdocrrrshortDescriptionszTestCase.shortDescriptioncCsdt|j|jfS)Nz%s.%s)rrr)rrrridsz TestCase.idcCs t|t|k rtS|j|jkS)N)r/NotImplementedr)rotherrrr__eq__szTestCase.__eq__cCstt||jfS)N)hashr/r)rrrr__hash__szTestCase.__hash__cCsd|jt|jfS)Nz%s (%s))rrr)rrrr__str__szTestCase.__str__cCsdt|j|jfS)Nz<%s testMethod=%s>)rrr)rrrr__repr__szTestCase.__repr__cCs<t|dd}|dk r |||ntjdtd|j|dS)NaddSkipz4TestResult has no addSkip method, skips not reportedr)rrrUrVRuntimeWarning addSuccess)rrr"r,rrrr_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. NT)r#)rrr collectionsChainMapparams new_child_SubTestr%rrZfailfastrr)rrErparentZ params_maprrrrsubTest s$  zTestCase.subTestcCsdx^|D]V\}}t|tr*|j|j||q|dk rt|d|jrP|j||q|j||qWdS)Nr)r.rrr"rArF 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)addExpectedFailurer[rUrVrr)rrr!rrrr_addExpectedFailure2s zTestCase._addExpectedFailurecCshy |j}WnPtk rZtjdty tdWn$tk rT|j|tjYnXYn X||dS)NzCTestResult has no addUnexpectedSuccess method, reporting as failure) addUnexpectedSuccessr[rUrVrrrr 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 startTestRunr2Fr3r:T)r# stopTestRun)rrrZ startTestrrrZstopTestrrr%rrrr doCleanupsrrrrrrrclear) rrZ orig_resultrrZskip_whyZexpecting_failure_methodZexpecting_failure_classroutcomerr,rrrrrunKsh               z TestCase.runc CsN|jp t}x:|jrF|jj\}}}|j||||WdQRXqW|jS)zNExecute all cleanup functions. Normally called for you after tearDown.N)rrrrXr%r)rrrr*r+rrrrs   zTestCase.doCleanupscOs |j||S)N)r)rr*kwdsrrr__call__szTestCase.__call__cCsJ|jt||j|jx&|jrD|jjd\}}}|||q WdS)z6Run the test without collecting errors in a TestResultrN)rrrrrrrX)rrr*r+rrrdebugs zTestCase.debugcCs t|dS)zSkip this test.N)r )rr,rrrskipTestszTestCase.skipTestcCs|j|dS)z)Fail immediately, with the given message.N)rF)rrErrrfailsz TestCase.failcCs&|r"|j|dt|}|j|dS)z#Check that the expression is false.z%s is not falseN)rDrrF)rexprrErrr assertFalseszTestCase.assertFalsecCs&|s"|j|dt|}|j|dS)z"Check that the expression is true.z%s is not trueN)rDrrF)rrrErrr assertTrueszTestCase.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) longMessageUnicodeDecodeErrorr)rrErGrrrrDs  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) assertRaisesN)r^r])rexpected_exceptionr*r+contextrrrrs 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) assertWarns)rlr])rexpected_warningr*r+rrrrrs 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. Nz specify delta or places not bothz%s == %s within %s deltarrz%s == %s within %r places)rSrrrrDrF)rrrrrErrGrrrassertNotAlmostEquals"   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 r.rFrrrSNotImplementedError capitalizerrangemin IndexErrorr/joindifflibndiffpprintpformat splitlines_truncateMessagerDr)rZseq1Zseq2rEseq_typeZ seq_type_nameZ differingZlen1Zlen2iZitem1Zitem2rGdiffMsgrrrassertSequenceEquals               zTestCase.assertSequenceEqualcCs2|j}|dkst||kr"||S|tt|S)N)maxDiffr DIFF_OMITTED)rrwdiffZmax_diffrrrrszTestCase._truncateMessagecCs|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)r r)rZlist1Zlist2rErrrr s zTestCase.assertListEqualcCs|j|||tddS)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)r r?)rZtuple1Ztuple2rErrrrs 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) differencerSrr[rreprrrD) rZset1Zset2rEZ difference1r$Z difference2linesitemrGrrrr"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 %sN)rrrD)rmember containerrErGrrrassertInMs 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 %sN)rrrD)rrrrErGrrr assertNotInTs 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 %sN)rrrD)rexpr1expr2rErGrrrassertIs[s zTestCase.assertIscCs,||kr(dt|f}|j|j||dS)zHJust like self.assertTrue(a is not b), but with a nicer default message.zunexpectedly identical: %sN)rrrD)rrrrErGrrr assertIsNotbszTestCase.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 dictionaryz%s != %sr) assertIsInstancerrrrrrrrrrrD)rZd1Zd2rErGr rrrrhs   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: %s,css|]}t|VqdS)N)r)r<rzrrrr>sz4TestCase.assertDictContainsSubset..z; zMismatched values: %s) rUrVrWitemsrrrrrD) rZsubsetZ dictionaryrEZmissingZ mismatchedkeyvaluerGrrrassertDictContainsSubsetts,     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)r<r rrr sz-TestCase.assertCountEqual..r) rrCounterrSrrrrrDr) rrrrEZ first_seqZ second_seqZ differencesrGrrrrrassertCountEquals      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)keependsrz rz%s != %srN)rrr_diffThresholdrrrrrrrrrrD)rrrrEZ firstlinesZ secondlinesrGr rrrrs     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 %sN)rrrD)rabrErGrrr assertLessszTestCase.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 %sN)rrrD)rr$r%rErGrrrassertLessEqualszTestCase.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 %sN)rrrD)rr$r%rErGrrr assertGreaterszTestCase.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 %sN)rrrD)rr$r%rErGrrrassertGreaterEqualszTestCase.assertGreaterEqualcCs,|dk r(dt|f}|j|j||dS)zCSame as self.assertTrue(obj is None), with a nicer default message.Nz%s is not None)rrrD)rr(rErGrrr assertIsNoneszTestCase.assertIsNonecCs"|dkrd}|j|j||dS)z(Included for symmetry with assertIsNone.Nzunexpectedly None)rrD)rr(rErGrrrassertIsNotNoneszTestCase.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 %rN)r.rrrD)rr(rrErGrrrrs zTestCase.assertIsInstancecCs0t||r,dt||f}|j|j||dS)z,Included for symmetry with assertIsInstance.z%s is an instance of %rN)r.rrrD)rr(rrErGrrrassertNotIsInstances zTestCase.assertNotIsInstancecOst|||}|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. assertRaisesRegex)r^r])rrrOr*r+rrrrr-s zTestCase.assertRaisesRegexcOst|||}|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. 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. assertWarnsRegex)rlr])rrrOr*r+rrrrr.s zTestCase.assertWarnsRegexcCsVt|ttfr$|stdtj|}|j|sRd|j|f}|j||}|j |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) r.rbytesAssertionErrorrMrNrdrerDrF)rtextrOrErGrrr 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) r.rr/rMrNrdstartendrerDrF)rr1Zunexpected_regexrEmatchrGrrrassertNotRegex&s   zTestCase.assertNotRegexcsfdd}|S)Ncs tjdjjtd||S)NzPlease use {0} instead.r)rUrVr`r rW)r*r+) original_funcrrdeprecated_func6s z,TestCase._deprecate..deprecated_funcr)r7r8r)r7r _deprecate5s zTestCase._deprecateii)r)N)N)N)N)NN)N)N)N)NNN)NNN)NN)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)]r r r r r0rFrr r#Z_classSetupFailedrrrrr classmethodrrrrrrrrrrrr&r'_subtest_msg_sentinelrrrrrrrrrrrrrDrrrrrrrrrr rrrrrrrrrrr!rr&r'r(r)r*r+rr,r-r.r2r6r9ZfailUnlessEqualZ 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||_||_||_||_dS)N)superr<r _setUpFunc _tearDownFunc _testFunc _description)rZtestFuncrrZ description)rrrrTs zFunctionTestCase.__init__cCs|jdk r|jdS)N)r>)rrrrr[s zFunctionTestCase.setUpcCs|jdk r|jdS)N)r?)rrrrr_s zFunctionTestCase.tearDowncCs |jdS)N)r@)rrrrrcszFunctionTestCase.runTestcCs|jjS)N)r@r )rrrrrfszFunctionTestCase.idcCs@t||jstS|j|jko>|j|jko>|j|jko>|j|jkS)N)r.rrr>r?r@rA)rrrrrris     zFunctionTestCase.__eq__cCstt||j|j|j|jfS)N)rr/r>r?r@rA)rrrrrrszFunctionTestCase.__hash__cCsdt|j|jjfS)Nz%s (%s))rrr@r )rrrrrvs zFunctionTestCase.__str__cCsdt|j|jfS)Nz <%s tec=%s>)rrr@)rrrrrzs zFunctionTestCase.__repr__cCs2|jdk r|jS|jj}|r.|jddjp0dS)Nrr)rAr@r rr)rrrrrr~s z!FunctionTestCase.shortDescription)NNN)r r r r rrrrrrrrrr __classcell__rr)rrr<Ks r<csDeZdZfddZddZddZddZd d Zd d ZZ S) rcs(tj||_||_||_|j|_dS)N)r=r_messager"rrF)rr"rwr)rrrrs  z_SubTest.__init__cCs tddS)Nzsubtests cannot be run directly)r)rrrrrsz_SubTest.runTestcCsbg}|jtk r |jdj|j|jrTdjddt|jjD}|jdj|dj|p`dS)Nz[{}]z, css|]\}}dj||VqdS)z{}={!r}N)r`)r<krvrrrr>sz+_SubTest._subDescription..z({}) z ())rCr;rr`rrsortedr)rpartsZ params_descrrr_subDescriptions z_SubTest._subDescriptioncCsdj|jj|jS)Nz{} {})r`r"rrH)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{} {})r`r"rH)rrrrrsz_SubTest.__str__) r r r rrrHrrrrBrr)rrrs   r)0r r r0rrIrrrMrUrr&rarrutilrrrrrZ __unittestobjectr;r  Exceptionr rrrr)r6r8r9rr;rCrKrLr^rl namedtupler}rrrrr<rrrrrsZ (  /%5 ,l:PK!Fk955'__pycache__/loader.cpython-36.opt-1.pycnu[3 \V@sdZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z dZ ejdejZGdd d e jZd d Zd d ZddZddZddZGdddeZeZdddZe jfddZde je jfddZde je jfddZ dS) zLoading unittests.N)fnmatch)casesuiteutilTz[_a-z]\w*\.py$cs,eZdZdZfddZfddZZS) _FailedTestNcs||_tt|j|dS)N) _exceptionsuperr__init__)selfZ method_name exception) __class__'/usr/lib64/python3.6/unittest/loader.pyr sz_FailedTest.__init__cs*|jkrttj|Sfdd}|S)Ncs jdS)N)rr)r rr testFailure!sz,_FailedTest.__getattr__..testFailure)_testMethodNamer r __getattr__)r namer)r )r rrs  z_FailedTest.__getattr__)__name__ __module__ __qualname__rr r __classcell__rr)r rrs rcCs"d|tjf}t|t|||S)Nz#Failed to import test module: %s %s) traceback format_exc_make_failed_test ImportError)r suiteClassmessagerrr_make_failed_import_test&srcCsdtjf}t||||S)NzFailed to call load_tests: %s)rrr)rr rrrrr_make_failed_load_tests+srcCst||}||f|fS)N)r) methodnamer rrtestrrrr0s rcCs<tjt|dd}||i}tdtjf|}|||fS)NcSsdS)Nr)r rrr testSkipped5sz'_make_skipped_test..testSkippedZ ModuleSkipped)rskipstrtypeTestCase)r r rr"ZattrsZ TestClassrrr_make_skipped_test4sr'cCs*|jjdr|ddStjj|dS)Nz $py.class ri)lowerendswithospathsplitext)r,rrr_jython_aware_splitext<s r.cseZdZdZdZeejZe j Z dZ fddZ ddZddd d Zd!d d Zd"d dZddZd#ddZddZddZddZddZd$ddZd%dd ZZS)& TestLoaderz This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite r!Ncs tt|jg|_t|_dS)N)r r/r errorsset_loading_packages)r )r rrr LszTestLoader.__init__cCsHt|tjrtd|j|}| r4t|dr4dg}|jt||}|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?ZrunTest) issubclassr TestSuite TypeErrorgetTestCaseNameshasattrrmap)r testCaseClassZ testCaseNamesZ loaded_suiterrrloadTestsFromTestCaseSs  z TestLoader.loadTestsFromTestCase)patternc Os2t|dksd|kr,tjdt|jddt|dkrRt|d}tdj|t|dkrxt|d}tdj|g}x@t|D]4}t ||}t |t rt |t jr|j|j|qWt |dd} |j|}| dk r.y | |||Stk r,} z$t|j| |j\} } |jj| | Sd} ~ XnX|S) z>Return a suite of all test cases contained in the given modulerZuse_load_testsz(use_load_tests is deprecated and ignoredNrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpopr5formatsorteddirgetattr isinstancer%r3rr&appendr:r Exceptionrrr0) r moduler;argsZkwsZ complainttestsrobjr<e error_case error_messagerrrloadTestsFromModuleas4           zTestLoader.loadTestsFromModulecCs>|jd}d\}}|dkr|dd}xb|rydj|}t|}PWq(tk r|j}t||j\}}|s|jj||SYq(Xq(W|dd}|} x|D]} y| t | | } } Wqt k r2} z\t | dddk r|dk r|jj||St | | |jdt j f\}}|jj||SWYdd} ~ XqXqWt| tjrP|j| St| trtt| tjrt|j| St| tjrt| trt| tjr|d }| |} tt | |tjs|j| gSnt| tjr| St| r.| }t|tjr|St|tjr|j|gStd| |fn td| dS) 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. .Nr__path__zFailed to access attribute: %sz"calling %s returned %s, not a testz$don't know how to make test from: %s)NN)splitjoin __import__rrArrr0rGrEAttributeErrorrrrrFtypes ModuleTyperPr%r3rr&r: FunctionTyperr4callabler5)r rrIpartsrNrOZ parts_copy module_nameZnext_attributerLpartparentrMZinstr!rrrloadTestsFromNamesl             zTestLoader.loadTestsFromNamecsfdd|D}j|S)zReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. csg|]}j|qSr)r`).0r)rIr rr sz1TestLoader.loadTestsFromNames..)r)r namesrIZsuitesr)rIr rloadTestsFromNamesszTestLoader.loadTestsFromNamescCs@||jfdd}tt|t|}|jr<|jtj|jd|S)zLReturn a sorted sequence of method names found within testCaseClass cSs|j|ott||S)N) startswithr[rE)Zattrnamer9prefixrrr isTestMethods z1TestLoader.getTestCaseNames..isTestMethod)key)testMethodPrefixlistfilterrDsortTestMethodsUsingsort functools cmp_to_key)r r9rgZ testFnNamesrrrr6s zTestLoader.getTestCaseNamestest*.pyc CsRd}|dkr|jdk r|j}n|dkr.d}|}tjj|}|tjkrRtjjd|||_d}d}g}tjjtjj|rtjj|}||krtjjtjj|d }nxy t |Wnt k rd}YnRXtj |}|j dd} ytjjtjj |j}Wntk ry |j} Wntk r8d} YnX| r| jdkr| jdk rd}x|jD]T} | r| j| rqd| j |jjdtjjd|_|j|j| |ddqdWn*|jtjkrtddntd j|dYnX|r |s|j| |_tjj|n tjj||r2t d ||sHt|j||}|j |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. FNTrz __init__.pyrQ) namespacez2Can not use builtin modules as dotted module namesz$don't know how to discover from {!r}z%Start directory is not importable: %r)!_top_level_dirr+r,abspathsysinsertisdirisfilerUrVrmodulesrTdirname__file__rW__spec__loadersubmodule_search_locationsrRrerreplacesepextend _find_testsbuiltin_module_namesr5rB _get_directory_containing_moduleremoverjr) r start_dirr;Z top_level_dirZset_implicit_topZis_not_importable is_namespacerKZ the_moduleZtop_partspecr,rrrdiscoversv               zTestLoader.discovercCsRtj|}tjj|j}tjj|jjdrBtjj tjj |Stjj |SdS)Nz __init__.py) rtrxr+r,rsrzbasenamer)rery)r r]rI full_pathrrrrXs  z+TestLoader._get_directory_containing_modulecCsB||jkrdSttjj|}tjj||j}|jtjjd}|S)NrQ)rrr.r+r,normpathrelpathr~r)r r,Z_relpathrrrr_get_name_from_pathds  zTestLoader._get_name_from_pathcCst|tj|S)N)rVrtrx)r rrrr_get_module_from_namepsz TestLoader._get_module_from_namecCs t||S)N)r)r r,rr;rrr _match_pathtszTestLoader._match_pathFc cs|j|}|dkrD||jkrD|j|||\}}|dk r<|V|sDdSttj|}x||D]t}tjj||} |j| ||\}}|dk r|V|rX|j| }|jj|z|j | ||EdHWd|jj |XqXWdS)z/Used by discovery. Yields test suites it loads.rQN) rr2_find_test_pathrCr+listdirr,rUaddrdiscard) r rr;rqrrKZshould_recursepathsr,rrrrrxs*    zTestLoader._find_testscCsPtjj|}tjj|rFtj|s(d S|j|||s:d S|j|}y|j|}WnXt j k r}zt |||j dfSd}~Xnt ||j \}} |jj| |dfStjjt|d|} ttjj| } ttjj|} | j| jkr0tjj| } ttjj|}tjj|}d}t||| |f|j||ddfSntjj|rH| rztjjtjj|d rzd Sd}d}|j|}y|j|}WnZt j k r}zt |||j dfSd}~Xnzt ||j \}} |jj| |dfSt|dd}|jj|z(|j||d}|dk r0|dfS|dfS|jj|Xnd SdS) 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). NFrzzW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?)r;z __init__.pyr<T)NF)NF)NF)NF)r+r,rrwVALID_MODULE_NAMEmatchrrrrZSkipTestr'rrr0rGrsrEr.realpathr)ryrrPrvrUr2rr)r rr;rqrrrIrMrNrOZmod_filerZfullpath_noextZ module_dirZmod_nameZ expected_dirmsgr<rKpackagerrrrsl           zTestLoader._find_test_path)N)N)rpN)F)F)rrr__doc__ri staticmethodr three_way_cmprlrr4rrrr r:rPr`rdr6rrrrrrrrrr)r rr/Bs$  ( N  n   "r/cCs t}||_||_|r||_|S)N)r/rlrir)rf sortUsingrr|rrr _makeLoaders rcCst||j|S)N)rr6)r9rfrrrrr6sr6r!cCst|||j|S)N)rr:)r9rfrrrrr makeSuites rcCst|||j|S)N)rrP)rIrfrrrrr findTestCasess r)N)!rr+rertrrXrnr>rrrrZ __unittestcompile IGNORECASErr&rrrrr'r.objectr/ZdefaultTestLoaderrrr6r4rrrrrrs8 ' PK!bC+C+'__pycache__/loader.cpython-36.opt-2.pycnu[3 \V@sddlZddlZddlZddlZddlZddlZddlZddlmZddlm Z m Z m Z dZ ej dejZGddde jZd d Zd d Zd dZddZddZGdddeZeZdddZe jfddZde je jfddZde je jfddZdS)N)fnmatch)casesuiteutilTz[_a-z]\w*\.py$cs,eZdZdZfddZfddZZS) _FailedTestNcs||_tt|j|dS)N) _exceptionsuperr__init__)selfZ method_name exception) __class__'/usr/lib64/python3.6/unittest/loader.pyr sz_FailedTest.__init__cs*|jkrttj|Sfdd}|S)Ncs jdS)N)rr)r rr testFailure!sz,_FailedTest.__getattr__..testFailure)_testMethodNamer r __getattr__)r namer)r )r rrs  z_FailedTest.__getattr__)__name__ __module__ __qualname__rr r __classcell__rr)r rrs rcCs"d|tjf}t|t|||S)Nz#Failed to import test module: %s %s) traceback format_exc_make_failed_test ImportError)r suiteClassmessagerrr_make_failed_import_test&srcCsdtjf}t||||S)NzFailed to call load_tests: %s)rrr)rr rrrrr_make_failed_load_tests+srcCst||}||f|fS)N)r) methodnamer rrtestrrrr0s rcCs<tjt|dd}||i}tdtjf|}|||fS)NcSsdS)Nr)r rrr testSkipped5sz'_make_skipped_test..testSkippedZ ModuleSkipped)rskipstrtypeTestCase)r r rr"ZattrsZ TestClassrrr_make_skipped_test4sr'cCs*|jjdr|ddStjj|dS)Nz $py.class ri)lowerendswithospathsplitext)r,rrr_jython_aware_splitext<s r.cseZdZdZeejZej Z dZ fddZ ddZ dddd Zd d d Zd!d d ZddZd"ddZddZddZddZddZd#ddZd$ddZZS)% TestLoaderr!Ncs tt|jg|_t|_dS)N)r r/r errorsset_loading_packages)r )r rrr LszTestLoader.__init__cCsHt|tjrtd|j|}| r4t|dr4dg}|jt||}|S)NzYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?ZrunTest) issubclassr TestSuite TypeErrorgetTestCaseNameshasattrrmap)r testCaseClassZ testCaseNamesZ loaded_suiterrrloadTestsFromTestCaseSs  z TestLoader.loadTestsFromTestCase)patternc Os2t|dksd|kr,tjdt|jddt|dkrRt|d}tdj|t|dkrxt|d}tdj|g}x@t|D]4}t ||}t |t rt |t jr|j|j|qWt |dd} |j|}| dk r.y | |||Stk r,} z$t|j| |j\} } |jj| | Sd} ~ XnX|S)NrZuse_load_testsz(use_load_tests is deprecated and ignoredrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpopr5formatsorteddirgetattr isinstancer%r3rr&appendr:r Exceptionrrr0) r moduler;argsZkwsZ complainttestsrobjr<e error_case error_messagerrrloadTestsFromModuleas4           zTestLoader.loadTestsFromModulecCs>|jd}d\}}|dkr|dd}xb|rydj|}t|}PWq(tk r|j}t||j\}}|s|jj||SYq(Xq(W|dd}|} x|D]} y| t | | } } Wqt k r2} z\t | dddk r|dk r|jj||St | | |jdt j f\}}|jj||SWYdd} ~ XqXqWt| tjrP|j| St| trtt| tjrt|j| St| tjrt| trt| tjr|d}| |} tt | |tjs|j| gSnt| tjr| St| r.| }t|tjr|St|tjr|j|gStd| |fn td| dS) N.r__path__zFailed to access attribute: %sz"calling %s returned %s, not a testz$don't know how to make test from: %s)NN)splitjoin __import__rrArrr0rGrEAttributeErrorrrrrFtypes ModuleTyperPr%r3rr&r: FunctionTyperr4callabler5)r rrIpartsrNrOZ parts_copy module_nameZnext_attributerLpartparentrMZinstr!rrrloadTestsFromNamesl             zTestLoader.loadTestsFromNamecsfdd|D}j|S)Ncsg|]}j|qSr)r`).0r)rIr rr sz1TestLoader.loadTestsFromNames..)r)r namesrIZsuitesr)rIr rloadTestsFromNamesszTestLoader.loadTestsFromNamescCs@||jfdd}tt|t|}|jr<|jtj|jd|S)NcSs|j|ott||S)N) startswithr[rE)Zattrnamer9prefixrrr isTestMethods z1TestLoader.getTestCaseNames..isTestMethod)key)testMethodPrefixlistfilterrDsortTestMethodsUsingsort functools cmp_to_key)r r9rgZ testFnNamesrrrr6s zTestLoader.getTestCaseNamestest*.pyc CsRd}|dkr|jdk r|j}n|dkr.d}|}tjj|}|tjkrRtjjd|||_d}d}g}tjjtjj|rtjj|}||krtjjtjj|d }nxy t |Wnt k rd}YnRXtj |}|j dd} ytjjtjj |j}Wntk ry |j} Wntk r8d} YnX| r| jdkr| jdk rd}x|jD]T} | r| j| rqd| j |jjdtjjd|_|j|j| |ddqdWn*|jtjkrtddntdj|dYnX|r |s|j| |_tjj|n tjj||r2t d ||sHt|j||}|j |S) NFTrz __init__.pyrQ) namespacez2Can not use builtin modules as dotted module namesz$don't know how to discover from {!r}z%Start directory is not importable: %r)!_top_level_dirr+r,abspathsysinsertisdirisfilerUrVrmodulesrTdirname__file__rW__spec__loadersubmodule_search_locationsrRrerreplacesepextend _find_testsbuiltin_module_namesr5rB _get_directory_containing_moduleremoverjr) r start_dirr;Z top_level_dirZset_implicit_topZis_not_importable is_namespacerKZ the_moduleZtop_partspecr,rrrdiscoversv               zTestLoader.discovercCsRtj|}tjj|j}tjj|jjdrBtjj tjj |Stjj |SdS)Nz __init__.py) rtrxr+r,rsrzbasenamer)rery)r r]rI full_pathrrrrXs  z+TestLoader._get_directory_containing_modulecCsB||jkrdSttjj|}tjj||j}|jtjjd}|S)NrQ)rrr.r+r,normpathrelpathr~r)r r,Z_relpathrrrr_get_name_from_pathds  zTestLoader._get_name_from_pathcCst|tj|S)N)rVrtrx)r rrrr_get_module_from_namepsz TestLoader._get_module_from_namecCs t||S)N)r)r r,rr;rrr _match_pathtszTestLoader._match_pathFc cs|j|}|dkrD||jkrD|j|||\}}|dk r<|V|sDdSttj|}x||D]t}tjj||} |j| ||\}}|dk r|V|rX|j| }|jj|z|j | ||EdHWd|jj |XqXWdS)NrQ) rr2_find_test_pathrCr+listdirr,rUaddrdiscard) r rr;rqrrKZshould_recursepathsr,rrrrrxs*    zTestLoader._find_testscCsPtjj|}tjj|rFtj|s(dS|j|||s:d S|j|}y|j|}WnXt j k r}zt |||j dfSd}~Xnt ||j \}} |jj| |dfStjjt|d|} ttjj| } ttjj|} | j| jkr0tjj| } ttjj|}tjj|}d}t||| |f|j||ddfSntjj|rH| rztjjtjj|d rzd Sd}d}|j|}y|j|}WnZt j k r}zt |||j dfSd}~Xnzt ||j \}} |jj| |dfSt|dd}|jj|z(|j||d}|dk r0|dfS|dfS|jj|Xnd SdS) NFrzzW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?)r;z __init__.pyr<T)NF)NF)NF)NF)r+r,rrwVALID_MODULE_NAMEmatchrrrrZSkipTestr'rrr0rGrsrEr.realpathr)ryrrPrvrUr2rr)r rr;rqrrrIrMrNrOZmod_filerZfullpath_noextZ module_dirZmod_nameZ expected_dirmsgr<rKpackagerrrrsl           zTestLoader._find_test_path)N)N)rpN)F)F)rrrri staticmethodr three_way_cmprlrr4rrrr r:rPr`rdr6rrrrrrrrrr)r rr/Bs"  ( N  n   "r/cCs t}||_||_|r||_|S)N)r/rlrir)rf sortUsingrr|rrr _makeLoaders rcCst||j|S)N)rr6)r9rfrrrrr6sr6r!cCst|||j|S)N)rr:)r9rfrrrrr makeSuites rcCst|||j|S)N)rrP)rIrfrrrrr findTestCasess r)N) r+rertrrXrnr>rrrrZ __unittestcompile IGNORECASErr&rrrrr'r.objectr/ZdefaultTestLoaderrrr6r4rrrrrrs6 ' PK!E8,6,6!__pycache__/loader.cpython-36.pycnu[3 \V@sdZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z dZ ejdejZGdd d e jZd d Zd d ZddZddZddZGdddeZeZdddZe jfddZde je jfddZde je jfddZ dS) zLoading unittests.N)fnmatch)casesuiteutilTz[_a-z]\w*\.py$cs,eZdZdZfddZfddZZS) _FailedTestNcs||_tt|j|dS)N) _exceptionsuperr__init__)selfZ method_name exception) __class__'/usr/lib64/python3.6/unittest/loader.pyr sz_FailedTest.__init__cs*|jkrttj|Sfdd}|S)Ncs jdS)N)rr)r rr testFailure!sz,_FailedTest.__getattr__..testFailure)_testMethodNamer r __getattr__)r namer)r )r rrs  z_FailedTest.__getattr__)__name__ __module__ __qualname__rr r __classcell__rr)r rrs rcCs"d|tjf}t|t|||S)Nz#Failed to import test module: %s %s) traceback format_exc_make_failed_test ImportError)r suiteClassmessagerrr_make_failed_import_test&srcCsdtjf}t||||S)NzFailed to call load_tests: %s)rrr)rr rrrrr_make_failed_load_tests+srcCst||}||f|fS)N)r) methodnamer rrtestrrrr0s rcCs<tjt|dd}||i}tdtjf|}|||fS)NcSsdS)Nr)r rrr testSkipped5sz'_make_skipped_test..testSkippedZ ModuleSkipped)rskipstrtypeTestCase)r r rr"attrsZ TestClassrrr_make_skipped_test4sr(cCs*|jjdr|ddStjj|dS)Nz $py.class ri)lowerendswithospathsplitext)r-rrr_jython_aware_splitext<s r/cseZdZdZdZeejZe j Z dZ fddZ ddZddd d Zd!d d Zd"d dZddZd#ddZddZddZddZddZd$ddZd%dd ZZS)& TestLoaderz This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite r!Ncs tt|jg|_t|_dS)N)r r0r errorsset_loading_packages)r )r rrr LszTestLoader.__init__cCsHt|tjrtd|j|}| r4t|dr4dg}|jt||}|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?ZrunTest) issubclassr TestSuite TypeErrorgetTestCaseNameshasattrrmap)r testCaseClassZ testCaseNamesZ loaded_suiterrrloadTestsFromTestCaseSs  z TestLoader.loadTestsFromTestCase)patternc Os2t|dksd|kr,tjdt|jddt|dkrRt|d}tdj|t|dkrxt|d}tdj|g}x@t|D]4}t ||}t |t rt |t jr|j|j|qWt |dd} |j|}| dk r.y | |||Stk r,} z$t|j| |j\} } |jj| | Sd} ~ XnX|S) z>Return a suite of all test cases contained in the given modulerZuse_load_testsz(use_load_tests is deprecated and ignoredNrzCloadTestsFromModule() takes 1 positional argument but {} were givenz=loadTestsFromModule() got an unexpected keyword argument '{}' load_tests)lenwarningswarnDeprecationWarningpopr6formatsorteddirgetattr isinstancer%r4rr&appendr;r Exceptionrrr1) r moduler<argsZkwsZ complainttestsrobjr=e error_case error_messagerrrloadTestsFromModuleas4           zTestLoader.loadTestsFromModulecCs>|jd}d\}}|dkr|dd}xb|rydj|}t|}PWq(tk r|j}t||j\}}|s|jj||SYq(Xq(W|dd}|} x|D]} y| t | | } } Wqt k r2} z\t | dddk r|dk r|jj||St | | |jdt j f\}}|jj||SWYdd} ~ XqXqWt| tjrP|j| St| trtt| tjrt|j| St| tjrt| trt| tjr|d }| |} tt | |tjs|j| gSnt| tjr| St| r.| }t|tjr|St|tjr|j|gStd| |fn td| dS) 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. .Nr__path__zFailed to access attribute: %sz"calling %s returned %s, not a testz$don't know how to make test from: %s)NN)splitjoin __import__rrBrrr1rHrFAttributeErrorrrrrGtypes ModuleTyperQr%r4rr&r; FunctionTyperr5callabler6)r rrJpartsrOrPZ parts_copy module_nameZnext_attributerMpartparentrNZinstr!rrrloadTestsFromNamesl             zTestLoader.loadTestsFromNamecsfdd|D}j|S)zReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. csg|]}j|qSr)ra).0r)rJr rr sz1TestLoader.loadTestsFromNames..)r)r namesrJZsuitesr)rJr rloadTestsFromNamesszTestLoader.loadTestsFromNamescCs@||jfdd}tt|t|}|jr<|jtj|jd|S)zLReturn a sorted sequence of method names found within testCaseClass cSs|j|ott||S)N) startswithr\rF)Zattrnamer:prefixrrr isTestMethods z1TestLoader.getTestCaseNames..isTestMethod)key)testMethodPrefixlistfilterrEsortTestMethodsUsingsort functools cmp_to_key)r r:rhZ testFnNamesrrrr7s zTestLoader.getTestCaseNamestest*.pyc CsRd}|dkr|jdk r|j}n|dkr.d}|}tjj|}|tjkrRtjjd|||_d}d}g}tjjtjj|rtjj|}||krtjjtjj|d }nxy t |Wnt k rd}YnRXtj |}|j dd} ytjjtjj |j}Wntk ry |j} Wntk r8d} YnX| r| jdkr| jdk rd}x|jD]T} | r| j| rqd| j |jjdtjjd|_|j|j| |ddqdWn*|jtjkrtddntd j|dYnX|r |s|j| |_tjj|n tjj||r2t d ||sHt|j||}|j |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. FNTrz __init__.pyrR) namespacez2Can not use builtin modules as dotted module namesz$don't know how to discover from {!r}z%Start directory is not importable: %r)!_top_level_dirr,r-abspathsysinsertisdirisfilerVrWrmodulesrUdirname__file__rX__spec__loadersubmodule_search_locationsrSrfrreplacesepextend _find_testsbuiltin_module_namesr6rC _get_directory_containing_moduleremoverkr) r start_dirr<Z top_level_dirZset_implicit_topZis_not_importable is_namespacerLZ the_moduleZtop_partspecr-rrrdiscoversv               zTestLoader.discovercCsRtj|}tjj|j}tjj|jjdrBtjj tjj |Stjj |SdS)Nz __init__.py) ruryr,r-rtr{basenamer*rfrz)r r^rJ full_pathrrrrXs  z+TestLoader._get_directory_containing_modulecCsl||jkrdSttjj|}tjj||j}tjj| sDtd|jd sXtd|j tjj d}|S)NrRzPath must be within the projectz..) rsr/r,r-normpathrelpathisabsAssertionErrorrfrr)r r-Z_relpathrrrr_get_name_from_pathds zTestLoader._get_name_from_pathcCst|tj|S)N)rWrury)r rrrr_get_module_from_namepsz TestLoader._get_module_from_namecCs t||S)N)r)r r-rr<rrr _match_pathtszTestLoader._match_pathFc cs|j|}|dkrD||jkrD|j|||\}}|dk r<|V|sDdSttj|}x||D]t}tjj||} |j| ||\}}|dk r|V|rX|j| }|jj|z|j | ||EdHWd|jj |XqXWdS)z/Used by discovery. Yields test suites it loads.rRN) rr3_find_test_pathrDr,listdirr-rVaddrdiscard) r rr<rrrrLZshould_recursepathsr-rrrrrxs*    zTestLoader._find_testscCsPtjj|}tjj|rFtj|s(d S|j|||s:d S|j|}y|j|}WnXt j k r}zt |||j dfSd}~Xnt ||j \}} |jj| |dfStjjt|d|} ttjj| } ttjj|} | j| jkr0tjj| } ttjj|}tjj|}d}t||| |f|j||ddfSntjj|rH| rztjjtjj|d rzd Sd}d}|j|}y|j|}WnZt j k r}zt |||j dfSd}~Xnzt ||j \}} |jj| |dfSt|dd}|jj|z(|j||d}|dk r0|dfS|dfS|jj|Xnd SdS) 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). NFr{zW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?)r<z __init__.pyr=T)NF)NF)NF)NF)r,r-rrxVALID_MODULE_NAMEmatchrrrrZSkipTestr(rrr1rHrtrFr/realpathr*rzrrQrwrVr3rr)r rr<rrrrrJrNrOrPZmod_filerZfullpath_noextZ module_dirZmod_nameZ expected_dirmsgr=rLpackagerrrrsl           zTestLoader._find_test_path)N)N)rqN)F)F)rrr__doc__rj staticmethodr three_way_cmprmrr5rrsr r;rQrarer7rrrrrrrrrr)r rr0Bs$  ( N  n   "r0cCs t}||_||_|r||_|S)N)r0rmrjr)rg sortUsingrr}rrr _makeLoaders rcCst||j|S)N)rr7)r:rgrrrrr7sr7r!cCst|||j|S)N)rr;)r:rgrrrrr makeSuites rcCst|||j|S)N)rrQ)rJrgrrrrr findTestCasess r)N)!rr,rerurrYror?rrrrZ __unittestcompile IGNORECASErr&rrrrr(r/objectr0ZdefaultTestLoaderrrr7r5rrrrrrs8 ' PK!vff%__pycache__/main.cpython-36.opt-1.pycnu[3 \8)@sldZddlZddlZddlZddlmZmZddlmZdZ dZ dZ d d Z d d Z Gd ddeZeZdS)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 cCsxtjj|rt|jjdrttjj|rXtjj|tj}tjj|sP|jtj rT|S|}|ddj ddj ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirreplace)nameZrel_pathr%/usr/lib64/python3.6/unittest/main.py _convert_names rcCsdd|DS)NcSsg|] }t|qSr)r).0rrrr .sz"_convert_names..r)namesrrr_convert_names-src @seZdZdZdZdZdZZZZ Z dZ dddde j ddddddf dddd Zdd d Zd d ZddZddZddZddZddZddZdddZddZdS) TestProgramzA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. Nr__main__TF) tb_localsc Cst|tr@t||_x0|jdddD]} t|j| |_q(Wn||_|dkrTtj}||_||_ | |_ ||_ | |_ | |_ | dkrtj rd|_n| |_||_||_||_tjj|d|_|j||jdS)Nrrdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr%r1r)r2r3r*r-r+r,r.r0r partrrr__init__;s,   zTestProgram.__init__cCs4|r t||jdkr|j|jtjddS)N)print_discovery_parser_initArgParsers _print_helpr(r*)r8msgrrr usageExitas  zTestProgram.usageExitcOsZ|jdkr6t|jjttd|ji|jjn t|jjttd|jidS)Nprog) r%r< _main_parserZ format_help MAIN_EXAMPLESr5r= print_helpMODULE_EXAMPLES)r8argskwargsrrrr?is   zTestProgram._print_helpcCs|j|jdkrpt|dkrD|djdkrD|j|dddS|jj|dd||js|jgdSn|jj|dd||jrt|j|_ t dkrd|_n6|j dkrd|_ n$t |j t r|j f|_ n t|j |_ |jdS)Nrdiscoverr;r)r>r%lenr _do_discoveryrC parse_argstestsr testNames__name__r1r"r#list createTests)r8r)rrrr6rs(       zTestProgram.parseArgscCs4|jdkr|jj|j|_n|jj|j|j|_dS)N)rNr3ZloadTestsFromModuler%testZloadTestsFromNames)r8rrrrQs  zTestProgram.createTestscCs$|j}|j||_|j||_dS)N)_getParentArgParser_getMainArgParserrC_getDiscoveryArgParserr=)r8Z parent_parserrrrr>s zTestProgram._initArgParserscCstjdd}|jddddddd |jd d ddd d d |jddddd|jdkrn|jddddddd|_|jdkr|jddddddd|_|jdkr|jddddddd|_|S)NF)Zadd_helpz-vz --verboser-Z store_constr;zVerbose output)destactionZconsthelpz-qz--quietrz Quiet outputz--localsr store_truez"Show local variables in tracebacks)rVrWrXz-fz --failfastr+zStop on first fail or errorz-cz--catchr,z'Catch Ctrl-C and display results so farz-bz--bufferr.z%Buffer stdout and stderr during tests)argparseArgumentParser add_argumentr+r,r.)r8parserrrrrSs4         zTestProgram._getParentArgParsercCs2tj|gd}|j|_|j|_|jdddd|S)N)parentsrM*z?a list of any number of test modules, classes and test methods.)nargsrX)rZr[r5rBr?rEr\)r8parentr]rrrrTs zTestProgram._getMainArgParsercCs~tj|gd}d|j|_d|_|jddddd|jd d d d d|jd ddddx"dD]}|j|dtjtjdq\W|S)N)r^z %s discoverzcFor test discovery all test modules must be importable from the top level directory of the project.z-sz--start-directorystartz*Directory to start discovery ('.' default))rVrXz-pz --patternpatternz+Pattern to match tests ('test*.py' default)z-tz--top-level-directorytopzrLr3rIrR)r8r)LoaderrrrrrKs zTestProgram._do_discoverycCs|jr t|jdkrtj|_t|jtryVy"|j|j|j|j |j |j d}Wn.t k r||j|j|j|j |j d}YnXWqt k r|j}YqXn|j}|j |j|_|jrtj|jj dS)N)r-r+r.r0r )r-r+r.r0)r,rr2rZTextTestRunnerr"typer-r+r.r0r TypeErrorZrunrRresultr*r(Z wasSuccessful)r8r2rrrr7s.  zTestProgram.runTests)N)N)rO __module__ __qualname____doc__r%r-r+r,r.r5r0r=rZdefaultTestLoaderr:rAr?r6rQr>rSrTrUrKr7rrrrr1s&#    r)rmr(rZr rrZsignalsrZ __unittestrDrFrrobjectrmainrrrrs  TPK!eg%__pycache__/main.cpython-36.opt-2.pycnu[3 \8)@shddlZddlZddlZddlmZmZddlmZdZdZ dZ dd Z d d Z Gd d d e ZeZdS)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 cCsxtjj|rt|jjdrttjj|rXtjj|tj}tjj|sP|jtj rT|S|}|ddj ddj ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirreplace)nameZrel_pathr%/usr/lib64/python3.6/unittest/main.py _convert_names rcCsdd|DS)NcSsg|] }t|qSr)r).0rrrr .sz"_convert_names..r)namesrrr_convert_names-src @seZdZdZdZdZZZZZ dZ dddde j ddddddf ddddZ dd d Zd d Zd dZddZddZddZddZddZdddZddZdS) TestProgramNr__main__TF) tb_localsc Cst|tr@t||_x0|jdddD]} t|j| |_q(Wn||_|dkrTtj}||_||_ | |_ ||_ | |_ | |_ | dkrtj rd|_n| |_||_||_||_tjj|d|_|j||jdS)Nrrdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr%r1r)r2r3r*r-r+r,r.r0r partrrr__init__;s,   zTestProgram.__init__cCs4|r t||jdkr|j|jtjddS)N)print_discovery_parser_initArgParsers _print_helpr(r*)r8msgrrr usageExitas  zTestProgram.usageExitcOsZ|jdkr6t|jjttd|ji|jjn t|jjttd|jidS)Nprog) r%r< _main_parserZ format_help MAIN_EXAMPLESr5r= print_helpMODULE_EXAMPLES)r8argskwargsrrrr?is   zTestProgram._print_helpcCs|j|jdkrpt|dkrD|djdkrD|j|dddS|jj|dd||js|jgdSn|jj|dd||jrt|j|_ t dkrd|_n6|j dkrd|_ n$t |j t r|j f|_ n t|j |_ |jdS)Nrdiscoverr;r)r>r%lenr _do_discoveryrC parse_argstestsr testNames__name__r1r"r#list createTests)r8r)rrrr6rs(       zTestProgram.parseArgscCs4|jdkr|jj|j|_n|jj|j|j|_dS)N)rNr3ZloadTestsFromModuler%testZloadTestsFromNames)r8rrrrQs  zTestProgram.createTestscCs$|j}|j||_|j||_dS)N)_getParentArgParser_getMainArgParserrC_getDiscoveryArgParserr=)r8Z parent_parserrrrr>s zTestProgram._initArgParserscCstjdd}|jddddddd |jd d ddd d d |jddddd|jdkrn|jddddddd|_|jdkr|jddddddd|_|jdkr|jddddddd|_|S)NF)Zadd_helpz-vz --verboser-Z store_constr;zVerbose output)destactionZconsthelpz-qz--quietrz Quiet outputz--localsr store_truez"Show local variables in tracebacks)rVrWrXz-fz --failfastr+zStop on first fail or errorz-cz--catchr,z'Catch Ctrl-C and display results so farz-bz--bufferr.z%Buffer stdout and stderr during tests)argparseArgumentParser add_argumentr+r,r.)r8parserrrrrSs4         zTestProgram._getParentArgParsercCs2tj|gd}|j|_|j|_|jdddd|S)N)parentsrM*z?a list of any number of test modules, classes and test methods.)nargsrX)rZr[r5rBr?rEr\)r8parentr]rrrrTs zTestProgram._getMainArgParsercCs~tj|gd}d|j|_d|_|jddddd|jd d d d d|jd ddddx"dD]}|j|dtjtjdq\W|S)N)r^z %s discoverzcFor test discovery all test modules must be importable from the top level directory of the project.z-sz--start-directorystartz*Directory to start discovery ('.' default))rVrXz-pz --patternpatternz+Pattern to match tests ('test*.py' default)z-tz--top-level-directorytopzrLr3rIrR)r8r)LoaderrrrrrKs zTestProgram._do_discoverycCs|jr t|jdkrtj|_t|jtryVy"|j|j|j|j |j |j d}Wn.t k r||j|j|j|j |j d}YnXWqt k r|j}YqXn|j}|j |j|_|jrtj|jj dS)N)r-r+r.r0r )r-r+r.r0)r,rr2rZTextTestRunnerr"typer-r+r.r0r TypeErrorZrunrRresultr*r(Z wasSuccessful)r8r2rrrr7s.  zTestProgram.runTests)N)N)rO __module__ __qualname__r%r-r+r,r.r5r0r=rZdefaultTestLoaderr:rAr?r6rQr>rSrTrUrKr7rrrrr1s$#    r)r(rZr rrZsignalsrZ __unittestrDrFrrobjectrmainrrrrs  TPK!vff__pycache__/main.cpython-36.pycnu[3 \8)@sldZddlZddlZddlZddlmZmZddlmZdZ dZ dZ d d Z d d Z Gd ddeZeZdS)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 cCsxtjj|rt|jjdrttjj|rXtjj|tj}tjj|sP|jtj rT|S|}|ddj ddj ddS|S)Nz.py\./) ospathisfilelowerendswithisabsrelpathgetcwd startswithpardirreplace)nameZrel_pathr%/usr/lib64/python3.6/unittest/main.py _convert_names rcCsdd|DS)NcSsg|] }t|qSr)r).0rrrr .sz"_convert_names..r)namesrrr_convert_names-src @seZdZdZdZdZdZZZZ Z dZ dddde j ddddddf dddd Zdd d Zd d ZddZddZddZddZddZddZdddZddZdS) TestProgramzA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. Nr__main__TF) tb_localsc Cst|tr@t||_x0|jdddD]} t|j| |_q(Wn||_|dkrTtj}||_||_ | |_ ||_ | |_ | |_ | dkrtj rd|_n| |_||_||_||_tjj|d|_|j||jdS)Nrrdefaultr) isinstancestr __import__modulesplitgetattrsysargvexitfailfast catchbreak verbositybufferr warnoptionswarnings defaultTest testRunner testLoaderr r basenameprogName parseArgsrunTests)selfr%r1r)r2r3r*r-r+r,r.r0r partrrr__init__;s,   zTestProgram.__init__cCs4|r t||jdkr|j|jtjddS)N)print_discovery_parser_initArgParsers _print_helpr(r*)r8msgrrr usageExitas  zTestProgram.usageExitcOsZ|jdkr6t|jjttd|ji|jjn t|jjttd|jidS)Nprog) r%r< _main_parserZ format_help MAIN_EXAMPLESr5r= print_helpMODULE_EXAMPLES)r8argskwargsrrrr?is   zTestProgram._print_helpcCs|j|jdkrpt|dkrD|djdkrD|j|dddS|jj|dd||js|jgdSn|jj|dd||jrt|j|_ t dkrd|_n6|j dkrd|_ n$t |j t r|j f|_ n t|j |_ |jdS)Nrdiscoverr;r)r>r%lenr _do_discoveryrC parse_argstestsr testNames__name__r1r"r#list createTests)r8r)rrrr6rs(       zTestProgram.parseArgscCs4|jdkr|jj|j|_n|jj|j|j|_dS)N)rNr3ZloadTestsFromModuler%testZloadTestsFromNames)r8rrrrQs  zTestProgram.createTestscCs$|j}|j||_|j||_dS)N)_getParentArgParser_getMainArgParserrC_getDiscoveryArgParserr=)r8Z parent_parserrrrr>s zTestProgram._initArgParserscCstjdd}|jddddddd |jd d ddd d d |jddddd|jdkrn|jddddddd|_|jdkr|jddddddd|_|jdkr|jddddddd|_|S)NF)Zadd_helpz-vz --verboser-Z store_constr;zVerbose output)destactionZconsthelpz-qz--quietrz Quiet outputz--localsr store_truez"Show local variables in tracebacks)rVrWrXz-fz --failfastr+zStop on first fail or errorz-cz--catchr,z'Catch Ctrl-C and display results so farz-bz--bufferr.z%Buffer stdout and stderr during tests)argparseArgumentParser add_argumentr+r,r.)r8parserrrrrSs4         zTestProgram._getParentArgParsercCs2tj|gd}|j|_|j|_|jdddd|S)N)parentsrM*z?a list of any number of test modules, classes and test methods.)nargsrX)rZr[r5rBr?rEr\)r8parentr]rrrrTs zTestProgram._getMainArgParsercCs~tj|gd}d|j|_d|_|jddddd|jd d d d d|jd ddddx"dD]}|j|dtjtjdq\W|S)N)r^z %s discoverzcFor test discovery all test modules must be importable from the top level directory of the project.z-sz--start-directorystartz*Directory to start discovery ('.' default))rVrXz-pz --patternpatternz+Pattern to match tests ('test*.py' default)z-tz--top-level-directorytopzrLr3rIrR)r8r)LoaderrrrrrKs zTestProgram._do_discoverycCs|jr t|jdkrtj|_t|jtryVy"|j|j|j|j |j |j d}Wn.t k r||j|j|j|j |j d}YnXWqt k r|j}YqXn|j}|j |j|_|jrtj|jj dS)N)r-r+r.r0r )r-r+r.r0)r,rr2rZTextTestRunnerr"typer-r+r.r0r TypeErrorZrunrRresultr*r(Z wasSuccessful)r8r2rrrr7s.  zTestProgram.runTests)N)N)rO __module__ __qualname____doc__r%r-r+r,r.r5r0r=rZdefaultTestLoaderr:rAr?r6rQr>rSrTrUrKr7rrrrr1s&#    r)rmr(rZr rrZsignalsrZ __unittestrDrFrrobjectrmainrrrrs  TPK!g"\\%__pycache__/mock.cpython-36.opt-1.pycnu[3 \7@sFdZd ZddlZddlZddlZddlZddlmZddlm Z m Z dde eDZ e fZdejkrzddlZe ejjfZdZeZddZddZddZdddZdd Zd!d"Zd#d$Zd%d&Zdd'd(Zd)d*Zd+d,Z Gd-d.d.e!Z"Gd/d0d0e!Z#e#Z$e$j%Z%e$j&Z'e$j(Z)d1d2Z*d3d4d5d6d7d8d9d:hZ+d;d<Z,Gd=d>d>e-Z.d?d@Z/GdAdBdBe!Z0GdCdDdDe!Z1GdEd d e1Z2dFdGZ3GdHdIdIe1Z4GdJdde4e2Z5dKdLZ6dMdNZ7dOdPZ8GdQdRdRe!Z9dSdTZ:e%dddddfdUdVZ;ddWdXZd\d]Z?d^d_Z@e;e=_!e>e=_Ae#srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock2srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception8s r cCst|tr6| r6y |j}Wntk r.dSXd}n*t|ts`y |j}Wntk r^dSX|rpt|d}n|}y|tj|fSt k rdSXdS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. NT) rr__init__AttributeError FunctionTypes__call__rinspectZ signature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_object?s$    r(FcsDt|||dkrdS\}fdd}t|||t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigdsz"_check_signature..checksig)r(_copy_func_detailsr_mock_check_sig)r'mock skipfirstinstancer.r)r-r_check_signature_s   r4c#Cs|j|_|j|_y |j|_Wntk r0YnXy |j|_Wntk rRYnXy |j|_Wntk rtYnXy |j|_Wntk rYnXdS)N)__name____doc____text_signature__r" __module__ __defaults____kwdefaults__)r'funcopyrrrr/js$    r/cCs&t|trdSt|dddk r"dSdS)NTr$F)rrgetattr)rrrr _callables  r=cCst|ttfkS)N)rlisttuple)rrrr_is_listsr@cCsHt|tst|dddk Sx(|f|jD]}|jjddk r(dSq(WdS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.r$NTF)rrr<__mro____dict__get)rbaserrr_instance_callables  rEc st|s dSt|t}t|||}|dkr.|S|\}fdd}t|||j}|js^d}||d}d|} t| |||} t| || S)Ncsj||dS)N)r))r+r,)r-rrr.sz _set_signature..checksigr;)Z _checksig_r1zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) r=rrr(r/r5 isidentifierexec _setup_func) r1originalr3r2resultr'r.rcontextsrcr;r)r-r_set_signatures$       rMc s_tsdSfdd}fdd}fdd}fdd}fd d }fd d }fd d}fdd} d_d_d_t_t_t_j _ j _ j _ |_ |_ |_|_| _|_|_|__dS)Ncs j||S)N)assert_called_with)r+r,)r1rrrNsz'_setup_func..assert_called_withcs j||S)N) assert_called)r+r,)r1rrrOsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r+r,)r1rrrPsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r+r,)r1rrrQsz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r+r,)r1rrrRsz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r+r,)r1rrrSsz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r+r,)r1rrrTsz$_setup_func..assert_any_callcs:t_t_jj}t|r6|k r6|jdS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)r;r1rrrXs z_setup_func..reset_mockFr)r1rcalled call_count call_argsrUcall_args_listrVrWrY side_effect_mock_childrenrNrRrSrTrXrOrPrQ_mock_delegate) r;r1rNrOrPrQrRrSrTrXr)r;r1rrHs:       rHcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrdc@s eZdZdZddZddZdS)_SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r)selfrrrrr!sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rfrrr__repr__sz_SentinelObject.__repr__N)r5r8 __qualname__r6r!rgrrrrresrec@s eZdZdZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)rfrrrr!sz_Sentinel.__init__cCs|dkr t|jj|t|S)N __bases__)r"rj setdefaultre)rfrrrr __getattr__sz_Sentinel.__getattr__N)r5r8rhr6r!rmrrrrrisricCs$t|ttttfkr t||S|S)N)rdictr>r?set)valuerrr_copys rqrY_mock_return_valuer__mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8tj|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||S)N)rar<)rfr _the_namer-rrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rarBsetattr)rfrprrxr-rrr_set$s z"_delegating_property.._set)_allowed_namesaddproperty)rrxryr{rrr_delegating_propertys  rc@seZdZddZddZdS)rUcCsnt|tstj||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)rr> __contains__lenrange)rfrpZ len_valueZlen_selfiZsub_listrrrr1s  z_CallList.__contains__cCstjt|S)N)pprintZpformatr>)rfrrrrg?sz_CallList.__repr__N)r5r8rhrrgrrrrrU/srUcCsxt|s dS|js,|js,|jdk s,|jdk r0dS|}x|dk rR||krJdS|j}q6W|rd||_||_|rt||_||_dS)NFT)rrvrwrtru)parentrprnew_name_parentrrr_check_and_set_parentCs$     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rfrrrrr!]sz_MockIter.__init__cCs|S)Nr)rfrrr__iter___sz_MockIter.__iter__cCs t|jS)N)nextr)rfrrr__next__asz_MockIter.__next__N)r5r8rhr!rrrrrrr\src@seZdZeZdZddZdS)BaseNcOsdS)Nr)rfr+r,rrrr!gsz Base.__init__)r5r8rhrrrrsr!rrrrrdsrc @sHeZdZdZddZdDddZd d ZdEd d ZdFd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdGdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z d2d3Z!d4d5Z"d6d7Z#d8d9Z$d:d;Z%dd?Z'd@dAZ(dBdCZ)dS)Ir z A non-callable version of `Mock`cOs$t|j|fd|ji}tj|}|S)Nr6)rr5r6object__new__)clsr+kwnewr3rrrros zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<|dk rB|}d}| dkrR|dk } |j||| | i| d<|| d<d| d<d | d <d| d <d | d <t| d<t| d<t| d<| | d<| r|jf| tt|j||||||dS)NrtrvrwruTr` _mock_wrapsraFZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrV _mock_unsafe)rB_mock_add_specrUconfigure_mock _safe_superr r!)rfspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer,rBrrrr!xs8      zNonCallableMock.__init__cCs(d|_d|_d|_d|_t|||dS)z 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.Nr)rtrurvrwrz)rfr1 attributerrr attach_mocks zNonCallableMock.attach_mockcCs|j||dS)zAdd 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.N)r)rfrrrrr mock_add_specszNonCallableMock.mock_add_specc Cs|d}d}|dk rRt| rRt|tr*|}nt|}t|||}|oH|d}t|}|j}||d<||d<||d<||d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods)r@rr _get_classr(dirrB) rfrrrrrrresrBrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rrrarYr_get_child_mock)rfrZrrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rarYrrr)rfrprrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rfrrr __class__s zNonCallableMock.__class__r[r\r]r^rWcCsT|j}|dkr|jS|j}|dk rPt| rPt|t rPt| rPt|}||_|S)N)rarsr_callablerrr )rf delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrarsr_)rfrprrrrZ__set_side_effects z!NonCallableMock.__set_side_effect)rYr_cCs|dkr g}t||krdS|jt|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ x0|j j D]"}t|tst|tkrqt|j|qtW|j }t|r||k r|j|dS)z-Restore the mock object to its initial state.NFr)idappendr[r]r\rUrWr^rVrrrrsr`valuesr _SpecState_deletedrXr)rfZvisitedrYr_ZchildrZrrrrX s, zNonCallableMock.reset_mockcKs`xZt|jdddD]B\}}|jd}|j}|}x|D]}t||}q:Wt|||qWdS)aZSet 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)cSs|djdS)Nr.)count)entryrrr8sz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr<rz)rfr,argvalr+finalrrrrrr+s   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|jdrdt||jj|}|tkrt|np|dkrd}|j dk rt |j |}|j |||||d}||j|<n.t |t rt|j|j|j|j|j}||j|<|S) NrrzMock object has no attribute %rassertassret)rrrrr>rr)rr)r"r _all_magicsrdrrr`rCrrr<rrrrrrr3rr)rfrrJrrrrrmAs6            zNonCallableMock.__getattr__c Cs"|jg}|j}|}d}|dgkr$d}t}xT|dk r~|}|j|j|d}|jdkrZd}|j}t||krnP|jt|q,Wtt|}|jpd}t |dkr|dd kr|d7}||d<dj |}d}|dkrd |}d} |j dk rd } |j rd } | |j j } d t|j || t|fS)Nr()rr1r().rmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rr)r1r)rwrurorrr}r>reversedrvrjoinrrr5r) rfZ _name_listrZlastdotseenZ_firstrZ name_stringZ spec_stringrrrrggsL           zNonCallableMock.__repr__cCshtstj|S|jpg}tt|}t|j}dd|D}dd|D}tt |||t|j S)z8Filter the output of `dir(mock)` to only useful members.cSsg|]}|jds|qS)r)r)rerrr sz+NonCallableMock.__dir__..cSs$g|]}|jd st|r|qS)r)rrd)rrrrrrs) r r__dir__rrrr>rBrror`)rfZextrasZ from_typeZ from_dictrrrrs    zNonCallableMock.__dir__cs"|tkrtj||SjrHjdk rH|jkrH|jkrHtd|n|tkrbd|}t|n|tkrjdk r|jkrtd|t |st t |t |||fdd}n(t |d|t t |||j|<n.|dkr|_dSt |||r|j|<tj||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csf||S)Nr)r+r)rIrfrrrsz-NonCallableMock.__setattr__..r)r|r __setattr__rrrBr"_unsupported_magicsrrrzr _get_methodrr`r)rfrrpmsgr)rIrfrrs2       zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS||jkrHtj|||jj|t}|t krft ||tk rv|j|=t |j|<dS)N) rrrBdelattrr __delattr__r`rC_missingrr")rfrrrrrrs   zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr1)rv_format_call_signature)rfr+r,rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|j||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rr]r)rfr+r,messageexpected_stringr]Z actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagecCst|j}|dk rlt|dkr(d}|\}}n |\}}}y||j||fStk rh}z |jdSd}~XqpXn|SdS)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. Nrbr)rrr) TypeErrorwith_traceback)rf_callr-rr+r,rrrr _call_matchers   zNonCallableMock._call_matchercCs.|}|jdkr*d|jpd|jf}t|dS)z/assert that the mock was never called. rz7Expected '%s' to not have been called. Called %s times.r1N)r\rvAssertionError)r*rfrrrrrPs  z!NonCallableMock.assert_not_calledcCs(|}|jdkr$d|jpd}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.r1N)r\rvr)r*rfrrrrrO s   zNonCallableMock.assert_calledcCs.|}|jdks*d|jpd|jf}t|dS)z3assert that the mock was called only once. rz8Expected '%s' to have been called once. Called %s times.r1N)r\rvr)r*rfrrrrrQs  z"NonCallableMock.assert_called_oncecs||jdkr(j}td|ffdd}jf}jj}||krxt|trh|nd}t||dS)zassert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.NzExpected call: %s Not calledcsj}|S)N)r)r)r+r,rfrr_error_message's z:NonCallableMock.assert_called_with.._error_message)r]rrrr Exception)r*r+r,expectedractualcauser)r+r,rfrrNs   z"NonCallableMock.assert_called_withcOs6|}|jdks*d|jpd|jf}t||j||S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rz1Expected '%s' to be called once. Called %s times.r1)r\rvrrN)r*r+r,rfrrrrrR1s  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sd||kr`tdt|jf|dSt|}g}x:|D]2}y|j|Wqvtk r|j|YqvXqvW|rtdt |f|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`.csg|]}j|qSr)r)rc)rfrrrFsz4NonCallableMock.assert_has_calls..Nc3s|]}j|VqdS)N)r)rr)rfrr Hsz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) rrrUrWrr>remover&rr?)rfZcallsZ any_orderrrZ all_callsZ not_foundZkallr)rfrrS<s*  z NonCallableMock.assert_has_callscsZj||f}fddjD}||krVt|tr8|nd}j||}td||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.csg|]}j|qSr)r)rr)rfrrrfsz3NonCallableMock.assert_any_call..Nz%s call not found)rr^rrrr)rfr+r,rrrrr)rfrrT_s zNonCallableMock.assert_any_callcKsFt|}t|ts2t|tr"t}q.) rrrrrrrrrr,attribute_namer)rfrrrrrisz _patch.copycCst|tr|j|S|j|S)N)rrdecorate_classdecorate_callable)rfr'rrrr$vs  z_patch.__call__cCsRxLt|D]@}|jtjsq t||}t|ds2q |j}t||||q W|S)Nr$)rrr TEST_PREFIXr<rrrz)rfrattr attr_valuerrrrr|s   z_patch.decorate_classcs<tdrjj|Stfdd|g_S)N patchingscsg}g}t}zybxJjD]@}|j}|j||jdk rF|j|q|jtkr|j|qW|t|7}||S||krt|r|j|t j }YnXWdxt |D]}|j |qWXdS)N) r?r __enter__rrupdaterrrsysexc_infor__exit__)r+Zkeywargs extra_argsZentered_patchersr patchingr)r'patchedrrrs*         z)_patch.decorate_callable..patched)rrrr)rfr'r)r'rrrs   z_patch.decorate_callablec Cs|j}|j}t}d}y|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j r|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rrrrBr"KeyErrorr< _builtinsrrr)rfrrrIlocalrrr get_originalsz_patch.get_originalcCs>|j|j|j}}}|j|j}}|j}|j|_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd|j \}}|t ko|dkrTd} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r,|t krtdt |t r,d} t } i} |dk rD|} nN|dk sX|dk r|} |dk rj|} t| r~d| k} n t|  } | rt} |dk r|| d<|dk r|| d <t | t rt| tr|jr|j| d <| j|| f| }| rt|r|} |dk r|} t|  r2t|  r2t} | jd | f|d d | |_nl|dk r|t k rptd |t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r:i}|jt kr|||j<x.|jD]$}|j }|jt kr|j|qW|S|S)zPerform the patch.FNzCan't specify spec and autospecTz6Can't provide explicit spec_set *and* spec or autospecz!Can't use 'spec' with create=Truer$rrrz())rrzBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=True)r_namez.Can't pass kwargs to a mock we aren't creating)TN)!rrrrr,rrrrrrrrrr@rr rr rr rrErrYboolr temp_originalrrzrrr )rfrrrrr,rrIrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrrr s                              z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jnBt|j|j|j rvt |j|j sd|jdkrvt|j|j|j|`|`|`x$t |j D]}t|r|j |qWdS) zUndo the patch.z stop called on unstarted patcherr6r8r9__annotations__r:N)r6r8r9rr:)r RuntimeErrorrrrrzrrrrrrrr )rfr rrrrr Hs z_patch.__exit__cCs|j}|jj||S)z-Activate a patch, returning any created mock.)r _active_patchesr)rfrJrrrstart`s z _patch.startc Cs.y|jj|Wntk r$YnX|jS)zStop an active patch.)rrr&r )rfrrrstopgs z _patch.stop)r5r8rhrrr!rr$rrrr r rrrrrrrIs (~rc sPyjdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrysz_get_target..)rsplitrr&)rrrr)rr _get_targetss r c s$fdd} 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. csS)Nrr)rrrrsz_patch_object..)r) rrrrrrrrr,rr)rr _patch_object}s  r!c sttkrfdd}n fdd}|s2tdt|j}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| jj| qvW| 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. cstS)N)rr)rrrrsz!_patch_multiple..csS)Nrr)rrrrsz=Must supply at least one keyword argument with patch.multiplerrN) rstrr&r>rrrrr) rrrrrrr,rrrrrZ this_patcherr)rr_patch_multiples&        r#c Ks$t|\}} 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 a `MagicMock`. 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 `MagicMock` is used. 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` takes arbitrary keyword arguments. These will be passed to the `Mock` (or `new_callable`) on construction. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. )r r) rrrrrrrr,rrrrrrsE  c@sVeZdZdZfdfddZddZddZd d Zd d Zd dZ ddZ eZ e Z dS) _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. FcKs>t|trt|}||_t||_|jj|||_d|_dS)N) rr"rin_dictrnrr clear _original)rfr%rr&r,rrrr!0s   z_patch_dict.__init__cs.ttrjStfdd}|S)Nc s"jz ||SjXdS)N)r$ _unpatch_dict)r+r)frfrr_inner>s z$_patch_dict.__call__.._inner)rrrr)rfr)r*r)r)rfrr$;s  z_patch_dict.__call__cCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)Nr$) rr<rrrrr$r%rr&rz)rfrrrZ decoratorZ decoratedrrrrIs   z_patch_dict.decorate_classcCs |jdS)zPatch the dict.N)r$)rfrrrr Tsz_patch_dict.__enter__cCs|j}|j}|j}y |j}Wn2tk rPi}x|D]}||||<q8WYnX||_|rdt|y|j|Wn.tk rx|D]}||||<qWYnXdS)N)rr%r&rr"r' _clear_dictr )rfrr%r&rIrrrrr$Ys"   z_patch_dict._patch_dictc CsV|j}|j}t|y|j|Wn.tk rPx|D]}||||<q8WYnXdS)N)r%r'r+r r")rfr%rIrrrrr(ss z_patch_dict._unpatch_dictcGs |jdS)zUnpatch the dict.F)r()rfr+rrrr sz_patch_dict.__exit__N) r5r8rhr6r!r$rr r$r(r rrrrrrr$s   r$c CsBy |jWn0tk r<t|}x|D] }||=q*WYnXdS)N)r&r"r>)r%keysrrrrr+s   r+cCs xttjD] }|jq WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrrr)rrrr_patch_stopallsr-Ztestzlt 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 trunc floor ceil bool next zHadd sub mul matmul div floordiv mod lshift rshift and xor or pow truediv ccs|]}d|VqdS)zi%sNr)rnrrrrsrccs|]}d|VqdS)zr%sNr)rr/rrrrs__get____set__ __delete__ __reversed__ __missing__ __reduce__ __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__ __setformat__rgr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)rfr+r)r'rrmethodsz_get_method..method)r5)rr'r?r)r'rrs rcCsh|] }d|qS)z__%s__r)rr?rrrrsrmrr!r __prepare____instancecheck____subclasscheck____del__cCs tj|S)N)r__hash__)rfrrrrsrcCs tj|S)N)r__str__)rfrrrrscCs tj|S)N)r __sizeof__)rfrrrrs)rDrErFry?g?) __lt____gt____le____ge____int__r__len__r  __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__rrrNotImplemented)otherret_val)rfrrrQs z_get_eq..__eq__r)rfrQr)rfr_get_eqs rUcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__rrrrR)rS)rfrrrVs  z_get_ne..__ne__r)rfrVr)rfr_get_nes rWcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rrrrr)rT)rfrrrsz_get_iter..__iter__r)rfrr)rfr _get_iters rX)rQrVrc Cstj|t}|tk r||_dStj|}|dk rdy ||}Wntk rXt|}YnX||_dStj|}|dk r|||_dS)N)_return_valuesrCrrY_calculate_return_valuer"_side_effect_methodsr_)r1r?rZfixedZreturn_calulatorrYZ side_effectorrrr_set_return_values    r\c@seZdZddZddZdS) MagicMixincOs&|jtt|j|||jdS)N)_mock_set_magicsrr]r!)rfr+rrrrr!(szMagicMixin.__init__cCst}t|dddk rTtj|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr< intersectionrrorrBrrz MagicProxy)rfZ these_magicsZ remove_magicsrrrrrr^.s   zMagicMixin._mock_set_magicsN)r5r8rhr!r^rrrrr]'sr]c@seZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcCs|j|||jdS)zAdd 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.N)rr^)rfrrrrrrGs z"NonCallableMagicMock.mock_add_specN)F)r5r8rhr6rrrrrr Esc@seZdZdZdddZdS)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`. FcCs|j|||jdS)zAdd 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.N)rr^)rfrrrrrr]s zMagicMock.mock_add_specN)F)r5r8rhr6rrrrrrRs c@s.eZdZddZddZddZd dd ZdS) racCs||_||_dS)N)rr)rfrrrrrr!iszMagicProxy.__init__cOs|j}|||S)N) create_mock)rfr+r,mrrrr$mszMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrzr\)rfrrrcrrrrbqs  zMagicProxy.create_mockNcCs|jS)N)rb)rfrrrrrr0zszMagicProxy.__get__)N)r5r8rhr!r$rbr0rrrrrahs rac@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)rfrSrrrrQsz _ANY.__eq__cCsdS)NFr)rfrSrrrrVsz _ANY.__ne__cCsdS)Nzr)rfrrrrgsz _ANY.__repr__N)r5r8rhr6rQrVrgrrrrrdsrdcCsdd|}d}djdd|D}djddt|jD}|rD|}|r\|rT|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrrsz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrprrrrs)rrr)rr+r,rZformatted_argsZ args_stringZ kwargs_stringrrrrsrc@sveZdZdZfddddfddZfddddfdd Zd d ZejZd d Z ddZ ddZ ddZ ddZ ddZdS)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. rNFTc Csf}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rtj|||fStj||||fS)Nrrbr)rrr"r?r) rrprrr from_kallr+r,_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)rvrt_mock_from_kall)rfrprrrrfrrrr!sz_Call.__init__c Csf|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}t|ddrzt|ddrz|j|jkrzdSd}|dkrfi}}n|dkr|\}}}n|dkr|\} t| tr| }i}n"t| tr| }fi}}nf}| }nV|dkr>|\} } t| tr2| }t| tr&| i}}n f| }}n | | }}ndS|rV||krVdS||f||fkS) NTFrrbrtrrr)rrrr<rtrr?r") rfrSZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrprhrirrrrQsP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)rvr)rfr+r,rrrrr$s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrfz%s.%s)rrrf)rvr)rfrrrrrrms  z_Call.__getattr__cOs|jd||S)Nr)rm)rfr+r,rrrr$sz _Call.countcOs|jd||S)Nindex)rm)rfr+r,rrrrk'sz _Call.indexcCs||js&|jpd}|jdr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|jdshd|}nd|}t|||S)Nrz()zcall%srbzcall.%s)rjrvrrr)rfrr+r,rrrrg*s       z_Call.__repr__cCs8g}|}x"|dk r*|jr"|j||j}q Wtt|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.N)rjrrtrUr)rfvalsrrrr call_list?s   z_Call.call_list)r5r8rhr6rr!rQrrVr$rmrrkrgrmrrrrrs  7r)rfcKs,t|rt|}t|t}d|i}|r0d|i}n |dkr.rrxrxrxrx)rbytesr) read_dataZ data_as_listliner)rwr_iterate_read_data s  r|rcsfdd}fdd}fddtdkr`ddl}ttt|jjtt|ja|dkrttd t d }ttd j _ t dgdj _ dj_ dj_ dj_ |j_d <d j_|j_fd d}||_|_ |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` methoddline`, and `readlines` of the file handle to return. This is an empty string by default. cs jjdk rjjStdS)Nr) readlinesrYr>)r+r,)_statehandlerr_readlines_side_effect( s z)mock_open.._readlines_side_effectcs(jjdk rjjStjdS)Nr)readrYrr)r+r,)r~rrzrr_read_side_effect- s z$mock_open.._read_side_effectc3sJjjdk rxjjVqWxdD] }|Vq&WxtVq6WdS)Nr)readlinerYr)r{)r~rrzrr_readline_side_effect2 s  z(mock_open.._readline_side_effectNropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r|rr_r)r+r,)rr~rrzrr reset_dataS s    zmock_open..reset_data) file_spec_ior>ror TextIOWrapperunionBytesIOrrr rYr|writerrr}r_)r1rzrrrrr)rr~rrzrr  s.  "     c@s(eZdZdZddZddZddZdS) r aW 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. cKs tf|S)N)r)rfr,rrrri szPropertyMock._get_child_mockcCs|S)Nr)rfrZobj_typerrrr0l szPropertyMock.__get__cCs ||dS)Nr)rfrrrrrr1n szPropertyMock.__set__N)r5r8rhr6rr0r1rrrrr ` s) rrrrrrrrr r r r r )F)F)NFNNN)FFNN)Nr)o__all__ __version__r%rr builtinstypesr functoolsrrrr BaseExceptionrplatformrZlangZ Throwabler superrrr r(r4r/r=r@rErMrHrdrrerirrZMISSINGrZDELETEDrrqr|rr>rUrrrr rrrrrrrr r!r#rr$r+r-rnZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrr_rrrZrRrYrUrWrXr[r\r]r rrardrrr?rrrrnrrrrQr#r0rrrr|r r rrrrs     4  i5 ,   1Jv        ,  w  DPK!+eQdd%__pycache__/mock.cpython-36.opt-2.pycnu[3 \7@sFdZd ZddlZddlZddlZddlZddlmZddlm Z m Z dde eDZ e fZdejkrzddlZe ejjfZdZeZddZddZddZdddZdd Zd!d"Zd#d$Zd%d&Zdd'd(Zd)d*Zd+d,Z Gd-d.d.e!Z"Gd/d0d0e!Z#e#Z$e$j%Z%e$j&Z'e$j(Z)d1d2Z*d3d4d5d6d7d8d9d:hZ+d;d<Z,Gd=d>d>e-Z.d?d@Z/GdAdBdBe!Z0GdCdDdDe!Z1GdEd d e1Z2dFdGZ3GdHdIdIe1Z4GdJdde4e2Z5dKdLZ6dMdNZ7dOdPZ8GdQdRdRe!Z9dSdTZ:e%dddddfdUdVZ;ddWdXZd\d]Z?d^d_Z@e;e=_!e>e=_Ae#srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock2srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception8s r cCst|tr6| r6y |j}Wntk r.dSXd}n*t|ts`y |j}Wntk r^dSX|rpt|d}n|}y|tj|fSt k rdSXdS)NT) rr__init__AttributeError FunctionTypes__call__rinspectZ signature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_object?s$    r(FcsDt|||dkrdS\}fdd}t|||t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigdsz"_check_signature..checksig)r(_copy_func_detailsr_mock_check_sig)r'mock skipfirstinstancer.r)r-r_check_signature_s   r4c#Cs|j|_|j|_y |j|_Wntk r0YnXy |j|_Wntk rRYnXy |j|_Wntk rtYnXy |j|_Wntk rYnXdS)N)__name____doc____text_signature__r" __module__ __defaults____kwdefaults__)r'funcopyrrrr/js$    r/cCs&t|trdSt|dddk r"dSdS)NTr$F)rrgetattr)rrrr _callables  r=cCst|ttfkS)N)rlisttuple)rrrr_is_listsr@cCsHt|tst|dddk Sx(|f|jD]}|jjddk r(dSq(WdS)Nr$TF)rrr<__mro____dict__get)rbaserrr_instance_callables  rEc st|s dSt|t}t|||}|dkr.|S|\}fdd}t|||j}|js^d}||d}d|} t| |||} t| || S)Ncsj||dS)N)r))r+r,)r-rrr.sz _set_signature..checksigr;)Z _checksig_r1zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) r=rrr(r/r5 isidentifierexec _setup_func) r1originalr3r2resultr'r.rcontextsrcr;r)r-r_set_signatures$       rMc s_tsdSfdd}fdd}fdd}fdd}fd d }fd d }fd d}fdd} d_d_d_t_t_t_j _ j _ j _ |_ |_ |_|_| _|_|_|__dS)Ncs j||S)N)assert_called_with)r+r,)r1rrrNsz'_setup_func..assert_called_withcs j||S)N) assert_called)r+r,)r1rrrOsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r+r,)r1rrrPsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r+r,)r1rrrQsz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r+r,)r1rrrRsz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r+r,)r1rrrSsz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r+r,)r1rrrTsz$_setup_func..assert_any_callcs:t_t_jj}t|r6|k r6|jdS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)r;r1rrrXs z_setup_func..reset_mockFr)r1rcalled call_count call_argsrUcall_args_listrVrWrY side_effect_mock_childrenrNrRrSrTrXrOrPrQ_mock_delegate) r;r1rNrOrPrQrRrSrTrXr)r;r1rrHs:       rHcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrdc@seZdZddZddZdS)_SentinelObjectcCs ||_dS)N)r)selfrrrrr!sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rfrrr__repr__sz_SentinelObject.__repr__N)r5r8 __qualname__r!rgrrrrresrec@seZdZddZddZdS) _SentinelcCs i|_dS)N) _sentinels)rfrrrr!sz_Sentinel.__init__cCs|dkr t|jj|t|S)N __bases__)r"rj setdefaultre)rfrrrr __getattr__sz_Sentinel.__getattr__N)r5r8rhr!rmrrrrrisricCs$t|ttttfkr t||S|S)N)rdictr>r?set)valuerrr_copys rqrY_mock_return_valuer__mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8tj|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||S)N)rar<)rfr _the_namer-rrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rarBsetattr)rfrprrxr-rrr_set$s z"_delegating_property.._set)_allowed_namesaddproperty)rrxryr{rrr_delegating_propertys  rc@seZdZddZddZdS)rUcCsnt|tstj||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)rr> __contains__lenrange)rfrpZ len_valueZlen_selfiZsub_listrrrr1s  z_CallList.__contains__cCstjt|S)N)pprintZpformatr>)rfrrrrg?sz_CallList.__repr__N)r5r8rhrrgrrrrrU/srUcCsxt|s dS|js,|js,|jdk s,|jdk r0dS|}x|dk rR||krJdS|j}q6W|rd||_||_|rt||_||_dS)NFT)rrvrwrtru)parentrprnew_name_parentrrr_check_and_set_parentCs$     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rfrrrrr!]sz_MockIter.__init__cCs|S)Nr)rfrrr__iter___sz_MockIter.__iter__cCs t|jS)N)nextr)rfrrr__next__asz_MockIter.__next__N)r5r8rhr!rrrrrrr\src@seZdZeZdZddZdS)BaseNcOsdS)Nr)rfr+r,rrrr!gsz Base.__init__)r5r8rhrrrrsr!rrrrrdsrc @sDeZdZddZdCddZdd ZdDd d ZdEd d ZddZddZ dZ e ee e Z e ddZ edZedZedZedZedZddZddZe eeZdFddddd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Z d3d4Z!d5d6Z"d7d8Z#d9d:Z$d;d<Z%dGd=d>Z&d?d@Z'dAdBZ(dS)Hr cOs$t|j|fd|ji}tj|}|S)Nr6)rr5r6object__new__)clsr+kwnewr3rrrros zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<|dk rB|}d}| dkrR|dk } |j||| | i| d<|| d<d| d<d | d <d| d <d | d <t| d<t| d<t| d<| | d<| r|jf| tt|j||||||dS)NrtrvrwruTr` _mock_wrapsraFZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrV _mock_unsafe)rB_mock_add_specrUconfigure_mock _safe_superr r!)rfspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer,rBrrrr!xs8      zNonCallableMock.__init__cCs(d|_d|_d|_d|_t|||dS)Nr)rtrurvrwrz)rfr1 attributerrr attach_mocks zNonCallableMock.attach_mockcCs|j||dS)N)r)rfrrrrr mock_add_specszNonCallableMock.mock_add_specc Cs|d}d}|dk rRt| rRt|tr*|}nt|}t|||}|oH|d}t|}|j}||d<||d<||d<||d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods)r@rr _get_classr(dirrB) rfrrrrrrresrBrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rrrarYr_get_child_mock)rfrZrrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rarYrrr)rfrprrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rfrrr __class__s zNonCallableMock.__class__r[r\r]r^rWcCsT|j}|dkr|jS|j}|dk rPt| rPt|t rPt| rPt|}||_|S)N)rarsr_callablerrr )rf delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrarsr_)rfrprrrrZ__set_side_effects z!NonCallableMock.__set_side_effect)rYr_cCs|dkr g}t||krdS|jt|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ x0|j j D]"}t|tst|tkrqt|j|qtW|j }t|r||k r|j|dS)NFr)idappendr[r]r\rUrWr^rVrrrrsr`valuesr _SpecState_deletedrXr)rfZvisitedrYr_ZchildrZrrrrX s, zNonCallableMock.reset_mockcKs`xZt|jdddD]B\}}|jd}|j}|}x|D]}t||}q:Wt|||qWdS)NcSs|djdS)Nr.)count)entryrrr8sz0NonCallableMock.configure_mock..)keyr)sorteditemssplitpopr<rz)rfr,argvalr+finalrrrrrr+s   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|jdrdt||jj|}|tkrt|np|dkrd}|j dk rt |j |}|j |||||d}||j|<n.t |t rt|j|j|j|j|j}||j|<|S) NrrzMock object has no attribute %rassertassret)rrrrr>rr)rr)r"r _all_magicsrdrrr`rCrrr<rrrrrrr3rr)rfrrJrrrrrmAs6            zNonCallableMock.__getattr__c Cs"|jg}|j}|}d}|dgkr$d}t}xT|dk r~|}|j|j|d}|jdkrZd}|j}t||krnP|jt|q,Wtt|}|jpd}t |dkr|dd kr|d7}||d<dj |}d}|dkrd |}d} |j dk rd } |j rd } | |j j } d t|j || t|fS)Nr()rr1r().rmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rr)r1r)rwrurorrr}r>reversedrvrjoinrrr5r) rfZ _name_listrZlastdotseenZ_firstrZ name_stringZ spec_stringrrrrggsL           zNonCallableMock.__repr__cCshtstj|S|jpg}tt|}t|j}dd|D}dd|D}tt |||t|j S)NcSsg|]}|jds|qS)r)r)rerrr sz+NonCallableMock.__dir__..cSs$g|]}|jd st|r|qS)r)rrd)rrrrrrs) r r__dir__rrrr>rBrror`)rfZextrasZ from_typeZ from_dictrrrrs    zNonCallableMock.__dir__cs"|tkrtj||SjrHjdk rH|jkrH|jkrHtd|n|tkrbd|}t|n|tkrjdk r|jkrtd|t |st t |t |||fdd}n(t |d|t t |||j|<n.|dkr|_dSt |||r|j|<tj||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csf||S)Nr)r+r)rIrfrrrsz-NonCallableMock.__setattr__..r)r|r __setattr__rrrBr"_unsupported_magicsrrrzr _get_methodrr`r)rfrrpmsgr)rIrfrrs2       zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS||jkrHtj|||jj|t}|t krft ||tk rv|j|=t |j|<dS)N) rrrBdelattrr __delattr__r`rC_missingrr")rfrrrrrrs   zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr1)rv_format_call_signature)rfr+r,rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|j||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rr]r)rfr+r,messageexpected_stringr]Z actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagecCst|j}|dk rlt|dkr(d}|\}}n |\}}}y||j||fStk rh}z |jdSd}~XqpXn|SdS)Nrbr)rrr) TypeErrorwith_traceback)rf_callr-rr+r,rrrr _call_matchers   zNonCallableMock._call_matchercCs.|}|jdkr*d|jpd|jf}t|dS)Nrz7Expected '%s' to not have been called. Called %s times.r1)r\rvAssertionError)r*rfrrrrrPs  z!NonCallableMock.assert_not_calledcCs(|}|jdkr$d|jpd}t|dS)Nrz"Expected '%s' to have been called.r1)r\rvr)r*rfrrrrrO s   zNonCallableMock.assert_calledcCs.|}|jdks*d|jpd|jf}t|dS)Nrz8Expected '%s' to have been called once. Called %s times.r1)r\rvr)r*rfrrrrrQs  z"NonCallableMock.assert_called_oncecs||jdkr(j}td|ffdd}jf}jj}||krxt|trh|nd}t||dS)NzExpected call: %s Not calledcsj}|S)N)r)r)r+r,rfrr_error_message's z:NonCallableMock.assert_called_with.._error_message)r]rrrr Exception)r*r+r,expectedractualcauser)r+r,rfrrNs   z"NonCallableMock.assert_called_withcOs6|}|jdks*d|jpd|jf}t||j||S)Nrz1Expected '%s' to be called once. Called %s times.r1)r\rvrrN)r*r+r,rfrrrrrR1s  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sd||kr`tdt|jf|dSt|}g}x:|D]2}y|j|Wqvtk r|j|YqvXqvW|rtdt |f|dS)Ncsg|]}j|qSr)r)rc)rfrrrFsz4NonCallableMock.assert_has_calls..c3s|]}j|VqdS)N)r)rr)rfrr Hsz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) rrrUrWrr>remover&rr?)rfZcallsZ any_orderrrZ all_callsZ not_foundZkallr)rfrrS<s*  z NonCallableMock.assert_has_callscsZj||f}fddjD}||krVt|tr8|nd}j||}td||dS)Ncsg|]}j|qSr)r)rr)rfrrrfsz3NonCallableMock.assert_any_call..z%s call not found)rr^rrrr)rfr+r,rrrrr)rfrrT_s zNonCallableMock.assert_any_callcKsFt|}t|ts2t|tr"t}q.) rrrrrrrrrr,attribute_namer)rfrrrrrisz _patch.copycCst|tr|j|S|j|S)N)rrdecorate_classdecorate_callable)rfr'rrrr$vs  z_patch.__call__cCsRxLt|D]@}|jtjsq t||}t|ds2q |j}t||||q W|S)Nr$)rrr TEST_PREFIXr<rrrz)rfrattr attr_valuerrrrr|s   z_patch.decorate_classcs<tdrjj|Stfdd|g_S)N patchingscsg}g}t}zybxJjD]@}|j}|j||jdk rF|j|q|jtkr|j|qW|t|7}||S||krt|r|j|t j }YnXWdxt |D]}|j |qWXdS)N) r?r __enter__rrupdaterrrsysexc_infor__exit__)r+Zkeywargs extra_argsZentered_patchersr patchingr)r'patchedrrrs*         z)_patch.decorate_callable..patched)rrrr)rfr'r)r'rrrs   z_patch.decorate_callablec Cs|j}|j}t}d}y|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j r|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rrrrBr"KeyErrorr< _builtinsrrr)rfrrrIlocalrrr get_originalsz_patch.get_originalcCs>|j|j|j}}}|j|j}}|j}|j|_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd|j \}}|t ko|dkrTd} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r,|t krtdt |t r,d} t } i} |dk rD|} nN|dk sX|dk r|} |dk rj|} t| r~d| k} n t|  } | rt} |dk r|| d<|dk r|| d<t | t rt| tr|jr|j| d <| j|| f| }| rt|r|} |dk r|} t|  r2t|  r2t} | jd | f|d d | |_nl|dk r|t k rptd |t krtd t|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r:i}|jt kr|||j<x.|jD]$}|j }|jt kr|j|qW|S|S)NFzCan't specify spec and autospecTz6Can't provide explicit spec_set *and* spec or autospecz!Can't use 'spec' with create=Truer$rrrz())rrzBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=True)r_namez.Can't pass kwargs to a mock we aren't creating)TN)!rrrrr,rrrrrrrrrr@rr rr rr rrErrYboolr temp_originalrrzrrr )rfrrrrr,rrIrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrrr s                              z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jnBt|j|j|j rvt |j|j sd|jdkrvt|j|j|j|`|`|`x$t |j D]}t|r|j |qWdS)Nz stop called on unstarted patcherr6r8r9__annotations__r:)r6r8r9rr:)r RuntimeErrorrrrrzrrrrrrrr )rfr rrrrr Hs z_patch.__exit__cCs|j}|jj||S)N)r _active_patchesr)rfrJrrrstart`s z _patch.startc Cs.y|jj|Wntk r$YnX|jS)N)rrr&r )rfrrrstopgs z _patch.stop)r5r8rhrrr!rr$rrrr r rrrrrrrIs (~rc sPyjdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrysz_get_target..)rsplitrr&)rrrr)rr _get_targetss r c s$fdd} t| |||||||| S)NcsS)Nrr)rrrrsz_patch_object..)r) rrrrrrrrr,rr)rr _patch_object}s  r!c sttkrfdd}n fdd}|s2tdt|j}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| jj| qvW| S)NcstS)N)rr)rrrrsz!_patch_multiple..csS)Nrr)rrrrsz=Must supply at least one keyword argument with patch.multiplerr) rstrr&r>rrrrr) rrrrrrr,rrrrrZ this_patcherr)rr_patch_multiples&        r#c Ks$t|\}} t|| ||||||| S)N)r r) rrrrrrrr,rrrrrrsE  c@sReZdZfdfddZddZddZdd Zd d Zd d ZddZ eZ e Z dS) _patch_dictFcKs>t|trt|}||_t||_|jj|||_d|_dS)N) rr"rin_dictrnrr clear _original)rfr%rr&r,rrrr!0s   z_patch_dict.__init__cs.ttrjStfdd}|S)Nc s"jz ||SjXdS)N)r$ _unpatch_dict)r+r)frfrr_inner>s z$_patch_dict.__call__.._inner)rrrr)rfr)r*r)r)rfrr$;s  z_patch_dict.__call__cCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)Nr$) rr<rrrrr$r%rr&rz)rfrrrZ decoratorZ decoratedrrrrIs   z_patch_dict.decorate_classcCs |jdS)N)r$)rfrrrr Tsz_patch_dict.__enter__cCs|j}|j}|j}y |j}Wn2tk rPi}x|D]}||||<q8WYnX||_|rdt|y|j|Wn.tk rx|D]}||||<qWYnXdS)N)rr%r&rr"r' _clear_dictr )rfrr%r&rIrrrrr$Ys"   z_patch_dict._patch_dictc CsV|j}|j}t|y|j|Wn.tk rPx|D]}||||<q8WYnXdS)N)r%r'r+r r")rfr%rIrrrrr(ss z_patch_dict._unpatch_dictcGs |jdS)NF)r()rfr+rrrr sz_patch_dict.__exit__N) r5r8rhr!r$rr r$r(r rrrrrrr$s   r$c CsBy |jWn0tk r<t|}x|D] }||=q*WYnXdS)N)r&r"r>)r%keysrrrrr+s   r+cCs xttjD] }|jq WdS)N)rrrr)rrrr_patch_stopallsr-Ztestzlt 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 trunc floor ceil bool next zHadd sub mul matmul div floordiv mod lshift rshift and xor or pow truediv ccs|]}d|VqdS)zi%sNr)rnrrrrsrccs|]}d|VqdS)zr%sNr)rr/rrrrs__get____set__ __delete__ __reversed__ __missing__ __reduce__ __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__ __setformat__rgr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)Ncs|f||S)Nr)rfr+r)r'rrmethodsz_get_method..method)r5)rr'r?r)r'rrs rcCsh|] }d|qS)z__%s__r)rr?rrrrsrmrr!r __prepare____instancecheck____subclasscheck____del__cCs tj|S)N)r__hash__)rfrrrrsrcCs tj|S)N)r__str__)rfrrrrscCs tj|S)N)r __sizeof__)rfrrrrs)rDrErFry?g?) __lt____gt____le____ge____int__r__len__r  __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__rrrNotImplemented)otherret_val)rfrrrQs z_get_eq..__eq__r)rfrQr)rfr_get_eqs rUcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__rrrrR)rS)rfrrrVs  z_get_ne..__ne__r)rfrVr)rfr_get_nes rWcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rrrrr)rT)rfrrrsz_get_iter..__iter__r)rfrr)rfr _get_iters rX)rQrVrc Cstj|t}|tk r||_dStj|}|dk rdy ||}Wntk rXt|}YnX||_dStj|}|dk r|||_dS)N)_return_valuesrCrrY_calculate_return_valuer"_side_effect_methodsr_)r1r?rZfixedZreturn_calulatorrYZ side_effectorrrr_set_return_values    r\c@seZdZddZddZdS) MagicMixincOs&|jtt|j|||jdS)N)_mock_set_magicsrr]r!)rfr+rrrrr!(szMagicMixin.__init__cCst}t|dddk rTtj|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr< intersectionrrorrBrrz MagicProxy)rfZ these_magicsZ remove_magicsrrrrrr^.s   zMagicMixin._mock_set_magicsN)r5r8rhr!r^rrrrr]'sr]c@seZdZdddZdS)r FcCs|j|||jdS)N)rr^)rfrrrrrrGs z"NonCallableMagicMock.mock_add_specN)F)r5r8rhrrrrrr Esc@seZdZdddZdS)rFcCs|j|||jdS)N)rr^)rfrrrrrr]s zMagicMock.mock_add_specN)F)r5r8rhrrrrrrRs c@s.eZdZddZddZddZd dd ZdS) racCs||_||_dS)N)rr)rfrrrrrr!iszMagicProxy.__init__cOs|j}|||S)N) create_mock)rfr+r,mrrrr$mszMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrzr\)rfrrrcrrrrbqs  zMagicProxy.create_mockNcCs|jS)N)rb)rfrrrrrr0zszMagicProxy.__get__)N)r5r8rhr!r$rbr0rrrrrahs rac@s$eZdZddZddZddZdS)_ANYcCsdS)NTr)rfrSrrrrQsz _ANY.__eq__cCsdS)NFr)rfrSrrrrVsz _ANY.__ne__cCsdS)Nzr)rfrrrrgsz _ANY.__repr__N)r5r8rhrQrVrgrrrrrdsrdcCsdd|}d}djdd|D}djddt|jD}|rD|}|r\|rT|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrrsz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrprrrrs)rrr)rr+r,rZformatted_argsZ args_stringZ kwargs_stringrrrrsrc@sreZdZfddddfddZfddddfddZd d ZejZd d Zd dZ ddZ ddZ ddZ ddZ dS)rrNFTc Csf}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rtj|||fStj||||fS)Nrrbr)rrr"r?r) rrprrr from_kallr+r,_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)rvrt_mock_from_kall)rfrprrrrfrrrr!sz_Call.__init__c Csf|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}t|ddrzt|ddrz|j|jkrzdSd}|dkrfi}}n|dkr|\}}}n|dkr|\} t| tr| }i}n"t| tr| }fi}}nf}| }nV|dkr>|\} } t| tr2| }t| tr&| i}}n f| }}n | | }}ndS|rV||krVdS||f||fkS) NTFrrbrtrrr)rrrr<rtrr?r") rfrSZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrprhrirrrrQsP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)rvr)rfr+r,rrrrr$s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrfz%s.%s)rrrf)rvr)rfrrrrrrms  z_Call.__getattr__cOs|jd||S)Nr)rm)rfr+r,rrrr$sz _Call.countcOs|jd||S)Nindex)rm)rfr+r,rrrrk'sz _Call.indexcCs||js&|jpd}|jdr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|jdshd|}nd|}t|||S)Nrz()zcall%srbzcall.%s)rjrvrrr)rfrr+r,rrrrg*s       z_Call.__repr__cCs8g}|}x"|dk r*|jr"|j||j}q Wtt|S)N)rjrrtrUr)rfvalsrrrr call_list?s   z_Call.call_list)r5r8rhrr!rQrrVr$rmrrkrgrmrrrrrs  7r)rfcKs,t|rt|}t|t}d|i}|r0d|i}n |dkr.rrxrxrxrx)rbytesr) read_dataZ data_as_listliner)rwr_iterate_read_data s  r|rcsfdd}fdd}fddtdkr`ddl}ttt|jjtt|ja|dkrttdt d }ttd j _ t dgdj _ dj_ dj_ dj_ |j_d <d j_|j_fd d }||_|_ |S)Ncs jjdk rjjStdS)Nr) readlinesrYr>)r+r,)_statehandlerr_readlines_side_effect( s z)mock_open.._readlines_side_effectcs(jjdk rjjStjdS)Nr)readrYrr)r+r,)r~rrzrr_read_side_effect- s z$mock_open.._read_side_effectc3sJjjdk rxjjVqWxdD] }|Vq&WxtVq6WdS)Nr)readlinerYr)r{)r~rrzrr_readline_side_effect2 s  z(mock_open.._readline_side_effectropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r|rr_r)r+r,)rr~rrzrr reset_dataS s    zmock_open..reset_data) file_spec_ior>ror TextIOWrapperunionBytesIOrrr rYr|writerrr}r_)r1rzrrrrr)rr~rrzrr  s.  "     c@s$eZdZddZddZddZdS)r cKs tf|S)N)r)rfr,rrrri szPropertyMock._get_child_mockcCs|S)Nr)rfrZobj_typerrrr0l szPropertyMock.__get__cCs ||dS)Nr)rfrrrrrr1n szPropertyMock.__set__N)r5r8rhrr0r1rrrrr ` s ) rrrrrrrrr r r r r )F)F)NFNNN)FFNN)Nr)o__all__ __version__r%rr builtinstypesr functoolsrrrr BaseExceptionrplatformrZlangZ Throwabler superrrr r(r4r/r=r@rErMrHrdrrerirrZMISSINGrZDELETEDrrqr|rr>rUrrrr rrrrrrrr r!r#rr$r+r-rnZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrr_rrrZrRrYrUrWrXr[r\r]r rrardrrr?rrrrnrrrrQr#r0rrrr|r r rrrrs     4  i5 ,   1Jv        ,  w  DPK!g"\\__pycache__/mock.cpython-36.pycnu[3 \7@sFdZd ZddlZddlZddlZddlZddlmZddlm Z m Z dde eDZ e fZdejkrzddlZe ejjfZdZeZddZddZddZdddZdd Zd!d"Zd#d$Zd%d&Zdd'd(Zd)d*Zd+d,Z Gd-d.d.e!Z"Gd/d0d0e!Z#e#Z$e$j%Z%e$j&Z'e$j(Z)d1d2Z*d3d4d5d6d7d8d9d:hZ+d;d<Z,Gd=d>d>e-Z.d?d@Z/GdAdBdBe!Z0GdCdDdDe!Z1GdEd d e1Z2dFdGZ3GdHdIdIe1Z4GdJdde4e2Z5dKdLZ6dMdNZ7dOdPZ8GdQdRdRe!Z9dSdTZ:e%dddddfdUdVZ;ddWdXZd\d]Z?d^d_Z@e;e=_!e>e=_Ae#srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock2srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception8s r cCst|tr6| r6y |j}Wntk r.dSXd}n*t|ts`y |j}Wntk r^dSX|rpt|d}n|}y|tj|fSt k rdSXdS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. NT) rr__init__AttributeError FunctionTypes__call__rinspectZ signature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_object?s$    r(FcsDt|||dkrdS\}fdd}t|||t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigdsz"_check_signature..checksig)r(_copy_func_detailsr_mock_check_sig)r'mock skipfirstinstancer.r)r-r_check_signature_s   r4c#Cs|j|_|j|_y |j|_Wntk r0YnXy |j|_Wntk rRYnXy |j|_Wntk rtYnXy |j|_Wntk rYnXdS)N)__name____doc____text_signature__r" __module__ __defaults____kwdefaults__)r'funcopyrrrr/js$    r/cCs&t|trdSt|dddk r"dSdS)NTr$F)rrgetattr)rrrr _callables  r=cCst|ttfkS)N)rlisttuple)rrrr_is_listsr@cCsHt|tst|dddk Sx(|f|jD]}|jjddk r(dSq(WdS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.r$NTF)rrr<__mro____dict__get)rbaserrr_instance_callables  rEc st|s dSt|t}t|||}|dkr.|S|\}fdd}t|||j}|js^d}||d}d|} t| |||} t| || S)Ncsj||dS)N)r))r+r,)r-rrr.sz _set_signature..checksigr;)Z _checksig_r1zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) r=rrr(r/r5 isidentifierexec _setup_func) r1originalr3r2resultr'r.rcontextsrcr;r)r-r_set_signatures$       rMc s_tsdSfdd}fdd}fdd}fdd}fd d }fd d }fd d}fdd} d_d_d_t_t_t_j _ j _ j _ |_ |_ |_|_| _|_|_|__dS)Ncs j||S)N)assert_called_with)r+r,)r1rrrNsz'_setup_func..assert_called_withcs j||S)N) assert_called)r+r,)r1rrrOsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r+r,)r1rrrPsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r+r,)r1rrrQsz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r+r,)r1rrrRsz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r+r,)r1rrrSsz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r+r,)r1rrrTsz$_setup_func..assert_any_callcs:t_t_jj}t|r6|k r6|jdS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)r;r1rrrXs z_setup_func..reset_mockFr)r1rcalled call_count call_argsrUcall_args_listrVrWrY side_effect_mock_childrenrNrRrSrTrXrOrPrQ_mock_delegate) r;r1rNrOrPrQrRrSrTrXr)r;r1rrHs:       rHcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrdc@s eZdZdZddZddZdS)_SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r)selfrrrrr!sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rfrrr__repr__sz_SentinelObject.__repr__N)r5r8 __qualname__r6r!rgrrrrresrec@s eZdZdZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)rfrrrr!sz_Sentinel.__init__cCs|dkr t|jj|t|S)N __bases__)r"rj setdefaultre)rfrrrr __getattr__sz_Sentinel.__getattr__N)r5r8rhr6r!rmrrrrrisricCs$t|ttttfkr t||S|S)N)rdictr>r?set)valuerrr_copys rqrY_mock_return_valuer__mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8tj|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||S)N)rar<)rfr _the_namer-rrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rarBsetattr)rfrprrxr-rrr_set$s z"_delegating_property.._set)_allowed_namesaddproperty)rrxryr{rrr_delegating_propertys  rc@seZdZddZddZdS)rUcCsnt|tstj||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)rr> __contains__lenrange)rfrpZ len_valueZlen_selfiZsub_listrrrr1s  z_CallList.__contains__cCstjt|S)N)pprintZpformatr>)rfrrrrg?sz_CallList.__repr__N)r5r8rhrrgrrrrrU/srUcCsxt|s dS|js,|js,|jdk s,|jdk r0dS|}x|dk rR||krJdS|j}q6W|rd||_||_|rt||_||_dS)NFT)rrvrwrtru)parentrprnew_name_parentrrr_check_and_set_parentCs$     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rfrrrrr!]sz_MockIter.__init__cCs|S)Nr)rfrrr__iter___sz_MockIter.__iter__cCs t|jS)N)nextr)rfrrr__next__asz_MockIter.__next__N)r5r8rhr!rrrrrrr\src@seZdZeZdZddZdS)BaseNcOsdS)Nr)rfr+r,rrrr!gsz Base.__init__)r5r8rhrrrrsr!rrrrrdsrc @sHeZdZdZddZdDddZd d ZdEd d ZdFd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdGdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z d2d3Z!d4d5Z"d6d7Z#d8d9Z$d:d;Z%dd?Z'd@dAZ(dBdCZ)dS)Ir z A non-callable version of `Mock`cOs$t|j|fd|ji}tj|}|S)Nr6)rr5r6object__new__)clsr+kwnewr3rrrros zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<|dk rB|}d}| dkrR|dk } |j||| | i| d<|| d<d| d<d | d <d| d <d | d <t| d<t| d<t| d<| | d<| r|jf| tt|j||||||dS)NrtrvrwruTr` _mock_wrapsraFZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrV _mock_unsafe)rB_mock_add_specrUconfigure_mock _safe_superr r!)rfspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer,rBrrrr!xs8      zNonCallableMock.__init__cCs(d|_d|_d|_d|_t|||dS)z 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.Nr)rtrurvrwrz)rfr1 attributerrr attach_mocks zNonCallableMock.attach_mockcCs|j||dS)zAdd 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.N)r)rfrrrrr mock_add_specszNonCallableMock.mock_add_specc Cs|d}d}|dk rRt| rRt|tr*|}nt|}t|||}|oH|d}t|}|j}||d<||d<||d<||d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods)r@rr _get_classr(dirrB) rfrrrrrrresrBrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rrrarYr_get_child_mock)rfrZrrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rarYrrr)rfrprrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rfrrr __class__s zNonCallableMock.__class__r[r\r]r^rWcCsT|j}|dkr|jS|j}|dk rPt| rPt|t rPt| rPt|}||_|S)N)rarsr_callablerrr )rf delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrarsr_)rfrprrrrZ__set_side_effects z!NonCallableMock.__set_side_effect)rYr_cCs|dkr g}t||krdS|jt|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ x0|j j D]"}t|tst|tkrqt|j|qtW|j }t|r||k r|j|dS)z-Restore the mock object to its initial state.NFr)idappendr[r]r\rUrWr^rVrrrrsr`valuesr _SpecState_deletedrXr)rfZvisitedrYr_ZchildrZrrrrX s, zNonCallableMock.reset_mockcKs`xZt|jdddD]B\}}|jd}|j}|}x|D]}t||}q:Wt|||qWdS)aZSet 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)cSs|djdS)Nr.)count)entryrrr8sz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr<rz)rfr,argvalr+finalrrrrrr+s   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|jdrdt||jj|}|tkrt|np|dkrd}|j dk rt |j |}|j |||||d}||j|<n.t |t rt|j|j|j|j|j}||j|<|S) NrrzMock object has no attribute %rassertassret)rrrrr>rr)rr)r"r _all_magicsrdrrr`rCrrr<rrrrrrr3rr)rfrrJrrrrrmAs6            zNonCallableMock.__getattr__c Cs"|jg}|j}|}d}|dgkr$d}t}xT|dk r~|}|j|j|d}|jdkrZd}|j}t||krnP|jt|q,Wtt|}|jpd}t |dkr|dd kr|d7}||d<dj |}d}|dkrd |}d} |j dk rd } |j rd } | |j j } d t|j || t|fS)Nr()rr1r().rmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rr)r1r)rwrurorrr}r>reversedrvrjoinrrr5r) rfZ _name_listrZlastdotseenZ_firstrZ name_stringZ spec_stringrrrrggsL           zNonCallableMock.__repr__cCshtstj|S|jpg}tt|}t|j}dd|D}dd|D}tt |||t|j S)z8Filter the output of `dir(mock)` to only useful members.cSsg|]}|jds|qS)r)r)rerrr sz+NonCallableMock.__dir__..cSs$g|]}|jd st|r|qS)r)rrd)rrrrrrs) r r__dir__rrrr>rBrror`)rfZextrasZ from_typeZ from_dictrrrrs    zNonCallableMock.__dir__cs"|tkrtj||SjrHjdk rH|jkrH|jkrHtd|n|tkrbd|}t|n|tkrjdk r|jkrtd|t |st t |t |||fdd}n(t |d|t t |||j|<n.|dkr|_dSt |||r|j|<tj||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csf||S)Nr)r+r)rIrfrrrsz-NonCallableMock.__setattr__..r)r|r __setattr__rrrBr"_unsupported_magicsrrrzr _get_methodrr`r)rfrrpmsgr)rIrfrrs2       zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS||jkrHtj|||jj|t}|t krft ||tk rv|j|=t |j|<dS)N) rrrBdelattrr __delattr__r`rC_missingrr")rfrrrrrrs   zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr1)rv_format_call_signature)rfr+r,rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|j||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rr]r)rfr+r,messageexpected_stringr]Z actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagecCst|j}|dk rlt|dkr(d}|\}}n |\}}}y||j||fStk rh}z |jdSd}~XqpXn|SdS)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. Nrbr)rrr) TypeErrorwith_traceback)rf_callr-rr+r,rrrr _call_matchers   zNonCallableMock._call_matchercCs.|}|jdkr*d|jpd|jf}t|dS)z/assert that the mock was never called. rz7Expected '%s' to not have been called. Called %s times.r1N)r\rvAssertionError)r*rfrrrrrPs  z!NonCallableMock.assert_not_calledcCs(|}|jdkr$d|jpd}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.r1N)r\rvr)r*rfrrrrrO s   zNonCallableMock.assert_calledcCs.|}|jdks*d|jpd|jf}t|dS)z3assert that the mock was called only once. rz8Expected '%s' to have been called once. Called %s times.r1N)r\rvr)r*rfrrrrrQs  z"NonCallableMock.assert_called_oncecs||jdkr(j}td|ffdd}jf}jj}||krxt|trh|nd}t||dS)zassert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.NzExpected call: %s Not calledcsj}|S)N)r)r)r+r,rfrr_error_message's z:NonCallableMock.assert_called_with.._error_message)r]rrrr Exception)r*r+r,expectedractualcauser)r+r,rfrrNs   z"NonCallableMock.assert_called_withcOs6|}|jdks*d|jpd|jf}t||j||S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rz1Expected '%s' to be called once. Called %s times.r1)r\rvrrN)r*r+r,rfrrrrrR1s  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sd||kr`tdt|jf|dSt|}g}x:|D]2}y|j|Wqvtk r|j|YqvXqvW|rtdt |f|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`.csg|]}j|qSr)r)rc)rfrrrFsz4NonCallableMock.assert_has_calls..Nc3s|]}j|VqdS)N)r)rr)rfrr Hsz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) rrrUrWrr>remover&rr?)rfZcallsZ any_orderrrZ all_callsZ not_foundZkallr)rfrrS<s*  z NonCallableMock.assert_has_callscsZj||f}fddjD}||krVt|tr8|nd}j||}td||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.csg|]}j|qSr)r)rr)rfrrrfsz3NonCallableMock.assert_any_call..Nz%s call not found)rr^rrrr)rfr+r,rrrrr)rfrrT_s zNonCallableMock.assert_any_callcKsFt|}t|ts2t|tr"t}q.) rrrrrrrrrr,attribute_namer)rfrrrrrisz _patch.copycCst|tr|j|S|j|S)N)rrdecorate_classdecorate_callable)rfr'rrrr$vs  z_patch.__call__cCsRxLt|D]@}|jtjsq t||}t|ds2q |j}t||||q W|S)Nr$)rrr TEST_PREFIXr<rrrz)rfrattr attr_valuerrrrr|s   z_patch.decorate_classcs<tdrjj|Stfdd|g_S)N patchingscsg}g}t}zybxJjD]@}|j}|j||jdk rF|j|q|jtkr|j|qW|t|7}||S||krt|r|j|t j }YnXWdxt |D]}|j |qWXdS)N) r?r __enter__rrupdaterrrsysexc_infor__exit__)r+Zkeywargs extra_argsZentered_patchersr patchingr)r'patchedrrrs*         z)_patch.decorate_callable..patched)rrrr)rfr'r)r'rrrs   z_patch.decorate_callablec Cs|j}|j}t}d}y|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j r|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rrrrBr"KeyErrorr< _builtinsrrr)rfrrrIlocalrrr get_originalsz_patch.get_originalcCs>|j|j|j}}}|j|j}}|j}|j|_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd|j \}}|t ko|dkrTd} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r,|t krtdt |t r,d} t } i} |dk rD|} nN|dk sX|dk r|} |dk rj|} t| r~d| k} n t|  } | rt} |dk r|| d<|dk r|| d <t | t rt| tr|jr|j| d <| j|| f| }| rt|r|} |dk r|} t|  r2t|  r2t} | jd | f|d d | |_nl|dk r|t k rptd |t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r:i}|jt kr|||j<x.|jD]$}|j }|jt kr|j|qW|S|S)zPerform the patch.FNzCan't specify spec and autospecTz6Can't provide explicit spec_set *and* spec or autospecz!Can't use 'spec' with create=Truer$rrrz())rrzBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=True)r_namez.Can't pass kwargs to a mock we aren't creating)TN)!rrrrr,rrrrrrrrrr@rr rr rr rrErrYboolr temp_originalrrzrrr )rfrrrrr,rrIrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrrr s                              z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jnBt|j|j|j rvt |j|j sd|jdkrvt|j|j|j|`|`|`x$t |j D]}t|r|j |qWdS) zUndo the patch.z stop called on unstarted patcherr6r8r9__annotations__r:N)r6r8r9rr:)r RuntimeErrorrrrrzrrrrrrrr )rfr rrrrr Hs z_patch.__exit__cCs|j}|jj||S)z-Activate a patch, returning any created mock.)r _active_patchesr)rfrJrrrstart`s z _patch.startc Cs.y|jj|Wntk r$YnX|jS)zStop an active patch.)rrr&r )rfrrrstopgs z _patch.stop)r5r8rhrrr!rr$rrrr r rrrrrrrIs (~rc sPyjdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrysz_get_target..)rsplitrr&)rrrr)rr _get_targetss r c s$fdd} 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. csS)Nrr)rrrrsz_patch_object..)r) rrrrrrrrr,rr)rr _patch_object}s  r!c sttkrfdd}n fdd}|s2tdt|j}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| jj| qvW| 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. cstS)N)rr)rrrrsz!_patch_multiple..csS)Nrr)rrrrsz=Must supply at least one keyword argument with patch.multiplerrN) rstrr&r>rrrrr) rrrrrrr,rrrrrZ this_patcherr)rr_patch_multiples&        r#c Ks$t|\}} 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 a `MagicMock`. 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 `MagicMock` is used. 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` takes arbitrary keyword arguments. These will be passed to the `Mock` (or `new_callable`) on construction. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. )r r) rrrrrrrr,rrrrrrsE  c@sVeZdZdZfdfddZddZddZd d Zd d Zd dZ ddZ eZ e Z dS) _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. FcKs>t|trt|}||_t||_|jj|||_d|_dS)N) rr"rin_dictrnrr clear _original)rfr%rr&r,rrrr!0s   z_patch_dict.__init__cs.ttrjStfdd}|S)Nc s"jz ||SjXdS)N)r$ _unpatch_dict)r+r)frfrr_inner>s z$_patch_dict.__call__.._inner)rrrr)rfr)r*r)r)rfrr$;s  z_patch_dict.__call__cCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)Nr$) rr<rrrrr$r%rr&rz)rfrrrZ decoratorZ decoratedrrrrIs   z_patch_dict.decorate_classcCs |jdS)zPatch the dict.N)r$)rfrrrr Tsz_patch_dict.__enter__cCs|j}|j}|j}y |j}Wn2tk rPi}x|D]}||||<q8WYnX||_|rdt|y|j|Wn.tk rx|D]}||||<qWYnXdS)N)rr%r&rr"r' _clear_dictr )rfrr%r&rIrrrrr$Ys"   z_patch_dict._patch_dictc CsV|j}|j}t|y|j|Wn.tk rPx|D]}||||<q8WYnXdS)N)r%r'r+r r")rfr%rIrrrrr(ss z_patch_dict._unpatch_dictcGs |jdS)zUnpatch the dict.F)r()rfr+rrrr sz_patch_dict.__exit__N) r5r8rhr6r!r$rr r$r(r rrrrrrr$s   r$c CsBy |jWn0tk r<t|}x|D] }||=q*WYnXdS)N)r&r"r>)r%keysrrrrr+s   r+cCs xttjD] }|jq WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrrr)rrrr_patch_stopallsr-Ztestzlt 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 trunc floor ceil bool next zHadd sub mul matmul div floordiv mod lshift rshift and xor or pow truediv ccs|]}d|VqdS)zi%sNr)rnrrrrsrccs|]}d|VqdS)zr%sNr)rr/rrrrs__get____set__ __delete__ __reversed__ __missing__ __reduce__ __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__ __setformat__rgr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)rfr+r)r'rrmethodsz_get_method..method)r5)rr'r?r)r'rrs rcCsh|] }d|qS)z__%s__r)rr?rrrrsrmrr!r __prepare____instancecheck____subclasscheck____del__cCs tj|S)N)r__hash__)rfrrrrsrcCs tj|S)N)r__str__)rfrrrrscCs tj|S)N)r __sizeof__)rfrrrrs)rDrErFry?g?) __lt____gt____le____ge____int__r__len__r  __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__rrrNotImplemented)otherret_val)rfrrrQs z_get_eq..__eq__r)rfrQr)rfr_get_eqs rUcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__rrrrR)rS)rfrrrVs  z_get_ne..__ne__r)rfrVr)rfr_get_nes rWcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rrrrr)rT)rfrrrsz_get_iter..__iter__r)rfrr)rfr _get_iters rX)rQrVrc Cstj|t}|tk r||_dStj|}|dk rdy ||}Wntk rXt|}YnX||_dStj|}|dk r|||_dS)N)_return_valuesrCrrY_calculate_return_valuer"_side_effect_methodsr_)r1r?rZfixedZreturn_calulatorrYZ side_effectorrrr_set_return_values    r\c@seZdZddZddZdS) MagicMixincOs&|jtt|j|||jdS)N)_mock_set_magicsrr]r!)rfr+rrrrr!(szMagicMixin.__init__cCst}t|dddk rTtj|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr< intersectionrrorrBrrz MagicProxy)rfZ these_magicsZ remove_magicsrrrrrr^.s   zMagicMixin._mock_set_magicsN)r5r8rhr!r^rrrrr]'sr]c@seZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcCs|j|||jdS)zAdd 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.N)rr^)rfrrrrrrGs z"NonCallableMagicMock.mock_add_specN)F)r5r8rhr6rrrrrr Esc@seZdZdZdddZdS)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`. FcCs|j|||jdS)zAdd 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.N)rr^)rfrrrrrr]s zMagicMock.mock_add_specN)F)r5r8rhr6rrrrrrRs c@s.eZdZddZddZddZd dd ZdS) racCs||_||_dS)N)rr)rfrrrrrr!iszMagicProxy.__init__cOs|j}|||S)N) create_mock)rfr+r,mrrrr$mszMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrzr\)rfrrrcrrrrbqs  zMagicProxy.create_mockNcCs|jS)N)rb)rfrrrrrr0zszMagicProxy.__get__)N)r5r8rhr!r$rbr0rrrrrahs rac@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)rfrSrrrrQsz _ANY.__eq__cCsdS)NFr)rfrSrrrrVsz _ANY.__ne__cCsdS)Nzr)rfrrrrgsz _ANY.__repr__N)r5r8rhr6rQrVrgrrrrrdsrdcCsdd|}d}djdd|D}djddt|jD}|rD|}|r\|rT|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrrsz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrprrrrs)rrr)rr+r,rZformatted_argsZ args_stringZ kwargs_stringrrrrsrc@sveZdZdZfddddfddZfddddfdd Zd d ZejZd d Z ddZ ddZ ddZ ddZ ddZdS)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. rNFTc Csf}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rtj|||fStj||||fS)Nrrbr)rrr"r?r) rrprrr from_kallr+r,_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)rvrt_mock_from_kall)rfrprrrrfrrrr!sz_Call.__init__c Csf|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}t|ddrzt|ddrz|j|jkrzdSd}|dkrfi}}n|dkr|\}}}n|dkr|\} t| tr| }i}n"t| tr| }fi}}nf}| }nV|dkr>|\} } t| tr2| }t| tr&| i}}n f| }}n | | }}ndS|rV||krVdS||f||fkS) NTFrrbrtrrr)rrrr<rtrr?r") rfrSZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrprhrirrrrQsP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)rvr)rfr+r,rrrrr$s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrfz%s.%s)rrrf)rvr)rfrrrrrrms  z_Call.__getattr__cOs|jd||S)Nr)rm)rfr+r,rrrr$sz _Call.countcOs|jd||S)Nindex)rm)rfr+r,rrrrk'sz _Call.indexcCs||js&|jpd}|jdr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|jdshd|}nd|}t|||S)Nrz()zcall%srbzcall.%s)rjrvrrr)rfrr+r,rrrrg*s       z_Call.__repr__cCs8g}|}x"|dk r*|jr"|j||j}q Wtt|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.N)rjrrtrUr)rfvalsrrrr call_list?s   z_Call.call_list)r5r8rhr6rr!rQrrVr$rmrrkrgrmrrrrrs  7r)rfcKs,t|rt|}t|t}d|i}|r0d|i}n |dkr.rrxrxrxrx)rbytesr) read_dataZ data_as_listliner)rwr_iterate_read_data s  r|rcsfdd}fdd}fddtdkr`ddl}ttt|jjtt|ja|dkrttd t d }ttd j _ t dgdj _ dj_ dj_ dj_ |j_d <d j_|j_fd d}||_|_ |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` methoddline`, and `readlines` of the file handle to return. This is an empty string by default. cs jjdk rjjStdS)Nr) readlinesrYr>)r+r,)_statehandlerr_readlines_side_effect( s z)mock_open.._readlines_side_effectcs(jjdk rjjStjdS)Nr)readrYrr)r+r,)r~rrzrr_read_side_effect- s z$mock_open.._read_side_effectc3sJjjdk rxjjVqWxdD] }|Vq&WxtVq6WdS)Nr)readlinerYr)r{)r~rrzrr_readline_side_effect2 s  z(mock_open.._readline_side_effectNropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r|rr_r)r+r,)rr~rrzrr reset_dataS s    zmock_open..reset_data) file_spec_ior>ror TextIOWrapperunionBytesIOrrr rYr|writerrr}r_)r1rzrrrrr)rr~rrzrr  s.  "     c@s(eZdZdZddZddZddZdS) r aW 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. cKs tf|S)N)r)rfr,rrrri szPropertyMock._get_child_mockcCs|S)Nr)rfrZobj_typerrrr0l szPropertyMock.__get__cCs ||dS)Nr)rfrrrrrr1n szPropertyMock.__set__N)r5r8rhr6rr0r1rrrrr ` s) rrrrrrrrr r r r r )F)F)NFNNN)FFNN)Nr)o__all__ __version__r%rr builtinstypesr functoolsrrrr BaseExceptionrplatformrZlangZ Throwabler superrrr r(r4r/r=r@rErMrHrdrrerirrZMISSINGrZDELETEDrrqr|rr>rUrrrr rrrrrrrr r!r#rr$r+r-rnZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrr_rrrZrRrYrUrWrXr[r\r]r rrardrrr?rrrrnrrrrQr#r0rrrr|r r rrrrs     4  i5 ,   1Jv        ,  w  DPK!nԀ<<'__pycache__/result.cpython-36.opt-1.pycnu[3 \@s\dZddlZddlZddlZddlmZddlmZdZddZ d Z d Z Gd d d e Z dS) zTest result objectN)util)wrapsTcstfdd}|S)Ncs$t|ddr|j|f||S)NfailfastF)getattrstop)selfargskw)method'/usr/lib64/python3.6/unittest/result.pyinner s zfailfast..inner)r)r rr )r r r srz Stdout: %sz Stderr: %sc@seZdZdZdZdZdZd.ddZddZdd Z d d Z d d Z ddZ ddZ ddZeddZeddZddZddZddZddZed d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-ZdS)/ 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. NFcCsbd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ t j |_t j|_d|_dS)NFr)rfailureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)rstreamZ descriptions verbosityr r r __init__&szTestResult.__init__cCsdS)z#Called by TestRunner after test runNr )rr r r printErrors7szTestResult.printErrorscCs |jd7_d|_|jdS)z-Called when the given test is about to be runrFN)rr _setupStdout)rtestr r r startTest:szTestResult.startTestcCs8|jr4|jdkr$tj|_tj|_|jt_|jt_dS)N)rrioStringIOrrrr)rr r r r%@s    zTestResult._setupStdoutcCsdS)zpCalled once before any tests are executed. See startTest for a method called before each test. Nr )rr r r startTestRunHszTestResult.startTestRuncCs|jd|_dS)z'Called when the given test has been runFN)_restoreStdoutr )rr&r r r stopTestNszTestResult.stopTestcCs|jr|jrltjj}tjj}|rF|jds6|d7}|jjt ||rl|jds\|d7}|j jt ||jt_|j t_|j j d|j j|jj d|jjdS)N r)rr rrgetvaluerendswithrwrite STDOUT_LINEr STDERR_LINErseektruncater)routputerrorr r r r+Ss$       zTestResult._restoreStdoutcCsdS)zmCalled once after all tests are executed. See stopTest for a method called after each test. Nr )rr r r stopTestRunhszTestResult.stopTestRuncCs"|jj||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 )rr&errr r r addErrornszTestResult.addErrorcCs"|jj||j||fd|_dS)zdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().TN)rr8r9r )rr&r:r r r addFailurevszTestResult.addFailurecCsZ|dk rVt|ddr|jt|d|jr4|j}n|j}|j||j||fd|_dS)zCalled 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(). NrFrT) rr issubclassfailureExceptionrrr8r9r )rr&Zsubtestr:rr r r addSubTest}s zTestResult.addSubTestcCsdS)z-Called when a test has completed successfullyNr )rr&r r r addSuccessszTestResult.addSuccesscCs|jj||fdS)zCalled when a test is skipped.N)rr8)rr&reasonr r r addSkipszTestResult.addSkipcCs|jj||j||fdS)z/Called when an expected failure/error occurred.N)rr8r9)rr&r:r r r addExpectedFailureszTestResult.addExpectedFailurecCs|jj|dS)z5Called when a test was expected to fail, but succeed.N)rr8)rr&r r r addUnexpectedSuccessszTestResult.addUnexpectedSuccesscCs>t|jt|jkodknoConverts a sys.exc_info()-style tuple of values into a string.N)limitcapture_localsr-)_is_relevant_tb_leveltb_nextr>_count_relevant_tb_levels tracebackTracebackExceptionrlistformatrrrr.rr/r8r1r2join) rr:r&exctypevaluetblengthZtb_eZmsgLinesr5r6r r r r9s*         zTestResult._exc_info_to_stringcCs d|jjkS)N __unittest)tb_frame f_globals)rrUr r r rKsz TestResult._is_relevant_tb_levelcCs,d}x"|r&|j| r&|d7}|j}qW|S)Nrr)rKrL)rrUrVr r r rMs  z$TestResult._count_relevant_tb_levelscCs&dtj|j|jt|jt|jfS)Nz!<%s run=%i errors=%i failures=%i>)rZstrclass __class__rrErr)rr r r __repr__szTestResult.__repr__)NNN)__name__ __module__ __qualname____doc__Z_previousTestClassZ_testRunEnteredZ_moduleSetUpFailedr#r$r'r%r*r,r+r7rr;r<r?r@rBrCrDrGrr9rKrMr[r r r r rs2      r)r_r(rrNrJr functoolsrrWrr1r2objectrr r r r s  PK!p4'__pycache__/result.cpython-36.opt-2.pycnu[3 \@sXddlZddlZddlZddlmZddlmZdZddZdZ d Z Gd d d e Z dS) N)util)wrapsTcstfdd}|S)Ncs$t|ddr|j|f||S)NfailfastF)getattrstop)selfargskw)method'/usr/lib64/python3.6/unittest/result.pyinner s zfailfast..inner)r)r rr )r r r srz Stdout: %sz Stderr: %sc@seZdZdZdZdZd-ddZddZddZd d Z d d Z d dZ ddZ ddZ eddZeddZddZddZddZddZedd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,ZdS). TestResultNFcCsbd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ t j |_t j|_d|_dS)NFr)rfailureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)rstreamZ descriptions verbosityr r r __init__&szTestResult.__init__cCsdS)Nr )rr r r printErrors7szTestResult.printErrorscCs |jd7_d|_|jdS)NrF)rr _setupStdout)rtestr r r startTest:szTestResult.startTestcCs8|jr4|jdkr$tj|_tj|_|jt_|jt_dS)N)rrioStringIOrrrr)rr r r r%@s    zTestResult._setupStdoutcCsdS)Nr )rr r r startTestRunHszTestResult.startTestRuncCs|jd|_dS)NF)_restoreStdoutr )rr&r r r stopTestNszTestResult.stopTestcCs|jr|jrltjj}tjj}|rF|jds6|d7}|jjt ||rl|jds\|d7}|j jt ||jt_|j t_|j j d|j j|jj d|jjdS)N r)rr rrgetvaluerendswithrwrite STDOUT_LINEr STDERR_LINErseektruncater)routputerrorr r r r+Ss$       zTestResult._restoreStdoutcCsdS)Nr )rr r r stopTestRunhszTestResult.stopTestRuncCs"|jj||j||fd|_dS)NT)rappend_exc_info_to_stringr )rr&errr r r addErrornszTestResult.addErrorcCs"|jj||j||fd|_dS)NT)rr8r9r )rr&r:r r r addFailurevszTestResult.addFailurecCsZ|dk rVt|ddr|jt|d|jr4|j}n|j}|j||j||fd|_dS)NrFrT) rr issubclassfailureExceptionrrr8r9r )rr&Zsubtestr:rr r r addSubTest}s zTestResult.addSubTestcCsdS)Nr )rr&r r r addSuccessszTestResult.addSuccesscCs|jj||fdS)N)rr8)rr&reasonr r r addSkipszTestResult.addSkipcCs|jj||j||fdS)N)rr8r9)rr&r:r r r addExpectedFailureszTestResult.addExpectedFailurecCs|jj|dS)N)rr8)rr&r r r addUnexpectedSuccessszTestResult.addUnexpectedSuccesscCs>t|jt|jkodkno_count_relevant_tb_levels tracebackTracebackExceptionrlistformatrrrr.rr/r8r1r2join) rr:r&exctypevaluetblengthZtb_eZmsgLinesr5r6r r r r9s*         zTestResult._exc_info_to_stringcCs d|jjkS)N __unittest)tb_frame f_globals)rrUr r r rKsz TestResult._is_relevant_tb_levelcCs,d}x"|r&|j| r&|d7}|j}qW|S)Nrr)rKrL)rrUrVr r r rMs  z$TestResult._count_relevant_tb_levelscCs&dtj|j|jt|jt|jfS)Nz!<%s run=%i errors=%i failures=%i>)rZstrclass __class__rrErr)rr r r __repr__szTestResult.__repr__)NNN)__name__ __module__ __qualname__Z_previousTestClassZ_testRunEnteredZ_moduleSetUpFailedr#r$r'r%r*r,r+r7rr;r<r?r@rBrCrDrGrr9rKrMr[r r r r rs0      r) r(rrNrJr functoolsrrWrr1r2objectrr r r r s  PK!nԀ<<!__pycache__/result.cpython-36.pycnu[3 \@s\dZddlZddlZddlZddlmZddlmZdZddZ d Z d Z Gd d d e Z dS) zTest result objectN)util)wrapsTcstfdd}|S)Ncs$t|ddr|j|f||S)NfailfastF)getattrstop)selfargskw)method'/usr/lib64/python3.6/unittest/result.pyinner s zfailfast..inner)r)r rr )r r r srz Stdout: %sz Stderr: %sc@seZdZdZdZdZdZd.ddZddZdd Z d d Z d d Z ddZ ddZ ddZeddZeddZddZddZddZddZed d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-ZdS)/ 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. NFcCsbd|_g|_g|_d|_g|_g|_g|_d|_d|_d|_ d|_ d|_ t j |_t j|_d|_dS)NFr)rfailureserrorstestsRunskippedexpectedFailuresunexpectedSuccesses shouldStopbuffer tb_locals_stdout_buffer_stderr_buffersysstdout_original_stdoutstderr_original_stderr _mirrorOutput)rstreamZ descriptions verbosityr r r __init__&szTestResult.__init__cCsdS)z#Called by TestRunner after test runNr )rr r r printErrors7szTestResult.printErrorscCs |jd7_d|_|jdS)z-Called when the given test is about to be runrFN)rr _setupStdout)rtestr r r startTest:szTestResult.startTestcCs8|jr4|jdkr$tj|_tj|_|jt_|jt_dS)N)rrioStringIOrrrr)rr r r r%@s    zTestResult._setupStdoutcCsdS)zpCalled once before any tests are executed. See startTest for a method called before each test. Nr )rr r r startTestRunHszTestResult.startTestRuncCs|jd|_dS)z'Called when the given test has been runFN)_restoreStdoutr )rr&r r r stopTestNszTestResult.stopTestcCs|jr|jrltjj}tjj}|rF|jds6|d7}|jjt ||rl|jds\|d7}|j jt ||jt_|j t_|j j d|j j|jj d|jjdS)N r)rr rrgetvaluerendswithrwrite STDOUT_LINEr STDERR_LINErseektruncater)routputerrorr r r r+Ss$       zTestResult._restoreStdoutcCsdS)zmCalled once after all tests are executed. See stopTest for a method called after each test. Nr )rr r r stopTestRunhszTestResult.stopTestRuncCs"|jj||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 )rr&errr r r addErrornszTestResult.addErrorcCs"|jj||j||fd|_dS)zdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().TN)rr8r9r )rr&r:r r r addFailurevszTestResult.addFailurecCsZ|dk rVt|ddr|jt|d|jr4|j}n|j}|j||j||fd|_dS)zCalled 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(). NrFrT) rr issubclassfailureExceptionrrr8r9r )rr&Zsubtestr:rr r r addSubTest}s zTestResult.addSubTestcCsdS)z-Called when a test has completed successfullyNr )rr&r r r addSuccessszTestResult.addSuccesscCs|jj||fdS)zCalled when a test is skipped.N)rr8)rr&reasonr r r addSkipszTestResult.addSkipcCs|jj||j||fdS)z/Called when an expected failure/error occurred.N)rr8r9)rr&r:r r r addExpectedFailureszTestResult.addExpectedFailurecCs|jj|dS)z5Called when a test was expected to fail, but succeed.N)rr8)rr&r r r addUnexpectedSuccessszTestResult.addUnexpectedSuccesscCs>t|jt|jkodknoConverts a sys.exc_info()-style tuple of values into a string.N)limitcapture_localsr-)_is_relevant_tb_leveltb_nextr>_count_relevant_tb_levels tracebackTracebackExceptionrlistformatrrrr.rr/r8r1r2join) rr:r&exctypevaluetblengthZtb_eZmsgLinesr5r6r r r r9s*         zTestResult._exc_info_to_stringcCs d|jjkS)N __unittest)tb_frame f_globals)rrUr r r rKsz TestResult._is_relevant_tb_levelcCs,d}x"|r&|j| r&|d7}|j}qW|S)Nrr)rKrL)rrUrVr r r rMs  z$TestResult._count_relevant_tb_levelscCs&dtj|j|jt|jt|jfS)Nz!<%s run=%i errors=%i failures=%i>)rZstrclass __class__rrErr)rr r r __repr__szTestResult.__repr__)NNN)__name__ __module__ __qualname____doc__Z_previousTestClassZ_testRunEnteredZ_moduleSetUpFailedr#r$r'r%r*r,r+r7rr;r<r?r@rBrCrDrGrr9rKrMr[r r r r rs2      r)r_r(rrNrJr functoolsrrWrr1r2objectrr r r r s  PK!kH'__pycache__/runner.cpython-36.opt-1.pycnu[3 \G@sndZddlZddlZddlZddlmZddlmZdZGddde Z Gd d d ej Z Gd d d e Z dS) z Running testsN)result)registerResultTc@s*eZdZdZddZddZd ddZdS) _WritelnDecoratorz@Used to decorate file-like objects with a handy 'writeln' methodcCs ||_dS)N)stream)selfrr'/usr/lib64/python3.6/unittest/runner.py__init__sz_WritelnDecorator.__init__cCs|dkrt|t|j|S)Nr __getstate__)rr )AttributeErrorgetattrr)rattrrrr __getattr__sz_WritelnDecorator.__getattr__NcCs|r|j||jddS)N )write)rargrrr writelns z_WritelnDecorator.writeln)N)__name__ __module__ __qualname____doc__r rrrrrr r srcseZdZdZddZddZfddZddZfd d Zfd d Z fd dZ fddZ fddZ fddZ fddZddZddZZS)TextTestResultzhA test result class that can print formatted text results to a stream. Used by TextTestRunner. =F-cs8tt|j|||||_|dk|_|dk|_||_dS)Nr)superrr rshowAlldots descriptions)rrr verbosity) __class__rr r %s   zTextTestResult.__init__cCs0|j}|jr$|r$djt||fSt|SdS)Nr)ZshortDescriptionrjoinstr)rtestZdoc_first_linerrr getDescription,s zTextTestResult.getDescriptioncsBtt|j||jr>|jj|j||jjd|jjdS)Nz ... )rr startTestrrrr%flush)rr$)r!rr r&3s  zTextTestResult.startTestcsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nok.) rr addSuccessrrrrrr')rr$)r!rr r*:s  zTextTestResult.addSuccesscsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NERRORE) rraddErrorrrrrrr')rr$err)r!rr r-Bs  zTextTestResult.addErrorcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NFAILF) rr addFailurerrrrrr')rr$r.)r!rr r1Js  zTextTestResult.addFailurecsLtt|j|||jr,|jjdj|n|jrH|jjd|jj dS)Nz skipped {0!r}s) rraddSkiprrrformatrrr')rr$reason)r!rr r3Rs  zTextTestResult.addSkipcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)Nzexpected failurex) rraddExpectedFailurerrrrrr')rr$r.)r!rr r7Zs  z!TextTestResult.addExpectedFailurecsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nzunexpected successu) rraddUnexpectedSuccessrrrrrr')rr$)r!rr r9bs  z#TextTestResult.addUnexpectedSuccesscCs6|js |jr|jj|jd|j|jd|jdS)Nr+r/)rrrrprintErrorListerrorsfailures)rrrr printErrorsjs  zTextTestResult.printErrorscCs\xV|D]N\}}|jj|j|jjd||j|f|jj|j|jjd|qWdS)Nz%s: %sz%s)rr separator1r% separator2)rZflavourr;r$r.rrr r:ps zTextTestResult.printErrorList)rrrrr>r?r r%r&r*r-r1r3r7r9r=r: __classcell__rr)r!r rs        rc@s4eZdZdZeZd ddddZd d Zd d 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 CsN|dkrtj}t||_||_||_||_||_||_||_ |dk rJ||_ dS)zConstruct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. N) sysstderrrrrr failfastbufferrBwarnings resultclass) rrrr rErFrHrGrBrrr r s zTextTestRunner.__init__cCs|j|j|j|jS)N)rHrrr )rrrr _makeResultszTextTestRunner._makeResultcCs4|j}t||j|_|j|_|j|_tj|jr^tj|j|jdkr^tjdt ddt j }t |dd}|dk r|z ||Wdt |dd}|dk r|Xt j }WdQRX||}|j t |d r|jj|j|j}|jjd ||d krd pd |f|jjd} } } ytt|j|j|jf} Wntk rVYn X| \} } } g} |js|jjdt|jt|j}}|r| jd||r| jd|n |jjd| r| jd| | r| jd| | r| jd| | r$|jjddj| fn |jjd|S)z&Run the given test case or test suite.defaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRunN stopTestRunr?zRan %d test%s in %.3fsrr2rZFAILEDz failures=%dz errors=%dZOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (%s)z, r)rJrK)rIrrErFrBrGcatch_warnings simplefilterfilterwarningsDeprecationWarningtimer r=hasattrrrr?ZtestsRunmaplenZexpectedFailuresunexpectedSuccessesskippedr Z wasSuccessfulrr<r;appendr")rr$rZ startTimerOrPZstopTimeZ timeTakenrunZ expectedFailsrZr[ZresultsZinfosZfailedZerroredrrr r]sr              zTextTestRunner.run)NTrFFNN) rrrrrrHr rIr]rrrr rAxsrA)rrCrVrGrQrZsignalsrZ __unittestobjectrZ TestResultrrArrrr s  [PK!T`aa'__pycache__/runner.cpython-36.opt-2.pycnu[3 \G@sjddlZddlZddlZddlmZddlmZdZGdddeZ Gdd d ej Z Gd d d eZ dS) N)result)registerResultTc@s&eZdZddZddZdddZdS) _WritelnDecoratorcCs ||_dS)N)stream)selfrr'/usr/lib64/python3.6/unittest/runner.py__init__sz_WritelnDecorator.__init__cCs|dkrt|t|j|S)Nr __getstate__)rr )AttributeErrorgetattrr)rattrrrr __getattr__sz_WritelnDecorator.__getattr__NcCs|r|j||jddS)N )write)rargrrr writelns z_WritelnDecorator.writeln)N)__name__ __module__ __qualname__r rrrrrr r srcseZdZddZddZfddZddZfdd Zfd d Zfd d Z fddZ fddZ fddZ fddZ ddZddZZS)TextTestResult=F-cs8tt|j|||||_|dk|_|dk|_||_dS)Nr)superrr rshowAlldots descriptions)rrr verbosity) __class__rr r %s   zTextTestResult.__init__cCs0|j}|jr$|r$djt||fSt|SdS)Nr)ZshortDescriptionrjoinstr)rtestZdoc_first_linerrr getDescription,s zTextTestResult.getDescriptioncsBtt|j||jr>|jj|j||jjd|jjdS)Nz ... )rr startTestrrrr$flush)rr#)r rr r%3s  zTextTestResult.startTestcsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nok.) rr addSuccessrrrrrr&)rr#)r rr r):s  zTextTestResult.addSuccesscsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NERRORE) rraddErrorrrrrrr&)rr#err)r rr r,Bs  zTextTestResult.addErrorcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NFAILF) rr addFailurerrrrrr&)rr#r-)r rr r0Js  zTextTestResult.addFailurecsLtt|j|||jr,|jjdj|n|jrH|jjd|jj dS)Nz skipped {0!r}s) rraddSkiprrrformatrrr&)rr#reason)r rr r2Rs  zTextTestResult.addSkipcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)Nzexpected failurex) rraddExpectedFailurerrrrrr&)rr#r-)r rr r6Zs  z!TextTestResult.addExpectedFailurecsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nzunexpected successu) rraddUnexpectedSuccessrrrrrr&)rr#)r rr r8bs  z#TextTestResult.addUnexpectedSuccesscCs6|js |jr|jj|jd|j|jd|jdS)Nr*r.)rrrrprintErrorListerrorsfailures)rrrr printErrorsjs  zTextTestResult.printErrorscCs\xV|D]N\}}|jj|j|jjd||j|f|jj|j|jjd|qWdS)Nz%s: %sz%s)rr separator1r$ separator2)rZflavourr:r#r-rrr r9ps zTextTestResult.printErrorList)rrrr=r>r r$r%r)r,r0r2r6r8r<r9 __classcell__rr)r r rs        rc@s0eZdZeZd ddddZdd Zd d ZdS) TextTestRunnerNTrF) tb_localsc CsN|dkrtj}t||_||_||_||_||_||_||_ |dk rJ||_ dS)N) sysstderrrrrrfailfastbufferrAwarnings resultclass) rrrrrDrErGrFrArrr r s zTextTestRunner.__init__cCs|j|j|j|jS)N)rGrrr)rrrr _makeResultszTextTestRunner._makeResultcCs4|j}t||j|_|j|_|j|_tj|jr^tj|j|jdkr^tjdt ddt j }t |dd}|dk r|z ||Wdt |dd}|dk r|Xt j }WdQRX||}|j t |dr|jj|j|j}|jjd ||d krd pd |f|jjd } } } ytt|j|j|jf} Wntk rVYn X| \} } } g} |js|jjdt|jt|j}}|r| jd||r| jd|n |jjd| r| jd| | r| jd| | r| jd| | r$|jjddj| fn |jjd|S)NdefaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRun stopTestRunr>zRan %d test%s in %.3fsrr1rZFAILEDz failures=%dz errors=%dZOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (%s)z, r)rIrJ)rHrrDrErArFcatch_warnings simplefilterfilterwarningsDeprecationWarningtimer r<hasattrrrr>ZtestsRunmaplenZexpectedFailuresunexpectedSuccessesskippedr Z wasSuccessfulrr;r:appendr!)rr#rZ startTimerNrOZstopTimeZ timeTakenrunZ expectedFailsrYrZZresultsZinfosZfailedZerroredrrr r\sr              zTextTestRunner.run)NTrFFNN)rrrrrGr rHr\rrrr r@xs r@) rBrUrFrPrZsignalsrZ __unittestobjectrZ TestResultrr@rrrr s  [PK!kH!__pycache__/runner.cpython-36.pycnu[3 \G@sndZddlZddlZddlZddlmZddlmZdZGddde Z Gd d d ej Z Gd d d e Z dS) z Running testsN)result)registerResultTc@s*eZdZdZddZddZd ddZdS) _WritelnDecoratorz@Used to decorate file-like objects with a handy 'writeln' methodcCs ||_dS)N)stream)selfrr'/usr/lib64/python3.6/unittest/runner.py__init__sz_WritelnDecorator.__init__cCs|dkrt|t|j|S)Nr __getstate__)rr )AttributeErrorgetattrr)rattrrrr __getattr__sz_WritelnDecorator.__getattr__NcCs|r|j||jddS)N )write)rargrrr writelns z_WritelnDecorator.writeln)N)__name__ __module__ __qualname____doc__r rrrrrr r srcseZdZdZddZddZfddZddZfd d Zfd d Z fd dZ fddZ fddZ fddZ fddZddZddZZS)TextTestResultzhA test result class that can print formatted text results to a stream. Used by TextTestRunner. =F-cs8tt|j|||||_|dk|_|dk|_||_dS)Nr)superrr rshowAlldots descriptions)rrr verbosity) __class__rr r %s   zTextTestResult.__init__cCs0|j}|jr$|r$djt||fSt|SdS)Nr)ZshortDescriptionrjoinstr)rtestZdoc_first_linerrr getDescription,s zTextTestResult.getDescriptioncsBtt|j||jr>|jj|j||jjd|jjdS)Nz ... )rr startTestrrrr%flush)rr$)r!rr r&3s  zTextTestResult.startTestcsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nok.) rr addSuccessrrrrrr')rr$)r!rr r*:s  zTextTestResult.addSuccesscsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NERRORE) rraddErrorrrrrrr')rr$err)r!rr r-Bs  zTextTestResult.addErrorcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)NFAILF) rr addFailurerrrrrr')rr$r.)r!rr r1Js  zTextTestResult.addFailurecsLtt|j|||jr,|jjdj|n|jrH|jjd|jj dS)Nz skipped {0!r}s) rraddSkiprrrformatrrr')rr$reason)r!rr r3Rs  zTextTestResult.addSkipcsFtt|j|||jr&|jjdn|jrB|jjd|jjdS)Nzexpected failurex) rraddExpectedFailurerrrrrr')rr$r.)r!rr r7Zs  z!TextTestResult.addExpectedFailurecsDtt|j||jr$|jjdn|jr@|jjd|jjdS)Nzunexpected successu) rraddUnexpectedSuccessrrrrrr')rr$)r!rr r9bs  z#TextTestResult.addUnexpectedSuccesscCs6|js |jr|jj|jd|j|jd|jdS)Nr+r/)rrrrprintErrorListerrorsfailures)rrrr printErrorsjs  zTextTestResult.printErrorscCs\xV|D]N\}}|jj|j|jjd||j|f|jj|j|jjd|qWdS)Nz%s: %sz%s)rr separator1r% separator2)rZflavourr;r$r.rrr r:ps zTextTestResult.printErrorList)rrrrr>r?r r%r&r*r-r1r3r7r9r=r: __classcell__rr)r!r rs        rc@s4eZdZdZeZd ddddZd d Zd d 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 CsN|dkrtj}t||_||_||_||_||_||_||_ |dk rJ||_ dS)zConstruct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. N) sysstderrrrrr failfastbufferrBwarnings resultclass) rrrr rErFrHrGrBrrr r s zTextTestRunner.__init__cCs|j|j|j|jS)N)rHrrr )rrrr _makeResultszTextTestRunner._makeResultcCs4|j}t||j|_|j|_|j|_tj|jr^tj|j|jdkr^tjdt ddt j }t |dd}|dk r|z ||Wdt |dd}|dk r|Xt j }WdQRX||}|j t |d r|jj|j|j}|jjd ||d krd pd |f|jjd} } } ytt|j|j|jf} Wntk rVYn X| \} } } g} |js|jjdt|jt|j}}|r| jd||r| jd|n |jjd| r| jd| | r| jd| | r| jd| | r$|jjddj| fn |jjd|S)z&Run the given test case or test suite.defaultalwaysmodulezPlease use assert\w+ instead.)categorymessage startTestRunN stopTestRunr?zRan %d test%s in %.3fsrr2rZFAILEDz failures=%dz errors=%dZOKz skipped=%dzexpected failures=%dzunexpected successes=%dz (%s)z, r)rJrK)rIrrErFrBrGcatch_warnings simplefilterfilterwarningsDeprecationWarningtimer r=hasattrrrr?ZtestsRunmaplenZexpectedFailuresunexpectedSuccessesskippedr Z wasSuccessfulrr<r;appendr")rr$rZ startTimerOrPZstopTimeZ timeTakenrunZ expectedFailsrZr[ZresultsZinfosZfailedZerroredrrr r]sr              zTextTestRunner.run)NTrFFNN) rrrrrrHr rIr]rrrr rAxsrA)rrCrVrGrQrZsignalsrZ __unittestobjectrZ TestResultrrArrrr s  [PK!~~(__pycache__/signals.cpython-36.opt-1.pycnu[3 \c @sbddlZddlZddlmZdZGdddeZejZddZ dd Z da d d Z dd d Z dS)N)wrapsTc@seZdZddZddZdS)_InterruptHandlercCsNd|_||_t|trD|tjkr(tj}n|tjkr.default_handlerzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr)selfrrrr__init__ s    z_InterruptHandler.__init__cCsVtjtj}||k r |j|||jr2|j||d|_xtjD] }|jqBWdS)NT)r getsignalSIGINTrr_resultskeysstop)rZsignumframeZinstalled_handlerresultrrr__call__s   z_InterruptHandler.__call__N)__name__ __module__ __qualname__rrrrrrr srcCs dt|<dS)N)r)rrrrregisterResult*srcCsttj|dS)N)boolrpop)rrrr removeResult-sr!cCs.tdkr*tjtj}t|atjtjtdS)N)_interrupt_handlerr rrr)rrrrinstallHandler1s r#cs<dk r tfdd}|Stdk r8tjtjtjdS)Nc s2tjtj}tz ||Stjtj|XdS)N)r rr removeHandler)argskwargsinitial)methodrrinner;s   zremoveHandler..inner)rr"r rr)r(r)r)r(rr$9s r$)N)r weakref functoolsrZ __unittestobjectrWeakKeyDictionaryrrr!r"r#r$rrrrs  PK!~~(__pycache__/signals.cpython-36.opt-2.pycnu[3 \c @sbddlZddlZddlmZdZGdddeZejZddZ dd Z da d d Z dd d Z dS)N)wrapsTc@seZdZddZddZdS)_InterruptHandlercCsNd|_||_t|trD|tjkr(tj}n|tjkr.default_handlerzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr)selfrrrr__init__ s    z_InterruptHandler.__init__cCsVtjtj}||k r |j|||jr2|j||d|_xtjD] }|jqBWdS)NT)r getsignalSIGINTrr_resultskeysstop)rZsignumframeZinstalled_handlerresultrrr__call__s   z_InterruptHandler.__call__N)__name__ __module__ __qualname__rrrrrrr srcCs dt|<dS)N)r)rrrrregisterResult*srcCsttj|dS)N)boolrpop)rrrr removeResult-sr!cCs.tdkr*tjtj}t|atjtjtdS)N)_interrupt_handlerr rrr)rrrrinstallHandler1s r#cs<dk r tfdd}|Stdk r8tjtjtjdS)Nc s2tjtj}tz ||Stjtj|XdS)N)r rr removeHandler)argskwargsinitial)methodrrinner;s   zremoveHandler..inner)rr"r rr)r(r)r)r(rr$9s r$)N)r weakref functoolsrZ __unittestobjectrWeakKeyDictionaryrrr!r"r#r$rrrrs  PK!~~"__pycache__/signals.cpython-36.pycnu[3 \c @sbddlZddlZddlmZdZGdddeZejZddZ dd Z da d d Z dd d Z dS)N)wrapsTc@seZdZddZddZdS)_InterruptHandlercCsNd|_||_t|trD|tjkr(tj}n|tjkr.default_handlerzYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object) calledoriginal_handler isinstanceintsignalSIG_DFLdefault_int_handlerSIG_IGN TypeErrorr)selfrrrr__init__ s    z_InterruptHandler.__init__cCsVtjtj}||k r |j|||jr2|j||d|_xtjD] }|jqBWdS)NT)r getsignalSIGINTrr_resultskeysstop)rZsignumframeZinstalled_handlerresultrrr__call__s   z_InterruptHandler.__call__N)__name__ __module__ __qualname__rrrrrrr srcCs dt|<dS)N)r)rrrrregisterResult*srcCsttj|dS)N)boolrpop)rrrr removeResult-sr!cCs.tdkr*tjtj}t|atjtjtdS)N)_interrupt_handlerr rrr)rrrrinstallHandler1s r#cs<dk r tfdd}|Stdk r8tjtjtjdS)Nc s2tjtj}tz ||Stjtj|XdS)N)r rr removeHandler)argskwargsinitial)methodrrinner;s   zremoveHandler..inner)rr"r rr)r(r)r)r(rr$9s r$)N)r weakref functoolsrZ __unittestobjectrWeakKeyDictionaryrrr!r"r#r$rrrrs  PK!ZZ##&__pycache__/suite.cpython-36.opt-1.pycnu[3 \(@s|dZddlZddlmZddlmZdZddZGd d d eZGd ddeZ Gd d d eZ ddZ GdddeZ dS) TestSuiteN)case)utilTcCst||dd}|dS)NcSsdS)Nrrr&/usr/lib64/python3.6/unittest/suite.py sz!_call_if_exists..)getattr)parentattrfuncrrr_call_if_exists sr c@speZdZdZdZffddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZdS) BaseTestSuitezNA simple test suite that doesn't provide class or module shared fixtures. TcCsg|_d|_|j|dS)Nr)_tests_removed_testsaddTests)selftestsrrr__init__szBaseTestSuite.__init__cCsdtj|jt|fS)Nz <%s tests=%s>)rstrclass __class__list)rrrr__repr__szBaseTestSuite.__repr__cCs t||jstSt|t|kS)N) isinstancerNotImplementedr)rotherrrr__eq__s zBaseTestSuite.__eq__cCs t|jS)N)iterr)rrrr__iter__"szBaseTestSuite.__iter__cCs(|j}x|D]}|r ||j7}q W|S)N)rcountTestCases)rZcasestestrrrr%s  zBaseTestSuite.countTestCasescCsLt|stdjt|t|trdSt|ddrNdSt|dd}|dk rt|dz^y |WnNtk r}z2t|trtj|}d|}|j|||WYdd}~XnXWdt|d XdS) NrAr;Fr<rD tearDownClassrFztearDownClass (%s)rG) r rr rHrrCrrrI) rr r.rJrKr[rLrMrNrrrr>s,         $z TestSuite._tearDownPreviousClassN)F) r6r7r8r9r0r5r@rPr?rIrBr>rrrrr\s ! c@sTeZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ dS)rWz 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. NcCs ||_dS)N) description)rr\rrrrsz_ErrorHolder.__init__cCs|jS)N)r\)rrrridsz_ErrorHolder.idcCsdS)Nr)rrrrshortDescription sz_ErrorHolder.shortDescriptioncCs d|jfS)Nz)r\)rrrrr#sz_ErrorHolder.__repr__cCs|jS)N)r])rrrr__str__&sz_ErrorHolder.__str__cCsdS)Nr)rr.rrrr0)sz_ErrorHolder.runcCs |j|S)N)r0)rr.rrrr4.sz_ErrorHolder.__call__cCsdS)Nrr)rrrrr1sz_ErrorHolder.countTestCases) r6r7r8r9ZfailureExceptionrr]r^rr_r0r4rrrrrrWsrWc Cs&y t|Wntk r dSXdS)z?A crude way to tell apart testcases and suites with duck-typingTF)rr")r rrrr=4s  r=c@seZdZdZdZdZdZdS)rCzCUsed by the TestSuite to hold previous class when running in debug.NF)r6r7r8r9rAr<r+rrrrrC=srC) r9rRrrZ __unittestr objectrrrWr=rCrrrrs  L3& PK!چ&__pycache__/suite.cpython-36.opt-2.pycnu[3 \(@sxddlZddlmZddlmZdZddZGdd d eZGd d d eZGd d d eZ ddZ GdddeZ dS)N)case)utilTcCst||dd}|dS)NcSsdS)Nrrr&/usr/lib64/python3.6/unittest/suite.py sz!_call_if_exists..)getattr)parentattrfuncrrr_call_if_exists sr c@sleZdZdZffddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS) BaseTestSuiteTcCsg|_d|_|j|dS)Nr)_tests_removed_testsaddTests)selftestsrrr__init__szBaseTestSuite.__init__cCsdtj|jt|fS)Nz <%s tests=%s>)rstrclass __class__list)rrrr__repr__szBaseTestSuite.__repr__cCs t||jstSt|t|kS)N) isinstancerNotImplementedr)rotherrrr__eq__s zBaseTestSuite.__eq__cCs t|jS)N)iterr)rrrr__iter__"szBaseTestSuite.__iter__cCs(|j}x|D]}|r ||j7}q W|S)N)rcountTestCases)rZcasestestrrrr%s  zBaseTestSuite.countTestCasescCsLt|stdjt|t|trs,      $zTestSuite._handleModuleFixturecCsLt|}t|dd}|dk r8t|tjr8||t|n|j|tjdS)NaddSkip) _ErrorHolderrrrZSkipTestr)ZaddErrorrQexc_info)rr.Z exceptionrMerrorrUrrrrHs  z)TestSuite._addClassOrModuleLevelExceptionc Cs|j|}|dkrdS|jr dSytj|}Wntk rBdSXt|dd}|dk rt|dzTy |WnDtk r}z(t|t rd|}|j |||WYdd}~XnXWdt|dXdS)NtearDownModulerEztearDownModule (%s)rF) rOr;rQrRrSrr rGrrBrH)rr.rNrTrYrKrMrrrrAs(     $zTestSuite._handleModuleTearDownc Cst|dd}|j}||krdSt|ddr.dSt|ddr>dSt|ddrNdSt|dd}|dk rt|dz^y |WnNtk r}z2t|trtj|}d|}|j|||WYdd}~XnXWdt|d XdS) Nr@r:Fr;rC tearDownClassrEztearDownClass (%s)rF) rrr rGrrBrrrH) rrr.rIrJrZrKrLrMrrrr=s,         $z TestSuite._tearDownPreviousClassN)F) r6r7r8r0r5r?rOr>rHrAr=rrrrr&\s ! r&c@sPeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ dS)rVNcCs ||_dS)N) description)rr[rrrrsz_ErrorHolder.__init__cCs|jS)N)r[)rrrridsz_ErrorHolder.idcCsdS)Nr)rrrrshortDescription sz_ErrorHolder.shortDescriptioncCs d|jfS)Nz)r[)rrrrr#sz_ErrorHolder.__repr__cCs|jS)N)r\)rrrr__str__&sz_ErrorHolder.__str__cCsdS)Nr)rr.rrrr0)sz_ErrorHolder.runcCs |j|S)N)r0)rr.rrrr4.sz_ErrorHolder.__call__cCsdS)Nrr)rrrrr1sz_ErrorHolder.countTestCases) r6r7r8ZfailureExceptionrr\r]rr^r0r4rrrrrrVs rVc Cs&y t|Wntk r dSXdS)NTF)rr!)rrrrr<4s  r<c@seZdZdZdZdZdS)rBNF)r6r7r8r@r;r+rrrrrB=srB) rQrrZ __unittestr objectr r&rVr<rBrrrrs  L3& PK!ZZ## __pycache__/suite.cpython-36.pycnu[3 \(@s|dZddlZddlmZddlmZdZddZGd d d eZGd ddeZ Gd d d eZ ddZ GdddeZ dS) TestSuiteN)case)utilTcCst||dd}|dS)NcSsdS)Nrrr&/usr/lib64/python3.6/unittest/suite.py sz!_call_if_exists..)getattr)parentattrfuncrrr_call_if_exists sr c@speZdZdZdZffddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZdS) BaseTestSuitezNA simple test suite that doesn't provide class or module shared fixtures. TcCsg|_d|_|j|dS)Nr)_tests_removed_testsaddTests)selftestsrrr__init__szBaseTestSuite.__init__cCsdtj|jt|fS)Nz <%s tests=%s>)rstrclass __class__list)rrrr__repr__szBaseTestSuite.__repr__cCs t||jstSt|t|kS)N) isinstancerNotImplementedr)rotherrrr__eq__s zBaseTestSuite.__eq__cCs t|jS)N)iterr)rrrr__iter__"szBaseTestSuite.__iter__cCs(|j}x|D]}|r ||j7}q W|S)N)rcountTestCases)rZcasestestrrrr%s  zBaseTestSuite.countTestCasescCsLt|stdjt|t|trdSt|ddrNdSt|dd}|dk rt|dz^y |WnNtk r}z2t|trtj|}d|}|j|||WYdd}~XnXWdt|d XdS) NrAr;Fr<rD tearDownClassrFztearDownClass (%s)rG) r rr rHrrCrrrI) rr r.rJrKr[rLrMrNrrrr>s,         $z TestSuite._tearDownPreviousClassN)F) r6r7r8r9r0r5r@rPr?rIrBr>rrrrr\s ! c@sTeZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ dS)rWz 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. NcCs ||_dS)N) description)rr\rrrrsz_ErrorHolder.__init__cCs|jS)N)r\)rrrridsz_ErrorHolder.idcCsdS)Nr)rrrrshortDescription sz_ErrorHolder.shortDescriptioncCs d|jfS)Nz)r\)rrrrr#sz_ErrorHolder.__repr__cCs|jS)N)r])rrrr__str__&sz_ErrorHolder.__str__cCsdS)Nr)rr.rrrr0)sz_ErrorHolder.runcCs |j|S)N)r0)rr.rrrr4.sz_ErrorHolder.__call__cCsdS)Nrr)rrrrr1sz_ErrorHolder.countTestCases) r6r7r8r9ZfailureExceptionrr]r^rr_r0r4rrrrrrWsrWc Cs&y t|Wntk r dSXdS)z?A crude way to tell apart testcases and suites with duck-typingTF)rr")r rrrr=4s  r=c@seZdZdZdZdZdZdS)rCzCUsed by the TestSuite to hold previous class when running in debug.NF)r6r7r8r9rAr<r+rrrrrC=srC) r9rRrrZ __unittestr objectrrrWr=rCrrrrs  L3& PK!ZSPP%__pycache__/util.cpython-36.opt-1.pycnu[3 \9@sdZddlmZmZddlmZdZdZdZdZ dZ dZ ee ee ee Z dd Z d d Zd d dZddZddZddZddZeddZddZddZddZdS)!zVarious utility functions.) namedtuple OrderedDict) commonprefixTP cCsBt|||}|tkr>d|d|||t||df}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlenZ suffixlenskipr %/usr/lib64/python3.6/unittest/util.py_shortens&rcsttt|}ttt|}|tkr(|St|tt|tt}|t krxt t|tfdd|DSt tt tfdd|DS)Nc3s|]}|dVqdS)Nr ).0r )prefixr r r 'sz'_common_shorten_repr..c3s&|]}t|dttVqdS)N)r _MIN_DIFF_LEN _MIN_END_LEN)rr )rr r rr*s) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENr)argsmaxlenZ common_lenr )rr r_common_shorten_reprs  rFc CsRy t|}Wntk r*tj|}YnX| s>t|tkrB|S|dtdS)Nz [truncated]...)repr Exceptionobject__repr__rr)objZshortresultr r rr-s rcCsd|j|jfS)Nz%s.%s) __module__ __qualname__)clsr r rstrclass6sr(cCs*d}}g}g}xy||}||}||kr\|j||d7}x|||krX|d7}qBWn||kr|j||d7}xf|||kr|d7}qxWnL|d7}zx|||kr|d7}qWWd|d7}x|||kr|d7}qWXWqtk r|j||d|j||dPYqXqW||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. rN)append IndexErrorextend)expectedactualijmissingZ unexpectedear r rsorted_list_difference9s:   r4c CsLg}x>|rB|j}y|j|Wqtk r>|j|YqXqW||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 ValueErrorr*)r-r.r1itemr r runorderable_list_differencebsr9cCs||k||kS)z.Return -1 if x < y, 0 if x == y and 1 if x > yr )xyr r r three_way_cmpssr<ZMismatchzactual expected valuecCsDt|t|}}t|t|}}t}g}xt|D]\}} | |krJq8d} } x.t||D] } || | kr^| d7} ||| <q^Wx,t|D] \} } | | kr| d7} ||| <qW| | kr8t| | | }|j|q8Wxlt|D]`\}} | |krqd} x2t||D]$} || | kr| d7} ||| <qWtd| | }|j|qW|S)zHReturns list of (cnt_act, cnt_exp, elem) triples where the counts differrr))listrr! enumeraterange _Mismatchr*)r.r-r tmnZNULLr$r/elemcnt_scnt_tr0Z other_elemdiffr r r_count_diff_all_purposeys<     rHcCs,t}x |D]}|j|dd||<q W|S)z@Return dict of element counts, in the order they were first seenrr))rget)iterablecrDr r r_ordered_counts rLc Cst|t|}}g}x>|jD]2\}}|j|d}||kr t|||}|j|q Wx2|jD]&\}}||kr`td||}|j|q`W|S)zHReturns list of (cnt_act, cnt_exp, elem) triples where the counts differr)rLitemsrIr@r*) r.r-r rAr$rDrErFrGr r r_count_diff_hashables   rNN)F)__doc__ collectionsrrZos.pathrZ __unittestrr rrrrrrrr(r4r9r<r@rHrLrNr r r rs*  ) #PK!tp%__pycache__/util.cpython-36.opt-2.pycnu[3 \9@sddlmZmZddlmZdZdZdZdZdZ dZ eeee ee Z ddZ d d Z dd d ZddZddZddZddZeddZddZddZddZdS) ) namedtuple OrderedDict) commonprefixTP cCsBt|||}|tkr>d|d|||t||df}|S)Nz%s[%d chars]%s)len_PLACEHOLDER_LEN)s prefixlenZ suffixlenskipr %/usr/lib64/python3.6/unittest/util.py_shortens&rcsttt|}ttt|}|tkr(|St|tt|tt}|t krxt t|tfdd|DSt tt tfdd|DS)Nc3s|]}|dVqdS)Nr ).0r )prefixr r r 'sz'_common_shorten_repr..c3s&|]}t|dttVqdS)N)r _MIN_DIFF_LEN _MIN_END_LEN)rr )rr r rr*s) tuplemap safe_reprmaxr _MAX_LENGTHr_MIN_BEGIN_LENr _MIN_COMMON_LENr)argsmaxlenZ common_lenr )rr r_common_shorten_reprs  rFc CsRy t|}Wntk r*tj|}YnX| s>t|tkrB|S|dtdS)Nz [truncated]...)repr Exceptionobject__repr__rr)objZshortresultr r rr-s rcCsd|j|jfS)Nz%s.%s) __module__ __qualname__)clsr r rstrclass6sr(cCs*d}}g}g}xy||}||}||kr\|j||d7}x|||krX|d7}qBWn||kr|j||d7}xf|||kr|d7}qxWnL|d7}zx|||kr|d7}qWWd|d7}x|||kr|d7}qWXWqtk r|j||d|j||dPYqXqW||fS)Nr)append IndexErrorextend)expectedactualijmissingZ unexpectedear r rsorted_list_difference9s:   r4c CsLg}x>|rB|j}y|j|Wqtk r>|j|YqXqW||fS)N)popremove ValueErrorr*)r-r.r1itemr r runorderable_list_differencebsr9cCs||k||kS)Nr )xyr r r three_way_cmpssr<ZMismatchzactual expected valuecCsDt|t|}}t|t|}}t}g}xt|D]\}} | |krJq8d} } x.t||D] } || | kr^| d7} ||| <q^Wx,t|D] \} } | | kr| d7} ||| <qW| | kr8t| | | }|j|q8Wxlt|D]`\}} | |krqd} x2t||D]$} || | kr| d7} ||| <qWtd| | }|j|qW|S)Nrr))listrr! enumeraterange _Mismatchr*)r.r-r tmnZNULLr$r/elemcnt_scnt_tr0Z other_elemdiffr r r_count_diff_all_purposeys<     rHcCs,t}x |D]}|j|dd||<q W|S)Nrr))rget)iterablecrDr r r_ordered_counts rLc Cst|t|}}g}x>|jD]2\}}|j|d}||kr t|||}|j|q Wx2|jD]&\}}||kr`td||}|j|q`W|S)Nr)rLitemsrIr@r*) r.r-r rAr$rDrErFrGr r r_count_diff_hashables   rNN)F) collectionsrrZos.pathrZ __unittestrr rrrrrrrr(r4r9r<r@rHrLrNr r r rs(  ) #PK!7 __init__.pynu[""" Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework. 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 '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', 'TestSuite', 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', 'expectedFailure', 'TextTestResult', 'installHandler', 'registerResult', 'removeResult', 'removeHandler'] # Expose obsolete functions for backwards compatibility __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) __unittest = True from .result import TestResult from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf, skipUnless, expectedFailure, _skipInRpmBuild, _expectedFailureInRpmBuild) from .suite import BaseTestSuite, TestSuite from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames, findTestCases) from .main import TestProgram, main from .runner import TextTestRunner, TextTestResult from .signals import installHandler, registerResult, removeResult, removeHandler # deprecated _TextTestResult = TextTestResult PK!m __main__.pynu["""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): sys.argv[0] = "python -m unittest" __unittest = True from .main import main, TestProgram, USAGE_AS_MAIN TestProgram.USAGE = USAGE_AS_MAIN main(module=None) PK!:ЫЫcase.pynu["""Test case implementation""" import collections import os import sys import functools import difflib import pprint import re import types import warnings from . import result from .util import ( strclass, safe_repr, unorderable_list_difference, _count_diff_all_purpose, _count_diff_hashable ) __unittest = True 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. """ pass class _ExpectedFailure(Exception): """ Raise this when a test is expected to fail. This is an implementation detail. """ def __init__(self, exc_info): super(_ExpectedFailure, self).__init__() self.exc_info = exc_info class _UnexpectedSuccess(Exception): """ The test was supposed to fail, but it didn't! """ pass def _id(obj): return obj def skip(reason): """ Unconditionally skip a test. """ def decorator(test_item): if not isinstance(test_item, (type, types.ClassType)): @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 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(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception: raise _ExpectedFailure(sys.exc_info()) raise _UnexpectedSuccess return wrapper # Non-standard/downstream-only hooks for handling issues with specific test # cases: def _skipInRpmBuild(reason): """ 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. """ if 'WITHIN_PYTHON_RPM_BUILD' in os.environ: return skip(reason) else: return _id def _expectedFailureInRpmBuild(func): """ 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. """ @functools.wraps(func) def wrapper(*args, **kwargs): if 'WITHIN_PYTHON_RPM_BUILD' in os.environ: try: func(*args, **kwargs) except Exception: raise _ExpectedFailure(sys.exc_info()) raise _UnexpectedSuccess else: # Call directly: func(*args, **kwargs) return wrapper class _AssertRaisesContext(object): """A context manager used to implement TestCase.assertRaises* methods.""" def __init__(self, expected, test_case, expected_regexp=None): self.expected = expected self.failureException = test_case.failureException self.expected_regexp = expected_regexp 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) raise self.failureException( "{0} not raised".format(exc_name)) if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False self.exception = exc_value # store for later retrieval if self.expected_regexp is None: return True expected_regexp = self.expected_regexp if not expected_regexp.search(str(exc_value)): raise self.failureException('"%s" does not match "%s"' % (expected_regexp.pattern, str(exc_value))) return True 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 = False maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 # Attribute used by TestSuite for classSetUp _classSetupFailed = False 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._resultForDoCleanups = None try: testMethod = getattr(self, methodName) except AttributeError: raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) self._testMethodDoc = testMethod.__doc__ self._cleanups = [] # 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') try: self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual') except NameError: # No unicode support in this build pass 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 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 and doc.split("\n")[0].strip() or 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 __ne__(self, other): return not self == other def __hash__(self): return hash((type(self), self._testMethodName)) def __str__(self): return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) def __repr__(self): return "<%s testMethod=%s>" % \ (strclass(self.__class__), self._testMethodName) def _addSkip(self, result, reason): addSkip = getattr(result, 'addSkip', None) if addSkip is not None: addSkip(self, reason) else: warnings.warn("TestResult has no addSkip method, skips not reported", RuntimeWarning, 2) result.addSuccess(self) def run(self, result=None): orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() self._resultForDoCleanups = result result.startTest(self) 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. try: skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) self._addSkip(result, skip_why) finally: result.stopTest(self) return try: success = False try: self.setUp() except SkipTest as e: self._addSkip(result, str(e)) except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) else: try: testMethod() except KeyboardInterrupt: raise except self.failureException: result.addFailure(self, sys.exc_info()) except _ExpectedFailure as e: addExpectedFailure = getattr(result, 'addExpectedFailure', None) if addExpectedFailure is not None: addExpectedFailure(self, e.exc_info) else: warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", RuntimeWarning) result.addSuccess(self) except _UnexpectedSuccess: addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None) if addUnexpectedSuccess is not None: addUnexpectedSuccess(self) else: warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures", RuntimeWarning) result.addFailure(self, sys.exc_info()) except SkipTest as e: self._addSkip(result, str(e)) except: result.addError(self, sys.exc_info()) else: success = True try: self.tearDown() except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) success = False cleanUpSuccess = self.doCleanups() success = success and cleanUpSuccess if success: result.addSuccess(self) finally: result.stopTest(self) if orig_result is None: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" result = self._resultForDoCleanups ok = True while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) try: function(*args, **kwargs) except KeyboardInterrupt: raise except: ok = False result.addError(self, sys.exc_info()) return ok def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the test without collecting errors in a TestResult""" self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) 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, excClass, callableObj=None, *args, **kwargs): """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() 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(excClass, self) if callableObj is None: return context with context: callableObj(*args, **kwargs) 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, basestring): 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' % (safe_repr(first), safe_repr(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") if delta is not None: if abs(first - second) <= delta: return standardMsg = '%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if round(abs(second-first), 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 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") if delta is not None: if not (first == second) and abs(first - second) > delta: return standardMsg = '%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if not (first == second) and round(abs(second-first), 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) # Synonyms for assertion methods # The plurals are undocumented. Keep them that way to discourage use. # Do not add more. Do not remove. # Going through a deprecation cycle on these would annoy many people. assertEquals = assertEqual assertNotEquals = assertNotEqual assertAlmostEquals = assertAlmostEqual assertNotAlmostEquals = assertNotAlmostEqual assert_ = assertTrue # These fail* assertion method names are pending deprecation and will # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578 def _deprecate(original_func): def deprecated_func(*args, **kwargs): warnings.warn( 'Please use {0} instead.'.format(original_func.__name__), PendingDeprecationWarning, 2) return original_func(*args, **kwargs) return deprecated_func failUnlessEqual = _deprecate(assertEqual) failIfEqual = _deprecate(assertNotEqual) failUnlessAlmostEqual = _deprecate(assertAlmostEqual) failIfAlmostEqual = _deprecate(assertNotAlmostEqual) failUnless = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) 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 seq1_repr = safe_repr(seq1) seq2_repr = safe_repr(seq2) if len(seq1_repr) > 30: seq1_repr = seq1_repr[:30] + '...' if len(seq2_repr) > 30: seq2_repr = seq2_repr[:30] + '...' elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = '%ss differ: %s != %s\n' % elements for i in xrange(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, safe_repr(item1), safe_repr(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, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, 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' % (safe_repr(d1, True), safe_repr(d2, True)) 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, expected, actual, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = [] for key, value in expected.iteritems(): if key not in actual: missing.append(key) elif value != actual[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[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 assertItemsEqual(self, expected_seq, actual_seq, msg=None): """An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(expected_seq), list(actual_seq) with warnings.catch_warnings(): if sys.py3kwarning: # Silence Py3k warning raised during the sorting for _msg in ["(code|dict|type) inequality comparisons", "builtin_function_or_method order comparisons", "comparing unequal types"]: warnings.filterwarnings("ignore", _msg, DeprecationWarning) 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, basestring, 'First argument is not a string') self.assertIsInstance(second, basestring, '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(True) secondlines = second.splitlines(True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True)) 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 assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs): """Asserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs. """ if expected_regexp is not None: expected_regexp = re.compile(expected_regexp) context = _AssertRaisesContext(expected_exception, self, expected_regexp) if callable_obj is None: return context with context: callable_obj(*args, **kwargs) def assertRegexpMatches(self, text, expected_regexp, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, basestring): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): msg = msg or "Regexp didn't match" msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text) raise self.failureException(msg) def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, basestring): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) if match: msg = msg or "Regexp matched" msg = '%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_regexp.pattern, text) raise self.failureException(msg) 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 __ne__(self, other): return not self == other 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 PK!44 loader.pynu["""Loading unittests.""" import os import re import sys import traceback import types from functools import cmp_to_key as _CmpToKey from fnmatch import fnmatch from . import case, suite __unittest = True # what about .pyc or .pyo (etc) # we would need to avoid loading the same tests multiple times # from '.py', '.pyc' *and* '.pyo' VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) def _make_failed_import_test(name, suiteClass): message = 'Failed to import test module: %s\n%s' % (name, traceback.format_exc()) return _make_failed_test('ModuleImportFailure', name, ImportError(message), suiteClass) def _make_failed_load_tests(name, exception, suiteClass): return _make_failed_test('LoadTestsFailure', name, exception, suiteClass) def _make_failed_test(classname, methodname, exception, suiteClass): def testFailure(self): raise exception attrs = {methodname: testFailure} TestClass = type(classname, (case.TestCase,), attrs) return suiteClass((TestClass(methodname),)) class TestLoader(object): """ This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ testMethodPrefix = 'test' sortTestMethodsUsing = cmp suiteClass = suite.TestSuite _top_level_dir = None 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?") testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) return loaded_suite def loadTestsFromModule(self, module, use_load_tests=True): """Return a suite of all test cases contained in the given module""" tests = [] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, case.TestCase): tests.append(self.loadTestsFromTestCase(obj)) load_tests = getattr(module, 'load_tests', None) tests = self.suiteClass(tests) if use_load_tests and load_tests is not None: try: return load_tests(self, tests, None) except Exception, e: return _make_failed_load_tests(module.__name__, e, self.suiteClass) 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('.') if module is None: parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: parent, obj = obj, getattr(obj, part) if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) elif isinstance(obj, type) and issubclass(obj, case.TestCase): return self.loadTestsFromTestCase(obj) elif (isinstance(obj, types.UnboundMethodType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): name = parts[-1] inst = parent(name) return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj elif hasattr(obj, '__call__'): 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 isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and \ hasattr(getattr(testCaseClass, attrname), '__call__') testFnNames = filter(isTestMethod, dir(testCaseClass)) if self.sortTestMethodsUsing: testFnNames.sort(key=_CmpToKey(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. 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. 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(). """ 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] start_dir = os.path.abspath(os.path.dirname((the_module.__file__))) 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): path = os.path.splitext(os.path.normpath(path))[0] _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.""" paths = os.listdir(start_dir) for path in paths: full_path = os.path.join(start_dir, path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(path): # valid Python identifiers only continue if not self._match_path(path, full_path, pattern): continue # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except: yield _make_failed_import_test(name, self.suiteClass) else: mod_file = os.path.abspath(getattr(module, '__file__', full_path)) realpath = os.path.splitext(os.path.realpath(mod_file))[0] fullpath_noext = os.path.splitext(os.path.realpath(full_path))[0] if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = os.path.splitext(os.path.basename(full_path))[0] 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)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): continue load_tests = None tests = None if fnmatch(path, pattern): # only check load_tests if the package directory itself matches the filter name = self._get_name_from_path(full_path) package = self._get_module_from_name(name) load_tests = getattr(package, 'load_tests', None) tests = self.loadTestsFromModule(package, use_load_tests=False) if load_tests is None: if tests is not None: # tests loaded from package file yield tests # recurse into the package for test in self._find_tests(full_path, pattern): yield test else: try: yield load_tests(self, tests, pattern) except Exception, e: yield _make_failed_load_tests(package.__name__, e, self.suiteClass) defaultTestLoader = TestLoader() def _makeLoader(prefix, sortUsing, suiteClass=None): loader = TestLoader() loader.sortTestMethodsUsing = sortUsing loader.testMethodPrefix = prefix if suiteClass: loader.suiteClass = suiteClass return loader def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass) def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module) PK!#{#{#main.pynu["""Unittest main program""" import sys import os import types from . import loader, runner from .signals import installHandler __unittest = True FAILFAST = " -f, --failfast Stop on first failure\n" CATCHBREAK = " -c, --catch Catch control-C and display results\n" BUFFEROUTPUT = " -b, --buffer Buffer stdout and stderr during test runs\n" USAGE_AS_MAIN = """\ Usage: %(progName)s [options] [tests] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s test_module - run tests from test_module %(progName)s module.TestClass - run tests from module.TestClass %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. Alternative Usage: %(progName)s discover [options] Options: -v, --verbose Verbose output %(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory) For test discovery all test modules must be importable from the top level directory of the project. """ USAGE_FROM_MODULE = """\ Usage: %(progName)s [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething %(progName)s MyTestCase - run all 'test*' test methods in MyTestCase """ class TestProgram(object): """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ USAGE = USAGE_FROM_MODULE # defaults for testing failfast = catchbreak = buffer = progName = 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): if isinstance(module, basestring): 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.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): if msg: print msg usage = {'progName': self.progName, 'catchbreak': '', 'failfast': '', 'buffer': ''} if self.failfast != False: usage['failfast'] = FAILFAST if self.catchbreak != False: usage['catchbreak'] = CATCHBREAK if self.buffer != False: usage['buffer'] = BUFFEROUTPUT print self.USAGE % usage sys.exit(2) def parseArgs(self, argv): if len(argv) > 1 and argv[1].lower() == 'discover': self._do_discovery(argv[2:]) return import getopt long_opts = ['help', 'verbose', 'quiet', 'failfast', 'catch', 'buffer'] try: options, args = getopt.getopt(argv[1:], 'hHvqfcb', long_opts) for opt, value in options: if opt in ('-h','-H','--help'): self.usageExit() if opt in ('-q','--quiet'): self.verbosity = 0 if opt in ('-v','--verbose'): self.verbosity = 2 if opt in ('-f','--failfast'): if self.failfast is None: self.failfast = True # Should this raise an exception if -f is not valid? if opt in ('-c','--catch'): if self.catchbreak is None: self.catchbreak = True # Should this raise an exception if -c is not valid? if opt in ('-b','--buffer'): if self.buffer is None: self.buffer = True # Should this raise an exception if -b is not valid? if len(args) == 0 and self.defaultTest is None: # createTests will load tests from self.module self.testNames = None elif len(args) > 0: self.testNames = args if __name__ == '__main__': # to support python -m unittest ... self.module = None else: self.testNames = (self.defaultTest,) self.createTests() except getopt.error, msg: self.usageExit(msg) def createTests(self): if self.testNames is None: self.test = self.testLoader.loadTestsFromModule(self.module) else: self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module) def _do_discovery(self, argv, Loader=None): if Loader is None: Loader = lambda: self.testLoader # handle command line args for test discovery self.progName = '%s discover' % self.progName import optparse parser = optparse.OptionParser() parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') if self.failfast != False: parser.add_option('-f', '--failfast', dest='failfast', default=False, help='Stop on first fail or error', action='store_true') if self.catchbreak != False: parser.add_option('-c', '--catch', dest='catchbreak', default=False, help='Catch Ctrl-C and display results so far', action='store_true') if self.buffer != False: parser.add_option('-b', '--buffer', dest='buffer', default=False, help='Buffer stdout and stderr during tests', action='store_true') parser.add_option('-s', '--start-directory', dest='start', default='.', help="Directory to start discovery ('.' default)") parser.add_option('-p', '--pattern', dest='pattern', default='test*.py', help="Pattern to match tests ('test*.py' default)") parser.add_option('-t', '--top-level-directory', dest='top', default=None, help='Top level directory of project (defaults to start directory)') options, args = parser.parse_args(argv) if len(args) > 3: self.usageExit() for name, value in zip(('start', 'pattern', 'top'), args): setattr(options, name, value) # only set options from the parsing here # if they weren't set explicitly in the constructor if self.failfast is None: self.failfast = options.failfast if self.catchbreak is None: self.catchbreak = options.catchbreak if self.buffer is None: self.buffer = options.buffer if options.verbose: self.verbosity = 2 start_dir = options.start pattern = options.pattern top_level_dir = options.top loader = Loader() self.test = loader.discover(start_dir, pattern, top_level_dir) def runTests(self): if self.catchbreak: installHandler() if self.testRunner is None: self.testRunner = runner.TextTestRunner if isinstance(self.testRunner, (type, types.ClassType)): try: testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer) 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 PK!X77mock.pynu[# 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', 'FILTER_DIR', 'NonCallableMock', 'NonCallableMagicMock', 'mock_open', 'PropertyMock', ) __version__ = '1.0' import inspect import pprint import sys import builtins from types import ModuleType from functools import wraps, partial _builtins = {name for name in dir(builtins) if not name.startswith('_')} BaseExceptions = (BaseException,) if 'java' in sys.platform: # jython import java BaseExceptions = (BaseException, java.lang.Throwable) FILTER_DIR = True # Workaround for issue #12370 # Without this, the __class__ properties wouldn't be set correctly _safe_super = super 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, BaseExceptions) or isinstance(obj, type) and issubclass(obj, BaseExceptions) ) 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__. try: func = func.__init__ except AttributeError: return None # Skip the `self` argument in __init__ eat_self = True 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(_mock_self, *args, **kwargs): sig.bind(*args, **kwargs) _copy_func_details(func, checksig) type(mock)._mock_check_sig = checksig def _copy_func_details(func, funcopy): funcopy.__name__ = func.__name__ funcopy.__doc__ = func.__doc__ try: funcopy.__text_signature__ = func.__text_signature__ except AttributeError: pass # we explicitly don't copy func.__dict__ into this copy as it would # expose original attributes that should be mocked try: funcopy.__module__ = func.__module__ except AttributeError: pass try: funcopy.__defaults__ = func.__defaults__ except AttributeError: pass try: funcopy.__kwdefaults__ = func.__kwdefaults__ except AttributeError: pass def _callable(obj): if isinstance(obj, type): return True 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. if not _callable(original): return 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) return funcopy def _setup_func(funcopy, mock): funcopy.mock = mock # can't use isinstance with mocks if not _is_instance_mock(mock): return 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 mock._mock_delegate = funcopy 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 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)) sentinel = _Sentinel() DEFAULT = sentinel.DEFAULT _missing = sentinel.MISSING _deleted = sentinel.DELETED def _copy(value): if type(value) in (dict, list, tuple, set): return type(value)(value) return value _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): 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 __iter__(self): return self 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`""" 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 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) instance = object.__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 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.""" mock._mock_parent = None mock._mock_new_parent = None mock._mock_name = '' 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): _spec_class = None _spec_signature = None if spec is not None and not _is_list(spec): if isinstance(spec, type): _spec_class = spec else: _spec_class = _get_class(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 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: 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) 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: if name.startswith(('assert', 'assret')): raise AttributeError(name) 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): result = create_autospec( result.spec, result.spec_set, result.instance, result.parent, result.name ) self._mock_children[name] = result return result def __repr__(self): _name_list = [self._mock_new_name] _parent = self._mock_new_parent last = self dot = '.' if _name_list == ['()']: dot = '' seen = set() 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 # use ids here so as not to call __hash__ on the mocks if id(_parent) in seen: break seen.add(id(_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 name = ''.join(_name_list) 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_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 + list(self._mock_children))) 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 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 if name in self.__dict__: object.__delattr__(self, name) obj = self._mock_children.get(name, _missing) if 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): message = 'Expected call: %s\nActual call: %s' expected_string = self._format_mock_call_signature(args, kwargs) call_args = self.call_args if len(call_args) == 3: call_args = call_args[1:] actual_string = self._format_mock_call_signature(*call_args) return message % (expected_string, actual_string) 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. """ sig = self._spec_signature if sig is not None: if len(_call) == 2: name = '' args, kwargs = _call else: name, args, kwargs = _call try: return name, sig.bind(*args, **kwargs) except TypeError as e: return e.with_traceback(None) else: return _call def assert_not_called(_mock_self): """assert that the mock was never called. """ self = _mock_self if self.call_count != 0: msg = ("Expected '%s' to not have been called. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) def assert_called(_mock_self): """assert that the mock was called at least once """ self = _mock_self if self.call_count == 0: msg = ("Expected '%s' to have been called." % self._mock_name or 'mock') raise AssertionError(msg) def assert_called_once(_mock_self): """assert that the mock was called only once. """ self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to have been called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None raise AssertionError(_error_message()) from cause def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) 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 = expected if isinstance(expected, Exception) else None all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) if not any_order: if expected not in all_calls: raise AssertionError( 'Calls not found.\nExpected: %r\n' 'Actual: %r' % (_CallList(calls), self.mock_calls) ) 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 not all found in call list' % (tuple(not_found),) ) 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((args, kwargs)) actual = [self._call_matcher(c) for c in self.call_args_list] if expected not in actual: cause = expected if isinstance(expected, Exception) else None 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).""" _type = type(self) if 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 _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__(_mock_self, *args, **kwargs): # can't use self in-case a function / method we are mocking uses self # in the signature _mock_self._mock_check_sig(*args, **kwargs) return _mock_self._mock_call(*args, **kwargs) def _mock_call(_mock_self, *args, **kwargs): self = _mock_self self.called = True self.call_count += 1 # handle call_args _call = _Call((args, kwargs), two=True) self.call_args = _call self.call_args_list.append(_call) seen = set() # 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 # check we're not in an infinite loop: # ( use ids here so as not to call __hash__ on the mocks) _new_parent_id = id(_new_parent) if _new_parent_id in seen: break seen.add(_new_parent_id) 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_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. * `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. """ def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: __import__(import_path) return getattr(thing, comp) def _importer(target): components = target.split('.') import_path = components.pop(0) thing = __import__(import_path) for comp in components: import_path += ".%s" % comp thing = _dot_lookup(thing, comp, import_path) return thing def _is_started(patcher): # XXXX horrible return hasattr(patcher, 'is_local') class _patch(object): attribute_name = None _active_patches = [] def __init__( self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ): 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" ) 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) 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 def decorate_callable(self, func): if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) def patched(*args, **keywargs): extra_args = [] entered_patchers = [] exc_info = tuple() try: for patching in patched.patchings: arg = patching.__enter__() entered_patchers.append(patching) if patching.attribute_name is not None: keywargs.update(arg) elif patching.new is DEFAULT: extra_args.append(arg) args += tuple(extra_args) return func(*args, **keywargs) except: if (patching not in entered_patchers and _is_started(patching)): # the patcher may have been started, but an exception # raised whilst entering one of its additional_patchers entered_patchers.append(patching) # Pass the exception to __exit__ exc_info = sys.exc_info() # re-raise the exception raise finally: for patching in reversed(entered_patchers): patching.__exit__(*exc_info) 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 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 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 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 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 = patching.__enter__() if patching.new is DEFAULT: extra_args.update(arg) return extra_args return new def __exit__(self, *exc_info): """Undo the patch.""" if not _is_started(self): raise RuntimeError('stop called on unstarted patcher') 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 for patcher in reversed(self.additional_patchers): if _is_started(patcher): patcher.__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 pass return self.__exit__() def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % (target,)) getter = lambda: _importer(target) return getter, attribute def _patch_object( target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **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. """ getter = lambda: target return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ) 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 = lambda: _importer(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, **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 a `MagicMock`. 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 `MagicMock` is used. 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` takes arbitrary keyword arguments. These will be passed to the `Mock` (or `new_callable`) on construction. `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 ) 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): if isinstance(in_dict, str): in_dict = _importer(in_dict) 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) @wraps(f) def _inner(*args, **kw): self._patch_dict() try: return 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() def _patch_dict(self): values = self.values 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.""" self._unpatch_dict() return False start = __enter__ stop = __exit__ 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 " "trunc floor ceil " "bool next " ) numerics = ( "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv" ) 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__', '__setformat__', '__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() } _all_magics = _magics | _non_defaults _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), } _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, } 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__ _side_effect_methods = { '__eq__': _get_eq, '__ne__': _get_ne, '__iter__': _get_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_calulator = _calculate_return_value.get(name) if return_calulator is not None: try: return_value = return_calulator(mock) except AttributeError: # XXXX why do we return AttributeError here? # set it as a side_effect instead? return_value = AttributeError(name) 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(object): 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): these_magics = _magics if getattr(self, "_mock_methods", None) is not None: these_magics = _magics.intersection(self._mock_methods) remove_magics = set() remove_magics = _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 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(object): def __init__(self, name, parent): self.name = name self.parent = parent def __call__(self, *args, **kwargs): m = self.create_mock() return m(*args, **kwargs) 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 _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 sorted(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): if other is ANY: return True try: len_other = len(other) except TypeError: return False 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 count(self, *args, **kwargs): return self.__getattr__('count')(*args, **kwargs) def index(self, *args, **kwargs): return self.__getattr__('index')(*args, **kwargs) 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, **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` 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) _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 _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 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) else: _check_signature(spec, mock, is_type, instance) if _parent is not None and not instance: _parent._mock_children[_name] = mock 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) 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} 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 new = MagicMock(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(getattr(result, '__get__', None), MethodWrapperTypes): # Normal method => skip if looked up on type # (if looked up on instance, self is already skipped) return is_type else: return False # shouldn't get here unless function is a dynamically provided attribute # XXXX untested behaviour return is_type def _get_class(obj): try: return obj.__class__ except AttributeError: # it is possible for objects to have no __class__ return type(obj) 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__), ) MethodWrapperTypes = ( type(ANY.__eq__.__get__), ) file_spec = None def _iterate_read_data(read_data): # Helper for mock_open: # Retrieve lines from read_data via a generator so that separate calls to # readline, read, and readlines are properly interleaved sep = b'\n' if isinstance(read_data, bytes) else '\n' data_as_list = [l + sep for l in read_data.split(sep)] if data_as_list[-1] == sep: # If the last line ended in a newline, the list comprehension will have an # extra entry that's just a newline. Remove this. data_as_list = data_as_list[:-1] else: # If there wasn't an extra newline by itself, then the file being # emulated doesn't have a newline to end the last line remove the # newline that our naive format() added data_as_list[-1] = data_as_list[-1][:-1] for line in data_as_list: yield line 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` methoddline`, and `readlines` of the file handle to return. This is an empty string by default. """ def _readlines_side_effect(*args, **kwargs): if handle.readlines.return_value is not None: return handle.readlines.return_value return list(_state[0]) def _read_side_effect(*args, **kwargs): if handle.read.return_value is not None: return handle.read.return_value return type(read_data)().join(_state[0]) def _readline_side_effect(): if handle.readline.return_value is not None: while True: yield handle.readline.return_value for line in _state[0]: yield line while True: yield type(read_data)() global file_spec if file_spec is None: import _io file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) if mock is None: mock = MagicMock(name='open', spec=open) handle = MagicMock(spec=file_spec) handle.__enter__.return_value = handle _state = [_iterate_read_data(read_data), None] 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 def reset_data(*args, **kwargs): _state[0] = _iterate_read_data(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): return self() def __set__(self, obj, val): self(val) PK!Jx result.pynu["""Test result object""" import os import sys import traceback from StringIO import StringIO 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._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 = StringIO() self._stdout_buffer = 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 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" return len(self.failures) == len(self.errors) == 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 # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) 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 _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures))) PK!<H܅ runner.pynu["""Running tests""" import sys import time from . import result 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 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() def addSuccess(self, test): super(TextTestResult, self).addSuccess(test) if self.showAll: self.stream.writeln("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.stream.writeln("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.stream.writeln("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.stream.writeln("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") 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") elif self.dots: self.stream.write("u") self.stream.flush() def printErrors(self): if self.dots or self.showAll: self.stream.writeln() self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) 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) 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=sys.stderr, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None): self.stream = _WritelnDecorator(stream) self.descriptions = descriptions self.verbosity = verbosity self.failfast = failfast self.buffer = buffer 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 startTime = time.time() 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.time() 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 = map(len, (result.failures, 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") return result PK! k k signals.pynu[import 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, long)): 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) PK!ĽQ&Q&suite.pynu["""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. """ def __init__(self, tests=()): self._tests = [] 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 __ne__(self, other): return not self == other # Can't guarantee hash invariant, so flag as unhashable __hash__ = None def __iter__(self): return iter(self._tests) def countTestCases(self): cases = 0 for test in self: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not hasattr(test, '__call__'): 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, basestring): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for test in self: if result.shouldStop: break test(result) return result 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 test in 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 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 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) if setUpClass is not None: _call_if_exists(result, '_setupStdout') try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise currentClass._classSetupFailed = True className = util.strclass(currentClass) errorName = 'setUpClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) 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: setUpModule() except Exception, e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True errorName = 'setUpModule (%s)' % currentModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _addClassOrModuleLevelException(self, result, exception, errorName): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: result.addError(error, sys.exc_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 tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: _call_if_exists(result, '_setupStdout') try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: 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) if tearDownClass is not None: _call_if_exists(result, '_setupStdout') try: tearDownClass() except Exception, e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) errorName = 'tearDownClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) 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 PK!lutil.pynu["""Various utility functions.""" from collections import namedtuple, OrderedDict __unittest = True _MAX_LENGTH = 80 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.__name__) 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, ignore_duplicate=False): """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 = [] unexpected = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) if ignore_duplicate: for lst in expected, actual: try: while True: lst.remove(item) except ValueError: pass if ignore_duplicate: while actual: item = actual.pop() unexpected.append(item) try: while True: actual.remove(item) except ValueError: pass return missing, unexpected # anything left in actual is unexpected return missing, actual _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 _ordered_count(iterable): 'Return dict of element counts, in the order they were first seen' c = OrderedDict() for elem in iterable: c[elem] = c.get(elem, 0) + 1 return c 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 = _ordered_count(actual), _ordered_count(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 PK!4-7-7test/test_runner.pyonu[ |fc@sddlZddlmZddlZddlmZmZdejfdYZdejfdYZ e dkrej ndS( iN(tStringIO(t LoggingResultt#ResultWithNoStartTestRunStopTestRunt TestCleanUpcBs,eZdZdZdZdZRS(c sdtjfdY}|d}|j|jggfd}fd}|j|dddd d d d |j||j|j|d td d d d f|difg|j}|j||jddifddtd d d d fgdS(Nt TestableTestcBseZdZRS(cSsdS(N((tself((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt testNothings(t__name__t __module__R(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR sRcsjd||fdS(Ni(tappend(targstkwargs(tcleanups(s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanup1scsjd||fdS(Ni(R (R R (R (s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanup2siiitfourthellotfivetgoodbye(iii(((iii(tunittesttTestCaset assertEqualt _cleanupst addCleanuptdictt doCleanupst assertTrue(RRttestR Rtresult((R s1/usr/lib64/python2.7/unittest/test/test_runner.pyt testCleanUp s "    cs+dtjfdY}dtfdY}|}|d}||_tdtdfd}fd }|j||j||j|jt|j \\}\}} } \} \} } } |j ||| f|tf|j | | | f|tfdS( NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR+s(RRR(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR*st MockResultcBseZgZdZRS(cSs|jj||fdS(N(terrorsR (RRtexc_info((s1/usr/lib64/python2.7/unittest/test/test_runner.pytaddError0s(RRRR!(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR.sRtfootbarcs dS(N(((texc1(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR 9scs dS(N(((texc2(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR<s( RRtobjectt_resultForDoCleanupst ExceptionRt assertFalseRtreversedRR(RRRRRR Rttest1tType1t instance1t_ttest2tType2t instance2((R$R%s1/usr/lib64/python2.7/unittest/test/test_runner.pyttestCleanUpWithErrors)s       3"cstgdtjffdY}|dfd}fd}j|j|fd}tj}||_j|jddd d d d gtg|dj|j|jdd gdS( NRcs8eZfdZfdZfdZRS(cs&jdr"tdndS(NtsetUpR"(R R((R(tblowUptordering(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR3Ms csjddS(NR(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRscsjddS(NttearDown(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR6Us(RRR3RR6((R4R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRLsRcsjddS(NR (R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR ZscsjddS(NR(R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR\scs!j|jddS(Ntsuccess(RR (t some_test(R5RR(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR7asR3RR6RR R7( tFalseRRRt TestResultt addSuccesstrunRtTrue(RRR RR7R((R4R5RRs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestCleanupInRunHs("         csgdtjffdY}|dfdfdj|jdddd d gdS( NRcs8eZfdZfdZfdZRS(csjd|jdS(NR3(R R(R(R R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR3ws csjddS(NR(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR{scsjddS(NR6(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR6~s(RRR3RR6((R R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRvsRcsjdjdS(NR (R R((RR5R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR s csjddS(NR(R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRsR3RR6R R(RRtdebugR(RR((R RR5Rs1/usr/lib64/python2.7/unittest/test/test_runner.pyt!testTestCaseDebugExecutesCleanupsss"  (RRRR2R>R@(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR s   +tTest_TextTestRunnercBsVeZdZdZdZdZdZdZdZdZ dZ RS( sTests for TextTestRunner.cCsitj}|j|j|j|j|j|jd|j|j|j|j tj dS(Ni( RtTextTestRunnerR)tfailfasttbufferRt verbosityRt descriptionst resultclasstTextTestResult(Rtrunner((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt test_inits  csOdtjffdYdtjfdY}|ddddS(NtAResultcseZfdZRS(cs t|j|||dS(N(tsupert__init__(RtstreamRFRE(RK(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMs(RRRM((RK(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRKst ATextResultcBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyROsi(RR:RHtNone(RRO((RKs1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_multiple_inheritancescsdtjfdY}tjtjdtdtdt}fd|_|j|d|jj |jj dS(NtTestcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttestFoos(RRRS(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRsRNRCRDcsS(N(((R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyttRS( RRR:RBRR=t _makeResultR<RRCRD(RRRRI((Rs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestBufferAndFailfasts  csdtjfdY}tjjfd}j|tjtjdt}fd|_d_ fd}|tj_|j tj j j ddS( NRRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRSs(RRRS(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRscstj_dS(N(RRItregisterResult((toriginalRegisterResult(s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanupsRNcsS(N(((R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRTRUics#jd7_j|dS(Ni(t wasRegisteredR(t thisResult(RR(s1/usr/lib64/python2.7/unittest/test/test_runner.pytfakeRegisterResultsi( RRRIRXRR:RBRRVR[R<t TestSuiteR(RRRRZRIR]((RYRRs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestRunnerRegistersResults     csXdtfdYdtjffdY}|jtjdS(Nt OldTextResultcBseZdZdZRS(RUcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt printErrorss(RRt separator2Ra(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR`stRunnercs&eZfdZfdZRS(cst|jtdS(N(RLRMR(R(Rc(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMscsS(N((R(R`(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRVs(RRRMRV((R`Rc(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRcs(RRRBR<R^(RRI((R`Rcs1/usr/lib64/python2.7/unittest/test/test_runner.pyt7test_works_with_result_without_startTestRun_stopTestRuns" cs}dtfdYdtjffdYg}|}|jtjddg}|j||dS(NtLoggingTextResultcBseZdZdZRS(RUcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRas(RRRbRa(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRest LoggingRunnercs&eZfdZfdZRS(cs&t|jt||_dS(N(RLRMRt_events(Rtevents(Rf(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMscs |jS(N(Rg(R(Re(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRVs(RRRMRV((RfRe(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRfst startTestRunt stopTestRun(RRRBR<R^R(RRhRItexpected((RfRes1/usr/lib64/python2.7/unittest/test/test_runner.pyt$test_startTestRun_stopTestRun_calleds"  cCsddlm}|d}tj|}x^ttjdD]I}tj|d|}tj|}|j|j j |j q?WdS(Ni(RR"itprotocol( RRRBtrangetpickletHIGHEST_PROTOCOLtdumpstloadsRRNtgetvalue(Rt PickleableIORNRIRmtstobj((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_pickle_unpickles cCs~d}t}t}t}tj|||d|}|j|j||j||f}|j|j|dS(NcWs|S(N((R ((s1/usr/lib64/python2.7/unittest/test/test_runner.pytMockResultClasssRG(R&RRBRRGRNRV(RRxtSTREAMt DESCRIPTIONSt VERBOSITYRItexpectedresult((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_resultclasss     ( RRt__doc__RJRQRWR_RdRlRwR}(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRAs     t__main__( Rt cStringIORRotunittest.test.supportRRRRRARtmain(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyts  } PK!ٙ7L@L@test/test_setups.pynu[import sys from cStringIO import StringIO import unittest def resultFactory(*_): return unittest.TestResult() class TestSetups(unittest.TestCase): def getRunner(self): return unittest.TextTestRunner(resultclass=resultFactory, stream=StringIO()) def runTests(self, *cases): suite = unittest.TestSuite() for case in cases: tests = unittest.defaultTestLoader.loadTestsFromTestCase(case) suite.addTests(tests) runner = self.getRunner() # creating a nested suite exposes some potential bugs realSuite = unittest.TestSuite() realSuite.addTest(suite) # adding empty suites to the end exposes potential bugs suite.addTest(unittest.TestSuite()) realSuite.addTest(unittest.TestSuite()) return runner.run(realSuite) def test_setup_class(self): class Test(unittest.TestCase): setUpCalled = 0 @classmethod def setUpClass(cls): Test.setUpCalled += 1 unittest.TestCase.setUpClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(Test.setUpCalled, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_teardown_class(self): class Test(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(Test.tearDownCalled, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_teardown_class_two_classes(self): class Test(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test2.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test, Test2) self.assertEqual(Test.tearDownCalled, 1) self.assertEqual(Test2.tearDownCalled, 1) self.assertEqual(result.testsRun, 4) self.assertEqual(len(result.errors), 0) def test_error_in_setupclass(self): class BrokenTest(unittest.TestCase): @classmethod def setUpClass(cls): raise TypeError('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(BrokenTest) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'setUpClass (%s.BrokenTest)' % __name__) def test_error_in_teardown_class(self): class Test(unittest.TestCase): tornDown = 0 @classmethod def tearDownClass(cls): Test.tornDown += 1 raise TypeError('foo') def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): tornDown = 0 @classmethod def tearDownClass(cls): Test2.tornDown += 1 raise TypeError('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(Test, Test2) self.assertEqual(result.testsRun, 4) self.assertEqual(len(result.errors), 2) self.assertEqual(Test.tornDown, 1) self.assertEqual(Test2.tornDown, 1) error, _ = result.errors[0] self.assertEqual(str(error), 'tearDownClass (%s.Test)' % __name__) def test_class_not_torndown_when_setup_fails(self): class Test(unittest.TestCase): tornDown = False @classmethod def setUpClass(cls): raise TypeError @classmethod def tearDownClass(cls): Test.tornDown = True raise TypeError('foo') def test_one(self): pass self.runTests(Test) self.assertFalse(Test.tornDown) def test_class_not_setup_or_torndown_when_skipped(self): class Test(unittest.TestCase): classSetUp = False tornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.tornDown = True def test_one(self): pass Test = unittest.skip("hop")(Test) self.runTests(Test) self.assertFalse(Test.classSetUp) self.assertFalse(Test.tornDown) def test_setup_teardown_order_with_pathological_suite(self): results = [] class Module1(object): @staticmethod def setUpModule(): results.append('Module1.setUpModule') @staticmethod def tearDownModule(): results.append('Module1.tearDownModule') class Module2(object): @staticmethod def setUpModule(): results.append('Module2.setUpModule') @staticmethod def tearDownModule(): results.append('Module2.tearDownModule') class Test1(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 1') @classmethod def tearDownClass(cls): results.append('teardown 1') def testOne(self): results.append('Test1.testOne') def testTwo(self): results.append('Test1.testTwo') class Test2(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 2') @classmethod def tearDownClass(cls): results.append('teardown 2') def testOne(self): results.append('Test2.testOne') def testTwo(self): results.append('Test2.testTwo') class Test3(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 3') @classmethod def tearDownClass(cls): results.append('teardown 3') def testOne(self): results.append('Test3.testOne') def testTwo(self): results.append('Test3.testTwo') Test1.__module__ = Test2.__module__ = 'Module' Test3.__module__ = 'Module2' sys.modules['Module'] = Module1 sys.modules['Module2'] = Module2 first = unittest.TestSuite((Test1('testOne'),)) second = unittest.TestSuite((Test1('testTwo'),)) third = unittest.TestSuite((Test2('testOne'),)) fourth = unittest.TestSuite((Test2('testTwo'),)) fifth = unittest.TestSuite((Test3('testOne'),)) sixth = unittest.TestSuite((Test3('testTwo'),)) suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth)) runner = self.getRunner() result = runner.run(suite) self.assertEqual(result.testsRun, 6) self.assertEqual(len(result.errors), 0) self.assertEqual(results, ['Module1.setUpModule', 'setup 1', 'Test1.testOne', 'Test1.testTwo', 'teardown 1', 'setup 2', 'Test2.testOne', 'Test2.testTwo', 'teardown 2', 'Module1.tearDownModule', 'Module2.setUpModule', 'setup 3', 'Test3.testOne', 'Test3.testTwo', 'teardown 3', 'Module2.tearDownModule']) def test_setup_module(self): class Module(object): moduleSetup = 0 @staticmethod def setUpModule(): Module.moduleSetup += 1 class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(Module.moduleSetup, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_error_in_setup_module(self): class Module(object): moduleSetup = 0 moduleTornDown = 0 @staticmethod def setUpModule(): Module.moduleSetup += 1 raise TypeError('foo') @staticmethod def tearDownModule(): Module.moduleTornDown += 1 class Test(unittest.TestCase): classSetUp = False classTornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.classTornDown = True def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' Test2.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test, Test2) self.assertEqual(Module.moduleSetup, 1) self.assertEqual(Module.moduleTornDown, 0) self.assertEqual(result.testsRun, 0) self.assertFalse(Test.classSetUp) self.assertFalse(Test.classTornDown) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'setUpModule (Module)') def test_testcase_with_missing_module(self): class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules.pop('Module', None) result = self.runTests(Test) self.assertEqual(result.testsRun, 2) def test_teardown_module(self): class Module(object): moduleTornDown = 0 @staticmethod def tearDownModule(): Module.moduleTornDown += 1 class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(Module.moduleTornDown, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_error_in_teardown_module(self): class Module(object): moduleTornDown = 0 @staticmethod def tearDownModule(): Module.moduleTornDown += 1 raise TypeError('foo') class Test(unittest.TestCase): classSetUp = False classTornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.classTornDown = True def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' Test2.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test, Test2) self.assertEqual(Module.moduleTornDown, 1) self.assertEqual(result.testsRun, 4) self.assertTrue(Test.classSetUp) self.assertTrue(Test.classTornDown) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'tearDownModule (Module)') def test_skiptest_in_setupclass(self): class Test(unittest.TestCase): @classmethod def setUpClass(cls): raise unittest.SkipTest('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.skipped), 1) skipped = result.skipped[0][0] self.assertEqual(str(skipped), 'setUpClass (%s.Test)' % __name__) def test_skiptest_in_setupmodule(self): class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass class Module(object): @staticmethod def setUpModule(): raise unittest.SkipTest('foo') Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.skipped), 1) skipped = result.skipped[0][0] self.assertEqual(str(skipped), 'setUpModule (Module)') def test_suite_debug_executes_setups_and_teardowns(self): ordering = [] class Module(object): @staticmethod def setUpModule(): ordering.append('setUpModule') @staticmethod def tearDownModule(): ordering.append('tearDownModule') class Test(unittest.TestCase): @classmethod def setUpClass(cls): ordering.append('setUpClass') @classmethod def tearDownClass(cls): ordering.append('tearDownClass') def test_something(self): ordering.append('test_something') Test.__module__ = 'Module' sys.modules['Module'] = Module suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test) suite.debug() expectedOrder = ['setUpModule', 'setUpClass', 'test_something', 'tearDownClass', 'tearDownModule'] self.assertEqual(ordering, expectedOrder) def test_suite_debug_propagates_exceptions(self): class Module(object): @staticmethod def setUpModule(): if phase == 0: raise Exception('setUpModule') @staticmethod def tearDownModule(): if phase == 1: raise Exception('tearDownModule') class Test(unittest.TestCase): @classmethod def setUpClass(cls): if phase == 2: raise Exception('setUpClass') @classmethod def tearDownClass(cls): if phase == 3: raise Exception('tearDownClass') def test_something(self): if phase == 4: raise Exception('test_something') Test.__module__ = 'Module' sys.modules['Module'] = Module _suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test) suite = unittest.TestSuite() suite.addTest(_suite) messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something') for phase, msg in enumerate(messages): with self.assertRaisesRegexp(Exception, msg): suite.debug() if __name__ == '__main__': unittest.main() PK!\pqqtest/test_setups.pycnu[ |fc@sgddlZddlmZddlZdZdejfdYZedkrcejndS(iN(tStringIOcGs tjS(N(tunittestt TestResult(t_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt resultFactoryst TestSetupscBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZRS(cCstjdtdtS(Nt resultclasststream(RtTextTestRunnerRR(tself((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt getRunnerscGstj}x-|D]%}tjj|}|j|qW|j}tj}|j||jtj|jtj|j|S(N(Rt TestSuitetdefaultTestLoadertloadTestsFromTestCasetaddTestsR taddTesttrun(R tcasestsuitetcasetteststrunnert realSuite((s1/usr/lib64/python2.7/unittest/test/test_setups.pytrunTestss     csqdtjffdY|j}|jjd|j|jd|jt|jddS(NtTestcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(t setUpCalledRtTestCaset setUpClass(tcls(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR$scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_one(scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_two*s(t__name__t __module__Rt classmethodRRR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR"s iii(RRRt assertEqualRttestsRuntlenterrors(R tresult((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_setup_class!s  csqdtjffdY|j}|jjd|j|jd|jt|jddS(NRcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(ttearDownCalledRRt tearDownClass(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)6scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR:scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR<s(RR R(R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR4s iii(RRRR"R(R#R$R%(R R&((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_class3s  csdtjffdYdtjffdY|j}|jjd|jjd|j|jd|jt|jddS(NRcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(R(RRR)(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)HscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRLscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRNs(RR R(R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs tTest2cs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(R(RRR)(R(R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)SscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRWscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRYs(RR R(R!R)RR((R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+Qs iii(RRRR"R(R#R$R%(R R&((RR+s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_class_two_classesEs  cCsdtjfdY}|j|}|j|jd|jt|jd|jd\}}|jt|dtdS(Nt BrokenTestcBs)eZedZdZdZRS(cSstddS(Ntfoo(t TypeError(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRescSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRhscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRjs(RR R!RRR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR-ds iissetUpClass (%s.BrokenTest)( RRRR"R#R$R%tstrR(R R-R&terrorR((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_setupclasscs csdtjffdYdtjffdY|j}|j|jd|jt|jd|jjd|jjd|jd\}}|jt|d t dS( NRcs5eZdZefdZdZdZRS(icsjd7_tddS(NiR.(ttornDownR/(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)xscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR|scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR~s(RR R3R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRvs R+cs5eZdZefdZdZdZRS(icsjd7_tddS(NiR.(R3R/(R(R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR R3R!R)RR((R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+s iiiistearDownClass (%s.Test)( RRRR"R#R$R%R3R0R(R R&R1R((RR+s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_teardown_classus  cs@dtjffdY|j|jjdS(NRcs;eZeZedZefdZdZRS(cSs tdS(N(R/(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscst_tddS(NR.(tTrueR3R/(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)s cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR tFalseR3R!RR)R((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RRRt assertFalseR3(R ((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyt(test_class_not_torndown_when_setup_failss csedtjffdYtjd|j|jj|jjdS(NRcsGeZeZeZefdZefdZdZRS(cs t_dS(N(R5t classSetUp(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscs t_dS(N(R5R3(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs( RR R6R9R3R!RR)R((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs thop(RRtskipRR7R9R3(R ((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyt-test_class_not_setup_or_torndown_when_skippeds   cs gdtffdY}dtffdY}dtjffdY}dtjffdY}d tjffd Y}d |_|_d|_|tjd <|tjd((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttearDownModules(RR t staticmethodR@RA((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR=stModule2cs2eZefdZefdZRS(csjddS(NsModule2.setUpModule(R>((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@scsjddS(NsModule2.tearDownModule(R>((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAs(RR RBR@RA((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRCstTest1csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 1(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 1(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test1.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttestOnescsjddS(Ns Test1.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttestTwos(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRDsR+csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 2(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 2(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test2.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyREscsjddS(Ns Test2.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+stTest3csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 3(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 3(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test3.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyREscsjddS(Ns Test3.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRGstModuleRERFiisModule1.setUpModulessetup 1s Test1.testOnes Test1.testTwos teardown 1ssetup 2s Test2.testOnes Test2.testTwos teardown 2sModule1.tearDownModulesModule2.setUpModulessetup 3s Test3.testOnes Test3.testTwos teardown 3sModule2.tearDownModule( tobjectRRR tsystmodulesR R RR"R#R$R%(R R=RCRDR+RGtfirsttsecondtthirdtfourthtfifthtsixthRRR&((R?s1/usr/lib64/python2.7/unittest/test/test_setups.pyt1test_setup_teardown_order_with_pathological_suites:      !    csdtffdYdtjfdY}d|_tjd<|j|}|jjd|j|j d|jt |j ddS(NRHcs#eZdZefdZRS(icsjd7_dS(Ni(t moduleSetup((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@ s(RR RSRBR@((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRH sRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs iii( RIRRR RJRKRR"RSR#R$R%(R RR&((RHs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_setup_module s  cs$dtffdYdtjffdYdtjfdY}d_d|_tjd<|j|}|jjd|jj d|j|j d|j j |j j |jt|jd|jd\}}|jt|d dS( NRHcs>eZdZdZefdZefdZRS(icsjd7_tddS(NiR.(RSR/((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@"scsjd7_dS(Ni(tmoduleTornDown((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRA&s(RR RSRURBR@RA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsRcsPeZeZeZefdZefdZdZdZ RS(cs t_dS(N(R5R9(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR-scs t_dS(N(R5t classTornDown(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)0scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR3scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR5s( RR R6R9RVR!RR)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR*s  R+cBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR9scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR;s(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+8s iissetUpModule (Module)(RIRRR RJRKRR"RSRUR#R7R9RVR$R%R0(R R+R&R1R((RHRs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_setup_modules    cCs[dtjfdY}d|_tjjdd|j|}|j|j ddS(NRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRMscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyROs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRLs RHi( RRR RJRKtpoptNoneRR"R#(R RR&((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt!test_testcase_with_missing_moduleKs  csdtffdYdtjfdY}d|_tjd<|j|}|jjd|j|j d|jt |j ddS(NRHcs#eZdZefdZRS(icsjd7_dS(Ni(RU((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAZs(RR RURBRA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHXsRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR_scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRas(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR^s iii( RIRRR RJRKRR"RUR#R$R%(R RR&((RHs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_moduleWs  csdtffdYdtjffdYdtjfdY}d_d|_tjd<|j|}|jjd|j|j d|j j |j j |jt |jd|jd \}}|jt|d dS( NRHcs#eZdZefdZRS(icsjd7_tddS(NiR.(RUR/((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAns(RR RURBRA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHlsRcsPeZeZeZefdZefdZdZdZ RS(cs t_dS(N(R5R9(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRvscs t_dS(N(R5RV(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)yscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR|scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR~s( RR R6R9RVR!RR)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRss  R+cBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+s iiistearDownModule (Module)(RIRRR RJRKRR"RUR#t assertTrueR9RVR$R%R0(R R+R&R1R((RHRs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_teardown_moduleks   cCsdtjfdY}|j|}|j|jd|jt|jd|jt|jd|jdd}|jt|dt dS(NRcBs)eZedZdZdZRS(cSstjddS(NR.(RtSkipTest(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR R!RRR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs iissetUpClass (%s.Test)( RRRR"R#R$R%tskippedR0R(R RR&R_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_skiptest_in_setupclasss cCsdtjfdY}dtfdY}d|_|tjd<|j|}|j|jd|jt |j d|jt |j d|j dd}|jt |ddS(NRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs RHcBseZedZRS(cSstjddS(NR.(RR^(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@s(RR RBR@(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsiissetUpModule (Module)( RRRIR RJRKRR"R#R$R%R_R0(R RRHR&R_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_skiptest_in_setupmodules  csgdtffdY}dtjffdY}d|_|tjd((tordering(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@scsjddS(NRA(R>((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAs(RR RBR@RA((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsRcsAeZefdZefdZfdZRS(csjddS(NR(R>(R(Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(NR)(R>(R(Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Nttest_something(R>(R (Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRcs(RR R!RR)Rc((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRsR@RRcR)RA( RIRRR RJRKR R tdebugR"(R RHRRt expectedOrder((Rbs1/usr/lib64/python2.7/unittest/test/test_setups.pyt.test_suite_debug_executes_setups_and_teardownss   csdtffdY}dtjffdY}d|_|tjds    PK!\pqqtest/test_setups.pyonu[ |fc@sgddlZddlmZddlZdZdejfdYZedkrcejndS(iN(tStringIOcGs tjS(N(tunittestt TestResult(t_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt resultFactoryst TestSetupscBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZRS(cCstjdtdtS(Nt resultclasststream(RtTextTestRunnerRR(tself((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt getRunnerscGstj}x-|D]%}tjj|}|j|qW|j}tj}|j||jtj|jtj|j|S(N(Rt TestSuitetdefaultTestLoadertloadTestsFromTestCasetaddTestsR taddTesttrun(R tcasestsuitetcasetteststrunnert realSuite((s1/usr/lib64/python2.7/unittest/test/test_setups.pytrunTestss     csqdtjffdY|j}|jjd|j|jd|jt|jddS(NtTestcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(t setUpCalledRtTestCaset setUpClass(tcls(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR$scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_one(scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_two*s(t__name__t __module__Rt classmethodRRR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR"s iii(RRRt assertEqualRttestsRuntlenterrors(R tresult((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_setup_class!s  csqdtjffdY|j}|jjd|j|jd|jt|jddS(NRcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(ttearDownCalledRRt tearDownClass(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)6scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR:scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR<s(RR R(R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR4s iii(RRRR"R(R#R$R%(R R&((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_class3s  csdtjffdYdtjffdY|j}|jjd|jjd|j|jd|jt|jddS(NRcs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(R(RRR)(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)HscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRLscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRNs(RR R(R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs tTest2cs5eZdZefdZdZdZRS(ics jd7_tjjdS(Ni(R(RRR)(R(R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)SscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRWscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRYs(RR R(R!R)RR((R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+Qs iii(RRRR"R(R#R$R%(R R&((RR+s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_class_two_classesEs  cCsdtjfdY}|j|}|j|jd|jt|jd|jd\}}|jt|dtdS(Nt BrokenTestcBs)eZedZdZdZRS(cSstddS(Ntfoo(t TypeError(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRescSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRhscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRjs(RR R!RRR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR-ds iissetUpClass (%s.BrokenTest)( RRRR"R#R$R%tstrR(R R-R&terrorR((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_setupclasscs csdtjffdYdtjffdY|j}|j|jd|jt|jd|jjd|jjd|jd\}}|jt|d t dS( NRcs5eZdZefdZdZdZRS(icsjd7_tddS(NiR.(ttornDownR/(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)xscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR|scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR~s(RR R3R!R)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRvs R+cs5eZdZefdZdZdZRS(icsjd7_tddS(NiR.(R3R/(R(R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR R3R!R)RR((R+(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+s iiiistearDownClass (%s.Test)( RRRR"R#R$R%R3R0R(R R&R1R((RR+s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_teardown_classus  cs@dtjffdY|j|jjdS(NRcs;eZeZedZefdZdZRS(cSs tdS(N(R/(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscst_tddS(NR.(tTrueR3R/(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)s cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR tFalseR3R!RR)R((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RRRt assertFalseR3(R ((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyt(test_class_not_torndown_when_setup_failss csedtjffdYtjd|j|jj|jjdS(NRcsGeZeZeZefdZefdZdZRS(cs t_dS(N(R5t classSetUp(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscs t_dS(N(R5R3(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs( RR R6R9R3R!RR)R((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs thop(RRtskipRR7R9R3(R ((Rs1/usr/lib64/python2.7/unittest/test/test_setups.pyt-test_class_not_setup_or_torndown_when_skippeds   cs gdtffdY}dtffdY}dtjffdY}dtjffdY}d tjffd Y}d |_|_d|_|tjd <|tjd((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttearDownModules(RR t staticmethodR@RA((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR=stModule2cs2eZefdZefdZRS(csjddS(NsModule2.setUpModule(R>((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@scsjddS(NsModule2.tearDownModule(R>((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAs(RR RBR@RA((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRCstTest1csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 1(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 1(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test1.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttestOnescsjddS(Ns Test1.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyttestTwos(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRDsR+csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 2(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 2(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test2.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyREscsjddS(Ns Test2.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+stTest3csPeZefdZefdZfdZfdZRS(csjddS(Nssetup 3(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(Ns teardown 3(R>(R(R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Ns Test3.testOne(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyREscsjddS(Ns Test3.testTwo(R>(R (R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRFs(RR R!RR)RERF((R?(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRGstModuleRERFiisModule1.setUpModulessetup 1s Test1.testOnes Test1.testTwos teardown 1ssetup 2s Test2.testOnes Test2.testTwos teardown 2sModule1.tearDownModulesModule2.setUpModulessetup 3s Test3.testOnes Test3.testTwos teardown 3sModule2.tearDownModule( tobjectRRR tsystmodulesR R RR"R#R$R%(R R=RCRDR+RGtfirsttsecondtthirdtfourthtfifthtsixthRRR&((R?s1/usr/lib64/python2.7/unittest/test/test_setups.pyt1test_setup_teardown_order_with_pathological_suites:      !    csdtffdYdtjfdY}d|_tjd<|j|}|jjd|j|j d|jt |j ddS(NRHcs#eZdZefdZRS(icsjd7_dS(Ni(t moduleSetup((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@ s(RR RSRBR@((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRH sRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs iii( RIRRR RJRKRR"RSR#R$R%(R RR&((RHs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_setup_module s  cs$dtffdYdtjffdYdtjfdY}d_d|_tjd<|j|}|jjd|jj d|j|j d|j j |j j |jt|jd|jd\}}|jt|d dS( NRHcs>eZdZdZefdZefdZRS(icsjd7_tddS(NiR.(RSR/((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@"scsjd7_dS(Ni(tmoduleTornDown((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRA&s(RR RSRURBR@RA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsRcsPeZeZeZefdZefdZdZdZ RS(cs t_dS(N(R5R9(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR-scs t_dS(N(R5t classTornDown(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)0scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR3scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR5s( RR R6R9RVR!RR)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR*s  R+cBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR9scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR;s(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+8s iissetUpModule (Module)(RIRRR RJRKRR"RSRUR#R7R9RVR$R%R0(R R+R&R1R((RHRs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_setup_modules    cCs[dtjfdY}d|_tjjdd|j|}|j|j ddS(NRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRMscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyROs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRLs RHi( RRR RJRKtpoptNoneRR"R#(R RR&((s1/usr/lib64/python2.7/unittest/test/test_setups.pyt!test_testcase_with_missing_moduleKs  csdtffdYdtjfdY}d|_tjd<|j|}|jjd|j|j d|jt |j ddS(NRHcs#eZdZefdZRS(icsjd7_dS(Ni(RU((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAZs(RR RURBRA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHXsRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR_scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRas(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR^s iii( RIRRR RJRKRR"RUR#R$R%(R RR&((RHs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_teardown_moduleWs  csdtffdYdtjffdYdtjfdY}d_d|_tjd<|j|}|jjd|j|j d|j j |j j |jt |jd|jd \}}|jt|d dS( NRHcs#eZdZefdZRS(icsjd7_tddS(NiR.(RUR/((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAns(RR RURBRA((RH(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHlsRcsPeZeZeZefdZefdZdZdZ RS(cs t_dS(N(R5R9(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRvscs t_dS(N(R5RV(R(R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)yscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR|scSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR~s( RR R6R9RVR!RR)RR((R(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRss  R+cBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR+s iiistearDownModule (Module)(RIRRR RJRKRR"RUR#t assertTrueR9RVR$R%R0(R R+R&R1R((RHRs1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_error_in_teardown_moduleks   cCsdtjfdY}|j|}|j|jd|jt|jd|jt|jd|jdd}|jt|dt dS(NRcBs)eZedZdZdZRS(cSstjddS(NR.(RtSkipTest(R((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR R!RRR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs iissetUpClass (%s.Test)( RRRR"R#R$R%tskippedR0R(R RR&R_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_skiptest_in_setupclasss cCsdtjfdY}dtfdY}d|_|tjd<|j|}|j|jd|jt |j d|jt |j d|j dd}|jt |ddS(NRcBseZdZdZRS(cSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscSsdS(N((R ((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs(RR RR(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRs RHcBseZedZRS(cSstjddS(NR.(RR^(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@s(RR RBR@(((s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsiissetUpModule (Module)( RRRIR RJRKRR"R#R$R%R_R0(R RRHR&R_((s1/usr/lib64/python2.7/unittest/test/test_setups.pyttest_skiptest_in_setupmodules  csgdtffdY}dtjffdY}d|_|tjd((tordering(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR@scsjddS(NRA(R>((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRAs(RR RBR@RA((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRHsRcsAeZefdZefdZfdZRS(csjddS(NR(R>(R(Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRscsjddS(NR)(R>(R(Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyR)scsjddS(Nttest_something(R>(R (Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRcs(RR R!RR)Rc((Rb(s1/usr/lib64/python2.7/unittest/test/test_setups.pyRsR@RRcR)RA( RIRRR RJRKR R tdebugR"(R RHRRt expectedOrder((Rbs1/usr/lib64/python2.7/unittest/test/test_setups.pyt.test_suite_debug_executes_setups_and_teardownss   csdtffdY}dtjffdY}d|_|tjds    PK!4}pptest/test_skipping.pynu[import unittest from unittest.test.support import LoggingResult class Test_TestSkipping(unittest.TestCase): def test_skipping(self): class Foo(unittest.TestCase): def test_skip_me(self): self.skipTest("skip") events = [] result = LoggingResult(events) test = Foo("test_skip_me") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "skip")]) # Try letting setUp skip the test now. class Foo(unittest.TestCase): def setUp(self): self.skipTest("testing") def test_nothing(self): pass events = [] result = LoggingResult(events) test = Foo("test_nothing") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(result.testsRun, 1) def test_skipping_decorators(self): op_table = ((unittest.skipUnless, False, True), (unittest.skipIf, True, False)) for deco, do_skip, dont_skip in op_table: class Foo(unittest.TestCase): @deco(do_skip, "testing") def test_skip(self): pass @deco(dont_skip, "testing") def test_dont_skip(self): pass test_do_skip = Foo("test_skip") test_dont_skip = Foo("test_dont_skip") suite = unittest.TestSuite([test_do_skip, test_dont_skip]) events = [] result = LoggingResult(events) suite.run(result) self.assertEqual(len(result.skipped), 1) expected = ['startTest', 'addSkip', 'stopTest', 'startTest', 'addSuccess', 'stopTest'] self.assertEqual(events, expected) self.assertEqual(result.testsRun, 2) self.assertEqual(result.skipped, [(test_do_skip, "testing")]) self.assertTrue(result.wasSuccessful()) def test_skip_class(self): @unittest.skip("testing") class Foo(unittest.TestCase): def test_1(self): record.append(1) record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_skip_non_unittest_class_old_style(self): @unittest.skip("testing") class Mixin: def test_1(self): record.append(1) class Foo(Mixin, unittest.TestCase): pass record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_skip_non_unittest_class_new_style(self): @unittest.skip("testing") class Mixin(object): def test_1(self): record.append(1) class Foo(Mixin, unittest.TestCase): pass record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_expected_failure(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): self.fail("help me!") events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addExpectedFailure', 'stopTest']) self.assertEqual(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_unexpected_success(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): pass events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addUnexpectedSuccess', 'stopTest']) self.assertFalse(result.failures) self.assertEqual(result.unexpectedSuccesses, [test]) self.assertTrue(result.wasSuccessful()) def test_skip_doesnt_run_setup(self): class Foo(unittest.TestCase): wasSetUp = False wasTornDown = False def setUp(self): Foo.wasSetUp = True def tornDown(self): Foo.wasTornDown = True @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertFalse(Foo.wasSetUp) self.assertFalse(Foo.wasTornDown) def test_decorated_skip(self): def decorator(func): def inner(*a): return func(*a) return inner class Foo(unittest.TestCase): @decorator @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) if __name__ == '__main__': unittest.main() PK!+%%test/test_skipping.pycnu[ |fc@sRddlZddlmZdejfdYZedkrNejndS(iN(t LoggingResulttTest_TestSkippingcBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCs dtjfdY}g}t|}|d}|j||j|dddg|j|j|dfgdtjfdY}g}t|}|d }|j||j|dddg|j|j|d fg|j|jd dS( NtFoocBseZdZRS(cSs|jddS(Ntskip(tskipTest(tself((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skip_me s(t__name__t __module__R(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR sRt startTesttaddSkiptstopTestRcBseZdZdZRS(cSs|jddS(Nttesting(R(R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pytsetUpscSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_nothingt(RRR R(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs RR i(tunittesttTestCaseRtrunt assertEqualtskippedttestsRun(RRteventstresultttest((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skippings      c s6tjttftjttff}x |D]\dtjffdY}|d}|d}tj||g}g}t|}|j||j t |j dddddd dg}|j |||j |j d |j |j |d fg|j |jq+WdS( NRcs8eZddZddZRS(R cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skip%scSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_dont_skip(s(RRRR((tdecotdo_skipt dont_skip(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR$sRRiR R R t addSuccessiR (Rt skipUnlesstFalsetTruetskipIfRt TestSuiteRRRtlenRRt assertTruet wasSuccessful( Rtop_tableRt test_do_skipRtsuiteRRtexpected((RRRs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skipping_decorators s"%     cstjddtjffdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR RcseZfdZRS(csjddS(Ni(tappend(R(trecord(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_1;s(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR9sR/(RRRt TestResultR$RRR(RRRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skip_class8s   cstjdddfdY}d|tjfdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR tMixincseZfdZRS(csjddS(Ni(R-(R(R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/Hs(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR2FsRcBseZRS((RR(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRJsR/((RRRR0R$RRR(RR2RRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt&test_skip_non_unittest_class_old_styleEs(   cstjddtffdY}d|tjfdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR R2cseZfdZRS(csjddS(Ni(R-(R(R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/Ws(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR2UsRcBseZRS((RR(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRYsR/( RRtobjectRR0R$RRR(RR2RRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt&test_skip_non_unittest_class_new_styleTs   cCsdtjfdY}g}t|}|d}|j||j|dddg|j|jdd||j|jdS(NRcBseZejdZRS(cSs|jddS(Nshelp me!(tfail(R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_diees(RRRtexpectedFailureR7(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRdsR7R taddExpectedFailureR i(RRRRRtexpectedFailuresR&R'(RRRRR((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_expected_failurecs    cCsdtjfdY}g}t|}|d}|j||j|dddg|j|j|j|j|g|j|j dS(NRcBseZejdZRS(cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR7ss(RRRR8R7(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRrsR7R taddUnexpectedSuccessR ( RRRRRt assertFalsetfailurestunexpectedSuccessesR&R'(RRRRR((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_unexpected_successqs    csdtjffdYtj}d}tj|g}|j||j|j|dfg|jj|jj dS(NRcsJeZeZeZfdZfdZejddZ RS(cs t_dS(N(R"twasSetUp(R(R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR scs t_dS(N(R"t wasTornDown(R(R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttornDownsR cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/s( RRR!RARBR RCRRR/((R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs R/R ( RRR0R$RRRR=RARB(RRRR*((Rs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skip_doesnt_run_setups   csddtjffdY}tj}|d}tj|g}|j||j|j|dfgdS(Ncsfd}|S(Ncs |S(N((ta(tfunc(s3/usr/lib64/python2.7/unittest/test/test_skipping.pytinners((RFRG((RFs3/usr/lib64/python2.7/unittest/test/test_skipping.pyt decoratorsRcs&eZejddZRS(R cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/s(RRRRR/((RH(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRsR/R (RRR0R$RRR(RRRRR*((RHs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_decorated_skips    ( RRRR,R1R3R5R;R@RDRI(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs       t__main__(Rtunittest.test.supportRRRRtmain(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyts  PK!+%%test/test_skipping.pyonu[ |fc@sRddlZddlmZdejfdYZedkrNejndS(iN(t LoggingResulttTest_TestSkippingcBsYeZdZdZdZdZdZdZdZdZ dZ RS( cCs dtjfdY}g}t|}|d}|j||j|dddg|j|j|dfgdtjfdY}g}t|}|d }|j||j|dddg|j|j|d fg|j|jd dS( NtFoocBseZdZRS(cSs|jddS(Ntskip(tskipTest(tself((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skip_me s(t__name__t __module__R(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR sRt startTesttaddSkiptstopTestRcBseZdZdZRS(cSs|jddS(Nttesting(R(R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pytsetUpscSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_nothingt(RRR R(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs RR i(tunittesttTestCaseRtrunt assertEqualtskippedttestsRun(RRteventstresultttest((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skippings      c s6tjttftjttff}x |D]\dtjffdY}|d}|d}tj||g}g}t|}|j||j t |j dddddd dg}|j |||j |j d |j |j |d fg|j |jq+WdS( NRcs8eZddZddZRS(R cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt test_skip%scSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_dont_skip(s(RRRR((tdecotdo_skipt dont_skip(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR$sRRiR R R t addSuccessiR (Rt skipUnlesstFalsetTruetskipIfRt TestSuiteRRRtlenRRt assertTruet wasSuccessful( Rtop_tableRt test_do_skipRtsuiteRRtexpected((RRRs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skipping_decorators s"%     cstjddtjffdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR RcseZfdZRS(csjddS(Ni(tappend(R(trecord(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_1;s(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR9sR/(RRRt TestResultR$RRR(RRRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skip_class8s   cstjdddfdY}d|tjfdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR tMixincseZfdZRS(csjddS(Ni(R-(R(R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/Hs(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR2FsRcBseZRS((RR(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRJsR/((RRRR0R$RRR(RR2RRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt&test_skip_non_unittest_class_old_styleEs(   cstjddtffdY}d|tjfdY}gtj}|d}tj|g}|j||j|j|dfg|jgdS(NR R2cseZfdZRS(csjddS(Ni(R-(R(R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/Ws(RRR/((R.(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR2UsRcBseZRS((RR(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRYsR/( RRtobjectRR0R$RRR(RR2RRRR*((R.s3/usr/lib64/python2.7/unittest/test/test_skipping.pyt&test_skip_non_unittest_class_new_styleTs   cCsdtjfdY}g}t|}|d}|j||j|dddg|j|jdd||j|jdS(NRcBseZejdZRS(cSs|jddS(Nshelp me!(tfail(R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_diees(RRRtexpectedFailureR7(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRdsR7R taddExpectedFailureR i(RRRRRtexpectedFailuresR&R'(RRRRR((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_expected_failurecs    cCsdtjfdY}g}t|}|d}|j||j|dddg|j|j|j|j|g|j|j dS(NRcBseZejdZRS(cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR7ss(RRRR8R7(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRrsR7R taddUnexpectedSuccessR ( RRRRRt assertFalsetfailurestunexpectedSuccessesR&R'(RRRRR((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_unexpected_successqs    csdtjffdYtj}d}tj|g}|j||j|j|dfg|jj|jj dS(NRcsJeZeZeZfdZfdZejddZ RS(cs t_dS(N(R"twasSetUp(R(R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR scs t_dS(N(R"t wasTornDown(R(R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyttornDownsR cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/s( RRR!RARBR RCRRR/((R(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs R/R ( RRR0R$RRRR=RARB(RRRR*((Rs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_skip_doesnt_run_setups   csddtjffdY}tj}|d}tj|g}|j||j|j|dfgdS(Ncsfd}|S(Ncs |S(N((ta(tfunc(s3/usr/lib64/python2.7/unittest/test/test_skipping.pytinners((RFRG((RFs3/usr/lib64/python2.7/unittest/test/test_skipping.pyt decoratorsRcs&eZejddZRS(R cSsdS(N((R((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyR/s(RRRRR/((RH(s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRsR/R (RRR0R$RRR(RRRRR*((RHs3/usr/lib64/python2.7/unittest/test/test_skipping.pyttest_decorated_skips    ( RRRR,R1R3R5R;R@RDRI(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyRs       t__main__(Rtunittest.test.supportRRRRtmain(((s3/usr/lib64/python2.7/unittest/test/test_skipping.pyts  PK!M;E,2/2/test/test_suite.pynu[import unittest import sys from unittest.test.support import LoggingResult, TestEquality ### Support code for Test_TestSuite ################################################################ class Test(object): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def test_3(self): pass def runTest(self): pass def _mk_TestSuite(*names): return unittest.TestSuite(Test.Foo(n) for n in names) ################################################################ class Test_TestSuite(unittest.TestCase, TestEquality): ### Set up attributes needed by inherited tests ################################################################ # Used by TestEquality.test_eq eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()), (unittest.TestSuite(), unittest.TestSuite([])), (_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] # Used by TestEquality.test_ne ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')), (unittest.TestSuite([]), _mk_TestSuite('test_1')), (_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')), (_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] ################################################################ ### /Set up attributes needed by inherited tests ### Tests for TestSuite.__init__ ################################################################ # "class TestSuite([tests])" # # The tests iterable should be optional def test_init__tests_optional(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should deal with empty tests iterables by allowing the # creation of an empty suite def test_init__empty_tests(self): suite = unittest.TestSuite([]) self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should allow any iterable to provide tests def test_init__tests_from_any_iterable(self): def tests(): yield unittest.FunctionTestCase(lambda: None) yield unittest.FunctionTestCase(lambda: None) suite_1 = unittest.TestSuite(tests()) self.assertEqual(suite_1.countTestCases(), 2) suite_2 = unittest.TestSuite(suite_1) self.assertEqual(suite_2.countTestCases(), 2) suite_3 = unittest.TestSuite(set(suite_1)) self.assertEqual(suite_3.countTestCases(), 2) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # Does TestSuite() also allow other TestSuite() instances to be present # in the tests iterable? def test_init__TestSuite_instances_in_tests(self): def tests(): ftc = unittest.FunctionTestCase(lambda: None) yield unittest.TestSuite([ftc]) yield unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite(tests()) self.assertEqual(suite.countTestCases(), 2) ################################################################ ### /Tests for TestSuite.__init__ # Container types should support the iter protocol def test_iter(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(list(suite), [test1, test2]) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite returns 0? def test_countTestCases_zero_simple(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite (even if it contains other empty # TestSuite instances) returns 0? def test_countTestCases_zero_nested(self): class Test1(unittest.TestCase): def test(self): pass suite = unittest.TestSuite([unittest.TestSuite()]) self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" def test_countTestCases_simple(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(suite.countTestCases(), 2) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Make sure this holds for nested TestSuite instances, too def test_countTestCases_nested(self): class Test1(unittest.TestCase): def test1(self): pass def test2(self): pass test2 = unittest.FunctionTestCase(lambda: None) test3 = unittest.FunctionTestCase(lambda: None) child = unittest.TestSuite((Test1('test2'), test2)) parent = unittest.TestSuite((test3, child, Test1('test1'))) self.assertEqual(parent.countTestCases(), 4) # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." # # And if there are no tests? What then? def test_run__empty_suite(self): events = [] result = LoggingResult(events) suite = unittest.TestSuite() suite.run(result) self.assertEqual(events, []) # "Note that unlike TestCase.run(), TestSuite.run() requires the # "result object to be passed in." def test_run__requires_result(self): suite = unittest.TestSuite() try: suite.run() except TypeError: pass else: self.fail("Failed to raise TypeError") # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." def test_run(self): events = [] result = LoggingResult(events) class LoggingCase(unittest.TestCase): def run(self, result): events.append('run %s' % self._testMethodName) def test1(self): pass def test2(self): pass tests = [LoggingCase('test1'), LoggingCase('test2')] unittest.TestSuite(tests).run(result) self.assertEqual(events, ['run test1', 'run test2']) # "Add a TestCase ... to the suite" def test_addTest__TestCase(self): class Foo(unittest.TestCase): def test(self): pass test = Foo('test') suite = unittest.TestSuite() suite.addTest(test) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [test]) # "Add a ... TestSuite to the suite" def test_addTest__TestSuite(self): class Foo(unittest.TestCase): def test(self): pass suite_2 = unittest.TestSuite([Foo('test')]) suite = unittest.TestSuite() suite.addTest(suite_2) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [suite_2]) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # "This is equivalent to iterating over tests, calling addTest() for # each element" def test_addTests(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass test_1 = Foo('test_1') test_2 = Foo('test_2') inner_suite = unittest.TestSuite([test_2]) def gen(): yield test_1 yield test_2 yield inner_suite suite_1 = unittest.TestSuite() suite_1.addTests(gen()) self.assertEqual(list(suite_1), list(gen())) # "This is equivalent to iterating over tests, calling addTest() for # each element" suite_2 = unittest.TestSuite() for t in gen(): suite_2.addTest(t) self.assertEqual(suite_1, suite_2) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # What happens if it doesn't get an iterable? def test_addTest__noniterable(self): suite = unittest.TestSuite() try: suite.addTests(5) except TypeError: pass else: self.fail("Failed to raise TypeError") def test_addTest__noncallable(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, 5) def test_addTest__casesuiteclass(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, Test_TestSuite) self.assertRaises(TypeError, suite.addTest, unittest.TestSuite) def test_addTests__string(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") def test_function_in_suite(self): def f(_): pass suite = unittest.TestSuite() suite.addTest(f) # when the bug is fixed this line will not crash suite.run(unittest.TestResult()) def test_basetestsuite(self): class Test(unittest.TestCase): wasSetUp = False wasTornDown = False @classmethod def setUpClass(cls): cls.wasSetUp = True @classmethod def tearDownClass(cls): cls.wasTornDown = True def testPass(self): pass def testFail(self): fail class Module(object): wasSetUp = False wasTornDown = False @staticmethod def setUpModule(): Module.wasSetUp = True @staticmethod def tearDownModule(): Module.wasTornDown = True Test.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.BaseTestSuite() suite.addTests([Test('testPass'), Test('testFail')]) self.assertEqual(suite.countTestCases(), 2) result = unittest.TestResult() suite.run(result) self.assertFalse(Module.wasSetUp) self.assertFalse(Module.wasTornDown) self.assertFalse(Test.wasSetUp) self.assertFalse(Test.wasTornDown) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 2) def test_overriding_call(self): class MySuite(unittest.TestSuite): called = False def __call__(self, *args, **kw): self.called = True unittest.TestSuite.__call__(self, *args, **kw) suite = MySuite() result = unittest.TestResult() wrapper = unittest.TestSuite() wrapper.addTest(suite) wrapper(result) self.assertTrue(suite.called) # reusing results should be permitted even if abominable self.assertFalse(result._testRunEntered) if __name__ == '__main__': unittest.main() PK!S.#Ď<<test/test_suite.pyonu[ |fc@sddlZddlZddlmZmZdefdYZdZdejefdYZ e dkrej ndS( iN(t LoggingResultt TestEqualitytTestcBs!eZdejfdYZRS(tFoocBs,eZdZdZdZdZRS(cCsdS(N((tself((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_1 tcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_2 RcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_3RcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pytrunTestR(t__name__t __module__RRRR (((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR s   (R R tunittesttTestCaseR(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR scGstjd|DS(Ncss|]}tj|VqdS(N(RR(t.0tn((s0/usr/lib64/python2.7/unittest/test/test_suite.pys s(R t TestSuite(tnames((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt _mk_TestSuitestTest_TestSuitecBsyeZejejfejejgfededfgZejedfejgedfeddeddfededfgZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZRS(RRRcCs&tj}|j|jddS(Ni(R Rt assertEqualtcountTestCases(Rtsuite((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_init__tests_optional0s cCs)tjg}|j|jddS(Ni(R RRR(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_init__empty_tests<scCsd}tj|}|j|jdtj|}|j|jdtjt|}|j|jddS(Ncss&tjdVtjdVdS(NcSsdS(N(tNone(((s0/usr/lib64/python2.7/unittest/test/test_suite.pytIRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRJR(R tFunctionTestCase(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestsHsi(R RRRtset(RRtsuite_1tsuite_2tsuite_3((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt"test_init__tests_from_any_iterableGs cCs5d}tj|}|j|jddS(Ncss8tjd}tj|gVtjdVdS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR^RcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR`R(R RR(tftc((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR]si(R RRR(RRR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt'test_init__TestSuite_instances_in_tests\s cCsYtjd}tjd}tj||f}|jt|||gdS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRjRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRkR(R RRRtlist(Rttest1ttest2R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt test_iteriscCs&tj}|j|jddS(Ni(R RRR(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_zero_simpleus cCsKdtjfdY}tjtjg}|j|jddS(NtTest1cBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttests(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR)si(R R RRR(RR)R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_zero_nestedscCsStjd}tjd}tj||f}|j|jddS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRi(R RRRR(RR%R&R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_simplescCsdtjfdY}tjd}tjd}tj|d|f}tj|||df}|j|jddS(NR)cBseZdZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR%RcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR&R(R R R%R&(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR)s cSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRR&R%i(R R RRRR(RR)R&ttest3tchildtparent((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_nesteds cCs?g}t|}tj}|j||j|gdS(N(RR RtrunR(RteventstresultR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_run__empty_suites    cCs?tj}y|jWntk r-nX|jddS(NsFailed to raise TypeError(R RR1t TypeErrortfail(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_run__requires_results   csygt}dtjffdY}|d|dg}tj|j||jddgdS(Nt LoggingCasecs)eZfdZdZdZRS(csjd|jdS(Nsrun %s(tappendt_testMethodName(RR3(R2(s0/usr/lib64/python2.7/unittest/test/test_suite.pyR1scSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR%RcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR&R(R R R1R%R&((R2(s0/usr/lib64/python2.7/unittest/test/test_suite.pyR8s R%R&s run test1s run test2(RR R RR1R(RR3R8R((R2s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_runs  cCsqdtjfdY}|d}tj}|j||j|jd|jt||gdS(NRcBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR*R(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRsR*i(R R RtaddTestRRR$(RRR*R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__TestCases    cCs}dtjfdY}tj|dg}tj}|j||j|jd|jt||gdS(NRcBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR*R(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRsR*i(R R RR<RRR$(RRRR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__TestSuites   csdtjfdY}|d|dtjgfd}tj}|j||jt|t|tj}x|D]}|j|qW|j||dS(NRcBseZdZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRR(R R RR(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRs RRc3sVVVdS(N(((t inner_suiteRR(s0/usr/lib64/python2.7/unittest/test/test_suite.pytgens(R R RtaddTestsRR$R<(RRR@RRtt((R?RRs0/usr/lib64/python2.7/unittest/test/test_suite.pyt test_addTestss    cCsBtj}y|jdWntk r0nX|jddS(NisFailed to raise TypeError(R RRAR5R6(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__noniterables   cCs&tj}|jt|jddS(Ni(R Rt assertRaisesR5R<(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__noncallables cCs?tj}|jt|jt|jt|jtjdS(N(R RRER5R<R(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__casesuiteclasss cCs&tj}|jt|jddS(Ntfoo(R RRER5RA(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTests__string"s cCs9d}tj}|j||jtjdS(NcSsdS(N((t_((s0/usr/lib64/python2.7/unittest/test/test_suite.pytf's(R RR<R1t TestResult(RRKR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_function_in_suite&s   csDdtjfdY}dtffdYd|_tjd<|jtjjdtj}|j |d|dg|j |j dtj }|j ||jj|jj|j|j|j|j|j t|jd|j t|jd |j |jddS( NRcBsDeZeZeZedZedZdZdZ RS(cSs t|_dS(N(tTruetwasSetUp(tcls((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt setUpClass5scSs t|_dS(N(RNt wasTornDown(RP((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt tearDownClass8scSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestPass;scSstdS(N(R6(R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestFail=s( R R tFalseRORRt classmethodRQRSRTRU(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR2s  tModulecs>eZeZeZefdZefdZRS(cs t_dS(N(RNRO((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyt setUpModuleBscs t_dS(N(RNRR((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyttearDownModuleEs(R R RVRORRt staticmethodRYRZ((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyRX?sRTRUiii(R R tobjectR tsystmodulest addCleanuptpopt BaseTestSuiteRARRRLR1t assertFalseRORRtlenterrorstfailuresttestsRun(RRRR3((RXs0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_basetestsuite1s"      cCsudtjfdY}|}tj}tj}|j||||j|j|j|jdS(NtMySuitecBseZeZdZRS(c_s#t|_tjj|||dS(N(RNtcalledR Rt__call__(Rtargstkw((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRj_s (R R RVRiRj(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRh]s(R RRLR<t assertTrueRiRbt_testRunEntered(RRhRR3twrapper((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_overriding_call\s     (R R R RRteq_pairstne_pairsRRR!R#R'R(R+R,R0R4R7R;R=R>RCRDRFRGRIRMRgRp(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRs:         +t__main__( R R]tunittest.test.supportRRR\RRR RR tmain(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyts   X PK!LB2test/__init__.pynu[import os import sys import unittest here = os.path.dirname(__file__) loader = unittest.defaultTestLoader def suite(): suite = unittest.TestSuite() for fn in os.listdir(here): if fn.startswith("test") and fn.endswith(".py"): modname = "unittest.test." + fn[:-3] __import__(modname) module = sys.modules[modname] suite.addTest(loader.loadTestsFromModule(module)) return suite if __name__ == "__main__": unittest.main(defaultTest="suite") PK!z#test/__init__.pycnu[ {fc@skddlZddlZddlZejjeZejZdZ e dkrgej ddndS(iNcCstj}xstjtD]b}|jdr|jdrd|d }t|tj |}|j t j |qqW|S(Nttests.pysunittest.test.i( tunittestt TestSuitetostlistdirtheret startswithtendswitht __import__tsystmodulestaddTesttloadertloadTestsFromModule(tsuitetfntmodnametmodule((s./usr/lib64/python2.7/unittest/test/__init__.pyR s   t__main__t defaultTestR( RR Rtpathtdirnamet__file__RtdefaultTestLoaderR Rt__name__tmain(((s./usr/lib64/python2.7/unittest/test/__init__.pyts     PK!z#test/__init__.pyonu[ {fc@skddlZddlZddlZejjeZejZdZ e dkrgej ddndS(iNcCstj}xstjtD]b}|jdr|jdrd|d }t|tj |}|j t j |qqW|S(Nttests.pysunittest.test.i( tunittestt TestSuitetostlistdirtheret startswithtendswitht __import__tsystmodulestaddTesttloadertloadTestsFromModule(tsuitetfntmodnametmodule((s./usr/lib64/python2.7/unittest/test/__init__.pyR s   t__main__t defaultTestR( RR Rtpathtdirnamet__file__RtdefaultTestLoaderR Rt__name__tmain(((s./usr/lib64/python2.7/unittest/test/__init__.pyts     PK!22 test/dummy.pynu[# Empty module for testing the loading of modules PK!Dtest/dummy.pycnu[ {fc@sdS(N((((s+/usr/lib64/python2.7/unittest/test/dummy.pyttPK!Dtest/dummy.pyonu[ {fc@sdS(N((((s+/usr/lib64/python2.7/unittest/test/dummy.pyttPK!r= test/support.pynu[import unittest class TestHashing(object): """Used as a mixin for TestCase""" # Check for a valid __hash__ implementation def test_hash(self): for obj_1, obj_2 in self.eq_pairs: try: if not hash(obj_1) == hash(obj_2): self.fail("%r and %r do not hash equal" % (obj_1, obj_2)) except KeyboardInterrupt: raise except Exception, e: self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e)) for obj_1, obj_2 in self.ne_pairs: try: if hash(obj_1) == hash(obj_2): self.fail("%s and %s hash equal, but shouldn't" % (obj_1, obj_2)) except KeyboardInterrupt: raise except Exception, e: self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) class TestEquality(object): """Used as a mixin for TestCase""" # Check for a valid __eq__ implementation def test_eq(self): for obj_1, obj_2 in self.eq_pairs: self.assertEqual(obj_1, obj_2) self.assertEqual(obj_2, obj_1) # Check for a valid __ne__ implementation def test_ne(self): for obj_1, obj_2 in self.ne_pairs: self.assertNotEqual(obj_1, obj_2) self.assertNotEqual(obj_2, obj_1) class LoggingResult(unittest.TestResult): def __init__(self, log): self._events = log super(LoggingResult, self).__init__() def startTest(self, test): self._events.append('startTest') super(LoggingResult, self).startTest(test) def startTestRun(self): self._events.append('startTestRun') super(LoggingResult, self).startTestRun() def stopTest(self, test): self._events.append('stopTest') super(LoggingResult, self).stopTest(test) def stopTestRun(self): self._events.append('stopTestRun') super(LoggingResult, self).stopTestRun() def addFailure(self, *args): self._events.append('addFailure') super(LoggingResult, self).addFailure(*args) def addSuccess(self, *args): self._events.append('addSuccess') super(LoggingResult, self).addSuccess(*args) def addError(self, *args): self._events.append('addError') super(LoggingResult, self).addError(*args) def addSkip(self, *args): self._events.append('addSkip') super(LoggingResult, self).addSkip(*args) def addExpectedFailure(self, *args): self._events.append('addExpectedFailure') super(LoggingResult, self).addExpectedFailure(*args) def addUnexpectedSuccess(self, *args): self._events.append('addUnexpectedSuccess') super(LoggingResult, self).addUnexpectedSuccess(*args) class ResultWithNoStartTestRunStopTestRun(object): """An object honouring TestResult before startTestRun/stopTestRun.""" def __init__(self): self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False def startTest(self, test): pass def stopTest(self, test): pass def addError(self, test): pass def addFailure(self, test): pass def addSuccess(self, test): pass def wasSuccessful(self): return True PK!%v tttest/support.pycnu[ {fc@skddlZdefdYZdefdYZdejfdYZdefd YZdS( iNt TestHashingcBseZdZdZRS(sUsed as a mixin for TestCasecCs*x|jD]\}}y6t|t|ksK|jd||fnWq tk rbq tk r}|jd|||fq Xq Wx|jD]\}}y6t|t|kr|jd||fnWqtk rqtk r!}|jd|||fqXqWdS(Ns%r and %r do not hash equalsProblem hashing %r and %r: %ss#%s and %s hash equal, but shouldn'tsProblem hashing %s and %s: %s(teq_pairsthashtfailtKeyboardInterruptt Exceptiontne_pairs(tselftobj_1tobj_2te((s-/usr/lib64/python2.7/unittest/test/support.pyt test_hashs" "  (t__name__t __module__t__doc__R (((s-/usr/lib64/python2.7/unittest/test/support.pyRst TestEqualitycBs eZdZdZdZRS(sUsed as a mixin for TestCasecCs>x7|jD],\}}|j|||j||q WdS(N(Rt assertEqual(RRR ((s-/usr/lib64/python2.7/unittest/test/support.pyttest_eq!scCs>x7|jD],\}}|j|||j||q WdS(N(RtassertNotEqual(RRR ((s-/usr/lib64/python2.7/unittest/test/support.pyttest_ne's(R R RRR(((s-/usr/lib64/python2.7/unittest/test/support.pyRs t LoggingResultcBskeZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( cCs ||_tt|jdS(N(t_eventstsuperRt__init__(Rtlog((s-/usr/lib64/python2.7/unittest/test/support.pyR.s cCs*|jjdtt|j|dS(Nt startTest(RtappendRRR(Rttest((s-/usr/lib64/python2.7/unittest/test/support.pyR2scCs'|jjdtt|jdS(Nt startTestRun(RRRRR(R((s-/usr/lib64/python2.7/unittest/test/support.pyR6scCs*|jjdtt|j|dS(NtstopTest(RRRRR(RR((s-/usr/lib64/python2.7/unittest/test/support.pyR:scCs'|jjdtt|jdS(Nt stopTestRun(RRRRR(R((s-/usr/lib64/python2.7/unittest/test/support.pyR>scGs*|jjdtt|j|dS(Nt addFailure(RRRRR(Rtargs((s-/usr/lib64/python2.7/unittest/test/support.pyRBscGs*|jjdtt|j|dS(Nt addSuccess(RRRRR!(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR!FscGs*|jjdtt|j|dS(NtaddError(RRRRR"(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR"JscGs*|jjdtt|j|dS(NtaddSkip(RRRRR#(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR#NscGs*|jjdtt|j|dS(NtaddExpectedFailure(RRRRR$(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR$RscGs*|jjdtt|j|dS(NtaddUnexpectedSuccess(RRRRR%(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR%Vs( R R RRRRRRR!R"R#R$R%(((s-/usr/lib64/python2.7/unittest/test/support.pyR-s          t#ResultWithNoStartTestRunStopTestRuncBsMeZdZdZdZdZdZdZdZdZ RS(s?An object honouring TestResult before startTestRun/stopTestRun.cCsCg|_g|_d|_g|_g|_g|_t|_dS(Ni(tfailuresterrorsttestsRuntskippedtexpectedFailurestunexpectedSuccessestFalset shouldStop(R((s-/usr/lib64/python2.7/unittest/test/support.pyR^s      cCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRgscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRjscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyR"mscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRpscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyR!sscCstS(N(tTrue(R((s-/usr/lib64/python2.7/unittest/test/support.pyt wasSuccessfulvs( R R RRRRR"RR!R0(((s-/usr/lib64/python2.7/unittest/test/support.pyR&[s     (tunittesttobjectRRt TestResultRR&(((s-/usr/lib64/python2.7/unittest/test/support.pyts .PK!%v tttest/support.pyonu[ {fc@skddlZdefdYZdefdYZdejfdYZdefd YZdS( iNt TestHashingcBseZdZdZRS(sUsed as a mixin for TestCasecCs*x|jD]\}}y6t|t|ksK|jd||fnWq tk rbq tk r}|jd|||fq Xq Wx|jD]\}}y6t|t|kr|jd||fnWqtk rqtk r!}|jd|||fqXqWdS(Ns%r and %r do not hash equalsProblem hashing %r and %r: %ss#%s and %s hash equal, but shouldn'tsProblem hashing %s and %s: %s(teq_pairsthashtfailtKeyboardInterruptt Exceptiontne_pairs(tselftobj_1tobj_2te((s-/usr/lib64/python2.7/unittest/test/support.pyt test_hashs" "  (t__name__t __module__t__doc__R (((s-/usr/lib64/python2.7/unittest/test/support.pyRst TestEqualitycBs eZdZdZdZRS(sUsed as a mixin for TestCasecCs>x7|jD],\}}|j|||j||q WdS(N(Rt assertEqual(RRR ((s-/usr/lib64/python2.7/unittest/test/support.pyttest_eq!scCs>x7|jD],\}}|j|||j||q WdS(N(RtassertNotEqual(RRR ((s-/usr/lib64/python2.7/unittest/test/support.pyttest_ne's(R R RRR(((s-/usr/lib64/python2.7/unittest/test/support.pyRs t LoggingResultcBskeZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( cCs ||_tt|jdS(N(t_eventstsuperRt__init__(Rtlog((s-/usr/lib64/python2.7/unittest/test/support.pyR.s cCs*|jjdtt|j|dS(Nt startTest(RtappendRRR(Rttest((s-/usr/lib64/python2.7/unittest/test/support.pyR2scCs'|jjdtt|jdS(Nt startTestRun(RRRRR(R((s-/usr/lib64/python2.7/unittest/test/support.pyR6scCs*|jjdtt|j|dS(NtstopTest(RRRRR(RR((s-/usr/lib64/python2.7/unittest/test/support.pyR:scCs'|jjdtt|jdS(Nt stopTestRun(RRRRR(R((s-/usr/lib64/python2.7/unittest/test/support.pyR>scGs*|jjdtt|j|dS(Nt addFailure(RRRRR(Rtargs((s-/usr/lib64/python2.7/unittest/test/support.pyRBscGs*|jjdtt|j|dS(Nt addSuccess(RRRRR!(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR!FscGs*|jjdtt|j|dS(NtaddError(RRRRR"(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR"JscGs*|jjdtt|j|dS(NtaddSkip(RRRRR#(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR#NscGs*|jjdtt|j|dS(NtaddExpectedFailure(RRRRR$(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR$RscGs*|jjdtt|j|dS(NtaddUnexpectedSuccess(RRRRR%(RR ((s-/usr/lib64/python2.7/unittest/test/support.pyR%Vs( R R RRRRRRR!R"R#R$R%(((s-/usr/lib64/python2.7/unittest/test/support.pyR-s          t#ResultWithNoStartTestRunStopTestRuncBsMeZdZdZdZdZdZdZdZdZ RS(s?An object honouring TestResult before startTestRun/stopTestRun.cCsCg|_g|_d|_g|_g|_g|_t|_dS(Ni(tfailuresterrorsttestsRuntskippedtexpectedFailurestunexpectedSuccessestFalset shouldStop(R((s-/usr/lib64/python2.7/unittest/test/support.pyR^s      cCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRgscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRjscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyR"mscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyRpscCsdS(N((RR((s-/usr/lib64/python2.7/unittest/test/support.pyR!sscCstS(N(tTrue(R((s-/usr/lib64/python2.7/unittest/test/support.pyt wasSuccessfulvs( R R RRRRR"RR!R0(((s-/usr/lib64/python2.7/unittest/test/support.pyR&[s     (tunittesttobjectRRt TestResultRR&(((s-/usr/lib64/python2.7/unittest/test/support.pyts .PK!pV'..test/test_assertions.pynu[import datetime import unittest class Test_Assertions(unittest.TestCase): def test_AlmostEqual(self): self.assertAlmostEqual(1.00000001, 1.0) self.assertNotAlmostEqual(1.0000001, 1.0) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.0000001, 1.0) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.00000001, 1.0) self.assertAlmostEqual(1.1, 1.0, places=0) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.1, 1.0, places=1) self.assertAlmostEqual(0, .1+.1j, places=0) self.assertNotAlmostEqual(0, .1+.1j, places=1) self.assertRaises(self.failureException, self.assertAlmostEqual, 0, .1+.1j, places=1) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 0, .1+.1j, places=0) self.assertAlmostEqual(float('inf'), float('inf')) self.assertRaises(self.failureException, self.assertNotAlmostEqual, float('inf'), float('inf')) def test_AmostEqualWithDelta(self): self.assertAlmostEqual(1.1, 1.0, delta=0.5) self.assertAlmostEqual(1.0, 1.1, delta=0.5) self.assertNotAlmostEqual(1.1, 1.0, delta=0.05) self.assertNotAlmostEqual(1.0, 1.1, delta=0.05) self.assertAlmostEqual(1.0, 1.0, delta=0.5) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.0, 1.0, delta=0.5) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.1, 1.0, delta=0.05) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.1, 1.0, delta=0.5) self.assertRaises(TypeError, self.assertAlmostEqual, 1.1, 1.0, places=2, delta=2) self.assertRaises(TypeError, self.assertNotAlmostEqual, 1.1, 1.0, places=2, delta=2) first = datetime.datetime.now() second = first + datetime.timedelta(seconds=10) self.assertAlmostEqual(first, second, delta=datetime.timedelta(seconds=20)) self.assertNotAlmostEqual(first, second, delta=datetime.timedelta(seconds=5)) def test_assertRaises(self): def _raise(e): raise e self.assertRaises(KeyError, _raise, KeyError) self.assertRaises(KeyError, _raise, KeyError("key")) try: self.assertRaises(KeyError, lambda: None) except self.failureException as e: self.assertIn("KeyError not raised", e.args) else: self.fail("assertRaises() didn't fail") try: self.assertRaises(KeyError, _raise, ValueError) except ValueError: pass else: self.fail("assertRaises() didn't let exception pass through") with self.assertRaises(KeyError) as cm: try: raise KeyError except Exception, e: raise self.assertIs(cm.exception, e) with self.assertRaises(KeyError): raise KeyError("key") try: with self.assertRaises(KeyError): pass except self.failureException as e: self.assertIn("KeyError not raised", e.args) else: self.fail("assertRaises() didn't fail") try: with self.assertRaises(KeyError): raise ValueError except ValueError: pass else: self.fail("assertRaises() didn't let exception pass through") def testAssertNotRegexpMatches(self): self.assertNotRegexpMatches('Ala ma kota', r'r+') try: self.assertNotRegexpMatches('Ala ma kota', r'k.t', 'Message') except self.failureException, e: self.assertIn("'kot'", e.args[0]) self.assertIn('Message', e.args[0]) else: self.fail('assertNotRegexpMatches should have failed.') class TestLongMessage(unittest.TestCase): """Test that the individual asserts honour longMessage. This actually tests all the message behaviour for asserts that use longMessage.""" def setUp(self): class TestableTestFalse(unittest.TestCase): longMessage = False failureException = self.failureException def testTest(self): pass class TestableTestTrue(unittest.TestCase): longMessage = True failureException = self.failureException def testTest(self): pass self.testableTrue = TestableTestTrue('testTest') self.testableFalse = TestableTestFalse('testTest') def testDefault(self): self.assertFalse(unittest.TestCase.longMessage) def test_formatMsg(self): self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo") self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo") self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo") self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") # This blows up if _formatMessage uses string concatenation self.testableTrue._formatMessage(object(), 'foo') def test_formatMessage_unicode_error(self): one = ''.join(chr(i) for i in range(255)) # this used to cause a UnicodeDecodeError constructing msg self.testableTrue._formatMessage(one, u'\uFFFD') def assertMessages(self, methodName, args, errors): def getMethod(i): useTestableFalse = i < 2 if useTestableFalse: test = self.testableFalse else: test = self.testableTrue return getattr(test, methodName) for i, expected_regexp in enumerate(errors): testMethod = getMethod(i) kwargs = {} withMsg = i % 2 if withMsg: kwargs = {"msg": "oops"} with self.assertRaisesRegexp(self.failureException, expected_regexp=expected_regexp): testMethod(*args, **kwargs) def testAssertTrue(self): self.assertMessages('assertTrue', (False,), ["^False is not true$", "^oops$", "^False is not true$", "^False is not true : oops$"]) def testAssertFalse(self): self.assertMessages('assertFalse', (True,), ["^True is not false$", "^oops$", "^True is not false$", "^True is not false : oops$"]) def testNotEqual(self): self.assertMessages('assertNotEqual', (1, 1), ["^1 == 1$", "^oops$", "^1 == 1$", "^1 == 1 : oops$"]) def testAlmostEqual(self): self.assertMessages('assertAlmostEqual', (1, 2), ["^1 != 2 within 7 places$", "^oops$", "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"]) def testNotAlmostEqual(self): self.assertMessages('assertNotAlmostEqual', (1, 1), ["^1 == 1 within 7 places$", "^oops$", "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"]) def test_baseAssertEqual(self): self.assertMessages('_baseAssertEqual', (1, 2), ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"]) def testAssertSequenceEqual(self): # Error messages are multiline so not testing on full message # assertTupleEqual and assertListEqual delegate to this method self.assertMessages('assertSequenceEqual', ([], [None]), ["\+ \[None\]$", "^oops$", r"\+ \[None\]$", r"\+ \[None\] : oops$"]) def testAssertSetEqual(self): self.assertMessages('assertSetEqual', (set(), set([None])), ["None$", "^oops$", "None$", "None : oops$"]) def testAssertIn(self): self.assertMessages('assertIn', (None, []), ['^None not found in \[\]$', "^oops$", '^None not found in \[\]$', '^None not found in \[\] : oops$']) def testAssertNotIn(self): self.assertMessages('assertNotIn', (None, [None]), ['^None unexpectedly found in \[None\]$', "^oops$", '^None unexpectedly found in \[None\]$', '^None unexpectedly found in \[None\] : oops$']) def testAssertDictEqual(self): self.assertMessages('assertDictEqual', ({}, {'key': 'value'}), [r"\+ \{'key': 'value'\}$", "^oops$", "\+ \{'key': 'value'\}$", "\+ \{'key': 'value'\} : oops$"]) def testAssertDictContainsSubset(self): self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}), ["^Missing: 'key'$", "^oops$", "^Missing: 'key'$", "^Missing: 'key' : oops$"]) def testAssertMultiLineEqual(self): self.assertMessages('assertMultiLineEqual', ("", "foo"), [r"\+ foo$", "^oops$", r"\+ foo$", r"\+ foo : oops$"]) def testAssertLess(self): self.assertMessages('assertLess', (2, 1), ["^2 not less than 1$", "^oops$", "^2 not less than 1$", "^2 not less than 1 : oops$"]) def testAssertLessEqual(self): self.assertMessages('assertLessEqual', (2, 1), ["^2 not less than or equal to 1$", "^oops$", "^2 not less than or equal to 1$", "^2 not less than or equal to 1 : oops$"]) def testAssertGreater(self): self.assertMessages('assertGreater', (1, 2), ["^1 not greater than 2$", "^oops$", "^1 not greater than 2$", "^1 not greater than 2 : oops$"]) def testAssertGreaterEqual(self): self.assertMessages('assertGreaterEqual', (1, 2), ["^1 not greater than or equal to 2$", "^oops$", "^1 not greater than or equal to 2$", "^1 not greater than or equal to 2 : oops$"]) def testAssertIsNone(self): self.assertMessages('assertIsNone', ('not None',), ["^'not None' is not None$", "^oops$", "^'not None' is not None$", "^'not None' is not None : oops$"]) def testAssertIsNotNone(self): self.assertMessages('assertIsNotNone', (None,), ["^unexpectedly None$", "^oops$", "^unexpectedly None$", "^unexpectedly None : oops$"]) def testAssertIs(self): self.assertMessages('assertIs', (None, 'foo'), ["^None is not 'foo'$", "^oops$", "^None is not 'foo'$", "^None is not 'foo' : oops$"]) def testAssertIsNot(self): self.assertMessages('assertIsNot', (None, None), ["^unexpectedly identical: None$", "^oops$", "^unexpectedly identical: None$", "^unexpectedly identical: None : oops$"]) if __name__ == '__main__': unittest.main() PK!o5z4z4test/test_assertions.pycnu[ {fc@sgddlZddlZdejfdYZdejfdYZedkrcejndS(iNtTest_AssertionscBs,eZdZdZdZdZRS(cCsH|jdd|jdd|j|j|jdd|j|j|jdd|jdddd|j|j|jdddd|jdd dd|jdd dd|j|j|jdd dd|j|j|jdddd|jtd td |j|j|jtd td dS(Ng1?g?g?g?tplacesiig?y?tinfy??y??y??y??(tassertAlmostEqualtassertNotAlmostEqualt assertRaisestfailureExceptiontfloat(tself((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_AlmostEquals$     c Cs|jdddd|jdddd|jdddd|jdddd|jdddd|j|j|jdddd|j|j|jdddd|j|j|jdddd|jt|jdddddd|jt|jddddddtjj}|tjdd }|j||dtjdd |j||dtjdd dS( Ng?g?tdeltag?g?Ritsecondsi ii(RRRRt TypeErrortdatetimetnowt timedelta(Rtfirsttsecond((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_AmostEqualWithDeltas*c Csd}|jt|t|jt|tdy|jtdWn)|jk rw}|jd|jnX|jdy|jt|tWntk rnX|jd|jt*}y tWntk r}nXWdQX|j|j ||jttdWdQXy|jtWdQXWn)|jk rr}|jd|jnX|jdy |jt tWdQXWntk rnX|jddS(NcSs |dS(N((te((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt_raise:stkeycSsdS(N(tNone(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt?tsKeyError not raisedsassertRaises() didn't fails0assertRaises() didn't let exception pass through( RtKeyErrorRtassertIntargstfailt ValueErrort ExceptiontassertIst exception(RRRtcm((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_assertRaises9sB         cCs|jddy|jdddWnD|jk rm}|jd|jd|jd|jdnX|jddS(Ns Ala ma kotasr+sk.ttMessages'kot'is*assertNotRegexpMatches should have failed.(tassertNotRegexpMatchesRRRR(RR((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertNotRegexpMatchesbs(t__name__t __module__R RR"R%(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyRs   )tTestLongMessagecBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(sTest that the individual asserts honour longMessage. This actually tests all the message behaviour for asserts that use longMessage.cs`dtjffdY}dtjffdY}|d_|d_dS(NtTestableTestFalsecs eZeZjZdZRS(cSsdS(N((R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestTestws(R&R'tFalset longMessageRR*((R(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR)ss tTestableTestTruecs eZeZjZdZRS(cSsdS(N((R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR*~s(R&R'tTrueR,RR*((R(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR-zs R*(tunittesttTestCaset testableTruet testableFalse(RR)R-((Rs5/usr/lib64/python2.7/unittest/test/test_assertions.pytsetUprscCs|jtjjdS(N(t assertFalseR/R0R,(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testDefaultscCs|j|jjddd|j|jjddd|j|jjddd|j|jjddd|jjtddS(Ntfootbars bar : foo(t assertEqualR2t_formatMessageRR1tobject(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_formatMsgs cCs6djdtdD}|jj|ddS(NRcss|]}t|VqdS(N(tchr(t.0ti((s5/usr/lib64/python2.7/unittest/test/test_assertions.pys siu�(tjointrangeR1R9(Rtone((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt test_formatMessage_unicode_errorsc sfd}xxt|D]j\}}||}i}|d} | r]idd6}njjd||||WdQXqWdS(Ncs4|dk}|rj}n j}t|S(Ni(R2R1tgetattr(R>tuseTestableFalsettest(t methodNameR(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt getMethods    itoopstmsgtexpected_regexp(t enumeratetassertRaisesRegexpR( RRFRterrorsRGR>RJt testMethodtkwargstwithMsg((RFRs5/usr/lib64/python2.7/unittest/test/test_assertions.pytassertMessagess   cCs&|jdtfddddgdS(Nt assertTrues^False is not true$s^oops$s^False is not true : oops$(RQR+(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertTrues cCs&|jdtfddddgdS(NR4s^True is not false$s^oops$s^True is not false : oops$(RQR.(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertFalses cCs#|jddddddgdS(NtassertNotEqualis^1 == 1$s^oops$s^1 == 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testNotEquals  cCs#|jddddddgdS(NRiis^1 != 2 within 7 places$s^oops$s^1 != 2 within 7 places : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAlmostEquals cCs#|jddddddgdS(NRis^1 == 1 within 7 places$s^oops$s^1 == 1 within 7 places : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestNotAlmostEquals cCs#|jddddddgdS(Nt_baseAssertEqualiis^1 != 2$s^oops$s^1 != 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_baseAssertEquals cCs,|jdgdgfddddgdS(NtassertSequenceEquals \+ \[None\]$s^oops$s\+ \[None\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertSequenceEquals cCs5|jdttdgfddddgdS(NtassertSetEqualsNone$s^oops$s None : oops$(RQtsetR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertSetEquals cCs)|jddgfddddgdS(NRs^None not found in \[\]$s^oops$s^None not found in \[\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testAssertInscCs,|jdddgfddddgdS(Nt assertNotIns%^None unexpectedly found in \[None\]$s^oops$s,^None unexpectedly found in \[None\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertNotInscCs0|jdiidd6fddddgdS(NtassertDictEqualtvalueRs\+ \{'key': 'value'\}$s^oops$s\+ \{'key': 'value'\} : oops$(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertDictEqualscCs0|jdidd6ifddddgdS(NtassertDictContainsSubsetRdRs^Missing: 'key'$s^oops$s^Missing: 'key' : oops$(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertDictContainsSubsetscCs#|jddddddgdS(NtassertMultiLineEqualRR6s\+ foo$s^oops$s\+ foo : oops$(RR6(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertMultiLineEquals cCs#|jddddddgdS(Nt assertLessiis^2 not less than 1$s^oops$s^2 not less than 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertLesss cCs#|jddddddgdS(NtassertLessEqualiis^2 not less than or equal to 1$s^oops$s&^2 not less than or equal to 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertLessEquals cCs#|jddddddgdS(Nt assertGreateriis^1 not greater than 2$s^oops$s^1 not greater than 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertGreaters cCs#|jddddddgdS(NtassertGreaterEqualiis"^1 not greater than or equal to 2$s^oops$s)^1 not greater than or equal to 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertGreaterEquals cCs#|jddddddgdS(Nt assertIsNonesnot Nones^'not None' is not None$s^oops$s^'not None' is not None : oops$(snot None(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNones cCs#|jddddddgdS(NtassertIsNotNones^unexpectedly None$s^oops$s^unexpectedly None : oops$(N(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNotNones cCs#|jddddddgdS(NRR6s^None is not 'foo'$s^oops$s^None is not 'foo' : oops$(NR6(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testAssertIss cCs#|jddddddgdS(Nt assertIsNots^unexpectedly identical: None$s^oops$s%^unexpectedly identical: None : oops$(NN(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNots (R&R't__doc__R3R5R;RBRQRSRTRVRWRXRZR\R_R`RbReRgRiRkRmRoRqRsRuRvRx(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR(ms6                        t__main__(R R/R0RR(R&tmain(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyts  g PK!o5z4z4test/test_assertions.pyonu[ {fc@sgddlZddlZdejfdYZdejfdYZedkrcejndS(iNtTest_AssertionscBs,eZdZdZdZdZRS(cCsH|jdd|jdd|j|j|jdd|j|j|jdd|jdddd|j|j|jdddd|jdd dd|jdd dd|j|j|jdd dd|j|j|jdddd|jtd td |j|j|jtd td dS(Ng1?g?g?g?tplacesiig?y?tinfy??y??y??y??(tassertAlmostEqualtassertNotAlmostEqualt assertRaisestfailureExceptiontfloat(tself((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_AlmostEquals$     c Cs|jdddd|jdddd|jdddd|jdddd|jdddd|j|j|jdddd|j|j|jdddd|j|j|jdddd|jt|jdddddd|jt|jddddddtjj}|tjdd }|j||dtjdd |j||dtjdd dS( Ng?g?tdeltag?g?Ritsecondsi ii(RRRRt TypeErrortdatetimetnowt timedelta(Rtfirsttsecond((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_AmostEqualWithDeltas*c Csd}|jt|t|jt|tdy|jtdWn)|jk rw}|jd|jnX|jdy|jt|tWntk rnX|jd|jt*}y tWntk r}nXWdQX|j|j ||jttdWdQXy|jtWdQXWn)|jk rr}|jd|jnX|jdy |jt tWdQXWntk rnX|jddS(NcSs |dS(N((te((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt_raise:stkeycSsdS(N(tNone(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt?tsKeyError not raisedsassertRaises() didn't fails0assertRaises() didn't let exception pass through( RtKeyErrorRtassertIntargstfailt ValueErrort ExceptiontassertIst exception(RRRtcm((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_assertRaises9sB         cCs|jddy|jdddWnD|jk rm}|jd|jd|jd|jdnX|jddS(Ns Ala ma kotasr+sk.ttMessages'kot'is*assertNotRegexpMatches should have failed.(tassertNotRegexpMatchesRRRR(RR((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertNotRegexpMatchesbs(t__name__t __module__R RR"R%(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyRs   )tTestLongMessagecBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(sTest that the individual asserts honour longMessage. This actually tests all the message behaviour for asserts that use longMessage.cs`dtjffdY}dtjffdY}|d_|d_dS(NtTestableTestFalsecs eZeZjZdZRS(cSsdS(N((R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestTestws(R&R'tFalset longMessageRR*((R(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR)ss tTestableTestTruecs eZeZjZdZRS(cSsdS(N((R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR*~s(R&R'tTrueR,RR*((R(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR-zs R*(tunittesttTestCaset testableTruet testableFalse(RR)R-((Rs5/usr/lib64/python2.7/unittest/test/test_assertions.pytsetUprscCs|jtjjdS(N(t assertFalseR/R0R,(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testDefaultscCs|j|jjddd|j|jjddd|j|jjddd|j|jjddd|jjtddS(Ntfootbars bar : foo(t assertEqualR2t_formatMessageRR1tobject(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_formatMsgs cCs6djdtdD}|jj|ddS(NRcss|]}t|VqdS(N(tchr(t.0ti((s5/usr/lib64/python2.7/unittest/test/test_assertions.pys siu�(tjointrangeR1R9(Rtone((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt test_formatMessage_unicode_errorsc sfd}xxt|D]j\}}||}i}|d} | r]idd6}njjd||||WdQXqWdS(Ncs4|dk}|rj}n j}t|S(Ni(R2R1tgetattr(R>tuseTestableFalsettest(t methodNameR(s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt getMethods    itoopstmsgtexpected_regexp(t enumeratetassertRaisesRegexpR( RRFRterrorsRGR>RJt testMethodtkwargstwithMsg((RFRs5/usr/lib64/python2.7/unittest/test/test_assertions.pytassertMessagess   cCs&|jdtfddddgdS(Nt assertTrues^False is not true$s^oops$s^False is not true : oops$(RQR+(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertTrues cCs&|jdtfddddgdS(NR4s^True is not false$s^oops$s^True is not false : oops$(RQR.(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertFalses cCs#|jddddddgdS(NtassertNotEqualis^1 == 1$s^oops$s^1 == 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testNotEquals  cCs#|jddddddgdS(NRiis^1 != 2 within 7 places$s^oops$s^1 != 2 within 7 places : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAlmostEquals cCs#|jddddddgdS(NRis^1 == 1 within 7 places$s^oops$s^1 == 1 within 7 places : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestNotAlmostEquals cCs#|jddddddgdS(Nt_baseAssertEqualiis^1 != 2$s^oops$s^1 != 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttest_baseAssertEquals cCs,|jdgdgfddddgdS(NtassertSequenceEquals \+ \[None\]$s^oops$s\+ \[None\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertSequenceEquals cCs5|jdttdgfddddgdS(NtassertSetEqualsNone$s^oops$s None : oops$(RQtsetR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertSetEquals cCs)|jddgfddddgdS(NRs^None not found in \[\]$s^oops$s^None not found in \[\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testAssertInscCs,|jdddgfddddgdS(Nt assertNotIns%^None unexpectedly found in \[None\]$s^oops$s,^None unexpectedly found in \[None\] : oops$(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertNotInscCs0|jdiidd6fddddgdS(NtassertDictEqualtvalueRs\+ \{'key': 'value'\}$s^oops$s\+ \{'key': 'value'\} : oops$(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertDictEqualscCs0|jdidd6ifddddgdS(NtassertDictContainsSubsetRdRs^Missing: 'key'$s^oops$s^Missing: 'key' : oops$(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertDictContainsSubsetscCs#|jddddddgdS(NtassertMultiLineEqualRR6s\+ foo$s^oops$s\+ foo : oops$(RR6(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertMultiLineEquals cCs#|jddddddgdS(Nt assertLessiis^2 not less than 1$s^oops$s^2 not less than 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertLesss cCs#|jddddddgdS(NtassertLessEqualiis^2 not less than or equal to 1$s^oops$s&^2 not less than or equal to 1 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertLessEquals cCs#|jddddddgdS(Nt assertGreateriis^1 not greater than 2$s^oops$s^1 not greater than 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertGreaters cCs#|jddddddgdS(NtassertGreaterEqualiis"^1 not greater than or equal to 2$s^oops$s)^1 not greater than or equal to 2 : oops$(ii(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertGreaterEquals cCs#|jddddddgdS(Nt assertIsNonesnot Nones^'not None' is not None$s^oops$s^'not None' is not None : oops$(snot None(RQ(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNones cCs#|jddddddgdS(NtassertIsNotNones^unexpectedly None$s^oops$s^unexpectedly None : oops$(N(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNotNones cCs#|jddddddgdS(NRR6s^None is not 'foo'$s^oops$s^None is not 'foo' : oops$(NR6(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyt testAssertIss cCs#|jddddddgdS(Nt assertIsNots^unexpectedly identical: None$s^oops$s%^unexpectedly identical: None : oops$(NN(RQR(R((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyttestAssertIsNots (R&R't__doc__R3R5R;RBRQRSRTRVRWRXRZR\R_R`RbReRgRiRkRmRoRqRsRuRvRx(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyR(ms6                        t__main__(R R/R0RR(R&tmain(((s5/usr/lib64/python2.7/unittest/test/test_assertions.pyts  g PK!grx%%test/test_break.pynu[import gc import os import sys import signal import weakref from cStringIO import StringIO import unittest @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreak(unittest.TestCase): int_handler = None def setUp(self): self._default_handler = signal.getsignal(signal.SIGINT) if self.int_handler is not None: signal.signal(signal.SIGINT, self.int_handler) def tearDown(self): signal.signal(signal.SIGINT, self._default_handler) unittest.signals._results = weakref.WeakKeyDictionary() unittest.signals._interrupt_handler = None def testInstallHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(unittest.signals._interrupt_handler.called) def testRegisterResult(self): result = unittest.TestResult() unittest.registerResult(result) for ref in unittest.signals._results: if ref is result: break elif ref is not result: self.fail("odd object in result set") else: self.fail("result not found") def testInterruptCaught(self): default_handler = signal.getsignal(signal.SIGINT) result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.breakCaught) def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught) def testTwoResults(self): unittest.installHandler() result = unittest.TestResult() unittest.registerResult(result) new_handler = signal.getsignal(signal.SIGINT) result2 = unittest.TestResult() unittest.registerResult(result2) self.assertEqual(signal.getsignal(signal.SIGINT), new_handler) result3 = unittest.TestResult() def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.shouldStop) self.assertTrue(result2.shouldStop) self.assertFalse(result3.shouldStop) def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt") def testRunner(self): # Creating a TextTestRunner with the appropriate argument should # register the TextTestResult it creates runner = unittest.TextTestRunner(stream=StringIO()) result = runner.run(unittest.TestSuite()) self.assertIn(result, unittest.signals._results) def testWeakReferences(self): # Calling registerResult on a result should not keep it alive result = unittest.TestResult() unittest.registerResult(result) ref = weakref.ref(result) del result # For non-reference counting implementations gc.collect();gc.collect() self.assertIsNone(ref()) def testRemoveResult(self): result = unittest.TestResult() unittest.registerResult(result) unittest.installHandler() self.assertTrue(unittest.removeResult(result)) # Should this raise an error instead? self.assertFalse(unittest.removeResult(unittest.TestResult())) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass self.assertFalse(result.shouldStop) def testMainInstallsHandler(self): failfast = object() test = object() verbosity = object() result = object() default_handler = signal.getsignal(signal.SIGINT) class FakeRunner(object): initArgs = [] runArgs = [] def __init__(self, *args, **kwargs): self.initArgs.append((args, kwargs)) def run(self, test): self.runArgs.append(test) return result class Program(unittest.TestProgram): def __init__(self, catchbreak): self.exit = False self.verbosity = verbosity self.failfast = failfast self.catchbreak = catchbreak self.testRunner = FakeRunner self.test = test self.result = None p = Program(False) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) FakeRunner.initArgs = [] FakeRunner.runArgs = [] p = Program(True) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) # check that calling removeHandler multiple times has no ill-effect unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandlerAsDecorator(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() @unittest.removeHandler def test(): self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) test() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakDefaultIntHandler(TestBreak): int_handler = signal.default_int_handler @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalIgnored(TestBreak): int_handler = signal.SIG_IGN @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalDefault(TestBreak): int_handler = signal.SIG_DFL PK!Ij̟''test/test_break.pycnu[ {fc@sddlZddlZddlZddlZddlZddlmZddlZeje eddej ej dkdej ej dkdd ej fd YZ eje eddej ej dkdej ej dkdd e fd YZeje eddej ej dkdej ej dkdd e fdYZeje eddej ej dkdej ej dkdde fdYZdS(iN(tStringIOtkillsTest requires os.killtwin32sTest cannot run on Windowstfreebsd6s9Test kills regrtest on freebsd6 if threads have been usedt TestBreakcBseZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZRS(cCsAtjtj|_|jdk r=tjtj|jndS(N(tsignalt getsignaltSIGINTt_default_handlert int_handlertNone(tself((s0/usr/lib64/python2.7/unittest/test/test_break.pytsetUpscCs8tjtj|jtjtj_dtj_ dS(N( RRRtweakreftWeakKeyDictionarytunittesttsignalst_resultsR t_interrupt_handler(R ((s0/usr/lib64/python2.7/unittest/test/test_break.pyttearDownscCstjtj}tj|jtjtj|y#tj}tj|tjWnt k r{|j dnX|j tj j jdS(NsKeyboardInterrupt not handled(RRRRtinstallHandlertassertNotEqualtostgetpidRtKeyboardInterrupttfailt assertTrueRRtcalled(R tdefault_handlertpid((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestInstallHandlers   cCsmtj}tj|xMtjjD]2}||kr<Pq&||k r&|jdq&q&W|jddS(Nsodd object in result setsresult not found(Rt TestResulttregisterResultRRR(R tresulttref((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRegisterResult,s    cstjtj}tj}tjtj|jtjtj|fd}y||Wntk rj dnXj |j dS(Ncs<tj}tj|tjt|_j|jdS(N( RRRRRtTruet breakCaughtRt shouldStop(R!R(R (s0/usr/lib64/python2.7/unittest/test/test_break.pyttestBs  sKeyboardInterrupt not handled( RRRRRRR RRRRR%(R RR!R'((R s0/usr/lib64/python2.7/unittest/test/test_break.pyttestInterruptCaught9s    cstjtjtjkr+jdntj}tjtj|fd}y||Wnt k r~nXj dj |j dS(Ns&test requires SIGINT to not be ignoredcs\tj}tj|tjt|_j|jtj|tjj ddS(Ns#Second KeyboardInterrupt not raised( RRRRRR$R%RR&R(R!R(R (s0/usr/lib64/python2.7/unittest/test/test_break.pyR'Xs   s#Second KeyboardInterrupt not raised( RRRtSIG_IGNtskipTestRRRR RRRR%(R R!R'((R s0/usr/lib64/python2.7/unittest/test/test_break.pyttestSecondInterruptOs     cCstjtj}tj|tjtj}tj}tj||jtjtj|tj}d}y||Wntk r|j dnX|j |j |j |j |j |j dS(NcSs#tj}tj|tjdS(N(RRRRR(R!R((s0/usr/lib64/python2.7/unittest/test/test_break.pyR'vs sKeyboardInterrupt not handled( RRRR RRRt assertEqualRRRR&t assertFalse(R R!t new_handlertresult2tresult3R'((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestTwoResultsis         cstjtjtjkr+|jdntjtjtjfd}tjtj|y#tj}tj |tjWnt k rnX|j ddS(Ns&test requires SIGINT to not be ignoredcs||dS(N((tframetsignum(thandler(s0/usr/lib64/python2.7/unittest/test/test_break.pyR.ss6replaced but delegated handler doesn't raise interrupt( RRRR)R*RRRRRRR(R R.R((R4s0/usr/lib64/python2.7/unittest/test/test_break.pyttestHandlerReplacedButCalleds   cCsDtjdt}|jtj}|j|tjjdS(Ntstream(RtTextTestRunnerRtrunt TestSuitetassertInRR(R trunnerR!((s0/usr/lib64/python2.7/unittest/test/test_break.pyt testRunnerscCsStj}tj|tj|}~tjtj|j|dS(N(RRR R R"tgctcollectt assertIsNone(R R!R"((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestWeakReferencess   cCstj}tj|tj|jtj||jtjtjy#tj}tj |t j Wnt k rnX|j|j dS(N(RRR RRt removeResultR-RRRRRRR&(R R!R((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveResults     cstttttjtj}dtffdYdtjffdY}|t}|j|jj didd6d6d6fg|jj g|j|j |jtjtj|g_ g_ |t }|j|jj d idd6d6d6fg|jj g|j|j |jtjtj|dS( Nt FakeRunnercs,eZgZgZdZfdZRS(c_s|jj||fdS(N(tinitArgstappend(R targstkwargs((s0/usr/lib64/python2.7/unittest/test/test_break.pyt__init__scs|jj|S(N(trunArgsRE(R R'(R!(s0/usr/lib64/python2.7/unittest/test/test_break.pyR8s(t__name__t __module__RDRIRHR8((R!(s0/usr/lib64/python2.7/unittest/test/test_break.pyRCs tProgramcs eZfdZRS(csCt|_|_|_||_|_|_d|_dS(N( tFalsetexitt verbositytfailfastt catchbreakR<R'R R!(R RQ(RCRPR'RO(s0/usr/lib64/python2.7/unittest/test/test_break.pyRHs      (RJRKRH((RCRPR'RO(s0/usr/lib64/python2.7/unittest/test/test_break.pyRLstbufferRORP(((tobjectRRRRt TestProgramRMtrunTestsR,RDR RIR!R$R(R RRLtp((RCRPR!R'ROs0/usr/lib64/python2.7/unittest/test/test_break.pyttestMainInstallsHandlers2     (      cCsltjtj}tjtj|jtjtj|tj|jtjtj|dS(N(RRRRRt removeHandlerR,(R R((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveHandlers    cs^tjtjtjtjfd}|jtjtjdS(Ncs jtjtjdS(N(R,RRR((RR (s0/usr/lib64/python2.7/unittest/test/test_break.pyR's(RRRRRRXR(R R'((RR s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveHandlerAsDecorators  N(RJRKR R R RRR#R(R+R1R5R<R@RBRWRYRZ(((s0/usr/lib64/python2.7/unittest/test/test_break.pyR s         2 tTestBreakDefaultIntHandlercBseZejZRS((RJRKRtdefault_int_handlerR (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR[ stTestBreakSignalIgnoredcBseZejZRS((RJRKRR)R (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR]stTestBreakSignalDefaultcBseZejZRS((RJRKRtSIG_DFLR (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR^s(R=RtsysRR t cStringIORRt skipUnlessthasattrtskipIftplatformtTestCaseRR[R]R^(((s0/usr/lib64/python2.7/unittest/test/test_break.pyts,      PK!Ij̟''test/test_break.pyonu[ {fc@sddlZddlZddlZddlZddlZddlmZddlZeje eddej ej dkdej ej dkdd ej fd YZ eje eddej ej dkdej ej dkdd e fd YZeje eddej ej dkdej ej dkdd e fdYZeje eddej ej dkdej ej dkdde fdYZdS(iN(tStringIOtkillsTest requires os.killtwin32sTest cannot run on Windowstfreebsd6s9Test kills regrtest on freebsd6 if threads have been usedt TestBreakcBseZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZRS(cCsAtjtj|_|jdk r=tjtj|jndS(N(tsignalt getsignaltSIGINTt_default_handlert int_handlertNone(tself((s0/usr/lib64/python2.7/unittest/test/test_break.pytsetUpscCs8tjtj|jtjtj_dtj_ dS(N( RRRtweakreftWeakKeyDictionarytunittesttsignalst_resultsR t_interrupt_handler(R ((s0/usr/lib64/python2.7/unittest/test/test_break.pyttearDownscCstjtj}tj|jtjtj|y#tj}tj|tjWnt k r{|j dnX|j tj j jdS(NsKeyboardInterrupt not handled(RRRRtinstallHandlertassertNotEqualtostgetpidRtKeyboardInterrupttfailt assertTrueRRtcalled(R tdefault_handlertpid((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestInstallHandlers   cCsmtj}tj|xMtjjD]2}||kr<Pq&||k r&|jdq&q&W|jddS(Nsodd object in result setsresult not found(Rt TestResulttregisterResultRRR(R tresulttref((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRegisterResult,s    cstjtj}tj}tjtj|jtjtj|fd}y||Wntk rj dnXj |j dS(Ncs<tj}tj|tjt|_j|jdS(N( RRRRRtTruet breakCaughtRt shouldStop(R!R(R (s0/usr/lib64/python2.7/unittest/test/test_break.pyttestBs  sKeyboardInterrupt not handled( RRRRRRR RRRRR%(R RR!R'((R s0/usr/lib64/python2.7/unittest/test/test_break.pyttestInterruptCaught9s    cstjtjtjkr+jdntj}tjtj|fd}y||Wnt k r~nXj dj |j dS(Ns&test requires SIGINT to not be ignoredcs\tj}tj|tjt|_j|jtj|tjj ddS(Ns#Second KeyboardInterrupt not raised( RRRRRR$R%RR&R(R!R(R (s0/usr/lib64/python2.7/unittest/test/test_break.pyR'Xs   s#Second KeyboardInterrupt not raised( RRRtSIG_IGNtskipTestRRRR RRRR%(R R!R'((R s0/usr/lib64/python2.7/unittest/test/test_break.pyttestSecondInterruptOs     cCstjtj}tj|tjtj}tj}tj||jtjtj|tj}d}y||Wntk r|j dnX|j |j |j |j |j |j dS(NcSs#tj}tj|tjdS(N(RRRRR(R!R((s0/usr/lib64/python2.7/unittest/test/test_break.pyR'vs sKeyboardInterrupt not handled( RRRR RRRt assertEqualRRRR&t assertFalse(R R!t new_handlertresult2tresult3R'((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestTwoResultsis         cstjtjtjkr+|jdntjtjtjfd}tjtj|y#tj}tj |tjWnt k rnX|j ddS(Ns&test requires SIGINT to not be ignoredcs||dS(N((tframetsignum(thandler(s0/usr/lib64/python2.7/unittest/test/test_break.pyR.ss6replaced but delegated handler doesn't raise interrupt( RRRR)R*RRRRRRR(R R.R((R4s0/usr/lib64/python2.7/unittest/test/test_break.pyttestHandlerReplacedButCalleds   cCsDtjdt}|jtj}|j|tjjdS(Ntstream(RtTextTestRunnerRtrunt TestSuitetassertInRR(R trunnerR!((s0/usr/lib64/python2.7/unittest/test/test_break.pyt testRunnerscCsStj}tj|tj|}~tjtj|j|dS(N(RRR R R"tgctcollectt assertIsNone(R R!R"((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestWeakReferencess   cCstj}tj|tj|jtj||jtjtjy#tj}tj |t j Wnt k rnX|j|j dS(N(RRR RRt removeResultR-RRRRRRR&(R R!R((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveResults     cstttttjtj}dtffdYdtjffdY}|t}|j|jj didd6d6d6fg|jj g|j|j |jtjtj|g_ g_ |t }|j|jj d idd6d6d6fg|jj g|j|j |jtjtj|dS( Nt FakeRunnercs,eZgZgZdZfdZRS(c_s|jj||fdS(N(tinitArgstappend(R targstkwargs((s0/usr/lib64/python2.7/unittest/test/test_break.pyt__init__scs|jj|S(N(trunArgsRE(R R'(R!(s0/usr/lib64/python2.7/unittest/test/test_break.pyR8s(t__name__t __module__RDRIRHR8((R!(s0/usr/lib64/python2.7/unittest/test/test_break.pyRCs tProgramcs eZfdZRS(csCt|_|_|_||_|_|_d|_dS(N( tFalsetexitt verbositytfailfastt catchbreakR<R'R R!(R RQ(RCRPR'RO(s0/usr/lib64/python2.7/unittest/test/test_break.pyRHs      (RJRKRH((RCRPR'RO(s0/usr/lib64/python2.7/unittest/test/test_break.pyRLstbufferRORP(((tobjectRRRRt TestProgramRMtrunTestsR,RDR RIR!R$R(R RRLtp((RCRPR!R'ROs0/usr/lib64/python2.7/unittest/test/test_break.pyttestMainInstallsHandlers2     (      cCsltjtj}tjtj|jtjtj|tj|jtjtj|dS(N(RRRRRt removeHandlerR,(R R((s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveHandlers    cs^tjtjtjtjfd}|jtjtjdS(Ncs jtjtjdS(N(R,RRR((RR (s0/usr/lib64/python2.7/unittest/test/test_break.pyR's(RRRRRRXR(R R'((RR s0/usr/lib64/python2.7/unittest/test/test_break.pyttestRemoveHandlerAsDecorators  N(RJRKR R R RRR#R(R+R1R5R<R@RBRWRYRZ(((s0/usr/lib64/python2.7/unittest/test/test_break.pyR s         2 tTestBreakDefaultIntHandlercBseZejZRS((RJRKRtdefault_int_handlerR (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR[ stTestBreakSignalIgnoredcBseZejZRS((RJRKRR)R (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR]stTestBreakSignalDefaultcBseZejZRS((RJRKRtSIG_DFLR (((s0/usr/lib64/python2.7/unittest/test/test_break.pyR^s(R=RtsysRR t cStringIORRt skipUnlessthasattrtskipIftplatformtTestCaseRR[R]R^(((s0/usr/lib64/python2.7/unittest/test/test_break.pyts,      PK! test/test_case.pynu[import difflib import pprint import pickle import re import sys from copy import deepcopy from test import test_support import unittest from unittest.test.support import ( TestEquality, TestHashing, LoggingResult, ResultWithNoStartTestRunStopTestRun ) class Test(object): "Keep these TestCase classes out of the main namespace" class Foo(unittest.TestCase): def runTest(self): pass def test1(self): pass class Bar(Foo): def test2(self): pass class LoggingTestCase(unittest.TestCase): """A test case which logs its calls.""" def __init__(self, events): super(Test.LoggingTestCase, self).__init__('test') self.events = events def setUp(self): self.events.append('setUp') def test(self): self.events.append('test') def tearDown(self): self.events.append('tearDown') class Test_TestCase(unittest.TestCase, TestEquality, TestHashing): ### Set up attributes used by inherited tests ################################################################ # Used by TestHashing.test_hash and TestEquality.test_eq eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))] # Used by TestEquality.test_ne ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')) ,(Test.Foo('test1'), Test.Bar('test1')) ,(Test.Foo('test1'), Test.Bar('test2'))] ################################################################ ### /Set up attributes used by inherited tests # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." # ... # "methodName defaults to "runTest"." # # Make sure it really is optional, and that it defaults to the proper # thing. def test_init__no_test_name(self): class Test(unittest.TestCase): def runTest(self): raise TypeError() def test(self): pass self.assertEqual(Test().id()[-13:], '.Test.runTest') # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__valid(self): class Test(unittest.TestCase): def runTest(self): raise TypeError() def test(self): pass self.assertEqual(Test('test').id()[-10:], '.Test.test') # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__invalid(self): class Test(unittest.TestCase): def runTest(self): raise TypeError() def test(self): pass try: Test('testfoo') except ValueError: pass else: self.fail("Failed to raise ValueError") # "Return the number of tests represented by the this test object. For # TestCase instances, this will always be 1" def test_countTestCases(self): class Foo(unittest.TestCase): def test(self): pass self.assertEqual(Foo('test').countTestCases(), 1) # "Return the default type of test result object to be used to run this # test. For TestCase instances, this will always be # unittest.TestResult; subclasses of TestCase should # override this as necessary." def test_defaultTestResult(self): class Foo(unittest.TestCase): def runTest(self): pass result = Foo().defaultTestResult() self.assertEqual(type(result), unittest.TestResult) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception. def test_run_call_order__error_in_setUp(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run(result) expected = ['startTest', 'setUp', 'addError', 'stopTest'] self.assertEqual(events, expected) # "With a temporary result stopTestRun is called when setUp errors. def test_run_call_order__error_in_setUp_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test raises # an error (as opposed to a failure). def test_run_call_order__error_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "With a default result, an error in the test still results in stopTestRun # being called." def test_run_call_order__error_in_test_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError', 'tearDown', 'stopTest', 'stopTestRun'] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test signals # a failure (as opposed to an error). def test_run_call_order__failure_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "When a test fails with a default result stopTestRun is still called." def test_run_call_order__failure_in_test_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure', 'tearDown', 'stopTest', 'stopTestRun'] events = [] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if tearDown() raises # an exception. def test_run_call_order__error_in_tearDown(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') Foo(events).run(result) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] self.assertEqual(events, expected) # "When tearDown errors with a default result stopTestRun is still called." def test_run_call_order__error_in_tearDown_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') events = [] Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "TestCase.run() still works when the defaultTestResult is a TestResult # that does not support startTestRun and stopTestRun. def test_run_call_order_default_result(self): class Foo(unittest.TestCase): def defaultTestResult(self): return ResultWithNoStartTestRunStopTestRun() def test(self): pass Foo('test').run() # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework. The initial value of this # attribute is AssertionError" def test_failureException__default(self): class Foo(unittest.TestCase): def test(self): pass self.assertIs(Foo('test').failureException, AssertionError) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__explicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): raise RuntimeError() failureException = RuntimeError self.assertIs(Foo('test').failureException, RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__implicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): self.fail("foo") failureException = RuntimeError self.assertIs(Foo('test').failureException, RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "The default implementation does nothing." def test_setUp(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().setUp() # "The default implementation does nothing." def test_tearDown(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().tearDown() # "Return a string identifying the specific test case." # # Because of the vague nature of the docs, I'm not going to lock this # test down too much. Really all that can be asserted is that the id() # will be a string (either 8-byte or unicode -- again, because the docs # just say "string") def test_id(self): class Foo(unittest.TestCase): def runTest(self): pass self.assertIsInstance(Foo().id(), basestring) # "If result is omitted or None, a temporary result object is created # and used, but is not made available to the caller. As TestCase owns the # temporary result startTestRun and stopTestRun are called. def test_run__uses_defaultTestResult(self): events = [] class Foo(unittest.TestCase): def test(self): events.append('test') def defaultTestResult(self): return LoggingResult(events) # Make run() find a result object on its own Foo('test').run() expected = ['startTestRun', 'startTest', 'test', 'addSuccess', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) def testShortDescriptionWithoutDocstring(self): self.assertIsNone(self.shortDescription()) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithOneLineDocstring(self): """Tests shortDescription() for a method with a docstring.""" self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a docstring.') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithMultiLineDocstring(self): """Tests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is. """ self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a longer ' 'docstring.') def testAddTypeEqualityFunc(self): class SadSnake(object): """Dummy class for test_addTypeEqualityFunc.""" s1, s2 = SadSnake(), SadSnake() self.assertNotEqual(s1, s2) def AllSnakesCreatedEqual(a, b, msg=None): return type(a) is type(b) is SadSnake self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) self.assertEqual(s1, s2) # No this doesn't clean up and remove the SadSnake equality func # from this TestCase instance but since its a local nothing else # will ever notice that. def testAssertIs(self): thing = object() self.assertIs(thing, thing) self.assertRaises(self.failureException, self.assertIs, thing, object()) def testAssertIsNot(self): thing = object() self.assertIsNot(thing, object()) self.assertRaises(self.failureException, self.assertIsNot, thing, thing) def testAssertIsInstance(self): thing = [] self.assertIsInstance(thing, list) self.assertRaises(self.failureException, self.assertIsInstance, thing, dict) def testAssertNotIsInstance(self): thing = [] self.assertNotIsInstance(thing, dict) self.assertRaises(self.failureException, self.assertNotIsInstance, thing, list) def testAssertIn(self): animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} self.assertIn('a', 'abc') self.assertIn(2, [1, 2, 3]) self.assertIn('monkey', animals) self.assertNotIn('d', 'abc') self.assertNotIn(0, [1, 2, 3]) self.assertNotIn('otter', animals) self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) self.assertRaises(self.failureException, self.assertIn, 'elephant', animals) self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) self.assertRaises(self.failureException, self.assertNotIn, 'cow', animals) def testAssertDictContainsSubset(self): self.assertDictContainsSubset({}, {}) self.assertDictContainsSubset({}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({1: "one"}, {}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 2}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) with test_support.check_warnings(("", UnicodeWarning)): one = ''.join(chr(i) for i in range(255)) # this used to cause a UnicodeDecodeError constructing the failure msg with self.assertRaises(self.failureException): self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'}) def testAssertEqual(self): equal_pairs = [ ((), ()), ({}, {}), ([], []), (set(), set()), (frozenset(), frozenset())] for a, b in equal_pairs: # This mess of try excepts is to test the assertEqual behavior # itself. try: self.assertEqual(a, b) except self.failureException: self.fail('assertEqual(%r, %r) failed' % (a, b)) try: self.assertEqual(a, b, msg='foo') except self.failureException: self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) try: self.assertEqual(a, b, 'foo') except self.failureException: self.fail('assertEqual(%r, %r) with third parameter failed' % (a, b)) unequal_pairs = [ ((), []), ({}, set()), (set([4,1]), frozenset([4,2])), (frozenset([4,5]), set([2,3])), (set([3,4]), set([5,4]))] for a, b in unequal_pairs: self.assertRaises(self.failureException, self.assertEqual, a, b) self.assertRaises(self.failureException, self.assertEqual, a, b, 'foo') self.assertRaises(self.failureException, self.assertEqual, a, b, msg='foo') def testEquality(self): self.assertListEqual([], []) self.assertTupleEqual((), ()) self.assertSequenceEqual([], ()) a = [0, 'a', []] b = [] self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, a, b) self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, tuple(a), tuple(b)) self.assertRaises(unittest.TestCase.failureException, self.assertSequenceEqual, a, tuple(b)) b.extend(a) self.assertListEqual(a, b) self.assertTupleEqual(tuple(a), tuple(b)) self.assertSequenceEqual(a, tuple(b)) self.assertSequenceEqual(tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, a, tuple(b)) self.assertRaises(self.failureException, self.assertTupleEqual, tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, None, b) self.assertRaises(self.failureException, self.assertTupleEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertSequenceEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertListEqual, 1, 1) self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) self.assertRaises(self.failureException, self.assertSequenceEqual, 1, 1) self.assertDictEqual({}, {}) c = { 'x': 1 } d = {} self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d) d.update(c) self.assertDictEqual(c, d) d['x'] = 0 self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d, 'These are unequal') self.assertRaises(self.failureException, self.assertDictEqual, None, d) self.assertRaises(self.failureException, self.assertDictEqual, [], d) self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) def testAssertSequenceEqualMaxDiff(self): self.assertEqual(self.maxDiff, 80*8) seq1 = 'a' + 'x' * 80**2 seq2 = 'b' + 'x' * 80**2 diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) # the +1 is the leading \n added by assertSequenceEqual omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) self.maxDiff = len(diff)//2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertLess(len(msg), len(diff)) self.assertIn(omitted, msg) self.maxDiff = len(diff) * 2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertGreater(len(msg), len(diff)) self.assertNotIn(omitted, msg) self.maxDiff = None try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertGreater(len(msg), len(diff)) self.assertNotIn(omitted, msg) def testTruncateMessage(self): self.maxDiff = 1 message = self._truncateMessage('foo', 'bar') omitted = unittest.case.DIFF_OMITTED % len('bar') self.assertEqual(message, 'foo' + omitted) self.maxDiff = None message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') self.maxDiff = 4 message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') def testAssertDictEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertDictEqual({}, {1: 0}) except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertDictEqual did not fail') def testAssertMultiLineEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertMultiLineEqual('foo', 'bar') except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertMultiLineEqual did not fail') def testAssertEqual_diffThreshold(self): # check threshold value self.assertEqual(self._diffThreshold, 2**16) # disable madDiff to get diff markers self.maxDiff = None # set a lower threshold value and add a cleanup to restore it old_threshold = self._diffThreshold self._diffThreshold = 2**8 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) # under the threshold: diff marker (^) in error message s = u'x' * (2**7) with self.assertRaises(self.failureException) as cm: self.assertEqual(s + 'a', s + 'b') self.assertIn('^', str(cm.exception)) self.assertEqual(s + 'a', s + 'a') # over the threshold: diff not used and marker (^) not in error message s = u'x' * (2**9) # if the path that uses difflib is taken, _truncateMessage will be # called -- replace it with explodingTruncation to verify that this # doesn't happen def explodingTruncation(message, diff): raise SystemError('this should not be raised') old_truncate = self._truncateMessage self._truncateMessage = explodingTruncation self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) s1, s2 = s + 'a', s + 'b' with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) self.assertNotIn('^', str(cm.exception)) self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) self.assertEqual(s + 'a', s + 'a') def testAssertItemsEqual(self): a = object() self.assertItemsEqual([1, 2, 3], [3, 2, 1]) self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) self.assertRaises(self.failureException, self.assertItemsEqual, [1, 2] + [3] * 100, [1] * 100 + [2, 3]) self.assertRaises(self.failureException, self.assertItemsEqual, [1, "2", "a", "a"], ["a", "2", True, 1]) self.assertRaises(self.failureException, self.assertItemsEqual, [10], [10, 11]) self.assertRaises(self.failureException, self.assertItemsEqual, [10, 11], [10]) self.assertRaises(self.failureException, self.assertItemsEqual, [10, 11, 10], [10, 11]) # Test that sequences of unhashable objects can be tested for sameness: self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]]) # Test that iterator of unhashable objects can be tested for sameness: self.assertItemsEqual(iter([1, 2, [], 3, 4]), iter([1, 2, [], 3, 4])) # hashable types, but not orderable self.assertRaises(self.failureException, self.assertItemsEqual, [], [divmod, 'x', 1, 5j, 2j, frozenset()]) # comparing dicts self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) # comparing heterogenous non-hashable sequences self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1]) self.assertRaises(self.failureException, self.assertItemsEqual, [], [divmod, [], 'x', 1, 5j, 2j, set()]) self.assertRaises(self.failureException, self.assertItemsEqual, [[1]], [[2]]) # Same elements, but not same sequence length self.assertRaises(self.failureException, self.assertItemsEqual, [1, 1, 2], [2, 1]) self.assertRaises(self.failureException, self.assertItemsEqual, [1, 1, "2", "a", "a"], ["2", "2", True, "a"]) self.assertRaises(self.failureException, self.assertItemsEqual, [1, {'b': 2}, None, True], [{'b': 2}, True, None]) # Same elements which don't reliably compare, in # different order, see issue 10242 a = [{2,4}, {1,2}] b = a[::-1] self.assertItemsEqual(a, b) # test utility functions supporting assertItemsEqual() diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) diffs = unittest.util._count_diff_all_purpose([[]], []) self.assertEqual(diffs, [(1, 0, [])]) diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) def testAssertSetEqual(self): set1 = set() set2 = set() self.assertSetEqual(set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, None, set2) self.assertRaises(self.failureException, self.assertSetEqual, [], set2) self.assertRaises(self.failureException, self.assertSetEqual, set1, None) self.assertRaises(self.failureException, self.assertSetEqual, set1, []) set1 = set(['a']) set2 = set() self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = set(['a']) self.assertSetEqual(set1, set2) set1 = set(['a']) set2 = set(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = frozenset(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a', 'b']) set2 = frozenset(['a', 'b']) self.assertSetEqual(set1, set2) set1 = set() set2 = "foo" self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) # make sure any string formatting is tuple-safe set1 = set([(0, 1), (2, 3)]) set2 = set([(4, 5)]) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) def testInequality(self): # Try ints self.assertGreater(2, 1) self.assertGreaterEqual(2, 1) self.assertGreaterEqual(1, 1) self.assertLess(1, 2) self.assertLessEqual(1, 2) self.assertLessEqual(1, 1) self.assertRaises(self.failureException, self.assertGreater, 1, 2) self.assertRaises(self.failureException, self.assertGreater, 1, 1) self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) self.assertRaises(self.failureException, self.assertLess, 2, 1) self.assertRaises(self.failureException, self.assertLess, 1, 1) self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) # Try Floats self.assertGreater(1.1, 1.0) self.assertGreaterEqual(1.1, 1.0) self.assertGreaterEqual(1.0, 1.0) self.assertLess(1.0, 1.1) self.assertLessEqual(1.0, 1.1) self.assertLessEqual(1.0, 1.0) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) # Try Strings self.assertGreater('bug', 'ant') self.assertGreaterEqual('bug', 'ant') self.assertGreaterEqual('ant', 'ant') self.assertLess('ant', 'bug') self.assertLessEqual('ant', 'bug') self.assertLessEqual('ant', 'ant') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') # Try Unicode self.assertGreater(u'bug', u'ant') self.assertGreaterEqual(u'bug', u'ant') self.assertGreaterEqual(u'ant', u'ant') self.assertLess(u'ant', u'bug') self.assertLessEqual(u'ant', u'bug') self.assertLessEqual(u'ant', u'ant') self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug') self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant', u'bug') self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant') self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant') self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant') # Try Mixed String/Unicode self.assertGreater('bug', u'ant') self.assertGreater(u'bug', 'ant') self.assertGreaterEqual('bug', u'ant') self.assertGreaterEqual(u'bug', 'ant') self.assertGreaterEqual('ant', u'ant') self.assertGreaterEqual(u'ant', 'ant') self.assertLess('ant', u'bug') self.assertLess(u'ant', 'bug') self.assertLessEqual('ant', u'bug') self.assertLessEqual(u'ant', 'bug') self.assertLessEqual('ant', u'ant') self.assertLessEqual(u'ant', 'ant') self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug') self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug') self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant') self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', u'bug') self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant', 'bug') self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant') self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant') self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant') self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant') self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant') self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant') def testAssertMultiLineEqual(self): sample_text = b"""\ http://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] """ revised_sample_text = b"""\ http://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. """ sample_text_error = b"""\ - http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. """ self.maxDiff = None for type_changer in (lambda x: x, lambda x: x.decode('utf8')): try: self.assertMultiLineEqual(type_changer(sample_text), type_changer(revised_sample_text)) except self.failureException, e: # need to remove the first line of the error message error = str(e).encode('utf8').split('\n', 1)[1] # assertMultiLineEqual is hooked up as the default for # unicode strings - so we can't use it for this check self.assertTrue(sample_text_error == error) def testAsertEqualSingleLine(self): sample_text = u"laden swallows fly slowly" revised_sample_text = u"unladen swallows fly quickly" sample_text_error = """\ - laden swallows fly slowly ? ^^^^ + unladen swallows fly quickly ? ++ ^^^^^ """ try: self.assertEqual(sample_text, revised_sample_text) except self.failureException as e: error = str(e).split('\n', 1)[1] self.assertTrue(sample_text_error == error) def testAssertIsNone(self): self.assertIsNone(None) self.assertRaises(self.failureException, self.assertIsNone, False) self.assertIsNotNone('DjZoPloGears on Rails') self.assertRaises(self.failureException, self.assertIsNotNone, None) def testAssertRegexpMatches(self): self.assertRegexpMatches('asdfabasdf', r'ab+') self.assertRaises(self.failureException, self.assertRegexpMatches, 'saaas', r'aaaa') def testAssertRaisesCallable(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') self.assertRaises(ExceptionMock, Stub) # A tuple of exception classes is accepted self.assertRaises((ValueError, ExceptionMock), Stub) # *args and **kwargs also work self.assertRaises(ValueError, int, '19', base=8) # Failure when no exception is raised with self.assertRaises(self.failureException): self.assertRaises(ExceptionMock, lambda: 0) # Failure when another exception is raised with self.assertRaises(ExceptionMock): self.assertRaises(ValueError, Stub) def testAssertRaisesContext(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') with self.assertRaises(ExceptionMock): Stub() # A tuple of exception classes is accepted with self.assertRaises((ValueError, ExceptionMock)) as cm: Stub() # The context manager exposes caught exception self.assertIsInstance(cm.exception, ExceptionMock) self.assertEqual(cm.exception.args[0], 'We expect') # *args and **kwargs also work with self.assertRaises(ValueError): int('19', base=8) # Failure when no exception is raised with self.assertRaises(self.failureException): with self.assertRaises(ExceptionMock): pass # Failure when another exception is raised with self.assertRaises(ExceptionMock): self.assertRaises(ValueError, Stub) def testAssertRaisesRegexp(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub) self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub) self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub) def testAssertNotRaisesRegexp(self): self.assertRaisesRegexp( self.failureException, '^Exception not raised$', self.assertRaisesRegexp, Exception, re.compile('x'), lambda: None) self.assertRaisesRegexp( self.failureException, '^Exception not raised$', self.assertRaisesRegexp, Exception, 'x', lambda: None) self.assertRaisesRegexp( self.failureException, '^Exception not raised$', self.assertRaisesRegexp, Exception, u'x', lambda: None) def testAssertRaisesRegexpInvalidRegexp(self): # Issue 20145. class MyExc(Exception): pass self.assertRaises(TypeError, self.assertRaisesRegexp, MyExc, lambda: True) def testAssertRaisesRegexpMismatch(self): def Stub(): raise Exception('Unexpected') self.assertRaisesRegexp( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegexp, Exception, '^Expected$', Stub) self.assertRaisesRegexp( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegexp, Exception, u'^Expected$', Stub) self.assertRaisesRegexp( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegexp, Exception, re.compile('^Expected$'), Stub) def testAssertRaisesExcValue(self): class ExceptionMock(Exception): pass def Stub(foo): raise ExceptionMock(foo) v = "particular value" ctx = self.assertRaises(ExceptionMock) with ctx: Stub(v) e = ctx.exception self.assertIsInstance(e, ExceptionMock) self.assertEqual(e.args[0], v) def testSynonymAssertMethodNames(self): """Test undocumented method name synonyms. Please do not use these methods names in your own code. This test confirms their continued existence and functionality in order to avoid breaking existing code. """ self.assertNotEquals(3, 5) self.assertEquals(3, 3) self.assertAlmostEquals(2.0, 2.0) self.assertNotAlmostEquals(3.0, 5.0) self.assert_(True) def testPendingDeprecationMethodNames(self): """Test fail* methods pending deprecation, they will warn in 3.2. Do not use these methods. They will go away in 3.3. """ with test_support.check_warnings(): self.failIfEqual(3, 5) self.failUnlessEqual(3, 3) self.failUnlessAlmostEqual(2.0, 2.0) self.failIfAlmostEqual(3.0, 5.0) self.failUnless(True) self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam') self.failIf(False) def testDeepcopy(self): # Issue: 5660 class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') # This shouldn't blow up deepcopy(test) def testKeyboardInterrupt(self): def _raise(self=None): raise KeyboardInterrupt def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): with self.assertRaises(KeyboardInterrupt): klass('test_something').run() def testSystemExit(self): def _raise(self=None): raise SystemExit def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): result = unittest.TestResult() klass('test_something').run(result) self.assertEqual(len(result.errors), 1) self.assertEqual(result.testsRun, 1) def testPickle(self): # Issue 10326 # Can't use TestCase classes defined in Test class as # pickle does not work with inner classes test = unittest.TestCase('run') for protocol in range(pickle.HIGHEST_PROTOCOL + 1): # blew up prior to fix pickled_test = pickle.dumps(test, protocol=protocol) unpickled_test = pickle.loads(pickled_test) self.assertEqual(test, unpickled_test) if __name__ == '__main__': unittest.main() PK!Ltest/test_case.pycnu[ {fc@sddlZddlZddlZddlZddlZddlmZddlmZddl Z ddl m Z m Z m Z mZdefdYZde je e fdYZed kre jndS( iN(tdeepcopy(t test_support(t TestEqualityt TestHashingt LoggingResultt#ResultWithNoStartTestRunStopTestRuntTestcBsVeZdZdejfdYZdefdYZdejfdYZRS(s5Keep these TestCase classes out of the main namespacetFoocBseZdZdZRS(cCsdS(N((tself((s//usr/lib64/python2.7/unittest/test/test_case.pytrunTesttcCsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyttest1R (t__name__t __module__R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRs tBarcBseZdZRS(cCsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyttest2R (R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRstLoggingTestCasecBs2eZdZdZdZdZdZRS(s!A test case which logs its calls.cCs&ttj|jd||_dS(Nttest(tsuperRRt__init__tevents(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyRscCs|jjddS(NtsetUp(Rtappend(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR"scCs|jjddS(NR(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR%scCs|jjddS(NttearDown(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR(s(R R t__doc__RRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyRs    (R R RtunittesttTestCaseRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyRst Test_TestCasecBseZejdejdfgZejdejdfejdejdfejdejdfgZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZejej j!dkddZ"ejej j!dkddZ#dZ$dZ%dZ&d Z'd!Z(d"Z)d#Z*d$Z+d%Z,d&Z-d'Z.d(Z/d)Z0d*Z1d+Z2d,Z3d-Z4d.Z5d/Z6d0Z7d1Z8d2Z9d3Z:d4Z;d5Z<d6Z=d7Z>d8Z?d9Z@d:ZAd;ZBd<ZCd=ZDd>ZERS(?R R RcCs:dtjfdY}|j|jdddS(NRcBseZdZdZRS(cSs tdS(N(t TypeError(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR HR cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRIR (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRGs is .Test.runTest(RRt assertEqualtid(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__no_test_nameFscCs=dtjfdY}|j|djdddS(NRcBseZdZdZRS(cSs tdS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR SR cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRTR (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRRs Ris .Test.test(RRRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__test_name__validQscCsLdtjfdY}y|dWntk r:nX|jddS(NRcBseZdZdZRS(cSs tdS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ^R cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR_R (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyR]s ttestfoosFailed to raise ValueError(RRt ValueErrortfail(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__test_name__invalid\s  cCs9dtjfdY}|j|djddS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRlR (R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRksRi(RRRtcountTestCases(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_countTestCasesjscCsEdtjfdY}|j}|jt|tjdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR vs(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRus(RRtdefaultTestResultRttypet TestResult(RRtresult((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_defaultTestResulttscsjg}t|}dtjffdY|j|ddddg}|j||dS(NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.setUp(RRt RuntimeError(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRst startTestRtaddErrortstopTest(RRRtrunR(RRR*texpected((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt#test_run_call_order__error_in_setUps  csag}dtjffdY|jddddddg}|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.setUp(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs t startTestRunR-RR.R/t stopTestRun(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt2test_run_call_order__error_in_setUp_default_results   cspg}t|}dtjffdYddddddg}|j||j||dS( NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.test(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRR.RR/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt"test_run_call_order__error_in_tests  csgg}dtjffdYddddddd d g}|j|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.test(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRR.RR/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt1test_run_call_order__error_in_test_default_results cspg}t|}dtjffdYddddddg}|j||j||dS( NRcseZfdZRS(cs$t|j|jddS(Nsraised by Foo.test(RRR#(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRt addFailureRR/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt$test_run_call_order__failure_in_tests  csgdtjffdYddddddd d g}g}|j|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs$t|j|jddS(Nsraised by Foo.test(RRR#(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRR8RR/R4(RRR0R(RR1R((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt3test_run_call_order__failure_in_test_default_results cspg}t|}dtjffdY|j|ddddddg}|j||dS( NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.tearDown(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRRR.R/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt&test_run_call_order__error_in_tearDowns  csgdtjffdYg}|jddddddd d g}|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.tearDown(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRRR.R/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt5test_run_call_order__error_in_tearDown_default_results cCs-dtjfdY}|djdS(NRcBseZdZdZRS(cSstS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRs R(RRR0(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt"test_run_call_order_default_resultscCs6dtjfdY}|j|djtdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR%s(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyR$sR(RRtassertIstfailureExceptiontAssertionError(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_failureException__default#scCszg}t|}dtjfdY}|j|djt|dj|dddg}|j||dS(NRcBseZdZeZRS(cSs tdS(N(R,(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR5s(R R RR,R?(((s//usr/lib64/python2.7/unittest/test/test_case.pyR4s RR-R8R/(RRRR>R?R,R0R(RRR*RR1((s//usr/lib64/python2.7/unittest/test/test_case.pyt2test_failureException__subclassing__explicit_raise0s cCszg}t|}dtjfdY}|j|djt|dj|dddg}|j||dS(NRcBseZdZeZRS(cSs|jddS(Ntfoo(R#(R((s//usr/lib64/python2.7/unittest/test/test_case.pyRLs(R R RR,R?(((s//usr/lib64/python2.7/unittest/test/test_case.pyRKs RR-R8R/(RRRR>R?R,R0R(RRR*RR1((s//usr/lib64/python2.7/unittest/test/test_case.pyt2test_failureException__subclassing__implicit_raiseGs cCs*dtjfdY}|jdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR [s(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRZs(RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt test_setUpYscCs*dtjfdY}|jdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ds(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRcs(RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt test_tearDownbscCs6dtjfdY}|j|jtdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR rs(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRqs(RRtassertIsInstanceRt basestring(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_idpscsagdtjffdY}|djddddddg}|j|dS( NRcs&eZfdZfdZRS(csjddS(NR(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRscs tS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR's(R R RR'((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR~sRR3R-t addSuccessR/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt test_run__uses_defaultTestResult{s   cCs|j|jdS(N(t assertIsNonetshortDescription(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt$testShortDescriptionWithoutDocstringsis)Docstrings are omitted with -O2 and abovecCs|j|jddS(s7Tests shortDescription() for a method with a docstring.N(RRM(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt(testShortDescriptionWithOneLineDocstrings cCs|j|jddS(sTests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is. s>Tests shortDescription() for a method with a longer docstring.N(RRM(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt*testShortDescriptionWithMultiLineDocstrings  csodtfdY}}|j||dfd}|j||j||dS(NtSadSnakecBseZdZRS(s)Dummy class for test_addTypeEqualityFunc.(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRQscs$t|t|ko!kSS(N(R((tatbtmsg(RQ(s//usr/lib64/python2.7/unittest/test/test_case.pytAllSnakesCreatedEquals(tobjecttassertNotEqualtNonetaddTypeEqualityFuncR(Rts1ts2RU((RQs//usr/lib64/python2.7/unittest/test/test_case.pyttestAddTypeEqualityFuncs cCs<t}|j|||j|j|j|tdS(N(RVR>t assertRaisesR?(Rtthing((s//usr/lib64/python2.7/unittest/test/test_case.pyt testAssertIss cCs<t}|j|t|j|j|j||dS(N(RVt assertIsNotR]R?(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsNots cCs6g}|j|t|j|j|j|tdS(N(RGtlistR]R?tdict(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsInstancescCs6g}|j|t|j|j|j|tdS(N(tassertNotIsInstanceRcR]R?Rb(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertNotIsInstancescCsKidd6dd6dd6}|jdd|jd d d d g|jd||jd d|jd d d d g|jd||j|j|jdd|j|j|jdd d d g|j|j|jd||j|j|jdd|j|j|jd d d d g|j|j|jd|dS(NtbananatmonkeytgrasstcowtfishtsealRRtabciiitditottertxitelephanttc(tassertInt assertNotInR]R?(Rtanimals((s//usr/lib64/python2.7/unittest/test/test_case.pyt testAssertIns%%cCs&|jii|jiidd6|jidd6idd6|jidd6idd6dd6|jidd6dd6idd6dd6|j|j|jidd6iWdQX|j|j#|jidd6idd6WdQX|j|j#|jidd6idd6WdQX|j|j*|jidd6dd6idd6WdQX|j|j*|jidd6dd6idd6WdQXtjdtf[djdtd D}|j|j#|ji|d 6id d 6WdQXWdQXdS( NiRRiRStoneRrR css|]}t|VqdS(N(tchr(t.0ti((s//usr/lib64/python2.7/unittest/test/test_case.pys siRCu�(tassertDictContainsSubsetR]R?Rtcheck_warningstUnicodeWarningtjointrange(RRw((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertDictContainsSubsets&%,$$++cCsd d fiifggfttfttfg}x|D]\}}y|j||Wn+|jk r|jd||fnXy|j||ddWn+|jk r|jd||fnXy|j||dWqF|jk r |jd||fqFXqFWd gfitftddgtddgftdd gtdd gftd dgtd dgfg}xq|D]i\}}|j|j|j|||j|j|j||d|j|j|j||ddqWdS(NsassertEqual(%r, %r) failedRTRCs$assertEqual(%r, %r) with msg= faileds/assertEqual(%r, %r) with third parameter failediiiii((((tsett frozensetRR?R#R](Rt equal_pairsRRRSt unequal_pairs((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertEquals<      !!'cCs|jgg|jdd|jgdddgg}g}|jtjj|j|||jtjj|jt|t||jtjj|j|t||j||j|||jt|t||j|t||jt|||j|j|j|t||j|j|jt|||j|j|jd||j|j|jdt||j|j|jdt||j|j|jdd|j|j|jdd|j|j|jdd|j iiidd6}i}|jtjj|j |||j ||j ||d|d<|jtjj|j ||d|j|j|j d||j|j|j g||j|j|j dddS( NiRRiRpsThese are unequal(((( tassertListEqualtassertTupleEqualtassertSequenceEqualR]RRR?ttupletextendRXtassertDictEqualtupdate(RRRRSRrRn((s//usr/lib64/python2.7/unittest/test/test_case.pyt testEqualitysT      cCs|j|jd ddd }ddd }djtjtj|jtj|j}tj j t |df}t |d|_y|j ||Wn#|j k r}|jd }nX|jd |jt |t ||j||t |d|_y|j ||Wn#|j k rW}|jd }nX|jd |jt |t ||j||d|_y|j ||Wn#|j k r}|jd }nX|jd |jt |t ||j||dS(NiPiRRRpiRSs iis!assertSequenceEqual did not fail.iii(RtmaxDiffR~tdifflibtndifftpprinttpformatt splitlinesRtcaset DIFF_OMITTEDtlenRR?targsR#t assertLessRst assertGreaterRtRX(Rtseq1tseq2tdifftomittedteRT((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertSequenceEqualMaxDiffRs<    cCsd|_|jdd}tjjtd}|j|d|d|_|jdd}|j|dd|_|jdd}|j|ddS(NiRCtbartfoobari(Rt_truncateMessageRRRRRRX(RtmessageR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestTruncateMessageys   cCs|tjd}d}||_y|jiidd6Wn,|jk rj}|jt|dnX|jddS(NRcSsdS(NRC((RTR((s//usr/lib64/python2.7/unittest/test/test_case.pyttruncatesiiRCsassertDictEqual did not fail(RRRRR?RtstrR#(RRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertDictEqualTruncatess  cCsutjd}d}||_y|jddWn,|jk rc}|jt|dnX|jddS(NRcSsdS(NRC((RTR((s//usr/lib64/python2.7/unittest/test/test_case.pyRsRCRs!assertMultiLineEqual did not fail(RRRtassertMultiLineEqualR?RRR#(RRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyt!testAssertMultiLineEqualTruncatess  csjjdd_jd_jfddd}jj}j|d|dWdQXjd t|j j|d|ddd}d }j |_ jfd |d|d}}jj}j||WdQXj d t|j jt|j d ||fj|d|ddS(NiiicstdS(Nt_diffThreshold(tsetattr((t old_thresholdR(s//usr/lib64/python2.7/unittest/test/test_case.pytR uxiRRRSt^i cSstddS(Nsthis should not be raised(t SystemError(RR((s//usr/lib64/python2.7/unittest/test/test_case.pytexplodingTruncationscstdS(NR(R((t old_truncateR(s//usr/lib64/python2.7/unittest/test/test_case.pyRR s%r != %riiii( RRRXRt addCleanupR]R?RsRt exceptionRRt(RtstcmRRZR[((RRRs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertEqual_diffThresholds*        #c Csyt}|jdddgdddg|jdddgdddg|j||dddg|dd|df|jddddgddtdg|j|j|jddgdgd dgd ddg|j|j|jddddgddtdg|j|j|jd gd d g|j|j|jd d gd g|j|j|jd d d gd d g|jddgdd gd gtdd gddgg|jtddgdd gtddgdd g|j|j|jgtddddtg|jidd6idd6gidd6idd6g|jddtggtgddg|j|j|jgtgddddt g|j|j|jdggdgg|j|j|jdddgddg|j|j|jdddddgddtdg|j|j|jdidd6dtgidd6tdgdd hddhg}|ddd}|j||t t j j dd}ddddh}|j||t j j ggg}|j|dd gfgt t j jdd}ddddh}|j||dS(NiiiRCRtbazt2RRidi i iiRpy@y@RSitaaabccdtabbbcceRnR(iiRR(iiRS(iiRn(iiR(iiRR(iiRS(iiRn(iiR(RVtassertItemsEqualtTrueR]R?tFalsetitertdivmodRRRXRtutilt_count_diff_all_purposeRt_count_diff_hashable(RRRRStdiffsR1((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertItemsEqualsV "".(,":8("%-cCs*t}t}|j|||j|j|jd||j|j|jg||j|j|j|d|j|j|j|gtdg}t}|j|j|j||tdg}tdg}|j||tdg}tddg}|j|j|j||tdg}tddg}|j|j|j||tddg}tddg}|j||t}d}|j|j|j|||j|j|j||td d g}td g}|j|j|j||dS( NRRRSRCiiiiii(ii(ii(ii(RtassertSetEqualR]R?RXR(Rtset1tset2((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertSetEquals:    cCs4|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdddS( Niig?g?tbugtantubuguant(RtassertGreaterEqualRtassertLessEqualR]R?(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestInequality)scCsd}d}d}d|_xddfD]w}y |j||||Wq.|jk r}t|jdjddd}|j||kq.Xq.WdS( Nsxhttp://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] shttp://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. s- http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. cSs|S(N((Rp((s//usr/lib64/python2.7/unittest/test/test_case.pyRR cSs |jdS(Ntutf8(tdecode(Rp((s//usr/lib64/python2.7/unittest/test/test_case.pyRR Rs i(RXRRR?Rtencodetsplitt assertTrue(Rt sample_texttrevised_sample_texttsample_text_errort type_changerRterror((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertMultiLineEquals  %cCsrd}d}d}y|j||WnE|jk rm}t|jddd}|j||knXdS(Nuladen swallows fly slowlyuunladen swallows fly quicklysr- laden swallows fly slowly ? ^^^^ + unladen swallows fly quickly ? ++ ^^^^^ s i(RR?RRR(RRRRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAsertEqualSingleLinescCsP|jd|j|j|jt|jd|j|j|jddS(NsDjZoPloGears on Rails(RLRXR]R?RtassertIsNotNone(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsNones  cCs0|jdd|j|j|jdddS(Nt asdfabasdfsab+tsaaastaaaa(tassertRegexpMatchesR]R?(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRegexpMatchesscsdtfdYfd}|j||jtf||jttddd|j|j|jdWdQX|j|jt|WdQXdS(Nt ExceptionMockcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pytStubst19tbaseicSsdS(Ni((((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (t ExceptionR]R"tintR?(RR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesCallablesc sdtfdYfd}|j |WdQX|jtf}|WdQX|j|j|j|jjdd|jttdddWdQX|j|j|jWdQXWdQX|j|jt|WdQXdS( NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsis We expectRRi( RR]R"RGRRRRR?(RRR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesContexts   cskdtfdYfd}|jtjd||jd||jd|dS(NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRssexpect$uexpect$(RtassertRaisesRegexptretcompile(RR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesRegexps cCs||j|jd|jttjdd|j|jd|jtdd|j|jd|jtdddS(Ns^Exception not raised$RpcSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR cSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR uxcSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (RR?RRR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertNotRaisesRegexps       cCs6dtfdY}|jt|j|ddS(NtMyExccBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscSstS(N(R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (RR]RR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt#testAssertRaisesRegexpInvalidRegexpscCs|d}|j|jd|jtd||j|jd|jtd||j|jd|jttjd|dS(NcSstddS(Nt Unexpected(R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRss*"\^Expected\$" does not match "Unexpected"s ^Expected$u ^Expected$(RR?RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesRegexpMismatchs     csdtfdYfd}d}|j}|||WdQX|j}|j||j|jd|dS(NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscs|dS(N((RC(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRssparticular valuei(RR]RRGRR(RRtvtctxR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesExcValues cCsQ|jdd|jdd|jdd|jdd|jtdS(sTest undocumented method name synonyms. Please do not use these methods names in your own code. This test confirms their continued existence and functionality in order to avoid breaking existing code. iig@g@g@N(tassertNotEqualst assertEqualstassertAlmostEqualstassertNotAlmostEqualstassert_R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestSynonymAssertMethodNames(s cCstjr|jdd|jdd|jdd|jdd|jt|jt d|j t WdQXdS(sTest fail* methods pending deprecation, they will warn in 3.2. Do not use these methods. They will go away in 3.3. iig@g@g@cSsddS(NgQ @uspam((t_((s//usr/lib64/python2.7/unittest/test/test_case.pyRAR N( RR|t failIfEqualtfailUnlessEqualtfailUnlessAlmostEqualtfailIfAlmostEqualt failUnlessRtfailUnlessRaisesRtfailIfR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt!testPendingDeprecationMethodNames6s  cCs3dtjfdY}|d}t|dS(Nt TestableTestcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyt testNothingGs(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRFsR(RRR(RRR((s//usr/lib64/python2.7/unittest/test/test_case.pyt testDeepcopyDs csddddtjffdY}dtjffdY}dtjffdY}d tjffd Y}x@||||fD],}|jt|d jWdQXqWdS( NcSs tdS(N(tKeyboardInterrupt(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt_raisePscSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pytnothingRstTest1cseZZRS((R R ttest_something((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR UstTest2cseZZZRS((R R RR ((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR XstTest3cseZZZRS((R R R R((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR \stTest4cseZfdZRS(cs|jdS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR as(R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR`sR (RXRRR]RR0(RR R R Rtklass((RR s//usr/lib64/python2.7/unittest/test/test_case.pyttestKeyboardInterruptOs  ""csddddtjffdY}dtjffdY}dtjffdY}d tjffd Y}xe||||fD]Q}tj}|d j||jt|jd |j|jd qWdS( NcSs tdS(N(t SystemExit(R((s//usr/lib64/python2.7/unittest/test/test_case.pyRiscSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ksR cseZZRS((R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR nsR cseZZZRS((R R RR ((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR qsR cseZZZRS((R R R R((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR usRcseZfdZRS(cs|jdS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR zs(R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRysR i( RXRRR)R0RRterrorsttestsRun(RR R R RRR*((RR s//usr/lib64/python2.7/unittest/test/test_case.pyttestSystemExiths  "" cCsetjd}xOttjdD]:}tj|d|}tj|}|j||q#WdS(NR0itprotocol(RRRtpickletHIGHEST_PROTOCOLtdumpstloadsR(RRRt pickled_testtunpickled_test((s//usr/lib64/python2.7/unittest/test/test_case.pyt testPickles (FR R RRteq_pairsRtne_pairsRR R$R&R+R2R5R6R7R9R:R;R<R=RARBRDRERFRIRKRNRtskipIftsystflagstoptimizeRORPR\R_RaRdRfRvRRRRRRRRRRRRRRRRRRRRRRRRRRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyR,s!!                       % 4 '  $ > ( V $             t__main__(RRRRR tcopyRRRRtunittest.test.supportRRRRRVRRRR tmain(((s//usr/lib64/python2.7/unittest/test/test_case.pyts      "j PK!Ltest/test_case.pyonu[ {fc@sddlZddlZddlZddlZddlZddlmZddlmZddl Z ddl m Z m Z m Z mZdefdYZde je e fdYZed kre jndS( iN(tdeepcopy(t test_support(t TestEqualityt TestHashingt LoggingResultt#ResultWithNoStartTestRunStopTestRuntTestcBsVeZdZdejfdYZdefdYZdejfdYZRS(s5Keep these TestCase classes out of the main namespacetFoocBseZdZdZRS(cCsdS(N((tself((s//usr/lib64/python2.7/unittest/test/test_case.pytrunTesttcCsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyttest1R (t__name__t __module__R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRs tBarcBseZdZRS(cCsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyttest2R (R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRstLoggingTestCasecBs2eZdZdZdZdZdZRS(s!A test case which logs its calls.cCs&ttj|jd||_dS(Nttest(tsuperRRt__init__tevents(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyRscCs|jjddS(NtsetUp(Rtappend(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR"scCs|jjddS(NR(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR%scCs|jjddS(NttearDown(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR(s(R R t__doc__RRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyRs    (R R RtunittesttTestCaseRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyRst Test_TestCasecBseZejdejdfgZejdejdfejdejdfejdejdfgZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZejej j!dkddZ"ejej j!dkddZ#dZ$dZ%dZ&d Z'd!Z(d"Z)d#Z*d$Z+d%Z,d&Z-d'Z.d(Z/d)Z0d*Z1d+Z2d,Z3d-Z4d.Z5d/Z6d0Z7d1Z8d2Z9d3Z:d4Z;d5Z<d6Z=d7Z>d8Z?d9Z@d:ZAd;ZBd<ZCd=ZDd>ZERS(?R R RcCs:dtjfdY}|j|jdddS(NRcBseZdZdZRS(cSs tdS(N(t TypeError(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR HR cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRIR (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRGs is .Test.runTest(RRt assertEqualtid(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__no_test_nameFscCs=dtjfdY}|j|djdddS(NRcBseZdZdZRS(cSs tdS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR SR cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRTR (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRRs Ris .Test.test(RRRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__test_name__validQscCsLdtjfdY}y|dWntk r:nX|jddS(NRcBseZdZdZRS(cSs tdS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ^R cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR_R (R R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyR]s ttestfoosFailed to raise ValueError(RRt ValueErrortfail(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_init__test_name__invalid\s  cCs9dtjfdY}|j|djddS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRlR (R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRksRi(RRRtcountTestCases(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_countTestCasesjscCsEdtjfdY}|j}|jt|tjdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR vs(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRus(RRtdefaultTestResultRttypet TestResult(RRtresult((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_defaultTestResulttscsjg}t|}dtjffdY|j|ddddg}|j||dS(NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.setUp(RRt RuntimeError(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRst startTestRtaddErrortstopTest(RRRtrunR(RRR*texpected((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt#test_run_call_order__error_in_setUps  csag}dtjffdY|jddddddg}|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.setUp(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs t startTestRunR-RR.R/t stopTestRun(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt2test_run_call_order__error_in_setUp_default_results   cspg}t|}dtjffdYddddddg}|j||j||dS( NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.test(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRR.RR/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt"test_run_call_order__error_in_tests  csgg}dtjffdYddddddd d g}|j|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.test(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRR.RR/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt1test_run_call_order__error_in_test_default_results cspg}t|}dtjffdYddddddg}|j||j||dS( NRcseZfdZRS(cs$t|j|jddS(Nsraised by Foo.test(RRR#(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRt addFailureRR/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt$test_run_call_order__failure_in_tests  csgdtjffdYddddddd d g}g}|j|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs$t|j|jddS(Nsraised by Foo.test(RRR#(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRR8RR/R4(RRR0R(RR1R((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt3test_run_call_order__failure_in_test_default_results cspg}t|}dtjffdY|j|ddddddg}|j||dS( NRcseZfdZRS(cs#t|jtddS(Nsraised by Foo.tearDown(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsR-RRRR.R/(RRRR0R(RRR*R1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt&test_run_call_order__error_in_tearDowns  csgdtjffdYg}|jddddddd d g}|j||dS( NRcs eZdZfdZRS(cSs t|jS(N(RR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scs#t|jtddS(Nsraised by Foo.tearDown(RRR,(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRs R3R-RRRR.R/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt5test_run_call_order__error_in_tearDown_default_results cCs-dtjfdY}|djdS(NRcBseZdZdZRS(cSstS(N(R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR'scSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyRs(R R R'R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRs R(RRR0(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt"test_run_call_order_default_resultscCs6dtjfdY}|j|djtdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR%s(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyR$sR(RRtassertIstfailureExceptiontAssertionError(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_failureException__default#scCszg}t|}dtjfdY}|j|djt|dj|dddg}|j||dS(NRcBseZdZeZRS(cSs tdS(N(R,(R((s//usr/lib64/python2.7/unittest/test/test_case.pyR5s(R R RR,R?(((s//usr/lib64/python2.7/unittest/test/test_case.pyR4s RR-R8R/(RRRR>R?R,R0R(RRR*RR1((s//usr/lib64/python2.7/unittest/test/test_case.pyt2test_failureException__subclassing__explicit_raise0s cCszg}t|}dtjfdY}|j|djt|dj|dddg}|j||dS(NRcBseZdZeZRS(cSs|jddS(Ntfoo(R#(R((s//usr/lib64/python2.7/unittest/test/test_case.pyRLs(R R RR,R?(((s//usr/lib64/python2.7/unittest/test/test_case.pyRKs RR-R8R/(RRRR>R?R,R0R(RRR*RR1((s//usr/lib64/python2.7/unittest/test/test_case.pyt2test_failureException__subclassing__implicit_raiseGs cCs*dtjfdY}|jdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR [s(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRZs(RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt test_setUpYscCs*dtjfdY}|jdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ds(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRcs(RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt test_tearDownbscCs6dtjfdY}|j|jtdS(NRcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR rs(R R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRqs(RRtassertIsInstanceRt basestring(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttest_idpscsagdtjffdY}|djddddddg}|j|dS( NRcs&eZfdZfdZRS(csjddS(NR(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRscs tS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR's(R R RR'((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR~sRR3R-t addSuccessR/R4(RRR0R(RRR1((Rs//usr/lib64/python2.7/unittest/test/test_case.pyt test_run__uses_defaultTestResult{s   cCs|j|jdS(N(t assertIsNonetshortDescription(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt$testShortDescriptionWithoutDocstringsis)Docstrings are omitted with -O2 and abovecCs|j|jddS(s7Tests shortDescription() for a method with a docstring.N(RRM(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt(testShortDescriptionWithOneLineDocstrings cCs|j|jddS(sTests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is. s>Tests shortDescription() for a method with a longer docstring.N(RRM(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt*testShortDescriptionWithMultiLineDocstrings  csodtfdY}}|j||dfd}|j||j||dS(NtSadSnakecBseZdZRS(s)Dummy class for test_addTypeEqualityFunc.(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRQscs$t|t|ko!kSS(N(R((tatbtmsg(RQ(s//usr/lib64/python2.7/unittest/test/test_case.pytAllSnakesCreatedEquals(tobjecttassertNotEqualtNonetaddTypeEqualityFuncR(Rts1ts2RU((RQs//usr/lib64/python2.7/unittest/test/test_case.pyttestAddTypeEqualityFuncs cCs<t}|j|||j|j|j|tdS(N(RVR>t assertRaisesR?(Rtthing((s//usr/lib64/python2.7/unittest/test/test_case.pyt testAssertIss cCs<t}|j|t|j|j|j||dS(N(RVt assertIsNotR]R?(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsNots cCs6g}|j|t|j|j|j|tdS(N(RGtlistR]R?tdict(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsInstancescCs6g}|j|t|j|j|j|tdS(N(tassertNotIsInstanceRcR]R?Rb(RR^((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertNotIsInstancescCsKidd6dd6dd6}|jdd|jd d d d g|jd||jd d|jd d d d g|jd||j|j|jdd|j|j|jdd d d g|j|j|jd||j|j|jdd|j|j|jd d d d g|j|j|jd|dS(NtbananatmonkeytgrasstcowtfishtsealRRtabciiitditottertxitelephanttc(tassertInt assertNotInR]R?(Rtanimals((s//usr/lib64/python2.7/unittest/test/test_case.pyt testAssertIns%%cCs&|jii|jiidd6|jidd6idd6|jidd6idd6dd6|jidd6dd6idd6dd6|j|j|jidd6iWdQX|j|j#|jidd6idd6WdQX|j|j#|jidd6idd6WdQX|j|j*|jidd6dd6idd6WdQX|j|j*|jidd6dd6idd6WdQXtjdtf[djdtd D}|j|j#|ji|d 6id d 6WdQXWdQXdS( NiRRiRStoneRrR css|]}t|VqdS(N(tchr(t.0ti((s//usr/lib64/python2.7/unittest/test/test_case.pys siRCu�(tassertDictContainsSubsetR]R?Rtcheck_warningstUnicodeWarningtjointrange(RRw((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertDictContainsSubsets&%,$$++cCsd d fiifggfttfttfg}x|D]\}}y|j||Wn+|jk r|jd||fnXy|j||ddWn+|jk r|jd||fnXy|j||dWqF|jk r |jd||fqFXqFWd gfitftddgtddgftdd gtdd gftd dgtd dgfg}xq|D]i\}}|j|j|j|||j|j|j||d|j|j|j||ddqWdS(NsassertEqual(%r, %r) failedRTRCs$assertEqual(%r, %r) with msg= faileds/assertEqual(%r, %r) with third parameter failediiiii((((tsett frozensetRR?R#R](Rt equal_pairsRRRSt unequal_pairs((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertEquals<      !!'cCs|jgg|jdd|jgdddgg}g}|jtjj|j|||jtjj|jt|t||jtjj|j|t||j||j|||jt|t||j|t||jt|||j|j|j|t||j|j|jt|||j|j|jd||j|j|jdt||j|j|jdt||j|j|jdd|j|j|jdd|j|j|jdd|j iiidd6}i}|jtjj|j |||j ||j ||d|d<|jtjj|j ||d|j|j|j d||j|j|j g||j|j|j dddS( NiRRiRpsThese are unequal(((( tassertListEqualtassertTupleEqualtassertSequenceEqualR]RRR?ttupletextendRXtassertDictEqualtupdate(RRRRSRrRn((s//usr/lib64/python2.7/unittest/test/test_case.pyt testEqualitysT      cCs|j|jd ddd }ddd }djtjtj|jtj|j}tj j t |df}t |d|_y|j ||Wn#|j k r}|jd }nX|jd |jt |t ||j||t |d|_y|j ||Wn#|j k rW}|jd }nX|jd |jt |t ||j||d|_y|j ||Wn#|j k r}|jd }nX|jd |jt |t ||j||dS(NiPiRRRpiRSs iis!assertSequenceEqual did not fail.iii(RtmaxDiffR~tdifflibtndifftpprinttpformatt splitlinesRtcaset DIFF_OMITTEDtlenRR?targsR#t assertLessRst assertGreaterRtRX(Rtseq1tseq2tdifftomittedteRT((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertSequenceEqualMaxDiffRs<    cCsd|_|jdd}tjjtd}|j|d|d|_|jdd}|j|dd|_|jdd}|j|ddS(NiRCtbartfoobari(Rt_truncateMessageRRRRRRX(RtmessageR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestTruncateMessageys   cCs|tjd}d}||_y|jiidd6Wn,|jk rj}|jt|dnX|jddS(NRcSsdS(NRC((RTR((s//usr/lib64/python2.7/unittest/test/test_case.pyttruncatesiiRCsassertDictEqual did not fail(RRRRR?RtstrR#(RRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertDictEqualTruncatess  cCsutjd}d}||_y|jddWn,|jk rc}|jt|dnX|jddS(NRcSsdS(NRC((RTR((s//usr/lib64/python2.7/unittest/test/test_case.pyRsRCRs!assertMultiLineEqual did not fail(RRRtassertMultiLineEqualR?RRR#(RRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyt!testAssertMultiLineEqualTruncatess  csjjdd_jd_jfddd}jj}j|d|dWdQXjd t|j j|d|ddd}d }j |_ jfd |d|d}}jj}j||WdQXj d t|j jt|j d ||fj|d|ddS(NiiicstdS(Nt_diffThreshold(tsetattr((t old_thresholdR(s//usr/lib64/python2.7/unittest/test/test_case.pytR uxiRRRSt^i cSstddS(Nsthis should not be raised(t SystemError(RR((s//usr/lib64/python2.7/unittest/test/test_case.pytexplodingTruncationscstdS(NR(R((t old_truncateR(s//usr/lib64/python2.7/unittest/test/test_case.pyRR s%r != %riiii( RRRXRt addCleanupR]R?RsRt exceptionRRt(RtstcmRRZR[((RRRs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertEqual_diffThresholds*        #c Csyt}|jdddgdddg|jdddgdddg|j||dddg|dd|df|jddddgddtdg|j|j|jddgdgd dgd ddg|j|j|jddddgddtdg|j|j|jd gd d g|j|j|jd d gd g|j|j|jd d d gd d g|jddgdd gd gtdd gddgg|jtddgdd gtddgdd g|j|j|jgtddddtg|jidd6idd6gidd6idd6g|jddtggtgddg|j|j|jgtgddddt g|j|j|jdggdgg|j|j|jdddgddg|j|j|jdddddgddtdg|j|j|jdidd6dtgidd6tdgdd hddhg}|ddd}|j||t t j j dd}ddddh}|j||t j j ggg}|j|dd gfgt t j jdd}ddddh}|j||dS(NiiiRCRtbazt2RRidi i iiRpy@y@RSitaaabccdtabbbcceRnR(iiRR(iiRS(iiRn(iiR(iiRR(iiRS(iiRn(iiR(RVtassertItemsEqualtTrueR]R?tFalsetitertdivmodRRRXRtutilt_count_diff_all_purposeRt_count_diff_hashable(RRRRStdiffsR1((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertItemsEqualsV "".(,":8("%-cCs*t}t}|j|||j|j|jd||j|j|jg||j|j|j|d|j|j|j|gtdg}t}|j|j|j||tdg}tdg}|j||tdg}tddg}|j|j|j||tdg}tddg}|j|j|j||tddg}tddg}|j||t}d}|j|j|j|||j|j|j||td d g}td g}|j|j|j||dS( NRRRSRCiiiiii(ii(ii(ii(RtassertSetEqualR]R?RXR(Rtset1tset2((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertSetEquals:    cCs4|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdd|j|j|jdddS( Niig?g?tbugtantubuguant(RtassertGreaterEqualRtassertLessEqualR]R?(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestInequality)scCsd}d}d}d|_xddfD]w}y |j||||Wq.|jk r}t|jdjddd}|j||kq.Xq.WdS( Nsxhttp://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] shttp://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. s- http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. cSs|S(N((Rp((s//usr/lib64/python2.7/unittest/test/test_case.pyRR cSs |jdS(Ntutf8(tdecode(Rp((s//usr/lib64/python2.7/unittest/test/test_case.pyRR Rs i(RXRRR?Rtencodetsplitt assertTrue(Rt sample_texttrevised_sample_texttsample_text_errort type_changerRterror((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertMultiLineEquals  %cCsrd}d}d}y|j||WnE|jk rm}t|jddd}|j||knXdS(Nuladen swallows fly slowlyuunladen swallows fly quicklysr- laden swallows fly slowly ? ^^^^ + unladen swallows fly quickly ? ++ ^^^^^ s i(RR?RRR(RRRRRR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAsertEqualSingleLinescCsP|jd|j|j|jt|jd|j|j|jddS(NsDjZoPloGears on Rails(RLRXR]R?RtassertIsNotNone(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertIsNones  cCs0|jdd|j|j|jdddS(Nt asdfabasdfsab+tsaaastaaaa(tassertRegexpMatchesR]R?(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRegexpMatchesscsdtfdYfd}|j||jtf||jttddd|j|j|jdWdQX|j|jt|WdQXdS(Nt ExceptionMockcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pytStubst19tbaseicSsdS(Ni((((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (t ExceptionR]R"tintR?(RR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesCallablesc sdtfdYfd}|j |WdQX|jtf}|WdQX|j|j|j|jjdd|jttdddWdQX|j|j|jWdQXWdQX|j|jt|WdQXdS( NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRsis We expectRRi( RR]R"RGRRRRR?(RRR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesContexts   cskdtfdYfd}|jtjd||jd||jd|dS(NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscsddS(Ns We expect(((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRssexpect$uexpect$(RtassertRaisesRegexptretcompile(RR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesRegexps cCs||j|jd|jttjdd|j|jd|jtdd|j|jd|jtdddS(Ns^Exception not raised$RpcSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR cSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR uxcSsdS(N(RX(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (RR?RRR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertNotRaisesRegexps       cCs6dtfdY}|jt|j|ddS(NtMyExccBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscSstS(N(R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRR (RR]RR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyt#testAssertRaisesRegexpInvalidRegexpscCs|d}|j|jd|jtd||j|jd|jtd||j|jd|jttjd|dS(NcSstddS(Nt Unexpected(R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRss*"\^Expected\$" does not match "Unexpected"s ^Expected$u ^Expected$(RR?RRR(RR((s//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesRegexpMismatchs     csdtfdYfd}d}|j}|||WdQX|j}|j||j|jd|dS(NRcBseZRS((R R (((s//usr/lib64/python2.7/unittest/test/test_case.pyRscs|dS(N((RC(R(s//usr/lib64/python2.7/unittest/test/test_case.pyRssparticular valuei(RR]RRGRR(RRtvtctxR((Rs//usr/lib64/python2.7/unittest/test/test_case.pyttestAssertRaisesExcValues cCsQ|jdd|jdd|jdd|jdd|jtdS(sTest undocumented method name synonyms. Please do not use these methods names in your own code. This test confirms their continued existence and functionality in order to avoid breaking existing code. iig@g@g@N(tassertNotEqualst assertEqualstassertAlmostEqualstassertNotAlmostEqualstassert_R(R((s//usr/lib64/python2.7/unittest/test/test_case.pyttestSynonymAssertMethodNames(s cCstjr|jdd|jdd|jdd|jdd|jt|jt d|j t WdQXdS(sTest fail* methods pending deprecation, they will warn in 3.2. Do not use these methods. They will go away in 3.3. iig@g@g@cSsddS(NgQ @uspam((t_((s//usr/lib64/python2.7/unittest/test/test_case.pyRAR N( RR|t failIfEqualtfailUnlessEqualtfailUnlessAlmostEqualtfailIfAlmostEqualt failUnlessRtfailUnlessRaisesRtfailIfR(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt!testPendingDeprecationMethodNames6s  cCs3dtjfdY}|d}t|dS(Nt TestableTestcBseZdZRS(cSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyt testNothingGs(R R R(((s//usr/lib64/python2.7/unittest/test/test_case.pyRFsR(RRR(RRR((s//usr/lib64/python2.7/unittest/test/test_case.pyt testDeepcopyDs csddddtjffdY}dtjffdY}dtjffdY}d tjffd Y}x@||||fD],}|jt|d jWdQXqWdS( NcSs tdS(N(tKeyboardInterrupt(R((s//usr/lib64/python2.7/unittest/test/test_case.pyt_raisePscSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pytnothingRstTest1cseZZRS((R R ttest_something((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR UstTest2cseZZZRS((R R RR ((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR XstTest3cseZZZRS((R R R R((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR \stTest4cseZfdZRS(cs|jdS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR as(R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR`sR (RXRRR]RR0(RR R R Rtklass((RR s//usr/lib64/python2.7/unittest/test/test_case.pyttestKeyboardInterruptOs  ""csddddtjffdY}dtjffdY}dtjffdY}d tjffd Y}xe||||fD]Q}tj}|d j||jt|jd |j|jd qWdS( NcSs tdS(N(t SystemExit(R((s//usr/lib64/python2.7/unittest/test/test_case.pyRiscSsdS(N((R((s//usr/lib64/python2.7/unittest/test/test_case.pyR ksR cseZZRS((R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyR nsR cseZZZRS((R R RR ((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR qsR cseZZZRS((R R R R((RR (s//usr/lib64/python2.7/unittest/test/test_case.pyR usRcseZfdZRS(cs|jdS(N(R(R(R(s//usr/lib64/python2.7/unittest/test/test_case.pyR zs(R R R ((R(s//usr/lib64/python2.7/unittest/test/test_case.pyRysR i( RXRRR)R0RRterrorsttestsRun(RR R R RRR*((RR s//usr/lib64/python2.7/unittest/test/test_case.pyttestSystemExiths  "" cCsetjd}xOttjdD]:}tj|d|}tj|}|j||q#WdS(NR0itprotocol(RRRtpickletHIGHEST_PROTOCOLtdumpstloadsR(RRRt pickled_testtunpickled_test((s//usr/lib64/python2.7/unittest/test/test_case.pyt testPickles (FR R RRteq_pairsRtne_pairsRR R$R&R+R2R5R6R7R9R:R;R<R=RARBRDRERFRIRKRNRtskipIftsystflagstoptimizeRORPR\R_RaRdRfRvRRRRRRRRRRRRRRRRRRRRRRRRRRRR(((s//usr/lib64/python2.7/unittest/test/test_case.pyR,s!!                       % 4 '  $ > ( V $             t__main__(RRRRR tcopyRRRRtunittest.test.supportRRRRRVRRRR tmain(((s//usr/lib64/python2.7/unittest/test/test_case.pyts      "j PK!77test/test_discovery.pynu[import os import re import sys import unittest import unittest.test class TestDiscovery(unittest.TestCase): # Heavily mocked tests so I can avoid hitting the filesystem def test_get_name_from_path(self): loader = unittest.TestLoader() loader._top_level_dir = '/foo' name = loader._get_name_from_path('/foo/bar/baz.py') self.assertEqual(name, 'bar.baz') if not __debug__: # asserts are off return with self.assertRaises(AssertionError): loader._get_name_from_path('/bar/baz.py') def test_find_tests(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir', 'test.foo', 'test-not-a-module.py', 'another_dir'], ['test3.py', 'test4.py', ]] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) def isdir(path): return path.endswith('dir') os.path.isdir = isdir self.addCleanup(restore_isdir) def isfile(path): # another_dir is not a package and so shouldn't be recursed into return not path.endswith('dir') and not 'another_dir' in path os.path.isfile = isfile self.addCleanup(restore_isfile) loader._get_module_from_name = lambda path: path + ' module' loader.loadTestsFromModule = lambda module: module + ' tests' top_level = os.path.abspath('/foo') loader._top_level_dir = top_level suite = list(loader._find_tests(top_level, 'test*.py')) expected = [name + ' module tests' for name in ('test1', 'test2')] expected.extend([('test_dir.%s' % name) + ' module tests' for name in ('test3', 'test4')]) self.assertEqual(suite, expected) def test_find_tests_with_package(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir directories = ['a_directory', 'test_directory', 'test_directory2'] path_lists = [directories, [], [], []] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) os.path.isdir = lambda path: True self.addCleanup(restore_isdir) os.path.isfile = lambda path: os.path.basename(path) not in directories self.addCleanup(restore_isfile) class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path self.paths.append(path) if os.path.basename(path) == 'test_directory': def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) return 'load_tests' self.load_tests = load_tests def __eq__(self, other): return self.path == other.path # Silence py3k warning __hash__ = None loader._get_module_from_name = lambda name: Module(name) def loadTestsFromModule(module, use_load_tests): if use_load_tests: raise self.failureException('use_load_tests should be False for packages') return module.path + ' module tests' loader.loadTestsFromModule = loadTestsFromModule loader._top_level_dir = '/foo' # this time no '.py' on the pattern so that it can match # a test package suite = list(loader._find_tests('/foo', 'test*')) # We should have loaded tests from the test_directory package by calling load_tests # and directly from the test_directory2 package self.assertEqual(suite, ['load_tests', 'test_directory2' + ' module tests']) self.assertEqual(Module.paths, ['test_directory', 'test_directory2']) # load_tests should have been called once with loader, tests and pattern self.assertEqual(Module.load_tests_args, [(loader, 'test_directory' + ' module tests', 'test*')]) def test_discover(self): loader = unittest.TestLoader() original_isfile = os.path.isfile original_isdir = os.path.isdir def restore_isfile(): os.path.isfile = original_isfile os.path.isfile = lambda path: False self.addCleanup(restore_isfile) orig_sys_path = sys.path[:] def restore_path(): sys.path[:] = orig_sys_path self.addCleanup(restore_path) full_path = os.path.abspath(os.path.normpath('/foo')) with self.assertRaises(ImportError): loader.discover('/foo/bar', top_level_dir='/foo') self.assertEqual(loader._top_level_dir, full_path) self.assertIn(full_path, sys.path) os.path.isfile = lambda path: True os.path.isdir = lambda path: True def restore_isdir(): os.path.isdir = original_isdir self.addCleanup(restore_isdir) _find_tests_args = [] def _find_tests(start_dir, pattern): _find_tests_args.append((start_dir, pattern)) return ['tests'] loader._find_tests = _find_tests loader.suiteClass = str suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar') top_level_dir = os.path.abspath('/foo/bar') start_dir = os.path.abspath('/foo/bar/baz') self.assertEqual(suite, "['tests']") self.assertEqual(loader._top_level_dir, top_level_dir) self.assertEqual(_find_tests_args, [(start_dir, 'pattern')]) self.assertIn(top_level_dir, sys.path) def test_discover_with_modules_that_fail_to_import(self): loader = unittest.TestLoader() listdir = os.listdir os.listdir = lambda _: ['test_this_does_not_exist.py'] isfile = os.path.isfile os.path.isfile = lambda _: True orig_sys_path = sys.path[:] def restore(): os.path.isfile = isfile os.listdir = listdir sys.path[:] = orig_sys_path self.addCleanup(restore) suite = loader.discover('.') self.assertIn(os.getcwd(), sys.path) self.assertEqual(suite.countTestCases(), 1) test = list(list(suite)[0])[0] # extract test from suite with self.assertRaises(ImportError): test.test_this_does_not_exist() def test_command_line_handling_parseArgs(self): # Haha - take that uninstantiable class program = object.__new__(unittest.TestProgram) args = [] def do_discovery(argv): args.extend(argv) program._do_discovery = do_discovery program.parseArgs(['something', 'discover']) self.assertEqual(args, []) program.parseArgs(['something', 'discover', 'foo', 'bar']) self.assertEqual(args, ['foo', 'bar']) def test_command_line_handling_do_discovery_too_many_arguments(self): class Stop(Exception): pass def usageExit(): raise Stop program = object.__new__(unittest.TestProgram) program.usageExit = usageExit program.testLoader = None with self.assertRaises(Stop): # too many args program._do_discovery(['one', 'two', 'three', 'four']) def test_command_line_handling_do_discovery_uses_default_loader(self): program = object.__new__(unittest.TestProgram) class Loader(object): args = [] def discover(self, start_dir, pattern, top_level_dir): self.args.append((start_dir, pattern, top_level_dir)) return 'tests' program.testLoader = Loader() program._do_discovery(['-v']) self.assertEqual(Loader.args, [('.', 'test*.py', None)]) def test_command_line_handling_do_discovery_calls_loader(self): program = object.__new__(unittest.TestProgram) class Loader(object): args = [] def discover(self, start_dir, pattern, top_level_dir): self.args.append((start_dir, pattern, top_level_dir)) return 'tests' program._do_discovery(['-v'], Loader=Loader) self.assertEqual(program.verbosity, 2) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['--verbose'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery([], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['fish', 'eggs'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['-s', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['-t', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')]) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['-p', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'fish', None)]) self.assertFalse(program.failfast) self.assertFalse(program.catchbreak) Loader.args = [] program = object.__new__(unittest.TestProgram) program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f', '-c'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) self.assertEqual(program.verbosity, 2) self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) def setup_module_clash(self): class Module(object): __file__ = 'bar/foo.py' sys.modules['foo'] = Module full_path = os.path.abspath('foo') original_listdir = os.listdir original_isfile = os.path.isfile original_isdir = os.path.isdir def cleanup(): os.listdir = original_listdir os.path.isfile = original_isfile os.path.isdir = original_isdir del sys.modules['foo'] if full_path in sys.path: sys.path.remove(full_path) self.addCleanup(cleanup) def listdir(_): return ['foo.py'] def isfile(_): return True def isdir(_): return True os.listdir = listdir os.path.isfile = isfile os.path.isdir = isdir return full_path def test_detect_module_clash(self): full_path = self.setup_module_clash() loader = unittest.TestLoader() mod_dir = os.path.abspath('bar') expected_dir = os.path.abspath('foo') msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " "Is this module globally installed?" % (mod_dir, expected_dir)) self.assertRaisesRegexp( ImportError, '^%s$' % msg, loader.discover, start_dir='foo', pattern='foo.py' ) self.assertEqual(sys.path[0], full_path) def test_module_symlink_ok(self): full_path = self.setup_module_clash() original_realpath = os.path.realpath mod_dir = os.path.abspath('bar') expected_dir = os.path.abspath('foo') def cleanup(): os.path.realpath = original_realpath self.addCleanup(cleanup) def realpath(path): if path == os.path.join(mod_dir, 'foo.py'): return os.path.join(expected_dir, 'foo.py') return path os.path.realpath = realpath loader = unittest.TestLoader() loader.discover(start_dir='foo', pattern='foo.py') def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _find_tests(start_dir, pattern): self.wasRun = True self.assertEqual(start_dir, expectedPath) return tests loader._find_tests = _find_tests suite = loader.discover('unittest.test') self.assertTrue(self.wasRun) self.assertEqual(suite._tests, tests) if __name__ == '__main__': unittest.main() PK!CVEEtest/test_discovery.pycnu[ {fc@srddlZddlZddlZddlZddlZdejfdYZedkrnejndS(iNt TestDiscoverycBs}eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d ZRS( cCsetj}d|_|jd}|j|dts>dS|jt|jdWdQXdS(Ns/foos/foo/bar/baz.pysbar.bazs /bar/baz.py(tunittestt TestLoadert_top_level_dirt_get_name_from_patht assertEqualt __debug__t assertRaisestAssertionError(tselftloadertname((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_get_name_from_path s  c stj}tjfd}tjjfd}tjjfd}dddddd d gd d ggfd t_|j|d}|tj_|j|d}|tj_|j|d|_d|_ tjj d}||_ t |j |d}gdD]} | d^q6} | jgdD]} d| d^qY|j|| dS(Ncs t_dS(N(tostlistdir((toriginal_listdir(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestore_listdirscstj_dS(N(R tpathtisfile((toriginal_isfile(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestore_isfile!scstj_dS(N(R Rtisdir((toriginal_isdir(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt restore_isdir$sstest1.pystest2.pys not_a_test.pyttest_dirstest.foostest-not-a-module.pyt another_dirstest3.pystest4.pycs jdS(Ni(tpop(R(t path_lists(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt*tcSs |jdS(Ntdir(tendswith(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR-scSs|jd od|kS(NRR(R(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR2scSs|dS(Ns module((R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR8RcSs|dS(Ns tests((tmodule((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR9Rs/foostest*.pyttest1ttest2s module teststtest3ttest4s test_dir.%s(R!R"(R#R$(RRR RRRRt addCleanupt_get_module_from_nametloadTestsFromModuletabspathRtlistt _find_teststextendR( R R RRRRRt top_leveltsuiteR texpected((RRRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_find_testss8                 cstj}tjfd}tjjfd}tjjfd}dddgggggfdt_j|dtj_j|fd tj_j|d tfd Yfd |_ fd }||_ d|_ t |j dd}j|dddgjjddgjj|dddfgdS(Ncs t_dS(N(R R((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRIscstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRLscstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyROst a_directoryttest_directoryttest_directory2cs jdS(Ni(R(R(R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRTRcSstS(N(tTrue(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRWRcstjj|kS(N(R Rtbasename(R(t directories(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRZRtModulecBs,eZgZgZdZdZdZRS(csP|_jj|tjj|dkrLfd}|_ndS(NR1csjj|||fdS(Nt load_tests(tload_tests_argstappend(R tteststpattern(R (s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR7es(RtpathsR9R R4R7(R RR7((R s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt__init__as  cSs|j|jkS(N(R(R tother((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt__eq__jsN(t__name__t __module__R<R8R=R?tNonet__hash__(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR6]s  cs |S(N((R (R6(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRpRcs#|rjdn|jdS(Ns+use_load_tests should be False for packagess module tests(tfailureExceptionR(R tuse_load_tests(R (s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR'qss/foostest*R7s module tests(RRR RRRRR%tobjectR&R'RR)R*RR<R8(R R RRRR'R-((R6R5RRRRR s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_find_tests_with_packageEs4           c stj}tjjtjjfd}dtj_|j|tjfd}|j|tjjtjj d}|j t |j dddWdQX|j |j||j|tjdtj_dtj_fd }|j|gfd }||_t|_|j d d d}tjjd}tjjd } |j |d |j |j||j | d fg|j|tjdS(Ncstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRscSstS(N(tFalse(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcstj(dS(N(tsysR((t orig_sys_path(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt restore_pathss/foos/foo/bart top_level_dircSstS(N(R3(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcSstS(N(R3(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRscsj||fdgS(NR:(R9(t start_dirR;(t_find_tests_args(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR*ss /foo/bar/bazR;s ['tests'](RRR RRRR%RIR(tnormpathRt ImportErrortdiscoverRRtassertInR*tstrt suiteClass( R R RRKt full_pathRR*R-RLRM((RNRJRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyt test_discovers:         cstj}tjdt_tjjdtj_tjfd}|j||jd}|j tj tj|j |j dt t |dd}|jt|jWdQXdS(NcSsdgS(Nstest_this_does_not_exist.py((t_((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcSstS(N(R3(RW((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcs#tj_t_tj(dS(N(R RRRRI((RRRJ(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestores  t.ii(RRR RRRRIR%RQRRtgetcwdRtcountTestCasesR)RRPttest_this_does_not_exist(R R RXR-ttest((RRRJs4/usr/lib64/python2.7/unittest/test/test_discovery.pyt.test_discover_with_modules_that_fail_to_imports      cstjtj}gfd}||_|jddg|jg|jddddg|jddgdS(Ncsj|dS(N(R+(targv(targs(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt do_discoveryst somethingRQtfootbar(RFt__new__Rt TestProgramt _do_discoveryt parseArgsR(R tprogramRa((R`s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt$test_command_line_handling_parseArgss c s|dtfdYfd}tjtj}||_d|_|j|j ddddgWdQXdS(NtStopcBseZRS((R@RA(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRkscs dS(N(((Rk(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt usageExitstonettwotthreetfour( t ExceptionRFReRRfRlRBt testLoaderRRg(R RlRi((Rks4/usr/lib64/python2.7/unittest/test/test_discovery.pyt:test_command_line_handling_do_discovery_too_many_argumentss  cCs^tjtj}dtfdY}||_|jdg|j|jdgdS(NtLoadercBseZgZdZRS(cSs|jj|||fdS(NR:(R`R9(R RMR;RL((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRQs(R@RAR`RQ(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRtss-vRYstest*.py(RYstest*.pyN( RFReRRfRrRgRR`RB(R RiRt((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt;test_command_line_handling_do_discovery_uses_default_loaders  cCstjtj}dtfdY}|jdgd||j|jd|j|jd|j|jdgg|_tjtj}|jdgd||j|jd|j|jdgg|_tjtj}|jgd||j|jd|j|jdgg|_tjtj}|jd gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jd d d gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jdd gd||j|jd|j|jdg|j |j |j |j g|_tjtj}|jdd d d dddgd||j|jd|j|jdg|j|jd|j |j |j |j dS(NRtcBseZgZdZRS(cSs|jj|||fdS(NR:(R`R9(R RMR;RL((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRQs(R@RAR`RQ(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRtss-viR:RYstest*.pys --verbosetfishteggsthams-ss-ts-ps-fs-c(RYstest*.pyN(RYstest*.pyN(RYstest*.pyN(Rvstest*.pyN(RvRwN(RvRwRx(Rvstest*.pyN(RYstest*.pyRv(RYRvN(RvRwN(RFReRRfRgRt verbosityR]R`RBt assertFalsetfailfastt catchbreakt assertTrue(R RiRt((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt4test_command_line_handling_do_discovery_calls_loadersr         !csdtfdY}|tjds           cCs|j}tj}tjjd}tjjd}tjd||f}|jt d||j dddd|j t jd|dS( NRdRcsZ'foo' module incorrectly imported from %r. Expected %r. Is this module globally installed?s^%s$RMR;sfoo.pyi( RRRR RR(tretescapetassertRaisesRegexpRPRQRRI(R RUR tmod_dirt expected_dirtmsg((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_detect_module_clash[s    cs|j}tjjtjjdtjjdfd}|j|fd}|tj_tj}|jdddddS(NRdRccstj_dS(N(R Rtrealpath((toriginal_realpath(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRqscs2|tjjdkr.tjjdS|S(Nsfoo.py(R Rtjoin(R(RR(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRusRMR;sfoo.py( RR RRR(R%RRRQ(R RURRR ((RRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_module_symlink_okis     cstj}gtjjtjjtjjt_ fd}||_ |j d}j j j |jdS(Ncst_j|S(N(R3twasRunR(RMR;(t expectedPathR R:(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR*s s unittest.test(RRR RR(tdirnameR]RRHRR*RQR}Rt_tests(R R R*R-((RR R:s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_discovery_from_dotted_path}s  $  (R@RAR R/RGRVR^RjRsRuR~RRRR(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR s  + A .    J   t__main__( R RRIRt unittest.testtTestCaseRR@tmain(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyts      PK!CVEEtest/test_discovery.pyonu[ {fc@srddlZddlZddlZddlZddlZdejfdYZedkrnejndS(iNt TestDiscoverycBs}eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d ZRS( cCsetj}d|_|jd}|j|dts>dS|jt|jdWdQXdS(Ns/foos/foo/bar/baz.pysbar.bazs /bar/baz.py(tunittestt TestLoadert_top_level_dirt_get_name_from_patht assertEqualt __debug__t assertRaisestAssertionError(tselftloadertname((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_get_name_from_path s  c stj}tjfd}tjjfd}tjjfd}dddddd d gd d ggfd t_|j|d}|tj_|j|d}|tj_|j|d|_d|_ tjj d}||_ t |j |d}gdD]} | d^q6} | jgdD]} d| d^qY|j|| dS(Ncs t_dS(N(tostlistdir((toriginal_listdir(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestore_listdirscstj_dS(N(R tpathtisfile((toriginal_isfile(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestore_isfile!scstj_dS(N(R Rtisdir((toriginal_isdir(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt restore_isdir$sstest1.pystest2.pys not_a_test.pyttest_dirstest.foostest-not-a-module.pyt another_dirstest3.pystest4.pycs jdS(Ni(tpop(R(t path_lists(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt*tcSs |jdS(Ntdir(tendswith(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR-scSs|jd od|kS(NRR(R(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR2scSs|dS(Ns module((R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR8RcSs|dS(Ns tests((tmodule((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR9Rs/foostest*.pyttest1ttest2s module teststtest3ttest4s test_dir.%s(R!R"(R#R$(RRR RRRRt addCleanupt_get_module_from_nametloadTestsFromModuletabspathRtlistt _find_teststextendR( R R RRRRRt top_leveltsuiteR texpected((RRRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_find_testss8                 cstj}tjfd}tjjfd}tjjfd}dddgggggfdt_j|dtj_j|fd tj_j|d tfd Yfd |_ fd }||_ d|_ t |j dd}j|dddgjjddgjj|dddfgdS(Ncs t_dS(N(R R((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRIscstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRLscstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyROst a_directoryttest_directoryttest_directory2cs jdS(Ni(R(R(R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRTRcSstS(N(tTrue(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRWRcstjj|kS(N(R Rtbasename(R(t directories(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRZRtModulecBs,eZgZgZdZdZdZRS(csP|_jj|tjj|dkrLfd}|_ndS(NR1csjj|||fdS(Nt load_tests(tload_tests_argstappend(R tteststpattern(R (s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR7es(RtpathsR9R R4R7(R RR7((R s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt__init__as  cSs|j|jkS(N(R(R tother((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt__eq__jsN(t__name__t __module__R<R8R=R?tNonet__hash__(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR6]s  cs |S(N((R (R6(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRpRcs#|rjdn|jdS(Ns+use_load_tests should be False for packagess module tests(tfailureExceptionR(R tuse_load_tests(R (s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR'qss/foostest*R7s module tests(RRR RRRRR%tobjectR&R'RR)R*RR<R8(R R RRRR'R-((R6R5RRRRR s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_find_tests_with_packageEs4           c stj}tjjtjjfd}dtj_|j|tjfd}|j|tjjtjj d}|j t |j dddWdQX|j |j||j|tjdtj_dtj_fd }|j|gfd }||_t|_|j d d d}tjjd}tjjd } |j |d |j |j||j | d fg|j|tjdS(Ncstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRscSstS(N(tFalse(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcstj(dS(N(tsysR((t orig_sys_path(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt restore_pathss/foos/foo/bart top_level_dircSstS(N(R3(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcSstS(N(R3(R((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcstj_dS(N(R RR((R(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRscsj||fdgS(NR:(R9(t start_dirR;(t_find_tests_args(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR*ss /foo/bar/bazR;s ['tests'](RRR RRRR%RIR(tnormpathRt ImportErrortdiscoverRRtassertInR*tstrt suiteClass( R R RRKt full_pathRR*R-RLRM((RNRJRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyt test_discovers:         cstj}tjdt_tjjdtj_tjfd}|j||jd}|j tj tj|j |j dt t |dd}|jt|jWdQXdS(NcSsdgS(Nstest_this_does_not_exist.py((t_((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcSstS(N(R3(RW((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRRcs#tj_t_tj(dS(N(R RRRRI((RRRJ(s4/usr/lib64/python2.7/unittest/test/test_discovery.pytrestores  t.ii(RRR RRRRIR%RQRRtgetcwdRtcountTestCasesR)RRPttest_this_does_not_exist(R R RXR-ttest((RRRJs4/usr/lib64/python2.7/unittest/test/test_discovery.pyt.test_discover_with_modules_that_fail_to_imports      cstjtj}gfd}||_|jddg|jg|jddddg|jddgdS(Ncsj|dS(N(R+(targv(targs(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt do_discoveryst somethingRQtfootbar(RFt__new__Rt TestProgramt _do_discoveryt parseArgsR(R tprogramRa((R`s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt$test_command_line_handling_parseArgss c s|dtfdYfd}tjtj}||_d|_|j|j ddddgWdQXdS(NtStopcBseZRS((R@RA(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRkscs dS(N(((Rk(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt usageExitstonettwotthreetfour( t ExceptionRFReRRfRlRBt testLoaderRRg(R RlRi((Rks4/usr/lib64/python2.7/unittest/test/test_discovery.pyt:test_command_line_handling_do_discovery_too_many_argumentss  cCs^tjtj}dtfdY}||_|jdg|j|jdgdS(NtLoadercBseZgZdZRS(cSs|jj|||fdS(NR:(R`R9(R RMR;RL((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRQs(R@RAR`RQ(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRtss-vRYstest*.py(RYstest*.pyN( RFReRRfRrRgRR`RB(R RiRt((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt;test_command_line_handling_do_discovery_uses_default_loaders  cCstjtj}dtfdY}|jdgd||j|jd|j|jd|j|jdgg|_tjtj}|jdgd||j|jd|j|jdgg|_tjtj}|jgd||j|jd|j|jdgg|_tjtj}|jd gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jd d d gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jd d gd||j|jd|j|jdgg|_tjtj}|jdd gd||j|jd|j|jdg|j |j |j |j g|_tjtj}|jdd d d dddgd||j|jd|j|jdg|j|jd|j |j |j |j dS(NRtcBseZgZdZRS(cSs|jj|||fdS(NR:(R`R9(R RMR;RL((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRQs(R@RAR`RQ(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRtss-viR:RYstest*.pys --verbosetfishteggsthams-ss-ts-ps-fs-c(RYstest*.pyN(RYstest*.pyN(RYstest*.pyN(Rvstest*.pyN(RvRwN(RvRwRx(Rvstest*.pyN(RYstest*.pyRv(RYRvN(RvRwN(RFReRRfRgRt verbosityR]R`RBt assertFalsetfailfastt catchbreakt assertTrue(R RiRt((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyt4test_command_line_handling_do_discovery_calls_loadersr         !csdtfdY}|tjds           cCs|j}tj}tjjd}tjjd}tjd||f}|jt d||j dddd|j t jd|dS( NRdRcsZ'foo' module incorrectly imported from %r. Expected %r. Is this module globally installed?s^%s$RMR;sfoo.pyi( RRRR RR(tretescapetassertRaisesRegexpRPRQRRI(R RUR tmod_dirt expected_dirtmsg((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_detect_module_clash[s    cs|j}tjjtjjdtjjdfd}|j|fd}|tj_tj}|jdddddS(NRdRccstj_dS(N(R Rtrealpath((toriginal_realpath(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRqscs2|tjjdkr.tjjdS|S(Nsfoo.py(R Rtjoin(R(RR(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyRusRMR;sfoo.py( RR RRR(R%RRRQ(R RURRR ((RRRs4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_module_symlink_okis     cstj}gtjjtjjtjjt_ fd}||_ |j d}j j j |jdS(Ncst_j|S(N(R3twasRunR(RMR;(t expectedPathR R:(s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR*s s unittest.test(RRR RR(tdirnameR]RRHRR*RQR}Rt_tests(R R R*R-((RR R:s4/usr/lib64/python2.7/unittest/test/test_discovery.pyttest_discovery_from_dotted_path}s  $  (R@RAR R/RGRVR^RjRsRuR~RRRR(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyR s  + A .    J   t__main__( R RRIRt unittest.testtTestCaseRR@tmain(((s4/usr/lib64/python2.7/unittest/test/test_discovery.pyts      PK!Yotest/test_functiontestcase.pynu[import unittest from unittest.test.support import LoggingResult class Test_FunctionTestCase(unittest.TestCase): # "Return the number of tests represented by the this test object. For # TestCase instances, this will always be 1" def test_countTestCases(self): test = unittest.FunctionTestCase(lambda: None) self.assertEqual(test.countTestCases(), 1) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception. def test_run_call_order__error_in_setUp(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') raise RuntimeError('raised by setUp') def test(): events.append('test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'addError', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test raises # an error (as opposed to a failure). def test_run_call_order__error_in_test(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') raise RuntimeError('raised by test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test signals # a failure (as opposed to an error). def test_run_call_order__failure_in_test(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') self.fail('raised by test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if tearDown() raises # an exception. def test_run_call_order__error_in_tearDown(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') def tearDown(): events.append('tearDown') raise RuntimeError('raised by tearDown') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "Return a string identifying the specific test case." # # Because of the vague nature of the docs, I'm not going to lock this # test down too much. Really all that can be asserted is that the id() # will be a string (either 8-byte or unicode -- again, because the docs # just say "string") def test_id(self): test = unittest.FunctionTestCase(lambda: None) self.assertIsInstance(test.id(), basestring) # "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 test method's docstring, if available, or None." def test_shortDescription__no_docstring(self): test = unittest.FunctionTestCase(lambda: None) self.assertEqual(test.shortDescription(), None) # "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 test method's docstring, if available, or None." def test_shortDescription__singleline_docstring(self): desc = "this tests foo" test = unittest.FunctionTestCase(lambda: None, description=desc) self.assertEqual(test.shortDescription(), "this tests foo") if __name__ == '__main__': unittest.main() PK!}'test/test_functiontestcase.pycnu[ |fc@sRddlZddlmZdejfdYZedkrNejndS(iN(t LoggingResulttTest_FunctionTestCasecBsPeZdZdZdZdZdZdZdZdZ RS(cCs,tjd}|j|jddS(NcSsdS(N(tNone(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt ti(tunittesttFunctionTestCaset assertEqualtcountTestCases(tselfttest((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyttest_countTestCases scsgt}fd}fd}fd}ddddg}tj|||j||j|dS(NcsjdtddS(NtsetUpsraised by setUp(tappendt RuntimeError((tevents(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR s csjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR scsjddS(NttearDown(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR!st startTestR taddErrortstopTest(RRRtrunR(R tresultR R Rtexpected((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt#test_run_call_order__error_in_setUps csgt}fd}fd}fd}dddddd g}tj|||j||j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR 3scsjdtddS(NR sraised by test(R R((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR 6s csjddS(NR(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR:sRR R RRR(RRRRR(R RR R RR((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt"test_run_call_order__error_in_test/s  csgt}fd}fd}fd}dddddd g}tj|||j|j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR MscsjdjddS(NR sraised by test(R tfail((RR (s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR Ps csjddS(NR(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRTsRR R t addFailureRR(RRRRR(R RR R RR((RR s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt$test_run_call_order__failure_in_testIs  csgt}fd}fd}fd}dddddd g}tj|||j||j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR gscsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR jscsjdtddS(NRsraised by tearDown(R R((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRms RR R RRR(RRRRR(R RR R RR((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt&test_run_call_order__error_in_tearDowncs  cCs,tjd}|j|jtdS(NcSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR}R(RRtassertIsInstancetidt basestring(R R ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyttest_id|scCs,tjd}|j|jddS(NcSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRR(RRRtshortDescriptionR(R R ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt#test_shortDescription__no_docstringscCs8d}tjdd|}|j|jddS(Nsthis tests foocSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRRt description(RRRR!(R tdescR ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt+test_shortDescription__singleline_docstrings( t__name__t __module__R RRRRR R"R%(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRs      t__main__(Rtunittest.test.supportRtTestCaseRR&tmain(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyts  PK!}'test/test_functiontestcase.pyonu[ |fc@sRddlZddlmZdejfdYZedkrNejndS(iN(t LoggingResulttTest_FunctionTestCasecBsPeZdZdZdZdZdZdZdZdZ RS(cCs,tjd}|j|jddS(NcSsdS(N(tNone(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt ti(tunittesttFunctionTestCaset assertEqualtcountTestCases(tselfttest((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyttest_countTestCases scsgt}fd}fd}fd}ddddg}tj|||j||j|dS(NcsjdtddS(NtsetUpsraised by setUp(tappendt RuntimeError((tevents(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR s csjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR scsjddS(NttearDown(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR!st startTestR taddErrortstopTest(RRRtrunR(R tresultR R Rtexpected((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt#test_run_call_order__error_in_setUps csgt}fd}fd}fd}dddddd g}tj|||j||j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR 3scsjdtddS(NR sraised by test(R R((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR 6s csjddS(NR(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR:sRR R RRR(RRRRR(R RR R RR((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt"test_run_call_order__error_in_test/s  csgt}fd}fd}fd}dddddd g}tj|||j|j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR MscsjdjddS(NR sraised by test(R tfail((RR (s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR Ps csjddS(NR(R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRTsRR R t addFailureRR(RRRRR(R RR R RR((RR s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt$test_run_call_order__failure_in_testIs  csgt}fd}fd}fd}dddddd g}tj|||j||j|dS( NcsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR gscsjddS(NR (R ((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR jscsjdtddS(NRsraised by tearDown(R R((R(s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRms RR R RRR(RRRRR(R RR R RR((Rs;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt&test_run_call_order__error_in_tearDowncs  cCs,tjd}|j|jtdS(NcSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyR}R(RRtassertIsInstancetidt basestring(R R ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyttest_id|scCs,tjd}|j|jddS(NcSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRR(RRRtshortDescriptionR(R R ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt#test_shortDescription__no_docstringscCs8d}tjdd|}|j|jddS(Nsthis tests foocSsdS(N(R(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRRt description(RRRR!(R tdescR ((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyt+test_shortDescription__singleline_docstrings( t__name__t __module__R RRRRR R"R%(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyRs      t__main__(Rtunittest.test.supportRtTestCaseRR&tmain(((s;/usr/lib64/python2.7/unittest/test/test_functiontestcase.pyts  PK! patest/test_loader.pynu[import sys import types import unittest class Test_TestLoader(unittest.TestCase): ### Tests for TestLoader.loadTestsFromTestCase ################################################################ # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" def test_loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # Make sure it does the right thing even if no tests were found def test_loadTestsFromTestCase__no_matches(self): class Foo(unittest.TestCase): def foo_bar(self): pass empty_suite = unittest.TestSuite() loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # What happens if loadTestsFromTestCase() is given an object # that isn't a subclass of TestCase? Specifically, what happens # if testCaseClass is a subclass of TestSuite? # # This is checked for specifically in the code, so we better add a # test for it. def test_loadTestsFromTestCase__TestSuite_subclass(self): class NotATestCase(unittest.TestSuite): pass loader = unittest.TestLoader() try: loader.loadTestsFromTestCase(NotATestCase) except TypeError: pass else: self.fail('Should raise TypeError') # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # Make sure loadTestsFromTestCase() picks up the default test method # name (as specified by TestCase), even though the method name does # not match the default TestLoader.testMethodPrefix string def test_loadTestsFromTestCase__default_method_name(self): class Foo(unittest.TestCase): def runTest(self): pass loader = unittest.TestLoader() # This has to be false for the test to succeed self.assertFalse('runTest'.startswith(loader.testMethodPrefix)) suite = loader.loadTestsFromTestCase(Foo) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [Foo('runTest')]) ################################################################ ### /Tests for TestLoader.loadTestsFromTestCase ### Tests for TestLoader.loadTestsFromModule ################################################################ # "This method searches `module` for classes derived from TestCase" def test_loadTestsFromModule__TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) expected = [loader.suiteClass([MyTestCase('test')])] self.assertEqual(list(suite), expected) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (no TestCase instances)? def test_loadTestsFromModule__no_TestCase_instances(self): m = types.ModuleType('m') loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (TestCases instances, but no tests)? def test_loadTestsFromModule__no_TestCase_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [loader.suiteClass()]) # "This method searches `module` for classes derived from TestCase"s # # What happens if loadTestsFromModule() is given something other # than a module? # # XXX Currently, it succeeds anyway. This flexibility # should either be documented or loadTestsFromModule() should # raise a TypeError # # XXX Certain people are using this behaviour. We'll add a test for it def test_loadTestsFromModule__not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # Check that loadTestsFromModule honors (or not) a module # with a load_tests function. def test_loadTestsFromModule__load_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(load_tests_args, [loader, suite, None]) load_tests_args = [] suite = loader.loadTestsFromModule(m, use_load_tests=False) self.assertEqual(load_tests_args, []) def test_loadTestsFromModule__faulty_load_tests(self): m = types.ModuleType('m') def load_tests(loader, tests, pattern): raise TypeError('some failure') m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(suite.countTestCases(), 1) test = list(suite)[0] self.assertRaisesRegexp(TypeError, "some failure", test.m) ################################################################ ### /Tests for TestLoader.loadTestsFromModule() ### Tests for TestLoader.loadTestsFromName() ################################################################ # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromName__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('') except ValueError, e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the name contains invalid characters? def test_loadTestsFromName__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? try: loader.loadTestsFromName('abc () //') except ValueError: pass except ImportError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve ... to a # module" # # What happens when a module by that name can't be found? def test_loadTestsFromName__unknown_module_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('sdasfasfasdf') except ImportError, e: self.assertEqual(str(e), "No module named sdasfasfasdf") else: self.fail("TestLoader.loadTestsFromName failed to raise ImportError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module is found, but the attribute can't? def test_loadTestsFromName__unknown_attr_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('unittest.sdasfasfasdf') except AttributeError, e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when we provide the module, but the attribute can't be # found? def test_loadTestsFromName__relative_unknown_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('sdasfasfasdf', unittest) except AttributeError, e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise ValueError when passed an empty # name relative to a provided module? # # XXX Should probably raise a ValueError instead of an AttributeError def test_loadTestsFromName__relative_empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('', unittest) except AttributeError: pass else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when an impossible name is given, relative to the provided # `module`? def test_loadTestsFromName__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? try: loader.loadTestsFromName('abc () //', unittest) except ValueError: pass except AttributeError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise TypeError when the `module` argument # isn't a module object? # # XXX Accepts the not-a-module object, ignoring the object's type # This should raise an exception or the method name should be changed # # XXX Some people are relying on this, so keep it for now def test_loadTestsFromName__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('test_2', NotAModule) reference = [MyTestCase('test')] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromName__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1', m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may # resolve either to ... a test case class" def test_loadTestsFromName__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." def test_loadTestsFromName__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromName('testsuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" def test_loadTestsFromName__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does loadTestsFromName() raise the proper exception when trying to # resolve "a test method within a test case class" that doesn't exist # for the given name (relative to a provided module)? def test_loadTestsFromName__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1.testfoo', m) except AttributeError, e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromName__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestSuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1, testcase_2]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromName__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() loader.suiteClass = SubTestSuite suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() loader.suiteClass=SubTestSuite suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens if the callable returns something else? def test_loadTestsFromName__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: loader.loadTestsFromName('return_wrong', m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromName__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromName(module_name) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### Tests for TestLoader.loadTestsFromName() ### Tests for TestLoader.loadTestsFromNames() ################################################################ # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # # What happens if that sequence of names is empty? def test_loadTestsFromNames__empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # ... # "The method optionally resolves name relative to the given module" # # What happens if that sequence of names is empty? # # XXX Should this raise a ValueError or just return an empty TestSuite? def test_loadTestsFromNames__relative_empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([], unittest) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromNames__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['']) except ValueError, e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when presented with an impossible module name? def test_loadTestsFromNames__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? try: loader.loadTestsFromNames(['abc () //']) except ValueError: pass except ImportError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when no module can be found for the given name? def test_loadTestsFromNames__unknown_module_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['sdasfasfasdf']) except ImportError, e: self.assertEqual(str(e), "No module named sdasfasfasdf") else: self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module can be found, but not the attribute? def test_loadTestsFromNames__unknown_attr_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) except AttributeError, e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when given an unknown attribute on a specified `module` # argument? def test_loadTestsFromNames__unknown_name_relative_1(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['sdasfasfasdf'], unittest) except AttributeError, e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Do unknown attributes (relative to a provided module) still raise an # exception even in the presence of valid attribute names? def test_loadTestsFromNames__unknown_name_relative_2(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) except AttributeError, e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when faced with the empty string? # # XXX This currently raises AttributeError, though ValueError is probably # more appropriate def test_loadTestsFromNames__relative_empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames([''], unittest) except AttributeError: pass else: self.fail("Failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when presented with an impossible attribute name? def test_loadTestsFromNames__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? try: loader.loadTestsFromNames(['abc () //'], unittest) except AttributeError: pass except ValueError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The method optionally resolves name relative to the given module" # # Does loadTestsFromNames() make sure the provided `module` is in fact # a module? # # XXX This validation is currently not done. This flexibility should # either be documented or a TypeError should be raised. def test_loadTestsFromNames__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['test_2'], NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromNames__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1'], m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test case class" def test_loadTestsFromNames__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1'], m) self.assertIsInstance(suite, loader.suiteClass) expected = loader.suiteClass([MyTestCase('test')]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a TestSuite instance" def test_loadTestsFromNames__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testsuite'], m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [m.testsuite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" def test_loadTestsFromNames__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.test'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([MyTestCase('test')]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" # # Does the method gracefully handle names that initially look like they # resolve to "a test method within a test case class" but don't? def test_loadTestsFromNames__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1.testfoo'], m) except AttributeError, e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromNames__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestSuite'], m) self.assertIsInstance(suite, loader.suiteClass) expected = unittest.TestSuite([testcase_1, testcase_2]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromNames__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestCase'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # Are staticmethods handled correctly? def test_loadTestsFromNames__callable__call_staticmethod(self): m = types.ModuleType('m') class Test1(unittest.TestCase): def test(self): pass testcase_1 = Test1('test') class Foo(unittest.TestCase): @staticmethod def foo(): return testcase_1 m.Foo = Foo loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['Foo.foo'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens when the callable returns something else? def test_loadTestsFromNames__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: loader.loadTestsFromNames(['return_wrong'], m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromNames__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromNames([module_name]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [unittest.TestSuite()]) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### /Tests for TestLoader.loadTestsFromNames() ### Tests for TestLoader.getTestCaseNames() ################################################################ # "Return a sorted sequence of method names found within testCaseClass" # # Test.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames(self): class Test(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) # "Return a sorted sequence of method names found within testCaseClass" # # Does getTestCaseNames() behave appropriately if no tests are found? def test_getTestCaseNames__no_tests(self): class Test(unittest.TestCase): def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), []) # "Return a sorted sequence of method names found within testCaseClass" # # Are not-TestCases handled gracefully? # # XXX This should raise a TypeError, not return a list # # XXX It's too late in the 2.5 release cycle to fix this, but it should # probably be revisited for 2.6 def test_getTestCaseNames__not_a_TestCase(self): class BadCase(int): def test_foo(self): pass loader = unittest.TestLoader() names = loader.getTestCaseNames(BadCase) self.assertEqual(names, ['test_foo']) # "Return a sorted sequence of method names found within testCaseClass" # # Make sure inherited names are handled. # # TestP.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames__inheritance(self): class TestP(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass class TestC(TestP): def test_1(self): pass def test_3(self): pass loader = unittest.TestLoader() names = ['test_1', 'test_2', 'test_3'] self.assertEqual(loader.getTestCaseNames(TestC), names) ################################################################ ### /Tests for TestLoader.getTestCaseNames() ### Tests for TestLoader.testMethodPrefix ################################################################ # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = [unittest.TestSuite([Foo('foo_bar')])] tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) tests_2 = unittest.TestSuite([tests_2]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) # "The default value is 'test'" def test_testMethodPrefix__default_value(self): loader = unittest.TestLoader() self.assertTrue(loader.testMethodPrefix == 'test') ################################################################ ### /Tests for TestLoader.testMethodPrefix ### Tests for TestLoader.sortTestMethodsUsing ################################################################ # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromTestCase(self): def reversed_cmp(x, y): return -cmp(x, y) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromModule(self): def reversed_cmp(x, y): return -cmp(x, y) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromModule(m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromName(self): def reversed_cmp(x, y): return -cmp(x, y) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromNames(self): def reversed_cmp(x, y): return -cmp(x, y) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames()" # # Does it actually affect getTestCaseNames()? def test_sortTestMethodsUsing__getTestCaseNames(self): def reversed_cmp(x, y): return -cmp(x, y) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp test_names = ['test_2', 'test_1'] self.assertEqual(loader.getTestCaseNames(Foo), test_names) # "The default value is the built-in cmp() function" def test_sortTestMethodsUsing__default_value(self): loader = unittest.TestLoader() self.assertTrue(loader.sortTestMethodsUsing is cmp) # "it can be set to None to disable the sort." # # XXX How is this different from reassigning cmp? Are the tests returned # in a random order or something? This behaviour should die def test_sortTestMethodsUsing__None(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = None test_names = ['test_2', 'test_1'] self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) ################################################################ ### /Tests for TestLoader.sortTestMethodsUsing ### Tests for TestLoader.suiteClass ################################################################ # "Callable object that constructs a test suite from a list of tests." def test_suiteClass__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromModule(m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) # "The default value is the TestSuite class" def test_suiteClass__default_value(self): loader = unittest.TestLoader() self.assertIs(loader.suiteClass, unittest.TestSuite) # Make sure the dotted name resolution works even if the actual # function doesn't have the same name as is used to find it. def test_loadTestsFromName__function_with_different_name_than_method(self): # lambdas have the name ''. m = types.ModuleType('m') class MyTestCase(unittest.TestCase): test = lambda: 1 m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.test'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([MyTestCase('test')]) self.assertEqual(list(suite), [ref_suite]) if __name__ == '__main__': unittest.main() PK!lױœtest/test_loader.pycnu[ |fc@sZddlZddlZddlZdejfdYZedkrVejndS(iNtTest_TestLoadercBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0d/Z1d0Z2d1Z3d2Z4d3Z5d4Z6d5Z7d6Z8d7Z9d8Z:d9Z;d:Z<d;Z=d<Z>d=Z?d>Z@d?ZAd@ZBdAZCdBZDdCZEdDZFdEZGdFZHdGZIRS(HcCscdtjfdY}tj|d|dg}tj}|j|j||dS(NtFoocBs#eZdZdZdZRS(cSsdS(N((tself((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_1tcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_2RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoo_barR(t__name__t __module__RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR(tunittesttTestCaset TestSuitet TestLoadert assertEqualtloadTestsFromTestCase(RRtteststloader((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_loadTestsFromTestCases! cCsNdtjfdY}tj}tj}|j|j||dS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs(R R R R R R(RRt empty_suiteR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromTestCase__no_matchess  cCs[dtjfdY}tj}y|j|Wntk rInX|jddS(Nt NotATestCasecBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR1ssShould raise TypeError(R R R Rt TypeErrortfail(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_loadTestsFromTestCase__TestSuite_subclass0s  cCsdtjfdY}tj}|jdj|j|j|}|j||j|j t ||dgdS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytrunTestDs(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRCsR( R R R t assertFalset startswithttestMethodPrefixRtassertIsInstancet suiteClassR tlist(RRRtsuite((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromTestCase__default_method_nameBs  cCstjd}dtjfdY}||_tj}|j|}|j||j|j|dgg}|j t ||dS(Ntmt MyTestCasecBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttestYs(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"XsR#( ttypest ModuleTypeR R t testcase_1R tloadTestsFromModuleRRR R(RR!R"RRtexpected((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__TestCase_subclassVs  cCsWtjd}tj}|j|}|j||j|jt|gdS(NR!( R$R%R R R'RRR R(RR!RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromModule__no_TestCase_instancesgs  cCstjd}dtjfdY}||_tj}|j|}|j||j|j t ||jgdS(NR!R"cBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"ts( R$R%R R R&R R'RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__no_TestCase_testsrs  csdtjfdYdtffdY}tj}|j|}tjdgg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"st NotAModulecseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,sR#(R R tobjectR R'R R R(RR,RRt reference((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromModule__not_a_modules  cstjd}dtjfdY}||_gfd}||_tj}|j|}j|tj j ||dgg|j|dt }j gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"scs-j|tjj|||f|S(N(RR R textend(RRtpattern(tload_tests_argsR(s1/usr/lib64/python2.7/unittest/test/test_loader.pyt load_testsstuse_load_tests( R$R%R R R&R3R R'RR R tNonetFalse(RR!R"R3RR((R2Rs1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_loadTestsFromModule__load_testss   cCstjd}d}||_tj}|j|}|j|tj|j|j dt |d}|j t d|j dS(NR!cSstddS(Ns some failure(R(RRR1((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR3siis some failure(R$R%R3R R R'RR R tcountTestCasesRtassertRaisesRegexpRR!(RR!R3RRR#((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__faulty_load_testss   cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(NRsEmpty module names7TestLoader.loadTestsFromName failed to raise ValueError(R R tloadTestsFromNamet ValueErrorR tstrR(RRte((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_loadTestsFromName__empty_names  cCsRtj}y|jdWn!tk r0ntk r@nX|jddS(Ns abc () //s7TestLoader.loadTestsFromName failed to raise ValueError(R R R;R<t ImportErrorR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromName__malformed_names   cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(Nt sdasfasfasdfsNo module named sdasfasfasdfs8TestLoader.loadTestsFromName failed to raise ImportError(R R R;R@R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__unknown_module_names  cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(Nsunittest.sdasfasfasdfs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R R;tAttributeErrorR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_loadTestsFromName__unknown_attr_names  cCs]tj}y|jdtWn)tk rK}|jt|dnX|jddS(NRBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R R;RDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromName__relative_unknown_name s  cCsEtj}y|jdtWntk r3nX|jddS(NRsFailed to raise AttributeError(R R R;RDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_empty_name"s   cCsUtj}y|jdtWn!tk r3ntk rCnX|jddS(Ns abc () //s7TestLoader.loadTestsFromName failed to raise ValueError(R R R;R<RDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromName__relative_malformed_name5s   cs|dtjfdYdtffdY}tj}|jd|}dg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#Ms(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"LsR,cseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,PsRR#(R R R-R R;R R(RR,RRR.((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromName__relative_not_a_moduleKs  cCs`tjd}t|_tj}y|jd|Wntk rNnX|jddS(NR!R&sShould have raised TypeError( R$R%R-R&R R R;RR(RR!R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_bad_object`s   cCstjd}dtjfdY}||_tj}|jd|}|j||j|j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#qs(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"psR&R#( R$R%R R R&R R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt2test_loadTestsFromName__relative_TestCase_subclassns  cCstjd}dtjfdY}tj|dg|_tj}|jd|}|j||j |j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR#t testsuite( R$R%R R R RLR R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromName__relative_TestSuite~s cCstjd}dtjfdY}||_tj}|jd|}|j||j|j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R$R%R R R&R R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_testmethods  cCstjd}dtjfdY}||_tj}y|jd|Wn)tk r|}|jt |dnX|j ddS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testfoos3type object 'MyTestCase' has no attribute 'testfoo'sFailed to raise AttributeError( R$R%R R R&R R;RDR R=R(RR!R"RR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromName__relative_invalid_testmethods  cstjd}tjdtjdfd}||_tj}|jd|}|j||j|j t |gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pytRcSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcstjgS(N(R R ((R&t testcase_2(s1/usr/lib64/python2.7/unittest/test/test_loader.pytreturn_TestSuitesRR( R$R%R tFunctionTestCaseRRR R;RRR R(RR!RRRR((R&RQs1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__callable__TestSuites  cstjd}tjdfd}||_tj}|jd|}|j||j|j t |gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pytreturn_TestCasesRU( R$R%R RSRUR R;RRR R(RR!RURR((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromName__callable__TestCase_instances  csdtjfdY}tjd}tjdfd}||_tj}||_|jd|}|j ||j|j t |gdS(Nt SubTestSuitecBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWsR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRUsRU( R R R$R%RSRUR RR;RR R(RRWR!RURR((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pytDtest_loadTestsFromName__callable__TestCase_instance_ProperSuiteClasss   cCsdtjfdY}tjd}dtjfdY}||_tj}||_|jd|}|j ||j|j t ||dgdS(NRWcBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWsR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R R R$R%R R&R RR;RR R(RRWR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt<test_loadTestsFromName__relative_testmethod_ProperSuiteClasss   cCsftjd}d}||_tj}y|jd|Wntk rTnX|jddS(NR!cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt return_wrongsRZs6TestLoader.loadTestsFromName failed to raise TypeError(R$R%RZR R R;RR(RR!RZR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromName__callable__wrong_types    cCsd}tjj|dtj}zO|j|}|j||j|j t |g|j |tjWd|tjkrtj|=nXdS(Nsunittest.test.dummy( tsystmodulestpopR5R R R;RRR RtassertIn(Rt module_nameRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_loadTestsFromName__module_not_loaded s cCsHtj}|jg}|j||j|jt|gdS(N(R R tloadTestsFromNamesRRR R(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_loadTestsFromNames__empty_name_list)s cCsKtj}|jgt}|j||j|jt|gdS(N(R R RbRRR R(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt1test_loadTestsFromNames__relative_empty_name_list8s cCs]tj}y|jdgWn)tk rK}|jt|dnX|jddS(NRsEmpty module names8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbR<R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt#test_loadTestsFromNames__empty_nameEs  cCsUtj}y|jdgWn!tk r3ntk rCnX|jddS(Ns abc () //s8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbR<R@R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt'test_loadTestsFromNames__malformed_nameUs   cCs]tj}y|jdgWn)tk rK}|jt|dnX|jddS(NRBsNo module named sdasfasfasdfs9TestLoader.loadTestsFromNames failed to raise ImportError(R R RbR@R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__unknown_module_namehs  cCs`tj}y|jddgWn)tk rN}|jt|dnX|jddS(Nsunittest.sdasfasfasdfR s/'module' object has no attribute 'sdasfasfasdf's<TestLoader.loadTestsFromNames failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromNames__unknown_attr_namexs  cCs`tj}y|jdgtWn)tk rN}|jt|dnX|jddS(NRBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__unknown_name_relative_1s  cCsctj}y|jddgtWn)tk rQ}|jt|dnX|jddS(NR RBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__unknown_name_relative_2s  cCsHtj}y|jdgtWntk r6nX|jddS(NRsFailed to raise ValueError(R R RbRDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_empty_names   cCsXtj}y|jdgtWn!tk r6ntk rFnX|jddS(Ns abc () //s8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbRDR<R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__relative_malformed_names   csdtjfdYdtffdY}tj}|jdg|}tjdgg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR,cseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,sRR#(R R R-R RbR R R(RR,RRR.((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_loadTestsFromNames__relative_not_a_modules  cCsctjd}t|_tj}y|jdg|Wntk rQnX|jddS(NR!R&sShould have raised TypeError( R$R%R-R&R R RbRR(RR!R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_bad_objects   cCstjd}dtjfdY}||_tj}|jdg|}|j||j|j|dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR&R#( R$R%R R R&R RbRRR R(RR!R"RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromNames__relative_TestCase_subclasss  cCstjd}dtjfdY}tj|dg|_tj}|jdg|}|j||j |j t ||jgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR#RL( R$R%R R R RLR RbRRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromNames__relative_TestSuite s cCstjd}dtjfdY}||_tj}|jdg|}|j||jtj |dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R$R%R R R&R RbRRR R R(RR!R"RRt ref_suite((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_testmethods  cCstjd}dtjfdY}||_tj}y|jdg|Wn)tk r}|jt |dnX|j ddS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#1s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"0sstestcase_1.testfoos3type object 'MyTestCase' has no attribute 'testfoo'sFailed to raise AttributeError( R$R%R R R&R RbRDR R=R(RR!R"RR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__relative_invalid_testmethod.s  cstjd}tjdtjdfd}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPARcSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPBRcstjgS(N(R R ((R&RQ(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRCsRR( R$R%R RSRRR RbRRR R R(RR!RRRRR(((R&RQs1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__callable__TestSuite?s  cstjd}tjdfd}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRUSsRU( R$R%R RSRUR RbRRR R R(RR!RURRRq((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__callable__TestCase_instancePs  cstjd}dtjfdY}|ddtjffdY}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!tTest1cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#es(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRvdsR#RcseZefdZRS(csS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoojs(RRt staticmethodRw((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRissFoo.foo( R$R%R R RR RbRRR R R(RR!RvRRRRq((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__callable__call_staticmethodbs   cCsitjd}d}||_tj}y|jdg|Wntk rWnX|jddS(NR!cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRZ|sRZs7TestLoader.loadTestsFromNames failed to raise TypeError(R$R%RZR R RbRR(RR!RZR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromNames__callable__wrong_typezs    cCsd}tjj|dtj}z[|j|g}|j||j|j t |tj g|j |tjWd|tjkrtj|=nXdS(Nsunittest.test.dummy( R\R]R^R5R R RbRRR RR R_(RR`RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromNames__module_not_loadeds cCsHdtjfdY}tj}|j|j|ddgdS(NtTestcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoobarR(RRRRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR|s  RR(R R R R tgetTestCaseNames(RR|R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_getTestCaseNamess cCsBdtjfdY}tj}|j|j|gdS(NR|cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR}R(RRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR|s(R R R R R~(RR|R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_getTestCaseNames__no_testss cCsHdtfdY}tj}|j|}|j|dgdS(NtBadCasecBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_foos(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsR(tintR R R~R (RRRtnames((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt%test_getTestCaseNames__not_a_TestCases cCsgdtjfdY}d|fdY}tj}dddg}|j|j||dS(NtTestPcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR}R(RRRRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  tTestCcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_3R(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RRR(R R R R R~(RRRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_getTestCaseNames__inheritances  cCsdtjfdY}tj|dg}tj|d|dg}tj}d|_|j|j||d|_|j|j||dS(NRcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#(R R R R RR R(RRttests_1ttests_2R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_testMethodPrefix__loadTestsFromTestCases!   cCstjd}dtjfdY}||_tj|dgg}tj|d|dgg}tj}d|_|jt |j ||d|_|jt |j ||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#( R$R%R R RR R RR RR'(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_testMethodPrefix__loadTestsFromModules $   cCstjd}dtjfdY}||_tj|dg}tj|d|dg}tj}d|_|j|j d||d|_|j|j d||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#( R$R%R R RR R RR R;(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_testMethodPrefix__loadTestsFromNames !   cCstjd}dtjfdY}||_tjtj|dgg}tj|d|dg}tj|g}tj}d|_|j|j dg||d|_|j|j dg||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR5RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR6RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR7R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR4s  RRRRwR#( R$R%R R RR R RR Rb(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_testMethodPrefix__loadTestsFromNames2s $!   cCs&tj}|j|jdkdS(NR#(R R t assertTrueR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_testMethodPrefix__default_valueFs cCsud}dtjfdY}tj}||_|j|d|dg}|j|j||dS(NcSst|| S(N(tcmp(txty((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt reversed_cmpSsRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRXR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRVs RR(R R R tsortTestMethodsUsingRR R(RRRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_sortTestMethodsUsing__loadTestsFromTestCaseRs    !cCsd}tjd}dtjfdY}||_tj}||_|j|d|dgg}|jt |j ||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRcsR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRhRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRiR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRgs RR( R$R%R R RR RRR RR'(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_sortTestMethodsUsing__loadTestsFromModulebs    $cCsd}tjd}dtjfdY}||_tj}||_|j|d|dg}|j|j d||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRusR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRzRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR{R(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRys RR( R$R%R R RR RRR R;(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_sortTestMethodsUsing__loadTestsFromNamets    !cCsd}tjd}dtjfdY}||_tj}||_|j|d|dgg}|jt |j dg||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR( R$R%R R RR RRR RRb(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_sortTestMethodsUsing__loadTestsFromNamess    $cCs`d}dtjfdY}tj}||_ddg}|j|j||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR(R R R RR R~(RRRRt test_names((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_sortTestMethodsUsing__getTestCaseNamess     cCs&tj}|j|jtkdS(N(R R RRR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_sortTestMethodsUsing__default_values cCscdtjfdY}tj}d|_ddg}|jt|j|t|dS(NRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR(R R R R5RR tsetR~(RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_sortTestMethodsUsing__Nones    cCscdtjfdY}|d|dg}tj}t|_|j|j||dS(NRcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR(R R R RRR R(RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_suiteClass__loadTestsFromTestCases   cCs~tjd}dtjfdY}||_|d|dgg}tj}t|_|j|j ||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR R'(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_suiteClass__loadTestsFromModules   cCs~tjd}dtjfdY}||_|d|dg}tj}t|_|j|j d||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR R;(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_suiteClass__loadTestsFromNames   cCstjd}dtjfdY}||_|d|dgg}tj}t|_|j|j dg||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR Rb(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt#test_suiteClass__loadTestsFromNamess   cCs&tj}|j|jtjdS(N(R R tassertIsRR (RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_suiteClass__default_values cCstjd}dtjfdY}||_tj}|jdg|}|j||jtj |dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRP R(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR" sstestcase_1.testR#( R$R%R R R&R RbRRR R R(RR!R"RRRq((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt@test_loadTestsFromName__function_with_different_name_than_methods  (JRRRRRR R)R*R+R/R7R:R?RARCRERFRGRHRIRJRKRMRNRORTRVRXRYR[RaRcRdReRfRgRhRiRjRkRlRmRnRoRpRrRsRtRuRyRzR{RRRRRRRRRRRRRRRRRRRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs                                                                   t__main__(R\R$R R RRtmain(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyts    PK!lױœtest/test_loader.pyonu[ |fc@sZddlZddlZddlZdejfdYZedkrVejndS(iNtTest_TestLoadercBseZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0d/Z1d0Z2d1Z3d2Z4d3Z5d4Z6d5Z7d6Z8d7Z9d8Z:d9Z;d:Z<d;Z=d<Z>d=Z?d>Z@d?ZAd@ZBdAZCdBZDdCZEdDZFdEZGdFZHdGZIRS(HcCscdtjfdY}tj|d|dg}tj}|j|j||dS(NtFoocBs#eZdZdZdZRS(cSsdS(N((tself((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_1tcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_2RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoo_barR(t__name__t __module__RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR(tunittesttTestCaset TestSuitet TestLoadert assertEqualtloadTestsFromTestCase(RRtteststloader((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_loadTestsFromTestCases! cCsNdtjfdY}tj}tj}|j|j||dS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs(R R R R R R(RRt empty_suiteR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromTestCase__no_matchess  cCs[dtjfdY}tj}y|j|Wntk rInX|jddS(Nt NotATestCasecBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR1ssShould raise TypeError(R R R Rt TypeErrortfail(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_loadTestsFromTestCase__TestSuite_subclass0s  cCsdtjfdY}tj}|jdj|j|j|}|j||j|j t ||dgdS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytrunTestDs(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRCsR( R R R t assertFalset startswithttestMethodPrefixRtassertIsInstancet suiteClassR tlist(RRRtsuite((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromTestCase__default_method_nameBs  cCstjd}dtjfdY}||_tj}|j|}|j||j|j|dgg}|j t ||dS(Ntmt MyTestCasecBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttestYs(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"XsR#( ttypest ModuleTypeR R t testcase_1R tloadTestsFromModuleRRR R(RR!R"RRtexpected((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__TestCase_subclassVs  cCsWtjd}tj}|j|}|j||j|jt|gdS(NR!( R$R%R R R'RRR R(RR!RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromModule__no_TestCase_instancesgs  cCstjd}dtjfdY}||_tj}|j|}|j||j|j t ||jgdS(NR!R"cBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"ts( R$R%R R R&R R'RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__no_TestCase_testsrs  csdtjfdYdtffdY}tj}|j|}tjdgg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"st NotAModulecseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,sR#(R R tobjectR R'R R R(RR,RRt reference((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromModule__not_a_modules  cstjd}dtjfdY}||_gfd}||_tj}|j|}j|tj j ||dgg|j|dt }j gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"scs-j|tjj|||f|S(N(RR R textend(RRtpattern(tload_tests_argsR(s1/usr/lib64/python2.7/unittest/test/test_loader.pyt load_testsstuse_load_tests( R$R%R R R&R3R R'RR R tNonetFalse(RR!R"R3RR((R2Rs1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_loadTestsFromModule__load_testss   cCstjd}d}||_tj}|j|}|j|tj|j|j dt |d}|j t d|j dS(NR!cSstddS(Ns some failure(R(RRR1((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR3siis some failure(R$R%R3R R R'RR R tcountTestCasesRtassertRaisesRegexpRR!(RR!R3RRR#((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromModule__faulty_load_testss   cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(NRsEmpty module names7TestLoader.loadTestsFromName failed to raise ValueError(R R tloadTestsFromNamet ValueErrorR tstrR(RRte((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_loadTestsFromName__empty_names  cCsRtj}y|jdWn!tk r0ntk r@nX|jddS(Ns abc () //s7TestLoader.loadTestsFromName failed to raise ValueError(R R R;R<t ImportErrorR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_loadTestsFromName__malformed_names   cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(Nt sdasfasfasdfsNo module named sdasfasfasdfs8TestLoader.loadTestsFromName failed to raise ImportError(R R R;R@R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__unknown_module_names  cCsZtj}y|jdWn)tk rH}|jt|dnX|jddS(Nsunittest.sdasfasfasdfs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R R;tAttributeErrorR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_loadTestsFromName__unknown_attr_names  cCs]tj}y|jdtWn)tk rK}|jt|dnX|jddS(NRBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R R;RDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromName__relative_unknown_name s  cCsEtj}y|jdtWntk r3nX|jddS(NRsFailed to raise AttributeError(R R R;RDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_empty_name"s   cCsUtj}y|jdtWn!tk r3ntk rCnX|jddS(Ns abc () //s7TestLoader.loadTestsFromName failed to raise ValueError(R R R;R<RDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt/test_loadTestsFromName__relative_malformed_name5s   cs|dtjfdYdtffdY}tj}|jd|}dg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#Ms(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"LsR,cseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,PsRR#(R R R-R R;R R(RR,RRR.((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromName__relative_not_a_moduleKs  cCs`tjd}t|_tj}y|jd|Wntk rNnX|jddS(NR!R&sShould have raised TypeError( R$R%R-R&R R R;RR(RR!R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_bad_object`s   cCstjd}dtjfdY}||_tj}|jd|}|j||j|j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#qs(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"psR&R#( R$R%R R R&R R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt2test_loadTestsFromName__relative_TestCase_subclassns  cCstjd}dtjfdY}tj|dg|_tj}|jd|}|j||j |j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR#t testsuite( R$R%R R R RLR R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromName__relative_TestSuite~s cCstjd}dtjfdY}||_tj}|jd|}|j||j|j t ||dgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R$R%R R R&R R;RRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__relative_testmethods  cCstjd}dtjfdY}||_tj}y|jd|Wn)tk r|}|jt |dnX|j ddS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testfoos3type object 'MyTestCase' has no attribute 'testfoo'sFailed to raise AttributeError( R$R%R R R&R R;RDR R=R(RR!R"RR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromName__relative_invalid_testmethods  cstjd}tjdtjdfd}||_tj}|jd|}|j||j|j t |gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pytRcSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcstjgS(N(R R ((R&t testcase_2(s1/usr/lib64/python2.7/unittest/test/test_loader.pytreturn_TestSuitesRR( R$R%R tFunctionTestCaseRRR R;RRR R(RR!RRRR((R&RQs1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromName__callable__TestSuites  cstjd}tjdfd}||_tj}|jd|}|j||j|j t |gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pytreturn_TestCasesRU( R$R%R RSRUR R;RRR R(RR!RURR((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromName__callable__TestCase_instances  csdtjfdY}tjd}tjdfd}||_tj}||_|jd|}|j ||j|j t |gdS(Nt SubTestSuitecBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWsR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRUsRU( R R R$R%RSRUR RR;RR R(RRWR!RURR((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pytDtest_loadTestsFromName__callable__TestCase_instance_ProperSuiteClasss   cCsdtjfdY}tjd}dtjfdY}||_tj}||_|jd|}|j ||j|j t ||dgdS(NRWcBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWsR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R R R$R%R R&R RR;RR R(RRWR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt<test_loadTestsFromName__relative_testmethod_ProperSuiteClasss   cCsftjd}d}||_tj}y|jd|Wntk rTnX|jddS(NR!cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt return_wrongsRZs6TestLoader.loadTestsFromName failed to raise TypeError(R$R%RZR R R;RR(RR!RZR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromName__callable__wrong_types    cCsd}tjj|dtj}zO|j|}|j||j|j t |g|j |tjWd|tjkrtj|=nXdS(Nsunittest.test.dummy( tsystmodulestpopR5R R R;RRR RtassertIn(Rt module_nameRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_loadTestsFromName__module_not_loaded s cCsHtj}|jg}|j||j|jt|gdS(N(R R tloadTestsFromNamesRRR R(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_loadTestsFromNames__empty_name_list)s cCsKtj}|jgt}|j||j|jt|gdS(N(R R RbRRR R(RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt1test_loadTestsFromNames__relative_empty_name_list8s cCs]tj}y|jdgWn)tk rK}|jt|dnX|jddS(NRsEmpty module names8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbR<R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt#test_loadTestsFromNames__empty_nameEs  cCsUtj}y|jdgWn!tk r3ntk rCnX|jddS(Ns abc () //s8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbR<R@R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt'test_loadTestsFromNames__malformed_nameUs   cCs]tj}y|jdgWn)tk rK}|jt|dnX|jddS(NRBsNo module named sdasfasfasdfs9TestLoader.loadTestsFromNames failed to raise ImportError(R R RbR@R R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__unknown_module_namehs  cCs`tj}y|jddgWn)tk rN}|jt|dnX|jddS(Nsunittest.sdasfasfasdfR s/'module' object has no attribute 'sdasfasfasdf's<TestLoader.loadTestsFromNames failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromNames__unknown_attr_namexs  cCs`tj}y|jdgtWn)tk rN}|jt|dnX|jddS(NRBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__unknown_name_relative_1s  cCsctj}y|jddgtWn)tk rQ}|jt|dnX|jddS(NR RBs/'module' object has no attribute 'sdasfasfasdf's;TestLoader.loadTestsFromName failed to raise AttributeError(R R RbRDR R=R(RRR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__unknown_name_relative_2s  cCsHtj}y|jdgtWntk r6nX|jddS(NRsFailed to raise ValueError(R R RbRDR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_empty_names   cCsXtj}y|jdgtWn!tk r6ntk rFnX|jddS(Ns abc () //s8TestLoader.loadTestsFromNames failed to raise ValueError(R R RbRDR<R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_loadTestsFromNames__relative_malformed_names   csdtjfdYdtffdY}tj}|jdg|}tjdgg}|jt||dS(NR"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR,cseZZRS((RRR((R"(s1/usr/lib64/python2.7/unittest/test/test_loader.pyR,sRR#(R R R-R RbR R R(RR,RRR.((R"s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_loadTestsFromNames__relative_not_a_modules  cCsctjd}t|_tj}y|jdg|Wntk rQnX|jddS(NR!R&sShould have raised TypeError( R$R%R-R&R R RbRR(RR!R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_bad_objects   cCstjd}dtjfdY}||_tj}|jdg|}|j||j|j|dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR&R#( R$R%R R R&R RbRRR R(RR!R"RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt3test_loadTestsFromNames__relative_TestCase_subclasss  cCstjd}dtjfdY}tj|dg|_tj}|jdg|}|j||j |j t ||jgdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sR#RL( R$R%R R R RLR RbRRR R(RR!R"RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_loadTestsFromNames__relative_TestSuite s cCstjd}dtjfdY}||_tj}|jdg|}|j||jtj |dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"sstestcase_1.testR#( R$R%R R R&R RbRRR R R(RR!R"RRt ref_suite((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__relative_testmethods  cCstjd}dtjfdY}||_tj}y|jdg|Wn)tk r}|jt |dnX|j ddS(NR!R"cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#1s(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR"0sstestcase_1.testfoos3type object 'MyTestCase' has no attribute 'testfoo'sFailed to raise AttributeError( R$R%R R R&R RbRDR R=R(RR!R"RR>((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__relative_invalid_testmethod.s  cstjd}tjdtjdfd}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPARcSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPBRcstjgS(N(R R ((R&RQ(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRCsRR( R$R%R RSRRR RbRRR R R(RR!RRRRR(((R&RQs1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_loadTestsFromNames__callable__TestSuite?s  cstjd}tjdfd}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!cSsdS(N(R5(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRPRRcsS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRUSsRU( R$R%R RSRUR RbRRR R R(RR!RURRRq((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__callable__TestCase_instancePs  cstjd}dtjfdY}|ddtjffdY}||_tj}|jdg|}|j||jtj g}|j t ||gdS(NR!tTest1cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR#es(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRvdsR#RcseZefdZRS(csS(N(((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoojs(RRt staticmethodRw((R&(s1/usr/lib64/python2.7/unittest/test/test_loader.pyRissFoo.foo( R$R%R R RR RbRRR R R(RR!RvRRRRq((R&s1/usr/lib64/python2.7/unittest/test/test_loader.pyt4test_loadTestsFromNames__callable__call_staticmethodbs   cCsitjd}d}||_tj}y|jdg|Wntk rWnX|jddS(NR!cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRZ|sRZs7TestLoader.loadTestsFromNames failed to raise TypeError(R$R%RZR R RbRR(RR!RZR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_loadTestsFromNames__callable__wrong_typezs    cCsd}tjj|dtj}z[|j|g}|j||j|j t |tj g|j |tjWd|tjkrtj|=nXdS(Nsunittest.test.dummy( R\R]R^R5R R RbRRR RR R_(RR`RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_loadTestsFromNames__module_not_loadeds cCsHdtjfdY}tj}|j|j|ddgdS(NtTestcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pytfoobarR(RRRRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR|s  RR(R R R R tgetTestCaseNames(RR|R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_getTestCaseNamess cCsBdtjfdY}tj}|j|j|gdS(NR|cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR}R(RRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR|s(R R R R R~(RR|R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_getTestCaseNames__no_testss cCsHdtfdY}tj}|j|}|j|dgdS(NtBadCasecBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_foos(RRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsR(tintR R R~R (RRRtnames((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt%test_getTestCaseNames__not_a_TestCases cCsgdtjfdY}d|fdY}tj}dddg}|j|j||dS(NtTestPcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR}R(RRRRR}(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  tTestCcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_3R(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RRR(R R R R R~(RRRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_getTestCaseNames__inheritances  cCsdtjfdY}tj|dg}tj|d|dg}tj}d|_|j|j||d|_|j|j||dS(NRcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#(R R R R RR R(RRttests_1ttests_2R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_testMethodPrefix__loadTestsFromTestCases!   cCstjd}dtjfdY}||_tj|dgg}tj|d|dgg}tj}d|_|jt |j ||d|_|jt |j ||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#( R$R%R R RR R RR RR'(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt*test_testMethodPrefix__loadTestsFromModules $   cCstjd}dtjfdY}||_tj|dg}tj|d|dg}tj}d|_|j|j d||d|_|j|j d||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RRRRwR#( R$R%R R RR R RR R;(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_testMethodPrefix__loadTestsFromNames !   cCstjd}dtjfdY}||_tjtj|dgg}tj|d|dg}tj|g}tj}d|_|j|j dg||d|_|j|j dg||dS( NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR5RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR6RcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR7R(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR4s  RRRRwR#( R$R%R R RR R RR Rb(RR!RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt)test_testMethodPrefix__loadTestsFromNames2s $!   cCs&tj}|j|jdkdS(NR#(R R t assertTrueR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_testMethodPrefix__default_valueFs cCsud}dtjfdY}tj}||_|j|d|dg}|j|j||dS(NcSst|| S(N(tcmp(txty((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt reversed_cmpSsRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRWRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRXR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRVs RR(R R R tsortTestMethodsUsingRR R(RRRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt0test_sortTestMethodsUsing__loadTestsFromTestCaseRs    !cCsd}tjd}dtjfdY}||_tj}||_|j|d|dgg}|jt |j ||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRcsR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRhRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRiR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRgs RR( R$R%R R RR RRR RR'(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt.test_sortTestMethodsUsing__loadTestsFromModulebs    $cCsd}tjd}dtjfdY}||_tj}||_|j|d|dg}|j|j d||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRusR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRzRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR{R(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRys RR( R$R%R R RR RRR R;(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt,test_sortTestMethodsUsing__loadTestsFromNamets    !cCsd}tjd}dtjfdY}||_tj}||_|j|d|dgg}|jt |j dg||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsR!RcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR( R$R%R R RR RRR RRb(RRR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt-test_sortTestMethodsUsing__loadTestsFromNamess    $cCs`d}dtjfdY}tj}||_ddg}|j|j||dS(NcSst|| S(N(R(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRsRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR(R R R RR R~(RRRRt test_names((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt+test_sortTestMethodsUsing__getTestCaseNamess     cCs&tj}|j|jtkdS(N(R R RRR(RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt(test_sortTestMethodsUsing__default_values cCscdtjfdY}tj}d|_ddg}|jt|j|t|dS(NRcBseZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs RR(R R R R5RR tsetR~(RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_sortTestMethodsUsing__Nones    cCscdtjfdY}|d|dg}tj}t|_|j|j||dS(NRcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR(R R R RRR R(RRRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt&test_suiteClass__loadTestsFromTestCases   cCs~tjd}dtjfdY}||_|d|dgg}tj}t|_|j|j ||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR R'(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt$test_suiteClass__loadTestsFromModules   cCs~tjd}dtjfdY}||_|d|dg}tj}t|_|j|j d||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR R;(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt"test_suiteClass__loadTestsFromNames   cCstjd}dtjfdY}||_|d|dgg}tj}t|_|j|j dg||dS(NR!RcBs#eZdZdZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRRcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRR(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs  RR( R$R%R R RR RRR Rb(RR!RRR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt#test_suiteClass__loadTestsFromNamess   cCs&tj}|j|jtjdS(N(R R tassertIsRR (RR((s1/usr/lib64/python2.7/unittest/test/test_loader.pyttest_suiteClass__default_values cCstjd}dtjfdY}||_tj}|jdg|}|j||jtj |dg}|j t ||gdS(NR!R"cBseZdZRS(cSsdS(Ni((((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRP R(RRR#(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyR" sstestcase_1.testR#( R$R%R R R&R RbRRR R R(RR!R"RRRq((s1/usr/lib64/python2.7/unittest/test/test_loader.pyt@test_loadTestsFromName__function_with_different_name_than_methods  (JRRRRRR R)R*R+R/R7R:R?RARCRERFRGRHRIRJRKRMRNRORTRVRXRYR[RaRcRdReRfRgRhRiRjRkRlRmRnRoRpRrRsRtRuRyRzR{RRRRRRRRRRRRRRRRRRRRRR(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyRs                                                                   t__main__(R\R$R R RRtmain(((s1/usr/lib64/python2.7/unittest/test/test_loader.pyts    PK!x'Әtest/test_program.pynu[from cStringIO import StringIO import os import sys import unittest import unittest.test class Test_TestProgram(unittest.TestCase): def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _find_tests(start_dir, pattern): self.wasRun = True self.assertEqual(start_dir, expectedPath) return tests loader._find_tests = _find_tests suite = loader.discover('unittest.test') self.assertTrue(self.wasRun) self.assertEqual(suite._tests, tests) # Horrible white box test def testNoExit(self): result = object() test = object() class FakeRunner(object): def run(self, test): self.test = test return result runner = FakeRunner() oldParseArgs = unittest.TestProgram.parseArgs def restoreParseArgs(): unittest.TestProgram.parseArgs = oldParseArgs unittest.TestProgram.parseArgs = lambda *args: None self.addCleanup(restoreParseArgs) def removeTest(): del unittest.TestProgram.test unittest.TestProgram.test = test self.addCleanup(removeTest) program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2) self.assertEqual(program.result, result) self.assertEqual(runner.test, test) self.assertEqual(program.verbosity, 2) class FooBar(unittest.TestCase): def testPass(self): assert True def testFail(self): assert False class FooBarLoader(unittest.TestLoader): """Test loader that returns a suite containing FooBar.""" def loadTestsFromModule(self, module): return self.suiteClass( [self.loadTestsFromTestCase(Test_TestProgram.FooBar)]) def test_NonExit(self): program = unittest.main(exit=False, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=StringIO()), testLoader=self.FooBarLoader()) self.assertTrue(hasattr(program, 'result')) def test_Exit(self): self.assertRaises( SystemExit, unittest.main, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=StringIO()), exit=True, testLoader=self.FooBarLoader()) def test_ExitAsDefault(self): self.assertRaises( SystemExit, unittest.main, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=StringIO()), testLoader=self.FooBarLoader()) class InitialisableProgram(unittest.TestProgram): exit = False result = None verbosity = 1 defaultTest = None testRunner = None testLoader = unittest.defaultTestLoader progName = 'test' test = 'test' def __init__(self, *args): pass RESULT = object() class FakeRunner(object): initArgs = None test = None raiseError = False def __init__(self, **kwargs): FakeRunner.initArgs = kwargs if FakeRunner.raiseError: FakeRunner.raiseError = False raise TypeError def run(self, test): FakeRunner.test = test return RESULT class TestCommandLineArgs(unittest.TestCase): def setUp(self): self.program = InitialisableProgram() self.program.createTests = lambda: None FakeRunner.initArgs = None FakeRunner.test = None FakeRunner.raiseError = False def testHelpAndUnknown(self): program = self.program def usageExit(msg=None): program.msg = msg program.exit = True program.usageExit = usageExit for opt in '-h', '-H', '--help': program.exit = False program.parseArgs([None, opt]) self.assertTrue(program.exit) self.assertIsNone(program.msg) program.parseArgs([None, '-$']) self.assertTrue(program.exit) self.assertIsNotNone(program.msg) def testVerbosity(self): program = self.program for opt in '-q', '--quiet': program.verbosity = 1 program.parseArgs([None, opt]) self.assertEqual(program.verbosity, 0) for opt in '-v', '--verbose': program.verbosity = 1 program.parseArgs([None, opt]) self.assertEqual(program.verbosity, 2) def testBufferCatchFailfast(self): program = self.program for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), ('catch', 'catchbreak')): if attr == 'catch' and not hasInstallHandler: continue short_opt = '-%s' % arg[0] long_opt = '--%s' % arg for opt in short_opt, long_opt: setattr(program, attr, None) program.parseArgs([None, opt]) self.assertTrue(getattr(program, attr)) for opt in short_opt, long_opt: not_none = object() setattr(program, attr, not_none) program.parseArgs([None, opt]) self.assertEqual(getattr(program, attr), not_none) def testRunTestsRunnerClass(self): program = self.program program.testRunner = FakeRunner program.verbosity = 'verbosity' program.failfast = 'failfast' program.buffer = 'buffer' program.runTests() self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity', 'failfast': 'failfast', 'buffer': 'buffer'}) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def testRunTestsRunnerInstance(self): program = self.program program.testRunner = FakeRunner() FakeRunner.initArgs = None program.runTests() # A new FakeRunner should not have been instantiated self.assertIsNone(FakeRunner.initArgs) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def testRunTestsOldRunnerClass(self): program = self.program FakeRunner.raiseError = True program.testRunner = FakeRunner program.verbosity = 'verbosity' program.failfast = 'failfast' program.buffer = 'buffer' program.test = 'test' program.runTests() # If initializing raises a type error it should be retried # without the new keyword arguments self.assertEqual(FakeRunner.initArgs, {}) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def testCatchBreakInstallsHandler(self): module = sys.modules['unittest.main'] original = module.installHandler def restore(): module.installHandler = original self.addCleanup(restore) self.installed = False def fakeInstallHandler(): self.installed = True module.installHandler = fakeInstallHandler program = self.program program.catchbreak = True program.testRunner = FakeRunner program.runTests() self.assertTrue(self.installed) if __name__ == '__main__': unittest.main() PK!ú((test/test_program.pycnu[ |fc@sddlmZddlZddlZddlZddlZdejfdYZdejfdYZ e Z de fdYZ d ejfd YZ ed krejndS( i(tStringIONtTest_TestProgramcBsgeZdZdZdejfdYZdejfdYZdZ dZ dZ RS( cstj}gtjjtjjtjjt_ fd}||_ |j d}j j j |jdS(Ncst_j|S(N(tTruetwasRunt assertEqual(t start_dirtpattern(t expectedPathtselfttests(s2/usr/lib64/python2.7/unittest/test/test_program.pyt _find_testss s unittest.test(tunittestt TestLoadertostpathtabspathtdirnamettestt__file__tFalseRR tdiscovert assertTrueRt_tests(RtloaderR tsuite((RRR s2/usr/lib64/python2.7/unittest/test/test_program.pyttest_discovery_from_dotted_path s  $  cstt}dtffdY}|}tjjfd}dtj_|j|d}|tj_|j|tjd|dtdd }|j|j|j|j||j|j d dS( Nt FakeRunnercseZfdZRS(cs ||_S(N(R(RR(tresult(s2/usr/lib64/python2.7/unittest/test/test_program.pytrun!s (t__name__t __module__R((R(s2/usr/lib64/python2.7/unittest/test/test_program.pyR scstj_dS(N(R t TestProgramt parseArgs((t oldParseArgs(s2/usr/lib64/python2.7/unittest/test/test_program.pytrestoreParseArgs(scWsdS(N(tNone(targs((s2/usr/lib64/python2.7/unittest/test/test_program.pyt*tcSs tj`dS(N(R RR(((s2/usr/lib64/python2.7/unittest/test/test_program.pyt removeTest-st testRunnertexitt verbosityi( tobjectR RR t addCleanupRRRRR*(RRRtrunnerR"R'tprogram((R!Rs2/usr/lib64/python2.7/unittest/test/test_program.pyt testNoExits        tFooBarcBseZdZdZRS(cCsts tdS(N(RtAssertionError(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestPass9scCsts tdS(N(RR1(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestFail;s(RRR2R3(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR08s t FooBarLoadercBseZdZdZRS(s3Test loader that returns a suite containing FooBar.cCs|j|jtjgS(N(t suiteClasstloadTestsFromTestCaseRR0(Rtmodule((s2/usr/lib64/python2.7/unittest/test/test_program.pytloadTestsFromModule@s(RRt__doc__R8(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR4>sc CsVtjdtddgdtjdtd|j}|jt|ddS(NR)targvtfoobarR(tstreamt testLoaderR(R tmainRtTextTestRunnerRR4Rthasattr(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyt test_NonExitEs  c CsG|jttjddgdtjdtdtd|jdS(NR:R;R(R<R)R=(t assertRaisest SystemExitR R>R?RRR4(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyt test_ExitMs  c CsA|jttjddgdtjdtd|jdS(NR:R;R(R<R=(RBRCR R>R?RR4(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttest_ExitAsDefaultWs   ( RRRR/R tTestCaseR0R R4RARDRE(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR s    tInitialisableProgramcBsDeZeZdZdZdZdZe j Z dZ dZ dZRS(iRcGsdS(N((RR$((s2/usr/lib64/python2.7/unittest/test/test_program.pyt__init__isN(RRRR)R#RR*t defaultTestR(R tdefaultTestLoaderR=tprogNameRRH(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRG`s RcBs,eZdZdZeZdZdZRS(cKs(|t_tjr$tt_tndS(N(RtinitArgst raiseErrorRt TypeError(Rtkwargs((s2/usr/lib64/python2.7/unittest/test/test_program.pyRHss   cCs |t_tS(N(RRtRESULT(RR((s2/usr/lib64/python2.7/unittest/test/test_program.pyRys N( RRR#RLRRRMRHR(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRns  tTestCommandLineArgscBsPeZdZdZdZdZdZdZdZdZ RS(cCs:t|_d|j_dt_dt_tt_dS(NcSsdS(N(R#(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR%R&( RGR.t createTestsR#RRLRRRM(R((s2/usr/lib64/python2.7/unittest/test/test_program.pytsetUps    cs|jdfd}|_xJdD]B}t_jd|g|jj|jjq+Wjddg|jj|j jdS(Ncs|_t_dS(N(tmsgRR)(RT(R.(s2/usr/lib64/python2.7/unittest/test/test_program.pyt usageExits s-hs-Hs--helps-$(s-hs-Hs--help( R.R#RURR)R Rt assertIsNoneRTtassertIsNotNone(RRUtopt((R.s2/usr/lib64/python2.7/unittest/test/test_program.pyttestHelpAndUnknowns    cCs|j}x=dD]5}d|_|jd|g|j|jdqWx=d D]5}d|_|jd|g|j|jdqPWdS( Ns-qs--quietiis-vs --verbosei(s-qs--quiet(s-vs --verbose(R.R*R R#R(RR.RX((s2/usr/lib64/python2.7/unittest/test/test_program.pyt testVerbositys     cCs |j}xdd d fD]\}}|dkr>t r>qnd|d}d|}xM||fD]?}t||d|jd|g|jt||qcWxY||fD]K}t}t||||jd|g|jt|||qWqWdS( Ntbuffertfailfasttcatcht catchbreaks-%sis--%s(R[R[(R\R\(R]R^( R.thasInstallHandlertsetattrR#R RtgetattrR+R(RR.targtattrt short_opttlong_optRXtnot_none((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestBufferCatchFailfasts     cCs|j}t|_d|_d|_d|_|j|jtjidd6dd6dd6|jtj d|j |j t dS(NR*R\R[R( R.RR(R*R\R[trunTestsRRLRtassertIsRRP(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsRunnerClasss       cCsb|j}t|_dt_|j|jtj|jtjd|j |j t dS(NR( R.RR(R#RLRhRVRRRiRRP(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsRunnerInstances    cCs|j}tt_t|_d|_d|_d|_d|_|j |j tj i|j tjd|j |j tdS(NR*R\R[R(R.RRRMR(R*R\R[RRhRRLRiRRP(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsOldRunnerClasss        cstjdjfd}j|t_fd}|_j}t|_t |_ |j j jdS(Ns unittest.maincs _dS(N(tinstallHandler((R7toriginal(s2/usr/lib64/python2.7/unittest/test/test_program.pytrestorescs t_dS(N(Rt installed((R(s2/usr/lib64/python2.7/unittest/test/test_program.pytfakeInstallHandlers( tsystmodulesRmR,RRpR.RR^RR(RhR(RRoRqR.((R7RnRs2/usr/lib64/python2.7/unittest/test/test_program.pyttestCatchBreakInstallsHandlers         ( RRRSRYRZRgRjRkRlRt(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRQ}s      t__main__(t cStringIORR RrR t unittest.testRFRRRGR+RPRRQRR>(((s2/usr/lib64/python2.7/unittest/test/test_program.pyts    W  PK!((test/test_program.pyonu[ |fc@sddlmZddlZddlZddlZddlZdejfdYZdejfdYZ e Z de fdYZ d ejfd YZ ed krejndS( i(tStringIONtTest_TestProgramcBsgeZdZdZdejfdYZdejfdYZdZ dZ dZ RS( cstj}gtjjtjjtjjt_ fd}||_ |j d}j j j |jdS(Ncst_j|S(N(tTruetwasRunt assertEqual(t start_dirtpattern(t expectedPathtselfttests(s2/usr/lib64/python2.7/unittest/test/test_program.pyt _find_testss s unittest.test(tunittestt TestLoadertostpathtabspathtdirnamettestt__file__tFalseRR tdiscovert assertTrueRt_tests(RtloaderR tsuite((RRR s2/usr/lib64/python2.7/unittest/test/test_program.pyttest_discovery_from_dotted_path s  $  cstt}dtffdY}|}tjjfd}dtj_|j|d}|tj_|j|tjd|dtdd }|j|j|j|j||j|j d dS( Nt FakeRunnercseZfdZRS(cs ||_S(N(R(RR(tresult(s2/usr/lib64/python2.7/unittest/test/test_program.pytrun!s (t__name__t __module__R((R(s2/usr/lib64/python2.7/unittest/test/test_program.pyR scstj_dS(N(R t TestProgramt parseArgs((t oldParseArgs(s2/usr/lib64/python2.7/unittest/test/test_program.pytrestoreParseArgs(scWsdS(N(tNone(targs((s2/usr/lib64/python2.7/unittest/test/test_program.pyt*tcSs tj`dS(N(R RR(((s2/usr/lib64/python2.7/unittest/test/test_program.pyt removeTest-st testRunnertexitt verbosityi( tobjectR RR t addCleanupRRRRR*(RRRtrunnerR"R'tprogram((R!Rs2/usr/lib64/python2.7/unittest/test/test_program.pyt testNoExits        tFooBarcBseZdZdZRS(cCsdS(N((R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestPass9scCsdS(N((R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestFail;s(RRR1R2(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR08s t FooBarLoadercBseZdZdZRS(s3Test loader that returns a suite containing FooBar.cCs|j|jtjgS(N(t suiteClasstloadTestsFromTestCaseRR0(Rtmodule((s2/usr/lib64/python2.7/unittest/test/test_program.pytloadTestsFromModule@s(RRt__doc__R7(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR3>sc CsVtjdtddgdtjdtd|j}|jt|ddS(NR)targvtfoobarR(tstreamt testLoaderR(R tmainRtTextTestRunnerRR3Rthasattr(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyt test_NonExitEs  c CsG|jttjddgdtjdtdtd|jdS(NR9R:R(R;R)R<(t assertRaisest SystemExitR R=R>RRR3(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyt test_ExitMs  c CsA|jttjddgdtjdtd|jdS(NR9R:R(R;R<(RARBR R=R>RR3(R((s2/usr/lib64/python2.7/unittest/test/test_program.pyttest_ExitAsDefaultWs   ( RRRR/R tTestCaseR0R R3R@RCRD(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR s    tInitialisableProgramcBsDeZeZdZdZdZdZe j Z dZ dZ dZRS(iRcGsdS(N((RR$((s2/usr/lib64/python2.7/unittest/test/test_program.pyt__init__isN(RRRR)R#RR*t defaultTestR(R tdefaultTestLoaderR<tprogNameRRG(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRF`s RcBs,eZdZdZeZdZdZRS(cKs(|t_tjr$tt_tndS(N(RtinitArgst raiseErrorRt TypeError(Rtkwargs((s2/usr/lib64/python2.7/unittest/test/test_program.pyRGss   cCs |t_tS(N(RRtRESULT(RR((s2/usr/lib64/python2.7/unittest/test/test_program.pyRys N( RRR#RKRRRLRGR(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRns  tTestCommandLineArgscBsPeZdZdZdZdZdZdZdZdZ RS(cCs:t|_d|j_dt_dt_tt_dS(NcSsdS(N(R#(((s2/usr/lib64/python2.7/unittest/test/test_program.pyR%R&( RFR.t createTestsR#RRKRRRL(R((s2/usr/lib64/python2.7/unittest/test/test_program.pytsetUps    cs|jdfd}|_xJdD]B}t_jd|g|jj|jjq+Wjddg|jj|j jdS(Ncs|_t_dS(N(tmsgRR)(RS(R.(s2/usr/lib64/python2.7/unittest/test/test_program.pyt usageExits s-hs-Hs--helps-$(s-hs-Hs--help( R.R#RTRR)R Rt assertIsNoneRStassertIsNotNone(RRTtopt((R.s2/usr/lib64/python2.7/unittest/test/test_program.pyttestHelpAndUnknowns    cCs|j}x=dD]5}d|_|jd|g|j|jdqWx=d D]5}d|_|jd|g|j|jdqPWdS( Ns-qs--quietiis-vs --verbosei(s-qs--quiet(s-vs --verbose(R.R*R R#R(RR.RW((s2/usr/lib64/python2.7/unittest/test/test_program.pyt testVerbositys     cCs |j}xdd d fD]\}}|dkr>t r>qnd|d}d|}xM||fD]?}t||d|jd|g|jt||qcWxY||fD]K}t}t||||jd|g|jt|||qWqWdS( Ntbuffertfailfasttcatcht catchbreaks-%sis--%s(RZRZ(R[R[(R\R]( R.thasInstallHandlertsetattrR#R RtgetattrR+R(RR.targtattrt short_opttlong_optRWtnot_none((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestBufferCatchFailfasts     cCs|j}t|_d|_d|_d|_|j|jtjidd6dd6dd6|jtj d|j |j t dS(NR*R[RZR( R.RR(R*R[RZtrunTestsRRKRtassertIsRRO(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsRunnerClasss       cCsb|j}t|_dt_|j|jtj|jtjd|j |j t dS(NR( R.RR(R#RKRgRURRRhRRO(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsRunnerInstances    cCs|j}tt_t|_d|_d|_d|_d|_|j |j tj i|j tjd|j |j tdS(NR*R[RZR(R.RRRLR(R*R[RZRRgRRKRhRRO(RR.((s2/usr/lib64/python2.7/unittest/test/test_program.pyttestRunTestsOldRunnerClasss        cstjdjfd}j|t_fd}|_j}t|_t |_ |j j jdS(Ns unittest.maincs _dS(N(tinstallHandler((R6toriginal(s2/usr/lib64/python2.7/unittest/test/test_program.pytrestorescs t_dS(N(Rt installed((R(s2/usr/lib64/python2.7/unittest/test/test_program.pytfakeInstallHandlers( tsystmodulesRlR,RRoR.RR]RR(RgR(RRnRpR.((R6RmRs2/usr/lib64/python2.7/unittest/test/test_program.pyttestCatchBreakInstallsHandlers         ( RRRRRXRYRfRiRjRkRs(((s2/usr/lib64/python2.7/unittest/test/test_program.pyRP}s      t__main__(t cStringIORR RqR t unittest.testRERRRFR+RORRPRR=(((s2/usr/lib64/python2.7/unittest/test/test_program.pyts    W  PK!pJpJtest/test_result.pynu[import sys import textwrap from StringIO import StringIO from test import test_support import traceback import unittest class Test_TestResult(unittest.TestCase): # Note: there are not separate tests for TestResult.wasSuccessful(), # TestResult.errors, TestResult.failures, TestResult.testsRun or # TestResult.shouldStop because these only have meaning in terms of # other TestResult methods. # # Accordingly, tests for the aforenamed attributes are incorporated # in with the tests for the defining methods. ################################################################ def test_init(self): result = unittest.TestResult() self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 0) self.assertEqual(result.shouldStop, False) self.assertIsNone(result._stdout_buffer) self.assertIsNone(result._stderr_buffer) # "This method can be called to signal that the set of tests being # run should be aborted by setting the TestResult's shouldStop # attribute to True." def test_stop(self): result = unittest.TestResult() result.stop() self.assertEqual(result.shouldStop, True) # "Called when the test case test is about to be run. The default # implementation simply increments the instance's testsRun counter." def test_startTest(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) result.stopTest(test) # "Called after the test case test has been executed, regardless of # the outcome. The default implementation does nothing." def test_stopTest(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) result.stopTest(test) # Same tests as above; make sure nothing has changed self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) # "Called before and after tests are run. The default implementation does nothing." def test_startTestRun_stopTestRun(self): result = unittest.TestResult() result.startTestRun() result.stopTestRun() # "addSuccess(test)" # ... # "Called when the test case test succeeds" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addSuccess(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) result.addSuccess(test) result.stopTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) # "addFailure(test, err)" # ... # "Called when the test case test signals a failure. err is a tuple of # the form returned by sys.exc_info(): (type, value, traceback)" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addFailure(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') try: test.fail("foo") except: exc_info_tuple = sys.exc_info() result = unittest.TestResult() result.startTest(test) result.addFailure(test, exc_info_tuple) result.stopTest(test) self.assertFalse(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 1) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) test_case, formatted_exc = result.failures[0] self.assertIs(test_case, test) self.assertIsInstance(formatted_exc, str) # "addError(test, err)" # ... # "Called when the test case test raises an unexpected exception err # is a tuple of the form returned by sys.exc_info(): # (type, value, traceback)" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addError(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') try: raise TypeError() except: exc_info_tuple = sys.exc_info() result = unittest.TestResult() result.startTest(test) result.addError(test, exc_info_tuple) result.stopTest(test) self.assertFalse(result.wasSuccessful()) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) test_case, formatted_exc = result.errors[0] self.assertIs(test_case, test) self.assertIsInstance(formatted_exc, str) def testGetDescriptionWithoutDocstring(self): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), 'testGetDescriptionWithoutDocstring (' + __name__ + '.Test_TestResult)') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetDescriptionWithOneLineDocstring(self): """Tests getDescription() for a method with a docstring.""" result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), ('testGetDescriptionWithOneLineDocstring ' '(' + __name__ + '.Test_TestResult)\n' 'Tests getDescription() for a method with a docstring.')) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetDescriptionWithMultiLineDocstring(self): """Tests getDescription() for a method with a longer docstring. The second line of the docstring. """ result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), ('testGetDescriptionWithMultiLineDocstring ' '(' + __name__ + '.Test_TestResult)\n' 'Tests getDescription() for a method with a longer ' 'docstring.')) def testStackFrameTrimming(self): class Frame(object): class tb_frame(object): f_globals = {} result = unittest.TestResult() self.assertFalse(result._is_relevant_tb_level(Frame)) Frame.tb_frame.f_globals['__unittest'] = True self.assertTrue(result._is_relevant_tb_level(Frame)) def testFailFast(self): result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addError(None, None) self.assertTrue(result.shouldStop) result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addFailure(None, None) self.assertTrue(result.shouldStop) result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addUnexpectedSuccess(None) self.assertTrue(result.shouldStop) def testFailFastSetByRunner(self): runner = unittest.TextTestRunner(stream=StringIO(), failfast=True) def test(result): self.assertTrue(result.failfast) runner.run(test) classDict = dict(unittest.TestResult.__dict__) for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess', '__init__'): del classDict[m] def __init__(self, stream=None, descriptions=None, verbosity=None): self.failures = [] self.errors = [] self.testsRun = 0 self.shouldStop = False self.buffer = False classDict['__init__'] = __init__ OldResult = type('OldResult', (object,), classDict) class Test_OldTestResult(unittest.TestCase): def assertOldResultWarning(self, test, failures): with test_support.check_warnings(("TestResult has no add.+ method,", RuntimeWarning)): result = OldResult() test.run(result) self.assertEqual(len(result.failures), failures) def testOldTestResult(self): class Test(unittest.TestCase): def testSkip(self): self.skipTest('foobar') @unittest.expectedFailure def testExpectedFail(self): raise TypeError @unittest.expectedFailure def testUnexpectedSuccess(self): pass for test_name, should_pass in (('testSkip', True), ('testExpectedFail', True), ('testUnexpectedSuccess', False)): test = Test(test_name) self.assertOldResultWarning(test, int(not should_pass)) def testOldTestTesultSetup(self): class Test(unittest.TestCase): def setUp(self): self.skipTest('no reason') def testFoo(self): pass self.assertOldResultWarning(Test('testFoo'), 0) def testOldTestResultClass(self): @unittest.skip('no reason') class Test(unittest.TestCase): def testFoo(self): pass self.assertOldResultWarning(Test('testFoo'), 0) def testOldResultWithRunner(self): class Test(unittest.TestCase): def testFoo(self): pass runner = unittest.TextTestRunner(resultclass=OldResult, stream=StringIO()) # This will raise an exception if TextTestRunner can't handle old # test result objects runner.run(Test('testFoo')) class MockTraceback(object): @staticmethod def format_exception(*_): return ['A traceback'] def restore_traceback(): unittest.result.traceback = traceback class TestOutputBuffering(unittest.TestCase): def setUp(self): self._real_out = sys.stdout self._real_err = sys.stderr def tearDown(self): sys.stdout = self._real_out sys.stderr = self._real_err def testBufferOutputOff(self): real_out = self._real_out real_err = self._real_err result = unittest.TestResult() self.assertFalse(result.buffer) self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) result.startTest(self) self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) def testBufferOutputStartTestAddSuccess(self): real_out = self._real_out real_err = self._real_err result = unittest.TestResult() self.assertFalse(result.buffer) result.buffer = True self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) result.startTest(self) self.assertIsNot(real_out, sys.stdout) self.assertIsNot(real_err, sys.stderr) self.assertIsInstance(sys.stdout, StringIO) self.assertIsInstance(sys.stderr, StringIO) self.assertIsNot(sys.stdout, sys.stderr) out_stream = sys.stdout err_stream = sys.stderr result._original_stdout = StringIO() result._original_stderr = StringIO() print 'foo' print >> sys.stderr, 'bar' self.assertEqual(out_stream.getvalue(), 'foo\n') self.assertEqual(err_stream.getvalue(), 'bar\n') self.assertEqual(result._original_stdout.getvalue(), '') self.assertEqual(result._original_stderr.getvalue(), '') result.addSuccess(self) result.stopTest(self) self.assertIs(sys.stdout, result._original_stdout) self.assertIs(sys.stderr, result._original_stderr) self.assertEqual(result._original_stdout.getvalue(), '') self.assertEqual(result._original_stderr.getvalue(), '') self.assertEqual(out_stream.getvalue(), '') self.assertEqual(err_stream.getvalue(), '') def getStartedResult(self): result = unittest.TestResult() result.buffer = True result.startTest(self) return result def testBufferOutputAddErrorOrFailure(self): unittest.result.traceback = MockTraceback self.addCleanup(restore_traceback) for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), ('errors', 'addError', True), ('failures', 'addFailure', False) ]: result = self.getStartedResult() buffered_out = sys.stdout buffered_err = sys.stderr result._original_stdout = StringIO() result._original_stderr = StringIO() print >> sys.stdout, 'foo' if include_error: print >> sys.stderr, 'bar' addFunction = getattr(result, add_attr) addFunction(self, (None, None, None)) result.stopTest(self) result_list = getattr(result, message_attr) self.assertEqual(len(result_list), 1) test, message = result_list[0] expectedOutMessage = textwrap.dedent(""" Stdout: foo """) expectedErrMessage = '' if include_error: expectedErrMessage = textwrap.dedent(""" Stderr: bar """) expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) self.assertIs(test, self) self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage) self.assertEqual(result._original_stderr.getvalue(), expectedErrMessage) self.assertMultiLineEqual(message, expectedFullMessage) def testBufferSetupClass(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): @classmethod def setUpClass(cls): 1//0 def test_foo(self): pass suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferTearDownClass(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): @classmethod def tearDownClass(cls): 1//0 def test_foo(self): pass suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferSetUpModule(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): def test_foo(self): pass class Module(object): @staticmethod def setUpModule(): 1//0 Foo.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferTearDownModule(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): def test_foo(self): pass class Module(object): @staticmethod def tearDownModule(): 1//0 Foo.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) if __name__ == '__main__': unittest.main() PK!aDϗSStest/test_result.pycnu[ |fc@s>ddlZddlZddlmZddlmZddlZddlZdejfdYZe ej j Z x!dddd fD] Z e e =qWeeed Zee d R(RR<R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestStackFrameTrimmings  cCstj}d|_t|_|jdd|j|jtj}d|_t|_|j dd|j|jtj}d|_t|_|j d|j|jdS(NcWsdS(Nt((t_((s1/usr/lib64/python2.7/unittest/test/test_result.pytRCcWsdS(NRC((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pyRERCcWsdS(NRC((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pyRERC( RRt_exc_info_to_stringRtfailfastR4R7RR R*taddUnexpectedSuccess(RR((s1/usr/lib64/python2.7/unittest/test/test_result.pyt testFailFasts          cs;tjdtdt}fd}|j|dS(NtstreamRGcsj|jdS(N(RRG(R(R(s1/usr/lib64/python2.7/unittest/test/test_result.pyR%s(RtTextTestRunnerRRtrun(RtrunnerR((Rs1/usr/lib64/python2.7/unittest/test/test_result.pyttestFailFastSetByRunner#s(RRRRRR R#R%R2R5R9RtskipIfR(tflagstoptimizeR:R;RBRIRN(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR s      ' 0    taddSkiptaddExpectedFailureRHt__init__cCs1g|_g|_d|_t|_t|_dS(Ni(R R R R R tbuffer(RRJt descriptionst verbosity((s1/usr/lib64/python2.7/unittest/test/test_result.pyRT/s     t OldResulttTest_OldTestResultcBs5eZdZdZdZdZdZRS(cCsOtjdtf4t}|j||jt|j|WdQXdS(NsTestResult has no add.+ method,(Rtcheck_warningstRuntimeWarningRXRLRRR (RRR R((s1/usr/lib64/python2.7/unittest/test/test_result.pytassertOldResultWarning;s     cCsrdtjfdY}xRdtfdtfdtffD]/\}}||}|j|t| q;WdS(NtTestcBs5eZdZejdZejdZRS(cSs|jddS(Ntfoobar(tskipTest(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestSkipDscSs tdS(N(R3(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestExpectedFailFscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestUnexpectedSuccessIs(RRR`RtexpectedFailureRaRb(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]Cs R`RaRb(RRRR R\tint(RR]t test_namet should_passR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestResultBs    cCs3dtjfdY}|j|dddS(NR]cBseZdZdZRS(cSs|jddS(Ns no reason(R_(R((s1/usr/lib64/python2.7/unittest/test/test_result.pytsetUpUscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestFooWs(RRRhRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]Ts Rii(RRR\(RR]((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestTesultSetupSscCsBtjddtjfdY}|j|dddS(Ns no reasonR]cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRi^s(RRRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]\sRii(RtskipRR\(RR]((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestResultClass[scCsKdtjfdY}tjdtdt}|j|ddS(NR]cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRids(RRRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]cst resultclassRJRi(RRRKRXRRL(RR]RM((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldResultWithRunnerbs (RRR\RgRjRlRn(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRY9s     t MockTracebackcBseZedZRS(cGsdgS(Ns A traceback((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pytformat_exceptionns(RRt staticmethodRp(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRomscCsttj_dS(N(t tracebackRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pytrestore_tracebackrstTestOutputBufferingcBsbeZdZdZdZdZdZdZdZdZ dZ d Z RS( cCstj|_tj|_dS(N(R(tstdoutt _real_outtstderrt _real_err(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRhxs cCs|jt_|jt_dS(N(RvR(RuRxRw(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttearDown|s cCs|j}|j}tj}|j|j|j|tj|j|tj |j ||j|tj|j|tj dS(N( RvRxRRR+RUR,R(RuRwR(Rtreal_outtreal_errR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferOutputOffs    cCs|j}|j}tj}|j|jt|_|j|tj |j|tj |j ||j |tj |j |tj |j tj t|j tj t|j tj tj tj }tj }t|_t|_dGHtj dIJ|j|jd|j|jd|j|jjd|j|jjd|j||j||jtj |j|jtj |j|j|jjd|j|jjd|j|jd|j|jddS(NR&tbarsfoo sbar RC(RvRxRRR+RURR,R(RuRwRt assertIsNotR-Rt_original_stdoutt_original_stderrRtgetvalueR$R(RRzR{Rt out_streamt err_stream((s1/usr/lib64/python2.7/unittest/test/test_result.pyt#testBufferOutputStartTestAddSuccesss>            cCs&tj}t|_|j||S(N(RRRRUR(RR((s1/usr/lib64/python2.7/unittest/test/test_result.pytgetStartedResults   cCsttj_|jtxddtfddtfddtfddtfgD]U\}}}|j}t j }t j }t |_ t |_t j dIJ|rt j dIJnt||}||d |j|t||}|jt|d|d\} } tjd } d } |rCtjd } nd | | f} |j| ||j|j j| |j|jj| |j| | qPWdS(NR R4R R*R&R}iis9 Stdout: foo RCs9 Stderr: bar sA traceback%s%s(NNN(RoRRRrt addCleanupRsRR RR(RuRwRRRtgetattrR7RRRttextwraptdedentR,RtassertMultiLineEqual(Rt message_attrtadd_attrt include_errorRt buffered_outt buffered_errt addFunctiont result_listRtmessagetexpectedOutMessagetexpectedErrMessagetexpectedFullMessage((s1/usr/lib64/python2.7/unittest/test/test_result.pyt!testBufferOutputAddErrorOrFailures@               cCsmtj}t|_dtjfdY}tj|dg}|||jt|jddS(NRcBs eZedZdZRS(cSs dddS(Nii((tcls((s1/usr/lib64/python2.7/unittest/test/test_result.pyt setUpClassscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttest_foos(RRt classmethodRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi( RRRRURt TestSuiteRRR (RRRtsuite((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferSetupClasss    cCsmtj}t|_dtjfdY}tj|dg}|||jt|jddS(NRcBs eZedZdZRS(cSs dddS(Nii((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyt tearDownClassscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyR s(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi( RRRRURRRRR (RRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferTearDownClasss    cCstj}t|_dtjfdY}dtfdY}d|_|tjd<|j tjj dtj |dg}|||j t |jddS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRs(RRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRstModulecBseZedZRS(cSs dddS(Nii((((s1/usr/lib64/python2.7/unittest/test/test_result.pyt setUpModules(RRRqR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi(RRRRURR?RR(tmodulesRtpopRRRR (RRRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferSetUpModules     cCstj}t|_dtjfdY}dtfdY}d|_|tjd<|j tjj dtj |dg}|||j t |jddS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyR's(RRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR&sRcBseZedZRS(cSs dddS(Nii((((s1/usr/lib64/python2.7/unittest/test/test_result.pyttearDownModule*s(RRRqR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR)sRi(RRRRURR?RR(RRRRRRR (RRRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferTearDownModule"s     ( RRRhRyR|RRRRRRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRtvs    0  .   t__main__(R(RRRRRrRRRtdictRt__dict__t classDicttmR7RTttypeR?RXRYRoRsRtRtmain(((s1/usr/lib64/python2.7/unittest/test/test_result.pyts(    !    4  PK!aDϗSStest/test_result.pyonu[ |fc@s>ddlZddlZddlmZddlmZddlZddlZdejfdYZe ej j Z x!dddd fD] Z e e =qWeeed Zee d R(RR<R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestStackFrameTrimmings  cCstj}d|_t|_|jdd|j|jtj}d|_t|_|j dd|j|jtj}d|_t|_|j d|j|jdS(NcWsdS(Nt((t_((s1/usr/lib64/python2.7/unittest/test/test_result.pytRCcWsdS(NRC((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pyRERCcWsdS(NRC((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pyRERC( RRt_exc_info_to_stringRtfailfastR4R7RR R*taddUnexpectedSuccess(RR((s1/usr/lib64/python2.7/unittest/test/test_result.pyt testFailFasts          cs;tjdtdt}fd}|j|dS(NtstreamRGcsj|jdS(N(RRG(R(R(s1/usr/lib64/python2.7/unittest/test/test_result.pyR%s(RtTextTestRunnerRRtrun(RtrunnerR((Rs1/usr/lib64/python2.7/unittest/test/test_result.pyttestFailFastSetByRunner#s(RRRRRR R#R%R2R5R9RtskipIfR(tflagstoptimizeR:R;RBRIRN(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR s      ' 0    taddSkiptaddExpectedFailureRHt__init__cCs1g|_g|_d|_t|_t|_dS(Ni(R R R R R tbuffer(RRJt descriptionst verbosity((s1/usr/lib64/python2.7/unittest/test/test_result.pyRT/s     t OldResulttTest_OldTestResultcBs5eZdZdZdZdZdZRS(cCsOtjdtf4t}|j||jt|j|WdQXdS(NsTestResult has no add.+ method,(Rtcheck_warningstRuntimeWarningRXRLRRR (RRR R((s1/usr/lib64/python2.7/unittest/test/test_result.pytassertOldResultWarning;s     cCsrdtjfdY}xRdtfdtfdtffD]/\}}||}|j|t| q;WdS(NtTestcBs5eZdZejdZejdZRS(cSs|jddS(Ntfoobar(tskipTest(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestSkipDscSs tdS(N(R3(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestExpectedFailFscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestUnexpectedSuccessIs(RRR`RtexpectedFailureRaRb(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]Cs R`RaRb(RRRR R\tint(RR]t test_namet should_passR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestResultBs    cCs3dtjfdY}|j|dddS(NR]cBseZdZdZRS(cSs|jddS(Ns no reason(R_(R((s1/usr/lib64/python2.7/unittest/test/test_result.pytsetUpUscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestFooWs(RRRhRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]Ts Rii(RRR\(RR]((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestTesultSetupSscCsBtjddtjfdY}|j|dddS(Ns no reasonR]cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRi^s(RRRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]\sRii(RtskipRR\(RR]((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldTestResultClass[scCsKdtjfdY}tjdtdt}|j|ddS(NR]cBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRids(RRRi(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR]cst resultclassRJRi(RRRKRXRRL(RR]RM((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestOldResultWithRunnerbs (RRR\RgRjRlRn(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRY9s     t MockTracebackcBseZedZRS(cGsdgS(Ns A traceback((RD((s1/usr/lib64/python2.7/unittest/test/test_result.pytformat_exceptionns(RRt staticmethodRp(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRomscCsttj_dS(N(t tracebackRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pytrestore_tracebackrstTestOutputBufferingcBsbeZdZdZdZdZdZdZdZdZ dZ d Z RS( cCstj|_tj|_dS(N(R(tstdoutt _real_outtstderrt _real_err(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRhxs cCs|jt_|jt_dS(N(RvR(RuRxRw(R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttearDown|s cCs|j}|j}tj}|j|j|j|tj|j|tj |j ||j|tj|j|tj dS(N( RvRxRRR+RUR,R(RuRwR(Rtreal_outtreal_errR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferOutputOffs    cCs|j}|j}tj}|j|jt|_|j|tj |j|tj |j ||j |tj |j |tj |j tj t|j tj t|j tj tj tj }tj }t|_t|_dGHtj dIJ|j|jd|j|jd|j|jjd|j|jjd|j||j||jtj |j|jtj |j|j|jjd|j|jjd|j|jd|j|jddS(NR&tbarsfoo sbar RC(RvRxRRR+RURR,R(RuRwRt assertIsNotR-Rt_original_stdoutt_original_stderrRtgetvalueR$R(RRzR{Rt out_streamt err_stream((s1/usr/lib64/python2.7/unittest/test/test_result.pyt#testBufferOutputStartTestAddSuccesss>            cCs&tj}t|_|j||S(N(RRRRUR(RR((s1/usr/lib64/python2.7/unittest/test/test_result.pytgetStartedResults   cCsttj_|jtxddtfddtfddtfddtfgD]U\}}}|j}t j }t j }t |_ t |_t j dIJ|rt j dIJnt||}||d |j|t||}|jt|d|d\} } tjd } d } |rCtjd } nd | | f} |j| ||j|j j| |j|jj| |j| | qPWdS(NR R4R R*R&R}iis9 Stdout: foo RCs9 Stderr: bar sA traceback%s%s(NNN(RoRRRrt addCleanupRsRR RR(RuRwRRRtgetattrR7RRRttextwraptdedentR,RtassertMultiLineEqual(Rt message_attrtadd_attrt include_errorRt buffered_outt buffered_errt addFunctiont result_listRtmessagetexpectedOutMessagetexpectedErrMessagetexpectedFullMessage((s1/usr/lib64/python2.7/unittest/test/test_result.pyt!testBufferOutputAddErrorOrFailures@               cCsmtj}t|_dtjfdY}tj|dg}|||jt|jddS(NRcBs eZedZdZRS(cSs dddS(Nii((tcls((s1/usr/lib64/python2.7/unittest/test/test_result.pyt setUpClassscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyttest_foos(RRt classmethodRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi( RRRRURt TestSuiteRRR (RRRtsuite((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferSetupClasss    cCsmtj}t|_dtjfdY}tj|dg}|||jt|jddS(NRcBs eZedZdZRS(cSs dddS(Nii((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyt tearDownClassscSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyR s(RRRRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi( RRRRURRRRR (RRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferTearDownClasss    cCstj}t|_dtjfdY}dtfdY}d|_|tjd<|j tjj dtj |dg}|||j t |jddS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyRs(RRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRstModulecBseZedZRS(cSs dddS(Nii((((s1/usr/lib64/python2.7/unittest/test/test_result.pyt setUpModules(RRRqR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRsRi(RRRRURR?RR(tmodulesRtpopRRRR (RRRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferSetUpModules     cCstj}t|_dtjfdY}dtfdY}d|_|tjd<|j tjj dtj |dg}|||j t |jddS(NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_result.pyR's(RRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR&sRcBseZedZRS(cSs dddS(Nii((((s1/usr/lib64/python2.7/unittest/test/test_result.pyttearDownModule*s(RRRqR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyR)sRi(RRRRURR?RR(RRRRRRR (RRRRR((s1/usr/lib64/python2.7/unittest/test/test_result.pyttestBufferTearDownModule"s     ( RRRhRyR|RRRRRRR(((s1/usr/lib64/python2.7/unittest/test/test_result.pyRtvs    0  .   t__main__(R(RRRRRrRRRtdictRt__dict__t classDicttmR7RTttypeR?RXRYRoRsRtRtmain(((s1/usr/lib64/python2.7/unittest/test/test_result.pyts(    !    4  PK!Fcw!!test/test_runner.pynu[import unittest from cStringIO import StringIO import pickle from unittest.test.support import (LoggingResult, ResultWithNoStartTestRunStopTestRun) class TestCleanUp(unittest.TestCase): def testCleanUp(self): class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') self.assertEqual(test._cleanups, []) cleanups = [] def cleanup1(*args, **kwargs): cleanups.append((1, args, kwargs)) def cleanup2(*args, **kwargs): cleanups.append((2, args, kwargs)) test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye') test.addCleanup(cleanup2) self.assertEqual(test._cleanups, [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')), (cleanup2, (), {})]) result = test.doCleanups() self.assertTrue(result) self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))]) def testCleanUpWithErrors(self): class TestableTest(unittest.TestCase): def testNothing(self): pass class MockResult(object): errors = [] def addError(self, test, exc_info): self.errors.append((test, exc_info)) result = MockResult() test = TestableTest('testNothing') test._resultForDoCleanups = result exc1 = Exception('foo') exc2 = Exception('bar') def cleanup1(): raise exc1 def cleanup2(): raise exc2 test.addCleanup(cleanup1) test.addCleanup(cleanup2) self.assertFalse(test.doCleanups()) (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors) self.assertEqual((test1, Type1, instance1), (test, Exception, exc1)) self.assertEqual((test2, Type2, instance2), (test, Exception, exc2)) def testCleanupInRun(self): blowUp = False ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') if blowUp: raise Exception('foo') def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') def cleanup2(): ordering.append('cleanup2') test.addCleanup(cleanup1) test.addCleanup(cleanup2) def success(some_test): self.assertEqual(some_test, test) ordering.append('success') result = unittest.TestResult() result.addSuccess = success test.run(result) self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup2', 'cleanup1', 'success']) blowUp = True ordering = [] test = TestableTest('testNothing') test.addCleanup(cleanup1) test.run(result) self.assertEqual(ordering, ['setUp', 'cleanup1']) def testTestCaseDebugExecutesCleanups(self): ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') self.addCleanup(cleanup1) def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') test.addCleanup(cleanup2) def cleanup2(): ordering.append('cleanup2') test.debug() self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2']) class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" def test_init(self): runner = unittest.TextTestRunner() self.assertFalse(runner.failfast) self.assertFalse(runner.buffer) self.assertEqual(runner.verbosity, 1) self.assertTrue(runner.descriptions) self.assertEqual(runner.resultclass, unittest.TextTestResult) def test_multiple_inheritance(self): class AResult(unittest.TestResult): def __init__(self, stream, descriptions, verbosity): super(AResult, self).__init__(stream, descriptions, verbosity) class ATextResult(unittest.TextTestResult, AResult): pass # This used to raise an exception due to TextTestResult not passing # on arguments in its __init__ super call ATextResult(None, None, 1) def testBufferAndFailfast(self): class Test(unittest.TestCase): def testFoo(self): pass result = unittest.TestResult() runner = unittest.TextTestRunner(stream=StringIO(), failfast=True, buffer=True) # Use our result object runner._makeResult = lambda: result runner.run(Test('testFoo')) self.assertTrue(result.failfast) self.assertTrue(result.buffer) def testRunnerRegistersResult(self): class Test(unittest.TestCase): def testFoo(self): pass originalRegisterResult = unittest.runner.registerResult def cleanup(): unittest.runner.registerResult = originalRegisterResult self.addCleanup(cleanup) result = unittest.TestResult() runner = unittest.TextTestRunner(stream=StringIO()) # Use our result object runner._makeResult = lambda: result self.wasRegistered = 0 def fakeRegisterResult(thisResult): self.wasRegistered += 1 self.assertEqual(thisResult, result) unittest.runner.registerResult = fakeRegisterResult runner.run(unittest.TestSuite()) self.assertEqual(self.wasRegistered, 1) def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' def printErrors(self): pass class Runner(unittest.TextTestRunner): def __init__(self): super(Runner, self).__init__(StringIO()) def _makeResult(self): return OldTextResult() runner = Runner() runner.run(unittest.TestSuite()) def test_startTestRun_stopTestRun_called(self): class LoggingTextResult(LoggingResult): separator2 = '' def printErrors(self): pass class LoggingRunner(unittest.TextTestRunner): def __init__(self, events): super(LoggingRunner, self).__init__(StringIO()) self._events = events def _makeResult(self): return LoggingTextResult(self._events) events = [] runner = LoggingRunner(events) runner.run(unittest.TestSuite()) expected = ['startTestRun', 'stopTestRun'] self.assertEqual(events, expected) def test_pickle_unpickle(self): # Issue #7197: a TextTestRunner should be (un)pickleable. This is # required by test_multiprocessing under Windows (in verbose mode). from StringIO import StringIO as PickleableIO # cStringIO objects are not pickleable, but StringIO objects are. stream = PickleableIO("foo") runner = unittest.TextTestRunner(stream) for protocol in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(runner, protocol=protocol) obj = pickle.loads(s) # StringIO objects never compare equal, a cheap test instead. self.assertEqual(obj.stream.getvalue(), stream.getvalue()) def test_resultclass(self): def MockResultClass(*args): return args STREAM = object() DESCRIPTIONS = object() VERBOSITY = object() runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY, resultclass=MockResultClass) self.assertEqual(runner.resultclass, MockResultClass) expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY) self.assertEqual(runner._makeResult(), expectedresult) if __name__ == '__main__': unittest.main() PK!4-7-7test/test_runner.pycnu[ |fc@sddlZddlmZddlZddlmZmZdejfdYZdejfdYZ e dkrej ndS( iN(tStringIO(t LoggingResultt#ResultWithNoStartTestRunStopTestRunt TestCleanUpcBs,eZdZdZdZdZRS(c sdtjfdY}|d}|j|jggfd}fd}|j|dddd d d d |j||j|j|d td d d d f|difg|j}|j||jddifddtd d d d fgdS(Nt TestableTestcBseZdZRS(cSsdS(N((tself((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt testNothings(t__name__t __module__R(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR sRcsjd||fdS(Ni(tappend(targstkwargs(tcleanups(s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanup1scsjd||fdS(Ni(R (R R (R (s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanup2siiitfourthellotfivetgoodbye(iii(((iii(tunittesttTestCaset assertEqualt _cleanupst addCleanuptdictt doCleanupst assertTrue(RRttestR Rtresult((R s1/usr/lib64/python2.7/unittest/test/test_runner.pyt testCleanUp s "    cs+dtjfdY}dtfdY}|}|d}||_tdtdfd}fd }|j||j||j|jt|j \\}\}} } \} \} } } |j ||| f|tf|j | | | f|tfdS( NRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR+s(RRR(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR*st MockResultcBseZgZdZRS(cSs|jj||fdS(N(terrorsR (RRtexc_info((s1/usr/lib64/python2.7/unittest/test/test_runner.pytaddError0s(RRRR!(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR.sRtfootbarcs dS(N(((texc1(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR 9scs dS(N(((texc2(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR<s( RRtobjectt_resultForDoCleanupst ExceptionRt assertFalseRtreversedRR(RRRRRR Rttest1tType1t instance1t_ttest2tType2t instance2((R$R%s1/usr/lib64/python2.7/unittest/test/test_runner.pyttestCleanUpWithErrors)s       3"cstgdtjffdY}|dfd}fd}j|j|fd}tj}||_j|jddd d d d gtg|dj|j|jdd gdS( NRcs8eZfdZfdZfdZRS(cs&jdr"tdndS(NtsetUpR"(R R((R(tblowUptordering(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR3Ms csjddS(NR(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRscsjddS(NttearDown(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR6Us(RRR3RR6((R4R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRLsRcsjddS(NR (R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR ZscsjddS(NR(R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR\scs!j|jddS(Ntsuccess(RR (t some_test(R5RR(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR7asR3RR6RR R7( tFalseRRRt TestResultt addSuccesstrunRtTrue(RRR RR7R((R4R5RRs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestCleanupInRunHs("         csgdtjffdY}|dfdfdj|jdddd d gdS( NRcs8eZfdZfdZfdZRS(csjd|jdS(NR3(R R(R(R R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR3ws csjddS(NR(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR{scsjddS(NR6(R (R(R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR6~s(RRR3RR6((R R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRvsRcsjdjdS(NR (R R((RR5R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyR s csjddS(NR(R ((R5(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRsR3RR6R R(RRtdebugR(RR((R RR5Rs1/usr/lib64/python2.7/unittest/test/test_runner.pyt!testTestCaseDebugExecutesCleanupsss"  (RRRR2R>R@(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR s   +tTest_TextTestRunnercBsVeZdZdZdZdZdZdZdZdZ dZ RS( sTests for TextTestRunner.cCsitj}|j|j|j|j|j|jd|j|j|j|j tj dS(Ni( RtTextTestRunnerR)tfailfasttbufferRt verbosityRt descriptionst resultclasstTextTestResult(Rtrunner((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt test_inits  csOdtjffdYdtjfdY}|ddddS(NtAResultcseZfdZRS(cs t|j|||dS(N(tsupert__init__(RtstreamRFRE(RK(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMs(RRRM((RK(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRKst ATextResultcBseZRS((RR(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyROsi(RR:RHtNone(RRO((RKs1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_multiple_inheritancescsdtjfdY}tjtjdtdtdt}fd|_|j|d|jj |jj dS(NtTestcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttestFoos(RRRS(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRsRNRCRDcsS(N(((R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyttRS( RRR:RBRR=t _makeResultR<RRCRD(RRRRI((Rs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestBufferAndFailfasts  csdtjfdY}tjjfd}j|tjtjdt}fd|_d_ fd}|tj_|j tj j j ddS( NRRcBseZdZRS(cSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRSs(RRRS(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRRscstj_dS(N(RRItregisterResult((toriginalRegisterResult(s1/usr/lib64/python2.7/unittest/test/test_runner.pytcleanupsRNcsS(N(((R(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRTRUics#jd7_j|dS(Ni(t wasRegisteredR(t thisResult(RR(s1/usr/lib64/python2.7/unittest/test/test_runner.pytfakeRegisterResultsi( RRRIRXRR:RBRRVR[R<t TestSuiteR(RRRRZRIR]((RYRRs1/usr/lib64/python2.7/unittest/test/test_runner.pyttestRunnerRegistersResults     csXdtfdYdtjffdY}|jtjdS(Nt OldTextResultcBseZdZdZRS(RUcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyt printErrorss(RRt separator2Ra(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyR`stRunnercs&eZfdZfdZRS(cst|jtdS(N(RLRMR(R(Rc(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMscsS(N((R(R`(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRVs(RRRMRV((R`Rc(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRcs(RRRBR<R^(RRI((R`Rcs1/usr/lib64/python2.7/unittest/test/test_runner.pyt7test_works_with_result_without_startTestRun_stopTestRuns" cs}dtfdYdtjffdYg}|}|jtjddg}|j||dS(NtLoggingTextResultcBseZdZdZRS(RUcSsdS(N((R((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRas(RRRbRa(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRest LoggingRunnercs&eZfdZfdZRS(cs&t|jt||_dS(N(RLRMRt_events(Rtevents(Rf(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRMscs |jS(N(Rg(R(Re(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRVs(RRRMRV((RfRe(s1/usr/lib64/python2.7/unittest/test/test_runner.pyRfst startTestRunt stopTestRun(RRRBR<R^R(RRhRItexpected((RfRes1/usr/lib64/python2.7/unittest/test/test_runner.pyt$test_startTestRun_stopTestRun_calleds"  cCsddlm}|d}tj|}x^ttjdD]I}tj|d|}tj|}|j|j j |j q?WdS(Ni(RR"itprotocol( RRRBtrangetpickletHIGHEST_PROTOCOLtdumpstloadsRRNtgetvalue(Rt PickleableIORNRIRmtstobj((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_pickle_unpickles cCs~d}t}t}t}tj|||d|}|j|j||j||f}|j|j|dS(NcWs|S(N((R ((s1/usr/lib64/python2.7/unittest/test/test_runner.pytMockResultClasssRG(R&RRBRRGRNRV(RRxtSTREAMt DESCRIPTIONSt VERBOSITYRItexpectedresult((s1/usr/lib64/python2.7/unittest/test/test_runner.pyttest_resultclasss     ( RRt__doc__RJRQRWR_RdRlRwR}(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyRAs     t__main__( Rt cStringIORRotunittest.test.supportRRRRRARtmain(((s1/usr/lib64/python2.7/unittest/test/test_runner.pyts  } PK!S.#Ď<<test/test_suite.pycnu[ |fc@sddlZddlZddlmZmZdefdYZdZdejefdYZ e dkrej ndS( iN(t LoggingResultt TestEqualitytTestcBs!eZdejfdYZRS(tFoocBs,eZdZdZdZdZRS(cCsdS(N((tself((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_1 tcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_2 RcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_3RcCsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pytrunTestR(t__name__t __module__RRRR (((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR s   (R R tunittesttTestCaseR(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR scGstjd|DS(Ncss|]}tj|VqdS(N(RR(t.0tn((s0/usr/lib64/python2.7/unittest/test/test_suite.pys s(R t TestSuite(tnames((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt _mk_TestSuitestTest_TestSuitecBsyeZejejfejejgfededfgZejedfejgedfeddeddfededfgZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZRS(RRRcCs&tj}|j|jddS(Ni(R Rt assertEqualtcountTestCases(Rtsuite((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_init__tests_optional0s cCs)tjg}|j|jddS(Ni(R RRR(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_init__empty_tests<scCsd}tj|}|j|jdtj|}|j|jdtjt|}|j|jddS(Ncss&tjdVtjdVdS(NcSsdS(N(tNone(((s0/usr/lib64/python2.7/unittest/test/test_suite.pytIRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRJR(R tFunctionTestCase(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestsHsi(R RRRtset(RRtsuite_1tsuite_2tsuite_3((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt"test_init__tests_from_any_iterableGs cCs5d}tj|}|j|jddS(Ncss8tjd}tj|gVtjdVdS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR^RcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR`R(R RR(tftc((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR]si(R RRR(RRR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt'test_init__TestSuite_instances_in_tests\s cCsYtjd}tjd}tj||f}|jt|||gdS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRjRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRkR(R RRRtlist(Rttest1ttest2R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt test_iteriscCs&tj}|j|jddS(Ni(R RRR(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_zero_simpleus cCsKdtjfdY}tjtjg}|j|jddS(NtTest1cBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttests(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR)si(R R RRR(RR)R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_zero_nestedscCsStjd}tjd}tj||f}|j|jddS(NcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRi(R RRRR(RR%R&R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_simplescCsdtjfdY}tjd}tjd}tj|d|f}tj|||df}|j|jddS(NR)cBseZdZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR%RcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR&R(R R R%R&(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR)s cSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N(R(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRR&R%i(R R RRRR(RR)R&ttest3tchildtparent((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_countTestCases_nesteds cCs?g}t|}tj}|j||j|gdS(N(RR RtrunR(RteventstresultR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_run__empty_suites    cCs?tj}y|jWntk r-nX|jddS(NsFailed to raise TypeError(R RR1t TypeErrortfail(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_run__requires_results   csygt}dtjffdY}|d|dg}tj|j||jddgdS(Nt LoggingCasecs)eZfdZdZdZRS(csjd|jdS(Nsrun %s(tappendt_testMethodName(RR3(R2(s0/usr/lib64/python2.7/unittest/test/test_suite.pyR1scSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR%RcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR&R(R R R1R%R&((R2(s0/usr/lib64/python2.7/unittest/test/test_suite.pyR8s R%R&s run test1s run test2(RR R RR1R(RR3R8R((R2s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_runs  cCsqdtjfdY}|d}tj}|j||j|jd|jt||gdS(NRcBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR*R(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRsR*i(R R RtaddTestRRR$(RRR*R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__TestCases    cCs}dtjfdY}tj|dg}tj}|j||j|jd|jt||gdS(NRcBseZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR*R(R R R*(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRsR*i(R R RR<RRR$(RRRR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__TestSuites   csdtjfdY}|d|dtjgfd}tj}|j||jt|t|tj}x|D]}|j|qW|j||dS(NRcBseZdZdZRS(cSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRRcSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRR(R R RR(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRs RRc3sVVVdS(N(((t inner_suiteRR(s0/usr/lib64/python2.7/unittest/test/test_suite.pytgens(R R RtaddTestsRR$R<(RRR@RRtt((R?RRs0/usr/lib64/python2.7/unittest/test/test_suite.pyt test_addTestss    cCsBtj}y|jdWntk r0nX|jddS(NisFailed to raise TypeError(R RRAR5R6(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__noniterables   cCs&tj}|jt|jddS(Ni(R Rt assertRaisesR5R<(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__noncallables cCs?tj}|jt|jt|jt|jtjdS(N(R RRER5R<R(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTest__casesuiteclasss cCs&tj}|jt|jddS(Ntfoo(R RRER5RA(RR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_addTests__string"s cCs9d}tj}|j||jtjdS(NcSsdS(N((t_((s0/usr/lib64/python2.7/unittest/test/test_suite.pytf's(R RR<R1t TestResult(RRKR((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_function_in_suite&s   csDdtjfdY}dtffdYd|_tjd<|jtjjdtj}|j |d|dg|j |j dtj }|j ||jj|jj|j|j|j|j|j t|jd|j t|jd |j |jddS( NRcBsDeZeZeZedZedZdZdZ RS(cSs t|_dS(N(tTruetwasSetUp(tcls((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt setUpClass5scSs t|_dS(N(RNt wasTornDown(RP((s0/usr/lib64/python2.7/unittest/test/test_suite.pyt tearDownClass8scSsdS(N((R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestPass;scSstdS(N(R6(R((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttestFail=s( R R tFalseRORRt classmethodRQRSRTRU(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyR2s  tModulecs>eZeZeZefdZefdZRS(cs t_dS(N(RNRO((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyt setUpModuleBscs t_dS(N(RNRR((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyttearDownModuleEs(R R RVRORRt staticmethodRYRZ((RX(s0/usr/lib64/python2.7/unittest/test/test_suite.pyRX?sRTRUiii(R R tobjectR tsystmodulest addCleanuptpopt BaseTestSuiteRARRRLR1t assertFalseRORRtlenterrorstfailuresttestsRun(RRRR3((RXs0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_basetestsuite1s"      cCsudtjfdY}|}tj}tj}|j||||j|j|j|jdS(NtMySuitecBseZeZdZRS(c_s#t|_tjj|||dS(N(RNtcalledR Rt__call__(Rtargstkw((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRj_s (R R RVRiRj(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRh]s(R RRLR<t assertTrueRiRbt_testRunEntered(RRhRR3twrapper((s0/usr/lib64/python2.7/unittest/test/test_suite.pyttest_overriding_call\s     (R R R RRteq_pairstne_pairsRRR!R#R'R(R+R,R0R4R7R;R=R>RCRDRFRGRIRMRgRp(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyRs:         +t__main__( R R]tunittest.test.supportRRR\RRR RR tmain(((s0/usr/lib64/python2.7/unittest/test/test_suite.pyts   X PK!A __init__.pycnu[ {fc@sDdZddddddddd d d d d dddddgZejdddgeZddlmZddlmZm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZmZmZmZmZddlmZmZddlmZmZddlm Z m!Z!m"Z"m#Z#eZ$dS(s Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework. 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 '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. t TestResulttTestCaset TestSuitetTextTestRunnert TestLoadertFunctionTestCasetmaintdefaultTestLoadertSkipTesttskiptskipIft skipUnlesstexpectedFailuretTextTestResulttinstallHandlertregisterResultt removeResultt removeHandlertgetTestCaseNamest makeSuitet findTestCasesi(R( RRRR R R R t_skipInRpmBuildt_expectedFailureInRpmBuild(t BaseTestSuiteR(RRRRR(t TestProgramR(RR (RRRRN(%t__doc__t__all__textendtTruet __unittesttresultRtcaseRRRR R R R RRtsuiteRRtloaderRRRRRRRtrunnerRR tsignalsRRRRt_TextTestResult(((s)/usr/lib64/python2.7/unittest/__init__.pyt-s   @("PK!A __init__.pyonu[ {fc@sDdZddddddddd d d d d dddddgZejdddgeZddlmZddlmZm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZmZmZmZmZddlmZmZddlmZmZddlm Z m!Z!m"Z"m#Z#eZ$dS(s Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework. 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 '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. t TestResulttTestCaset TestSuitetTextTestRunnert TestLoadertFunctionTestCasetmaintdefaultTestLoadertSkipTesttskiptskipIft skipUnlesstexpectedFailuretTextTestResulttinstallHandlertregisterResultt removeResultt removeHandlertgetTestCaseNamest makeSuitet findTestCasesi(R( RRRR R R R t_skipInRpmBuildt_expectedFailureInRpmBuild(t BaseTestSuiteR(RRRRR(t TestProgramR(RR (RRRRN(%t__doc__t__all__textendtTruet __unittesttresultRtcaseRRRR R R R RRtsuiteRRtloaderRRRRRRRtrunnerRR tsignalsRRRRt_TextTestResult(((s)/usr/lib64/python2.7/unittest/__init__.pyt-s   @("PK! FE __main__.pycnu[ {fc@stdZddlZejdjdr8dejds  PK! FE __main__.pyonu[ {fc@stdZddlZejdjdr8dejds  PK!u<΢΢case.pycnu[ {fc@s}dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z mZmZmZmZeZdZdefdYZd efd YZd efd YZd ZdZdZdZdZdZdZde fdYZ!de fdYZ"de"fdYZ#dS(sTest case implementationiNi(tresult(tstrclasst safe_reprtunorderable_list_differencet_count_diff_all_purposet_count_diff_hashables@ Diff is %s characters long. Set self.maxDiff to None to see it.tSkipTestcBseZdZRS(s 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. (t__name__t __module__t__doc__(((s%/usr/lib64/python2.7/unittest/case.pyRst_ExpectedFailurecBseZdZdZRS(s\ Raise this when a test is expected to fail. This is an implementation detail. cCs tt|j||_dS(N(tsuperR t__init__texc_info(tselfR ((s%/usr/lib64/python2.7/unittest/case.pyR *s(RRR R (((s%/usr/lib64/python2.7/unittest/case.pyR #st_UnexpectedSuccesscBseZdZRS(s7 The test was supposed to fail, but it didn't! (RRR (((s%/usr/lib64/python2.7/unittest/case.pyR.scCs|S(N((tobj((s%/usr/lib64/python2.7/unittest/case.pyt_id4scsfd}|S(s& Unconditionally skip a test. csUt|ttjfs?tj|fd}|}nt|_|_|S(NcstdS(N(R(targstkwargs(treason(s%/usr/lib64/python2.7/unittest/case.pyt skip_wrapper=s( t isinstancettypettypest ClassTypet functoolstwrapstTruet__unittest_skip__t__unittest_skip_why__(t test_itemR(R(s%/usr/lib64/python2.7/unittest/case.pyt decorator;s    ((RR ((Rs%/usr/lib64/python2.7/unittest/case.pytskip7s cCs|rt|StS(s/ Skip a test if the condition is true. (R!R(t conditionR((s%/usr/lib64/python2.7/unittest/case.pytskipIfGs cCs|st|StS(s3 Skip a test unless the condition is true. (R!R(R"R((s%/usr/lib64/python2.7/unittest/case.pyt skipUnlessOs cs"tjfd}|S(NcsAy||Wn#tk r6ttjnXtdS(N(t ExceptionR tsysR R(RR(tfunc(s%/usr/lib64/python2.7/unittest/case.pytwrapperYs  (RR(R'R(((R's%/usr/lib64/python2.7/unittest/case.pytexpectedFailureXscCs!dtjkrt|StSdS(s 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. tWITHIN_PYTHON_RPM_BUILDN(tostenvironR!R(R((s%/usr/lib64/python2.7/unittest/case.pyt_skipInRpmBuildfs cs"tjfd}|S(s  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. cs`dtjkrOy||Wn#tk rEttjnXtn ||dS(NR*(R+R,R%R R&R R(RR(R'(s%/usr/lib64/python2.7/unittest/case.pyR({s  (RR(R'R(((R's%/usr/lib64/python2.7/unittest/case.pyt_expectedFailureInRpmBuildss t_AssertRaisesContextcBs,eZdZddZdZdZRS(sCA context manager used to implement TestCase.assertRaises* methods.cCs"||_|j|_||_dS(N(texpectedtfailureExceptiontexpected_regexp(RR0t test_caseR2((s%/usr/lib64/python2.7/unittest/case.pyR s  cCs|S(N((R((s%/usr/lib64/python2.7/unittest/case.pyt __enter__scCs|dkrZy|jj}Wn tk r>t|j}nX|jdj|nt||jsptS||_ |j dkrt S|j }|j t|s|jd|j t|fnt S(Ns{0} not raiseds"%s" does not match "%s"(tNoneR0RtAttributeErrortstrR1tformatt issubclasstFalset exceptionR2Rtsearchtpattern(Rtexc_typet exc_valuettbtexc_nameR2((s%/usr/lib64/python2.7/unittest/case.pyt__exit__s"     N(RRR R5R R4RB(((s%/usr/lib64/python2.7/unittest/case.pyR/s  tTestCasecBs)eZdZeZeZd@ZdAZeZ ddZ dZ dZ d Z d Zed Zed Zd ZdZdZdZdZdZdZdZdZdZdBdZdZdZdZ dZ!dBdZ"dBdZ#dBdZ$dZ%dBd Z&d!Z'dBd"Z(dBd#Z)dBd$Z*dBdBdBd%Z+dBdBdBd&Z,e)Z-e*Z.e+Z/e,Z0e$Z1d'Z2e2e)Z3e2e*Z4e2e+Z5e2e,Z6e2e$Z7e2e&Z8e2e#Z9dBdBd(Z:d)Z;dBd*Z<dBd+Z=dBd,Z>dBd-Z?dBd.Z@dBd/ZAdBd0ZBdBd1ZCdBd2ZDdBd3ZEdBd4ZFdBd5ZGdBd6ZHdBd7ZIdBd8ZJdBd9ZKdBd:ZLdBd;ZMdBd<ZNdBd=ZOdBd>ZPdBd?ZQRS(CsWA 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. iPiiitrunTestcCs||_d|_yt||}Wn*tk rQtd|j|fnX|j|_g|_ i|_ |j t d|j t d|j td|j td|j tdy|j tdWntk rnXdS(sCreate 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. sno such test method in %s: %stassertDictEqualtassertListEqualtassertTupleEqualtassertSetEqualtassertMultiLineEqualN(t_testMethodNameR5t_resultForDoCleanupstgetattrR6t ValueErrort __class__R t_testMethodDoct _cleanupst_type_equality_funcstaddTypeEqualityFunctdicttlistttupletsett frozensettunicodet NameError(Rt methodNamet testMethod((s%/usr/lib64/python2.7/unittest/case.pyR s&       cCs||j|(RRNRJ(R((s%/usr/lib64/python2.7/unittest/case.pyt__repr__@scCsRt|dd}|dk r.|||n tjdtd|j|dS(NtaddSkips4TestResult has no addSkip method, skips not reportedi(RLR5twarningstwarntRuntimeWarningt addSuccess(RRRRv((s%/usr/lib64/python2.7/unittest/case.pyt_addSkipDs    c Csr|}|dkrI|j}t|dd}|dk rI|qIn||_|j|t||j}t|jdtst|dtrz;t|jddpt|dd}|j||Wd|j |XdSz>t}y|j WnXt k r*}|j|t |nt k r=n|j|tjnXy |WnBt k r{n5|jk r|j|tjn tk r}t|dd}|dk r|||jqtjdt|j|ntk ret|dd} | dk r<| |qtjdt|j|tjnKt k r}|j|t |n#|j|tjnXt}y|jWn6t k rn#|j|tjt}nX|j} |o | }|r%|j|nWd|j ||dkrmt|d d} | dk rm| qmnXdS( Nt startTestRunRRRdtaddExpectedFailures@TestResult has no addExpectedFailure method, reporting as passestaddUnexpectedSuccesssDTestResult has no addUnexpectedSuccess method, reporting as failurest stopTestRun(R5RhRLRKt startTestRJRNR:R{tstopTestR`RR7tKeyboardInterrupttaddErrorR&R R1t addFailureR RwRxRyRzRRRat doCleanups( RRt orig_resultR|R[tskip_whytsuccessteR}R~tcleanUpSuccessR((s%/usr/lib64/python2.7/unittest/case.pytrunMs                      cCs|j}t}xr|jr|jjd\}}}y|||Wqtk r]qt}|j|tjqXqW|S(sNExecute all cleanup functions. Normally called for you after tearDown.i( RKRRPtpopRR:RR&R (RRtokR]RR((s%/usr/lib64/python2.7/unittest/case.pyRs   cOs|j||S(N(R(RRtkwds((s%/usr/lib64/python2.7/unittest/case.pyt__call__scCsc|jt||j|jx5|jr^|jjd\}}}|||q*WdS(s6Run the test without collecting errors in a TestResultiN(R`RLRJRaRPR(RR]RR((s%/usr/lib64/python2.7/unittest/case.pytdebugs    cCst|dS(sSkip this test.N(R(RR((s%/usr/lib64/python2.7/unittest/case.pytskipTestscCs|j|dS(s)Fail immediately, with the given message.N(R1(Rtmsg((s%/usr/lib64/python2.7/unittest/case.pytfailscCs8|r4|j|dt|}|j|ndS(s#Check that the expression is false.s%s is not falseN(t_formatMessageRR1(RtexprR((s%/usr/lib64/python2.7/unittest/case.pyt assertFalsescCs8|s4|j|dt|}|j|ndS(s"Check that the expression is true.s%s is not trueN(RRR1(RRR((s%/usr/lib64/python2.7/unittest/case.pyt assertTruescCsd|js|p|S|dkr#|Syd||fSWn(tk r_dt|t|fSXdS(sHonour 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 s%s : %sN(t longMessageR5tUnicodeDecodeErrorR(RRt standardMsg((s%/usr/lib64/python2.7/unittest/case.pyRs    cOs=t||}|dkr|S||||WdQXdS(sFail 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() 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) N(R/R5(RtexcClasst callableObjRRtcontext((s%/usr/lib64/python2.7/unittest/case.pyt assertRaisess  cCskt|t|krd|jjt|}|dk rdt|tr]t||}n|Sn|jS(sGet 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(RRQtgetR5Rt basestringRLt_baseAssertEqual(Rtfirsttsecondtasserter((s%/usr/lib64/python2.7/unittest/case.pyt_getAssertEqualityFuncs cCsP||ksLdt|t|f}|j||}|j|ndS(s:The default assertEqual implementation, not type specific.s%s != %sN(RRR1(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyRs cCs)|j||}|||d|dS(s[Fail if the two objects are unequal as determined by the '==' operator. RN(R(RRRRtassertion_func((s%/usr/lib64/python2.7/unittest/case.pyt assertEqual"scCsJ||ksF|j|dt|t|f}|j|ndS(sYFail if the two objects are equal as determined by the '!=' operator. s%s == %sN(RRR1(RRRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotEqual)s cCs||krdS|dk r7|dk r7tdn|dk rt|||kr]dSdt|t|t|f}nW|dkrd}ntt|||dkrdSdt|t||f}|j||}|j|dS(s'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. Ns specify delta or places not boths%s != %s within %s deltaiis%s != %s within %r places(R5t TypeErrortabsRtroundRR1(RRRtplacesRtdeltaR((s%/usr/lib64/python2.7/unittest/case.pytassertAlmostEqual3s&         cCs |dk r'|dk r'tdn|dk r||k rZt|||krZdSdt|t|t|f}nd|dkrd}n||k rtt|||dkrdSdt|t||f}|j||}|j|dS(sFail 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. s specify delta or places not bothNs%s == %s within %s deltaiis%s == %s within %r places(R5RRRRRR1(RRRRRRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotAlmostEqualZs"  #    ,   csfd}|S(Ncs,tjdjjtd||S(NsPlease use {0} instead.i(RwRxR8RtPendingDeprecationWarning(RR(t original_func(s%/usr/lib64/python2.7/unittest/case.pytdeprecated_funcs ((RR((Rs%/usr/lib64/python2.7/unittest/case.pyt _deprecatescCs |dk rz|j}t||sF|jd|t|fnt||s|jd|t|fqnd}d}yt|}Wn!ttfk rd|}nX|dkryt|}Wqttfk rd|}qXn|dkr||krdSt|} t|} t| dkrT| d d} nt| dkrw| d d} n|j| | f} d | }xt t ||D]} y|| } Wn/tt tfk r|d | |f7}PnXy|| }Wn/tt tfk r1|d | |f7}PnX| |kr|d | t| t|f7}PqqW||kr|dkrt |t |krdS||kr|d |||f7}y"|d|t||f7}Wqtt tfk r|d||f7}qXq||kr|d|||f7}y"|d|t||f7}Wqtt tfk r|d||f7}qXqn|}ddj tjtj|jtj|j}|j||}|j||}|j|dS(sAAn 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. sFirst sequence is not a %s: %ssSecond sequence is not a %s: %stsequences(First %s has no length. Non-sequence?s)Second %s has no length. Non-sequence?Nis...s%ss differ: %s != %s s( Unable to index element %d of first %s s) Unable to index element %d of second %s s# First differing element %d: %s %s s+ First %s contains %d additional elements. sFirst extra element %d: %s s'Unable to index element %d of first %s s, Second %s contains %d additional elements. s(Unable to index element %d of second %s s (R5RRR1RtlenRtNotImplementedErrort capitalizetxrangetmint IndexErrorRtjointdifflibtndifftpprinttpformatt splitlinest_truncateMessageRR(Rtseq1tseq2Rtseq_typet seq_type_namet differingtlen1tlen2t seq1_reprt seq2_reprtelementstititem1titem2RtdiffMsg((s%/usr/lib64/python2.7/unittest/case.pytassertSequenceEquals               cCsA|j}|dks't||kr/||S|tt|S(N(tmaxDiffR5Rt DIFF_OMITTED(Rtmessagetdifftmax_diff((s%/usr/lib64/python2.7/unittest/case.pyRs cCs|j|||dtdS(sA 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(RRT(Rtlist1tlist2R((s%/usr/lib64/python2.7/unittest/case.pyRFs cCs|j|||dtdS(sA 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(RRU(Rttuple1ttuple2R((s%/usr/lib64/python2.7/unittest/case.pyRGs c Cspy|j|}WnGtk r9}|jd|n$tk r\}|jd|nXy|j|}WnGtk r}|jd|n$tk r}|jd|nX|p|sdSg}|r |jdx$|D]}|jt|qWn|rD|jdx$|D]}|jt|q$Wndj|} |j|j|| dS(sA 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). s/invalid type when attempting set difference: %ss2first argument does not support set difference: %ss3second argument does not support set difference: %sNs*Items in the first set but not the second:s*Items in the second set but not the first:s (t differenceRRR6R^treprRR( Rtset1tset2Rt difference1Rt difference2tlinestitemR((s%/usr/lib64/python2.7/unittest/case.pyRHs2      cCsH||krDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a in b), but with a nicer default message.s%s not found in %sN(RRR(Rtmembert containerRR((s%/usr/lib64/python2.7/unittest/case.pytassertInEs  cCsH||krDdt|t|f}|j|j||ndS(sHJust like self.assertTrue(a not in b), but with a nicer default message.s%s unexpectedly found in %sN(RRR(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertNotInLs  cCsH||k rDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a is b), but with a nicer default message.s %s is not %sN(RRR(Rtexpr1texpr2RR((s%/usr/lib64/python2.7/unittest/case.pytassertIsSs  cCs?||kr;dt|f}|j|j||ndS(sHJust like self.assertTrue(a is not b), but with a nicer default message.sunexpectedly identical: %sN(RRR(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertIsNotZs cCs|j|td|j|td||krdt|tt|tf}ddjtjtj|j tj|j }|j ||}|j |j ||ndS(Ns"First argument is not a dictionarys#Second argument is not a dictionarys%s != %ss ( tassertIsInstanceRSRRRRRRRRRRR(Rtd1td2RRR((s%/usr/lib64/python2.7/unittest/case.pyRE`s "c Csg}g}xy|jD]k\}}||krA|j|q|||kr|jdt|t|t||fqqW|p|sdSd}|rddjd|D}n|r|r|d7}n|ddj|7}n|j|j||dS( s0Checks whether actual is a superset of expected.s%s, expected: %s, actual: %sNRds Missing: %st,css|]}t|VqdS(N(R(t.0tm((s%/usr/lib64/python2.7/unittest/case.pys }ss; sMismatched values: %s(t iteritemsR^RRRR( RR0tactualRtmissingt mismatchedtkeytvalueR((s%/usr/lib64/python2.7/unittest/case.pytassertDictContainsSubsetls(    c Cs9t|t|}}tjtjr_x-dddgD]}tjd|tq?Wny"tj|}tj|}Wn t k rt ||} n X||krdSt ||} WdQX| r5d} g| D]} d| ^q} dj | } |j | | } |j|| }|j|ndS( sAn unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. s'(code|dict|type) inequality comparisonss,builtin_function_or_method order comparisonsscomparing unequal typestignoreNsElement counts were not equal: s First has %d, Second has %d: %rs (RTRwtcatch_warningsR&t py3kwarningtfilterwarningstDeprecationWarningt collectionstCounterRRRRRRR(Rt expected_seqt actual_seqRt first_seqt second_seqt_msgRRt differencesRRRR((s%/usr/lib64/python2.7/unittest/case.pytassertItemsEquals,      cCsG|j|td|j|td||krCt||jks\t||jkrr|j|||n|jt}|jt}t|dkr|jd|kr|dg}|dg}ndt|tt|tf}ddj t j ||}|j ||}|j |j||ndS( s-Assert that two multi-line strings are equal.sFirst argument is not a stringsSecond argument is not a stringis s s%s != %sRdN(RRRt_diffThresholdRRRRjRRRRRRR(RRRRt firstlinest secondlinesRR((s%/usr/lib64/python2.7/unittest/case.pyRIs$   ' cCsH||ksDdt|t|f}|j|j||ndS(sCJust like self.assertTrue(a < b), but with a nicer default message.s%s not less than %sN(RRR(RtatbRR((s%/usr/lib64/python2.7/unittest/case.pyt assertLesss cCsH||ksDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a <= b), but with a nicer default message.s%s not less than or equal to %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pytassertLessEquals cCsH||ksDdt|t|f}|j|j||ndS(sCJust like self.assertTrue(a > b), but with a nicer default message.s%s not greater than %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pyt assertGreaters cCsH||ksDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a >= b), but with a nicer default message.s"%s not greater than or equal to %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pytassertGreaterEquals cCs?|dk r;dt|f}|j|j||ndS(sCSame as self.assertTrue(obj is None), with a nicer default message.s%s is not NoneN(R5RRR(RRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertIsNones cCs2|dkr.d}|j|j||ndS(s(Included for symmetry with assertIsNone.sunexpectedly NoneN(R5RR(RRRR((s%/usr/lib64/python2.7/unittest/case.pytassertIsNotNones cCsEt||sAdt||f}|j|j||ndS(sTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.s%s is not an instance of %rN(RRRR(RRRbRR((s%/usr/lib64/python2.7/unittest/case.pyRscCsEt||rAdt||f}|j|j||ndS(s,Included for symmetry with assertIsInstance.s%s is an instance of %rN(RRRR(RRRbRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotIsInstancescOs^|dk rtj|}nt|||}|dkr@|S||||WdQXdS(sAsserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs. N(R5tretcompileR/(Rtexpected_exceptionR2t callable_objRRR((s%/usr/lib64/python2.7/unittest/case.pytassertRaisesRegexps  cCsht|tr!tj|}n|j|sd|p9d}d||j|f}|j|ndS(s=Fail the test unless the text matches the regular expression.sRegexp didn't matchs%s: %r not found in %rN(RRRRR<R=R1(RttextR2R((s%/usr/lib64/python2.7/unittest/case.pytassertRegexpMatches s  cCst|tr!tj|}n|j|}|r|p?d}d|||j|j!|j|f}|j|ndS(s9Fail the test if the text matches the regular expression.sRegexp matcheds%s: %r matches %r in %rN( RRRRR<tstarttendR=R1(RRtunexpected_regexpRtmatch((s%/usr/lib64/python2.7/unittest/case.pytassertNotRegexpMatchess  iiN(RRRR tAssertionErrorR1R:RRRt_classSetupFailedR RRR_R`Rat classmethodRcReRfRhRlRmRpRqRsRtRuR{R5RRRRRRRRRRRRRRRRt assertEqualstassertNotEqualstassertAlmostEqualstassertNotAlmostEqualstassert_RtfailUnlessEqualt failIfEqualtfailUnlessAlmostEqualtfailIfAlmostEqualt failUnlesstfailUnlessRaisestfailIfRRRFRGRHRRRRRERRRIR R R R RRRRRRR(((s%/usr/lib64/python2.7/unittest/case.pyRCs              Q            '$        g  +      (           tFunctionTestCasecBszeZdZd d d dZdZdZdZdZdZ dZ dZ d Z d Z d ZRS( sIA 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. cCs;tt|j||_||_||_||_dS(N(R R,R t _setUpFunct _tearDownFunct _testFunct _description(RttestFuncR`Rat description((s%/usr/lib64/python2.7/unittest/case.pyR *s    cCs |jdk r|jndS(N(R-R5(R((s%/usr/lib64/python2.7/unittest/case.pyR`1scCs |jdk r|jndS(N(R.R5(R((s%/usr/lib64/python2.7/unittest/case.pyRa5scCs|jdS(N(R/(R((s%/usr/lib64/python2.7/unittest/case.pyRD9scCs |jjS(N(R/R(R((s%/usr/lib64/python2.7/unittest/case.pyRm<scCs\t||jstS|j|jko[|j|jko[|j|jko[|j|jkS(N(RRNRnR-R.R/R0(RRo((s%/usr/lib64/python2.7/unittest/case.pyRp?s cCs ||k S(N((RRo((s%/usr/lib64/python2.7/unittest/case.pyRqHscCs+tt||j|j|j|jfS(N(RrRR-R.R/R0(R((s%/usr/lib64/python2.7/unittest/case.pyRsKscCsdt|j|jjfS(Ns%s (%s)(RRNR/R(R((s%/usr/lib64/python2.7/unittest/case.pyRtOscCsdt|j|jfS(Ns <%s tec=%s>(RRNR/(R((s%/usr/lib64/python2.7/unittest/case.pyRuSscCsE|jdk r|jS|jj}|rA|jddjpDdS(Ns i(R0R5R/R RiRj(RRk((s%/usr/lib64/python2.7/unittest/case.pyRlWs N(RRR R5R R`RaRDRmRpRqRsRtRuRl(((s%/usr/lib64/python2.7/unittest/case.pyR,!s        ($R RR+R&RRRRRRwRdRtutilRRRRRRt __unittestRR%RR RRR!R#R$R)R-R.tobjectR/RCR,(((s%/usr/lib64/python2.7/unittest/case.pyts:         (       !{PK!u<΢΢case.pyonu[ {fc@s}dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z mZmZmZmZeZdZdefdYZd efd YZd efd YZd ZdZdZdZdZdZdZde fdYZ!de fdYZ"de"fdYZ#dS(sTest case implementationiNi(tresult(tstrclasst safe_reprtunorderable_list_differencet_count_diff_all_purposet_count_diff_hashables@ Diff is %s characters long. Set self.maxDiff to None to see it.tSkipTestcBseZdZRS(s 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. (t__name__t __module__t__doc__(((s%/usr/lib64/python2.7/unittest/case.pyRst_ExpectedFailurecBseZdZdZRS(s\ Raise this when a test is expected to fail. This is an implementation detail. cCs tt|j||_dS(N(tsuperR t__init__texc_info(tselfR ((s%/usr/lib64/python2.7/unittest/case.pyR *s(RRR R (((s%/usr/lib64/python2.7/unittest/case.pyR #st_UnexpectedSuccesscBseZdZRS(s7 The test was supposed to fail, but it didn't! (RRR (((s%/usr/lib64/python2.7/unittest/case.pyR.scCs|S(N((tobj((s%/usr/lib64/python2.7/unittest/case.pyt_id4scsfd}|S(s& Unconditionally skip a test. csUt|ttjfs?tj|fd}|}nt|_|_|S(NcstdS(N(R(targstkwargs(treason(s%/usr/lib64/python2.7/unittest/case.pyt skip_wrapper=s( t isinstancettypettypest ClassTypet functoolstwrapstTruet__unittest_skip__t__unittest_skip_why__(t test_itemR(R(s%/usr/lib64/python2.7/unittest/case.pyt decorator;s    ((RR ((Rs%/usr/lib64/python2.7/unittest/case.pytskip7s cCs|rt|StS(s/ Skip a test if the condition is true. (R!R(t conditionR((s%/usr/lib64/python2.7/unittest/case.pytskipIfGs cCs|st|StS(s3 Skip a test unless the condition is true. (R!R(R"R((s%/usr/lib64/python2.7/unittest/case.pyt skipUnlessOs cs"tjfd}|S(NcsAy||Wn#tk r6ttjnXtdS(N(t ExceptionR tsysR R(RR(tfunc(s%/usr/lib64/python2.7/unittest/case.pytwrapperYs  (RR(R'R(((R's%/usr/lib64/python2.7/unittest/case.pytexpectedFailureXscCs!dtjkrt|StSdS(s 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. tWITHIN_PYTHON_RPM_BUILDN(tostenvironR!R(R((s%/usr/lib64/python2.7/unittest/case.pyt_skipInRpmBuildfs cs"tjfd}|S(s  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. cs`dtjkrOy||Wn#tk rEttjnXtn ||dS(NR*(R+R,R%R R&R R(RR(R'(s%/usr/lib64/python2.7/unittest/case.pyR({s  (RR(R'R(((R's%/usr/lib64/python2.7/unittest/case.pyt_expectedFailureInRpmBuildss t_AssertRaisesContextcBs,eZdZddZdZdZRS(sCA context manager used to implement TestCase.assertRaises* methods.cCs"||_|j|_||_dS(N(texpectedtfailureExceptiontexpected_regexp(RR0t test_caseR2((s%/usr/lib64/python2.7/unittest/case.pyR s  cCs|S(N((R((s%/usr/lib64/python2.7/unittest/case.pyt __enter__scCs|dkrZy|jj}Wn tk r>t|j}nX|jdj|nt||jsptS||_ |j dkrt S|j }|j t|s|jd|j t|fnt S(Ns{0} not raiseds"%s" does not match "%s"(tNoneR0RtAttributeErrortstrR1tformatt issubclasstFalset exceptionR2Rtsearchtpattern(Rtexc_typet exc_valuettbtexc_nameR2((s%/usr/lib64/python2.7/unittest/case.pyt__exit__s"     N(RRR R5R R4RB(((s%/usr/lib64/python2.7/unittest/case.pyR/s  tTestCasecBs)eZdZeZeZd@ZdAZeZ ddZ dZ dZ d Z d Zed Zed Zd ZdZdZdZdZdZdZdZdZdZdBdZdZdZdZ dZ!dBdZ"dBdZ#dBdZ$dZ%dBd Z&d!Z'dBd"Z(dBd#Z)dBd$Z*dBdBdBd%Z+dBdBdBd&Z,e)Z-e*Z.e+Z/e,Z0e$Z1d'Z2e2e)Z3e2e*Z4e2e+Z5e2e,Z6e2e$Z7e2e&Z8e2e#Z9dBdBd(Z:d)Z;dBd*Z<dBd+Z=dBd,Z>dBd-Z?dBd.Z@dBd/ZAdBd0ZBdBd1ZCdBd2ZDdBd3ZEdBd4ZFdBd5ZGdBd6ZHdBd7ZIdBd8ZJdBd9ZKdBd:ZLdBd;ZMdBd<ZNdBd=ZOdBd>ZPdBd?ZQRS(CsWA 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. iPiiitrunTestcCs||_d|_yt||}Wn*tk rQtd|j|fnX|j|_g|_ i|_ |j t d|j t d|j td|j td|j tdy|j tdWntk rnXdS(sCreate 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. sno such test method in %s: %stassertDictEqualtassertListEqualtassertTupleEqualtassertSetEqualtassertMultiLineEqualN(t_testMethodNameR5t_resultForDoCleanupstgetattrR6t ValueErrort __class__R t_testMethodDoct _cleanupst_type_equality_funcstaddTypeEqualityFunctdicttlistttupletsett frozensettunicodet NameError(Rt methodNamet testMethod((s%/usr/lib64/python2.7/unittest/case.pyR s&       cCs||j|(RRNRJ(R((s%/usr/lib64/python2.7/unittest/case.pyt__repr__@scCsRt|dd}|dk r.|||n tjdtd|j|dS(NtaddSkips4TestResult has no addSkip method, skips not reportedi(RLR5twarningstwarntRuntimeWarningt addSuccess(RRRRv((s%/usr/lib64/python2.7/unittest/case.pyt_addSkipDs    c Csr|}|dkrI|j}t|dd}|dk rI|qIn||_|j|t||j}t|jdtst|dtrz;t|jddpt|dd}|j||Wd|j |XdSz>t}y|j WnXt k r*}|j|t |nt k r=n|j|tjnXy |WnBt k r{n5|jk r|j|tjn tk r}t|dd}|dk r|||jqtjdt|j|ntk ret|dd} | dk r<| |qtjdt|j|tjnKt k r}|j|t |n#|j|tjnXt}y|jWn6t k rn#|j|tjt}nX|j} |o | }|r%|j|nWd|j ||dkrmt|d d} | dk rm| qmnXdS( Nt startTestRunRRRdtaddExpectedFailures@TestResult has no addExpectedFailure method, reporting as passestaddUnexpectedSuccesssDTestResult has no addUnexpectedSuccess method, reporting as failurest stopTestRun(R5RhRLRKt startTestRJRNR:R{tstopTestR`RR7tKeyboardInterrupttaddErrorR&R R1t addFailureR RwRxRyRzRRRat doCleanups( RRt orig_resultR|R[tskip_whytsuccessteR}R~tcleanUpSuccessR((s%/usr/lib64/python2.7/unittest/case.pytrunMs                      cCs|j}t}xr|jr|jjd\}}}y|||Wqtk r]qt}|j|tjqXqW|S(sNExecute all cleanup functions. Normally called for you after tearDown.i( RKRRPtpopRR:RR&R (RRtokR]RR((s%/usr/lib64/python2.7/unittest/case.pyRs   cOs|j||S(N(R(RRtkwds((s%/usr/lib64/python2.7/unittest/case.pyt__call__scCsc|jt||j|jx5|jr^|jjd\}}}|||q*WdS(s6Run the test without collecting errors in a TestResultiN(R`RLRJRaRPR(RR]RR((s%/usr/lib64/python2.7/unittest/case.pytdebugs    cCst|dS(sSkip this test.N(R(RR((s%/usr/lib64/python2.7/unittest/case.pytskipTestscCs|j|dS(s)Fail immediately, with the given message.N(R1(Rtmsg((s%/usr/lib64/python2.7/unittest/case.pytfailscCs8|r4|j|dt|}|j|ndS(s#Check that the expression is false.s%s is not falseN(t_formatMessageRR1(RtexprR((s%/usr/lib64/python2.7/unittest/case.pyt assertFalsescCs8|s4|j|dt|}|j|ndS(s"Check that the expression is true.s%s is not trueN(RRR1(RRR((s%/usr/lib64/python2.7/unittest/case.pyt assertTruescCsd|js|p|S|dkr#|Syd||fSWn(tk r_dt|t|fSXdS(sHonour 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 s%s : %sN(t longMessageR5tUnicodeDecodeErrorR(RRt standardMsg((s%/usr/lib64/python2.7/unittest/case.pyRs    cOs=t||}|dkr|S||||WdQXdS(sFail 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() 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) N(R/R5(RtexcClasst callableObjRRtcontext((s%/usr/lib64/python2.7/unittest/case.pyt assertRaisess  cCskt|t|krd|jjt|}|dk rdt|tr]t||}n|Sn|jS(sGet 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(RRQtgetR5Rt basestringRLt_baseAssertEqual(Rtfirsttsecondtasserter((s%/usr/lib64/python2.7/unittest/case.pyt_getAssertEqualityFuncs cCsP||ksLdt|t|f}|j||}|j|ndS(s:The default assertEqual implementation, not type specific.s%s != %sN(RRR1(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyRs cCs)|j||}|||d|dS(s[Fail if the two objects are unequal as determined by the '==' operator. RN(R(RRRRtassertion_func((s%/usr/lib64/python2.7/unittest/case.pyt assertEqual"scCsJ||ksF|j|dt|t|f}|j|ndS(sYFail if the two objects are equal as determined by the '!=' operator. s%s == %sN(RRR1(RRRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotEqual)s cCs||krdS|dk r7|dk r7tdn|dk rt|||kr]dSdt|t|t|f}nW|dkrd}ntt|||dkrdSdt|t||f}|j||}|j|dS(s'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. Ns specify delta or places not boths%s != %s within %s deltaiis%s != %s within %r places(R5t TypeErrortabsRtroundRR1(RRRtplacesRtdeltaR((s%/usr/lib64/python2.7/unittest/case.pytassertAlmostEqual3s&         cCs |dk r'|dk r'tdn|dk r||k rZt|||krZdSdt|t|t|f}nd|dkrd}n||k rtt|||dkrdSdt|t||f}|j||}|j|dS(sFail 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. s specify delta or places not bothNs%s == %s within %s deltaiis%s == %s within %r places(R5RRRRRR1(RRRRRRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotAlmostEqualZs"  #    ,   csfd}|S(Ncs,tjdjjtd||S(NsPlease use {0} instead.i(RwRxR8RtPendingDeprecationWarning(RR(t original_func(s%/usr/lib64/python2.7/unittest/case.pytdeprecated_funcs ((RR((Rs%/usr/lib64/python2.7/unittest/case.pyt _deprecatescCs |dk rz|j}t||sF|jd|t|fnt||s|jd|t|fqnd}d}yt|}Wn!ttfk rd|}nX|dkryt|}Wqttfk rd|}qXn|dkr||krdSt|} t|} t| dkrT| d d} nt| dkrw| d d} n|j| | f} d | }xt t ||D]} y|| } Wn/tt tfk r|d | |f7}PnXy|| }Wn/tt tfk r1|d | |f7}PnX| |kr|d | t| t|f7}PqqW||kr|dkrt |t |krdS||kr|d |||f7}y"|d|t||f7}Wqtt tfk r|d||f7}qXq||kr|d|||f7}y"|d|t||f7}Wqtt tfk r|d||f7}qXqn|}ddj tjtj|jtj|j}|j||}|j||}|j|dS(sAAn 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. sFirst sequence is not a %s: %ssSecond sequence is not a %s: %stsequences(First %s has no length. Non-sequence?s)Second %s has no length. Non-sequence?Nis...s%ss differ: %s != %s s( Unable to index element %d of first %s s) Unable to index element %d of second %s s# First differing element %d: %s %s s+ First %s contains %d additional elements. sFirst extra element %d: %s s'Unable to index element %d of first %s s, Second %s contains %d additional elements. s(Unable to index element %d of second %s s (R5RRR1RtlenRtNotImplementedErrort capitalizetxrangetmint IndexErrorRtjointdifflibtndifftpprinttpformatt splitlinest_truncateMessageRR(Rtseq1tseq2Rtseq_typet seq_type_namet differingtlen1tlen2t seq1_reprt seq2_reprtelementstititem1titem2RtdiffMsg((s%/usr/lib64/python2.7/unittest/case.pytassertSequenceEquals               cCsA|j}|dks't||kr/||S|tt|S(N(tmaxDiffR5Rt DIFF_OMITTED(Rtmessagetdifftmax_diff((s%/usr/lib64/python2.7/unittest/case.pyRs cCs|j|||dtdS(sA 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(RRT(Rtlist1tlist2R((s%/usr/lib64/python2.7/unittest/case.pyRFs cCs|j|||dtdS(sA 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(RRU(Rttuple1ttuple2R((s%/usr/lib64/python2.7/unittest/case.pyRGs c Cspy|j|}WnGtk r9}|jd|n$tk r\}|jd|nXy|j|}WnGtk r}|jd|n$tk r}|jd|nX|p|sdSg}|r |jdx$|D]}|jt|qWn|rD|jdx$|D]}|jt|q$Wndj|} |j|j|| dS(sA 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). s/invalid type when attempting set difference: %ss2first argument does not support set difference: %ss3second argument does not support set difference: %sNs*Items in the first set but not the second:s*Items in the second set but not the first:s (t differenceRRR6R^treprRR( Rtset1tset2Rt difference1Rt difference2tlinestitemR((s%/usr/lib64/python2.7/unittest/case.pyRHs2      cCsH||krDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a in b), but with a nicer default message.s%s not found in %sN(RRR(Rtmembert containerRR((s%/usr/lib64/python2.7/unittest/case.pytassertInEs  cCsH||krDdt|t|f}|j|j||ndS(sHJust like self.assertTrue(a not in b), but with a nicer default message.s%s unexpectedly found in %sN(RRR(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertNotInLs  cCsH||k rDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a is b), but with a nicer default message.s %s is not %sN(RRR(Rtexpr1texpr2RR((s%/usr/lib64/python2.7/unittest/case.pytassertIsSs  cCs?||kr;dt|f}|j|j||ndS(sHJust like self.assertTrue(a is not b), but with a nicer default message.sunexpectedly identical: %sN(RRR(RRRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertIsNotZs cCs|j|td|j|td||krdt|tt|tf}ddjtjtj|j tj|j }|j ||}|j |j ||ndS(Ns"First argument is not a dictionarys#Second argument is not a dictionarys%s != %ss ( tassertIsInstanceRSRRRRRRRRRRR(Rtd1td2RRR((s%/usr/lib64/python2.7/unittest/case.pyRE`s "c Csg}g}xy|jD]k\}}||krA|j|q|||kr|jdt|t|t||fqqW|p|sdSd}|rddjd|D}n|r|r|d7}n|ddj|7}n|j|j||dS( s0Checks whether actual is a superset of expected.s%s, expected: %s, actual: %sNRds Missing: %st,css|]}t|VqdS(N(R(t.0tm((s%/usr/lib64/python2.7/unittest/case.pys }ss; sMismatched values: %s(t iteritemsR^RRRR( RR0tactualRtmissingt mismatchedtkeytvalueR((s%/usr/lib64/python2.7/unittest/case.pytassertDictContainsSubsetls(    c Cs9t|t|}}tjtjr_x-dddgD]}tjd|tq?Wny"tj|}tj|}Wn t k rt ||} n X||krdSt ||} WdQX| r5d} g| D]} d| ^q} dj | } |j | | } |j|| }|j|ndS( sAn unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. s'(code|dict|type) inequality comparisonss,builtin_function_or_method order comparisonsscomparing unequal typestignoreNsElement counts were not equal: s First has %d, Second has %d: %rs (RTRwtcatch_warningsR&t py3kwarningtfilterwarningstDeprecationWarningt collectionstCounterRRRRRRR(Rt expected_seqt actual_seqRt first_seqt second_seqt_msgRRt differencesRRRR((s%/usr/lib64/python2.7/unittest/case.pytassertItemsEquals,      cCsG|j|td|j|td||krCt||jks\t||jkrr|j|||n|jt}|jt}t|dkr|jd|kr|dg}|dg}ndt|tt|tf}ddj t j ||}|j ||}|j |j||ndS( s-Assert that two multi-line strings are equal.sFirst argument is not a stringsSecond argument is not a stringis s s%s != %sRdN(RRRt_diffThresholdRRRRjRRRRRRR(RRRRt firstlinest secondlinesRR((s%/usr/lib64/python2.7/unittest/case.pyRIs$   ' cCsH||ksDdt|t|f}|j|j||ndS(sCJust like self.assertTrue(a < b), but with a nicer default message.s%s not less than %sN(RRR(RtatbRR((s%/usr/lib64/python2.7/unittest/case.pyt assertLesss cCsH||ksDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a <= b), but with a nicer default message.s%s not less than or equal to %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pytassertLessEquals cCsH||ksDdt|t|f}|j|j||ndS(sCJust like self.assertTrue(a > b), but with a nicer default message.s%s not greater than %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pyt assertGreaters cCsH||ksDdt|t|f}|j|j||ndS(sDJust like self.assertTrue(a >= b), but with a nicer default message.s"%s not greater than or equal to %sN(RRR(RRR RR((s%/usr/lib64/python2.7/unittest/case.pytassertGreaterEquals cCs?|dk r;dt|f}|j|j||ndS(sCSame as self.assertTrue(obj is None), with a nicer default message.s%s is not NoneN(R5RRR(RRRR((s%/usr/lib64/python2.7/unittest/case.pyt assertIsNones cCs2|dkr.d}|j|j||ndS(s(Included for symmetry with assertIsNone.sunexpectedly NoneN(R5RR(RRRR((s%/usr/lib64/python2.7/unittest/case.pytassertIsNotNones cCsEt||sAdt||f}|j|j||ndS(sTSame as self.assertTrue(isinstance(obj, cls)), with a nicer default message.s%s is not an instance of %rN(RRRR(RRRbRR((s%/usr/lib64/python2.7/unittest/case.pyRscCsEt||rAdt||f}|j|j||ndS(s,Included for symmetry with assertIsInstance.s%s is an instance of %rN(RRRR(RRRbRR((s%/usr/lib64/python2.7/unittest/case.pytassertNotIsInstancescOs^|dk rtj|}nt|||}|dkr@|S||||WdQXdS(sAsserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs. N(R5tretcompileR/(Rtexpected_exceptionR2t callable_objRRR((s%/usr/lib64/python2.7/unittest/case.pytassertRaisesRegexps  cCsht|tr!tj|}n|j|sd|p9d}d||j|f}|j|ndS(s=Fail the test unless the text matches the regular expression.sRegexp didn't matchs%s: %r not found in %rN(RRRRR<R=R1(RttextR2R((s%/usr/lib64/python2.7/unittest/case.pytassertRegexpMatches s  cCst|tr!tj|}n|j|}|r|p?d}d|||j|j!|j|f}|j|ndS(s9Fail the test if the text matches the regular expression.sRegexp matcheds%s: %r matches %r in %rN( RRRRR<tstarttendR=R1(RRtunexpected_regexpRtmatch((s%/usr/lib64/python2.7/unittest/case.pytassertNotRegexpMatchess  iiN(RRRR tAssertionErrorR1R:RRRt_classSetupFailedR RRR_R`Rat classmethodRcReRfRhRlRmRpRqRsRtRuR{R5RRRRRRRRRRRRRRRRt assertEqualstassertNotEqualstassertAlmostEqualstassertNotAlmostEqualstassert_RtfailUnlessEqualt failIfEqualtfailUnlessAlmostEqualtfailIfAlmostEqualt failUnlesstfailUnlessRaisestfailIfRRRFRGRHRRRRRERRRIR R R R RRRRRRR(((s%/usr/lib64/python2.7/unittest/case.pyRCs              Q            '$        g  +      (           tFunctionTestCasecBszeZdZd d d dZdZdZdZdZdZ dZ dZ d Z d Z d ZRS( sIA 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. cCs;tt|j||_||_||_||_dS(N(R R,R t _setUpFunct _tearDownFunct _testFunct _description(RttestFuncR`Rat description((s%/usr/lib64/python2.7/unittest/case.pyR *s    cCs |jdk r|jndS(N(R-R5(R((s%/usr/lib64/python2.7/unittest/case.pyR`1scCs |jdk r|jndS(N(R.R5(R((s%/usr/lib64/python2.7/unittest/case.pyRa5scCs|jdS(N(R/(R((s%/usr/lib64/python2.7/unittest/case.pyRD9scCs |jjS(N(R/R(R((s%/usr/lib64/python2.7/unittest/case.pyRm<scCs\t||jstS|j|jko[|j|jko[|j|jko[|j|jkS(N(RRNRnR-R.R/R0(RRo((s%/usr/lib64/python2.7/unittest/case.pyRp?s cCs ||k S(N((RRo((s%/usr/lib64/python2.7/unittest/case.pyRqHscCs+tt||j|j|j|jfS(N(RrRR-R.R/R0(R((s%/usr/lib64/python2.7/unittest/case.pyRsKscCsdt|j|jjfS(Ns%s (%s)(RRNR/R(R((s%/usr/lib64/python2.7/unittest/case.pyRtOscCsdt|j|jfS(Ns <%s tec=%s>(RRNR/(R((s%/usr/lib64/python2.7/unittest/case.pyRuSscCsE|jdk r|jS|jj}|rA|jddjpDdS(Ns i(R0R5R/R RiRj(RRk((s%/usr/lib64/python2.7/unittest/case.pyRlWs N(RRR R5R R`RaRDRmRpRqRsRtRuRl(((s%/usr/lib64/python2.7/unittest/case.pyR,!s        ($R RR+R&RRRRRRwRdRtutilRRRRRRt __unittestRR%RR RRR!R#R$R)R-R.tobjectR/RCR,(((s%/usr/lib64/python2.7/unittest/case.pyts:         (       !{PK!Wp,p, loader.pycnu[ {fc@sdZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z m Z e ZejdejZdZd Zd Zd efd YZeZed ZedZdee jdZdee jdZdS(sLoading unittests.iN(t cmp_to_key(tfnmatchi(tcasetsuites[_a-z]\w*\.py$cCs/d|tjf}td|t||S(Ns#Failed to import test module: %s %stModuleImportFailure(t tracebackt format_exct_make_failed_testt ImportError(tnamet suiteClasstmessage((s'/usr/lib64/python2.7/unittest/loader.pyt_make_failed_import_testscCstd|||S(NtLoadTestsFailure(R(R t exceptionR ((s'/usr/lib64/python2.7/unittest/loader.pyt_make_failed_load_testsscsGfd}i||6}t|tjf|}|||fS(Ncs dS(N((tself(R(s'/usr/lib64/python2.7/unittest/loader.pyt testFailures(ttypeRtTestCase(t classnamet methodnameRR Rtattrst TestClass((Rs'/usr/lib64/python2.7/unittest/loader.pyRs t TestLoadercBseZdZdZeZejZdZ dZ e dZ ddZddZdZdddZd Zd Zd Zd Zd ZRS(s This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite ttestcCsnt|tjr!tdn|j|}| rRt|drRdg}n|jt||}|S(s;Return a suite of all test cases contained in testCaseClasssYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?trunTest(t issubclassRt TestSuitet TypeErrortgetTestCaseNamesthasattrR tmap(Rt testCaseClasst testCaseNamest loaded_suite((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromTestCase0s cCsg}x]t|D]O}t||}t|trt|tjr|j|j|qqWt|dd}|j |}|r|dk ry|||dSWqt k r}t |j ||j SXn|S(s>Return a suite of all test cases contained in the given modulet load_testsN(tdirtgetattrt isinstanceRRRRtappendR$tNoneR t ExceptionRt__name__(Rtmoduletuse_load_teststtestsR tobjR%te((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromModule;s! c Cs|jd}|dkr}|}xK|roytdj|}PWq%tk rk|d=|slqlq%Xq%W|d}n|}x$|D]}|t||}}qWt|tjr|j |St|t rt |t j r|j|St|tjrPt|t rPt |t j rP|d}||}|j|gSt|tjrf|St|dr|} t| tjr| St| t j r|j| gStd|| fntd|dS(sSReturn 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. t.iit__call__s"calling %s returned %s, not a tests$don't know how to make test from: %sN(tsplitR*t __import__tjoinRR'R(ttypest ModuleTypeR2RRRRR$tUnboundMethodTypeR RRRR( RR R-tpartst parts_copyR0tparttparenttinstR((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromNameMsH       !    cCs2g|D]}|j||^q}|j|S(sReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. (R@R (RtnamesR-R tsuites((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromNames~s%cCsP||jd}t|t|}|jrL|jdt|jn|S(sLReturn a sorted sequence of method names found within testCaseClass cSs%|j|o$tt||dS(NR4(t startswithRR'(tattrnameR!tprefix((s'/usr/lib64/python2.7/unittest/loader.pyt isTestMethodstkey(ttestMethodPrefixtfilterR&tsortTestMethodsUsingtsortt _CmpToKey(RR!RGt testFnNames((s'/usr/lib64/python2.7/unittest/loader.pyRs  stest*.pyc Cst}|dkr-|jdk r-|j}n|dkrHt}|}ntjj|}|tjkrtjjd|n||_t}tjj tjj|rtjj|}||krtjj tjj |d }qnyt |Wnt k rt}nmXtj|}|jdd}tjjtjj|j}|r|j||_tjj|n|rt d|nt|j||}|j|S(s+Find and return all test modules from the specified start directory, recursing into subdirectories to find 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. 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(). is __init__.pyR3s%Start directory is not importable: %rN(tFalseR*t_top_level_dirtTruetostpathtabspathtsystinserttisdirtisfileR7R6RtmodulesR5tdirnamet__file__t _get_directory_containing_moduletremovetlistt _find_testsR ( Rt start_dirtpatternt top_level_dirtset_implicit_toptis_not_importablet the_modulettop_partR/((s'/usr/lib64/python2.7/unittest/loader.pytdiscovers:     (   !cCsstj|}tjj|j}tjj|jjdr_tjj tjj |Stjj |SdS(Ns __init__.py( RURYRRRSRTR[tbasenametlowerRDRZ(Rt module_nameR-t full_path((s'/usr/lib64/python2.7/unittest/loader.pyR\s  !cCstjjtjj|d}tjj||j}tjj| sYtd|jd sutd|j tjj d}|S(NisPath must be within the projects..R3( RRRStsplitexttnormpathtrelpathRPtisabstAssertionErrorRDtreplacetsep(RRSt_relpathR ((s'/usr/lib64/python2.7/unittest/loader.pyt_get_name_from_paths "cCst|tj|S(N(R6RURY(RR ((s'/usr/lib64/python2.7/unittest/loader.pyt_get_module_from_names cCs t||S(N(R(RRSRkRa((s'/usr/lib64/python2.7/unittest/loader.pyt _match_pathsccstj|}x|D]}tjj||}tjj|rtj|sXqn|j|||ssqn|j|}y|j |}Wnt ||j VqXtjj t |d|}tjjtjj|d} tjjtjj|d} | j| jkrtjj| } tjjtjj|d} tjj|} d}t|| | | fn|j|Vqtjj|rtjjtjj|dsqnd}d}t||r?|j|}|j |}t |dd}|j|dt}n|dkr|dk r_|Vnxd|j||D] }|VqrWqy||||VWqtk r}t|j||j VqXqqWdS(s/Used by discovery. Yields test suites it loads.R[isW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?s __init__.pyR%R.N(RRtlistdirRSR7RXtVALID_MODULE_NAMEtmatchRvRtRuR R RTR'RltrealpathRiRZRhRR2RWR*RROR_R+RR,(RR`RatpathsRSRkR R-tmod_fileRztfullpath_noextt module_dirtmod_namet expected_dirtmsgR%R/tpackageRR1((s'/usr/lib64/python2.7/unittest/loader.pyR_sV """!    N(R,t __module__t__doc__RItcmpRKRRR R*RPR$RQR2R@RCRRgR\RtRuRvR_(((s'/usr/lib64/python2.7/unittest/loader.pyR&s    1  @  cCs1t}||_||_|r-||_n|S(N(RRKRIR (RFt sortUsingR tloader((s'/usr/lib64/python2.7/unittest/loader.pyt _makeLoader+s     cCst||j|S(N(RR(R!RFR((s'/usr/lib64/python2.7/unittest/loader.pyR3sRcCst|||j|S(N(RR$(R!RFRR ((s'/usr/lib64/python2.7/unittest/loader.pyt makeSuite6scCst|||j|S(N(RR2(R-RFRR ((s'/usr/lib64/python2.7/unittest/loader.pyt findTestCases:s(RRRtreRURR8t functoolsRRMRtRRRQt __unittesttcompilet IGNORECASERxR RRtobjectRtdefaultTestLoaderR*RRRRRR(((s'/usr/lib64/python2.7/unittest/loader.pyts,           PK!nT++ loader.pyonu[ {fc@sdZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z m Z e ZejdejZdZd Zd Zd efd YZeZed ZedZdee jdZdee jdZdS(sLoading unittests.iN(t cmp_to_key(tfnmatchi(tcasetsuites[_a-z]\w*\.py$cCs/d|tjf}td|t||S(Ns#Failed to import test module: %s %stModuleImportFailure(t tracebackt format_exct_make_failed_testt ImportError(tnamet suiteClasstmessage((s'/usr/lib64/python2.7/unittest/loader.pyt_make_failed_import_testscCstd|||S(NtLoadTestsFailure(R(R t exceptionR ((s'/usr/lib64/python2.7/unittest/loader.pyt_make_failed_load_testsscsGfd}i||6}t|tjf|}|||fS(Ncs dS(N((tself(R(s'/usr/lib64/python2.7/unittest/loader.pyt testFailures(ttypeRtTestCase(t classnamet methodnameRR Rtattrst TestClass((Rs'/usr/lib64/python2.7/unittest/loader.pyRs t TestLoadercBseZdZdZeZejZdZ dZ e dZ ddZddZdZdddZd Zd Zd Zd Zd ZRS(s This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite ttestcCsnt|tjr!tdn|j|}| rRt|drRdg}n|jt||}|S(s;Return a suite of all test cases contained in testCaseClasssYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?trunTest(t issubclassRt TestSuitet TypeErrortgetTestCaseNamesthasattrR tmap(Rt testCaseClasst testCaseNamest loaded_suite((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromTestCase0s cCsg}x]t|D]O}t||}t|trt|tjr|j|j|qqWt|dd}|j |}|r|dk ry|||dSWqt k r}t |j ||j SXn|S(s>Return a suite of all test cases contained in the given modulet load_testsN(tdirtgetattrt isinstanceRRRRtappendR$tNoneR t ExceptionRt__name__(Rtmoduletuse_load_teststtestsR tobjR%te((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromModule;s! c Cs|jd}|dkr}|}xK|roytdj|}PWq%tk rk|d=|slqlq%Xq%W|d}n|}x$|D]}|t||}}qWt|tjr|j |St|t rt |t j r|j|St|tjrPt|t rPt |t j rP|d}||}|j|gSt|tjrf|St|dr|} t| tjr| St| t j r|j| gStd|| fntd|dS(sSReturn 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. t.iit__call__s"calling %s returned %s, not a tests$don't know how to make test from: %sN(tsplitR*t __import__tjoinRR'R(ttypest ModuleTypeR2RRRRR$tUnboundMethodTypeR RRRR( RR R-tpartst parts_copyR0tparttparenttinstR((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromNameMsH       !    cCs2g|D]}|j||^q}|j|S(sReturn a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. (R@R (RtnamesR-R tsuites((s'/usr/lib64/python2.7/unittest/loader.pytloadTestsFromNames~s%cCsP||jd}t|t|}|jrL|jdt|jn|S(sLReturn a sorted sequence of method names found within testCaseClass cSs%|j|o$tt||dS(NR4(t startswithRR'(tattrnameR!tprefix((s'/usr/lib64/python2.7/unittest/loader.pyt isTestMethodstkey(ttestMethodPrefixtfilterR&tsortTestMethodsUsingtsortt _CmpToKey(RR!RGt testFnNames((s'/usr/lib64/python2.7/unittest/loader.pyRs  stest*.pyc Cst}|dkr-|jdk r-|j}n|dkrHt}|}ntjj|}|tjkrtjjd|n||_t}tjj tjj|rtjj|}||krtjj tjj |d }qnyt |Wnt k rt}nmXtj|}|jdd}tjjtjj|j}|r|j||_tjj|n|rt d|nt|j||}|j|S(s+Find and return all test modules from the specified start directory, recursing into subdirectories to find 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. 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(). is __init__.pyR3s%Start directory is not importable: %rN(tFalseR*t_top_level_dirtTruetostpathtabspathtsystinserttisdirtisfileR7R6RtmodulesR5tdirnamet__file__t _get_directory_containing_moduletremovetlistt _find_testsR ( Rt start_dirtpatternt top_level_dirtset_implicit_toptis_not_importablet the_modulettop_partR/((s'/usr/lib64/python2.7/unittest/loader.pytdiscovers:     (   !cCsstj|}tjj|j}tjj|jjdr_tjj tjj |Stjj |SdS(Ns __init__.py( RURYRRRSRTR[tbasenametlowerRDRZ(Rt module_nameR-t full_path((s'/usr/lib64/python2.7/unittest/loader.pyR\s  !cCsVtjjtjj|d}tjj||j}|jtjjd}|S(NiR3(RRRStsplitexttnormpathtrelpathRPtreplacetsep(RRSt_relpathR ((s'/usr/lib64/python2.7/unittest/loader.pyt_get_name_from_paths"cCst|tj|S(N(R6RURY(RR ((s'/usr/lib64/python2.7/unittest/loader.pyt_get_module_from_names cCs t||S(N(R(RRSRkRa((s'/usr/lib64/python2.7/unittest/loader.pyt _match_pathsccstj|}x|D]}tjj||}tjj|rtj|sXqn|j|||ssqn|j|}y|j |}Wnt ||j VqXtjj t |d|}tjjtjj|d} tjjtjj|d} | j| jkrtjj| } tjjtjj|d} tjj|} d}t|| | | fn|j|Vqtjj|rtjjtjj|dsqnd}d}t||r?|j|}|j |}t |dd}|j|dt}n|dkr|dk r_|Vnxd|j||D] }|VqrWqy||||VWqtk r}t|j||j VqXqqWdS(s/Used by discovery. Yields test suites it loads.R[isW%r module incorrectly imported from %r. Expected %r. Is this module globally installed?s __init__.pyR%R.N(RRtlistdirRSR7RXtVALID_MODULE_NAMEtmatchRtRrRsR R RTR'RltrealpathRiRZRhRR2RWR*RROR_R+RR,(RR`RatpathsRSRkR R-tmod_fileRxtfullpath_noextt module_dirtmod_namet expected_dirtmsgR%R/tpackageRR1((s'/usr/lib64/python2.7/unittest/loader.pyR_sV """!    N(R,t __module__t__doc__RItcmpRKRRR R*RPR$RQR2R@RCRRgR\RrRsRtR_(((s'/usr/lib64/python2.7/unittest/loader.pyR&s    1  @  cCs1t}||_||_|r-||_n|S(N(RRKRIR (RFt sortUsingR tloader((s'/usr/lib64/python2.7/unittest/loader.pyt _makeLoader+s     cCst||j|S(N(RR(R!RFR((s'/usr/lib64/python2.7/unittest/loader.pyR3sRcCst|||j|S(N(RR$(R!RFRR ((s'/usr/lib64/python2.7/unittest/loader.pyt makeSuite6scCst|||j|S(N(RR2(R-RFRR ((s'/usr/lib64/python2.7/unittest/loader.pyt findTestCases:s(RRRtreRURR8t functoolsRRMRtRRRQt __unittesttcompilet IGNORECASERvR RRtobjectRtdefaultTestLoaderR*RRRRRR(((s'/usr/lib64/python2.7/unittest/loader.pyts,           PK!(G<<main.pycnu[ {fc@sdZddlZddlZddlZddlmZmZddlmZe Z dZ dZ dZ d Zd Zd efd YZeZdS( sUnittest main programiNi(tloadertrunner(tinstallHandlers) -f, --failfast Stop on first failure s7 -c, --catch Catch control-C and display results s= -b, --buffer Buffer stdout and stderr during test runs sUsage: %(progName)s [options] [tests] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s test_module - run tests from test_module %(progName)s module.TestClass - run tests from module.TestClass %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. Alternative Usage: %(progName)s discover [options] Options: -v, --verbose Verbose output %(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory) For test discovery all test modules must be importable from the top level directory of the project. s1Usage: %(progName)s [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething %(progName)s MyTestCase - run all 'test*' test methods in MyTestCase t TestProgramc BseZdZeZd ZZZZ dd d d e j e dd d d d Z d dZdZdZd dZdZRS( sA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. t__main__ic Cst|trTt||_x<|jddD]} t|j| |_q2Wn ||_|dkrutj}n||_ ||_ | |_ ||_ | |_ ||_||_||_tjj|d|_|j||jdS(Nt.ii(t isinstancet basestringt __import__tmoduletsplittgetattrtNonetsystargvtexittfailfastt catchbreakt verbositytbuffert defaultTestt testRunnert testLoadertostpathtbasenametprogNamet parseArgstrunTests( tselfR RRRRRRRRRtpart((s%/usr/lib64/python2.7/unittest/main.pyt__init__Hs$            cCs|r|GHni|jd6dd6dd6dd6}|jtkrOt|dR s %s discoveris-vs --verbosetdestR+tdefaultR*sVerbose outputtactiont store_trues-fs --failfastRsStop on first fail or errors-cs--catchRs'Catch Ctrl-C and display results so fars-bs--bufferRs%Buffer stdout and stderr during testss-ss--start-directorytstartRs*Directory to start discovery ('.' default)s-ps --patterntpatternstest*.pys+Pattern to match tests ('test*.py' default)s-ts--top-level-directoryttops<Top level directory of project (defaults to start directory)ii(RERFRG(R Rtoptparset OptionParsertprogt add_optionR!RRRt parse_argsR/R(tziptsetattrR+RRERFRGR)R>( RRtLoaderRHtparserR9R:tnameR<t start_dirRFt top_level_dirR((Rs%/usr/lib64/python2.7/unittest/main.pyR1sX               cCs|jrtn|jdkr1tj|_nt|jttj fry+|jd|j d|j d|j }Wqt k r|j}qXn |j}|j|j|_|jrtj|jj ndS(NRRR(RRRR RtTextTestRunnerRttypettypest ClassTypeRRRt TypeErrortrunR>tresultRR t wasSuccessful(RR((s%/usr/lib64/python2.7/unittest/main.pyRs      N(R5t __module__t__doc__tUSAGE_FROM_MODULER%R RRRRRtdefaultTestLoaderR3RR(RR6R1R(((s%/usr/lib64/python2.7/unittest/main.pyR?s      *  8(R]R RRVR RRtsignalsRR3t __unittestR"R#R$t USAGE_AS_MAINR^tobjectRtmain(((s%/usr/lib64/python2.7/unittest/main.pyts   PK!(G<<main.pyonu[ {fc@sdZddlZddlZddlZddlmZmZddlmZe Z dZ dZ dZ d Zd Zd efd YZeZdS( sUnittest main programiNi(tloadertrunner(tinstallHandlers) -f, --failfast Stop on first failure s7 -c, --catch Catch control-C and display results s= -b, --buffer Buffer stdout and stderr during test runs sUsage: %(progName)s [options] [tests] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s test_module - run tests from test_module %(progName)s module.TestClass - run tests from module.TestClass %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. Alternative Usage: %(progName)s discover [options] Options: -v, --verbose Verbose output %(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory) For test discovery all test modules must be importable from the top level directory of the project. s1Usage: %(progName)s [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething %(progName)s MyTestCase - run all 'test*' test methods in MyTestCase t TestProgramc BseZdZeZd ZZZZ dd d d e j e dd d d d Z d dZdZdZd dZdZRS( sA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. t__main__ic Cst|trTt||_x<|jddD]} t|j| |_q2Wn ||_|dkrutj}n||_ ||_ | |_ ||_ | |_ ||_||_||_tjj|d|_|j||jdS(Nt.ii(t isinstancet basestringt __import__tmoduletsplittgetattrtNonetsystargvtexittfailfastt catchbreakt verbositytbuffert defaultTestt testRunnert testLoadertostpathtbasenametprogNamet parseArgstrunTests( tselfR RRRRRRRRRtpart((s%/usr/lib64/python2.7/unittest/main.pyt__init__Hs$            cCs|r|GHni|jd6dd6dd6dd6}|jtkrOt|dR s %s discoveris-vs --verbosetdestR+tdefaultR*sVerbose outputtactiont store_trues-fs --failfastRsStop on first fail or errors-cs--catchRs'Catch Ctrl-C and display results so fars-bs--bufferRs%Buffer stdout and stderr during testss-ss--start-directorytstartRs*Directory to start discovery ('.' default)s-ps --patterntpatternstest*.pys+Pattern to match tests ('test*.py' default)s-ts--top-level-directoryttops<Top level directory of project (defaults to start directory)ii(RERFRG(R Rtoptparset OptionParsertprogt add_optionR!RRRt parse_argsR/R(tziptsetattrR+RRERFRGR)R>( RRtLoaderRHtparserR9R:tnameR<t start_dirRFt top_level_dirR((Rs%/usr/lib64/python2.7/unittest/main.pyR1sX               cCs|jrtn|jdkr1tj|_nt|jttj fry+|jd|j d|j d|j }Wqt k r|j}qXn |j}|j|j|_|jrtj|jj ndS(NRRR(RRRR RtTextTestRunnerRttypettypest ClassTypeRRRt TypeErrortrunR>tresultRR t wasSuccessful(RR((s%/usr/lib64/python2.7/unittest/main.pyRs      N(R5t __module__t__doc__tUSAGE_FROM_MODULER%R RRRRRtdefaultTestLoaderR3RR(RR6R1R(((s%/usr/lib64/python2.7/unittest/main.pyR?s      *  8(R]R RRVR RRtsignalsRR3t __unittestR"R#R$t USAGE_AS_MAINR^tobjectRtmain(((s%/usr/lib64/python2.7/unittest/main.pyts   PK! result.pycnu[ {fc@sdZddlZddlZddlZddlmZddlmZddlmZe Z dZ dZ d Z d efd YZdS( sTest result objectiN(tStringIOi(tutil(twrapscstfd}|S(Ncs/t|dtr|jn|||S(Ntfailfast(tgetattrtFalsetstop(tselftargstkw(tmethod(s'/usr/lib64/python2.7/unittest/result.pytinners (R(R R ((R s'/usr/lib64/python2.7/unittest/result.pyRss Stdout: %ss Stderr: %st TestResultcBseZdZdZeZeZddddZdZ dZ dZ dZ dZ dZdZed Zed Zd Zd Zd ZedZdZdZdZdZdZdZRS(sHolder 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. cCst|_g|_g|_d|_g|_g|_g|_t|_t|_ d|_ d|_ t j|_t j|_t|_dS(Ni(RRtfailuresterrorsttestsRuntskippedtexpectedFailurestunexpectedSuccessest shouldStoptbuffertNonet_stdout_buffert_stderr_buffertsyststdoutt_original_stdouttstderrt_original_stderrt _mirrorOutput(Rtstreamt descriptionst verbosity((s'/usr/lib64/python2.7/unittest/result.pyt__init__(s             cCsdS(s#Called by TestRunner after test runN((R((s'/usr/lib64/python2.7/unittest/result.pyt printErrors8tcCs&|jd7_t|_|jdS(s-Called when the given test is about to be runiN(RRRt _setupStdout(Rttest((s'/usr/lib64/python2.7/unittest/result.pyt startTest;s cCsR|jrN|jdkr3t|_t|_n|jt_|jt_ndS(N(RRRRRRRR(R((s'/usr/lib64/python2.7/unittest/result.pyR$As    cCsdS(spCalled once before any tests are executed. See startTest for a method called before each test. N((R((s'/usr/lib64/python2.7/unittest/result.pyt startTestRunIR#cCs|jt|_dS(s'Called when the given test has been runN(t_restoreStdoutRR(RR%((s'/usr/lib64/python2.7/unittest/result.pytstopTestOs cCs|jr|jrtjj}tjj}|ri|jdsR|d7}n|jjt |n|r|jds|d7}n|j jt |qn|jt_|j t_|j j d|j j|jj d|jjndS(Ns i(RRRRtgetvalueRtendswithRtwritet STDOUT_LINERt STDERR_LINERtseekttruncateR(Rtoutputterror((s'/usr/lib64/python2.7/unittest/result.pyR(Ts$       cCsdS(smCalled once after all tests are executed. See stopTest for a method called after each test. N((R((s'/usr/lib64/python2.7/unittest/result.pyt stopTestRuniR#cCs/|jj||j||ft|_dS(smCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). N(Rtappendt_exc_info_to_stringtTrueR(RR%terr((s'/usr/lib64/python2.7/unittest/result.pytaddErroros"cCs/|jj||j||ft|_dS(sdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().N(R R4R5R6R(RR%R7((s'/usr/lib64/python2.7/unittest/result.pyt addFailurews"cCsdS(s-Called when a test has completed successfullyN((RR%((s'/usr/lib64/python2.7/unittest/result.pyt addSuccess~scCs|jj||fdS(sCalled when a test is skipped.N(RR4(RR%treason((s'/usr/lib64/python2.7/unittest/result.pytaddSkipscCs&|jj||j||fdS(s/Called when an expected failure/error occurred.N(RR4R5(RR%R7((s'/usr/lib64/python2.7/unittest/result.pytaddExpectedFailures cCs|jj|dS(s5Called when a test was expected to fail, but succeed.N(RR4(RR%((s'/usr/lib64/python2.7/unittest/result.pytaddUnexpectedSuccessscCs*t|jt|jko'dkSS(s.Tells whether or not this result was a successi(tlenR R(R((s'/usr/lib64/python2.7/unittest/result.pyt wasSuccessfulscCs t|_dS(s*Indicates that the tests should be abortedN(R6R(R((s'/usr/lib64/python2.7/unittest/result.pyRsc Cs%|\}}}x"|r3|j|r3|j}qW||jkrm|j|}tj||||}ntj|||}|jrtjj }tj j } |r|j ds|d7}n|j t |n| r| j ds| d7} n|j t| qndj|S(s>Converts a sys.exc_info()-style tuple of values into a string.s R#(t_is_relevant_tb_levelttb_nexttfailureExceptiont_count_relevant_tb_levelst tracebacktformat_exceptionRRRR*RR+R4R-R.tjoin( RR7R%texctypetvaluettbtlengthtmsgLinesR1R2((s'/usr/lib64/python2.7/unittest/result.pyR5s&    cCsd|jjkS(Nt __unittest(ttb_framet f_globals(RRJ((s'/usr/lib64/python2.7/unittest/result.pyRAscCs:d}x-|r5|j| r5|d7}|j}q W|S(Nii(RARB(RRJRK((s'/usr/lib64/python2.7/unittest/result.pyRDs   cCs5dtj|j|jt|jt|jfS(Ns!<%s run=%i errors=%i failures=%i>(Rtstrclasst __class__RR?RR (R((s'/usr/lib64/python2.7/unittest/result.pyt__repr__s!N(t__name__t __module__t__doc__Rt_previousTestClassRt_testRunEnteredt_moduleSetUpFailedR!R"R&R$R'R)R(R3RR8R9R:R<R=R>R@RR5RARDRR(((s'/usr/lib64/python2.7/unittest/result.pyR s0                (RUtosRRERR#Rt functoolsRR6RMRR-R.tobjectR (((s'/usr/lib64/python2.7/unittest/result.pyts    PK! result.pyonu[ {fc@sdZddlZddlZddlZddlmZddlmZddlmZe Z dZ dZ d Z d efd YZdS( sTest result objectiN(tStringIOi(tutil(twrapscstfd}|S(Ncs/t|dtr|jn|||S(Ntfailfast(tgetattrtFalsetstop(tselftargstkw(tmethod(s'/usr/lib64/python2.7/unittest/result.pytinners (R(R R ((R s'/usr/lib64/python2.7/unittest/result.pyRss Stdout: %ss Stderr: %st TestResultcBseZdZdZeZeZddddZdZ dZ dZ dZ dZ dZdZed Zed Zd Zd Zd ZedZdZdZdZdZdZdZRS(sHolder 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. cCst|_g|_g|_d|_g|_g|_g|_t|_t|_ d|_ d|_ t j|_t j|_t|_dS(Ni(RRtfailuresterrorsttestsRuntskippedtexpectedFailurestunexpectedSuccessest shouldStoptbuffertNonet_stdout_buffert_stderr_buffertsyststdoutt_original_stdouttstderrt_original_stderrt _mirrorOutput(Rtstreamt descriptionst verbosity((s'/usr/lib64/python2.7/unittest/result.pyt__init__(s             cCsdS(s#Called by TestRunner after test runN((R((s'/usr/lib64/python2.7/unittest/result.pyt printErrors8tcCs&|jd7_t|_|jdS(s-Called when the given test is about to be runiN(RRRt _setupStdout(Rttest((s'/usr/lib64/python2.7/unittest/result.pyt startTest;s cCsR|jrN|jdkr3t|_t|_n|jt_|jt_ndS(N(RRRRRRRR(R((s'/usr/lib64/python2.7/unittest/result.pyR$As    cCsdS(spCalled once before any tests are executed. See startTest for a method called before each test. N((R((s'/usr/lib64/python2.7/unittest/result.pyt startTestRunIR#cCs|jt|_dS(s'Called when the given test has been runN(t_restoreStdoutRR(RR%((s'/usr/lib64/python2.7/unittest/result.pytstopTestOs cCs|jr|jrtjj}tjj}|ri|jdsR|d7}n|jjt |n|r|jds|d7}n|j jt |qn|jt_|j t_|j j d|j j|jj d|jjndS(Ns i(RRRRtgetvalueRtendswithRtwritet STDOUT_LINERt STDERR_LINERtseekttruncateR(Rtoutputterror((s'/usr/lib64/python2.7/unittest/result.pyR(Ts$       cCsdS(smCalled once after all tests are executed. See stopTest for a method called after each test. N((R((s'/usr/lib64/python2.7/unittest/result.pyt stopTestRuniR#cCs/|jj||j||ft|_dS(smCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). N(Rtappendt_exc_info_to_stringtTrueR(RR%terr((s'/usr/lib64/python2.7/unittest/result.pytaddErroros"cCs/|jj||j||ft|_dS(sdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().N(R R4R5R6R(RR%R7((s'/usr/lib64/python2.7/unittest/result.pyt addFailurews"cCsdS(s-Called when a test has completed successfullyN((RR%((s'/usr/lib64/python2.7/unittest/result.pyt addSuccess~scCs|jj||fdS(sCalled when a test is skipped.N(RR4(RR%treason((s'/usr/lib64/python2.7/unittest/result.pytaddSkipscCs&|jj||j||fdS(s/Called when an expected failure/error occurred.N(RR4R5(RR%R7((s'/usr/lib64/python2.7/unittest/result.pytaddExpectedFailures cCs|jj|dS(s5Called when a test was expected to fail, but succeed.N(RR4(RR%((s'/usr/lib64/python2.7/unittest/result.pytaddUnexpectedSuccessscCs*t|jt|jko'dkSS(s.Tells whether or not this result was a successi(tlenR R(R((s'/usr/lib64/python2.7/unittest/result.pyt wasSuccessfulscCs t|_dS(s*Indicates that the tests should be abortedN(R6R(R((s'/usr/lib64/python2.7/unittest/result.pyRsc Cs%|\}}}x"|r3|j|r3|j}qW||jkrm|j|}tj||||}ntj|||}|jrtjj }tj j } |r|j ds|d7}n|j t |n| r| j ds| d7} n|j t| qndj|S(s>Converts a sys.exc_info()-style tuple of values into a string.s R#(t_is_relevant_tb_levelttb_nexttfailureExceptiont_count_relevant_tb_levelst tracebacktformat_exceptionRRRR*RR+R4R-R.tjoin( RR7R%texctypetvaluettbtlengthtmsgLinesR1R2((s'/usr/lib64/python2.7/unittest/result.pyR5s&    cCsd|jjkS(Nt __unittest(ttb_framet f_globals(RRJ((s'/usr/lib64/python2.7/unittest/result.pyRAscCs:d}x-|r5|j| r5|d7}|j}q W|S(Nii(RARB(RRJRK((s'/usr/lib64/python2.7/unittest/result.pyRDs   cCs5dtj|j|jt|jt|jfS(Ns!<%s run=%i errors=%i failures=%i>(Rtstrclasst __class__RR?RR (R((s'/usr/lib64/python2.7/unittest/result.pyt__repr__s!N(t__name__t __module__t__doc__Rt_previousTestClassRt_testRunEnteredt_moduleSetUpFailedR!R"R&R$R'R)R(R3RR8R9R:R<R=R>R@RR5RARDRR(((s'/usr/lib64/python2.7/unittest/result.pyR s0                (RUtosRRERR#Rt functoolsRR6RMRR-R.tobjectR (((s'/usr/lib64/python2.7/unittest/result.pyts    PK!&xK runner.pycnu[ {fc@sdZddlZddlZddlmZddlmZeZde fdYZ dej fd YZ d e fd YZ dS( s Running testsiNi(tresult(tregisterResultt_WritelnDecoratorcBs,eZdZdZdZddZRS(s@Used to decorate file-like objects with a handy 'writeln' methodcCs ||_dS(N(tstream(tselfR((s'/usr/lib64/python2.7/unittest/runner.pyt__init__scCs+|dkrt|nt|j|S(NRt __getstate__(RR(tAttributeErrortgetattrR(Rtattr((s'/usr/lib64/python2.7/unittest/runner.pyt __getattr__s cCs'|r|j|n|jddS(Ns (twrite(Rtarg((s'/usr/lib64/python2.7/unittest/runner.pytwritelnsN(t__name__t __module__t__doc__RR tNoneR (((s'/usr/lib64/python2.7/unittest/runner.pyR s  tTextTestResultcBseZdZddZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZRS(shA test result class that can print formatted text results to a stream. Used by TextTestRunner. t=iFt-cCsPtt|j|||||_|dk|_|dk|_||_dS(Ni(tsuperRRRtshowAlltdotst descriptions(RRRt verbosity((s'/usr/lib64/python2.7/unittest/runner.pyR$s  cCsB|j}|jr4|r4djt||fSt|SdS(Ns (tshortDescriptionRtjointstr(Rttesttdoc_first_line((s'/usr/lib64/python2.7/unittest/runner.pytgetDescription+s cCs\tt|j||jrX|jj|j||jjd|jjndS(Ns ... (RRt startTestRRR Rtflush(RR((s'/usr/lib64/python2.7/unittest/runner.pyR 2s  cCs_tt|j||jr2|jjdn)|jr[|jjd|jjndS(Ntokt.( RRt addSuccessRRR RR R!(RR((s'/usr/lib64/python2.7/unittest/runner.pyR$9s   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(NtERRORtE( RRtaddErrorRRR RR R!(RRterr((s'/usr/lib64/python2.7/unittest/runner.pyR'As   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(NtFAILtF( RRt addFailureRRR RR R!(RRR(((s'/usr/lib64/python2.7/unittest/runner.pyR+Is   cCsktt|j|||jr>|jjdj|n)|jrg|jjd|jj ndS(Ns skipped {0!r}ts( RRtaddSkipRRR tformatRR R!(RRtreason((s'/usr/lib64/python2.7/unittest/runner.pyR-Qs   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(Nsexpected failuretx( RRtaddExpectedFailureRRR RR R!(RRR(((s'/usr/lib64/python2.7/unittest/runner.pyR1Ys   cCs_tt|j||jr2|jjdn)|jr[|jjd|jjndS(Nsunexpected successtu( RRtaddUnexpectedSuccessRRR RR R!(RR((s'/usr/lib64/python2.7/unittest/runner.pyR3as   cCsL|js|jr"|jjn|jd|j|jd|jdS(NR%R)(RRRR tprintErrorListterrorstfailures(R((s'/usr/lib64/python2.7/unittest/runner.pyt printErrorsiscCsxxq|D]i\}}|jj|j|jjd||j|f|jj|j|jjd|qWdS(Ns%s: %ss%s(RR t separator1Rt separator2(RtflavourR5RR(((s'/usr/lib64/python2.7/unittest/runner.pyR4os #(RRRR8R9RRR R$R'R+R-R1R3R7R4(((s'/usr/lib64/python2.7/unittest/runner.pyRs            tTextTestRunnercBsDeZdZeZejedeeddZ dZ dZ RS(sA 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. icCsOt||_||_||_||_||_|dk rK||_ndS(N(RRRRtfailfasttbufferRt resultclass(RRRRR<R=R>((s'/usr/lib64/python2.7/unittest/runner.pyRs     cCs|j|j|j|jS(N(R>RRR(R((s'/usr/lib64/python2.7/unittest/runner.pyt _makeResultscCs|j}t||j|_|j|_tj}t|dd}|dk rb|nz||Wdt|dd}|dk r|nXtj}||}|jt|dr|j j |j n|j }|j j d||dkr dpd|f|j j d } } } y%t t|j|j|jf} Wntk rlnX| \} } } g} |js|j jd t t|j|jf\}}|r| jd |n|r| jd |qn|j jd | r | jd| n| r:| jd| n| rT| jd| n| r}|j j ddj| fn|j jd|S(s&Run the given test case or test suite.t startTestRunNt stopTestRunR9sRan %d test%s in %.3fsiR,titFAILEDs failures=%ds errors=%dtOKs skipped=%dsexpected failures=%dsunexpected successes=%ds (%s)s, s (R?RR<R=ttimeRRR7thasattrRR R9ttestsRuntmaptlentexpectedFailurestunexpectedSuccessestskippedRt wasSuccessfulR R6R5tappendR(RRRt startTimeR@RAtstopTimet timeTakentrunt expectedFailsRKRLtresultstinfostfailedterrored((s'/usr/lib64/python2.7/unittest/runner.pyRRsb              #    !#N( RRRRR>tsyststderrtTruetFalseRRR?RR(((s'/usr/lib64/python2.7/unittest/runner.pyR;ws   (RRXRERBRtsignalsRRZt __unittesttobjectRt TestResultRR;(((s'/usr/lib64/python2.7/unittest/runner.pyts  [PK!&xK runner.pyonu[ {fc@sdZddlZddlZddlmZddlmZeZde fdYZ dej fd YZ d e fd YZ dS( s Running testsiNi(tresult(tregisterResultt_WritelnDecoratorcBs,eZdZdZdZddZRS(s@Used to decorate file-like objects with a handy 'writeln' methodcCs ||_dS(N(tstream(tselfR((s'/usr/lib64/python2.7/unittest/runner.pyt__init__scCs+|dkrt|nt|j|S(NRt __getstate__(RR(tAttributeErrortgetattrR(Rtattr((s'/usr/lib64/python2.7/unittest/runner.pyt __getattr__s cCs'|r|j|n|jddS(Ns (twrite(Rtarg((s'/usr/lib64/python2.7/unittest/runner.pytwritelnsN(t__name__t __module__t__doc__RR tNoneR (((s'/usr/lib64/python2.7/unittest/runner.pyR s  tTextTestResultcBseZdZddZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZRS(shA test result class that can print formatted text results to a stream. Used by TextTestRunner. t=iFt-cCsPtt|j|||||_|dk|_|dk|_||_dS(Ni(tsuperRRRtshowAlltdotst descriptions(RRRt verbosity((s'/usr/lib64/python2.7/unittest/runner.pyR$s  cCsB|j}|jr4|r4djt||fSt|SdS(Ns (tshortDescriptionRtjointstr(Rttesttdoc_first_line((s'/usr/lib64/python2.7/unittest/runner.pytgetDescription+s cCs\tt|j||jrX|jj|j||jjd|jjndS(Ns ... (RRt startTestRRR Rtflush(RR((s'/usr/lib64/python2.7/unittest/runner.pyR 2s  cCs_tt|j||jr2|jjdn)|jr[|jjd|jjndS(Ntokt.( RRt addSuccessRRR RR R!(RR((s'/usr/lib64/python2.7/unittest/runner.pyR$9s   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(NtERRORtE( RRtaddErrorRRR RR R!(RRterr((s'/usr/lib64/python2.7/unittest/runner.pyR'As   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(NtFAILtF( RRt addFailureRRR RR R!(RRR(((s'/usr/lib64/python2.7/unittest/runner.pyR+Is   cCsktt|j|||jr>|jjdj|n)|jrg|jjd|jj ndS(Ns skipped {0!r}ts( RRtaddSkipRRR tformatRR R!(RRtreason((s'/usr/lib64/python2.7/unittest/runner.pyR-Qs   cCsbtt|j|||jr5|jjdn)|jr^|jjd|jjndS(Nsexpected failuretx( RRtaddExpectedFailureRRR RR R!(RRR(((s'/usr/lib64/python2.7/unittest/runner.pyR1Ys   cCs_tt|j||jr2|jjdn)|jr[|jjd|jjndS(Nsunexpected successtu( RRtaddUnexpectedSuccessRRR RR R!(RR((s'/usr/lib64/python2.7/unittest/runner.pyR3as   cCsL|js|jr"|jjn|jd|j|jd|jdS(NR%R)(RRRR tprintErrorListterrorstfailures(R((s'/usr/lib64/python2.7/unittest/runner.pyt printErrorsiscCsxxq|D]i\}}|jj|j|jjd||j|f|jj|j|jjd|qWdS(Ns%s: %ss%s(RR t separator1Rt separator2(RtflavourR5RR(((s'/usr/lib64/python2.7/unittest/runner.pyR4os #(RRRR8R9RRR R$R'R+R-R1R3R7R4(((s'/usr/lib64/python2.7/unittest/runner.pyRs            tTextTestRunnercBsDeZdZeZejedeeddZ dZ dZ RS(sA 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. icCsOt||_||_||_||_||_|dk rK||_ndS(N(RRRRtfailfasttbufferRt resultclass(RRRRR<R=R>((s'/usr/lib64/python2.7/unittest/runner.pyRs     cCs|j|j|j|jS(N(R>RRR(R((s'/usr/lib64/python2.7/unittest/runner.pyt _makeResultscCs|j}t||j|_|j|_tj}t|dd}|dk rb|nz||Wdt|dd}|dk r|nXtj}||}|jt|dr|j j |j n|j }|j j d||dkr dpd|f|j j d } } } y%t t|j|j|jf} Wntk rlnX| \} } } g} |js|j jd t t|j|jf\}}|r| jd |n|r| jd |qn|j jd | r | jd| n| r:| jd| n| rT| jd| n| r}|j j ddj| fn|j jd|S(s&Run the given test case or test suite.t startTestRunNt stopTestRunR9sRan %d test%s in %.3fsiR,titFAILEDs failures=%ds errors=%dtOKs skipped=%dsexpected failures=%dsunexpected successes=%ds (%s)s, s (R?RR<R=ttimeRRR7thasattrRR R9ttestsRuntmaptlentexpectedFailurestunexpectedSuccessestskippedRt wasSuccessfulR R6R5tappendR(RRRt startTimeR@RAtstopTimet timeTakentrunt expectedFailsRKRLtresultstinfostfailedterrored((s'/usr/lib64/python2.7/unittest/runner.pyRRsb              #    !#N( RRRRR>tsyststderrtTruetFalseRRR?RR(((s'/usr/lib64/python2.7/unittest/runner.pyR;ws   (RRXRERBRtsignalsRRZt __unittesttobjectRt TestResultRR;(((s'/usr/lib64/python2.7/unittest/runner.pyts  [PK!X signals.pycnu[ {fc@sddlZddlZddlmZeZdefdYZejZ dZ dZ da dZddZdS( iN(twrapst_InterruptHandlercBseZdZdZRS(cCsyt|_||_t|ttfrl|tjkrBtj}ql|tj kr]d}qlt dn||_ dS(NcSsdS(N((t unused_signumt unused_frame((s(/usr/lib64/python2.7/unittest/signals.pytdefault_handlerssYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object( tFalsetcalledtoriginal_handlert isinstancetinttlongtsignaltSIG_DFLtdefault_int_handlertSIG_IGNt TypeErrorR(tselfR((s(/usr/lib64/python2.7/unittest/signals.pyt__init__ s    cCs{tjtj}||k r1|j||n|jrM|j||nt|_xtjD]}|jqcWdS(N( R t getsignaltSIGINTRRtTruet_resultstkeyststop(Rtsignumtframetinstalled_handlertresult((s(/usr/lib64/python2.7/unittest/signals.pyt__call__s   (t__name__t __module__RR(((s(/usr/lib64/python2.7/unittest/signals.pyR s cCsdt|s      PK!X signals.pyonu[ {fc@sddlZddlZddlmZeZdefdYZejZ dZ dZ da dZddZdS( iN(twrapst_InterruptHandlercBseZdZdZRS(cCsyt|_||_t|ttfrl|tjkrBtj}ql|tj kr]d}qlt dn||_ dS(NcSsdS(N((t unused_signumt unused_frame((s(/usr/lib64/python2.7/unittest/signals.pytdefault_handlerssYexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object( tFalsetcalledtoriginal_handlert isinstancetinttlongtsignaltSIG_DFLtdefault_int_handlertSIG_IGNt TypeErrorR(tselfR((s(/usr/lib64/python2.7/unittest/signals.pyt__init__ s    cCs{tjtj}||k r1|j||n|jrM|j||nt|_xtjD]}|jqcWdS(N( R t getsignaltSIGINTRRtTruet_resultstkeyststop(Rtsignumtframetinstalled_handlertresult((s(/usr/lib64/python2.7/unittest/signals.pyt__call__s   (t__name__t __module__RR(((s(/usr/lib64/python2.7/unittest/signals.pyR s cCsdt|s      PK!'y9*)*) suite.pycnu[ {fc@sdZddlZddlmZddlmZeZdZdefdYZ de fd YZ d efd YZ d Z d efdYZ dS(t TestSuiteiNi(tcase(tutilcCs t||d}|dS(NcSsdS(N(tNone(((s&/usr/lib64/python2.7/unittest/suite.pyt t(tgetattr(tparenttattrtfunc((s&/usr/lib64/python2.7/unittest/suite.pyt_call_if_exists st BaseTestSuitecBszeZdZd dZdZdZdZd ZdZ dZ dZ dZ d Z d Zd ZRS(sNA simple test suite that doesn't provide class or module shared fixtures. cCsg|_|j|dS(N(t_teststaddTests(tselfttests((s&/usr/lib64/python2.7/unittest/suite.pyt__init__s cCs dtj|jt|fS(Ns <%s tests=%s>(Rtstrclasst __class__tlist(R((s&/usr/lib64/python2.7/unittest/suite.pyt__repr__scCs,t||jstSt|t|kS(N(t isinstanceRtNotImplementedR(Rtother((s&/usr/lib64/python2.7/unittest/suite.pyt__eq__scCs ||k S(N((RR((s&/usr/lib64/python2.7/unittest/suite.pyt__ne__scCs t|jS(N(titerR (R((s&/usr/lib64/python2.7/unittest/suite.pyt__iter__%scCs+d}x|D]}||j7}q W|S(Ni(tcountTestCases(Rtcasesttest((s&/usr/lib64/python2.7/unittest/suite.pyR(s cCswt|ds-tdjt|nt|trct|tjt frctdn|j j |dS(Nt__call__s{} is not callablesNTestCases and TestSuites must be instantiated before passing them to addTest()( thasattrt TypeErrortformattreprRttypet issubclassRtTestCaseRR tappend(RR((s&/usr/lib64/python2.7/unittest/suite.pytaddTest.s cCs@t|trtdnx|D]}|j|q%WdS(Ns0tests must be an iterable of tests, not a string(Rt basestringR!R((RRR((s&/usr/lib64/python2.7/unittest/suite.pyR 8s cCs,x%|D]}|jrPn||qW|S(N(t shouldStop(RtresultR((s&/usr/lib64/python2.7/unittest/suite.pytrun>s   cOs|j||S(N(R,(Rtargstkwds((s&/usr/lib64/python2.7/unittest/suite.pyREscCsx|D]}|jqWdS(s7Run the tests without collecting errors in a TestResultN(tdebug(RR((s&/usr/lib64/python2.7/unittest/suite.pyR/Hs (N(t__name__t __module__t__doc__RRRRRt__hash__RRR(R R,RR/(((s&/usr/lib64/python2.7/unittest/suite.pyR s         cBsYeZdZedZdZdZdZdZdZ dZ dZ RS( sA 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. cCst}t|dttkr.t|_}nx|D]}|jrHPnt|r|j|||j|||j|||j |_ t|j dts5t|dtrq5qn|s||q5|j q5W|r|jd||j |t|_n|S(Nt_testRunEnteredt_classSetupFailedt_moduleSetUpFailed(tFalseRtTrueR4R*t _isnotsuitet_tearDownPreviousClasst_handleModuleFixturet_handleClassSetUpRt_previousTestClassR/Rt_handleModuleTearDown(RR+R/ttopLevelR((s&/usr/lib64/python2.7/unittest/suite.pyR,Xs,        cCst}|j|tdS(s7Run the tests without collecting errors in a TestResultN(t _DebugResultR,R8(RR/((s&/usr/lib64/python2.7/unittest/suite.pyR/vs c Cs!t|dd}|j}||kr+dS|jr8dSt|dtrNdSy t|_Wntk rnnXt|dd}|dk rt|dzoy |Wn]tk r}t |t rnt |_t j |}d|}|j|||nXWdt|dXndS(NR=t__unittest_skip__t setUpClasst _setupStdoutssetUpClass (%s)t_restoreStdout(RRRR6R7R5R!R t ExceptionRR@R8RRt_addClassOrModuleLevelException( RRR+t previousClasst currentClassRBtet classNamet errorName((s&/usr/lib64/python2.7/unittest/suite.pyR<}s4          cCs4d}t|dd}|dk r0|j}n|S(NR=(RRR1(RR+tpreviousModuleRG((s&/usr/lib64/python2.7/unittest/suite.pyt_get_previous_modules   c Cs |j|}|jj}||kr+dS|j|t|_ytj|}Wntk rfdSXt |dd}|dk rt |dz`y |WnNt k r}t |trnt|_d|}|j|||nXWdt |dXndS(Nt setUpModuleRCssetUpModule (%s)RD(RMRR1R>R7R6tsystmodulestKeyErrorRRR RERR@R8RF( RRR+RLt currentModuletmoduleRNRIRK((s&/usr/lib64/python2.7/unittest/suite.pyR;s.          cCslt|}t|dd}|dk rRt|tjrR||t|n|j|tj dS(NtaddSkip( t _ErrorHolderRRRRtSkipTesttstrtaddErrorROtexc_info(RR+t exceptionRKterrorRT((s&/usr/lib64/python2.7/unittest/suite.pyRFs  cCs|j|}|dkrdS|jr,dSytj|}Wntk rQdSXt|dd}|dk rt|dzWy |WnEtk r}t |t rnd|}|j |||nXWdt|dXndS(NttearDownModuleRCstearDownModule (%s)RD( RMRR6RORPRQRR RERR@RF(RR+RLRSR\RIRK((s&/usr/lib64/python2.7/unittest/suite.pyR>s*       c Cst|dd}|j}||kr+dSt|dtrAdSt|dtrWdSt|dtrmdSt|dd}|dk rt|dzfy |WnTtk r}t|trntj |}d|}|j |||nXWdt|dXndS( NR=R5R6RAt tearDownClassRCstearDownClass (%s)RD( RRRR7R RERR@RRRF( RRR+RGRHR]RIRJRK((s&/usr/lib64/python2.7/unittest/suite.pyR:s.      ( R0R1R2R7R,R/R<RMR;RFR>R:(((s&/usr/lib64/python2.7/unittest/suite.pyRNs      RUcBs\eZdZd ZdZdZdZdZdZ dZ dZ dZ RS( s 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. cCs ||_dS(N(t description(RR^((s&/usr/lib64/python2.7/unittest/suite.pyRscCs|jS(N(R^(R((s&/usr/lib64/python2.7/unittest/suite.pytid scCsdS(N(R(R((s&/usr/lib64/python2.7/unittest/suite.pytshortDescriptionscCsd|jfS(Ns(R^(R((s&/usr/lib64/python2.7/unittest/suite.pyRscCs |jS(N(R_(R((s&/usr/lib64/python2.7/unittest/suite.pyt__str__scCsdS(N((RR+((s&/usr/lib64/python2.7/unittest/suite.pyR,scCs |j|S(N(R,(RR+((s&/usr/lib64/python2.7/unittest/suite.pyRscCsdS(Ni((R((s&/usr/lib64/python2.7/unittest/suite.pyRsN( R0R1R2RtfailureExceptionRR_R`RRaR,RR(((s&/usr/lib64/python2.7/unittest/suite.pyRUs       cCs'yt|Wntk r"tSXtS(s?A crude way to tell apart testcases and suites with duck-typing(RR!R8R7(R((s&/usr/lib64/python2.7/unittest/suite.pyR9"s  R@cBs eZdZdZeZeZRS(sCUsed by the TestSuite to hold previous class when running in debug.N(R0R1R2RR=R7R6R*(((s&/usr/lib64/python2.7/unittest/suite.pyR@+s(R2RORRRR8t __unittestR tobjectR RRUR9R@(((s&/usr/lib64/python2.7/unittest/suite.pyts  >& PK!'y9*)*) suite.pyonu[ {fc@sdZddlZddlmZddlmZeZdZdefdYZ de fd YZ d efd YZ d Z d efdYZ dS(t TestSuiteiNi(tcase(tutilcCs t||d}|dS(NcSsdS(N(tNone(((s&/usr/lib64/python2.7/unittest/suite.pyt t(tgetattr(tparenttattrtfunc((s&/usr/lib64/python2.7/unittest/suite.pyt_call_if_exists st BaseTestSuitecBszeZdZd dZdZdZdZd ZdZ dZ dZ dZ d Z d Zd ZRS(sNA simple test suite that doesn't provide class or module shared fixtures. cCsg|_|j|dS(N(t_teststaddTests(tselfttests((s&/usr/lib64/python2.7/unittest/suite.pyt__init__s cCs dtj|jt|fS(Ns <%s tests=%s>(Rtstrclasst __class__tlist(R((s&/usr/lib64/python2.7/unittest/suite.pyt__repr__scCs,t||jstSt|t|kS(N(t isinstanceRtNotImplementedR(Rtother((s&/usr/lib64/python2.7/unittest/suite.pyt__eq__scCs ||k S(N((RR((s&/usr/lib64/python2.7/unittest/suite.pyt__ne__scCs t|jS(N(titerR (R((s&/usr/lib64/python2.7/unittest/suite.pyt__iter__%scCs+d}x|D]}||j7}q W|S(Ni(tcountTestCases(Rtcasesttest((s&/usr/lib64/python2.7/unittest/suite.pyR(s cCswt|ds-tdjt|nt|trct|tjt frctdn|j j |dS(Nt__call__s{} is not callablesNTestCases and TestSuites must be instantiated before passing them to addTest()( thasattrt TypeErrortformattreprRttypet issubclassRtTestCaseRR tappend(RR((s&/usr/lib64/python2.7/unittest/suite.pytaddTest.s cCs@t|trtdnx|D]}|j|q%WdS(Ns0tests must be an iterable of tests, not a string(Rt basestringR!R((RRR((s&/usr/lib64/python2.7/unittest/suite.pyR 8s cCs,x%|D]}|jrPn||qW|S(N(t shouldStop(RtresultR((s&/usr/lib64/python2.7/unittest/suite.pytrun>s   cOs|j||S(N(R,(Rtargstkwds((s&/usr/lib64/python2.7/unittest/suite.pyREscCsx|D]}|jqWdS(s7Run the tests without collecting errors in a TestResultN(tdebug(RR((s&/usr/lib64/python2.7/unittest/suite.pyR/Hs (N(t__name__t __module__t__doc__RRRRRt__hash__RRR(R R,RR/(((s&/usr/lib64/python2.7/unittest/suite.pyR s         cBsYeZdZedZdZdZdZdZdZ dZ dZ RS( sA 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. cCst}t|dttkr.t|_}nx|D]}|jrHPnt|r|j|||j|||j|||j |_ t|j dts5t|dtrq5qn|s||q5|j q5W|r|jd||j |t|_n|S(Nt_testRunEnteredt_classSetupFailedt_moduleSetUpFailed(tFalseRtTrueR4R*t _isnotsuitet_tearDownPreviousClasst_handleModuleFixturet_handleClassSetUpRt_previousTestClassR/Rt_handleModuleTearDown(RR+R/ttopLevelR((s&/usr/lib64/python2.7/unittest/suite.pyR,Xs,        cCst}|j|tdS(s7Run the tests without collecting errors in a TestResultN(t _DebugResultR,R8(RR/((s&/usr/lib64/python2.7/unittest/suite.pyR/vs c Cs!t|dd}|j}||kr+dS|jr8dSt|dtrNdSy t|_Wntk rnnXt|dd}|dk rt|dzoy |Wn]tk r}t |t rnt |_t j |}d|}|j|||nXWdt|dXndS(NR=t__unittest_skip__t setUpClasst _setupStdoutssetUpClass (%s)t_restoreStdout(RRRR6R7R5R!R t ExceptionRR@R8RRt_addClassOrModuleLevelException( RRR+t previousClasst currentClassRBtet classNamet errorName((s&/usr/lib64/python2.7/unittest/suite.pyR<}s4          cCs4d}t|dd}|dk r0|j}n|S(NR=(RRR1(RR+tpreviousModuleRG((s&/usr/lib64/python2.7/unittest/suite.pyt_get_previous_modules   c Cs |j|}|jj}||kr+dS|j|t|_ytj|}Wntk rfdSXt |dd}|dk rt |dz`y |WnNt k r}t |trnt|_d|}|j|||nXWdt |dXndS(Nt setUpModuleRCssetUpModule (%s)RD(RMRR1R>R7R6tsystmodulestKeyErrorRRR RERR@R8RF( RRR+RLt currentModuletmoduleRNRIRK((s&/usr/lib64/python2.7/unittest/suite.pyR;s.          cCslt|}t|dd}|dk rRt|tjrR||t|n|j|tj dS(NtaddSkip( t _ErrorHolderRRRRtSkipTesttstrtaddErrorROtexc_info(RR+t exceptionRKterrorRT((s&/usr/lib64/python2.7/unittest/suite.pyRFs  cCs|j|}|dkrdS|jr,dSytj|}Wntk rQdSXt|dd}|dk rt|dzWy |WnEtk r}t |t rnd|}|j |||nXWdt|dXndS(NttearDownModuleRCstearDownModule (%s)RD( RMRR6RORPRQRR RERR@RF(RR+RLRSR\RIRK((s&/usr/lib64/python2.7/unittest/suite.pyR>s*       c Cst|dd}|j}||kr+dSt|dtrAdSt|dtrWdSt|dtrmdSt|dd}|dk rt|dzfy |WnTtk r}t|trntj |}d|}|j |||nXWdt|dXndS( NR=R5R6RAt tearDownClassRCstearDownClass (%s)RD( RRRR7R RERR@RRRF( RRR+RGRHR]RIRJRK((s&/usr/lib64/python2.7/unittest/suite.pyR:s.      ( R0R1R2R7R,R/R<RMR;RFR>R:(((s&/usr/lib64/python2.7/unittest/suite.pyRNs      RUcBs\eZdZd ZdZdZdZdZdZ dZ dZ dZ RS( s 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. cCs ||_dS(N(t description(RR^((s&/usr/lib64/python2.7/unittest/suite.pyRscCs|jS(N(R^(R((s&/usr/lib64/python2.7/unittest/suite.pytid scCsdS(N(R(R((s&/usr/lib64/python2.7/unittest/suite.pytshortDescriptionscCsd|jfS(Ns(R^(R((s&/usr/lib64/python2.7/unittest/suite.pyRscCs |jS(N(R_(R((s&/usr/lib64/python2.7/unittest/suite.pyt__str__scCsdS(N((RR+((s&/usr/lib64/python2.7/unittest/suite.pyR,scCs |j|S(N(R,(RR+((s&/usr/lib64/python2.7/unittest/suite.pyRscCsdS(Ni((R((s&/usr/lib64/python2.7/unittest/suite.pyRsN( R0R1R2RtfailureExceptionRR_R`RRaR,RR(((s&/usr/lib64/python2.7/unittest/suite.pyRUs       cCs'yt|Wntk r"tSXtS(s?A crude way to tell apart testcases and suites with duck-typing(RR!R8R7(R((s&/usr/lib64/python2.7/unittest/suite.pyR9"s  R@cBs eZdZdZeZeZRS(sCUsed by the TestSuite to hold previous class when running in debug.N(R0R1R2RR=R7R6R*(((s&/usr/lib64/python2.7/unittest/suite.pyR@+s(R2RORRRR8t __unittestR tobjectR RRUR9R@(((s&/usr/lib64/python2.7/unittest/suite.pyts  >& PK!rnutil.pycnu[ {fc@sdZddlmZmZeZdZedZdZ dZ edZ edd Z d Z d Zd Zd S(sVarious utility functions.i(t namedtuplet OrderedDictiPcCs\yt|}Wn tk r2tj|}nX| sLt|tkrP|S|t dS(Ns [truncated]...(treprt Exceptiontobjectt__repr__tlent _MAX_LENGTH(tobjtshorttresult((s%/usr/lib64/python2.7/unittest/util.pyt safe_reprs cCsd|j|jfS(Ns%s.%s(t __module__t__name__(tcls((s%/usr/lib64/python2.7/unittest/util.pytstrclassscCshd}}g}g}xEtr]y||}||}||kr}|j||d7}x|||kry|d7}q\Wn||kr|j||d7}x|||kr|d7}qWn^|d7}z%x|||kr|d7}qWWd|d7}x|||kr |d7}qWXWqtk rY|j|||j||PqXqW||fS(srFinds 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. iiN(tTruetappendt IndexErrortextend(texpectedtactualtitjtmissingt unexpectedteta((s%/usr/lib64/python2.7/unittest/util.pytsorted_list_differences:              cCsg}g}x|r|j}y|j|Wntk rR|j|nX|rxI||fD]8}yxtr|j|qrWWqftk rqfXqfWqqW|rxU|r|j}|j|yxtr|j|qWWqtk rqXqW||fS||fS(sSame 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. (tpoptremovet ValueErrorRR(RRtignore_duplicateRRtitemtlst((s%/usr/lib64/python2.7/unittest/util.pytunorderable_list_difference>s4           tMismatchsactual expected valuecCst|t|}}t|t|}}t}g}xt|D]\}} | |krlqNnd} } x>t||D]-} || | kr| d7} ||| t||D]-} || | krj| d7} ||| s  ) $ # PK!rnutil.pyonu[ {fc@sdZddlmZmZeZdZedZdZ dZ edZ edd Z d Z d Zd Zd S(sVarious utility functions.i(t namedtuplet OrderedDictiPcCs\yt|}Wn tk r2tj|}nX| sLt|tkrP|S|t dS(Ns [truncated]...(treprt Exceptiontobjectt__repr__tlent _MAX_LENGTH(tobjtshorttresult((s%/usr/lib64/python2.7/unittest/util.pyt safe_reprs cCsd|j|jfS(Ns%s.%s(t __module__t__name__(tcls((s%/usr/lib64/python2.7/unittest/util.pytstrclassscCshd}}g}g}xEtr]y||}||}||kr}|j||d7}x|||kry|d7}q\Wn||kr|j||d7}x|||kr|d7}qWn^|d7}z%x|||kr|d7}qWWd|d7}x|||kr |d7}qWXWqtk rY|j|||j||PqXqW||fS(srFinds 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. iiN(tTruetappendt IndexErrortextend(texpectedtactualtitjtmissingt unexpectedteta((s%/usr/lib64/python2.7/unittest/util.pytsorted_list_differences:              cCsg}g}x|r|j}y|j|Wntk rR|j|nX|rxI||fD]8}yxtr|j|qrWWqftk rqfXqfWqqW|rxU|r|j}|j|yxtr|j|qWWqtk rqXqW||fS||fS(sSame 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. (tpoptremovet ValueErrorRR(RRtignore_duplicateRRtitemtlst((s%/usr/lib64/python2.7/unittest/util.pytunorderable_list_difference>s4           tMismatchsactual expected valuecCst|t|}}t|t|}}t}g}xt|D]\}} | |krlqNnd} } x>t||D]-} || | kr| d7} ||| t||D]-} || | krj| d7} ||| s  ) $ # PK!&%__pycache__/util.cpython-36.pycnu[PK!99 )__pycache__/__init__.cpython-36.opt-1.pycnu[PK!d)__pycache__/__init__.cpython-36.opt-2.pycnu[PK!99 #E$__pycache__/__init__.cpython-36.pycnu[PK!v?)a0__pycache__/__main__.cpython-36.opt-1.pycnu[PK!ݥ~~)Y2__pycache__/__main__.cpython-36.opt-2.pycnu[PK!v?#04__pycache__/__main__.cpython-36.pycnu[PK!qĻĻ%"6__pycache__/case.cpython-36.opt-1.pycnu[PK!W%;__pycache__/case.cpython-36.opt-2.pycnu[PK!7",s__pycache__/case.cpython-36.pycnu[PK!Fk955'u/__pycache__/loader.cpython-36.opt-1.pycnu[PK!bC+C+'e__pycache__/loader.cpython-36.opt-2.pycnu[PK!E8,6,6!#__pycache__/loader.cpython-36.pycnu[PK!vff%__pycache__/main.cpython-36.opt-1.pycnu[PK!eg%[__pycache__/main.cpython-36.opt-2.pycnu[PK!vffd__pycache__/main.cpython-36.pycnu[PK!g"\\%__pycache__/mock.cpython-36.opt-1.pycnu[PK!+eQdd% __pycache__/mock.cpython-36.opt-2.pycnu[PK!g"\\__pycache__/mock.cpython-36.pycnu[PK!nԀ<<'.__pycache__/result.cpython-36.opt-1.pycnu[PK!p4'__pycache__/result.cpython-36.opt-2.pycnu[PK!nԀ<<!__pycache__/result.cpython-36.pycnu[PK!kH'__pycache__/runner.cpython-36.opt-1.pycnu[PK!T`aa'__pycache__/runner.cpython-36.opt-2.pycnu[PK!kH!|5__pycache__/runner.cpython-36.pycnu[PK!~~(P__pycache__/signals.cpython-36.opt-1.pycnu[PK!~~(mY__pycache__/signals.cpython-36.opt-2.pycnu[PK!~~"Cb__pycache__/signals.cpython-36.pycnu[PK!ZZ##&k__pycache__/suite.cpython-36.opt-1.pycnu[PK!چ&>__pycache__/suite.cpython-36.opt-2.pycnu[PK!ZZ## ;__pycache__/suite.cpython-36.pycnu[PK!ZSPP%`__pycache__/util.cpython-36.opt-1.pycnu[PK!tp%__pycache__/util.cpython-36.opt-2.pycnu[PK!7 X__init__.pynu[PK!m q__main__.pynu[PK!:ЫЫcase.pynu[PK!44 loader.pynu[PK!#{#{#main.pynu[PK!X77Emock.pynu[PK!Jx l> result.pynu[PK!<H܅ IW runner.pynu[PK! k k q signals.pynu[PK!ĽQ&Q&z suite.pynu[PK!l5 util.pynu[PK!4-7-7j test/test_runner.pyonu[PK!ٙ7L@L@ test/test_setups.pynu[PK!\pqqj+ test/test_setups.pycnu[PK!\pqq test/test_setups.pyonu[PK!4}pp test/test_skipping.pynu[PK!+%%& test/test_skipping.pycnu[PK!+%%XL test/test_skipping.pyonu[PK!M;E,2/2/r test/test_suite.pynu[PK!S.#Ď<< test/test_suite.pyonu[PK!LB2d test/__init__.pynu[PK!z# test/__init__.pycnu[PK!z#q test/__init__.pyonu[PK!22 < test/dummy.pynu[PK!D test/dummy.pycnu[PK!Dk test/dummy.pyonu[PK!r= + test/support.pynu[PK!%v tt test/support.pycnu[PK!%v tt test/support.pyonu[PK!pV'..a' test/test_assertions.pynu[PK!o5z4z4aV test/test_assertions.pycnu[PK!o5z4z4# test/test_assertions.pyonu[PK!grx%% test/test_break.pynu[PK!Ij̟'' test/test_break.pycnu[PK!Ij̟'' test/test_break.pyonu[PK! 5 test/test_case.pynu[PK!Ll test/test_case.pycnu[PK!L\test/test_case.pyonu[PK!77LXtest/test_discovery.pynu[PK!CVEE{test/test_discovery.pycnu[PK!CVEEtest/test_discovery.pyonu[PK!Yotest/test_functiontestcase.pynu[PK!}'1test/test_functiontestcase.pycnu[PK!}'Itest/test_functiontestcase.pyonu[PK! pa1atest/test_loader.pynu[PK!lױœ>$test/test_loader.pycnu[PK!lױœtest/test_loader.pyonu[PK!x'Әtest/test_program.pynu[PK!ú((test/test_program.pycnu[PK!((test/test_program.pyonu[PK!pJpJtest/test_result.pynu[PK!aDϗSSdtest/test_result.pycnu[PK!aDϗSStest/test_result.pyonu[PK!Fcw!!e test/test_runner.pynu[PK!4-7-7I.test/test_runner.pycnu[PK!S.#Ď<<etest/test_suite.pycnu[PK!A __init__.pycnu[PK!A __init__.pyonu[PK! FE __main__.pycnu[PK! FE __main__.pyonu[PK!u<΢΢case.pycnu[PK!u<΢΢ bcase.pyonu[PK!Wp,p, loader.pycnu[PK!nT++ 1loader.pyonu[PK!(G<<]main.pycnu[PK!(G<<M}main.pyonu[PK! result.pycnu[PK! result.pyonu[PK!&xK runner.pycnu[PK!&xK (runner.pyonu[PK!X 1signals.pycnu[PK!X I"signals.pyonu[PK!'y9*)*) a-suite.pycnu[PK!'y9*)*) Vsuite.pyonu[PK!rn'util.pycnu[PK!rnutil.pyonu[PKmm$