B
    u9aˆ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r e ¡  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ÚexistsZskipTestÚgetcwdÚoldcwdÚchdir)ÚselfÚhereZbasepathZexenameZextZexepathZexe© r   ú /usr/lib/python3.7/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rœtjrœt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ÚstderrZuniversal_newlinesr   r   z--- z failed ---zstdout:
zstderr:
z------zbad returncode %d, stderr is %r)r   Úextendr   Úcopyr   ÚenvironÚ
subprocessÚPopenÚPIPEZ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rÆt|	ƒ |  |	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 {} ---é   é   )r-   r'   r   Ú
splitlinesÚformatÚlenr   r%   r&   Z
assertLessÚreÚmatchZassertRegexÚgroupsZ
assertTrueÚinterpÚtstateÚmodulesÚappend)r   r+   r,   Z
interp_patr.   ZnumloopsZcurrent_runÚliner5   r7   Úmainr   r   r   Ú%run_repeated_init_and_subinterpretersC   s:    



z9EmbeddingTestsMixin.run_repeated_init_and_subinterpreters)Ú__name__Ú
__module__Ú__qualname__r   r   r-   r=   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)r=   r'   Úid)r   Úrunr<   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 )Nr/   )r=   ÚintrC   Ú	enumerater'   Ústr)r   rD   r<   Ú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)r=   ÚunittestZSkipTestZassertNotEqualr7   r8   r9   )r   rD   r<   rI   rJ   rL   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   r/   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    r-   r   r%   r&   r   r2   ÚmaxDiffr'   Ústrip)r   r   r+   r,   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: rQ   r   N)rS   r   r    Úpathsepr   r   r   r-   r   r   r   ÚassertInr'   )r   r   r+   r,   Zexpected_pathrV   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).
        )rX   Zpre_initialization_sys_options)r   z¤sys.warnoptions: ['once', 'module', 'default']
sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}
warnings.filters[:3]: ['default', 'module', 'once']
r   N)
rS   r   r    rY   r   r   r   r-   rZ   r'   )r   r   r+   r,   rV   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)r-   r'   )r   r+   r,   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)r-   r'   )r   r+   r,   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)r-   r'   Úrstrip)r   r+   r,   r   r   r   Útest_initialize_pymainø   s    z%EmbeddingTests.test_initialize_pymainN)r>   r?   r@   rE   rM   rO   rW   r[   r\   r]   r^   r`   r   r   r   r   rA   w   s   +
	rA   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r¦e 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   ÚsurrogatepassrP   )Zdll_pathr   Zmodule_search_pathsr/   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)rq   ry   rw   rx   r   rc   rv   rt   )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_IgnoreEnvironmentFlagrd   )ZPy_UTF8Modero   c             C   s@   i }x6|D ].}d|kr0|  dd¡\}}|||< q
d||< q
W |S )Nú=r/   T)Úsplit)r   Zxoptions_listrs   Ú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_configrs   )Ú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rˆtd	|j›d
|j›ƒ‚|j d¡}t |¡}x*| ¡ D ]\}	}
|
| jkr¨||	 ||	< q¨W x*| ¡ D ]\}	}
|
| jkrÔ||	 ||	< qÔW ||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   rB   ÚPYTHONCOERCECLOCALEÚ
PYTHONUTF8)r   r   r   z)failed to get the default config: stdout=z stderr=zutf-8)rS   ÚDEFAULT_CORE_CONFIGÚDEFAULT_GLOBAL_CONFIGÚtextwrapÚdedentr   r   r!   rD   r#   Z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Ž   )rS   Ú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   r/   Úglobal_config)ÚCOPY_GLOBAL_CONFIGr3   rS   Ú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 )NZPYTHONrB   r•   r–   )r   )rS   r   r    ÚlistÚ
startswithr-   r   rž   r¥   r¨   r”   r®   )	r   Ztestnamer¡   r¢   r   r‹   r+   r,   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./globalvarr/   )rp   ro   zutf-8é   )rz   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   r/   é{   Úmalloc_debugr³   z./conf_program_namez-cÚpassZconf_programzcore_xoption1=3zcore_xoption2=Zcore_xoption3Údefaultzerror::ResourceWarning)rc   re   rf   rg   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ri   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 )	Nr/   é*   r·   r³   )	re   rf   rg   rj   rk   rn   ro   ri   rh   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 )Nr/   Údebug)rh   ri   rg   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 )Nrd   r/   )r   rƒ   Zinit_isolated)r±   )r   rŽ   rª   r   r   r   Útest_init_isolated1  s    z"InitConfigTests.test_init_isolated)r>   r?   r@   rT   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   ra     sŠ   

/ra   Ú__main__)Ztestr   rN   Úcollectionsr   r   r   r4   r!   r   r™   Únamer   r   ZTestCaserA   ra   r>   r<   r   r   r   r   Ú<module>   s"   
f   =