a
    P·5gp5  ã                   @   sR  d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	m
Z
mZmZ ddlmZ ddlZeƒ ej_ejj d¡ e	j ¡ ZdZedd	„ ƒZed
ƒdd„ ƒZedƒeddƒdd„ ƒƒZedd„ ƒZe
jG dd„ de
j
ƒƒZdd„ Zdd„ Z g d¢Z!dd„ Z"d&dd„Z#d d!„ Z$zdd"l%m&Z& W n  e'�y>   dd#l%m(Z( Y n0 e&j(Z(d$d%„ Z)dS )'aÁ  
Unit testing system for C/C++/D and interpreted languages providing test execution:

* in parallel, by using ``waf -j``
* partial (only the tests that have changed) or full (by using ``waf --alltests``)

The tests are declared by adding the **test** feature to programs::

    def options(opt):
        opt.load('compiler_cxx wcb_unit_test')
    def configure(conf):
        conf.load('compiler_cxx wcb_unit_test')
    def build(bld):
        bld(features='cxx cxxprogram test', source='main.cpp', target='app')
        # or
        bld.program(features='test', source='main2.cpp', target='app2')

When the build is executed, the program 'test' will be built and executed without arguments.
The success/failure is detected by looking at the return code. The status and the standard output/error
are stored on the build context.

The results can be displayed by registering a callback function. Here is how to call
the predefined callback::

    def build(bld):
        bld(features='cxx cxxprogram test', source='main.c', target='app')
        from waflib.Tools import wcb_unit_test
        bld.add_post_fun(wcb_unit_test.summary)

By passing --dump-test-scripts the build outputs corresponding python files
(with extension _run.py) that are useful for debugging purposes.

Extended for wcb:
- reindent (sorry tab lovers)
- add timing to test execution and summary
- flip default to not tests and option names --notests to --tests.
- include management of test data files
é    N)ÚfeatureÚafter_methodÚtaskgen_method)ÚUtilsÚTaskÚLogsÚOptions)ÚccrootÚwcb_unit_test_cachezá#! %(python)s
import subprocess, sys
cmd = %(cmd)r
# if you want to debug with gdb:
#cmd = ['gdb', '-args'] + cmd
env = %(env)r
status = subprocess.call(cmd, env=env, cwd=%(cwd)r, shell=isinstance(cmd, str))
sys.exit(status)
c                 C   sJ   t | |dƒ}|rFt|tƒrFtj |¡r8| jj |¡| _	n| j |¡| _	dS )zr
    Task generator method, used internally to limit code duplication.
    This method may disappear anytime.
    N)
ÚgetattrÚ
isinstanceÚstrÚosÚpathÚisabsÚbldÚrootÚ	make_nodeÚut_cwd)ÚselfÚkeyÚcwd© r   ú?/home/yuhw/wc/larsoft925/src/wct-porting2/waft/wcb_unit_test.pyÚhandle_ut_cwdC   s    
r   Útest_scriptsc                    s<  dD ]"}t ˆ |ƒst d| ¡  dS qtjˆ jtˆ ddƒd�\ˆ _}ˆ  ˆ j	¡}|D ]2}ˆ  
d|g¡}||j |_| | ¡ ¡|jd< qVˆ  d	¡ tˆ d
dƒ}|r¬|ˆ _nttjƒˆ _tˆ di ƒ}| ¡ D ]L\}}	ˆ j |d¡ tj¡}
t|	tƒ�r|	 tj¡}	tj |
|	 ¡ˆ j|< qÌˆ j d‡ fdd„ˆ jD ƒ¡ dS )zCreate interpreted unit tests.)Útest_scripts_sourceÚtest_scripts_templatez#a test_scripts taskgen i missing %sNZtest_scripts_shellF©ÚshellÚutestZSCRIPTZtest_scripts_cwdÚtest_scripts_envZtest_scripts_pathsÚ ÚUT_DEPSc                    s   g | ]}d |ˆ j | f ‘qS ©z%r%r©Úut_env©Ú.0r   ©r   r   r   Ú
<listcomp>p   ó    z)make_interpreted_test.<locals>.<listcomp>)Úhasattrr   Úwarnr   Úcompile_funr   r   Úut_runÚto_nodesr   Úcreate_taskÚvarsÚ	path_fromÚget_cwdÚenvr   r&   Údictr   ÚenvironÚitemsÚgetÚsplitÚpathsepr   r   ÚjoinÚappend_value)r   ÚxÚlstZscript_nodesZscript_nodeÚtskr5   ÚpathsÚkÚvÚpr   r)   r   Úmake_interpreted_testR   s,    

