
    f7                     4   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jB                  nejD                  Z#e#d        Z$d Z%de%_&        d Z'd Z(d)dZ)d*dZ*	 	 d+dZ+ G d dejX                        Z-dZ.d Z/eZ0 e1 ejd                  d            Z3dZ4 G d d e5      Z6d!Z7 G d" d#e6      Z8e	d$        Z9e	d%        Z:d& Z;d,d'Z<d,d(Z=y)-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                     t        |      }t        j                  j                  |       d   }|D cg c]"  }t        j                  j	                  ||      $ c}S c c}w )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   )r   ospathsplitjoin)	startPathfilesbasefs       P/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/testing/tools.py	full_pathr   &   sI    @ E77==#A&D+02aRWW\\$q!222s   'Ac                    t        j                  d| t         j                        }|r t        |j	                  d            }d}||fS t        j                  d| t         j                        }|r d}t        |j	                  d            }||fS t        j                  d| t         j                        }|r8t        |j	                  d            }t        |j	                  d            }||fS y)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)txterr_mnerrnfailfail_mboth_ms         r   parse_test_outputr+   K   s    & II13EE5;;q>"eYY4c2<<HFFLLO$eYYBC||%F6<<?#FLLO$e     Fc                  
    g dS )zEReturn a valid default argv for creating testing instances of ipython)z--quickz--colors=NoColorz--no-term-titlez--no-bannerz--autocall=0 r.   r,   r   default_argvr/   y   s     r,   c                  8   t               } d| j                  _        d| j                  _        d| j                  _        t        j                  dd      }t        |j                        | j                  _        |j                          d| j                  _        | S )z6Return a config object with good defaults for testing.NoColorFr   ztest_hist.sqliteF)suffixdeletei'  )r	   TerminalInteractiveShellcolors TerminalTerminalInteractiveShell
term_titleautocalltempfileNamedTemporaryFiler   nameHistoryManager	hist_fileclosedb_cache_size)configr   s     r   default_configrB      sx    XF-6F##*9?F++6/0F##,##+>uMA&*166lF#GGI*/F'Mr,   c                 R    t         j                  ddg}| rdj                  |      }|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-mIPython )sys
executabler   )	as_stringipython_cmds     r   get_ipython_cmdrJ      s+     >>43Khh{+r,   c                    d}|g }t               |z   }t        j                  j                  t              }t               }t        j                  j                  ||       }||z   d|gz   }t        j                  j                         }	d|	d<   |	j                  dd       |	j                         D ]"  \  }
}t        |t              rt        |
|       $ t        |t        t        t        |	      }|j!                  t#        j$                  dj                  |            xs d	      \  }}t#        j&                  |      t#        j&                  |      }}|rt)        j*                  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--ignorePYTHONWARNINGSPYCHARM_HOSTED)stdoutstderrstdinenv
)inputz\x1b\[[^h]+h )r/   r   r   dirname__file__rJ   r   environcopypopitems
isinstancestrprintr   r   communicater   encodedecoder    sub)fnameoptionscommands__tracebackhide__cmdargstest_dirrI   
full_fnamefull_cmdrR   kvpouterrs                  r   ipexecrp      s>   . nw&Gwwx(H!#Kh.JW$j'99H
**//
C %C GGd#		 1 !S!!QK	
 	htD#FA}}9#3#3DIIh4G#H#PD}QHC$i&6&6s&;C ff_b#.8Or,   rU   c                    d}t        | ||      \  }}|rp|r]dj                  |j                         j                               dj                  |j                         j                               k(  sJ t	        d| d|      dj                  |j                         j                               dj                  |j                         j                               k(  sJ y)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
    TrS   zRunning file z produced error: N)rp   r   strip
splitlines
ValueError)rc   expected_outexpected_errrd   re   rf   rn   ro   s           r   ipexec_validaterw      s    4 eWh/HC
 99SYY[3356$))""$//1;    #S* + + 99SYY[++-.$))'')3   r,   c                   *    e Zd ZdZddZd Zd Zd Zy)TempFileMixinzcUtility class to create temporary Python/IPython files.

    Meant as a mixin class for test cases.c                     t        ||      }t        | d      sg | _        | j                  j                  |       || _        y)zMake a valid python temp file.tmpsN)r   hasattrr{   appendrc   )selfsrcextrc   s       r   mktmpzTempFileMixin.mktmp  s8    C%tV$DI		
r,   c                 z    t        | d      r(| j                  D ]  }	 t        j                  |        y y #  Y !xY w)Nr{   )r|   r{   r   unlink)r~   rc   s     r   tearDownzTempFileMixin.tearDown  sC     4  IIe$	 ! s   6:c                     | S Nr.   r~   s    r   	__enter__zTempFileMixin.__enter__%  s    r,   c                 $    | j                          y r   )r   )r~   exc_type	exc_value	tracebacks       r   __exit__zTempFileMixin.__exit__(  s    r,   N)z.py)__name__
__module____qualname____doc__r   r   r   r   r.   r,   r   ry   ry   
  s    .r,   ry   z8Testing {0}

In:
  {1!r}
Expected:
  {2!r}
Got:
  {3!r}
