3
gu                 @   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	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 d dlmZmZ d dlmZmZmZmZ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 dl#Z#Y nX 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
j'Z)G dd dZ*G dd dZ+dd Z,d a-dd Z.dd Z/G dd de
j0Z1G dd dZ2dd Z3d'dd Z4d(d!d"Z5d#d$ Z6d%d& Z7dS ))    N)import_module)StringIO)call_command)connections)SimpleTestCaseTestCase)NullTimeKeeper
TimeKeepersetup_databasessetup_test_environmentteardown_databasesteardown_test_environment)
OrderedSet)PY37c                   s`   e Zd Z fd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                s4   t jd| _| jjt j d | _t j||| d S )Nzdjango.db.backends)logging	getLoggerloggersetLevelDEBUGdebug_sql_streamsuper__init__)selfstreamZdescriptions	verbosity)	__class__ P/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/test/runner.pyr   &   s    zDebugSQLTextTestResult.__init__c                s4   t  | _tj| j| _| jj| j t j| d S )N)	r   r   r   StreamHandlerhandlerr   
addHandlerr   	startTest)r   test)r   r   r   r"   ,   s    z DebugSQLTextTestResult.startTestc                sP   t  j| | jj| j | jrL| jjd | jj	| jj
  | jj| j d S )Nr   )r   stopTestr   removeHandlerr    ZshowAllr   seekr   writereadwriteln
separator2)r   r#   )r   r   r   r$   2   s    zDebugSQLTextTestResult.stopTestc                sN   t  j|| | jd krd}n| jjd | jj }| jd |f | jd< d S )N r      r-   )r   addErrorr   r&   r(   errors)r   r#   errZsql)r   r   r   r.   :   s    

zDebugSQLTextTestResult.addErrorc                s:   t  j|| | jjd | jd | jj f | jd< d S )Nr   r,   r-   r-   )r   
addFailurer   r&   failuresr(   )r   r#   r0   )r   r   r   r1   D   s    z!DebugSQLTextTestResult.addFailurec                s\   t  j||| |d k	rX| jjd t|d |jr:| jn| j}|d | jj f |d< d S )Nr   r,   r-   r-   )	r   
addSubTestr   r&   
issubclassZfailureExceptionr2   r/   r(   )r   r#   subtestr0   r/   )r   r   r   r3   I   s
    z!DebugSQLTextTestResult.addSubTestc             C   st   xn|D ]f\}}}| j j| j | j jd|| j|f  | j j| j | j j| | j j| j | j j| qW d S )Nz%s: %s)r   r)   Z
separator1ZgetDescriptionr*   )r   Zflavourr/   r#   r0   Z	sql_debugr   r   r   printErrorListP   s    z%DebugSQLTextTestResult.printErrorList)__name__
__module____qualname__r   r"   r$   r.   r1   r3   r6   __classcell__r   r   )r   r   r   %   s   
r   c                   s4   e Zd ZdZ fddZ fddZdd Z  ZS )PDBDebugResultz^
    Custom result class that triggers a PDB session when an error or failure
    occurs.
    c                s   t  j|| | j| d S )N)r   r.   debug)r   r#   r0   )r   r   r   r.   `   s    zPDBDebugResult.addErrorc                s   t  j|| | j| d S )N)r   r1   r<   )r   r#   r0   )r   r   r   r1   d   s    zPDBDebugResult.addFailurec             C   s2   | j   d| _|\}}}td|  tj| d S )NFz
Opening PDB: %r)Z_restoreStdoutbufferprintpdbZpost_mortem)r   errorexc_type	exc_value	tracebackr   r   r   r<   h   s
    
zPDBDebugResult.debug)r7   r8   r9   __doc__r.   r1   r<   r:   r   r   )r   r   r;   Z   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"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.   t d k	rt jj  g | _d| _d| _d| _d S )NFr   )tblibZpickling_supportinstalleventsfailfast
shouldStoptestsRun)r   r   r   r   r   {   s    
zRemoteTestResult.__init__c             C   s
   | j d S )Nr,   )rK   )r   r   r   r   
