B
    u9a)                 @   s  d Z ddlZddlZddlZddlZddlZyddlZW n ek
rP   dZY nX ddlm	Z	m
Z
mZmZ dd Zdd Zdd	 ZG d
d dejZdd ZG dd dejZG dd dejZeddrtedk	rtejZedejZejZefe_eje_ejZ ej!ejejfe _ej"e _ej#Z$ej!eje%ejfe$_ej"e$_da&dd Z'ee'Z(ee(Z)G dd dejZ*dddZ+e,dkre+  dS )a7  This module includes tests of the code object representation.

>>> def f(x):
...     def g(y):
...         return x + y
...     return g
...

>>> dump(f.__code__)
name: f
argcount: 1
kwonlyargcount: 0
names: ()
varnames: ('x', 'g')
cellvars: ('x',)
freevars: ()
nlocals: 2
flags: 3
consts: ('None', '<code object g>', "'f.<locals>.g'")

>>> dump(f(4).__code__)
name: g
argcount: 1
kwonlyargcount: 0
names: ()
varnames: ('y',)
cellvars: ()
freevars: ('x',)
nlocals: 1
flags: 19
consts: ('None',)

>>> def h(x, y):
...     a = x + y
...     b = x - y
...     c = a * b
...     return c
...

>>> dump(h.__code__)
name: h
argcount: 2
kwonlyargcount: 0
names: ()
varnames: ('x', 'y', 'a', 'b', 'c')
cellvars: ()
freevars: ()
nlocals: 5
flags: 67
consts: ('None',)

>>> def attrs(obj):
...     print(obj.attr1)
...     print(obj.attr2)
...     print(obj.attr3)

>>> dump(attrs.__code__)
name: attrs
argcount: 1
kwonlyargcount: 0
names: ('print', 'attr1', 'attr2', 'attr3')
varnames: ('obj',)
cellvars: ()
freevars: ()
nlocals: 1
flags: 67
consts: ('None',)

>>> def optimize_away():
...     'doc string'
...     'not a docstring'
...     53
...     0x53

>>> dump(optimize_away.__code__)
name: optimize_away
argcount: 0
kwonlyargcount: 0
names: ()
varnames: ()
cellvars: ()
freevars: ()
nlocals: 0
flags: 67
consts: ("'doc string'", 'None')

>>> def keywordonly_args(a,b,*,k1):
...     return a,b,k1
...

>>> dump(keywordonly_args.__code__)
name: keywordonly_args
argcount: 2
kwonlyargcount: 1
names: ()
varnames: ('a', 'b', 'k1')
cellvars: ()
freevars: ()
nlocals: 3
flags: 67
consts: ('None',)

    N)run_doctestrun_unittestcpython_onlycheck_impl_detailc             c   s8   x2| D ]*}t |}|dr*d|j V  q|V  qW dS )z.Yield a doctest-safe sequence of object reprs.z<code objectz<code object %s>N)repr
startswithco_name)tZeltr r   /usr/lib/python3.7/test_code.pyconstsv   s
    

r   c             C   s@   x&dD ]}t d|t| d| f  qW t dtt| j dS )z1Print out a text representation of a code object.)	nameZargcountZkwonlyargcountnamesZvarnamesZcellvarsZfreevarsZnlocalsflagsz%s: %sZco_zconsts:N)printgetattrtupler   	co_consts)coattrr   r   r   dump   s    
r   c             C   s   dt  | S )NzForeign getitem: )super__getitem__)selfir   r   r   external_getitem   s    r   c               @   s$   e Zd Zedd Zedd ZdS )CodeTestc             C   sD   dd l }|ddd}| |jd | |jd | |jd d S )Nr   filenamefuncname   )	_testcapiZcode_newemptyassertEqualco_filenamer   co_firstlineno)r   r!   r   r   r   r   test_newempty   s
    zCodeTest.test_newemptyc                s   ddl mm  dd  fddfdd}G d	d
 d
