B
    18\Q                 @   s   d dl m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	Z	d dl
Z
ejdkZG dd dZG dd deejZG d	d
 d
eejZedkre  dS )    )supportN)
namedtuplentc               @   s2   e Zd Zdd Zdd ZddddZd	d
 ZdS )EmbeddingTestsMixinc             C   s   t jt}t jt jt j|}d}tr^dtjkr>dndd }||7 }t jtj}nt j|d}t j|| | _	}t j
|s| d|  t  | _t | d S )NZ
_testembedZ_d z.exeZProgramsz%r doesn't exist)ospathabspath__file__dirname
MS_WINDOWSsys
executablejointest_exeexistsskipTestgetcwdoldcwdchdir)selfhereZbasepathZexenameextZexepathZexe r   S/oak/stanford/groups/akundaje/marinovg/programs/Python-3.7.3/Lib/test/test_embed.pysetUp   s    
zEmbeddingTestsMixin.setUpc             C   s   t | j d S )N)r   r   r   )r   r   r   r   tearDown%   s    zEmbeddingTestsMixin.tearDownN)envc            G   s   | j g}|| |dk	r4tr4| }tjd |d< tj|tjtjd|d}|	 \}}|j
dkrtjrtd| d td|  td	|  td
 | |j
dd|j
|f  ||fS )z'Runs a test in the embedded interpreterNZ
SYSTEMROOTT)stdoutstderruniversal_newlinesr   r   z--- z failed ---zstdout:
zstderr:
z------zbad returncode %d, stderr is %r)r   extendr   copyr   environ
subprocessPopenPIPEcommunicate
returncoder   verboseprintassertEqual)r   r   argscmdpouterrr   r   r   run_embedded_interpreter(   s(    

z,EmbeddingTestsMixin.run_embedded_interpreterc             c   s&  |  d\}}| |d d}tdd}d}g }x| D ]}|d|krx| t|d tjdkrnt| |d7 }q:| 	t|d	 t
||}|d kr| || ||  }	tjdkrt|	 | |	j | |	j | |	j ||	 t|d	kr:|d }
| |	|
 |V  g }q:W d S )
NZ!repeated_init_and_subinterpretersr   zS^interp (\d+) <(0x[\dA-F]+)>, thread state <(0x[\dA-F]+)>: id\(modules\) = ([\d]+)$Interpzid interp tstate modulesr   z--- Pass {} ---      )r1   r+   r   
splitlinesformatlenr   r)   r*   
assertLessrematchassertRegexgroups
assertTrueinterptstatemodulesappend)r   r/   r0   Z
interp_patr2   ZnumloopsZcurrent_runliner:   r>   mainr   r   r   %run_repeated_init_and_subinterpretersC   s:    



z9EmbeddingTestsMixin.run_repeated_init_and_subinterpreters)__name__
__module____qualname__r   r   r1   rD   r   r   r   r   r      s   r   c               @   sT   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd ZdS )EmbeddingTestsc             C   s,   x&|   D ]}|d }| |jd q
W d S )Nr   0)rD   r+   id)r   runrC   r   r   r   test_subinterps_mainx   s    z#EmbeddingTests.test_subinterps_mainc             C   s\   xV|   D ]J}|^}}}t|j}x.t|D ]"\}}| |jt|| d  q.W q
W d S )Nr3   )rD   intrJ   	enumerater+   str)r   rK   rC   subs_Zmainidisubr   r   r   test_subinterps_different_ids~   s
    