test_index   s    zRemoteTestResult.test_indexc             C   s   t jt j| dS )z
        Confirm that obj can be pickled and unpickled as multiprocessing will
        need to pickle the exception in the child process and unpickle it in
        the parent process. Let the exception rise, if not.
        N)pickleloadsdumps)r   objr   r   r   _confirm_picklable   s    z#RemoteTestResult._confirm_picklablec             C   s   t dj||| d S )Na'  
Subtest failed:

    test: {}
 subtest: {}

Unfortunately, the subtest that failed cannot be pickled, so the parallel
test runner cannot handle it cleanly. Here is the pickling error:

> {}

You should re-run this test with --parallel=1 to reproduce the failure
with a cleaner failure message.
)r>   format)r   r#   r5   Z
pickle_excr   r   r   _print_unpicklable_subtest   s    z+RemoteTestResult._print_unpicklable_subtestc             C   s   y| 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:

    python -m 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.
)rQ   	ExceptionreprtextwrapfillrF   r>   rR   )r   r#   r0   excZoriginal_exc_txtZpickle_exc_txtr   r   r   check_picklable   s    z RemoteTestResult.check_picklablec             C   sF   y| j | W n2 tk
r@ } z| j|||  W Y d d }~X nX d S )N)rQ   rW   rS   )r   r#   r5   r[   r   r   r   check_subtest_picklable   s
    z(RemoteTestResult.check_subtest_picklablec             C   s   | j r| j  d S )N)rI   stop)r   r   r   r   stop_if_failfast   s    z!RemoteTestResult.stop_if_failfastc             C   s
   d| _ d S )NT)rJ   )r   r   r   r   r^      s    zRemoteTestResult.stopc             C   s   | j jd d S )NstartTestRun)r`   )rH   append)r   r   r   r   r`      s    zRemoteTestResult.startTestRunc             C   s   | j jd d S )NstopTestRun)rb   )rH   ra   )r   r   r   r   rb      s    zRemoteTestResult.stopTestRunc             C   s$   |  j d7  _ | jjd| jf d S )Nr,   r"   )rK   rH   ra   rL   )r   r#   r   r   r   r"      s    zRemoteTestResult.startTestc             C   s   | j jd| jf d S )Nr$   )rH   ra   rL   )r   r#   r   r   r   r$      s    zRemoteTestResult.stopTestc             C   s,   | j || | jjd| j|f | j  d S )Nr.   )r\   rH   ra   rL   r_   )r   r#   r0   r   r   r   r.      s    zRemoteTestResult.addErrorc             C   s,   | j || | jjd| j|f | j  d S )Nr1   )r\   rH   ra   rL   r_   )r   r#   r0   r   r   r   r1      s    zRemoteTestResult.addFailurec             C   sB   |d k	r>| j || | j|| | jjd| j||f | j  d S )Nr3   )r\   r]   rH   ra   rL   r_   )r   r#   r5   r0   r   r   r   r3      s
    zRemoteTestResult.addSubTestc             C   s   | j jd| jf d S )N
addSuccess)rH   ra   rL   )r   r#   r   r   r   rc      s    zRemoteTestResult.addSuccessc             C   s   | j jd| j|f d S )NaddSkip)rH   ra   rL   )r   r#   reasonr   r   r   rd     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)rF   r\   rH   ra   rL   )r   r#   r0   r   r   r   rf     s    z#RemoteTestResult.addExpectedFailurec             C   s   | j jd| jf | j  d S )NaddUnexpectedSuccess)rH   ra   rL   r_   )r   r#   r   r   r   rg     s    z%RemoteTestResult.addUnexpectedSuccessN)r7   r8   r9   rD   r   propertyrL   rQ   rS   r\   r]   r_   r^   r`   rb   r"   r$   r.   r1   r3   rc   rd   rf   rg   r   r   r   r   rE   p   s(   		/
rE   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)rI   resultclass)r   rI   rj   r   r   r   r     s    zRemoteTestRunner.__init__c             C   s&   | j  }tj| | j|_|| |S )N)rj   unittestZregisterResultrI   )r   r#   resultr   r   r   run"  s
    
