
    &eZ                     l   d Z ddlZddlZddlZddlZddlZddl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c 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  ej                    d
k    r ej        dd           d Z  G d d          Z! G d de          Z"d Z# G d de"          Z$dS )z Tests for autoreload extension.
    N)StringIO)	dataclass)TestCase)AutoreloadMagics)EventManagerpre_run_cell)skipif_not_numpy)ExecutionInfoPyPyz;Current autoreload implementation is extremely slow on PyPyT)allow_module_levelc                      d S N )akws     Hlib/python3.11/site-packages/IPython/extensions/tests/test_autoreload.py<lambda>r   /   s         c                   H    e Zd Zd ZexZZ	 	 	 	 	 d	dZd Zd Z	d Z
d
dZdS )	FakeShellc                     i | _         | j         | _        i | _        t          | dt          h          | _        t          |           | _        | j                            d| j        j                   d S )Nr   )shell)	nsuser_nsuser_ns_hiddenr   r   eventsr   auto_magicsregisterselfs    r   __init__zFakeShell.__init__3   sg    w "4.,)GHH+$777^T-=-JKKKKKr   NFc                 ,    t          j                     d S r   )	traceback	print_exc)r    	exc_tuplefilename	tb_offsetexception_onlyrunning_compiled_codes         r   showtracebackzFakeShell.showtraceback=   s     	r   c           
          | j                             dt          ddddd                      t          || j                   | j                                         d S )Nr    F)raw_cellstore_historysilentshell_futurescell_id)r   triggerr
   execr   r   post_execute_hook)r    codes     r   run_codezFakeShell.run_codeG   so    ##  		
 		
 		
 	T4<   **,,,,,r   c                 :    | j                             |           d S r   )r   update)r    itemss     r   pushzFakeShell.pushU   s    ur   c                 :    | j                             |           d S r   )r   
autoreload)r    	parameters     r   magic_autoreloadzFakeShell.magic_autoreloadX   s    ##I.....r   c                 p    | j                             ||           | j                                          d S )Nstream)r   aimportr4   )r    r=   rA   s      r   magic_aimportzFakeShell.magic_aimport[   s9      6 :::**,,,,,r   )NNNFFr   )__name__
__module____qualname__r!   noopregister_magicsset_hookr*   r6   r:   r>   rC   r   r   r   r   r   2   s        L L L "&%Oh #   - - -  / / /- - - - - -r   r   c                   <    e Zd ZdZdZdZdZd Zd Zd Z	d Z
d ZdS )	Fixturez&Fixture for creating test module filesN#abcdefghijklmopqrstuvwxyz0123456789c                     t          j                    | _        t          t          j                  | _        t          j                            d| j                   t                      | _	        d S )Nr   )
tempfilemkdtemptest_dirlistsyspathold_sys_pathinsertr   r   r   s    r   setUpzFixture.setUpg   sI     (** NN4=)))[[


r   c                     t          j        | j                   | j        t          _        d | _        d | _        d | _        d S r   )shutilrmtreerP   rT   rR   rS   r   r   s    r   tearDownzFixture.tearDownm   s8    dm$$$$ 


r   c                     dd                     t          j        | j        d                    z   }|t          j        v rt          j        |= t          j                             | j        |dz             }||fS )Ntmpmod_r,      z.py)	joinrandomsamplefilename_charsrR   modulesosrS   rP   )r    module_name	file_names      r   
get_modulezFixture.get_moduleu   se    "''&-8KR*P*P"Q"QQ#+%%K(GLLe0CDD	I%%r   c                     t          j        |          }t          j        d           t	          |dd          5 }|                    |           ddd           dS # 1 swxY w Y   dS )a+  
        Write a file, and force a timestamp difference of at least one second

        Notes
        -----
        Python's .pyc files record the timestamp of their compilation
        with a time resolution of one second.

        Therefore, we need to force a timestamp difference between .py
        and .pyc, without having the .py file be timestamped in the
        future, and without changing the timestamp of the .pyc file
        (because that is stored in the file).  The only reliable way
        to achieve this seems to be to sleep.
        g?wutf-8encodingN)textwrapdedenttimesleepopenwrite)r    r&   contentfs       r   
