o
    b|                     @   s  d Z g dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZmZ dd
lmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$ e%dZ&dd Z'dd Z(dd Z)dd Z*dd Z+dd Z,dd Z-G dd de$Z.dZ/G d d! d!e$Z0G d"d# d#e$Z1d$d% Z2d&d' Z3eeG d(d) d)Z4G d*d+ d+e4Z5G d,d- d-Z6d.d/ Z7G d0d1 d1Z8dS )2zK
A miscellany of code used to run Trial tests.

Maintainer: Jonathan Lange
)	TestSuiteDestructiveTestSuiteErrorHolderLoggedSuite
TestHolder
TestLoaderTrialRunner
TrialSuitefilenameToModule	isPackageisPackageDirectory
isTestCasenamesamefileNOT_IN_TEST    N)SourceFileLoader)implementer)defer)failurefilepathlogmodulesreflect)unittestutil) _ForceGarbageCollectionDecorator_iterateTests)_logObserver)	ITestCase)UncleanWarningsReporterWrapper_ExitWrapper)r   r   c                 C   s2   t | tjsdS tjtj| jd }|dkS )z>Given an object return True if the object looks like a packageFr   __init__)
isinstancetypes
ModuleTypeospathsplitextbasename__file__)moduler(    r+   6/usr/lib/python3/dist-packages/twisted/trial/runner.pyr
   8   s   r
   c                 C   s>   dd }| D ]}d| }t jt j| |r|  S qdS )z
    Is the directory at path 'dirname' a Python package directory?
    Returns the name of the __init__ file (it may have a weird extension)
    if dirname is a package directory.  Otherwise, returns False
    c                   S   s
   t j S N)	importlib	machineryall_suffixesr+   r+   r+   r,   _getSuffixesG      
z(isPackageDirectory.<locals>._getSuffixesr!   F)r%   r&   existsjoin)dirnamer1   extinitFiler+   r+   r,   r   @   s   
r   c                 C   s   t j| t j|kS )z
    A hacky implementation of C{os.path.samefile}. Used by L{filenameToModule}
    when the platform doesn't provide C{os.path.samefile}. Do not use this.
    )r%   r&   abspath)	filename1	filename2r+   r+   r,   r   Q   s   r   c              	   C   s  | }dt j  krdk rn ntj| stjt | } tj| s+t|dt	
| }zt	|}W n ttfyH   t| |d Y S w t|dddu rWt| |dS tj|jd d }ttjd	t}tj| r|| |st j|j= t| |d}|S )
aV  
    Given a filename, do whatever possible to return a module object matching
    that file.

    If the file in question is a module in Python path, properly import and
    return that module. Otherwise, load the source manually.

    @param fn: A filename.
    @return: A module object.
    @raise ValueError: If C{fn} does not exist.
    )      )r;   
   z doesn't exist)
moduleNamer)   Nr   z.pyr   )sysversion_infor%   r&   isabsr4   getcwdr3   
ValueErrorr   filenameToModuleNamenamedAnyAttributeError_importFromFilegetattrr'   r)   r   isfiler   __name__)fnoldFnr>   retretFilesamer+   r+   r,   r	   Y   s&   &

r	   c                C   s|   t | } |stjtj| d d }|tjv rtj| S tj	|| }|s+t
| tj|}|j| |tj|< |S )Nr   )_resolveDirectoryr%   r&   r'   splitr?   r   r.   r   spec_from_file_locationSyntaxErrormodule_from_specloaderexec_module)rK   r>   specr*   r+   r+   r,   rG      s   


rG   c                 C   s<   t j| rt| }|rt j| |} | S t| d| S )Nz is not a package directory)r%   r&   isdirr   r4   rC   )rK   r7   r+   r+   r,   rQ      s   rQ   c                 C   sH   t | j| jt | kr!t| jD ]}t | j|t | kr |  S q| jS )z
    Find the attribute name on the method's class which refers to the method.

    For some methods, notably decorators which have not had __name__ set correctly:

    getattr(method.im_class, method.__name__) != method
    )rH   im_classrJ   objectdir)methodaliasr+   r+   r,   _getMethodNameInClass   s   r_   c                   @   s   e Zd ZdZdd ZdS )r   zQ
    A test suite which remove the tests once run, to minimize memory usage.
    c                 C   s0   | j r|jr		 |S | j d}|| | j s|S )zn
        Almost the same as L{TestSuite.run}, but with C{self._tests} being
        empty at the end.
        r   )_tests
