a
    ø£Be7  ã                   @   s²  d Z ddlZddlm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m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 ddlmZ ddlmZ ej dkrÔej!nej"Z#e#dd„ ƒZ$dd„ Z%de%_&dd„ Z'dd„ Z(d7dd„Z)d8dd„Z*d9d d!„Z+G d"d#„ d#ej,ƒZ-d$Z.d%d&„ Z/eZ0e1e 2d¡ƒZ3d'Z4G d(d)„ d)e5ƒZ6d*Z7G d+d,„ d,e6ƒZ8e	d-d.„ ƒZ9e	d/d0„ ƒZ:d1d2„ Z;d:d3d4„Z<d;d5d6„Z=dS )<zWGeneric testing tools.

Authors
-------
- Fernando Perez <Fernando.Perez@berkeley.edu>
é    N)ÚPath)Úcontextmanager)ÚStringIO)ÚPopenÚPIPE)Úpatch)ÚConfig)Úget_output_error_code)Úlist_strings)Útemp_pyfileÚTee)Ú	py3compaté   )Ú
decorators)ÚskipdoctestÚwin32c                    s*   t |ƒ}tj | ¡d ‰ ‡ fdd„|D ƒS )aP  Make full paths for all the listed files, based on startPath.

    Only the base part of startPath is kept, since this routine is typically
    used with a script's ``__file__`` variable as startPath. The base of startPath
    is then prepended to all the listed files, forming the output list.

    Parameters
    ----------
    startPath : string
      Initial path to use as the base for the results.  This path is split
      using os.path.split() and only its first component is kept.

    files : string or list
      One or more files.

    Examples
    --------

    >>> full_path('/foo/bar.py',['a.txt','b.txt'])
    ['/foo/a.txt', '/foo/b.txt']

    >>> full_path('/foo',['a.txt','b.txt'])
    ['/a.txt', '/b.txt']

    If a single file is given, the output is still a list::

        >>> full_path('/foo','a.txt')
        ['/a.txt']
    r   c                    s   g | ]}t j ˆ |¡‘qS © )ÚosÚpathÚjoin)Ú.0Úf©Úbaser   úX/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/IPython/testing/tools.pyÚ
<listcomp>H   ó    zfull_path.<locals>.<listcomp>)r
   r   r   Úsplit)Z	startPathÚfilesr   r   r   Ú	full_path&   s     r   c                 C   s˜   t  d| t j¡}|r.t| d¡ƒ}d}||fS t  d| t j¡}|r\d}t| d¡ƒ}||fS t  d| t j¡}|r”t| d¡ƒ}t| d¡ƒ}||fS dS )a  Parse the output of a test run and return errors, failures.

    Parameters
    ----------
    txt : str
      Text output of a test run, assumed to contain a line of one of the
      following forms::

        'FAILED (errors=1)'
        'FAILED (failures=1)'
        'FAILED (errors=1, failures=1)'

    Returns
    -------
    nerr, nfail
      number of errors and failures.
    z^FAILED \(errors=(\d+)\)r   r   z^FAILED \(failures=(\d+)\)z(^FAILED \(errors=(\d+), failures=(\d+)\)é   )r   r   )ÚreÚsearchÚ	MULTILINEÚintÚgroup)ÚtxtZerr_mZnerrZnfailZfail_mZboth_mr   r   r   Úparse_test_outputK   s$    ÿr'   Fc                   C   s   g d¢S )zEReturn a valid default argv for creating testing instances of ipython)z--quickz--colors=NoColorz--no-term-titlez--no-bannerz--autocall=0r   r   r   r   r   Údefault_argvy   s    r(   c                  C   sN   t ƒ } d| j_d| j_d| j_tjddd�}t|j	ƒ| j
_| ¡  d| j
_| S )z6Return a config object with good defaults for testing.ZNoColor)Fr   ztest_hist.sqliteF)ÚsuffixÚdeletei'  )r   ÚTerminalInteractiveShellÚcolorsZ TerminalTerminalInteractiveShellZ
term_titleZautocallÚtempfileÚNamedTemporaryFiler   ÚnameZHistoryManagerZ	hist_fileÚcloseZdb_cache_size)Úconfigr   r   r   r   Údefault_config‚   s    r2   c                 C   s   t jddg}| rd |¡}|S )aW  
    Return appropriate IPython command line name. By default, this will return
    a list that can be used with subprocess.Popen, for example, but passing
    `as_string=True` allows for returning the IPython command as a string.

    Parameters
    ----------
    as_string: bool
        Flag to allow to return the command as a string.
    z-mZIPythonú )ÚsysÚ