write_filezFixture.write_file|   s     /'**
4 (C'222 	aGGG	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AA"%A"c                     t          j        |          }|                                 \  }}t          |dd          5 }|                    |           d d d            n# 1 swxY w Y   ||fS )Nrh   ri   rj   )rl   rm   rf   rp   rq   )r    r5   mod_namemod_fnrs   s        r   
new_modulezFixture.new_module   s    t$$??,,&&#000 	AGGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   A  A$'A$)rD   rE   rF   __doc__rP   rT   ra   rV   rZ   rf   rt   rx   r   r   r   rK   rK   `   st        00HL:N! ! !  & & &  .         r   rK   c                     | j         j        }t          | dd          }t          j        |         }|                    d          D ]}t          ||          }|S )z;
    Original issue comes from pickle; hence the name.
    rE   N.)	__class__rD   getattrrR   rb   split)objnamerd   obj2subpaths        r   pickle_get_current_classr      sZ     =!D#|T22K;{#D::c?? & &tW%%Kr   c                   b    e Zd Zd Zd Zd Zed             Zd Zd Z	d Z
d Zdd
Zd Zd ZdS )TestAutoreloadc                    |                      t          j        d                    \  }}| j                            d           | j                            |           |                     |t          j        d                     t          j        d|z  d          5  | j        	                    d           d d d            d S # 1 swxY w Y   d S )Nz
                                from enum import Enum
                                class MyEnum(Enum):
                                    A = 'A'
                                    B = 'B'
                            2a  
                                from enum import Enum
                                class MyEnum(Enum):
                                    A = 'A'
                                    B = 'B'
                                    C = 'C'
                            [autoreload of %s failed:stderrchannelpass)
rx   rl   rm   r   r>   rC   rt   ttAssertNotPrintsr6   r    rv   rw   s      r   test_reload_enumsz TestAutoreload.test_reload_enums   s)   ??O  	
 	
& 	
##C(((
  ***O  	
 	
 	
 (83h
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s    CCCc                 F   | j                             d           |                     d          \  }}d| j         j        vsJ d| j         j        vsJ | j                             d|z             | j                             d           |                     |d           | j         j        d         }| j                             d           t          |          }t          ||          sJ | j                             d	           | j                             d
           d S )Nr   zd
            class Test():
                def meth(self):
                    return "old"
        testresultzfrom %s import Testztest = Test()zd
            class Test():
                def meth(self):
                    return "new"
        r   zimport picklezp = pickle.dumps(test))r   r>   rx   r   r6   rt   r   
isinstance)r    rv   rw   test_object
test_classs        r   test_reload_class_typez%TestAutoreload.test_reload_class_type   s1   
##C(((??
 
& TZ]****tz},,,,
1H<===
O,,,	
 	
 	
 jmF+ 	
F###-k::
+z22222 	
O,,,
455555r   c                 F   | j                             d           |                     t          j        d                    \  }}| j                             d|z             | j                             d           | j                             d           |                     t                    5  | j                             d           d d d            n# 1 swxY w Y   |                     t                    5  | j                             d           d d d            n# 1 swxY w Y   | j                             d           |                     t                    5  | j                             d	           d d d            n# 1 swxY w Y   |                     |t          j        d
                     | j                             d           dD ]G}| j                             | d           |                     t                    5  | j                             | d           d d d            n# 1 swxY w Y   |                     t                    5  | j                             | d           d d d            n# 1 swxY w Y   | j                             | d           | j                             | d           |                     t                    5  | j                             | d           d d d            n# 1 swxY w Y   Id S )Nr   a  
                                class MyClass:

                                    def __init__(self, a=10):
                                        self.a = a
                                        self.b = 22 
                                        # self.toto = 33

                                    def square(self):
                                        print('compute square')
                                        return self.a*self.a
                            from %s import MyClasszfirst = MyClass(5)zfirst.square()zfirst.cube()zfirst.power(5)zfirst.bz