shouldStoppop)selfresulttestr+   r+   r,   run   s   zDestructiveTestSuite.runN)rJ   
__module____qualname____doc__rf   r+   r+   r+   r,   r      s    r   z<not in test>c                       s    e Zd ZdZ fddZ  ZS )r   z[
    Any errors logged in this suite will be reported to the L{TestResult}
    object.
    c                    sJ   t }|  t | |  | D ]
}|tt| q|	  dS )z
        Run the suite, storing all errors in C{result}. If an error is logged
        while no tests are running, then it will be added as an error to
        C{result}.

        @param result: A L{TestResult} object.
        N)
r   _addsuperrf   _remove	getErrorsaddErrorr   r   flushErrors)rc   rd   observererror	__class__r+   r,   rf      s   zLoggedSuite.run)rJ   rg   rh   ri   rf   __classcell__r+   r+   rr   r,   r      s    r   c                       s2   e Zd ZdZd
 fdd	Zdd Zdd	 Z  ZS )r   z
    Suite to wrap around every single test in a C{trial} run. Used internally
    by Trial to set up things necessary for Trial tests to work, regardless of
    what context they are run in.
    r+   Fc                    sF   |rg }|D ]}t |t}|| q|}t|}t |g d S r-   )r   decorater   appendr   rk   r!   )rc   testsforceGarbageCollectionnewTestsre   suiterr   r+   r,   r!      s   zTrialSuite.__init__c                    sH   ddl m} t  |dd fdd |d td  d S )Nr   )reactoraftershutdownc                      s
     d S r-   )callbackr+   dr+   r,   <lambda>      
 z"TrialSuite._bail.<locals>.<lambda>mktemp)	twisted.internetr{   r   DeferredaddSystemEventTriggerfireSystemEventr   TestCase_wait)rc   r{   r+   r   r,   _bail   s
   
zTrialSuite._bailc                 C   s&   zt | | W |   d S |   w r-   )r   rf   r   rc   rd   r+   r+   r,   rf      s   zTrialSuite.run)r+   F)rJ   rg   rh   ri   r!   r   rf   rt   r+   r+   rr   r,   r      s
    
r   c                 C   s@   t | rt| }|S z|  }W |S  ty   | j}Y |S w )z
    @param thing: an object from modules (instance of PythonModule,
        PythonAttribute), a TestCase subclass, or an instance of a TestCase.
    )r   r   qualidrF   r   )thingtheNamer+   r+   r,   r     s   
	
r   c                 C   s$   zt | tjW S  ty   Y dS w )z
    @return: C{True} if C{obj} is a class that contains test cases, C{False}
        otherwise. Used to find all the tests in a module.
    F)
issubclasspyunitr   	TypeError)objr+   r+   r,   r     s
   r   c                   @   sD   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dS )r   z
    Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
    is concerned, this looks exactly like a unit test.
    Nc                 C   s
   || _ dS )zM
        @param description: A string to be displayed L{TestResult}.
        Ndescription)rc   r   r+   r+   r,   r!   ,  s   
zTestHolder.__init__c                 C   s
   |  |S r-   rf   r   r+   r+   r,   __call__2  r2   zTestHolder.__call__c                 C      | j S r-   r   rc   r+   r+   r,   r   5     zTestHolder.idc                 C   s   dS )Nr   r+   r   r+   r+   r,   countTestCases8  s   zTestHolder.countTestCasesc                 C   s"   | |  ||  ||  dS )z
        This test is just a placeholder. Run the test successfully.

        @param result: The C{TestResult} to store the results in.
        @type result: L{twisted.trial.itrial.IReporter}.
        N)	startTest
addSuccessstopTestr   r+   r+   r,   rf   ;  s   

