o
    g                     @   s  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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Z d dlmZ d dlmZ d dlmZmZ zd dlZW n eyq   dZY nw ed	Zd dlZee
d
Z dd Z!dd Z"G dd dZ#G dd dej$Z%G dd dej$Z&G dd dej$Z'G dd dej$Z(G dd dej$Z)G dd dej$Z*G dd dej$Z+G dd  d e+Z,e-e. d!G d"d# d#e+Z/e-e d$G d%d& d&e+Z0G d'd( d(ej$Z1e2d)kre3  dS dS )*    )OrderedDictN)support)MISSING_C_DOCSTRINGS)import_helper)threading_helper)warnings_helper)assert_python_failureassert_python_ok	_testcapiZgettotalrefcountc                 C   s   |  ddddS )Nzutf-8replace )decoder   )err r   D/Users/admin/.pyenv/versions/3.10.0/lib/python3.10/test/test_capi.pydecode_stderr&      r   c                 C   s   | S )zsome docNr   selfr   r   r   testfunction*   s   r   c                   @   s    e Zd ZeeZeeZdS )InstanceMethodN)__name__
__module____qualname__r
   Zinstancemethodidr   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ee	d	d
d Z
ee	d	dd Zeed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eeed#d$d%d& Zd'd( Zed)d*d+ Zed)d,d- Zd.d/ Z d0d1 Z!d2d3 Z"d4d5 Z#d6d7 Z$d8d9 Z%d:d; Z&d<d= Z'd>d? Z(d@dA Z)dBdC Z*dDdE Z+dFdG Z,dTdIdJZ-dKdL Z.dMdN Z/dOdP Z0dQdR Z1dSS )UCAPITestc                 C   s~   t  }| t||  | | |u  | |jjtj | t jjtj dt j_| tjd | tt	|jdd d S )Ntest	attribute)
r   assertEqualr   
assertTruer   __doc__r   assertRaisesAttributeErrorsetattrr   instr   r   r   test_instancemethod5   s   zCAPITest.test_instancemethodc                 C   sv   t   tjtjddgtjtjd}W d    n1 sw   Y  | \}}| |d | 	|
 d| d S )N-cz4import _testcapi;_testcapi.crash_no_current_thread())stdoutstderr    s   Fatal Python error: PyThreadState_Get: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL))r   SuppressCrashReport
subprocessPopensys
executablePIPEcommunicater   r    rstrip
startswith)r   poutr   r   r   r    test_no_FatalError_infinite_loop@   s   

z)CAPITest.test_no_FatalError_infinite_loopc                 C   s   |  ttj d S N)r"   
ValueErrorr
   Z!make_memoryview_from_NULL_pointerr   r   r   r   !test_memoryview_from_NULL_pointerR      z*CAPITest.test_memoryview_from_NULL_pointerc           
   
   C   s   t d}td}z| t yg } zQ|j}t }t|j|d }t }tj| }t }	| |d | | 	||j||f | 	|| | 	|	| | 	||j|d f | 	|| W Y d }~d S d }~ww )N5ZTEST   F)r9   	TypeError__traceback__r/   exc_infor
   Zset_exc_info	__class__r   ZassertSequenceEqualr    )
r   Zraised_exceptionnew_excetbZorig_sys_exc_infoZorig_exc_infoZnew_sys_exc_infoZnew_exc_infoZreset_sys_exc_infor   r   r   test_exc_infoU   s&   
zCAPITest.test_exc_infoz(_posixsubprocess required for this test.c                 C   s   G dd dt }| ttjd| dddddd	d
dddddddddddd G dd dt }| ttjd| dddddd	d
dddddddddddd d S )Nc                   @      e Zd Zdd ZdS )1CAPITest.test_seq_bytes_to_charp_array.<locals>.Zc                 S      dS Nr=   r   r   r   r   r   __len__p      9CAPITest.test_seq_bytes_to_charp_array.<locals>.Z.__len__Nr   r   r   rJ   r   r   r   r   Zo       rN   r=      r=                  	   
                                    c                   @   s   e Zd Zdd Zdd ZdS )rG   c                 S   s   t jS r8   )r/   maxsizer   r   r   r   rJ   v   s   rL   c                 S   rH   )N   xr   )r   ir   r   r   __getitem__x   rK   z=CAPITest.test_seq_bytes_to_charp_array.<locals>.Z.__getitem__N)r   r   r   rJ   rg   r   r   r   r   rN   u   s    )objectr"   r>   _posixsubprocess	fork_execMemoryErrorr   rN   r   r   r   test_seq_bytes_to_charp_arrayl   s   
