m %UIc@sdZdZdZddd!ZdkZdkZdkZdkZdkZddd d d d d dgZ e i dddgei d d*jod+\Z Z dZneZdZdZdfdYZdfdYZd fdYZd efdYZd fdYZeZddZedZdeedZdeed Zd!fd"YZd#efd$YZ d fd%YZ!d&fd'YZ"e"Z#e$d(joe#d)dndS(,sw 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 IntegerArithmenticTestCase(unittest.TestCase): def testAdd(self): ## test method names begin 'test*' self.assertEquals((1 + 2), 3) self.assertEquals(0 + 1, 1) def testMultiply(self): self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40) if __name__ == '__main__': unittest.main() Further information is available in the bundled documentation, and from http://pyunit.sourceforge.net/ Copyright (c) 1999-2003 Steve Purcell 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. s Steve Purcells stephen_purcell at yahoo dot coms#Revision: 1.63 $i iNt TestResulttTestCaset TestSuitetTextTestRunnert TestLoadertFunctionTestCasetmaintdefaultTestLoadertgetTestCaseNamest makeSuitet findTestCasesiiicCsdk}t|titifjoNxC|D];}|tjo ti}n|i||odSq/q/WdSn|i||SdS(Nii( t __builtin__ttypetclsinfottypest TupleTypetListTypetclst ClassTypet isinstancetobj(RR R R((t%/data/zmath/lib/python2.4/unittest.pyRHs   cCsd|i|ifS(Ns%s.%s(Rt __module__t__name__(R((Rt _strclassZscBsztZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d ZRS( 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. cCs(g|_g|_d|_d|_dS(Ni(tselftfailuresterrorsttestsRunt shouldStop(R((Rt__init__js   cCs|id|_dS(s-Called when the given test is about to be runiN(RR(Rttest((Rt startTestpscCsdS(s'Called when the given test has been runN((RR((RtstopTesttscCs&|ii||i||fdS(smCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). N(RRtappendRt_exc_info_to_stringterr(RRR$((RtaddErrorxscCs&|ii||i||fdS(sdCalled when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().N(RRR"RR#R$(RRR$((Rt addFailure~scCsdS(s-Called when a test has completed successfullyN((RR((Rt addSuccessscCs-t|it|ijo djnS(s.Tells whether or not this result was a successiN(tlenRRR(R((Rt wasSuccessfulscCs t|_dS(s*Indicates that the tests should be abortedN(tTrueRR(R((RtstopscCs|\}}}x%|o|i|o |i}qW||ijo2|i |}di t i ||||Sndi t i |||S(s>Converts a sys.exc_info()-style tuple of values into a string.tN(R$texctypetvaluettbRt_is_relevant_tb_levelttb_nextRtfailureExceptiont_count_relevant_tb_levelstlengthtjoint tracebacktformat_exception(RR$RR.R-R4R/((RR#s#cCs|iiidS(Nt __unittest(R/ttb_framet f_globalsthas_key(RR/((RR0scCs=d}x0|o(|i| o|d7}|i}q W|S(Nii(R4R/RR0R1(RR/R4((RR3s  cCs2dt|i|it|it|ifS(Ns!<%s run=%i errors=%i failures=%i>(RRt __class__RR(RR(R((Rt__repr__s(RRt__doc__RR R!R%R&R'R)R+R#R0R3R=(((RR_s           cBs0tZdZeZddZdZdZdZdZ dZ dZ d Z d Z ed Zd Zd ZdZedZedZedZdZedZedZdedZdedZeZZeZZeZZ eZ!Z"eZ#eZ$Z%eZ&RS(sA 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. trunTestcCsXy(||_t||}|i|_Wn)tj otd|i |fnXdS(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: %sN( t methodNameRt_TestCase__testMethodNametgetattrt testMethodR>t_TestCase__testMethodDoctAttributeErrort ValueErrorR<(RR@RC((RRs cCsdS(sAHook method for setting up the test fixture before exercising it.N((R((RtsetUpscCsdS(sAHook method for deconstructing the test fixture after testing it.N((R((RttearDownscCsdS(Ni((R((RtcountTestCasesscCstS(N(R(R((RtdefaultTestResultscCs.|i}|o|iddipdS(sReturns 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. s iN(RRDtdoctsplittstriptNone(RRK((RtshortDescriptions cCsdt|i|ifS(Ns%s.%s(RRR<RA(R((RtidscCsd|it|ifS(Ns%s (%s)(RRARR<(R((Rt__str__scCsdt|i|ifS(Ns<%s testMethod=%s>(RRR<RA(R((RR=scCst|djo|i}n|i|t||i}z#y|iWn6t j o n"|i ||i dSnXt }y|t}Wn]|ij o|i||i n3t j o n|i ||i nXy|iWn8t j o n$|i ||i t }nX|o|i|nWd|i|XdS(N(tresultRNRRJR RBRARCRGtKeyboardInterruptR%t_TestCase__exc_infotFalsetokR*R2R&RHR'R!(RRRRVRC((RtrunsB    cOs|i||S(N(RRWtargstkwds(RRXRY((Rt__call__scCs+|it||i|idS(s6Run the test without collecting errors in a TestResultN(RRGRBRARH(R((Rtdebugs cCsGti\}}}tid djo|||fSn|||fS(sReturn a version of sys.exc_info() with the traceback frame minimised; usually the top level of the traceback frame is not needed. itjavaN(tsystexc_infoR-texcvalueR/tplatform(RR-R/R_((Rt __exc_info!s cCs|i|dS(s)Fail immediately, with the given message.N(RR2tmsg(RRb((Rtfail+scCs|o|i|ndS(s(Fail the test if the expression is true.N(texprRR2Rb(RRdRb((RtfailIf/scCs|p|i|ndS(s,Fail the test unless the expression is true.N(RdRR2Rb(RRdRb((Rt failUnless3scOshy|||Wn|j o dSn;Xt|do |i}n t|}|i d|dS(siFail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. NRs %s not raised( t callableObjRXtkwargstexcClassthasattrRtexcNametstrRR2(RRiRgRXRhRk((RtfailUnlessRaises7s   cCs2||jp!|i|pd||fndS(s[Fail if the two objects are unequal as determined by the '==' operator. s%r != %rN(tfirsttsecondRR2Rb(RRnRoRb((RtfailUnlessEqualHs cCs2||jo!|i|pd||fndS(sYFail if the two objects are equal as determined by the '==' operator. s%r == %rN(RnRoRR2Rb(RRnRoRb((Rt failIfEqualPs icCsBt|||djo$|i|pd|||fndS(sKFail 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. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). is%r != %r within %r placesN(troundRoRntplacesRR2Rb(RRnRoRsRb((RtfailUnlessAlmostEqualXscCsBt|||djo$|i|pd|||fndS(sIFail 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. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). is%r == %r within %r placesN(RrRoRnRsRR2Rb(RRnRoRsRb((RtfailIfAlmostEqualds('RRR>tAssertionErrorR2RRGRHRIRJRORPRQR=RNRWRZR[RTRcReRfRmRpRqRtRut assertEqualt assertEqualstassertNotEqualtassertNotEqualstassertAlmostEqualtassertAlmostEqualstassertNotAlmostEqualtassertNotAlmostEqualst assertRaisestassert_t assertTruet assertFalse(((RRs<         #              cBshtZdZfdZdZeZdZdZdZdZ dZ dZ d Z 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. cCsg|_|i|dS(N(Rt_teststaddTeststtests(RR((RRs cCsdt|i|ifS(Ns <%s tests=%s>(RRR<R(R((RR=scCs t|iS(N(titerRR(R((Rt__iter__scCs.d}x!|iD]}||i7}qW|S(Ni(tcasesRRRRI(RRR((RRIs  cCs|ii|dS(N(RRR"R(RR((RtaddTestscCs"x|D]}|i|qWdS(N(RRRR(RRR((RRscCs1x*|iD]}|ioPn||q W|S(N(RRRRRR(RRRR((RRWs   cOs|i||S(N(RRWRXRY(RRXRY((RRZscCs"x|iD]}|iq WdS(s7Run the tests without collecting errors in a TestResultN(RRRR[(RR((RR[s ( RRR>RR=RQRRIRRRWRZR[(((RRs         cBs_tZdZeeedZdZdZdZdZdZ dZ dZ RS( sGA test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit 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. cCs5ti|||_||_||_||_ dS(N( RRRRGt_FunctionTestCase__setUpFuncRHt_FunctionTestCase__tearDownFuncttestFunct_FunctionTestCase__testFunct descriptiont_FunctionTestCase__description(RRRGRHR((RRs     cCs"|idj o|indS(N(RRRN(R((RRGscCs"|idj o|indS(N(RRRN(R((RRHscCs|idS(N(RR(R((RR?scCs |iiS(N(RRR(R((RRPscCsdt|i|iifS(Ns%s (%s)(RRR<RR(R((RRQscCsdt|i|ifS(Ns<%s testFunc=%s>(RRR<R(R((RR=scCsL|idj o |iSn|ii}|o|iddipdS(Ns i(RRRNRR>RKRLRM(RRK((RROs  ( RRR>RNRRGRHR?RPRQR=RO(((RRs       cBsStZdZdZeZeZdZdZ e dZ e dZ dZ RS(swThis class is responsible for loading tests according to various criteria and returning them wrapped in a Test RcCsjt|totdn|i|}| ot|do dg}n|it ||S(s<Return a suite of all tests cases contained in testCaseClasssYTest cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?R?N( t issubclasst testCaseClassRt TypeErrorRRt testCaseNamesRjt suiteClasstmap(RRR((RtloadTestsFromTestCases cCs|g}xft|D]X}t||}t|tti fo*t |t o|i |i|qqW|i|S(s?Return a suite of all tests cases contained in the given moduleN(RtdirtmoduletnameRBRRR RRRRR"RRR(RRRRR((RtloadTestsFromModules )c Cs|id}|djoi|}xQ|oIytdi|}PWq&tj o|d=|pqrq&Xq&W|d}n|}x$|D]}|t ||}}qWt |tijo|i|Snt|t tifo!t|to|i|Snt |tijo||iSnqt|to|SnYt|o>|}t|ttfptd||fn|Sntd|dS(sTReturn a suite of all tests 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.iis"calling %s returned %s, not a tests$don't know how to make test from: %sN(RRLtpartsRRNt parts_copyt __import__R5t ImportErrorRtpartRBtparentR Rt ModuleTypeRRRRRRRtUnboundMethodTypeRRtcallableRRF( RRRRRRRRR((RtloadTestsFromNames@ )  cCs:g}|D]}||i||q ~}|i|S(sReturn a suite of all tests cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. N(t_[1]tnamesRRRRtsuitesR(RRRRRR((RtloadTestsFromNames(s-cCs||id}t|t|}xI|iD]>}x5|i |D]$}||jo|i |qGqGWq1W|i o|i |i n|S(sLReturn a sorted sequence of method names found within testCaseClass cCs#|i|ott||S(N(tattrnamet startswithtprefixRRBR(RRR((Rt isTestMethod2sN(RRttestMethodPrefixRtfilterRt testFnNamest __bases__t baseclassRt testFnNameR"tsortTestMethodsUsingtsort(RRRRRR((RR/s   (RRR>RtcmpRRRRRRNRRR(((RRs  * cCs3t}||_||_|o ||_n|S(N(Rtloadert sortUsingRRRR(RRRR((Rt _makeLoaderFs     cCst||i|S(N(RRRRR(RRR((RRMsRcCst|||i|S(N(RRRRRR(RRRR((RR PscCst|||i|S(N(RRRRRR(RRRR((RR Sst_WritelnDecoratorcBs,tZdZdZdZedZRS(s@Used to decorate file-like objects with a handy 'writeln' methodcCs ||_dS(N(tstreamR(RR((RR]scCst|i|S(N(RBRRtattr(RR((Rt __getattr__`scCs)|o|i|n|iddS(Ns (targRtwrite(RR((Rtwritelncs(RRR>RRRNR(((RR[s   t_TextTestResultcBsjtZdZddZddZdZdZdZdZdZ d Z d Z d Z RS( shA test result class that can print formatted text results to a stream. Used by TextTestRunner. t=iFt-cCsAti|||_|dj|_|dj|_||_dS(Ni(RRRRt verbositytshowAlltdotst descriptions(RRRR((RRps   cCs3|io|ip t|Sn t|SdS(N(RRRRORl(RR((RtgetDescriptionws cCsKti|||io-|ii|i||iidndS(Ns ... (RR RRRRRR(RR((RR }s cCsPti|||io|iidn|io|iidndS(NRVR( RR'RRRRRRR(RR((RR's   cCsSti||||io|iidn|io|ii dndS(NtERRORtE( RR%RRR$RRRRR(RRR$((RR%s   cCsSti||||io|iidn|io|ii dndS(NtFAILtF( RR&RRR$RRRRR(RRR$((RR&s   cCsO|ip |io|iin|id|i|id|idS(NRR(RRRRRtprintErrorListRR(R((Rt printErrorsscCsxxq|D]i\}}|ii|i|iid||i|f|ii|i |iid|qWdS(Ns%s: %ss%s( RRR$RRRt separator1tflavourRt separator2(RRRRR$((RRs  #( RRR>RRRRR R'R%R&RR(((RRhs          cBs5tZdZeidddZdZdZRS(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. icCs%t||_||_||_dS(N(RRRRR(RRRR((RRs cCst|i|i|iS(N(RRRRR(R((Rt _makeResultsc Cs[|i}ti}||ti}||}|i|i i |i |i }|i i d||djodpd|f|i i |ip|i idtt|i|if\}}|o|i id|n|o3|o|i idn|i id|n|i i d n|i i d |S( s&Run the given test case or test suite.sRan %d test%s in %.3fsitsR,sFAILED (s failures=%ds, s errors=%dt)tOKN(RRRRttimet startTimeRtstopTimet timeTakenRRRRRRWR)RRR(RRtfailedterrored( RRRWRRRRRRR((RRWs.       1  !(RRR>R]tstderrRRRW(((RRs  t TestProgramcBsStZdZdZdeeeedZedZdZdZ dZ RS(sA command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. s Usage: %(progName)s [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output 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__main__cCst|tdjoFt||_x=|iddD]}t|i||_q<Wn ||_|djo t i}nd|_ ||_ ||_ ||_ tii|d|_|i||idS(NR,Rii(R RRRRLRRBtargvRNR]Rt defaultTestt testRunnert testLoadertostpathtbasenametprogNamet parseArgstrunTests(RRRRRRR((RRs        cCs0|o |GHn|i|iGHtiddS(Ni(RbRtUSAGEt__dict__R]texit(RRb((Rt usageExits cCsCdk}y|i|dddddg\}}xc|D][\}}|djo|in|djo d |_n|djo d|_q;q;Wt |d jo0|i djo |i i |i|_dSnt |d jo ||_n|i f|_|iWn%|ij o}|i|nXdS(NithHvqthelptverbosetquiets-hs-Hs--helps-qs--quietis-vs --verbosei(s-hs-Hs--help(s-qs--quiet(s-vs --verbose(tgetoptRtoptionsRXtoptR.RRRR(RRNRRRRt testNamest createTeststerrorRb(RRRRXR.RbRR((RRs*      # cCs"|ii|i|i|_dS(N(RRRRRR(R((RRscCsV|idjotd|i|_n|ii|i}ti |i dS(NR( RRRNRRRWRRRR]RR)(RRR((RRs( RRR>RRNRRRRRR(((RRs    RR(ii(ii(%R>t __author__t __email__t __version__RR]R6RRt__all__textendt version_infoRUR*RR t __metaclass__RR8RRRRRRRNRRRR R RRRRRR(RRRRRRRR8RRR*RRRRR RRR]RRRRRURRR6R RR((Rt?-sB         K10\    >.K