3
(h-o                 @   s  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Zd dl	m
Z
 d dlmZ d dlmZ d dl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 yd dlZW n ek
r   dZY nX G d
d dejZ G dd de!Z"G dd de!Z#dd Z$d a%dd Z&dd Z'G dd dej(Z)G dd de!Z*dd Z+dd Z,d+dd Z-d,d!d"Z.d#d$ Z/d%d& Z0d-d'd(Z1d)d* Z2dS ).    N)import_module)settings)ImproperlyConfigured)DEFAULT_DB_ALIASconnections)SimpleTestCaseTestCase)setup_test_environmentteardown_test_environment)
OrderedSet)StringIOc                   sT   e Zd Z fddZ fddZ fddZ fddZ fd	d
Zdd Z  Z	S )DebugSQLTextTestResultc                s2   t jd| _| jjt j tt| j||| d S )Nzdjango.db.backends)logging	getLoggerloggersetLevelDEBUGsuperr   __init__)selfstreamZdescriptions	verbosity)	__class__ 6/tmp/pip-install-q3hcpn_q/Django/django/test/runner.pyr      s    zDebugSQLTextTestResult.__init__c                s8   t  | _tj| j| _| jj| j tt| j	| d S )N)
r   debug_sql_streamr   StreamHandlerhandlerr   
addHandlerr   r   	startTest)r   test)r   r   r   r       s    z DebugSQLTextTestResult.startTestc                sT   t t| j| | jj| j | jrP| jjd | j	j
| jj  | j	j| j d S )Nr   )r   r   stopTestr   removeHandlerr   ZshowAllr   seekr   writereadwriteln
separator2)r   r    )r   r   r   r!   &   s    zDebugSQLTextTestResult.stopTestc                s>   t t| j|| | jjd | jd | jj f | jd< d S )Nr      r)   )r   r   addErrorr   r#   errorsr%   )r   r    err)r   r   r   r*   .   s    zDebugSQLTextTestResult.addErrorc                s>   t t| j|| | jjd | jd | jj f | jd< d S )Nr   r(   r)   r)   )r   r   
addFailurer   r#   failuresr%   )r   r    r,   )r   r   r   r-   3   s    z!DebugSQLTextTestResult.addFailurec             C   s|   xv|D ]n\}}}| j j| j | j jd|| j|f  | j j| j | j jd|  | j j| j | j jd|  qW d S )Nz%s: %sz%s)r   r&   Z
separator1ZgetDescriptionr'   )r   Zflavourr+   r    r,   Z	sql_debugr   r   r   printErrorList8   s    z%DebugSQLTextTestResult.printErrorList)
__name__
__module____qualname__r   r   r!   r*   r-   r/   __classcell__r   r   )r   r   r      s   r   c               @   s   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"S )#RemoteTestResulta  
    Record information about which tests have succeeded and which have failed.

    The sole purpose of this class is to record events in the child processes
    so they can be replayed in the master process. As a consequence it doesn't
    inherit unittest.TestResult and doesn't attempt to implement all its API.

    The implementation matches the unpythonic coding style of unittest2.
    c             C   s   g | _ d| _d| _d| _d S )NFr   )eventsfailfast
shouldStoptestsRun)r   r   r   r   r   M   s    zRemoteTestResult.__init__c             C   s
   | j d S )Nr(   )r8   )r   r   r   r   
test_indexS   s    zRemoteTestResult.test_indexc             C   s   yt j| W n tk
r } zlt|d }tj|dddd}t|}tj|dddd}td krrtdj|| ntdj|||  W Y d d }~X nX d S )Nr(   K   z    )initial_indentsubsequent_indentz

{} failed:

{}

Unfortunately, tracebacks cannot be pickled, making it impossible for the
parallel test runner to handle this exception cleanly.

In order to see the traceback, you should install tblib:

    pip install tblib
aL  

{} failed:

{}

Unfortunately, the exception it raised cannot be pickled, making it impossible
for the parallel test runner to handle it cleanly.

Here's the error encountered while trying to pickle the exception:

{}