,
,z&CAPITest.test_seq_bytes_to_charp_arrayc                 C   sP   G dd dt }| ttj| dgdddddd	d
dddddddddddd d S )Nc                   @   rF   )z-CAPITest.test_subprocess_fork_exec.<locals>.Zc                 S   rH   rI   r   r   r   r   r   rJ      rK   z5CAPITest.test_subprocess_fork_exec.<locals>.Z.__len__NrM   r   r   r   r   rN      rO   rN      1rP   rQ   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   )rh   r"   r>   ri   rj   rl   r   r   r   test_subprocess_fork_exec}   s   
.z"CAPITest.test_subprocess_fork_execz6Signature information for builtins requires docstringsc                 C   s  |  tjjd  |  tjjd  |  tjjd  |  tjjd  |  tjjd |  tjjd  |  tjjd |  tjjd  |  tjjd |  tjjd  |  tj	jd |  tj	jd |  tj
jd  |  tj
jd |  tjjd |  tjjd d S )Nz This docstring has no signature.z[docstring_with_invalid_signature($module, /, boo)

This docstring has an invalid signature.zedocstring_with_invalid_signature2($module, /, boo)

--

This docstring also has an invalid signature.z%This docstring has a valid signature.z($module, /, sig)z>
This docstring has a valid signature and some extra newlines.z($module, /, parameter))r   r
   Zno_docstringr!   __text_signature__Zdocstring_emptyZdocstring_no_signatureZ docstring_with_invalid_signatureZ!docstring_with_invalid_signature2Zdocstring_with_signatureZ#docstring_with_signature_but_no_docZ+docstring_with_signature_and_extra_newlinesr   r   r   r    test_docstring_signature_parsing   s<   






z)CAPITest.test_docstring_signature_parsingc                 C   s   t j}| }| }| || d||f | |d d|df | d| dd|f |}|| }| |d||f |}|d }| |d|df d}|| }| |dd|f d S )Nmatmul*   imatmul)r
   Z
matmulTyper   )r   MZm1Zm2or   r   r   &test_c_type_with_matrix_multiplication   s   z/CAPITest.test_c_type_with_matrix_multiplicationc                 C   s2   t  }| |dd | |ddd d S )Nr=   )r=   NrR   )rR   rR   )r
   ZipowTyper   __ipow__)r   rv   r   r   r   test_c_type_with_ipow   s   zCAPITest.test_c_type_with_ipowc                 C   ~   t rtd}td|\}}}t|}| |d d S | t}t	  W d    n1 s/w   Y  | t