zRemoteTestRunner.run)FN)r7   r8   r9   rD   rE   rj   r   rm   r   r   r   r   ri     s   
ri   c               C   s<   t j dkrdS yttjd S  tk
r6   t j S X dS )zBDefault number of test processes when using the --parallel option.forkr,   ZDJANGO_TEST_PROCESSESN)multiprocessingget_start_methodintosenvironKeyError	cpu_countr   r   r   r   default_test_processes*  s    rv   c             C   sf   | j   |  jd7  _| jaW dQ R X x8tD ]0}t| }|jjt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   ZcreationZget_test_db_clone_settingsstrsettings_dictupdateclose)counteralias
connectionrz   r   r   r   _init_worker9  s    


r   c             C   s*   | \}}}}||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.
    )rI   )rm   rH   )argsrunner_classsubsuite_indexsubsuiterI   runnerrl   r   r   r   _run_subsuiteR  s    

r   c                   s>   e Zd ZdZeZeZeZ	d	 fdd	Z
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 j  d S )N)partition_suite_by_case	subsuites	processesrI   r   r   )r   suiter   rI   )r   r   r   r   t  s    
zParallelTestSuite.__init__c                s  t jtjd}t j j jj|gd} fddt j	D }|j
 jj|}x|jr`|j  P y|jdd\}}W n4 t jk
r   wPY 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 qPW |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 which cannot be unpickled.
        r   )r   initializerinitargsc                s    g | ]\}} j || jfqS r   )r   rI   ).0indexr   )r   r   r   
<listcomp>  s   z)ParallelTestSuite.run.<locals>.<listcomp>g?)timeoutNr,      )ro   Valuectypesc_intPoolr   init_worker__func__	enumerater   Zimap_unorderedrun_subsuiterJ   	terminatenextTimeoutErrorStopIterationr|   listgetattrjoin)r   rl   r}   poolr   Ztest_resultsr   rH   testseventZ
event_namer    r#   r   )r   r   rm   z  s<    


zParallelTestSuite.runc             C   s
   t | jS )N)iterr   )r   r   r   r   __iter__  s    zParallelTestSuite.__iter__)F)r7   r8   r9   rD   r   r   r   r   ri   r   r   rm   r   r:   r   r   )r   r   r   _  s   6r   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 Zdd Zdd  Zd!d" Zd'd#d$ZdS )(DiscoverRunnerz8A Django test runner that uses unittest2 test discovery.Nr,   TFr   c             K   s  || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	t
|pDg | _t
|pRg | _tj  r|rytjtjj d W n, ttjfk
r   tjtjj d Y nX || _| jr| j	dkrtd|| _| jr| j	dkrtdd | _|rt nt | _|rdd |D | _d S )N)filer,   zFYou cannot use --pdb with parallel tests; pass --parallel=1 to use it.zLYou cannot use -b/--buffer with parallel tests; pass --parallel=1 to use it.c             S   s    h | ]}d |kr|nd| qS )*z*%s*r   )r   patternr   r   r   	<setcomp>  s   z*DiscoverRunner.__init__.<locals>.<setcomp>)r   	top_levelr   interactiverI   keepdbreverse
debug_mode	debug_sqlparallelsettagsexclude_tagsfaulthandlerZ
is_enabledenablesysstderrfilenoAttributeErrorioUnsupportedOperation
__stderr__r?   
ValueErrorr=   test_name_patternsr	   r   time_keeper)r   r   r   r   r   rI   r   r   r   r   r   r   r   r   r?   r=   enable_faulthandlerZtimingkwargsr   r   r   r     s:    zDiscoverRunner.__init__c          	   C   s  |j ddddd |j dddd	d
 |j dddd |j ddddd |j dddd |j ddddd |j dddtt ddd |j dddd d! |j d"dd#d$d! |j d%dd&d |j d'd(dd)d |j d*d+d,d-d! |j d.dd/d tr|j d0dd1d2d! d S )3Nz-tz--top-level-directoryr   z,Top level of project for unittest discovery.)desthelpz-pz	--patternztest*.pyz0The test matching pattern. Defaults to test*.py.)defaultr   z--keepdb
store_truez#Preserves the test DB between runs.)actionr   z-rz	--reversezReverses test cases order.z--debug-modezSets settings.DEBUG to True.z-dz--debug-sqlz%Prints logged SQL queries on failure.z
--parallel?r,   Nz+Run tests using up to N parallel processes.)nargsr   typeconstmetavarr   z--tagra   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.z--pdbz@Runs a debugger (pdb, or ipdb if installed) on error or failure.z-bz--bufferz"Discard output from passing tests.z--no-faulthandlerstore_falser   z5Disables the Python faulthandler module during tests.z--timingz=Output timings, including database set up and total run time.z-kr   z~Only run test methods and classes that match the pattern or substring. Can be used multiple times. Same as unittest -k option.)add_argumentrq   rv   r   )clsparserr   r   r   add_arguments  sX    zDiscoverRunner.add_argumentsc             K   s   t | jd tj  d S )N)r<   )r   r   rk   ZinstallHandler)r   r   r   r   r   r   +  s    z%DiscoverRunner.setup_test_environmentc             K   s  | j  }|pdg}|pg }| j| j_i }| jd k	r<| j|d< | jd k	rP| 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  r"t|r"| jjf d|i|}d | j_|j| qVW x|D ]}|j| q6W | jsZ| jr| jdkr| jrtddjt| j  | jrtd	djt| j  t|| j| j}t|| j| j}| jd
kr| j|| j| j }t!|j"}t#| j|| _| jd
kr|}|S )N.r   Ztop_level_dirz__init__.py	start_dirr   zIncluding test tag(s): %s.z, zExcluding test tag(s): %s.r,   )$
test_suiter   test_loaderZtestNamePatternsr   r   copyrr   pathabspathexistsZloadTestsFromNameisdirr   dirnameZcountTestCasesis_discoverableZdiscoverZ_top_level_diraddTestsaddTestr   r   r   r>   sortedfilter_tests_by_tagsreorder_suite
reorder_byr   r   parallel_test_suiterI   lenr   min)r   test_labelsextra_testsr   r   Zdiscover_kwargslabelr   Zlabel_as_pathr   Zinit_pyZtry_nextr#   Zparallel_suiteZparallel_unitsr   r   r   build_suite/  s`    