You should re-run this test with the --parallel=1 option to reproduce the
failure and get a correct traceback.
)	pickledumps	Exceptionreprtextwrapfilltblibprintformat)r   r    r,   excZoriginal_exc_txtZpickle_exc_txtr   r   r   check_picklableW   s    z RemoteTestResult.check_picklablec             C   s   | j r| j  d S )N)r6   stop)r   r   r   r   stop_if_failfast   s    z!RemoteTestResult.stop_if_failfastc             C   s
   d| _ d S )NT)r7   )r   r   r   r   rH      s    zRemoteTestResult.stopc             C   s   | j jd d S )NstartTestRun)rJ   )r5   append)r   r   r   r   rJ      s    zRemoteTestResult.startTestRunc             C   s   | j jd d S )NstopTestRun)rL   )r5   rK   )r   r   r   r   rL      s    zRemoteTestResult.stopTestRunc             C   s$   |  j d7  _ | jjd| jf d S )Nr(   r   )r8   r5   rK   r9   )r   r    r   r   r   r      s    zRemoteTestResult.startTestc             C   s   | j jd| jf d S )Nr!   )r5   rK   r9   )r   r    r   r   r   r!      s    zRemoteTestResult.stopTestc             C   s,   | j || | jjd| j|f | j  d S )Nr*   )rG   r5   rK   r9   rI   )r   r    r,   r   r   r   r*      s    zRemoteTestResult.addErrorc             C   s,   | j || | jjd| j|f | j  d S )Nr-   )rG   r5   rK   r9   rI   )r   r    r,   r   r   r   r-      s    zRemoteTestResult.addFailurec             C   s   t dd S )Nz&subtests aren't supported at this time)NotImplementedError)r   r    Zsubtestr,   r   r   r   
addSubTest   s    zRemoteTestResult.addSubTestc             C   s   | j jd| jf d S )N
addSuccess)r5   rK   r9   )r   r    r   r   r   rO      s    zRemoteTestResult.addSuccessc             C   s   | j jd| j|f d S )NaddSkip)r5   rK   r9   )r   r    reasonr   r   r   rP      s    zRemoteTestResult.addSkipc             C   s>   t d kr|d |d d f}| j|| | jjd| j|f d S )Nr   r(   addExpectedFailure)rC   rG   r5   rK   r9   )r   r    r,   r   r   r   rR      s    z#RemoteTestResult.addExpectedFailurec             C   s   | j jd| jf | j  d S )NaddUnexpectedSuccess)r5   rK   r9   rI   )r   r    r   r   r   rS      s    z%RemoteTestResult.addUnexpectedSuccessN)r0   r1   r2   __doc__r   propertyr9   rG   rI   rH   rJ   rL   r   r!   r*   r-   rN   rO   rP   rR   rS   r   r   r   r   r4   B   s"   	/
r4   c               @   s&   e Zd ZdZeZdddZdd ZdS )	RemoteTestRunnerz
    Run tests and record everything but don't display anything.

    The implementation matches the unpythonic coding style of unittest2.
    FNc             C   s   || _ |d k	r|| _d S )N)r6   resultclass)r   r6   rW   r   r   r   r      s    zRemoteTestRunner.__init__c             C   s&   | j  }tj| | j|_|| |S )N)rW   unittestZregisterResultr6   )r   r    resultr   r   r   run   s
    
zRemoteTestRunner.run)FN)r0   r1   r2   rT   r4   rW   r   rZ   r   r   r   r   rV      s   
rV   c               C   s:   t tdsdS yttjd S  tk
r4   tj S X dS )zL
    Default number of test processes when using the --parallel option.
    forkr(   ZDJANGO_TEST_PROCESSESN)hasattrosintenvironKeyErrormultiprocessing	cpu_countr   r   r   r   default_test_processes   s    
rc   c          
   C   sb   | j   |  jd7  _| jaW dQ R X x4tD ],}t| }|jjt}|jj| |j  q.W dS )z
    Switch to databases dedicated to this worker.

    This helper lives at module-level because of the multiprocessing module's
    requirements.
    r(   N)	Zget_lockvalue
_worker_idr   creationZget_test_db_clone_settingssettings_dictupdateclose)counteralias
connectionrg   r   r   r   _init_worker   s    


rm   c             C   s(   | \}}}t |d}|j|}||jfS )z
    Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.

    This helper lives at module-level and its arguments are wrapped in a tuple
    because of the multiprocessing module's requirements.
    )r6   )rV   rZ   r5   )argssubsuite_indexsubsuiter6   ZrunnerrY   r   r   r   _run_subsuite   s    


