o
    û›h½6  ã                   @   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rjej!nej"Z#e#de$de%e$ de%e$ fdd„ƒZ&dd„ Z'de'_(dd„ Z)dd„ Z*d:dd„Z+d;d d!„Z,	"	d<d#d$„Z-G d%d&„ d&ej.ƒZ/d'Z0d(d)„ Z1eZ2e3e 4d"¡ƒZ5d*Z6G d+d,„ d,e7ƒZ8d-Z9G d.d/„ d/e8ƒZ:e	d0d1„ ƒZ;e	d2d3„ ƒZ<d4d5„ Z=d=d6d7„Z>d=d8d9„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Úwin32Ú	startPathÚfilesÚreturnc                    s0   t |tƒsJ ‚tj | ¡d ‰ ‡ fdd„|D ƒS )aÐ  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 : 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']

    r   c                    s   g | ]	}t j ˆ |¡‘qS © )ÚosÚpathÚjoin)Ú.0Úf©Úbaser   úKc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/testing/tools.pyÚ
<listcomp>C   s    zfull_path.<locals>.<listcomp>)Ú
isinstanceÚlistr   r   Úsplit)r   r   r   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¡}|rJt| 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_outputF   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_argvt   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   r6   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   
r<   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ƒsFt|
|ƒ q8t|ttt|	d�}|jt d |¡¡p[dd	�\}}t |¡t |¡}}|rtt 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__r<   r   ÚenvironÚcopyÚpopÚitemsr   ÚstrÚprintr   r   Úcommunicater   ÚencodeÚdecoder$   Úsub)ÚfnameÚoptionsÚcommandsÚ__tracebackhide__ZcmdargsZtest_dirr;   Z
full_fnameZfull_cmdrA   ÚkÚvÚpÚoutÚerrr   r   r   Úipexecœ   s*   



€ rZ   rD   c                 C   s‚   d}t | ||ƒ\}}|r+|r#d | ¡  ¡ ¡d | ¡  ¡ ¡ks"J ‚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
    TrB   z"Running file %r produced error: %rN)rZ   r   ÚstripÚ
splitlinesÚ
ValueError)rQ   Zexpected_outZexpected_errrR   rS   rT   rX   rY   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   Úhasattrra   ÚappendrQ   )ÚselfÚsrcÚextrQ   r   r   r   Úmktmp
  s
   


zTempFileMixin.mktmpc                 C   s6   t | dƒr| jD ]}zt |¡ W q   Y qd S d S )Nra   )rb   ra   r   Úunlink)rd   rQ   r   r   r   ÚtearDown  s   

÷zTempFileMixin.tearDownc                 C   s   | S ©Nr   ©rd   r   r   r   Ú	__enter__   s   zTempFileMixin.__enter__c                 C   s   |   ¡  d S rj   )ri   )rd   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   Ú__exit__#  s   zTempFileMixin.__exit__N)r`   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rg   ri   rl   rp   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_namerq   z	<unknown>N)ÚgetattrÚpair_fail_msgÚformat)ÚfuncÚpairsrT   r3   ÚinpÚexpectedrX   r   r   r   Úcheck_pairs.  s   þr}   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 rj   )Úsr   rK   Ú_re_typeÚchannelÚsuppress)rd   r   r�   r‚   r   r   r   Ú__init__\  s
   

zAssertPrints.__init__c                 C   sN   t t| jƒ| _tƒ | _t| j| jd�| _tt| j| j	r!| jƒ d S | jƒ d S )N)r�   )
rv   r8   r�   Úorig_streamÚ
MyStringIOÚbufferr   ÚteeÚsetattrr‚   rk   r   r   r   rl   c  s   &zAssertPrints.__enter__c                 C   s²   d}zP|d urW | j  ¡  dS | j  ¡  tt| j| jƒ | j ¡ }| j	D ]&}t
|tƒr<| |¡s;J t |j| j|¡ƒ‚q$||v sJJ t || j|¡ƒ‚q$W | j  ¡  dS | j  ¡  w ©NTF)r‡   r4   Úflushrˆ   r8   r�   r„   r†   Úgetvaluer   r   r€   r%   Únotprinted_msgrx   Úpattern©rd   ÚetypeÚvaluero   rT   Zprintedr   r   r   r   rp   i  s   
ö


"zAssertPrints.__exit__N)r>   T)rq   rr   rs   rt   rƒ   rl   rp   r   r   r   r   r~   P  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}zU|d ur| j  ¡  W | j  ¡  dS | j  ¡  tt| j| jƒ | j ¡ }| j	D ]&}t
|tƒrA| |¡r@J t |j| j|¡ƒ‚q)||vsOJ t || j|¡ƒ‚q)W | j  ¡  dS | j  ¡  w r‰   )r‡   r4   rŠ   rˆ   r8   r�   r„   r†   r‹   r   r   r€   r%   Úprinted_msgrx   r�   rŽ   r   r   r   rp   †  s&   

ô



ÿÿzAssertNotPrints.__exit__N)rq   rr   rs   rt   rp   r   r   r   r   r‘   ‚  s    r‘   c                  c   s:   � ddl m}  | j}dd„ | _z	d V  W || _d S || _w )Nr   )Úwarnc                  _   s   d S rj   r   )ÚaÚkwr   r   r   Ú<lambda>   s    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 | ¡ dS t | ¡ w )zGCreate an empty, named, temporary file for the duration of the context.Úwzutf-8)ÚencodingN)Úopenr4   r   rh   )r3   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.
    rD   c              
      s.   zt ˆ ƒW S  ty } ztdƒ|‚d }~ww )NzNo more inputs given)ÚnextÚStopIterationÚEOFError)ÚpromptÚe©Úitr   r   Ú
mock_input»  s   

€ÿzfake_input.<locals>.mock_inputzbuiltins.inputN©rD   )Úiterr   )Zinputsr¤   r   r¢   r   Ú
fake_input¯  s   
r§   c                 C   óX   t ƒ | dg }t|ƒ\}}}|dksJ |ƒ‚d|vsJ ‚d|v s"J ‚d|v s(J ‚||fS )z)test that `ipython [subcommand] -h` worksz-hr   Ú	TracebackÚOptionsú
--help-all©r<   r	   ©Ú
subcommandÚcmdrX   rY   Úrcr   r   r   Úhelp_output_testÃ  ó   r±   c                 C   r¨   )z1test that `ipython [subcommand] --help-all` worksr«   r   r©   rª   ÚClassr¬   r­   r   r   r   Úhelp_all_output_testÎ  r²   r´   r,   )Nr   )rD   Nr   r¥   )@rt   r   Úpathlibr   r$   r8   r1   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   rD   r   Údecr   ÚplatformZskip_doctestZ	null_decoZdoctest_decorK   r    r"   r*   Z__test__r+   r6   r<   rZ   r^   ZTestCaser_   rw   r}   r…   ÚtypeÚcompiler€   rŒ   Úobjectr~   r’   r‘   r˜   rœ   r§   r±   r´   r   r   r   r   Ú<module>   s\     +	

:
ÿ/",
	

