o
    HXh2o                     @   s  d Z ddlZddl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 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ZddlZddlZddlZddlmZ dd	lmZ ejjryed
ddl Z e j!duZ"da#dd Z$dd Z%G dd dej&Z'G dd de(Z)G dd dej&Z*G dd dej&Z+e,ej-dkdG dd dej&Z.e/dkre0  dS dS )zTests for 'site'.

Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.

    N)support)	os_helper)socket_helper)captured_stderr)TESTFNEnvironmentVarGuard
change_cwd)mock)copyzPython was invoked with -Sc               
   C   sv   t jd d  atjr7tjtjs9zttj t	tj W d S  t
y6 }  z
tdtj| f d } ~ ww d S d S )Nz-unable to create user site directory (%r): %s)syspathOLD_SYS_PATHsiteENABLE_USER_SITEosisdir	USER_SITEmakedirs
addsitedirPermissionErrorunittestSkipTest)exc r   8/opt/python-3.10.19/usr/lib/python3.10/test/test_site.pysetUpModule,   s   r   c                   C   s   t tjd d < d S N)r   r   r   r   r   r   r   tearDownModule;   s   r   c                   @   s0  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	de
fddZdd Zdd Zdd Zdd Zdd Zdd Zeeedddd  Zeejd!kd"d#d$ Zd%d& Zeed'd(d) Zeejd*d+d, Zeed'd-d. Z eed'd/d0 Z!d1d2 Z"eed'd3d4 Z#d5d6 Z$d7S )8HelperFunctionsTestsz Tests for helper functions.
    c                 C   s@   t jdd | _tj| _tj| _tj| _	t
j| _tt
j| _dS )zSave a copy of sys.pathN)r   r   sys_pathr   	USER_BASEold_baser   old_sitePREFIXESold_prefixes	sysconfig_CONFIG_VARSoriginal_varsr
   old_varsselfr   r   r   setUpC   s   zHelperFunctionsTests.setUpc                 C   sZ   | j tjdd< | jt_| jt_| jt_	| j
t_tjdur+tj  tj| j dS dS zRestore sys.pathN)r   r   r   r!   r   r    r"   r   r$   r#   r'   r%   r&   clearupdater(   r)   r   r   r   tearDownL   s   

zHelperFunctionsTests.tearDownc                 C   sj   d}t jj| }tj| \}}| t j|| |t j|kr)| || d S | t j|| d S )N)Z	BeginningZEnd)r   r   joinr   makepathassertEqualabspathnormcase)r*   
path_partsZoriginal_dirZabs_dirZnorm_dirr   r   r   test_makepathX   s   z"HelperFunctionsTests.test_makepathc                 C   s8   t  }dd tjD D ]}| ||d||f  qd S )Nc                 S   s*   g | ]}|rt j|rt|d  qS )   )r   r   existsr   r1   ).0r   r   r   r   
<listcomp>g   s
    
z;HelperFunctionsTests.test_init_pathinfo.<locals>.<listcomp>zB%s from sys.path not found in set returned by _init_pathinfo(): %s)r   _init_pathinfor   r   assertIn)r*   Zdir_setentryr   r   r   test_init_pathinfoe   s   z'HelperFunctionsTests.test_init_pathinfoc                 C   sJ   |  |jtjd|j  |  t|jd tj | t	j
|j dS )z>Contain common code for testing results of reading a .pth filez%s not in sys.modulesr   N)r<   importedr   modulesr   r1   good_dir_pathr   assertFalser   r8   bad_dir_pathr*   pth_filer   r   r   pth_file_testsm   s
   z#HelperFunctionsTests.pth_file_testsc                 C   sR   t  }|jdd z|  t|j|jt  | | W |  d S |  w NTprep)	PthFilecleanupcreater   