rq   c                   s2   e Zd ZdZeZeZd fdd	Zdd Z	  Z
S )ParallelTestSuitea  
    Run a series of tests in parallel in several processes.

    While the unittest module's documentation implies that orchestrating the
    execution of tests is the responsibility of the test runner, in practice,
    it appears that TestRunner classes are more concerned with formatting and
    displaying test results.

    Since there are fewer use cases for customizing TestSuite than TestRunner,
    implementing parallelization at the level of the TestSuite improves
    interoperability with existing custom test runners. A single instance of a
    test runner can still collect results from all tests without being aware
    that they have been run in parallel.
    Fc                s(   t || _|| _|| _tt| j  d S )N)partition_suite_by_case	subsuites	processesr6   r   rr   r   )r   suiteru   r6   )r   r   r   r     s    
zParallelTestSuite.__init__c                s,  t dk	rt jj  tjtjd}tj j j	j
|gd} fddt jD }|j jj
|}x|jrr|j  P y|jdd\}}W n4 tjk
r   wbY n tk
r   |j  P Y nX t j| }xP|D ]H}	|	d }
t||
d}|dkrq||	d  }|	d	d }||f|  qW qbW |j  |S )
a/  
        Distribute test cases across workers.

        Return an identifier of each test case with its result in order to use
        imap_unordered to show results as soon as they're available.

        To minimize pickling errors when getting results from workers:

        - pass back numeric indexes in self.subsuites instead of tests
        - make tracebacks picklable with tblib, if available

        Even with tblib, errors may still occur for dynamically created
        exception classes such Model.DoesNotExist which cannot be unpickled.
        Nr   )ru   ZinitializerZinitargsc                s   g | ]\}}|| j fqS r   )r6   ).0indexrp   )r   r   r   
<listcomp><  s   z)ParallelTestSuite.run.<locals>.<listcomp>g?)timeoutr(      )rC   Zpickling_supportinstallra   Valuectypesc_intZPoolru   init_worker__func__	enumeratert   Zimap_unorderedrun_subsuiter7   	terminatenextTimeoutErrorStopIterationri   listgetattrjoin)r   rY   rj   poolrn   Ztest_resultsro   r5   testseventZ
event_namer   r    r   )r   r   rZ   $  s@    



zParallelTestSuite.run)F)r0   r1   r2   rT   rm   r   rq   r   r   rZ   r3   r   r   )r   r   rr   
  s
   rr   c               @   s   e Zd ZdZejZeZej	Z
ejZeefZdddZed	d
 Zdd ZdddZdd Zdd Zdd Zdd Zdd Zdd ZdddZdS ) DiscoverRunnerzB
    A Django test runner that uses unittest2 test discovery.
    Nr(   TFr   c             K   sV   || _ || _|| _|| _|| _|| _|| _|| _|	| _t	|
p>g | _
t	|pLg | _d S )N)pattern	top_levelr   interactiver6   keepdbreverse	debug_sqlparallelsettagsexclude_tags)r   r   r   r   r   r6   r   r   r   r   r   r   kwargsr   r   r   r   h  s    zDiscoverRunner.__init__c          
   C   s   |j ddddd dd |j dddd	d
dd |j ddddddd |j ddddddd |j ddddddd |j ddddtt ddd  |j d!d"d#d$d% |j d&d"d'd(d% d S ))Nz-tz--top-level-directorystorer   z,Top level of project for unittest discovery.)actiondestdefaulthelpz-pz	--patternr   ztest*.pyz0The test matching pattern. Defaults to test*.py.z-kz--keepdb
store_truer   Fz#Preserves the test DB between runs.z-rz	--reverser   zReverses test cases order.z-dz--debug-sqlr   z%Prints logged SQL queries on failure.z
--parallelr   ?r(   Nz+Run tests using up to N parallel processes.)r   nargsr   typeconstmetavarr   z--tagrK   r   zBRun only tests with the specified tag. Can be used multiple times.)r   r   r   z--exclude-tagr   zDDo not run tests with the specified tag. Can be used multiple times.)add_argumentr^   rc   )clsparserr   r   r   add_argumentsy  s2    