|jd d S )Nz
                import _testcapi
                from test import support

                with support.SuppressCrashReport():
                    _testcapi.return_null_without_error()
            r(   a#  Fatal Python error: _Py_CheckFunctionResult: a function returned NULL without setting an exception\nPython runtime state: initialized\nSystemError: <built-in function return_null_without_error> returned NULL without setting an exception\n\nCurrent thread.*:\n  File .*", line 6 in <module>\nzFreturn_null_without_error.* returned NULL without setting an exception)Py_DEBUGtextwrapdedentr   r   assertRegexr"   SystemErrorr
   Zreturn_null_without_errorstr	exceptionr   codercr6   r   cmr   r   r   test_return_null_without_error   s   


z'CAPITest.test_return_null_without_errorc                 C   rz   )Nz
                import _testcapi
                from test import support

                with support.SuppressCrashReport():
                    _testcapi.return_result_with_error()
            r(   aq  Fatal Python error: _Py_CheckFunctionResult: a function returned a result with an exception set\nPython runtime state: initialized\nValueError\n\nThe above exception was the direct cause of the following exception:\n\nSystemError: <built-in function return_result_with_error> returned a result with an exception set\n\nCurrent thread.*:\n  File .*, line 6 in <module>\nzBreturn_result_with_error.* returned a result with an exception set)r{   r|   r}   r   r   r~   r"   r   r
   Zreturn_result_with_errorr   r   r   r   r   r   test_return_result_with_error   s   

z&CAPITest.test_return_result_with_errorc                 C   sJ   t d}td|\}}}t|}d|vr| |d d S | d| d S )Nz
            import _testcapi
            from test import support

            with support.SuppressCrashReport():
                _testcapi.getitem_with_error({1: 2}, 1)
        r(   zSystemError: a  Fatal Python error: _Py_CheckSlotResult: Slot __getitem__ of type dict succeeded with an exception set\nPython runtime state: initialized\nValueError: bug\n\nCurrent thread .* \(most recent call first\):\n  File .*, line 6 in <module>\n\nExtension modules: _testcapi \(total: 1\)\nz'returned a result with an exception set)r|   r}   r   r   r~   assertInr   r   r   r6   r   r   r   r   test_getitem_with_error	  s   
z CAPITest.test_getitem_with_errorc                 C      t   d S r8   )r
   test_buildvalue_Nr   r   r   r   r   '  s   zCAPITest.test_buildvalue_Nc                 C   s<   d}t d|\}}}| d| | d| | d| d S )Na*  if 1:
            import _testcapi

            class C(): pass

            # The first loop tests both functions and that remove_mem_hooks()
            # can be called twice in a row. The second loop checks a call to
            # set_nomemory() after a call to remove_mem_hooks(). The third
            # loop checks the start and stop arguments of set_nomemory().
            for outer_cnt in range(1, 4):
                start = 10 * outer_cnt
                for j in range(100):
                    if j == 0:
                        if outer_cnt != 3:
                            _testcapi.set_nomemory(start)
                        else:
                            _testcapi.set_nomemory(start, start + 1)
                    try:
                        C()
                    except MemoryError as e:
                        if outer_cnt != 3:
                            _testcapi.remove_mem_hooks()
                        print('MemoryError', outer_cnt, j)
                        _testcapi.remove_mem_hooks()
                        break
        r(   s   MemoryError 1 10s   MemoryError 2 20s   MemoryError 3 30)r	   r   r   r   r   r   test_set_nomemory*  s
   zCAPITest.test_set_nomemoryc              	   C   s   G dd dt }G dd dt }dddd}i t | | |t|||||fD ])}| t|t|  | t|t|  | t	|t|
  q)d S )	Nc                       4   e Zd Z fddZ fddZ fddZ  ZS )z9CAPITest.test_mapping_keys_values_items.<locals>.Mapping1c                       t t  S r8   )listsuperkeysr   rA   r   r   r   L     z>CAPITest.test_mapping_keys_values_items.<locals>.Mapping1.keysc                    r   r8   )r   r   valuesr   r   r   r   r   N  r   z@CAPITest.test_mapping_keys_values_items.<locals>.Mapping1.valuesc                    r   r8   )r   r   itemsr   r   r   r   r   P  r   z?CAPITest.test_mapping_keys_values_items.<locals>.Mapping1.itemsr   r   r   r   r   r   __classcell__r   r   r   r   Mapping1K      r   c                       r   )z9CAPITest.test_mapping_keys_values_items.<locals>.Mapping2c                    r   r8   )tupler   r   r   r   r   r   r   S  r   z>CAPITest.test_mapping_keys_values_items.<locals>.Mapping2.keysc                    r   r8   )r   r   r   r   r   r   r   r   U  r   z@CAPITest.test_mapping_keys_values_items.<locals>.Mapping2.valuesc                    r   r8   )r   r   r   r   r   r   r   r   W  r   z?CAPITest.test_mapping_keys_values_items.<locals>.Mapping2.itemsr   r   r   r   r   Mapping2R  r   r   r=   rR   rP   )fooZbarZspam)dictr   ZassertListEqualr
   get_mapping_keysr   r   get_mapping_valuesr   get_mapping_itemsr   )r   r   r   Zdict_objmappingr   r   r   test_mapping_keys_values_itemsJ  s"   