addpackagebase_dirfilenamesetrF   rD   r   r   r   test_addpackaget   s   z$HelperFunctionsTests.test_addpackage.c                    sz   t j|}|d }t j|| t ddd}|  fdd || W d    ||fS 1 s4w   Y  ||fS )N.pthwutf-8)encodingc                      s
   t  S r   )r   remover   pth_fnr   r   <lambda>   s   
 z/HelperFunctionsTests.make_pth.<locals>.<lambda>)r   r   r3   r0   open
addCleanupwrite)r*   contentspth_dirZpth_nameZpth_basenamerE   r   rX   r   make_pth   s   
zHelperFunctionsTests.make_pthc              	   C   s   |  d\}}t }t||t  W d    n1 sw   Y  | | d | | tt	j
|| | | d | | d | | d d S )Nzimport bad-syntax
zline 1	Tracebackzimport bad-syntaxSyntaxErrorr`   r   r   rM   rP   ZassertRegexgetvaluereescaper   r   r0   r*   r_   rY   err_outr   r   r   !test_addpackage_import_bad_syntax   s   
z6HelperFunctionsTests.test_addpackage_import_bad_syntaxc              	   C   s   |  d\}}t }t||t  W d    n1 sw   Y  | | d | | tt	j
|| | | d | | d d S )Nzrandompath
import nosuchmodule
zline 2ra   ModuleNotFoundErrorrc   rg   r   r   r   test_addpackage_import_bad_exec   s   
z4HelperFunctionsTests.test_addpackage_import_bad_execc                 C   s0   |  d\}}t||t }| |t  d S )Nz

  

)r`   r   rM   rP   r2   )r*   r_   rY   known_pathsr   r   r   test_addpackage_empty_lines   s   z0HelperFunctionsTests.test_addpackage_empty_linesc                 C   s   |  d\}}t }| t||t  W d    n1 s w   Y  d | _| | d t	j
D ]}t|tr@| d| q3d S )Nzabc def
 zabc def)r`   r   rB   r   rM   rP   ZmaxDiffr2   rd   r   r   
isinstancestrassertNotIn)r*   r_   rY   rh   r   r   r   r   #test_addpackage_import_bad_pth_file   s   

z8HelperFunctionsTests.test_addpackage_import_bad_pth_filec                 C   sN   t  }|jdd z|  t|jt  | | W |  d S |  w rG   )rJ   rK   rL   r   r   rN   rP   rF   rD   r   r   r   test_addsitedir   s   z$HelperFunctionsTests.test_addsitedirc                 C   sp   t d}|jdd z(|  t|jt  | t|j	d t
j | |jt
j W |  d S |  w )Nz.dotfileTrH   r   )rJ   rK   rL   r   r   rN   rP   rq   r1   rA   r   r   r<   rD   r   r   r   test_addsitedir_dotfile   s   z,HelperFunctionsTests.test_addsitedir_dotfilechflagsztest needs os.chflags()c                 C   s   t  }|jdd z9|  t|j}t|j|jtjB  t	
|jt  | t	|jd tj | |jtj W |  d S |  w )NTrH   r   )rJ   rK   rL   r   stat	file_pathru   st_flags	UF_HIDDENr   r   rN   rP   rq   r1   rA   r   r   r<   )r*   rE   str   r   r   test_addsitedir_hidden_flags   s   z1HelperFunctionsTests.test_addsitedir_hidden_flagswin32ztest needs Windowsc                 C   s   t  }|jdd z1|  tdd|jg t|jt	  | 
t|jd tj | |jtj W |  d S |  w )NTrH   Zattribz+Hr   )rJ   rK   rL   
subprocess
check_callrw   r   r   rN   rP   rq   r1   rA   r   r   r<   rD   r   r   r   %test_addsitedir_hidden_file_attribute   s   z:HelperFunctionsTests.test_addsitedir_hidden_file_attributec                 C   s   |  t t  d S r   )r2   r   _getuserbaser%   r)   r   r   r   test__getuserbase   s   z&HelperFunctionsTests.test__getuserbasezneed user sitec                 C   sJ   t jdkrt jrd}ntjd }| tjt	t
 td| d S )NdarwinZosx_framework_user_userZpurelib)r   platform
_frameworkr   namer2   r   normpathr   	_get_pathr   r%   Zget_path)r*   schemer   r   r   test_get_path   s   

z"HelperFunctionsTests.test_get_pathz<requires access to PEP 370 user-site (site.ENABLE_USER_SITE)c                 C   s0  t jtj}| |tj t j }t	j
tjdd| g|d}| |d t j }t	j
tjddd| g|d}|t d krH| |d n| |dd t j }d|d	< t	j
tjdd| g|d}|t d krt| |d n| |dd
 t j }d|d< t	j
tjddg|d}| |dd d S )N-cz$import sys; sys.exit(%r in sys.path)envr7   z-sr   z%User site still added to path with -s1ZPYTHONNOUSERSITEz3User site still added to path with PYTHONNOUSERSITEz/tmpPYTHONUSERBASEz=import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))z#User base not set by PYTHONUSERBASE)r   r   r   r   r   r<   r   environr
   r}   call
executabler2   getsitepackages)r*   Zusersiter   rcr   r   r   test_s_option   sP   






z"HelperFunctionsTests.test_s_optionc                 C   s~   d t _t  }| t j| d t _dd l}d |_t }d|d< | t  dt   W d    d S 1 s8w   Y  d S )Nr   xoxor   )	r   r    getuserbaser2   r%   r&   r   
assertTrue
startswith)r*   	user_baser%   r   r   r   r   test_getuserbase#  s   "z%HelperFunctionsTests.test_getuserbasec                 C   sL   d t _d t _t  }| t j| | |t j| | t jt   d S r   )r   r   r    getusersitepackagesr2   r   r   r   )r*   	user_siter   r   r   test_getusersitepackages5  s   z-HelperFunctionsTests.test_getusersitepackagesc                 C   s   dgt _t  }tjdkrVtjdkr4| t|d tj	
dtjdtjd d  d}| |d | n| t|d tj	
dddtjd d  d}| |d	 | d S | t|d | |d d tj	
ddd}| |d | d S )
Nr   /lib   zpython%d.%dzsite-packagesr   r7   )r   r#   r   r   sepr   
platlibdirr2   lenr   r0   version_info)r*   dirsZwantedr   r   r   test_getsitepackages@  s(   


z)HelperFunctionsTests.test_getsitepackagesc              
   C   st  d t _d t _t C}tddd + |d= |d= t  }| |dt	j
 | t  }| ||| W d    n1 s@w   Y  W d    n1 sOw   Y  tjddd	U}tjt d
5}tt dd t }t | || |  | | W d    n1 sw   Y  W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )Nzos.path.expanduserc                 S   s   | S r   r   )r   r   r   r   rZ   a  s    z=HelperFunctionsTests.test_no_home_directory.<locals>.<lambda>r   APPDATA~zos.path.isdirF)Zreturn_valuer   r   T)r   r   r    r   r	   patchr   r   r   r   r   r   objectr   Z	swap_attrrP   addusersitepackagesZassert_called_once_withZassert_not_calledrB   )r*   r   r   r   Z
mock_isdirZmock_addsitedirrl   r   r   r   test_no_home_directoryX  s<    

P z+HelperFunctionsTests.test_no_home_directoryc              
   C   s   d}d|d fdfD ]D\}}t dt j|d. t dt  t| | tj	
 | W d    n1 s:w   Y  W d    n1 sIw   Y  q
d S )Nzbla-bla-blaT
)Frn   z	sys.flags)verbosez
sys.stderr)r	   r   ZMockioStringIOr   _tracer2   r   stderrrd   )r*   messager   outr   r   r   
test_tracez  s   
 zHelperFunctionsTests.test_traceN)%__name__
__module____qualname____doc__r+   r/   r6   r>   rF   rQ   r   r`   ri   rk   rm   rr   rs   rt   r   
skipUnlesshasattrr   r{   r   r   r   r   HAS_USER_SITEr   r   r   r   r   r   r   r   r   r   r   r   r   r   ?   s@    	






'





!r   c                   @   s4   e Zd ZdZedddfddZdd Zdd
dZdS )rJ   z/Helper class for handling testing of .pth filestimeZ__testdir__Z__badc                 C   sj   |d | _ tjd| _tj| j| j | _|| _|| _|| _	tj| j| j| _
tj| j| j	| _dS )zInitialize instance variablesrS   rn   N)rO   r   r   r3   rN   r0   rw   r?   good_dirnamebad_dirnamerA   rC   )r*   filename_baser?   r   r   r   r   r   __init__  s   
zPthFile.__init__c                 C   sz   t | jd}z)td|d td|d td| j |d t| j|d t| j|d W |  n|  w t| j	 dS )ao  Create a .pth file with a comment, blank lines, an ``import
        <self.imported>``, a line with self.good_dirname, and a line with
        self.bad_dirname.

        Creation of the directory for self.good_dir_path (based off of
        self.good_dirname) is also performed.

        Make sure to call self.cleanup() to undo anything done by this method.

        rT   z#import @bad module namefiler   z	import %sN)