executabler   )Ú	as_stringÚipython_cmdr   r   r   Úget_ipython_cmd�   s    
r8   r   c                 C   sð   d}|du rg }t ƒ | }tj t¡}tƒ }tj || ¡}|| d|g }tj ¡ }	d|	d< |	 	dd¡ |	 
¡ D ]\}
}t|tƒspt|
|ƒ qpt|ttt|	d�}|jt d |¡¡p¶dd	�\}}t |¡t |¡ }}|rèt d
d|¡}||fS )a  Utility to call 'ipython filename'.

    Starts IPython with a minimal and safe configuration to make startup as fast
    as possible.

    Note that this starts IPython in a subprocess!

    Parameters
    ----------
    fname : str, Path
      Name of file to be executed (should have .py or .ipy extension).

    options : optional, list
      Extra command-line flags to be passed to IPython.

    commands : optional, list
      Commands to send in on stdin

    Returns
    -------
    ``(stdout, stderr)`` of ipython subprocess.
    TNz--ÚignoreZPYTHONWARNINGSZPYCHARM_HOSTED)ÚstdoutÚstderrÚstdinÚenvÚ
)Úinputz\x1b\[[^h]+hÚ )r(   r   r   ÚdirnameÚ__file__r8   r   ÚenvironÚcopyÚpopÚitemsÚ
isinstanceÚstrÚprintr   r   Úcommunicater   ÚencodeÚdecoder!   Úsub)ÚfnameÚoptionsÚcommandsÚ__tracebackhide__ZcmdargsZtest_dirr7   Z
full_fnameZfull_cmdr=   ÚkÚvÚpÚoutÚerrr   r   r   Úipexec¡   s(    


 rW   r@   c                 C   s‚   d}t | ||ƒ\}}|rV|rFd | ¡  ¡ ¡d | ¡  ¡ ¡ksVJ ‚ntd| |f ƒ‚d | ¡  ¡ ¡d | ¡  ¡ ¡ks~J ‚dS )a9  Utility to call 'ipython filename' and validate output/error.

    This function raises an AssertionError if the validation fails.

    Note that this starts IPython in a subprocess!

    Parameters
    ----------
    fname : str, Path
      Name of the file to be executed (should have .py or .ipy extension).

    expected_out : str
      Expected stdout of the process.

    expected_err : optional, str
      Expected stderr of the process.

    options : optional, list
      Extra command-line flags to be passed to IPython.

    Returns
    -------
    None
    Tr>   z"Running file %r produced error: %rN)rW   r   ÚstripÚ
splitlinesÚ
ValueError)rN   Zexpected_outZexpected_errrO   rP   rQ   rU   rV   r   r   r   Úipexec_validateÛ   s    
ÿÿ
ÿr[   c                   @   s2   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ ZdS )ÚTempFileMixinzcUtility class to create temporary Python/IPython files.

    Meant as a mixin class for test cases.ú.pyc                 C   s0   t ||ƒ}t| dƒsg | _| j |¡ || _dS )zMake a valid python temp file.ÚtmpsN)r   Úhasattrr^   ÚappendrN   )ÚselfÚsrcÚextrN   r   r   r   Úmktmp  s
    

zTempFileMixin.mktmpc                 C   s6   t | dƒr2| jD ] }zt |¡ W q   Y q0 qd S )Nr^   )r_   r^   r   Úunlink)ra   rN   r   r   r   ÚtearDown  s    

zTempFileMixin.tearDownc                 C   s   | S ©Nr   ©ra   r   r   r   Ú	__enter__%  s    zTempFileMixin.__enter__c                 C   s   |   ¡  d S rg   )rf   )ra   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   Ú__exit__(  s    zTempFileMixin.__exit__N)r]   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rd   rf   ri   rm   r   r   r   r   r\   
  s
   
r\   z8Testing {0}

In:
  {1!r}
Expected:
  {2!r}
Got:
  {3!r}
c                 C   sN   d}t | dt | ddƒƒ}|D ],\}}| |ƒ}||ksJ t ||||¡ƒ‚qdS )a—  Utility function for the common case of checking a function with a
    sequence of input/output pairs.

    Parameters
    ----------
    func : callable
      The function to be tested. Should accept a single argument.
    pairs : iterable
      A list of (input, expected_output) tuples.

    Returns
    -------
    None. Raises an AssertionError if any output does not match the expected
    value.
    TÚ	func_namern   z	<unknown>N)ÚgetattrÚpair_fail_msgÚformat)ÚfuncÚpairsrQ   r/   ÚinpÚexpectedrU   r   r   r   Úcheck_pairs3  s
    rz   zEDid not find {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                   @   s*   e Zd ZdZddd„Zdd„ Zdd	„ Zd
S )ÚAssertPrintszØContext manager for testing that code prints certain text.

    Examples
    --------
    >>> with AssertPrints("abc", suppress=False):
    ...     print("abcd")
    ...     print("def")
    ...
    abcd
    def
    r:   Tc                 C   s0   || _ t| j ttfƒr | j g| _ || _|| _d S rg   )ÚsrG   rH   Ú_re_typeÚchannelÚsuppress)ra   r|   r~   r   r   r   r   Ú__init__a  s
    