rE   ÚtestZ
apply_linkZprocess_usec              	      s¬  t ˆddƒsdS ˆ dˆjj¡}t ˆddƒrftjˆjt ˆddƒd�\ˆ_}|j| |_ˆj	 
dˆj¡ ˆ d	¡ tˆd
ƒsæg }ˆjD ]L}zˆj |¡j}W n ty¬   Y q„0 t|tjƒs„| |jd j ¡ ¡ q„tj |¡tj ˆ_tˆdƒ�sJttjƒ ˆ_‰ ‡ ‡fdd„}tj�r"|dƒ n(t  ¡ dk�rB|dƒ |dƒ n|dƒ tˆdƒ�sft t!j"ddƒˆ_#ˆj	 
dt$ˆj#ƒ¡ ˆj	 
dˆj¡ ˆj	 
d‡fdd„ˆjD ƒ¡ dS )zRCreate the unit test task. There can be only one unit test task by task generator.Ú	link_taskNr    Úut_strZut_shellFr   r#   r   Úut_pathsr   r&   c                    s   ˆj ˆ  | d¡ ˆ | < d S )Nr"   )rI   r9   )Úvar©Údctr   r   r   Úadd_path�   s    zmake_test.<locals>.add_pathÚPATHÚdarwinZDYLD_LIBRARY_PATHÚLD_LIBRARY_PATHÚut_cmdÚtestcmdc                    s   g | ]}d |ˆ j | f ‘qS r$   r%   r'   r)   r   r   r*   ž   r+   zmake_test.<locals>.<listcomp>)%r   r1   rG   Úoutputsr   r.   rH   r/   r2   r5   r=   r   r,   Ztmp_use_sortedr   Úget_tgen_by_nameÚAttributeErrorr   r	   Zstlink_taskÚappendÚparentÚabspathr   r;   r<   rI   r6   r7   r&   r   Úis_win32Úunversioned_sys_platformr   ÚoptionsrQ   r   )r   r@   r?   rA   r>   ÚyrM   r   rK   r   Ú	make_testr   s@    




r]   c                 C   sv   t  dt|ƒ|f ¡ z| j |¡ W n ty@   |g| _Y n0 z| jj |¡ W n typ   |g| j_Y n0 dS )zTOverride and return tup[1] to interrupt the build immediately if a test does not runzwut: result tuple %d %rN)r   ÚdebugÚlenÚutest_resultsrV   rU   r   )r   Útupr   r   r   Úadd_test_results    s    rb   c                       s^   e Zd ZdZdZddgZdgZ‡ fdd„Zdd	„ Z‡ fd
d„Z	dd„ Z
dd„ Zdd„ Z‡  ZS )r    z
    Execute a unit test
    ÚPINKZvnumÚinstr#   c                    sš   | j jstjS tt| ƒ ¡ }|tjkr:ttj	ddƒr:tj
}t| j ddƒ}|tj
kr–|r–| jjj t| ƒd¡}|dur–||kr–t d||| f ¡ tj}|S )z®
        Skip running if `waf --tests` is NOT used or `waf --notests`
        is used.  Still skip if test already run unless `waf --tests
        --alltests` given.
        Ú	all_testsFÚTEST_DURATIONNz1wut: skip presumed slow (%.3f s > %.3f s) test %s)r5   ÚTESTSr   ÚSKIP_MEÚsuperr    Úrunnable_statusr   r   r[   ÚRUN_MEÚ	generatorr   r
   r9   r   r   r^   )r   ÚretZmaxdurZdur©Ú	__class__r   r   rj   ¶   s    