r[   rw   printr?   r   r   closer   mkdirrA   )r*   FILEr   r   r   rL     s   zPthFile.createFc                 C   s   t j| jrt | j |r tj| j| _	| j	rtj| j= n
| j	r*| j	tj| j< t j| j
r7t | j
 t j| jrFt | j dS dS )zMake sure that the .pth file is deleted, self.imported is not in
        sys.modules, and that both self.good_dirname and self.bad_dirname are
        not existing directories.N)r   r   r8   rw   rW   r   r@   getr?   Zimported_modulerA   rmdirrC   )r*   rI   r   r   r   rK     s   
zPthFile.cleanupN)F)r   r   r   r   r   r   rL   rK   r   r   r   r   rJ     s    
rJ   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Ze	d
dd Z
dd Zdd Zdd Zdd Zdd Zejdejjeeejdddd ZdS )ImportSideEffectTestsz(Test side-effects from importing 'site'.c                 C   s   t jdd | _dS )zMake a copy of sys.pathN)r   r   r   r)   r   r   r   r+        zImportSideEffectTests.setUpc                 C   s   | j tjdd< dS r,   )r   r   r   r)   r   r   r   r/     r   zImportSideEffectTests.tearDownc                 C   s*   dt jd _t  | t jd j dS )zTest for __cached__ is None.

        Regarding to PEP 3147, __cached__ can be None.

        See also: https://bugs.python.org/issue30167
        Ntest)r   r@   