z'CAPITest.test_mapping_keys_values_itemsc                 C   sx   |  ttjd  |  ttjd  |  ttjd  G dd d}| }|  ttj| |  ttj| |  ttj| d S )Nc                   @   $   e Zd Zdd Zdd Zdd ZdS )zCCAPITest.test_mapping_keys_values_items_bad_arg.<locals>.BadMappingc                 S      d S r8   r   r   r   r   r   r   k  rK   zHCAPITest.test_mapping_keys_values_items_bad_arg.<locals>.BadMapping.keysc                 S   r   r8   r   r   r   r   r   r   m  rK   zJCAPITest.test_mapping_keys_values_items_bad_arg.<locals>.BadMapping.valuesc                 S   r   r8   r   r   r   r   r   r   o  rK   zICAPITest.test_mapping_keys_values_items_bad_arg.<locals>.BadMapping.itemsN)r   r   r   r   r   r   r   r   r   r   
BadMappingj  s    r   )r"   r#   r
   r   r   r   r>   )r   r   Zbad_mappingr   r   r   &test_mapping_keys_values_items_bad_arge  s   z/CAPITest.test_mapping_keys_values_items_bad_argZnegative_refcountz need _testcapi.negative_refcountc                 C   s*   t d}td|\}}}| |d d S )Nz
            import _testcapi
            from test import support

            with support.SuppressCrashReport():
                _testcapi.negative_refcount()
        r(   s`   _testcapimodule\.c:[0-9]+: _Py_NegativeRefcount: Assertion failed: object has negative ref count)r|   r}   r   r~   r   r   r   r   test_negative_refcountv  s
   
zCAPITest.test_negative_refcountc                 C   s,   ddl m} d }tdD ]}||f}qd S )Nr   MyList  )r
   r   range)r   r   Lrf   r   r   r   test_trashcan_subclass  s
   zCAPITest.test_trashcan_subclassZcpuc                 C   s   |  t d S r8   )do_test_trashcan_python_classr   r   r   r   r   test_trashcan_python_class1  s   z$CAPITest.test_trashcan_python_class1c                 C   s   ddl m} | | d S )Nr   r   )r
   r   r   )r   r   r   r   r   test_trashcan_python_class2  s   z$CAPITest.test_trashcan_python_class2c                 C   sh   G dd d|}dD ]'}d }t dD ]
}||f}||_q|r"|f}| |jd ~| |jd q
d S )Nc                       s,   e Zd ZdZ fddZ fddZ  ZS )z6CAPITest.do_test_trashcan_python_class.<locals>.PyListr   c                    s     j d7  _ t j|  d S rI   )numr   __init__)r   argsr   r   r   r     s   z?CAPITest.do_test_trashcan_python_class.<locals>.PyList.__init__c                    s     j d8  _ d S rI   )r   r   r   r   r   __del__  r;   z>CAPITest.do_test_trashcan_python_class.<locals>.PyList.__del__)r   r   r   r   r   r   r   r   r   r   r   PyList  s    r   )r   r=   i   r   )r   attrZassertGreaterr   r   )r   baser   Zparityr   rf   r   r   r   r     s   

z&CAPITest.do_test_trashcan_python_classc                 C   s$   |  tjjd |  tjjd d S )NZsomedocz(arg1, arg2))r   r
   ZHeapDocCTyper!   rp   r   r   r   r   &test_heap_ctype_doc_and_text_signature  s   z/CAPITest.test_heap_ctype_doc_and_text_signaturec                 C   s   |  tjjd  d S r8   )r   r
   ZNullTpDocTyper!   r   r   r   r   test_null_type_doc  r   zCAPITest.test_null_type_docc                 C   sZ   G dd dt j}| }t|}| |jd | |jd ~| |d t| d S )Nc                          e Zd Z fddZ  ZS )z`CAPITest.test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once.<locals>.HeapGcCTypeSubclassc                       d| _ t   d S Nrb   value2r   r   r   r   r   r   r        ziCAPITest.test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once.<locals>.HeapGcCTypeSubclass.__init__r   r   r   r   r   r   r   r   r   HeapGcCTypeSubclass      r   rX   rb   r=   )r
   HeapGcCTyper/   getrefcountr   valuer   )r   r   subclass_instancetype_refcntr   r   r   :test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once  s   
zCCAPITest.test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_oncec                    s   G dd dt j G  fddd  }t}t }| |jd | |jd ~| |d j | |d  j | |d t | |t  d S )Nc                       r   )zdCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once.<locals>.Ac                    r   r   r   r   r   r   r   r     r   zmCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once.<locals>.A.__init__r   r   r   r   r   A  r   r   c                       s*   e Zd Z fddZfddZ  ZS )zdCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once.<locals>.Bc                    s   t    d S r8   )r   r   r   r   r   r   r     r   zmCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once.<locals>.B.__init__c                    s"    | _ t  _t_d S r8   )rA   r/   r   refcnt_in_delr   r   Br   r   r     s   zlCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once.<locals>.B.__del__)r   r   r   r   r   r   r   r   r   r   r     s    r   rX   rb   r=   )r
   r   r/   r   r   r   r   r   r   r   r   Znew_type_refcntr   r   r   Ptest_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once  s   	

zYCAPITest.test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_oncec                 C   X   t  }d|_| |jd | |j|j | |jddi t  }| i |j d S Nrs   r   )r
   ZHeapCTypeWithDictr   r   dictobj__dict__r%   r   r   r   test_heaptype_with_dict     z CAPITest.test_heaptype_with_dictc                 C   r   r   )r
   ZHeapCTypeWithNegativeDictr   r   r   r   r%   r   r   r    test_heaptype_with_negative_dict  r   z)CAPITest.test_heaptype_with_negative_dictc                 C   s2   t  }t|}| | | | |j| d S r8   )r
   ZHeapCTypeWithWeakrefweakrefrefr   Zweakreflist)r   r&   r   r   r   r   test_heaptype_with_weakref  s   