zDiscoverRunner.add_argumentsc             K   s   t   dt_tj  d S )NF)r	   r   r   rX   ZinstallHandler)r   r   r   r   r   r	     s    z%DiscoverRunner.setup_test_environmentc             K   s  | j  }|pdg}|pg }i }| jd k	r2| j|d< | jd k	rF| j|d< x|D ]}|j }d }tjj|}tjj|s| jj	|}n^tjj
|r| j r|}	x<tjj|	d}
tjj|
rtjj|	}||	krP |}	qP qW |	|d< |o|j  ot|r| jjf d|i|}d | j_|j| qLW x|D ]}|j| q*W | jsN| jr^t|| j| j}t|| j| j}| jdkr| j|| j| j}t|j}| j|kr|| _| jdkr|}|S )N.r   Ztop_level_dirz__init__.py	start_dirr(   )
test_suiter   r   copyr]   pathabspathexiststest_loaderZloadTestsFromNameisdirr   dirnameZcountTestCasesis_discoverableZdiscoverZ_top_level_diraddTestsaddTestr   r   filter_tests_by_tagsreorder_suite
reorder_byr   r   parallel_test_suiter6   lenrt   )r   test_labelsextra_testsr   rv   Zdiscover_kwargslabelr   Zlabel_as_pathr   Zinit_pyZtry_nextr    Zparallel_suiteZparallel_unitsr   r   r   build_suite  sV    







zDiscoverRunner.build_suitec             K   s   t | j| j| j| j| jf|S )N)setup_databasesr   r   r   r   r   )r   r   r   r   r   r     s    zDiscoverRunner.setup_databasesc             C   s   | j r
tS d S )N)r   r   )r   r   r   r   get_resultclass  s    zDiscoverRunner.get_resultclassc             K   s"   | j  }| j| j| j|dj|S )N)r   r6   rW   )r   test_runnerr   r6   rZ   )r   rv   r   rW   r   r   r   	run_suite  s    zDiscoverRunner.run_suitec             K   sh   xb|D ]Z\}}}|r| j dkrLx,t| j D ]}|jj|d | j| jd q*W |jj|| j| j qW dS )z8
        Destroys all the non-mirror databases.
        r(   )numberr   r   N)r   rangerf   Zdestroy_test_dbr   r   )r   
old_configr   rl   Zold_namedestroyrx   r   r   r   teardown_databases  s    
z!DiscoverRunner.teardown_databasesc             K   s   t j  t  d S )N)rX   r"   r
   )r   r   r   r   r   r
     s    z(DiscoverRunner.teardown_test_environmentc             K   s   t |jt |j S )N)r   r.   r+   )r   rv   rY   r   r   r   r   suite_result  s    zDiscoverRunner.suite_resultc             K   sD   | j   | j||}| j }| j|}| j| | j  | j||S )a[  
        Run the unit tests for all the test labels in the provided list.

        Test labels should be dotted Python paths to test modules, test
        classes, or test methods.

        A list of 'extra' tests may also be provided; these tests
        will be added to the test suite.

        Returns the number of tests that failed.
        )r	   r   r   r   r   r
   r   )r   r   r   r   rv   r   rY   r   r   r   	run_tests  s    

zDiscoverRunner.run_tests)NNr(   TFFFFr   NN)NN)N)r0   r1   r2   rT   rX   	TestSuiter   rr   r   ZTextTestRunnerr   ZdefaultTestLoaderr   r   r   r   r   classmethodr   r	   r   r   r   r   r   r
   r   r   r   r   r   r   r   ]  s(      
$
Nr   c             C   sD   yt | }W n ttfk
r$   Y nX t|dS tjjtjj| S )z
    Check if a test label points to a python package or file directory.

    Relative labels like "." and ".." are seen as directories.
    __path__)r   ImportError	TypeErrorr\   r]   r   r   r   )r   modr   r   r   r   ,  s    
r   c             C   s   g }t  }i }xX| D ]P\}\}}t  }x|D ]}	|j|j|	g  q,W |j|s\td| |||< qW xx| rd}
g }xV| D ]N\}\}}|| j|r|j| |j|||ff d}
q||j|||ff q|W |
std|} qjW |S )zp
    Reorder test_databases into an order that honors the dependencies
    described in TEST[DEPENDENCIES].
    zHCircular dependency: databases %r depend on each other, but are aliases.FTz)Circular dependency in TEST[DEPENDENCIES])r   rh   get
isdisjointr   issubsetrK   )test_databasesdependenciesZordered_test_databasesZresolved_databasesZdependencies_mapsig_aliasesZall_depsrk   changeddeferred	signaturedb_namer   r   r   dependency_ordered<  s4    