__cached__r   	abs_pathsZassertIsNoner)   r   r   r   test_abs_paths_cached_None  s   z0ImportSideEffectTests.test_abs_paths_cached_Nonec                 C   s4   t   t }tjD ]}| || || q
d S r   )r   removeduppathsrP   r   r   rq   add)r*   Z
seen_pathsr   r   r   r   test_no_duplicate_paths  s   
z-ImportSideEffectTests.test_no_duplicate_pathsztest not implementedc                 C   s   d S r   r   r)   r   r   r   test_add_build_dir  s   z(ImportSideEffectTests.test_add_build_dirc                 C   s$   |  ttd |  ttd d S )Nquitexitr   r   builtinsr)   r   r   r   test_setting_quit  s   z'ImportSideEffectTests.test_setting_quitc                 C   s4   |  ttd |  ttd |  ttd d S )N	copyrightcreditslicenser   r)   r   r   r   test_setting_copyright  s   z,ImportSideEffectTests.test_setting_copyrightc                 C   s   |  ttd d S )Nhelpr   r)   r   r   r   test_setting_help  r   z'ImportSideEffectTests.test_setting_helpc                 C   sZ   t jdkr)dd l}| d dr+tjj D ]	}|dkr! d S q| d d S d S d S )Nr|   r   r7   Zcpmbcszdid not alias mbcs)	r   r   localegetdefaultlocaler   	encodingsaliasesvaluesfail)r*   r   valuer   r   r   test_aliasing_mbcs  s   
z(ImportSideEffectTests.test_aliasing_mbcsc                 C   s>   dt jvrzdd l}W n
 ty   Y d S w | d d S d S )Nsitecustomizer   z(sitecustomize not imported automatically)r   r@   r   ImportErrorr   )r*   r   r   r   r   test_sitecustomize_executed  s   