z#CAPITest.test_heaptype_with_weakrefc                 C   s    t  }t|}| |d d S )Ns   1234)r
   ZHeapCTypeWithBufferbytesr   )r   r&   br   r   r   test_heaptype_with_buffer
  s   z"CAPITest.test_heaptype_with_bufferc                 C   sN   t  }tt j}| |jd | |jd ~| |d tt j d S NrX   rb   r=   )r
   HeapCTypeSubclassr/   r   r   r   r   )r   r   r   r   r   r   9test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once  s   zBCAPITest.test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_oncec                 C   s   t  }tt j}tt j}| |jd | |jd ~| |d t jj | |d t jj | |d tt j | |tt j d S r   )	r
   ZHeapCTypeSubclassWithFinalizerr/   r   r   r   r   r   r   r   r   r   r   Otest_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once  s   zXCAPITest.test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_oncec                 C   s@   t  }| |jd d|_| |jd |`| |jd d S )NrX   rZ   r   )r
   ZHeapCTypeSetattrr   Zpvaluer   )r   objr   r   r   test_heaptype_with_setattro1  s   z$CAPITest.test_heaptype_with_setattroc                 C   s   ddl m} | |ddd | |ddd | |ddd	 | |dd
d | |ddd | |ddd | |ddd | |dd
d | t|dd | t|d	d | t|dd d S )Nr   )pynumber_tobase{   rR   Z	0b1111011rV   Z0o173rX   123r^   Z0x7biz
-0b1111011z-0o173z-123z-0x7bg     ^@)r
   r   r   r"   r>   r   )r   r   r   r   r   test_pynumber_tobase9  s   zCAPITest.test_pynumber_tobaser   c                 C   s   t   tdd|\}}}W d    n1 sw   Y  t|}| d| td|tj}|s9| d| t	|
d d}t|
d}	|D ]}
| |
| qN|D ]}
| |
| qY| t||	 d S )	Nz-sSIr(   z.Fatal Python error: test_fatal_error: MESSAGE
z,^Extension modules:(.*) \(total: ([0-9]+)\)$z$Cannot find 'Extension modules:' in r=   z, rR   )r   r,   r   r   r   research	MULTILINEZfailsetgroupstripsplitintZassertNotInr   len)r   r   expectednot_expectedr   r6   r   matchmodulestotalnamer   r   r   check_fatal_errorG  s&   
zCAPITest.check_fatal_errorc                 C   s<   d}d}d}|  ||| d}d}td}|  || d S )N)r
   )r/   z8import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")z
            import _testcapi, sys
            sys.stdlib_module_names = frozenset({"_testcapi"})
            _testcapi.fatal_error(b"MESSAGE")
        )r   r|   r}   )r   r   r   r   r   r   r   test_fatal_error\  s   
zCAPITest.test_fatal_errorc                 C      t  }| |d d S Nz<NULL>)r
   Zpyobject_repr_from_nullr   r   sr   r   r   test_pyobject_repr_from_nulln     z%CAPITest.test_pyobject_repr_from_nullc                 C   r   r   )r
   Zpyobject_str_from_nullr   r   r   r   r   test_pyobject_str_from_nullr  r   z$CAPITest.test_pyobject_str_from_nullc                 C   r   )Ns   <NULL>)r
   Zpyobject_bytes_from_nullr   r   r   r   r   test_pyobject_bytes_from_nullv  r   z&CAPITest.test_pyobject_bytes_from_nullN)r   )2r   r   r   r'   r7   r:   rE   unittest
skipUnlessri   rm   ro   ZskipIfr   rq   rw   ry   r   r   r   r   r   r   r   hasattrr
   r   r   r   Zrequires_resourcer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   3   sb    



	
)" 


#


r   c                   @   s6   e Zd Zdd ZdddZdd Zdd	 Zd
d ZdS )TestPendingCallsc                    s>    fdd}t |D ]}tt d  	 t|rq
qd S )Nc                      s     d  d S r8   )appendr   lr   r   callback~  s   z6TestPendingCalls.pendingcalls_submit.<locals>.callbackg{Gz?T)r   timesleeprandomr
   Z_pending_threadfunc)r   r  nr  rf   r   r  r   pendingcalls_submit}  s   
z$TestPendingCalls.pendingcalls_submitNc                 C   sl   d}t ||kr4	 tdD ]}|| }q|r|j sq|d7 }| |dk d|t |f  t ||ksd S )Nr   Fz(%i)r   r=   i'  z(timeout waiting for %i callbacks, got %i)r   r   verboseprintr   eventis_setr    )r   r  r  contextcountrf   ar   r   r   pendingcalls_wait  s   

z"TestPendingCalls.pendingcalls_waitc                    s   d}g }G dd dt }|  g  _d _| j  _d _t  _t  _	 fddt
 jD }t|  j|  W d    d S 1 sNw   Y  d S )N    c                   @      e Zd ZdS )z8TestPendingCalls.test_pendingcalls_threaded.<locals>.fooNr   r   r   r   r   r   r   r     s    r   rR   r   c                    s   g | ]}t jj fd qS ))targetr   )	threadingThreadpendingcalls_thread).0rf   r  r   r   r   
<listcomp>  s
    
z?TestPendingCalls.test_pendingcalls_threaded.<locals>.<listcomp>)rh   r  r  nThreads	nFinishedr  LocklockEventr  r   r   Zstart_threadsr  )r   r  threadsr   r   r  r   test_pendingcalls_threaded  s    

"z+TestPendingCalls.test_pendingcalls_threadedc                 C   s   z5|  |j|j W |j | jd7  _|j}	 W d    n1 s#w   Y  ||jkr4|j	
  d S d S |j | jd7  _|j}	 W d    n1 sOw   Y  ||jkr_|j	
  w w )Nr=   Fzfinished threads: )r  r  r  r"  r   r   r  r  r  r  r   )r   r  r   r   r   r   r    s$   

z$TestPendingCalls.pendingcalls_threadc                 C   s$   g }d}|  || | || d S )N@   )r  r  )r   r  r  r   r   r   test_pendingcalls_non_threaded  s   z/TestPendingCalls.test_pendingcalls_non_threadedr8   )r   r   r   r  r  r%  r  r'  r   r   r   r   r  {  s    
r  c                   @   r   )SubinterpreterTestc                 C   s   dd l }t \}}d|}t|d+}t|}| |d | t	
|ttj | t	
|t| W d    d S 1 sBw   Y  d S )Nr   zif 1:
            import sys, builtins, pickle
            with open({:d}, "wb") as f:
                pickle.dump(id(sys.modules), f)
                pickle.dump(id(builtins), f)
            rb)builtinsospipeformatopenr   run_in_subinterpr   ZassertNotEqualpickleloadr   r/   r   )r   r*  rwr   fretr   r   r   test_subinterps  s   
"z"SubinterpreterTest.test_subinterpsc                 C   st   t  \}}d|}t|d }t|}| |d | t|ddd W d    d S 1 s3w   Y  d S )Naa  if 1:
            import pickle
            with open({:d}, "wb") as f:

                @(lambda x:x)  # Py 3.9
                def noop(x): return x

                a = (b := f'1{{2}}3') + noop('x')  # Py 3.8 (:=) / 3.6 (f'')

                async def foo(arg): return await arg  # Py 3.5

                pickle.dump(dict(a=a, b=b), f)
            r)  r   Z123xr   )r  r   )	r+  r,  r-  r.  r   r/  r   r0  r1  )r   r2  r3  r   r4  r5  r   r   r   (test_subinterps_recent_language_features  s   
"z;SubinterpreterTest.test_subinterps_recent_language_featuresc                 C   s(   ddl }td | t|jd dS )z
        Exceptions saved in global module state get shared between
        individual module instances. This test checks whether or not
        a change in one interpreter's module gets reflected into the
        other ones.
        r   Nz1import binascii; binascii.Error.foobar = 'foobar'Zfoobar)binasciir   r/  ZassertFalser  Error)r   r8  r   r   r   test_mutate_exception  s   
z(SubinterpreterTest.test_mutate_exceptionN)r   r   r   r6  r7  r:  r   r   r   r   r(    s    r(  c                   @   s   e Zd Zejdd ZdS )TestThreadStatec                    s2    fdd}|  t j|d}|  |  d S )Nc                     sH   g   fdd} t |  |  }}td  t dd d S )Nc                      s     t  d S r8   )r  r  	get_identr   Zidentsr   r   r    r;   zCTestThreadState.test_thread_state.<locals>.target.<locals>.callbackr=   rP   z/Couldn't find main thread correctly in the list)r
   Z_test_thread_stater  r	  r   r  r  r<  )r  r  r   r   r=  r   r    s   

z1TestThreadState.test_thread_state.<locals>.target)r  )r  r  startjoin)r   r  tr   r   r   test_thread_state   s
   z!TestThreadState.test_thread_stateN)r   r   r   r   Zreap_threadsrA  r   r   r   r   r;    s    r;  c                   @   s:   e Zd Ze dd eeD  eje	ddd Z
dS )Test_testcapic                 c   s2    | ]}| d r|ds|tt|fV  qdS )test__codeN)r4   endswithgetattrr
   r  r   r   r   r   	<genexpr>  s    zTest_testcapi.<genexpr>)categoryc                 C   r   r8   )r
   test_widecharr   r   r   r   rJ    s   zTest_testcapi.test_widecharN)r   r   r   localsupdatedirr
   r   Zignore_warningsDeprecationWarningrJ  r   r   r   r   rB    s    
rB  c                   @   s&   e Zd Ze dd eeD  dS )Test_testinternalcapic                 c   s(    | ]}| d r|tt|fV  qdS )rC  N)r4   rF  _testinternalcapirG  r   r   r   rH  "  s
    zTest_testinternalcapi.<genexpr>N)r   r   r   rK  rL  rM  rP  r   r   r   r   rO  !  s    rO  c                   @   sl   e Zd Zd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d Zdd ZdS )PyMemDebugTestsdebugz(?:0x)?[0-9a-fA-F]+c                 C   sJ   t   td|| jd}W d    n1 sw   Y  |j}|ddS )Nr(   PYTHONMALLOCasciir   )r   r,   r   rT  r   r   )r   r   r6   r*   r   r   r   check,  s   
zPyMemDebugTests.checkc                 C   s<   |  d}d}|j| jd}tj|tjd}| || d S )Nz3import _testcapi; _testcapi.pymem_buffer_overflow()a6  Debug memory block at address p={ptr}: API 'm'\n    16 bytes originally requested\n    The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n    The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n        at tail\+0: 0x78 \*\*\* OUCH\n        at tail\+1: 0xfd\n        at tail\+2: 0xfd\n        .*\n(    The block was made by call #[0-9]+ to debug malloc/realloc.\n)?    Data at p: cd cd cd .*\n\nEnable tracemalloc to get the memory block allocation traceback\n\nFatal Python error: _PyMem_DebugRawFree: bad trailing pad byteZptr)flags)rV  r-  	PTR_REGEXr   compileDOTALLr~   r   r6   Zregexr   r   r   test_buffer_overflow3  s
   
z$PyMemDebugTests.test_buffer_overflowc                 C   s,   |  d}d}|j| jd}| || d S )Nz.import _testcapi; _testcapi.pymem_api_misuse()a  Debug memory block at address p={ptr}: API 'm'\n    16 bytes originally requested\n    The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n    The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n(    The block was made by call #[0-9]+ to debug malloc/realloc.\n)?    Data at p: cd cd cd .*\n\nEnable tracemalloc to get the memory block allocation traceback\n\nFatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\nrW  )rV  r-  rY  r~   r\  r   r   r   test_api_misuseG  s   

zPyMemDebugTests.test_api_misusec                 C   s   |  |}d}| || d S )Nz^Fatal Python error: _PyMem_DebugMalloc: Python memory allocator called without holding the GIL)rV  r   )r   r   r6   r   r   r   r   check_malloc_without_gilV  s   
z(PyMemDebugTests.check_malloc_without_gilc                 C      d}|  | d S )Nz6import _testcapi; _testcapi.pymem_malloc_without_gil()r_  r   r   r   r   r   test_pymem_malloc_without_gil\     z-PyMemDebugTests.test_pymem_malloc_without_gilc                 C   r`  )Nz9import _testcapi; _testcapi.pyobject_malloc_without_gil()ra  rb  r   r   r    test_pyobject_malloc_without_gilb  rd  z0PyMemDebugTests.test_pyobject_malloc_without_gilc                 C   s&   t d| d}td|| jd d S )Nz
            import gc, os, sys, _testcapi
            # Disable the GC to avoid crash on GC collection
            gc.disable()
            try:
                _testcapi.z()
                # Exit immediately to avoid a crash while deallocating
                # the invalid object
                os._exit(0)
            except _testcapi.error:
                os._exit(1)
        r(   rS  )r|   r}   r	   rT  )r   	func_namer   r   r   r   check_pyobject_is_freedh  s   