zTestHolder.runc                 C   r   r-   r   r   r+   r+   r,   shortDescriptionF  r   zTestHolder.shortDescription)rJ   rg   rh   ri   failureExceptionr!   r   r   r   rf   r   r+   r+   r+   r,   r   #  s    r   c                       s6   e Zd ZdZ fddZdefddZdd Z  ZS )	r   a  
    Used to insert arbitrary errors into a test suite run. Provides enough
    methods to look like a C{TestCase}, however, when it is run, it simply adds
    an error to the C{TestResult}. The most common use-case is for when a
    module fails to import.
    c                    s   t  | t|| _dS )a+  
        @param description: A string used by C{TestResult}s to identify this
        error. Generally, this is the name of a module that failed to import.

        @param error: The error to be added to the result. Can be an `exc_info`
        tuple or a L{twisted.python.failure.Failure}.
        N)rk   r!   r   excInfoOrFailureToExcInforq   )rc   r   rq   rr   r+   r,   r!   R  s   zErrorHolder.__init__returnc                 C   s   d | j| jd S )Nz)<ErrorHolder description={!r} error={!r}>   )formatr   rq   r   r+   r+   r,   __repr__]  s   zErrorHolder.__repr__c                 C   s&   | |  || | j ||  dS )z
        Run the test, reporting the error.

        @param result: The C{TestResult} to store the results in.
        @type result: L{twisted.trial.itrial.IReporter}.
        N)r   rn   rq   r   r   r+   r+   r,   rf   c  s   
zErrorHolder.run)	rJ   rg   rh   ri   r!   strr   rf   rt   r+   r+   rr   r,   r   J  s
    r   c                   @   s   e Zd ZdZdZdZdd Zdd Zdd	 Zd&ddZ	dd Z
e
Zdd ZeZdd Zdd Zdd Zd&ddZdd Zd'ddZd&ddZeZd&d d!Zd"d# Zd&d$d%ZdS )(r   a4  
    I find tests inside function, modules, files -- whatever -- then return
    them wrapped inside a Test (either a L{TestSuite} or a L{TestCase}).

    @ivar methodPrefix: A string prefix. C{TestLoader} will assume that all the
    methods in a class that begin with C{methodPrefix} are test cases.

    @ivar modulePrefix: A string prefix. Every module in a package that begins
    with C{modulePrefix} is considered a module full of tests.

    @ivar forceGarbageCollection: A flag applied to each C{TestCase} loaded.
    See L{unittest.TestCase} for more information.

    @ivar sorter: A key function used to sort C{TestCase}s, test classes,
    modules and packages.

    @ivar suiteFactory: A callable which is passed a list of tests (which
    themselves may be suites of tests). Must return a test suite.
    re   test_c                 C   s   t | _t| _g | _d S r-   )r   suiteFactoryr   sorter_importErrorsr   r+   r+   r,   r!     s   
zTestLoader.__init__c                 C   s   t || jdS )zt
        Sort the given things using L{sorter}.

        @param xs: A list of test cases, class or modules.
        )key)sortedr   )rc   xsr+   r+   r,   sort  s   zTestLoader.sortc                 C   s4   g }t |D ]\}}t|r|| q| |S )z-Given a module, return all Trial test classes)inspect
getmembersr   rv   r   )rc   r*   classesr   valr+   r+   r,   findTestClasses  s   

zTestLoader.findTestClassesFc              	   C   sb  t j|v r!t|}zt| W n ty    | j||d Y S w |}d } }}t|D ]B\}}z
t|}|}W  n4 tyo   t	
 d }	|	jdurU|	j}	|	jdusM|	jjj}