zutest.runnable_statusc                 C   s   | j jS )z‘
        In general, tests may require any library built anywhere in the project.
        Override this method if fewer paths are needed
        )rl   r&   r)   r   r   r   Úget_test_envÏ   s    zutest.get_test_envc                    s<   t t| ƒ ¡  ttjddƒr8| jd r8d | jjj	|  
¡ < d S )NÚclear_failed_testsFé   )ri   r    Úpost_runr   r   r[   Úwcb_unit_test_resultsrl   r   Ú	task_sigsÚuidr)   rn   r   r   rs   Ö   s    zutest.post_runc                 C   sj   t | jdƒr| j | ¡S t| jd| jd  ¡ gƒ| _t| jddƒ}|r^t |t	 
| j¡ ¡| _|  | j¡S )zä
        Execute the test. The execution is always successful, and the results
        are stored on ``self.generator.bld.utest_results`` for postprocessing.

        Override ``add_test_results`` to interrupt the build
        r/   Úut_execr   rQ   F)r,   rl   r/   r   ÚinputsrX   rw   Úshlexr:   r   Úshell_escapeÚexec_command)r   rQ   r   r   r   ÚrunÛ   s    z	utest.runc              	   K   sD  | j j ||¡ ttjddƒr†ttj|  	¡ |  
¡  ¡ |dœ }| jd  ¡ d }tj||dd� t |tj¡ tjdkr†t d	| ¡ t ¡ }| ¡ }tjj||  
¡  ¡ |  	¡ tjjtjjt|tƒd
�}| ¡ \}}	| ¡ }
|
| | j jjt| ƒ< | jd  ¡ |j||	t|ƒf | _}t  !¡  z| j  "|¡W t  #¡  S t  #¡  0 d S )NÚdump_test_scriptsF)Úpythonr5   r   Úcmdr   z_run.pyúutf-8)Úencodingrr   zTest debug file written as %r)r   r5   ÚstderrÚstdoutr   )$rl   r   Úlog_commandr   r   r[   ÚSCRIPT_TEMPLATEÚsysÚ
executablerp   r4   rX   rx   r   Úwritefr   ÚchmodÚO755r   ÚverboseÚinfoÚTimerÚnowÚ
subprocessÚPopenÚPIPEr   r   Úcommunicater
   Ú