z,EmbeddingTests.test_subinterps_different_idsc             C   sr   xl|   D ]`}|^}}}d|kr,tdx<|D ]4}| |j|j | |j|j | |j|j q2W q
W d S )NZ0x0zplatform prints pointers as 0x0)rD   unittestSkipTestassertNotEqualr>   r?   r@   )r   rK   rC   rP   rQ   rS   r   r   r   test_subinterps_distinct_state   s    

z-EmbeddingTests.test_subinterps_distinct_statec             C   s   t tjdd}| jd|d\}}tjdkr@t  t| t| d}d}dd	d
dddddd
ddddddddddddddddg}|j|||d}d | _	| 
| | d S )Nzutf-8:surrogateescape)ZPYTHONIOENCODINGZforced_io_encoding)r   r3   zutf-8surrogateescape
z--- Use defaults ---zExpected encoding: defaultzExpected errors: defaultzstdin: {in_encoding}:{errors}zstdout: {out_encoding}:{errors}z'stderr: {out_encoding}:backslashreplacez--- Set errors only ---zExpected errors: ignorezstdin: {in_encoding}:ignorezstdout: {out_encoding}:ignorez--- Set encoding only ---zExpected encoding: latin-1zstdin: latin-1:{errors}zstdout: latin-1:{errors}z stderr: latin-1:backslashreplacez--- Set encoding and errors ---zExpected errors: replacezstdin: latin-1:replacezstdout: latin-1:replace)Zin_encodingZout_encodingerrors)dictr   r#   r1   r   r)   r*   r   r6   maxDiffr+   strip)r   r   r/   r0   Zexpected_stream_encodingZexpected_errorsexpected_outputr   r   r   test_forced_io_encoding   sN    
z&EmbeddingTests.test_forced_io_encodingc             C   sp   t tjtjtjd}| jd|d\}}tr6| j	}ntjt
 d}d| d}| || | |d dS )	z
        Checks some key parts of the C-API that need to work before the runtine
        is initialized (via Py_Initialize()).
        )
PYTHONPATHZpre_initialization_api)r   Zspamzsys.executable: rZ   r   N)r\   r   r#   pathsepr   r   r   r1   r   r   r   assertInr+   )r   r   r/   r0   Zexpected_pathr_   r   r   r   test_pre_initialization_api   s    z*EmbeddingTests.test_pre_initialization_apic             C   sJ   t tjtjtjd}| jd|d\}}d}| || | 	|d dS )z
        Checks that sys.warnoptions and sys._xoptions can be set before the
        runtime is initialized (otherwise they won't be effective).
        )ra   Zpre_initialization_sys_options)r   zsys.warnoptions: ['once', 'module', 'default']
sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}
warnings.filters[:3]: ['default', 'module', 'once']
r   N)
r\   r   r#   rb   r   r   r   r1   rc   r+   )r   r   r/   r0   r_   r   r   r   #test_pre_initialization_sys_options   s    z2EmbeddingTests.test_pre_initialization_sys_optionsc             C   s*   |  d\}}| |d | |d dS )z
        bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
        calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
        call PyEval_InitThreads() for us in this case.
        Zbpo20891r   N)r1   r+   )r   r/   r0   r   r   r   test_bpo20891   s    zEmbeddingTests.test_bpo20891c             C   s*   |  d\}}| |d | |d dS )zf
        bpo-33932: Calling Py_Initialize() twice should do nothing (and not
        crash!).
        Zinitialize_twicer   N)r1   r+   )r   r/   r0   r   r   r   test_initialize_twice   s    z$EmbeddingTests.test_initialize_twicec             C   s.   |  d\}}| | d | |d dS )zS
        bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
        Zinitialize_pymainz6Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']r   N)r1   r+   rstrip)r   r/   r0   r   r   r   test_initialize_pymain   s    z%EmbeddingTests.test_initialize_pymainN)rE   rF   rG   rL   rT   rX   r`   rd   re   rf   rg   ri   r   r   r   r   rH   w   s   +
	rH   c               @   s  e Zd ZdZerdndZdZe Zdddddddddddddddddg dg g ddeeeedd	Z	d
Z
dZdZdddeeddddddddddddZereddd ddgZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( ZdS ))InitConfigTestsi   surrogatepassrY   )Zdll_pathr   Zmodule_search_pathsr3   r   Nz./_testembed)install_signal_handlersignore_environmentuse_hash_seed	hash_seed	allocatordev_modefaulthandlertracemallocimport_timeshow_ref_countshow_alloc_countZ	dump_refsmalloc_stats	utf8_modeZcoerce_c_localeZcoerce_c_locale_warnprogram_nameargvprogramxoptionswarnoptionsZmodule_search_path_envhomeprefixbase_prefixexec_prefixbase_exec_prefixZ_disable_importlib)Zmodule_search_path)rz   r   r   r   r   rl   r   r}   )ZPy_HasFileSystemDefaultEncoding)Py_BytesWarningFlagZPy_DebugFlagPy_DontWriteBytecodeFlag Py_FileSystemDefaultEncodeErrorsPy_FileSystemDefaultEncodingPy_FrozenFlagZPy_HashRandomizationFlagPy_InspectFlagPy_InteractiveFlagPy_IsolatedFlagPy_NoSiteFlagPy_NoUserSiteDirectoryPy_OptimizeFlagPy_QuietFlagPy_UnbufferedStdioFlagPy_VerboseFlag)ZPy_LegacyWindowsFSEncodingFlagZPy_LegacyWindowsStdioFlag)ZPy_IgnoreEnvironmentFlagrm   )ZPy_UTF8Moderx   c             C   s@   i }x6|D ].}d|kr0| dd\}}|||< q
d||< q
W |S )N=r3   T)split)r   Zxoptions_listr|   optkeyvaluer   r   r   main_xoptionsj  s    