|
tjkr` |dkrmtd| dY q-w |du rt|}|dtd|jd d }z|D ]
}|t||}}qW n ty   t| dw | j||||d	S )
a  
        Find and load tests, given C{name}.

        @param _name: The qualified name of the thing to load.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.

        @return: If C{name} is a filename, return the module. If C{name} is a
        fully-qualified Python name, return the object it refers to.
        recurseN    zThe module z does not exist..r   )parentqualNamer   )r%   sepr   rD   
__import__ImportErrorloadFile_qualNameWalkernamedModuler?   exc_infotb_nexttb_framef_codeco_filenamer)   ModuleNotFoundrE   rR   lenrJ   rH   rF   loadAnything)rc   _namer   r   r   r   	remaining
searchNameremainingNametbfilenameWhereHappenedpartr+   r+   r,   
findByName  sN   







"zTestLoader.findByNamec                 C   s   t |tjst|dt|dr| S t|dr| S |  }| |D ]
}|	| 
| q(t|ds:|S |  }|jD ]
}|	| | qA| ||gS )a  
        Return a test suite with all the tests from a module.

        Included are TestCase subclasses and doctests listed in the module's
        __doctests__ module. If that's not good for you, put a function named
        either C{testSuite} or C{test_suite} in your module that returns a
        TestSuite, and I'll use the results of that instead.

        If C{testSuite} and C{test_suite} are both present, then I'll use
        C{testSuite}.
        z is not a module	testSuite
test_suite__doctests__)r"   r#   r$   r   hasattrr   r   r   r   addTest	loadClassr   loadDoctests)rc   r*   rz   	testClassdocSuitedocTestr+   r+   r,   
loadModule  s   



zTestLoader.loadModulec                    s\   t  tst dt st d } fdd|D }|S )z
        Given a class which contains test cases, return a list of L{TestCase}s.

        @param klass: The class to load tests from.
        z is not a classz is not a test casec                    s   g | ]}  j| qS r+   )	_makeCasemethodPrefix).0r   klassrc   r+   r,   
<listcomp>  s    z(TestLoader.loadClass.<locals>.<listcomp>)r"   typer   r   rC   getTestCaseNamesr   r   )rc   r   namesrw   r+   r   r,   r     s   


zTestLoader.loadClassc                 C   s   t || jS )z
        Given a class that contains C{TestCase}s, return a list of names of
        methods that probably contain tests.
        )r   prefixedMethodNamesr   )rc   r   r+   r+   r,   r   %  s   zTestLoader.getTestCaseNamesc                 C   s   t d)NzCan't happen on Py3)NotImplementedError)rc   r]   r+   r+   r,   
loadMethod,     zTestLoader.loadMethodc                 C   s   ||S r-   r+   )rc   r   
methodNamer+   r+   r,   r   /  r   zTestLoader._makeCasec              	   C   s   t |st|dt|j}|r| }n| }g }|D ]}|jdd 	| j
r3|| q |  }| |D ]$}z| }	W n tyV   t|jt }
Y nw | |	}
||
 q=|S )a  
        Load tests from a module object representing a package, and return a
        TestSuite containing those tests.

        Tests are only loaded from modules whose name begins with 'test_'
        (or whatever C{modulePrefix} is set to).

        @param package: a types.ModuleType object (or reasonable facsimile
        obtained by importing) which may contain tests.

        @param recurse: A boolean.  If True, inspect modules within packages
        within the given package (and so on), otherwise, only inspect modules
        in the package itself.

        @raise TypeError: If C{package} is not a package.

        @return: a TestSuite created with my suiteFactory, containing all the
        tests.
        z is not a packager   rP   )r
   r   r   	getModulerJ   walkModulesiterModulesr   rR   
startswithmodulePrefixrv   r   r   loadBaseExceptionr   r   Failurer   r   )rc   packager   pkgobj	discovery
discovereddiscorz   modinfor*   
thingToAddr+   r+   r,   loadPackage2  s*   


zTestLoader.loadPackagec                 C   sx   t |trzt|}W n ty   t|t  Y S w t	|s)t
d dS i }dd }||d< tj|fi |S )z
        Return a suite of tests for all the doctests defined in C{module}.

        @param module: A module object or a module name.
        z&trial only supports doctesting modulesNc                 S   s    t | d| j| _| j | _dS )z
            Save C{test.globs} and replace it with a copy so that if
            necessary, the original will be available for the next test
            run.
            _savedGlobalsN)rH   globsr   copy)re   r+   r+   r,   saveGlobalsm  s   z,TestLoader.loadDoctests.<locals>.saveGlobalssetUp)r"   r   r   rE   r   r   r   r   r   ismodulewarningswarndoctestDocTestSuite)rc   r*   	extraArgsr   r+   r+   r,   r   \  s   


	zTestLoader.loadDoctestsNc                 C   s   t |tjrt|r| j||dS | |S t |tr&t|tj	r&| 
|S t |tjrLt |trLt|tj	rL|d }||}t||jj|ksJJ |S t |trS|S td| )a  
        Load absolutely anything (as long as that anything is a module,
        package, class, or method (with associated parent class and qualname).

        @param obj: The object to load.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.
        @param parent: If C{obj} is a method, this is the parent class of the
            method. C{qualName} is also required.
        @param qualName: If C{obj} is a method, this a list containing is the
            qualified name of the method. C{parent} is also required.

        @return: A C{TestCase} or C{TestSuite}.
        r   rP   z"don't know how to make test from: )r"   r#   r$   r
   r   loadTestsFromModuler   r   r   r   loadTestsFromTestCaseFunctionTyperH   _testMethodName__func__r   r   )rc   r   r   r   r   r   instr+   r+   r,   r   y  s&   




zTestLoader.loadAnythingc              	   C   sB   z|  | j||dgW S  ty    |  t|t g Y S w )a*  
        Load some tests by name.

        @param name: The qualified name for the test to load.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.
        r   )r   r   r   r   r   r   )rc   r   r   r+   r+   r,   
loadByName  s
   	zTestLoader.loadByNamec              
   C   sj   g }g }|D ]!}z| | j||d W q ty'   | t|t  Y qw || | | |S )a+  
        Load some tests by a list of names.

        @param names: A L{list} of qualified names.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.
        r   )	rv   r  r   r   r   r   extendr   _uniqueTests)rc   r   r   thingserrorsr   r+   r+   r,   loadByNames  s   	
zTestLoader.loadByNamesc                 c   sF    t  }|D ]}|j}|D ]}t||vr|V  |t| qqdS )a  
        Gather unique suite objects from loaded things. This will guarantee
        uniqueness of inherited methods on TestCases which would otherwise hash
        to same value and collapse to one test unexpectedly if using simpler
        means: e.g. set().
        N)setr`   r   add)rc   r  seen	testthing