r   Fc             C   sd   t |}t| }dd t|d D }t| |||d | }x"t|d D ]}|j||  qJW |S )aT  
    Reorders a test suite by test type.

    `classes` is a sequence of types

    All tests of type classes[0] are placed first, then tests of type
    classes[1], etc. Tests with no match in classes are placed last.

    If `reverse` is True, tests within classes are sorted in opposite order,
    but test classes are not reversed.
    c             S   s   g | ]
}t  qS r   )r   )rw   ir   r   r   ry   t  s    z!reorder_suite.<locals>.<listcomp>r(   )r   )r   r   r   partition_suite_by_typer   )rv   classesr   Zclass_countsuite_classbinsZreordered_suiter   r   r   r   r   f  s    r   c             C   s   t | }|rtt| } xj| D ]b}t||r>t||||d qx@tt|D ]"}t||| rL|| j| P qLW |d j| qW dS )aX  
    Partitions a test suite by test type. Also prevents duplicated tests.

    classes is a sequence of types
    bins is a sequence of TestSuites, one more than classes
    reverse changes the ordering of tests within bins

    Tests of type classes[i] are added to bins[i],
    tests with no match found in classes are place in bins[-1]
    )r   r(   Nr)   )r   reversedtuple
isinstancer   r   r   add)rv   r   r   r   r   r    r   r   r   r   r   |  s    

r   c             C   sb   g }t | }xPtj| t D ]@\}}t|tjr>|j|| qx|D ]}|jt| qDW qW |S )zN
    Partitions a test suite by test case, preserving the order of tests.
    )	r   	itertoolsgroupby
issubclassrX   r   rK   extendrs   )rv   groupsr   Z	test_typeZ
test_groupitemr   r   r   rs     s    
rs   c              C   s   i } i }i }t t jj }xt D ]}t | }|jd }|d rL|d | |< q |j|jj |jd t f}|d j| d|kr|d ||< q |tkr |jj |kr |jdtg||< q W t	|j
 |}tj|}|| fS )a  
    Figure out which databases actually need to be created.

    Deduplicate entries in DATABASES that correspond the same database or are
    configured as test mirrors.

    Return two values:
    - test_databases: ordered mapping of signatures to (name, list of aliases)
                      where all aliases share the same underlying database.
    - mirrored_aliases: mapping of mirror aliases to original aliases.
    TESTZMIRRORNAMEr(   ZDEPENDENCIES)r   r   rf   Ztest_db_signaturerg   
setdefaultr   r   r   r   itemscollectionsOrderedDict)mirrored_aliasesr   r   Zdefault_sigrk   rl   Ztest_settingsr   r   r   r    get_unique_databases_and_mirrors  s(    


r   c          	   K   s"  t  \}}g }x|j D ]\}	\}
}d}x|D ]}t| }|j||
|dkf |dkr|}|jj| | ||jjdi jddd |dkrx>t|D ]}|jj	|d | |d qW q.t| jj
t| j q.W qW x*|j D ]\}}t| jj
t| j qW |rxtD ]}dt| _q
W |S )z%
    Creates the test databases.
    Nr   Z	SERIALIZET)r   Zautoclobberr   	serializer(   )r   r   r   )r   r   r   rK   rf   Zcreate_test_dbrg   r   r   Zclone_test_dbZset_as_test_mirrorZforce_debug_cursor)r   r   r   r   r   r   r   r   Z	old_namesr   r   r   Zfirst_aliasrk   rl   rx   Zmirror_aliasr   r   r   r     s:    




r   c             C   s   t | }| }x| D ]}t||r6|jt||| qtt|dt }t|dt|}t|||}tt|dt }	|j|	}
|
j|}|s| r|
j| r|j	| qW |S )Nr   Z_testMethodName)
r   r   r   r   r   r   strunionintersectionr   )rv   r   r   r   Zfiltered_suiter    Z	test_tagsZtest_fn_nameZtest_fnZtest_fn_tagsZall_tagsZmatched_tagsr   r   r   r     s    



r   )F)F)FFr   )3r   r~   r   r   ra   r]   r=   rA   rX   	importlibr   Zdjango.confr   Zdjango.core.exceptionsr   Z	django.dbr   r   Zdjango.testr   r   Zdjango.test.utilsr	   r
   Zdjango.utils.datastructuresr   Zdjango.utils.sixr   Ztblib.pickling_supportrC   r   ZTextTestResultr   objectr4   rV   rc   re   rm   rq   r   rr   r   r   r   r   r   rs   r   r   r   r   r   r   r   <module>   sL   
(zS P*

-
/