z1ImportSideEffectTests.test_sitecustomize_executednetworkZHTTPSHandlerz$need SSL support to download licensec              
   C   s   t j d }tjj|dd}| tjj z1t	|" tj
|}| }W d    n1 s2w   Y  W d    n1 sAw   Y  W n tjjy^ } z	|j}W Y d }~nd }~ww | j|dd| d d S )Nr7   ZHEAD)method   zCan't find )msg)r   _Printer__dataspliturllibrequestZRequestr\   
urlcleanupr   Ztransient_interneturlopenZgetcodeerror	HTTPErrorcoder2   )r*   urlZreqdatar   er   r   r   test_license_exists_at_url  s    
z0ImportSideEffectTests.test_license_exists_at_urlN)r   r   r   r   r+   r/   r   r   r   skipr   r   r   r   r   r   r   r   Zrequires_resourceZsystem_must_validate_certr   r   r   r   r   r   r   r   r   r     s&    	



r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
StartupImportTestsc           
      C   s8  t jtjdddgt jdd}| d }| |jdt| t	|}|D ]}t

tjt
|d}|rB| dt| d	|  q$t jtjdd
ddgt jt jdd}| \}}| |jd||f t	|}| d| h d}| ||| | d|| | d|| h dtj}	| ||	| d S )N-Ir   z!import sys; print(repr(sys.path))rU   )stdoutrV   r   z*.pthzfound z .pth files in: z-vz#import sys; print(set(sys.modules)))r  r   rV   r   >   re   _sre	sre_parsesre_compilesre_constantsr   copyreg>
   	functoolscollectionskeywordtypesweakref_collections	itertoolsreprliboperatorheapq)r}   Popenr   r   PIPEcommunicater2   
returncodereprevalglobr   r   r0   rf   ZskipTestr   r<   rB   intersectionrq   
differencebuiltin_module_names)
r*   popenr  Zisolated_pathsr   Z	pth_filesr   r@   Zre_modsZcollection_modsr   r   r   test_startup_imports  sB   z'StartupImportTests.test_startup_importsc                 C   s&   t tjddg }| |d d S )Nr   9import sys; sys.exit(hasattr(sys, "__interactivehook__"))z''__interactivehook__' not added by siter}   r  r   r   waitr   r*   rr   r   r   test_startup_interactivehookI  s   
z/StartupImportTests.test_startup_interactivehookc                 C   (   t tjdddg }| |d d S )Nr   r   r  z,'__interactivehook__' added in isolated mode)r}   r  r   r   r  rB   r   r   r   r   %test_startup_interactivehook_isolatedN     z8StartupImportTests.test_startup_interactivehook_isolatedc                 C   r#  )Nr   r   zYimport site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))z6'__interactivehook__' not added by enablerlcompleter()r  r   r   r   r   .test_startup_interactivehook_isolated_explicitT  r%  zAStartupImportTests.test_startup_interactivehook_isolated_explicitN)r   r   r   r  r"  r$  r&  r   r   r   r   r     s
    0r   r|   zonly supported on Windowsc                   @   s6   e Zd ZdddZdd Zdd Zdd	 Zd
d ZdS )_pthFileTestsTc              
   C   s6  dd l }t }| tj| tj|tj	t