first.totoa  
                            class MyClass:

                                def __init__(self, a=10):
                                    self.a = a
                                    self.b = 11

                                def power(self, p):
                                    print('compute power '+str(p))
                                    return self.a**p
                            zsecond = MyClass(5)>   firstsecondz	.power(5)z.cube()z	.square()z.bz.az.toto)	r   r>   rx   rl   rm   r6   assertRaisesAttributeErrorrt   )r    rv   rw   object_names       r   test_reload_class_attributesz+TestAutoreload.test_reload_class_attributes   s{   
##C(((??O  
 
&  	
4x?@@@
0111
,---~.. 	0 	0J///	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0~.. 	2 	2J 0111	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2
I&&&~.. 	. 	.J---	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.
 	O
  	
 	
 	
" 	
1222. 		; 		;KJ; 9 9 9:::"">22 = =
##{$;$;$;<<<= = = = = = = = = = = = = = ="">22 ? ?
##{$=$=$=>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ?J; 2 2 2333J; 2 2 2333"">22 ; ;
##{$9$9$9:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ;		; 		;sl   0CCC<D##D'*D'"F		FFH<<I 	I 	!JJ	J	*LL	L	c                    | j                             d           | j                             d           |                     t	          j        d                    \  }}| j                             d|z             | j                             d           |                     |t	          j        d                     t          j        d|z  d	          5  | j                             d
           d d d            d S # 1 swxY w Y   d S )Nr   z1+1z
                                import numpy as np
                                class MyClass:
                                    a = (np.array((.1, .2)),
                                         np.array((.2, .3)))
                            r   zfirst = MyClass()z
                                import numpy as np
                                class MyClass:
                                    a = (np.array((.3, .4)),
                                         np.array((.5, .6)))
                            r   r   r   r   )	r   r>   r6   rx   rl   rm   rt   r   r   r   s      r   test_comparing_numpy_structuresz.TestAutoreload.test_comparing_numpy_structures,  s^   