zAssertPrints.__init__c                 C   sH   t t| jƒ| _tƒ | _t| j| jd�| _tt| j| j	r<| jn| jƒ d S )N)r~   )
rs   r4   r~   Úorig_streamÚ
MyStringIOÚbufferr   ÚteeÚsetattrr   rh   r   r   r   ri   h  s    zAssertPrints.__enter__c                 C   s¶   d}z |d urW | j  ¡  dS | j  ¡  tt| j| jƒ | j ¡ }| j	D ]L}t
|tƒrx| |¡s”J t |j| j|¡ƒ‚qH||v sHJ t || j|¡ƒ‚qHW | j  ¡  dS | j  ¡  0 d S ©NTF)r„   r0   Úflushr…   r4   r~   r�   rƒ   Úgetvaluer|   rG   r}   r"   Únotprinted_msgru   Úpattern©ra   ÚetypeÚvaluerl   rQ   Zprintedr|   r   r   r   rm   n  s"    
õ



"
þzAssertPrints.__exit__N)r:   T)rn   ro   rp   rq   r€   ri   rm   r   r   r   r   r{   U  s   
r{   z>Found {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                   @   s   e Zd ZdZdd„ ZdS )ÚAssertNotPrintszcContext manager for checking that certain output *isn't* produced.

    Counterpart of AssertPrintsc                 C   sÀ   d}zª|d ur(| j  ¡  W | j  ¡  dS | j  ¡  tt| j| jƒ | j ¡ }| j	D ]L}t
|tƒr‚| |¡ržJ t |j| j|¡ƒ‚qR||vsRJ t || j|¡ƒ‚qRW | j  ¡  dS | j  ¡  0 d S r†   )r„   r0   r‡   r…   r4   r~   r�   rƒ   rˆ   r|   rG   r}   r"   Úprinted_msgru   rŠ   r‹   r   r   r   rm   ‹  s,    

ó




ÿÿ
þzAssertNotPrints.__exit__N)rn   ro   rp   rq   rm   r   r   r   r   rŽ   ‡  s   rŽ   c                  c   s:   ddl m}  | j}dd„ | _zd V  W || _n|| _0 d S )Nr   )Úwarnc                  _   s   d S rg   r   )ÚaÚkwr   r   r   Ú<lambda>¥  r   zmute_warn.<locals>.<lambda>)ÚIPython.utilsr�   )r�   Z	save_warnr   r   r   Ú	mute_warn¡  s    
r•   c              	   c   s8   t | ddd� ¡  zdV  W t | ¡ nt | ¡ 0 dS )zGCreate an empty, named, temporary file for the duration of the context.Úwzutf-8)ÚencodingN)Úopenr0   r   re   )r/   r   r   r   Úmake_tempfile«  s    r™   c                    s    t | ƒ‰ d‡ fdd„	}td|ƒS )a  Temporarily replace the input() function to return the given values

    Use as a context manager:

    with fake_input(['result1', 'result2']):
        ...

    Values are returned in order. If input() is called again after the last value
    was used, EOFError is raised.
    r@   c              
      s>   z
t ˆ ƒW S  ty8 } ztdƒ|‚W Y d }~n
d }~0 0 d S )NzNo more inputs given)ÚnextÚStopIterationÚEOFError)ÚpromptÚe©Úitr   r   Ú
mock_inputÀ  s    
zfake_input.<locals>.mock_inputzbuiltins.input)r@   )Úiterr   )Úinputsr¡   r   rŸ   r   Ú
fake_input´  s    r¤   c                 C   sX   t ƒ | dg }t|ƒ\}}}|dks,J |ƒ‚d|vs8J ‚d|v sDJ ‚d|v sPJ ‚||fS )z)test that `ipython [subcommand] -h` worksz-hr   Ú	TracebackÚOptionsú
--help-all©r8   r	   ©Ú
subcommandÚcmdrU   rV   Úrcr   r   r   Úhelp_output_testÈ  s    r­   c                 C   sX   t ƒ | dg }t|ƒ\}}}|dks,J |ƒ‚d|vs8J ‚d|v sDJ ‚d|v sPJ ‚||fS )z1test that `ipython [subcommand] --help-all` worksr§   r   r¥   r¦   ÚClassr¨   r©   r   r   r   Úhelp_all_output_testÓ  s    r¯   )F)Nr   )r@   Nr   )r@   )r@   )>rq   r   Úpathlibr   r!   r4   r-   ZunittestÚ
contextlibr   Úior   Ú
subprocessr   r   Zunittest.mockr   Ztraitlets.config.loaderr   ZIPython.utils.processr	   ZIPython.utils.textr
   ZIPython.utils.ior   r   r”   r   r@   r   Údecr   ÚplatformZskip_doctestZ	null_decoZdoctest_decor   r'   Z__test__r(   r2   r8   rW   r[   ZTestCaser\   rt   rz   r‚   ÚtypeÚcompiler}   r‰   Úobjectr{   r�   rŽ   r•   r™   r¤   r­   r¯   r   r   r   r   Ú<module>   sZ   
$+	

:  ÿ
/",
	