jd }|t
j}tj|tj	|d }tt
j| t|| ttjtj	|d dD ]}t|tj|tj	|d  qM|rntj|d d }	n
tj|d d }	t|	d}
|D ]}t||
d qW d    |S 1 sw   Y  |S )Nr   r7   zvcruntime*.dllz._pthrT   r   )_winapitempfilemkdtempr\   r   rmtreer   r   r0   r   r   r   ZGetModuleFileNameZ	dllhandleshutilr
   r  splitextr[   r   )r*   linesexe_pthr(  Ztemp_direxe_fileZdll_src_fileZdll_filefnZ	_pth_filefliner   r   r   _create_underpth_exe]  s*   $$
z"_pthFileTests._create_underpth_exec                 C   sD   g }|D ]}|r|d dkrqt jt j||}|| q|S )Nr   #)r   r   r3   r0   append)r*   
sys_prefixr.  r   r3  Zabs_pathr   r   r   "_calc_sys_path_for_underpth_nositeq  s   z0_pthFileTests._calc_sys_path_for_underpth_nositec                    s   t jt jtj t jtj}dg fddtdD dd}| |}| 	t j||}t j
 }d|d< d	|t d
|d
< tj|ddg|dd}| d}| |d | ||d d S )Nfake-path-namec                       g | ]} qS r   r   r9   _Zlibpathr   r   r:         z;_pthFileTests.test_underpth_nosite_file.<locals>.<listcomp>r   rn   	# commentfrom-env
PYTHONPATH{};{}PATHr   zCimport sys; print("\n".join(sys.path) if sys.flags.no_site else "")ansi)r   rV   r   zsys.flags.no_site was Falsesys.path is incorrect)r   r   dirnamer   __file__r   r   ranger4  r8  r   r
   formatgetenvr}   check_outputrstripr   r   r2   )r*   
exe_prefixZ	pth_linesr0  r   r   outputZactual_sys_pathr   r=  r   test_underpth_nosite_filez  s<   


z'_pthFileTests.test_underpth_nosite_filec              
      s   t jt jtj t jtj}| dg fddtdD ddd}t j|}t j	
 }d|d	< d
|t d|d< tj|ddt j|d t j|df g|d}| |d d S )Nr9  c                    r:  r   r   r;  r=  r   r   r:     r>  z4_pthFileTests.test_underpth_file.<locals>.<listcomp>r   rn   r?  import siter@  rA  rB  rC  r   import sys; sys.exit(not sys.flags.no_site and %r in sys.path and %r in sys.path and %r not in sys.path and all("\r" not in p and "\n" not in p for p in sys.path))r   rE  r   r   rF  r   rG  r   r   r4  rH  r   r
   rI  rJ  r}   r   r0   r   r*   rM  r0  r7  r   r   r   r=  r   test_underpth_file  s8   
z _pthFileTests.test_underpth_filec              
      s   t jt jtj t jtj}| jdg fddtdD ddddd	}t j|}t j	
 }d
|d< d|t d|d< tj|ddt j|d t j|d
f g|d}| |d d S )Nr9  c                    r:  r   r   r;  r=  r   r   r:     r>  z8_pthFileTests.test_underpth_dll_file.<locals>.<listcomp>r   rn   r?  rP  F)r/  r@  rA  rB  rC  r   rQ  r   rE  rR  rS  r   r=  r   test_underpth_dll_file  s<   
z$_pthFileTests.test_underpth_dll_fileN)T)r   r   r   r4  r8  rO  rT  rU  r   r   r   r   r'  Z  s    
	r'  __main__)1r   r   Ztest.supportr   r   r   r   r   Ztest.support.os_helperr   r   r   r   r   r  r   r   re   r,  rv   r}   r   r%   r)  Zurllib.errorr   Zurllib.requestr	   r
   flagsno_siter   r   r   r   r   r   r   ZTestCaser   r   rJ   r   r   r   r   r'  r   mainr   r   r   r   <module>   sT    

  F7]Cm