z'PyMemDebugTests.check_pyobject_is_freedc                 C      |  d d S )NZcheck_pyobject_null_is_freedrg  r   r   r   r   test_pyobject_null_is_freedw  r   z+PyMemDebugTests.test_pyobject_null_is_freedc                 C   rh  )NZ%check_pyobject_uninitialized_is_freedri  r   r   r   r   $test_pyobject_uninitialized_is_freedz  r   z4PyMemDebugTests.test_pyobject_uninitialized_is_freedc                 C   rh  )NZ'check_pyobject_forbidden_bytes_is_freedri  r   r   r   r   &test_pyobject_forbidden_bytes_is_freed}  r   z6PyMemDebugTests.test_pyobject_forbidden_bytes_is_freedc                 C   rh  )NZcheck_pyobject_freed_is_freedri  r   r   r   r   test_pyobject_freed_is_freed  r   z,PyMemDebugTests.test_pyobject_freed_is_freedN)r   r   r   rT  rY  rV  r]  r^  r_  rc  re  rg  rj  rk  rl  rm  r   r   r   r   rQ  '  s    rQ  c                   @      e Zd ZdZdS )PyMemMallocDebugTestsZmalloc_debugNr   r   r   rT  r   r   r   r   ro    s    ro  zneed pymallocc                   @   rn  )PyMemPymallocDebugTestsZpymalloc_debugNrp  r   r   r   r   rq    s    rq  zneed Py_DEBUGc                   @   rn  )PyMemDefaultTestsr   Nrp  r   r   r   r   rr    s    rr  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )Test_ModuleStateAccessz%Test access to module start (PEP 573)c                 C   sN   d}t jdj}t j||}t j||}t j|}|| || _	d S )NZ!_testmultiphase_meth_state_accessZ_testmultiphase)
	importlibutil	find_specorigin	machineryExtensionFileLoaderspec_from_loadermodule_from_specexec_modulemodule)r   fullnamerw  loaderspecr}  r   r   r   setUp  s   