t}||dt |j}|jd j}| || | 	|j
jtj@ t|j
j |dddg}| |d d d S )Nr   )FunctionTypeCodeTypec                s    fddj S )Nc                  s    S )Nr   r   )	__class__r   r   <lambda>       zICodeTest.test_closure_injection.<locals>.create_closure.<locals>.<lambda>)__closure__)r(   r   )r(   r   create_closure   s    z7CodeTest.test_closure_injection.<locals>.create_closurec                sF    | j | j| j| j| j| j| j| j| j| j	| j
| j| j| jd | jS )z9A new code object with a __class__ cell added to freevars)r(   )co_argcountco_kwonlyargcount
co_nlocalsco_stacksizeco_flagsco_coder   co_namesco_varnamesr#   r   r$   	co_lnotabco_freevarsco_cellvars)c)r'   r   r   new_code   s
    z1CodeTest.test_closure_injection.<locals>.new_codec          	      s@   |j }|jrt| }|j}t| | |t ||| d S )N)__code__r+   AssertionError__defaults__setattrglobals)clsr   fcodeZclosuredefaults)r&   r,   r9   r   r   add_foreign_method   s
    

z;CodeTest.test_closure_injection.<locals>.add_foreign_methodc               @   s   e Zd ZdS )z-CodeTest.test_closure_injection.<locals>.ListN)__name__
__module____qualname__r   r   r   r   List   s   rG   r            zForeign getitem: 1)typesr&   r'   listr   r   r+   cell_contentsZassertIsassertFalser:   r1   inspectZ	CO_NOFREEhexr"   )r   rC   rG   ZfunctionZ	class_refobjr   )r'   r&   r,   r9   r   test_closure_injection   s    zCodeTest.test_closure_injectionN)rD   rE   rF   r   r%   rR   r   r   r   r   r      s   r   c             C   s   | t d|  d dd kS )N_rH   )sysintern)sr   r   r   
isinterned   s    rX   c               @   s`   e Zd Zdd Zdd Zdd Zedd Zed	d
 Zedd Z	edd Z
edd ZdS )CodeConstsTestc             C   s4   x|D ]}||kr|S qW |  || | d d S )NzShould never be reached)ZassertInfail)r   r   valuevr   r   r   
find_const   s
    
zCodeConstsTest.find_constc             C   s   t |s| d|f  d S )NzString %r is not interned)rX   rZ   )r   rW   r   r   r   assertIsInterned   s    zCodeConstsTest.assertIsInternedc             C   s   t |r| d|f  d S )NzString %r is interned)rX   rZ   )r   rW   r   r   r   assertIsNotInterned   s    z"CodeConstsTest.assertIsNotInternedc             C   s(   t ddd}| |jd}| | d S )Nzres = "str_value"?exec	str_value)compiler]   r   r^   )r   r   r\   r   r   r   test_interned_string   s    z#CodeConstsTest.test_interned_stringc             C   s,   t ddd}| |jd}| |d  d S )Nzres = ("str_value",)r`   ra   )rb   r   )rc   r]   r   r^   )r   r   r\   r   r   r   test_interned_string_in_tuple   s    z,CodeConstsTest.test_interned_string_in_tuplec             C   s4   t ddd}| |jtd}| t|d  d S )Nzres = a in {"str_value"}r`   ra   )rb   r   )rc   r]   r   	frozensetr^   r   )r   r   r\   r   r   r   !test_interned_string_in_frozenset   s    z0CodeConstsTest.test_interned_string_in_frozensetc             C   s   ddd}|  |  d S )Nrb   c             S   s   | S )Nr   )ar   r   r   r@      s    z6CodeConstsTest.test_interned_string_default.<locals>.f)rb   )r^   )r   r@   r   r   r   test_interned_string_default   s    
z+CodeConstsTest.test_interned_string_defaultc             C   s(   t ddd}| |jd}| | d S )Nzres = "str\0value!"r`   ra   z
str value!)rc   r]   r   r_   )r   r   r\   r   r   r   test_interned_string_with_null   s    z-CodeConstsTest.test_interned_string_with_nullN)rD   rE   rF   r]   r^   r_   r   rd   re   rg   ri   rj   r   r   r   r   rY      s   rY   c               @   s   e Zd Zdd ZdS )CodeWeakRefTestc                sn   i }t dt | |d }~d _ fdd}t|j|} t|  ~ t|    j d S )Nzdef f(): passr@   Fc                s
   d _ d S )NT)called)rA   )r   r   r   callback   s    z,CodeWeakRefTest.test_basic.<locals>.callback)	ra   r>   rl   weakrefrefr:   Z