c           	          d}t        | dt        | dd            }|D ]/  \  }} | |      }||k(  rJ t        j                  ||||              y)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_namer   z	<unknown>N)getattrpair_fail_msgformat)funcpairsrf   r<   inpexpectedrn   s          r   check_pairsr   3  sa      4gdJ&LMD OX3ihN 4 4T3# NNOr,   zEDid not find {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                   $    e Zd ZdZddZd Zd Zy)AssertPrintszContext manager for testing that code prints certain text.

    Examples
    --------
    >>> with AssertPrints("abc", suppress=False):
    ...     print("abcd")
    ...     print("def")
    ...
    abcd
    def
    c                     || _         t        | j                   t        t        f      r| j                   g| _         || _        || _        y r   )sr\   r]   _re_typechannelsuppress)r~   r   r   r   s       r   __init__zAssertPrints.__init__a  s6    dffsHo.ffXDF r,   c                 0   t        t        | j                        | _        t	               | _        t        | j
                  | j                        | _        t        t        | j                  | j                  r| j
                         y | j                         y )N)r   )
r   rF   r   orig_stream
MyStringIObufferr   teesetattrr   r   s    r   r   zAssertPrints.__enter__h  sW    "35 lt{{DLL9T\\$--4;;NTXXNr,   c                    d}	 |	 | j                   j                          y| j                   j                          t        t        | j
                  | j                         | j                  j                         }| j                  D ]~  }t        |t              rB|j                  |      r%J t        j                  |j                  | j
                  |             ||v rZJ t        j                  || j
                  |              	 | j                   j                          y# | j                   j                          w xY wNTF)r   r?   flushr   rF   r   r   r   getvaluer   r\   r   r!   notprinted_msgr   patternr~   etypevaluer   rf   printedr   s          r   r   zAssertPrints.__exit__n  s     	  HHNN HHNNCt'7'78kk**,GVV Ya*88G,en.C.CAIIt||]d.ee,<X)>)>q$,,PW)XX<	Y
 HHNNDHHNNs   D$ B	D$ ,4D$ !'D$ $E N)rO   T)r   r   r   r   r   r   r   r.   r,   r   r   r   U  s    
!Or,   r   z>Found {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                       e Zd ZdZd Zy)AssertNotPrintszcContext manager for checking that certain output *isn't* produced.

    Counterpart of AssertPrintsc                    d}	 |6| j                   j                          	 | j                   j                          y| j                   j                          t        t        | j
                  | j                         | j                  j                         }| j                  D ]~  }t        |t              rB|j                  |      s%J t        j                  |j                  | j
                  |             ||vrZJ t        j                  || j
                  |              	 | j                   j                          y# | j                   j                          w xY wr   )r   r?   r   r   rF   r   r   r   r   r   r\   r   r!   printed_msgr   r   r   s          r   r   zAssertNotPrints.__exit__  s    	   HHNN HHNNCt'7'78kk**,GVV 2a* xx0 :1C1C		4<<2: :0 G+ 2[-?-?4<<.2 2+2 HHNNDHHNNs   D> B	D> 4D> ;'D> >EN)r   r   r   r   r   r.   r,   r   r   r     s    #r,   r   c               #   p   K   ddl m}  | j                  }d | _        	 d  || _        y # || _        w xY ww)Nr   )warnc                       y r   r.   )akws     r   <lambda>zmute_warn.<locals>.<lambda>  s    r,   )IPython.utilsr   )r   	save_warns     r   	mute_warnr     s/     "		I%DI	I	s   6* 6	36c              #      K   t        | dd      j                          	 d t        j                  |        y# t        j                  |        w xY ww)zGCreate an empty, named, temporary file for the duration of the context.wzutf-8)encodingN)openr?   r   r   )r<   s    r   make_tempfiler     s;      	sW%++-
		$		$s   A: AAAc                 >    t        |       df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.
    c                 V    	 t              S # t        $ r}t        d      |d }~ww xY w)NzNo more inputs given)nextStopIterationEOFError)prompteits     r   
mock_inputzfake_input.<locals>.mock_input  s/    	:8O 	:129	:s   
 	(#(zbuiltins.inputrU   )iterr   )inputsr   r   s     @r   
fake_inputr     s#     
fB: !:..r,   c                     t               | dgz   }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rJ   r
   
subcommandcmdrn   ro   rcs        r   help_output_testr     sh    

z40
0C(-LCb7C7c!!!38Or,   c                     t               | dgz   }t        |      \  }}}|dk(  sJ |       d|vsJ d|v sJ d|v sJ ||fS )z1test that `ipython [subcommand] --help-all` worksr   r   r   r   Classr   r   s        r   help_all_output_testr     sf    

z<8
8C(-LCb7C7c!!!c>>8Or,   r2   )Nr.   )rU   Nr.   r   )>r   r   pathlibr   r    rF   r:   unittest
contextlibr   ior   
subprocessr   r   unittest.mockr   traitlets.config.loaderr	   IPython.utils.processr
   IPython.utils.textr   IPython.utils.ior   r   r   r   rU   r   decr   platformskip_doctest	null_decodoctest_decor   r+   __test__r/   rB   rJ   rp   rw   TestCasery   r   r   r   typecompiler   r   objectr   r   r   r   r   r   r   r   r.   r,   r   <module>r      s=   
  	 
   %  "  * 7 + - #  
 ,/<<7+B{''!3 !3H'V #  
$7t 79+-,^H%% DO0 



3 *6 *Xl 4    /(r,   