testthingsr   r+   r+   r,   r    s   zTestLoader._uniqueTestsc                 C   sF   t |}zt|| }| j||dW S  ty"   t| dw )a1  
        Load a file, and then the tests in that file.

        @param fileName: The file name to load.
        @param recurse: A boolean. If True, inspect modules within packages
            within the given package (and so on), otherwise, only inspect
            modules in the package itself.
        r   z is not a Python file.)r   rD   r   load_moduler   OSErrorrC   )rc   fileNamer   r   r*   r+   r+   r,   r     s   
	zTestLoader.loadFileF)FNN)rJ   rg   rh   ri   r   r   r!   r   r   r   r   r  r   r  r   r   r   r   r   r   r  loadTestsFromNamer  r  r   r+   r+   r+   r,   r   o  s.    
V
*

0
r   c                 c   sR    | g fV  |  d}tdt|D ]}d|d|  || d fV  qdS )a3  
    Given a Python qualified name, this function yields a 2-tuple of the most
    specific qualified name first, followed by the next-most-specific qualified
    name, and so on, paired with the remainder of the qualified name.

    @param qualName: A Python qualified name.
    @type qualName: L{str}
    r   r   N)rR   ranger   r4   )r   	qualPartsindexr+   r+   r,   r     s   


&r   c                   @   s   e Zd ZdZdZdZdd Zdd ZeZ	dd	 Z
d
dejddddd
dd
dfddZdd Zdd Zdd ZdddZdd Zd
S )r   z=
    A specialised runner that the trial front end uses.
    debugzdry-runc                 C   s<   |    t }t| j}t|\}| _t	|j
 |S r-   )_tearDownLogFiler%   rB   r   FilePathworkingDirectoryr   _unusedTestDirectory_testDirLockchdirr&   )rc   