##C(((
E"""??O  	
 	
& 	
4x?@@@
/000 	O  
	
 
	
 
	
 (83h
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   C??DDc                 &   | j                             d           d}|                     t          j        |                    \  }}| j                             d| d           | j                             d           |                     t                    5  | j                             d           d d d            n# 1 swxY w Y   |                     t                    5  | j                             d           d d d            n# 1 swxY w Y   |                     t                    5  | j                             d           d d d            n# 1 swxY w Y   d	}|                     |t          j        |                     | j                             d           | j                             d
| d           | j                             d           | j                             d           | j                             d           d}|                     |t          j        |                     | j                             d           | j                             d           | j                             d           | j                             d           t          j
        dk     r| j                             d           d}|                     t          j        |                    \  }}d| d}|                     |t          j        |                     | j                             d           | j                             d           | j                             d           | j                             d           d S )N3#
        def func1(): pass
        zfrom z	 import *zfunc1()zfunc2()z
t = Test()numberz
        def func1(): pass
        def func2(): pass
        class Test: pass
        number = 0
        from enum import Enum
        class TestEnum(Enum):
            A = 'a'
        zimport sys; sys.modules['z
'].func2()z
TestEnum.Aa%  
        def func1(): return 'changed'
        def func2(): return 'changed'
        class Test:
            def new_func(self):
                return 'changed'
        number = 1
        from enum import Enum
        class TestEnum(Enum):
            A = 'a'
            B = 'added'
        zassert func1() == 'changed'zassert func2() == 'changed'z,t = Test(); assert t.new_func() == 'changed'zassert number == 1)      z"assert TestEnum.B.value == 'added'z
        from enum import Enum
        class Ext(Enum):
            A = 'ext'
        def ext_func():
            return 'ext'
        class ExtTest:
            def meth(self):
                return 'ext'
        ext_int = 2
        z
        from z import *
        zassert Ext.A.value == 'ext'zassert ext_func() == 'ext'z't = ExtTest(); assert t.meth() == 'ext'zassert ext_int == 2)r   r>   rx   rl   rm   r6   r   	NameErrorrt   rR   version_info)	r    mod_coderv   rw   new_codenew_mod_codenew_mod_name
new_mod_fncurrent_mod_codes	            r   !test_autoload_newly_added_objectsz0TestAutoreload.test_autoload_newly_added_objectsO  s   
##C(((  ??8?8+D+DEE&
7H777888
I&&&y)) 	+ 	+J	***	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+y)) 	. 	.J---	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.y)) 	* 	*J)))	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*
 	 9 9::: 	
I&&&
LLLLMMM
L)))
H%%%
L))) 	 9 9:::
9:::
9:::
JKKK
0111g%%J DEEE
 $(??8?<3P3P#Q#Q j   	0@ A ABBB
9:::
8999
EFFF
122222s6   C  CC%DDD1EEEc                     t            G d d                       fd} |d           |d          k    sJ  |d           |d          k    sJ  |d           |d          k    sJ  |d	           |d
          k    sJ  |d           |d          k    sJ                      t                    5   j                            d           d d d            d S # 1 swxY w Y   d S )Nc                   .    e Zd ZU eed<   eed<   eed<   dS )=TestAutoreload.test_verbose_names.<locals>.AutoreloadSettings	check_allenabledautoload_objN)rD   rE   rF   bool__annotations__r   r   r   AutoreloadSettingsr     s0         OOOMMMr   r   c                     j                             |            j         j        j        } |j        |j        |j                  S r   )r   r>   r   	_reloaderr   r   r   )modemodule_reloaderr   r    s     r   gather_settingsz:TestAutoreload.test_verbose_names.<locals>.gather_settings  sM    J''---"j4>O%%)',  r   0offOFF1explicitr   allr   complete4)r   r   
ValueErrorr   r>   )r    r   r   s   ` @r   test_verbose_namesz!TestAutoreload.test_verbose_names  s   		 	 	 	 	 	 	 
	
	 	 	 	 	 	 s##u'='=====s##u'='=====s##z'B'BBBBBs##u'='=====s##z'B'BBBBB z** 	- 	-J'',,,	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   ?C''C+.C+c                 4   | j         j        j        }| j                             d           |j        d         du sJ d|j                                        vsJ | j                             d           |j        d         du sJ d|j                                        vsJ | j                             d           |j        d         du sJ d|j                                        vsJ |j        d         du sJ d|j                                        vsJ d S )Nrc   Tz-mathmathz	-os, math)r   r   r   rC   rb   skip_moduleskeys)r    r   s     r   test_aimport_parsingz#TestAutoreload.test_aimport_parsing  sD   *0:
  &&&&t,4444?7<<>>>>>>
  )))+F3t;;;;_499;;;;;;
  	
 	
 	
 &v.$6666_9>>@@@@@@+D1T9999?27799999999r   c                 H   | j                             d           d}|                     |          \  }}| j                             d|            t	          j        dd          5  | j                             d           d d d            n# 1 swxY w Y   | j                             d           |                     ||           t	          j        d	| d
d          5  | j                             d           d d d            n# 1 swxY w Y   | j                             d           |                     ||           t	          j        d	| d
d          5  | j                             d           d d d            n# 1 swxY w Y   | j                             d           |                     ||           t	          j        d	| d
d          5  | j                             d           d d d            n# 1 swxY w Y   | j                             d           |                     ||           |                     d          5 }| j                             d           d d d            n# 1 swxY w Y   |j        d| d
gk    sJ | j                             d           |                     ||           |                     d          5 }| j                             d           d d d            n# 1 swxY w Y   |j        d| d
gk    sJ d S )Nr   r   zimport r,   stdoutr   r   zcomplete --printzReloading 'z'.zcomplete -pzcomplete --print --logr<   )loggerzINFO:autoreload:Reloading 'zcomplete -l)	r   r>   rx   r6   r   AssertPrintsrt   
assertLogsoutput)r    r   rv   rw   los        r   test_autoreload_outputz%TestAutoreload.test_autoreload_output  s   
##J///  ??844&
0h00111_R222 	( 	(J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	
##$6777)))_&(&&&
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(
 	
##M222)))_&(&&&
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(
 	
##$<===)))_&(&&&
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(
 	
##$<===)))__L_11 	(RJ'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(yG8GGGHHHHH
##M222)))__L_11 	(RJ'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(yG8GGGHHHHHHHsl   (BBB$DDD FFFHH
HI;;I?I?LL	L	Tc                 $	   	                       d          \  }}|r։ j                            d            j                            |           t	                      } j                            d|                                d|z  |                                                                t                    5   j                            d           ddd           n# 1 swxY w Y   n j                            d            j        	                    d	|z             t	                      } j                            d|            
                    d
|                                v                                 | j        j                   t          j        |         j                            d                                          		 fd} |                                  |d           t%          j        d|z  d          5   j        	                    d           ddd           n# 1 swxY w Y   t%          j        d|z  d          5   j        	                    d           ddd           n# 1 swxY w Y    |                                  |d           	 fd} j        	                    d            |             t+          j        |            j        	                    d            |             |r j                            d|z              t	                      } j                            d|            
                    d|z  |                                v             j                            d           n j                            d                                |d            j        	                    d            j        	                    d            |             |r j                            |           n j                            d            j        	                    d                                j        d           dS )zt
        Functional test for the automatic reloader using either
        '%autoreload 1' or '%autoreload 2'
        a  
x = 9

z = 123  # this item will be deleted

def foo(y):
    return y + 3

class Baz(object):
    def __init__(self, x):
        self.x = x
    def bar(self, y):
        return self.x + y
    @property
    def quux(self):
        return 42
    def zzz(self):
        '''This method will be deleted below'''
        return 99

class Bar:    # old-style class: weakref doesn't work for it on Python < 2.7
    def foo(self):
        return 1
r   r,   r@   zModules to reload:
%stmpmod_as318989e89dsNr   z	import %sz%Modules to reload:
all-except-skipped	   c                                           j        d                                j        d                                 d          d                                                    d          d                               d          }                                          d          d                                |                     d          d                                | j        d                                |                                 d                                           }                                                     d                                |                                d           d S )	Nr   {   r   r      
   *   c   )	assertEqualxzfooBazbarquuxzzzBarr   r   modold_fooold_objold_obj2r    s     r   check_module_contentsz>TestAutoreload._check_smoketest.<locals>.check_module_contents=  sE   SUA&&&SUC(((WWQZZ+++SWWQZZ+++''!**CW[[^^R000SWWQZZ,,,SXr***SWWYY+++7799DX\\^^Q///TXXZZ+++++r   z
a syntax error
r   r   r   r   a  
x = 10

def foo(y):
    return y + 4

class Baz(object):
    def __init__(self, x):
        self.x = x
    def bar(self, y):
        return self.x + y + 1
    @property
    def quux(self):
        return 43

class Bar:    # old-style class
    def foo(self):
        return 2
c                                          j        d                               t          d                                           d          d                                                    d          d                               d          }                                          d          d                                |                     d          d                                j        d                                | j        d                               t          d	                                         t          | d	                                                     }                                                     d
                                |                                d
           d S )Nr   r   r      r   r      +   r      )	r   r   assertFalsehasattrr   r   r   r   r   r   s     r   r   z>TestAutoreload._check_smoketest.<locals>.check_module_contents  s   SUB'''WS#..///WWQZZ+++SWWQZZ+++''!**CW[[^^R000SWWQZZ,,,W\2...SXr***WWe44555WS%001117799DX\\^^Q///TXXZZ+++++r   -zModules to skip:
%sz-tmpmod_as318989e89dsr   z	
x = -99
i)rx   r   r>   rC   r   assertIngetvaluer   ImportErrorr6   
assertTruer   rR   rb   r   r   r   rt   r   r   r   rc   unlinkr   r   )
r    use_aimportrv   rw   rA   r   r   r   r   r   s
   `     @@@@r   _check_smoketestzTestAutoreload._check_smoketest  s     ??
 
&<  	J'',,,J$$X...ZZFJ$$R$777MM3h>ARARSSS"";// A A
(()?@@@A A A A A A A A A A A A A A A J'',,,Jh 6777ZZFJ$$R$777OO8FOO<M<MM   	h
...k(#
 '''!**7799	, 	, 	, 	, 	, 	, 	, 	, 	," 	 		
 	
 	
 _(83h
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( (83h
 
 
 	( 	( J'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	
 		
 	
 	
.	, 	, 	, 	, 	, 	, 	, 	, 	,* 	
F###
 		&
F###
  		-J$$S8^444ZZFJ$$R$777OO3h>6??CTCTTUUU J$$%<====J'',,,	
 	
 	
 	
F###
F###
  	,J$$X....J''+++
F###$$$$$s6   C**C.1C.$III/JJJc                 2    |                      d           d S )NTr   r   r   s    r   test_smoketest_aimportz%TestAutoreload.test_smoketest_aimport  s    $/////r   c                 2    |                      d           d S )NFr   r   r   s    r   test_smoketest_autoreloadz(TestAutoreload.test_smoketest_autoreload  s    %00000r   N)T)rD   rE   rF   r   r   r   r	   r   r   r   r   r   r   r   r  r   r   r   r   r      s        ( ( (<"6 "6 "6H;; ;; ;;z  (  (  (DS3 S3 S3j- - -6: : :&)I )I )IVD% D% D% D%L0 0 01 1 1 1 1r   r   )%ry   rc   platformpytestrR   rN   rl   rX   r_   rn   r#   ior   dataclassesr   IPython.testing.toolstestingtoolsr   unittestr   IPython.extensions.autoreloadr   IPython.core.eventsr   r   IPython.testing.decoratorsr	   IPython.core.interactiveshellr
   python_implementationskiprG   r   rK   r   r   r   r   r   <module>r     s    
			   



                ! ! ! ! ! ! " " " " " " " " "       : : : : : : : : : : : : : : 7 7 7 7 7 7 7 7 7 7 7 7!8!##v--FKE    +- +- +- +- +- +- +- +-\8  8  8  8  8 h 8  8  8 @	 	 	[1 [1 [1 [1 [1W [1 [1 [1 [1 [1r   