zTest_ModuleStateAccess.setUpc                 C   s0   G dd d| j j}| }| | | j  dS )z#PyType_GetModule for defining_classc                   @   r  )zQTest_ModuleStateAccess.test_subclass_get_module.<locals>.StateAccessType_SubclassNr  r   r   r   r   StateAccessType_Subclass  s    r  Nr}  StateAccessTypeZassertIsget_defining_moduler   r  instancer   r   r   test_subclass_get_module  s   z/Test_ModuleStateAccess.test_subclass_get_modulec                 C   s0   G dd d| j j}| }| | | j  d S )Nc                       r   )z\Test_ModuleStateAccess.test_subclass_get_module_with_super.<locals>.StateAccessType_Subclassc                    s
   t   S r8   )r   r  r   r   r   r   r    s   
zpTest_ModuleStateAccess.test_subclass_get_module_with_super.<locals>.StateAccessType_Subclass.get_defining_module)r   r   r   r  r   r   r   r   r   r    r   r  r  r  r   r   r   #test_subclass_get_module_with_super  s   z:Test_ModuleStateAccess.test_subclass_get_module_with_superc              
   C   sv  | j  }| j  }|j|jd}| D ]\}}| | | | |  | | d |  | | |  | | d |d | | |  | | d |ddd | | |  | | d | t	 |dd	 W d
   n1 sw   Y  | t	 |ddd W d
   n1 sw   Y  W d
   q1 sw   Y  qd
S )zChecks methods defined with and without argument clinic

        This tests a no-arg method (get_count) and a method with
        both a positional and keyword argument.
        )ZclinicZnoclinicr   r=   rP      T)Ztwice)ZthriceNrR   )
r}  r  Zincrement_count_clinicZincrement_count_noclinicr   ZsubTestr   Z	get_countr"   r>   )r   r  r   methodsr   Zincrement_countr   r   r   test_state_access  s6   

z(Test_ModuleStateAccess.test_state_accessN)r   r   r   r!   r  r  r  r  r   r   r   r   rs    s    	rs  __main__)4collectionsr   importlib.machineryrt  importlib.utilr+  r0  r
  r   r-   r/   r|   r  r  r   r   r   r   Ztest.supportr   r   r   r   Ztest.support.script_helperr   r	   ri   ImportErrorimport_moduler
   rP  r  r{   r   r   r   ZTestCaser   r  r(  r;  rB  rO  rQ  ro  r  Zwith_pymallocrq  rr  rs  r   mainr   r   r   r   <module>   sf   

    LO4]

G