zInitConfigTests.main_xoptionsc             C   sh   |d }|d }x| j D ]
}||= qW i }x| jD ]}|| ||< q2W | |d |d< | || d S )Ncore_configmain_configr|   )UNTESTED_MAIN_CONFIGCOPY_MAIN_CONFIGr   r+   )r   configr   r   r   expectedr   r   r   check_main_configt  s    
z!InitConfigTests.check_main_configc             C   s   t | jf|}t | jf|}td}tjdd|f}t |}|d sTd|d< d|d< tj||tj	tj
d}|jrtd	|jd
|j|jd}t|}x*| D ]\}	}
|
| jkr||	 ||	< qW x*| D ]\}	}
|
| jkr||	 ||	< qW ||fS )Na[  
            import json
            import sys

            data = {
                'prefix': sys.prefix,
                'base_prefix': sys.base_prefix,
                'exec_prefix': sys.exec_prefix,
                'base_exec_prefix': sys.base_exec_prefix,
                'Py_FileSystemDefaultEncoding': sys.getfilesystemencoding(),
                'Py_FileSystemDefaultEncodeErrors': sys.getfilesystemencodeerrors(),
            }

            data = json.dumps(data)
            data = data.encode('utf-8')
            sys.stdout.buffer.write(data)
            sys.stdout.buffer.flush()
        z-Sz-cr   rI   PYTHONCOERCECLOCALE
PYTHONUTF8)r   r   r   z)failed to get the default config: stdout=z stderr=zutf-8)r\   DEFAULT_CORE_CONFIGDEFAULT_GLOBAL_CONFIGtextwrapdedentr   r   r$   rK   r&   STDOUTr(   	Exceptionr   r   decodejsonloadsitemsGET_DEFAULT_CONFIG)r   expected_coreexpected_globalr   coder,   procr   r   r   r   r   r   r   get_expected_config  s.    



z#InitConfigTests.get_expected_configc             C   s8   t |d }x| jD ]}||d  qW | || d S )Nr   )r\   UNTESTED_CORE_CONFIGpopr+   )r   r   r   r   r   r   r   r   check_core_config  s    z!InitConfigTests.check_core_configc             C   s   |d }xN| j D ]D}t|dkr@|\}}}|| r6dnd||< q|\}}|| ||< qW t|d }	x| jD ]
}
|	|
= qlW | |	| d S )Nr      r   r3   global_config)COPY_GLOBAL_CONFIGr7   r\   UNTESTED_GLOBAL_CONFIGr+   )r   r   r   r   r   itemZ
global_keyZcore_keyZoppositer   r   r   r   r   check_global_config  s    

z#InitConfigTests.check_global_configc       	      C   s   t tj}x t|D ]}|dr||= qW d|d< d|d< | j||d\}}t|}| |||\}}| 	|| | 
| | ||| d S )NPYTHONrI   r   r   )r   )r\   r   r#   list
startswithr1   r   r   r   r   r   r   )	r   testnamer   r   r   r   r/   r0   r   r   r   r   check_config  s    




zInitConfigTests.check_configc             C   s   |  di i  d S )NZinit_default_config)r   )r   r   r   r   test_init_default_config  s    z(InitConfigTests.test_init_default_configc             C   s>   ddd}dd| j ddddddddddd}| d|| d S )Nz./globalvarr3   )ry   rx   zutf-8   )r   r   r   r   r   r   r   r   r   r   r   r   r   Zinit_global_config)UTF8_MODE_ERRORSr   )r   r   r   r   r   r   test_init_global_config  s     z'InitConfigTests.test_init_global_configc             C   sT   dddddddddddddgd	d
ddgddgdd}| j ddd}| d|| d S )Nr   r3   {   malloc_debugr   z./conf_program_namez-cpassZconf_programzcore_xoption1=3zcore_xoption2=Zcore_xoption3defaultzerror::ResourceWarning)rl   rn   ro   rp   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   rr   zutf-8)r   r   r   Zinit_from_config)r   r   )r   r   r   r   r   r   test_init_from_config  s(    z%InitConfigTests.test_init_from_configc          
   C   sB   dddddddddd	}d| j ddddddd}| d|| d S )	Nr3   *   r   r   )	rn   ro   rp   rs   rt   rw   rx   rr   rq   zutf-8)r   r   r   r   r   r   r   r   Zinit_env)r   r   )r   r   r   r   r   r   test_init_env  s$    zInitConfigTests.test_init_envc             C   s   dddd}|  d|i  d S )Nr3   debug)rq   rr   rp   Zinit_dev_mode)r   )r   r   r   r   r   test_init_dev_mode)  s    z"InitConfigTests.test_init_dev_modec             C   s$   ddi}ddd}|  d|| d S )Nrm   r3   )r   r   Zinit_isolated)r   )r   r   r   r   r   r   test_init_isolated1  s    z"InitConfigTests.test_init_isolated)rE   rF   rG   r]   r   r   r   objectr   r   r   r   r   r   updater   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj     s   

/rj   __main__)testr   rU   collectionsr   r   r   r9   r$   r   r   namer   r   TestCaserH   rj   rE   rC   r   r   r   r   <module>   s"   
f   =