returncodert   ÚtestlockÚacquirerb   Úrelease)r   r   ÚkwZscript_codeZscript_fileÚtimerÚt1Úprocrƒ   r‚   Út2ra   r   r   r   r{   ì   s8    
ü
ÿ$þzutest.exec_commandc                 C   s   t | jd| jd jƒS )Nr   r   )r   rl   rx   rW   r)   r   r   r   r4   	  s    zutest.get_cwd)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚcolorÚafterr2   rj   rp   rs   r|   r{   r4   Ú__classcell__r   r   rn   r   r    ­   s   r    c           	      C   sÊ   t | dg ƒ}|rÆt dd¡ t|ƒ}tdd„ |D ƒƒ}t dd|| |f ¡ |D ]&\}}}}}|sRt dd||f ¡ qRt |d	krŠdnd
d||f ¡ |D ]&\}}}}}|ržt d
d||f ¡ qždS )z÷
    Display an execution summary::

        def build(bld):
            bld(features='cxx cxxprogram test', source='main.c', target='app')
            from waflib.Tools import wcb_unit_test
            bld.add_post_fun(wcb_unit_test.summary)
    r`   ÚCYANzexecution summaryc                 S   s   g | ]}|d  r|‘qS )rr   r   )r(   r>   r   r   r   r*     r+   zsummary.<locals>.<listcomp>ÚGREENz  tests that pass %d/%dz    %s [%s]r   ÚREDz  tests that fail %d/%dN)r   r   Úpprintr_   )	r   r?   ÚtotalZtfailÚfÚcodeÚoutÚerrZtimr   r   r   Úsummary  s    	 r¬   c                 C   sx   t | dg ƒ}|D ]b\}}}}|rg }|rB| dtj| d¡f ¡ |r`| dtj| d¡f ¡ |  tj |¡¡ qdS )a¤  
    If any of the tests fail waf will exit with that exit code.
    This is useful if you have an automated build system which need
    to report on errors from the tests.
    You may use it like this:

        def build(bld):
            bld(features='cxx cxxprogram test', source='main.c', target='app')
            from waflib.Tools import wcb_unit_test
            bld.add_post_fun(wcb_unit_test.set_exit_code)
    r`   zstdout:%s%sr€   zstderr:%s%sN)r   rV   r   ÚlinesepÚdecodeÚfatalr<   )r   r?   r¨   r©   rª   r«   Úmsgr   r   r   Úset_exit_code%  s    r±   )ÚcheckÚatomicÚhistoryZreportc                 C   s´   | j ddddd� | j dtddd	� d
 t¡}| j ddtdg d| d d� | j ddddd� | j dddddd� | j dddddd� | j dddddd � | j d!ddd"d#d� dS )$z[
    Provide the ``--alltests``, ``--notests`` and ``--testcmd`` command-line options.
    z--testsNÚ
store_truezActivate tests [default: off])ÚdefaultÚactionÚhelpz--test-durationÚstorezISkip tests that may take longer than this many seconds [default: ignored])Útyper·   r¸   ú,z--test-groupÚallzSet test group {z,all} [default: all])r¶   Úchoicesr¸   z	--notestsÚstore_falseÚtestszDeactivate tests)r·   Údestr¸   z
--alltestsFzExec all unit testsre   )r·   r¶   r¸   rÀ   z--clear-failedz.Force failed unit tests to run again next timerq   z	--testcmdrR   zvRun the unit tests using the test-cmd string example "--testcmd="valgrind --error-exitcode=1 %s" to run under valgrind)r·   r¶   rÀ   r¸   z--dump-test-scriptsz)Create python scripts to help debug testsr}   )Ú
add_optionÚfloatr<   Útest_group_sequence)ÚoptZtgsr   r   r   r[   ?  s4    
ÿ
ÿ

þ
ÿ
ÿ
ÿÿ
ÿr[   Fc                 C   s    |s| j jdur t| j jƒ| j_t d| j j› d| jj› �¡ |sN| j jdurZ| j j| j_|sj| j j	durœ| j j	du s‚| j j	dkr�t
d | j_n| j j	| j_dS )z?
    Set ctx.env from options if they are given or forced.
    Nzwut: tests:z TESTS:r¼   éÿÿÿÿ)r[   r¿   Úboolr5   rg   r   r^   Útest_durationrf   Ú
test_grouprÃ   Ú
TEST_GROUP)ÚctxÚforcer   r   r   Úintern_test_optionsY  s    rÌ   c                 C   s   t | dƒ d S )NT)rÌ   )Úcfgr   r   r   Ú	configurel  s    rÎ   )Úrequest)Úurlopenc                 C   s   t | dƒ |  t¡ d S )NF)rÌ   Úadd_post_funr¬   )r   r   r   r   Úbuildw  s    
rÒ   )F)*rŸ   r   ry   r†   Zwaflib.TaskGenr   r   r   Úwaflibr   r   r   r   Zwaflib.Toolsr	   Úwaflib.Buildr6   ÚBuildr
   ÚSAVED_ATTRSrV   Ú	threadingÚLockr”   r…   r   rE   r]   rb   Údeep_inputsr    r¬   r±   rÃ   r[   rÌ   rÎ   ÚurllibrÏ   ÚImportErrorrÐ   rÒ   r   r   r   r   Ú<module>   s@   '




,
^