zDiscoverRunner.build_suitec             K   s(   t | j| jf| j| j| j| jd|S )N)r   r   r   r   )_setup_databasesr   r   r   r   r   r   )r   r   r   r   r   r
     s    zDiscoverRunner.setup_databasesc             C   s   | j r
tS | jrtS d S )N)r   r   r?   r;   )r   r   r   r   get_resultclass  s    zDiscoverRunner.get_resultclassc             C   s   | j | j | j| jdS )N)rI   rj   r   r=   )rI   r   r   r=   )r   r   r   r   get_test_runner_kwargs  s    z%DiscoverRunner.get_test_runner_kwargsc             C   s   t d| j|d d S )Ncheck)r   	databases)r   r   )r   r   r   r   r   
run_checks  s    zDiscoverRunner.run_checksc             K   s   | j  }| jf |}|j|S )N)r   test_runnerrm   )r   r   r   r   r   r   r   	run_suite  s    zDiscoverRunner.run_suitec             K   s   t || j| j| jd dS )z%Destroy all the non-mirror databases.)r   r   r   N)_teardown_databasesr   r   r   )r   
old_configr   r   r   r   r     s
    z!DiscoverRunner.teardown_databasesc             K   s   t j  t  d S )N)rk   r%   r   )r   r   r   r   r   r     s    z(DiscoverRunner.teardown_test_environmentc             K   s   t |jt |j S )N)r   r2   r/   )r   r   rl   r   r   r   r   suite_result  s    zDiscoverRunner.suite_resultc             C   s`   t  }xT|D ]L}t|tjrHt|dd }|dkr8t tS |rX|j| q|j| j| qW |S )Nr   __all__)r   
isinstancerk   r   r   r   r{   _get_databases)r   r   r   r#   Ztest_databasesr   r   r   r     s    
zDiscoverRunner._get_databasesc                sD   | j | | jdkr@ fddtD }|r@tddjt|   S )Nr   c                s   g | ]}| kr|qS r   r   )r   r~   )r   r   r   r     s    z0DiscoverRunner.get_databases.<locals>.<listcomp>z)Skipping setup of unused database(s): %s.z, )r   r   r   r>   r   r   )r   r   Zunused_databasesr   )r   r   get_databases  s    

zDiscoverRunner.get_databasesc       	   %   K   s   | j   | j||}| j|}| jjd | j|d}W dQ R X d}z8y| j| | j|}W n tk
rz   d} Y nX W dy.| jjd | j	| W dQ R X | j
  W n tk
r   |sĂ Y nX X | jj  | j||S )aZ  
        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.

        Return the number of tests that failed.
        zTotal database setup)aliasesNFTzTotal database teardown)r   r   r   r   Ztimedr
   r   r   rW   r   r   Zprint_resultsr   )	r   r   r   r   r   r   r   Z
run_failedrl   r   r   r   	run_tests  s*    



zDiscoverRunner.run_tests)NNr,   TFFFFFr   NNNFFTF)NN)N) r7   r8   r9   rD   rk   	TestSuiter   r   r   ZTextTestRunnerr   ZdefaultTestLoaderr   r   r   r   r   classmethodr   r   r   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s4        
&C
S	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	TypeErrorhasattrrr   r   r   r   )r   modr   r   r   r     s    
r   Fc             C   sd   t |}t| }dd t|d D }t| |||d | }x"t|d D ]}|j||  qJW |S )aI  
    Reorder 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, sort tests within classes in opposite order but
    don't reverse test classes.
    c             S   s   g | ]
}t  qS r   )r   )r   ir   r   r   r   	  s    z!reorder_suite.<locals>.<listcomp>r,   )r   )r   r   rangepartition_suite_by_typer   )r   classesr   Zclass_countsuite_classbinsZreordered_suiter  r   r   r   r     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 )aV  
    Partition a test suite by test type. Also prevent 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tupler   r  r  r   add)r   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 )zCPartition a test suite by test case, preserving the order of tests.)	r   	itertoolsgroupbyr4   rk   r   ra   extendr   )r   groupsr  Z	test_typeZ
test_groupitemr   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   ry   unionintersectionr   )r   r   r   r  Zfiltered_suiter#   Z	test_tagsZtest_fn_nameZtest_fnZtest_fn_tagsZall_tagsZmatched_tagsr   r   r   r   8  s    



r   )F)F)8r   r   r   r  r   ro   rr   rM   r   rY   rk   	importlibr   r   Zdjango.core.managementr   Z	django.dbr   Zdjango.testr   r   Zdjango.test.utilsr   r	   r
   r   r   r   r   r   Zdjango.utils.datastructuresr   Zdjango.utils.versionr   Zipdbr?   r   Ztblib.pickling_supportrF   ZTextTestResultr   r;   rE   ri   rv   rx   r   r   r   r   r   r   r   r  r   r   r   r   r   r   <module>   sX    
5 %U  9