assertTrueboolrN   )r   	namespacer@   rm   Zcoderefr   )r   r   
test_basic   s    zCodeWeakRefTest.test_basicN)rD   rE   rF   rr   r   r   r   r   rk      s   rk   T)cpythonc             C   s   | a d S )N)
LAST_FREED)Zptrr   r   r   myfree  s    ru   c               @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )CoExtrac             C   s   t dS )Nz	lambda:42)eval)r   r   r   r   get_func$  s    zCoExtra.get_funcc          	   C   s<   |   }| ttdttd | ttdttd d S )N*   d   )rx   assertRaisesSystemErrorSetExtra
FREE_INDEXctypesc_voidpGetExtra)r   r@   r   r   r   test_get_non_code*  s
    zCoExtra.test_get_non_codec          	   C   sJ   |   }| tt|jtd td | t	|jtd tdd d S )Nrz   r   )
rx   r{   r|   r}   r:   r~   r   r   r"   r   )r   r@   r   r   r   test_bad_index2  s
    zCoExtra.test_bad_indexc             C   s.   |   }t|jttd ~| td d S )Nrz   )rx   r}   r:   r~   r   r   r"   rt   )r   r@   r   r   r   test_free_called9  s    zCoExtra.test_free_calledc             C   sn   |   }t }t|jttd t|jttd | td t }t|jt| | |j	d ~d S )N   i,  )
rx   r   r   r}   r:   r~   r"   rt   r   r[   )r   r@   Zextrar   r   r   test_get_setB  s    zCoExtra.test_get_setc             C   sZ   |   }G dd dtj}t|jttd ||| }~|  |	  | 
td d S )Nc                   s$   e Zd Z fddZdd Z  ZS )z6CoExtra.test_free_different_thread.<locals>.ThreadTestc                s   t    || _|| _d S )N)r   __init__r@   test)r   r@   r   )r(   r   r   r   W  s    
z?CoExtra.test_free_different_thread.<locals>.ThreadTest.__init__c             S   s   | ` | jtd d S )Ni  )r@   r   r"   rt   )r   r   r   r   run[  s    z:CoExtra.test_free_different_thread.<locals>.ThreadTest.run)rD   rE   rF   r   r   __classcell__r   r   )r(   r   
ThreadTestV  s   r   i  )rx   	threadingZThreadr}   r:   r~   r   r   startjoinr"   rt   )r   r@   r   ttr   r   r   test_free_different_threadR  s    	
z"CoExtra.test_free_different_threadN)	rD   rE   rF   rx   r   r   r   r   r   r   r   r   r   rv   #  s   	rv   c             C   sH   ddl m} t||  tttg}tddr<td k	r<|t	 t
|  d S )Nr   )	test_codeT)rs   )r   r   r   r   rY   rk   r   r   appendrv   r   )verboser   Ztestsr   r   r   	test_mainf  s    


r   __main__)N)-__doc__rO   rU   r   Zunittestrn   r   ImportErrorZtest.supportr   r   r   r   r   r   r   ZTestCaser   rX   rY   rk   Z	pythonapipyZ	CFUNCTYPEr   ZfreefuncZ_PyEval_RequestCodeExtraIndexZRequestCodeExtraIndexZargtypesZ	c_ssize_tZrestypeZ_PyCode_SetExtrar}   Z	py_objectZc_intZ_PyCode_GetExtrar   ZPOINTERrt   ru   Z	FREE_FUNCr~   rv   r   rD   r   r   r   r   <module>g   sL   
		30C

