
    j3                     .   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 ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ej'        dk    rej(        nej)        Z*e*de+de,e+         de,e+         fd            Z-de+de%e.e.f         fdZ/de/_0        de#e+         fdZ1defdZ2d4de3de#e+         fdZ4d5de+d e$e#e+                  d!e%e+d"f         de%e+e+f         fd#Z5	 	 d6de+d%e+d&e+d e$e#e+                  d!e%e+d"f         f
d'Z6 G d( d)ej7                  Z8eZ9 e: ej;        d$                    Z<d*Z= G d+ d,          Z>d-Z? G d. d/e>          Z@e	d0             ZAd1 ZBd7d2ZCd7d3ZDdS )8zWGeneric 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)TracebackType)ListOptionalTupleTypewin32	startPathfilesreturnc                     t          |t                    sJ t          j                            |           d         f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                 P    g | ]"}t           j                            |          #S  )ospathjoin).0fbases     \/home/ubuntu/.hermes/hermes-agent/venv/lib/python3.11/site-packages/IPython/testing/tools.py
<listcomp>zfull_path.<locals>.<listcomp>E   s)    222aRW\\$q!!222    )
isinstancelistr   r   split)r   r   r#   s     @r$   	full_pathr*   (   sM    6 eT"""""7==##A&D222252222r&   txtc                    t          j        d| t           j                  }|r(t          |                    d                    }d}||fS t          j        d| t           j                  }|r(d}t          |                    d                    }||fS t          j        d| t           j                  }|rHt          |                    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)r+   err_mnerrnfailfail_mboth_ms         r$   parse_test_outputr8   H   s    & I13EEE 5;;q>>""eY4c2<HHF FLLOO$$eYBC|% %F 6<<??##FLLOO$$e 4r&   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=0r   r   r&   r$   default_argvr:   v   s       r&   c                     t                      } d| j        _        d| j        _        d| j        _        t          j        dd          }t          |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_configrM      sr    XXF-6F#*9AF+6/0F#,#+=eLLLA&*16llF#GGIII*/F'Mr&   	as_stringc                 R    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-mIPython )sys
executabler    )rN   ipython_cmds     r$   get_ipython_cmdrU      s1     >43K ,hh{++r&   r   fnameoptionscommands.c                 &   d}|g }t                      |z   }t          j                            t                    }t                      }t          j                            ||           }||z   d|gz   }t          j                                        }	d|	d<   |		                    dd           |	
                                D ]*\  }
}t          |t                    st          |
|           +t          |t          t          t          |	          }|                    t#          j        d                    |                    p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__rU   r    environcopypopitemsr'   strprintr   r   communicater   encodedecoder.   sub)rV   rW   rX   __tracebackhide__cmdargstest_dirrT   
full_fnamefull_cmdr`   kvpouterrs                  r$   ipexecrz      sk   . nnw&Gwx((H!##Kh..JW$j'99H
*//

C %C GGd###		  1 !S!! 	!QKKKhtD#FFFA}}9#3DIIh4G4G#H#H#PD}QQHC$$i&6s&;&;C  /f_b#..8Or&   rc   expected_outexpected_errc                 >   d}t          | ||          \  }}|r|rwd                    |                                                                          d                    |                                                                          k    sJ nt	          d| d|          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
    Tra   zRunning file z produced error: N)rz   r    strip
splitlines
ValueError)rV   r{   r|   rW   rX   rp   rx   ry   s           r$   ipexec_validater      s,   4 eWh//HC
  + 	+99SYY[[335566$))""$$//11; ;      *#eeSS* + + + 99SYY[[++--..$))''))3 3      r&   c                   6    e Zd ZdZd
dedefdZd Zd Zd Zd	S )TempFileMixinzcUtility class to create temporary Python/IPython files.

    Meant as a mixin class for test cases..pysrcextc                     t          ||          }t          | d          sg | _        | j                            |           || _        dS )zMake a valid python temp file.tmpsN)r   hasattrr   appendrV   )selfr   r   rV   s       r$   mktmpzTempFileMixin.mktmp  sK    C%%tV$$ 	DI	


r&   c                 v    t          | d          r&| j        D ] }	 t          j        |           #  Y xY wd S d S )Nr   )r   r   r   unlink)r   rV   s     r$   tearDownzTempFileMixin.tearDown  sc     4   		  Ie$$$$ D		 		 s   04c                     | S Nr   r   s    r$   	__enter__zTempFileMixin.__enter__&  s    r&   c                 .    |                                   d S r   )r   )r   exc_type	exc_value	tracebacks       r$   __exit__zTempFileMixin.__exit__)  s    r&   N)r   )	__name__
__module____qualname____doc__rj   r   r   r   r   r   r&   r$   r   r     sr        . .  3            r&   r   zEDid not find {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                   r    e Zd ZdZddededefdZd Zd	ee	e
                  d
ee
         dee         fdZdS )AssertPrintszContext manager for testing that code prints certain text.

    Examples
    --------
    >>> with AssertPrints("abc", suppress=False):
    ...     print("abcd")
    ...     print("def")
    ...
    abcd
    def
    r]   Tschannelsuppressc                     || _         t          | j         t          t          f          r| j         g| _         || _        || _        d S r   )r   r'   rj   _re_typer   r   )r   r   r   r   s       r$   __init__zAssertPrints.__init__C  s>    dfsHo.. 	fXDF r&   c                    t          t          | j                  | _        t	                      | _        t          | j        | j                  | _        t          t          | j        | j	        r| j        n| j                   d S )N)r   )
getattrrR   r   orig_stream
MyStringIObufferr   teesetattrr   r   s    r$   r   zAssertPrints.__enter__J  sb    "355 llt{DL999T\$-#M4;;TXNNNNNr&   etypevaluer   c                 |   d}	 |	 | j                                          dS | j                                          t          t          | j        | j                   | j                                        }| j	        D ]}t          |t                    rD|                    |          s.J t                              |j        | j        |                      [||v s)J t                              || j        |                      	 | j                                          dS # | j                                          w xY wNTF)r   rJ   flushr   rR   r   r   r   getvaluer   r'   r   r/   notprinted_msgformatpatternr   r   r   r   rp   printedr   s          r$   r   zAssertPrints.__exit__P  s+    	  HNN HNNCt'7888k**,,GV Y Ya** Y88G,,een.C.CAIt|]d.e.eee,e<<<)>)>q$,PW)X)X<<<<HNNDHNNs   D  C"D   D;N)r]   T)r   r   r   r   rj   boolr   r   r   r   BaseExceptionr   r   r   r&   r$   r   r   7  s        
 
! !# ! ! ! ! ! !O O OhtM':; H]D[ hpq~h      r&   r   z>Found {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                       e Zd ZdZd ZdS )AssertNotPrintszcContext manager for checking that certain output *isn't* produced.

    Counterpart of AssertPrintsc                    d}	 |5| j                                          	 | j                                          dS | j                                          t          t          | j        | j                   | j                                        }| j	        D ]}t          |t                    rD|                    |          r.J t                              |j        | j        |                      [||vs)J t                              || j        |                      	 | j                                          dS # | j                                          w xY wr   )r   rJ   r   r   rR   r   r   r   r   r   r'   r   r/   printed_msgr   r   r   s          r$   r   zAssertNotPrints.__exit__m  sU    	     HNN HNNCt'7888k**,,GV 2 2a** 2 xx00 : :1C1C	4<2: 2: : :0 : G+++[-?-?4<.2 .2++++HNNDHNNs   D9 C"D9 9EN)r   r   r   r   r   r   r&   r$   r   r   i  s-        # #    r&   r   c              #      K   t          | dd                                           	 dV  t          j        |            dS # t          j        |            w xY w)zGCreate an empty, named, temporary file for the duration of the context.wzutf-8)encodingN)openrJ   r   r   )rG   s    r$   make_tempfiler     sZ       	sW%%%++---
	$	$s   A Ac                 N    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.
    rc   c                 h    	 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  sC    	:88O 	: 	: 	:1229	:s    
1,1zbuiltins.inputrc   )iterr   )inputsr   r   s     @r$   
fake_inputr     sA     
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rU   r
   
subcommandcmdrx   ry   rcs        r$   help_output_testr     sy    


z40
0C(--LCb777C777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     su    


z<8
8C(--LCb777C777c!!!!c>>>>8Or&   r=   )Nr   )rc   Nr   r   )Er   r   pathlibr   r.   rR   rE   unittest
contextlibr   ior   
subprocessr   r   unittest.mockr   traitlets.config.loaderr	   IPython.utils.processr
   IPython.utils.textr   IPython.utils.ior   r   IPython.utilsr   rc   r   decr   typesr   typingr   r   r   r   platformskip_doctest	null_decodoctest_decorj   r(   r*   r1   r8   __test__r:   rM   r   rU   rz   r   TestCaser   r   typecompiler   r   r   r   r   r   r   r   r   r   r&   r$   <module>r      s    
			       				 



   % % % % % %       " " " " " " " "       * * * * * * 7 7 7 7 7 7 + + + + + + - - - - - - - - # # # # # #                   . . . . . . . . . . . .
 ,/<7+B+B{''3 3T#Y 349 3 3 3 3>'3 '5c? ' ' ' 'V #  
d3i 
 
 
 

 
 
 
 
 t d3i    $7 7# 7c 3 7E#s(O 7[`adfiai[j 7 7 7 7t FHQS, ,3 ,c , ,%d3i0,AFsCx, , , ,^    H%   D 
4

3  * * * * * * * *X    l   4   / / /(        r&   