currentDirbasetestdirr+   r+   r,   _setUpTestdir  s   zTrialRunner._setUpTestdirc                 C   s   t | | j  d S r-   )r%   r$  r#  unlock)rc   oldDirr+   r+   r,   _tearDownTestdir  s   
zTrialRunner._tearDownTestdirc                 C   s8   |  | j| j| j| j}| jrt|}| jrt|}|S r-   )	reporterFactorystreamtbformatrterrors_log
_exitFirstr    uncleanWarningsr   )rc   reporterr+   r+   r,   _makeResult  s   zTrialRunner._makeResultNztest.logFdefaultc                 C   st   || _ || _|| _|| _|| _|| _|| _d | _|	pd| _d | _	d | _
|
| _|| _|| _|r8t| jd| _d S d S )N_trial_tempzprofile.data)r,  logfilemoder-  r.  r/  r2  _resultr!  _logFileObserver_logFileObject_forceGarbageCollectiondebuggerr1  r   profiledrf   )rc   r,  r8  r7  r-  profiletracebackFormatrealTimeErrorsr2  r!  rx   r=  	exitFirstr+   r+   r,   r!   #  s"   
zTrialRunner.__init__c                 C   s@   | j d urt| j j d | _ | jd ur| j  d | _d S d S r-   )r:  r   removeObserveremitr;  closer   r+   r+   r,   r  C  s   



zTrialRunner._tearDownLogFilec                 C   sL   |    | jdkrtj}nt| jd}|| _t|| _t	| jj
d d S )N-ar   )r  r7  r?   stdoutopenr;  r   FileLogObserverr:  startLoggingWithObserverrD  )rc   logFiler+   r+   r,   _setUpLogFileK  s   
zTrialRunner._setUpLogFilec                 C   s   t |t}| || jS )zC
        Run the test or suite and return a result object.
        )r   ru   r   _runWithoutDecorationr<  )rc   re   r+   r+   r,   rf   U  s   zTrialRunner.runc           	   	      sF     t|g|t }jjkr+tD ]} |  |  | qn7jj	kr: fdd}n fdd}
 }z  |  W   | n
  | w t }t dd}|du rtjdt j tdd      j  d	 j||   d
     S     S )zR
        Private helper that runs the given test but doesn't decorate it.
        c                      s   j j S r-   )r=  runcallrf   r+   rd   rc   rz   r+   r,   r   m  s    z3TrialRunner._runWithoutDecoration.<locals>.<lambda>c                      s
     S r-   r   r+   )rd   rz   r+   r,   r   o  r   doneNzR%s should implement done() but doesn't. Falling back to printErrors() and friends.r;   )category
stacklevelzRan %d tests in %.3fs
)r4  r   timer8  DRY_RUNr   r   r   r   DEBUGr(  rM  r  r+  rH   r   r  r   r   rs   DeprecationWarningprintErrorswriteln	separatortestsRunwriteprintSummaryrQ  )	rc   re   rx   	startTimesinglerf   r*  endTimerQ  r+   rP  r,   rN  \  sP   



z!TrialRunner._runWithoutDecorationc                 C   s^   d}	 |d7 }| j d|f  |dkr| |}n| |}|jdkr'	 |S | s.	 |S q)z8
        Repeatedly run C{test} until it fails.
        r   Tr   zTest Pass %d
)r-  r]  rf   rN  r\  wasSuccessful)rc   re   countrd   r+   r+   r,   runUntilFailure  s   

zTrialRunner.runUntilFailurer  )rJ   rg   rh   ri   rW  rV  r(  r+  r   r0  r4  r?   rH  r!   r  rM  rf   rN  rd  r+   r+   r+   r,   r     s2    
 

1r   )9ri   __all__r  r.   r   r%   r?   rU  r#   r   importlib.machineryr   zope.interfacer   r   r   twisted.pythonr   r   r   r   r   twisted.trialr   r   twisted.trial._asyncrunnerr   r   twisted.trial._synctestr   twisted.trial.itrialr   twisted.trial.reporterr   r    twisted.trial.unittestr   r   r   r
   r   r   r	   rG   rQ   r_   r   r   r   r   r   r   r   r   r   r   r   r+   r+   r+   r,   <module>   sV   1
$&%   