
    ^h7                     @   S r SSKrSSKJr  SSKrSSKrSSKrSSKrSSKJ	r	  SSK
Jr  SSKJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJr  SSKJr  SSKJr  \R@                  S:X  a  \RB                  O\RD                  r#\#S 5       r$S r%S\%l&        S r'S r(S)S jr)S*S jr*  S+S jr+ " S S\RX                  5      r-Sr.S r/\r0\1" \Rd                  " S5      5      r3Sr4 " S S \55      r6S!r7 " S" S#\65      r8\	S$ 5       r9\	S% 5       r:S& r;S,S' jr<S,S( jr=g)-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                     [        U5      n[        R                  R                  U 5      S   nU Vs/ s H"  n[        R                  R	                  X#5      PM$     sn$ s  snf )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 : 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       O/home/james-whalen/.local/lib/python3.13/site-packages/IPython/testing/tools.py	full_pathr   &   sK    @ E77==#A&D+025aRWW\\$!5222s   )Ac                    [         R                  " SU [         R                  5      nU(       a  [        UR	                  S5      5      nSnX#4$ [         R                  " SU [         R                  5      nU(       a  Sn[        UR	                  S5      5      nX#4$ [         R                  " SU [         R                  5      nU(       a7  [        UR	                  S5      5      n[        UR	                  S5      5      nX#4$ g)aK  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>"YY4c2<<HFFLLO$YYBC||%F6<<?#FLLO$     Fc                  
    / SQ$ )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                  4   [        5       n SU R                  l        SU R                  l        SU R                  l        [        R                  " SSS9n[        UR                  5      U R                  l        UR                  5         SU R                  l        U $ )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                  SS/nU (       a  SR                  U5      nU$ )a7  
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                    SnUc  / n[        5       U-   n[        R                  R                  [        5      n[        5       n[        R                  R                  XP5      nXd-   SU/-   n[        R                  R                  5       n	SU	S'   U	R                  SS5        U	R                  5        H'  u  p[        U[        5      (       a  M  [        X5        M)     [        U[        [        [        U	S9nUR!                  ["        R$                  " SR                  U5      5      =(       d    SS	9u  p["        R&                  " U5      ["        R&                  " U5      pU(       a  [(        R*                  " S
SU5      nX4$ )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$j'99H
**//
C %C GGd#		 !S!!!K	 
 	htD#FA}}9#3#3DIIh4G#H#PD}QHC$i&6&6s&; ff_b#.8Or,   rU   c                    Sn[        XU5      u  pgU(       ay  U(       a_  SR                  UR                  5       R                  5       5      SR                  UR                  5       R                  5       5      :X  d   eO[	        SU < SU< 35      eSR                  UR                  5       R                  5       5      SR                  UR                  5       R                  5       5      :X  d   eg)a  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 eh/HC
 99SYY[3356$))""$//1;    #S* + + 99SYY[++-.$))'')3   r,   c                   4    \ rS rSrSrS	S jrS rS rS rSr	g)
TempFileMixini
  z_Utility class to create temporary Python/IPython files.

Meant as a mixin class for test cases.c                     [        X5      n[        U S5      (       d  / U l        U R                  R                  U5        X0l        g)zMake a valid python temp file.tmpsN)r   hasattrr{   appendrc   )selfsrcextrc   s       r   mktmpTempFileMixin.mktmp  s7    C%tV$$DI		
r,   c                     [        U S5      (       a+  U R                   H  n [        R                  " U5        M     g g !    M%  = f)Nr{   )r|   r{   r   unlink)r~   rc   s     r   tearDownTempFileMixin.tearDown  sA     4  IIe$	 # ! s	   >Ac                     U $ Nr.   r~   s    r   	__enter__TempFileMixin.__enter__%  s    r,   c                 $    U R                  5         g r   )r   )r~   exc_type	exc_value	tracebacks       r   __exit__TempFileMixin.__exit__(  s    r,   )rc   r{   N)z.py)
__name__
__module____qualname____firstlineno____doc__r   r   r   r   __static_attributes__r.   r,   r   ry   ry   
  s    .r,   ry   z8Testing {0}

In:
  {1!r}
Expected:
  {2!r}
Got:
  {3!r}
c           	          Sn[        U S[        U SS5      5      nU H-  u  pEU " U5      nXe:X  a  M   [        R                  X4XV5      5       e   g)ag  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  sR      4gdJ&LMD3iN 4 4T NN r,   zEDid not find {0!r} in printed output (on {1}):
-------
{2!s}
-------
c                   .    \ rS rSrSrSS jrS rS rSrg)	AssertPrintsiU  zContext manager for testing that code prints certain text.

Examples
--------
>>> with AssertPrints("abc", suppress=False):
...     print("abcd")
...     print("def")
...
abcd
def
c                     Xl         [        U R                   [        [        45      (       a  U R                   /U l         X l        X0l        g r   )sr\   r]   _re_typechannelsuppress)r~   r   r   r   s       r   __init__AssertPrints.__init__a  s3    dffsHo..ffXDF r,   c                 4   [        [        U R                  5      U l        [	        5       U l        [        U R
                  U R                  S9U l        [        [        U R                  U R                  (       a  U R
                  5        g U R                  5        g )N)r   )
r   rF   r   orig_stream
MyStringIObufferr   teesetattrr   r   s    r   r   AssertPrints.__enter__h  sW    "35 lt{{DLL9T\\$--4;;NTXXNr,   c                    Sn Ub   U R                   R                  5         gU R                   R                  5         [        [        U R
                  U R                  5        U R                  R                  5       nU R                   H  n[        U[        5      (       aH  UR                  U5      (       d0   [        R                  UR                  U R
                  U5      5       eM`  Xe;   a  Mg   [        R                  X`R
                  U5      5       e    U R                   R                  5         g! U R                   R                  5         f = fNTF)r   r?   flushr   rF   r   r   r   getvaluer   r\   r   r!   notprinted_msgr   patternr~   etypevaluer   rf   printedr   s          r   r   AssertPrints.__exit__n  s     	  HHNN HHNNCt'7'78kk**,GVVa**88G,,en.C.CAIIt||]d.ee,<X)>)>q,,PW)XX<	 
 HHNNDHHNNs   D2 CD2 /'D2 2E)r   r   r   r   r   r   N)rO   T)	r   r   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                       \ rS rSrSrS rSrg)AssertNotPrintsi  z_Context manager for checking that certain output *isn't* produced.

Counterpart of AssertPrintsc                    Sn Ub6  U R                   R                  5          U R                   R                  5         gU R                   R                  5         [        [        U R
                  U R                  5        U R                  R                  5       nU R                   H  n[        U[        5      (       aH  UR                  U5      (       a0   [        R                  UR                  U R
                  U5      5       eM`  Xe;  a  Mg   [        R                  X`R
                  U5      5       e    U R                   R                  5         g! U R                   R                  5         f = fr   )r   r?   r   r   rF   r   r   r   r   r   r\   r   r!   printed_msgr   r   r   s          r   r   AssertNotPrints.__exit__  s    	   HHNN HHNNCt'7'78kk**,GVVa** xx00 :1C1C		4<<2: :00 + 2[-?-?<<.2 2+  HHNNDHHNNs   E CE 	'E E(r.   N)r   r   r   r   r   r   r   r.   r,   r   r   r     s    #r,   r   c               #   l   #    SSK Jn   U R                  nS U l         S v   Xl        g ! Xl        f = f7f)Nr   )warnc                      g r   r.   )akws     r   <lambda>mute_warn.<locals>.<lambda>  s    r,   )IPython.utilsr   )r   	save_warns     r   	mute_warnr     s*     "		I%DI	I	s   4) 414c              #      #    [        U SSS9R                  5          Sv   [        R                  " U 5        g! [        R                  " U 5        f = f7f)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8 AAAc                 B   ^ [        U 5      mSU4S jjn[        SU5      $ )zTemporarily 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                 X   >  [        T5      $ ! [         a  n[        S5      UeS nAff = f)NzNo more inputs given)nextStopIterationEOFError)prompteits     r   
mock_input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                     [        5       U S/-   n[        U5      u  p#nUS:X  d   U5       eSU;  d   eSU;   d   eSU;   d   eX#4$ )z)test that `ipython [subcommand] -h` worksz-hr   	TracebackOptions
--help-allrJ   r
   
subcommandcmdrn   ro   rcs        r   help_output_testr     sd    

z40
0C(-LCb7C7c!!!38Or,   c                     [        5       U S/-   n[        U5      u  p#nUS:X  d   U5       eSU;  d   eSU;   d   eSU;   d   eX#4$ )z1test that `ipython [subcommand] --help-all` worksr   r   r   r   Classr   r   s        r   help_all_output_testr     sb    

z<8
8C(-LCb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,   