o
    IXh_J                     @   s   d 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 ZdZ	dZ
dZdZd	Zd
ZdZdZdZdZdZdZdZG dd dejZG dd deZG dd deZG dd deZedkrce  dS dS )z>Tests for the unparse.py script in the Tools/parser directory.    Nc                 C   s6   t | }| W  d   S 1 sw   Y  dS )znRead and return the contents of a Python source file (as a
    string), taking into account the file encoding.N)tokenizeopenread)filenamestream r   ;/opt/python-3.10.19/usr/lib/python3.10/test/test_unparse.pyread_pyfile   s   $r	   zQdef f():
    for x in range(10):
        break
    else:
        y = 2
    z = 3
zIdef g():
    while True:
        break
    else:
        y = 2
    z = 3
zQfrom . import fred
from .. import barney
from .australia import shrimp as prawns
zzdef f():
    x = 1
    def g():
        nonlocal x
        x = 2
        y = 7
        def h():
            nonlocal x, y
zOtry:
    1 / 0
except ZeroDivisionError as e:
    raise ArithmeticError from e
z@f1(arg)
@f2
class Foo: pass
z=if cond1:
    suite1
elif cond2:
    suite2
else:
    suite3
z,if cond1:
    suite1
elif cond2:
    suite2
zctry:
    suite1
except ex1:
    suite2
except ex2:
    suite3
else:
    suite4
finally:
    suite5
zwith f():
    suite1
zwith f() as x:
    suite1
z$with f() as x, g() as y:
    suite1
) zclass foo:
    zdef foo():
    zasync def foo():
    c                   @   sF   e Zd Zdd Zdd ZefddZddd	Zdd
dZdddZ	dS )ASTTestCasec                 C   s   |  t|t| d S N)assertEqualastdump)selfast1ast2r   r   r   assertASTEqualw   s   zASTTestCase.assertASTEqualc                 K   sn   | j ||d& tj|fi |}t|}tj|fi |}| || W d    d S 1 s0w   Y  d S )N)code1Zast_parse_kwargs)subTestr   parseunparser   )r   r   kwargsr   code2r   r   r   r   check_ast_roundtripz   s   
"zASTTestCase.check_ast_roundtripc                 C   sB   | j |d | |tj| W d    d S 1 sw   Y  d S )N)node)r   ZassertRaisesr   r   )r   r   Zraisesr   r   r   check_invalid   s   "zASTTestCase.check_invalidNc                 C   s    |p|}t t |}||fS r   )r   r   r   r   r   r   r   r   r   
get_source   s   zASTTestCase.get_sourcec                 C   P   |  ||\}}| j||d | || W d    d S 1 s!w   Y  d S N)r   r   )r   r   r   r   r   r   r   check_src_roundtrip      "zASTTestCase.check_src_roundtripc                 C   r   r    )r   r   ZassertNotEqualr   r   r   r   check_src_dont_roundtrip   r"   z$ASTTestCase.check_src_dont_roundtripr   )
__name__
__module____qualname__r   r   
ValueErrorr   r   r!   r#   r   r   r   r   r   v   s    

r   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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%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)dOdP Z*dQdR Z+dSdT Z,dUdV Z-dWdX Z.dYdZ Z/d[d\ Z0d]S )^UnparseTestCasec                 C   ,   |  d |  d |  d |  d d S )Nzf'{f"{0}"*3}'zf'{f"{y}"*3}'zf''zf"""'end' "quote\""""r   r   r   r   r   test_fstrings   s   


zUnparseTestCase.test_fstringsc                 C   sJ   |  d |  d |  d |  d |  d |  d |  d d S )Nzf'''{"'"}'''%f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-'''z4f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-'single quote\''''zf"""{'''
'''}"""zf"""{g('''
''')}"""z	f"a\r\nb"f"\u2028{'x'}"r*   r+   r   r   r   test_fstrings_complicated   s   





z)UnparseTestCase.test_fstrings_complicatedc                 C   "   |  d |  d |  d d S )Nzu'foo'zr'foo'zb'foo'r*   r+   r   r   r   test_strings      

zUnparseTestCase.test_stringsc                 C      |  d d S )Nzdel x, y, zr*   r+   r   r   r   test_del_statement      z"UnparseTestCase.test_del_statementc                 C      |  d |  d d S )Nz45 << 2z13 >> 7r*   r+   r   r   r   test_shifts      
zUnparseTestCase.test_shiftsc                 C      |  t d S r   )r   for_elser+   r   r   r   test_for_else   r5   zUnparseTestCase.test_for_elsec                 C   r9   r   )r   
while_elser+   r   r   r   test_while_else   r5   zUnparseTestCase.test_while_elsec                 C   6   |  d |  d |  d |  d |  d d S )Nz(-1)**7z(-1.)**8z(-1j)**6znot True or FalsezTrue or not Falser*   r+   r   r   r   test_unary_parens   
   



z!UnparseTestCase.test_unary_parensc                 C   r3   )Nz3 .__abs__()r*   r+   r   r   r   test_integer_parens   r5   z#UnparseTestCase.test_integer_parensc                 C   r)   )NZ1e1000z-1e1000Z1e1000jz-1e1000jr*   r+   r   r   r   test_huge_float      


zUnparseTestCase.test_huge_floatc              	   C   s.   |  tttjtddtd d S )Nnanvaluez1e1000 - 1e1000)r   r   r   r   Constantfloatr+   r   r   r   test_nan   s   zUnparseTestCase.test_nanc                 C   s    |  td |  td d S )Ni   l         )r   strr+   r   r   r   test_min_int   s   zUnparseTestCase.test_min_intc                 C   r)   )NZ7jz-7jZ0jz-0jr*   r+   r   r   r   test_imaginary_literals   rC   z'UnparseTestCase.test_imaginary_literalsc                 C   r3   )Nz(lambda: int)()r*   r+   r   r   r   test_lambda_parentheses   r5   z'UnparseTestCase.test_lambda_parenthesesc                 C   r6   )Nz
1 < 4 <= 5za is b is c is not dr*   r+   r   r   r   test_chained_comparisons   r8   z(UnparseTestCase.test_chained_comparisonsc                 C   s|   |  d |  d |  d |  d |  d |  d |  d |  d |  d	 |  d
 |  d |  d d S )Nzdef f(): passzdef f(a): passzdef f(b = 2): passzdef f(a, b): passzdef f(a, b = 2): passzdef f(a = 5, b = 2): passzdef f(*, a = 1, b = 2): passzdef f(*, a = 1, b): passzdef f(*, a, b = 2): passz&def f(a, b = None, *, c, **kwds): passz'def f(a=2, *args, c=5, d, **kwds): passzdef f(*args, **kwargs): passr*   r+   r   r   r   test_function_arguments   s   










z'UnparseTestCase.test_function_argumentsc                 C   r9   r   )r   relative_importr+   r   r   r   test_relative_import   r5   z$UnparseTestCase.test_relative_importc                 C   r9   r   )r   nonlocal_exr+   r   r   r   test_nonlocal   r5   zUnparseTestCase.test_nonlocalc                 C   r9   r   )r   
raise_fromr+   r   r   r   test_raise_from   r5   zUnparseTestCase.test_raise_fromc                 C   r3   )Nzb'123'r*   r+   r   r   r   
test_bytes   r5   zUnparseTestCase.test_bytesc                 C   r>   )Nzdef f(a : int): passzdef f(a: int = 5): passzdef f(*args: [int]): passzdef f(**kwargs: dict): passzdef f() -> None: passr*   r+   r   r   r   test_annotations   r@   z UnparseTestCase.test_annotationsc                 C   r3   )Nz{'a', 'b', 'c'}r*   r+   r   r   r   test_set_literal  r5   z UnparseTestCase.test_set_literalc              	   C   s*   |  tttjg dtd d S )N)eltsz{*()})r   r   r   r   Setr+   r   r   r   test_empty_set  s   zUnparseTestCase.test_empty_setc                 C   r3   )Nz{x for x in range(5)}r*   r+   r   r   r   test_set_comprehension  r5   z&UnparseTestCase.test_set_comprehensionc                 C   r3   )Nz{x: x*x for x in range(10)}r*   r+   r   r   r   test_dict_comprehension  r5   z'UnparseTestCase.test_dict_comprehensionc                 C   r9   r   )r   class_decoratorr+   r   r   r   test_class_decorators  r5   z%UnparseTestCase.test_class_decoratorsc                 C   r3   )Nz(class A(metaclass=type, *[], **{}): passr*   r+   r   r   r   test_class_definition  r5   z%UnparseTestCase.test_class_definitionc                 C   s   |  t |  t d S r   )r   elif1elif2r+   r   r   r   
test_elifs  r8   zUnparseTestCase.test_elifsc                 C   r9   r   )r   try_except_finallyr+   r   r   r   test_try_except_finally  r5   z'UnparseTestCase.test_try_except_finallyc                 C   r)   )Nza, *b, c = seqza, (*b, c) = seqza, *b[0], c = seqza, *(b, c) = seqr*   r+   r   r   r   test_starred_assignment  rC   z'UnparseTestCase.test_starred_assignmentc                 C   r9   r   )r   with_simpler+   r   r   r   test_with_simple$  r5   z UnparseTestCase.test_with_simplec                 C   r9   r   )r   with_asr+   r   r   r   test_with_as'  r5   zUnparseTestCase.test_with_asc                 C   r9   r   )r   with_two_itemsr+   r   r   r   test_with_two_items*  r5   z#UnparseTestCase.test_with_two_itemsc                 C   r6   )Nz{**{'y': 2}, 'x': 1}z{**{'y': 2}, **{'x': 1}}r*   r+   r   r   r   test_dict_unpacking_in_dict-  s   
z+UnparseTestCase.test_dict_unpacking_in_dictc                 C   s   |  d |  d |  d |  d |  d |  d |  d |  d |  d	 |  d
 |  d |  d |  d |  d |  d d S )Nza[i]za[i,]za[i, j]za[(*a,)]z	a[(a:=b)]za[(a:=b,c)]za[()]za[i:j]za[:j]za[i:]za[i:j:k]za[:j:k]za[i::k]za[i:j,]z	a[i:j, k]r*   r+   r   r   r   test_slices2  s   













zUnparseTestCase.test_slicesc                 C   s    |  tjd tjddd d S )NX)id)exccause)r   r   ZRaiseNamer+   r   r   r   test_invalid_raiseC      z"UnparseTestCase.test_invalid_raisec                 C   s    |  tjtjddgd d S )Nd   rE   )values)r   r   Z	JoinedStrrG   r+   r   r   r   test_invalid_fstring_constantF  ru   z-UnparseTestCase.test_invalid_fstring_constantc                 C   s(   |  tjtjdd dtdd d d S )NarF   kindY)rF   
conversionformat_spec)r   r   FormattedValuerG   ordr+   r   r   r   test_invalid_fstring_conversionI  s   z/UnparseTestCase.test_invalid_fstring_conversionc                 C   s   |  tjtjddd d S )Nz\\rE   )r   r   r   rG   r+   r   r   r   test_invalid_fstring_backslashR  s   z.UnparseTestCase.test_invalid_fstring_backslashc                 C   s   |  tjd d d S )NrE   )r   r   Z	YieldFromr+   r   r   r   test_invalid_yield_fromU  s   z'UnparseTestCase.test_invalid_yield_fromc                 C   sZ   t jdt jddgd}| t |d t jdt jddgd d}| t |d d S )Nmodx)name)modulenameszfrom mod import x)r   r   level)r   Z
ImportFromaliasr   r   )r   Ztreer   r   r   test_import_from_level_noneX  s   z+UnparseTestCase.test_import_from_level_nonec                 C   s$   d}|D ]}|  d| d qd S )N)zthis ends with double quote"z"this includes a """triple quote"""z\r	z\t
z\nz	\r	\t
\nz$""">>> content = """blabla""" <<<"""z	foo\n\x00z' \'\'\'""" ""\'\' \'u   🐍⛎𩸽üéş^\\X\\BB⟿z'''r*   )r   
docstrings	docstringr   r   r   test_docstrings^  s   zUnparseTestCase.test_docstringsc                 C   s0   |  tjdd dd |  tjdd dd d S )N)   rz   z(1,))r         z	(1, 2, 3))r!   r   rG   r+   r   r   r   test_constant_tuplesr  s   z$UnparseTestCase.test_constant_tuplesc                 C      dD ]	}| j |dd qd S )N)z	() -> intz(int, int) -> intz=(Callable[complex], More[Complex(call.to_typevar())]) -> NoneZ	func_type)moder*   )r   Zfunction_typer   r   r   test_function_typex  s   z"UnparseTestCase.test_function_typec                 C   r   )N)za = 5 # type:za = 5 # type: intza = 5 # type: int and morez!def x(): # type: () -> None
	passz.def x(y): # type: (int) -> None and more
	passz'async def x(): # type: () -> None
	passz4async def x(y): # type: (int) -> None and more
	passzfor x in y: # type: int
	passz#async for x in y: # type: int
	passzwith x(): # type: int
	passz!async with x(): # type: int
	passTZtype_commentsr*   r   Z	statementr   r   r   test_type_comments  s   z"UnparseTestCase.test_type_commentsc                 C   r   )N)
za = 5 # type: ignoreza = 5 # type: ignore and morezdef x(): # type: ignore
	passz'def x(y): # type: ignore and more
	passz#async def x(): # type: ignore
	passz-async def x(y): # type: ignore and more
	passz for x in y: # type: ignore
	passz&async for x in y: # type: ignore
	passzwith x(): # type: ignore
	passz$async with x(): # type: ignore
	passTr   r*   r   r   r   r   test_type_ignore  s   z UnparseTestCase.test_type_ignoreN)1r$   r%   r&   r,   r/   r1   r4   r7   r;   r=   r?   rA   rB   rI   rK   rL   rM   rN   rO   rQ   rS   rU   rV   rW   rX   r[   r\   r]   r_   r`   rc   re   rf   rh   rj   rl   rm   rn   rt   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   r(      s^    
	r(   c                   @   sH   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d Z
dS )CosmeticTestCasezATest if there are cosmetic issues caused by unnecessary additionsc                 C   s  |  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 |  d d S )Nz(a := b)zawait xzx if x else yzlambda x: xz1 + 1z	1 + 2 / 3z(1 + 2) / 3z(1 + 2) * 3 + 4 * (5 + 2)z(1 + 2) * 3 + 4 * (5 + 2) ** 2z~xzx and yzx and y and zzx and (y and x)z(x and y) and zz(x ** y) ** z ** qzx >> yzx << yzx >> y and x >> zzx + y - z * q ^ t ** kzP * V if P and V else n * R * Tz"lambda P, V, n: P * V == n * R * Tzflag & (other | foo)z
not x == yzx == (not y)zyield xzyield from xzcall((yield x))zreturn x + (yield x)r!   r+   r   r   r   test_simple_expressions_parens  s8   


























z/CosmeticTestCase.test_simple_expressions_parensc                 C   sh   |  d |  d |  d |  d |  d |  d |  d |  d |  d	 |  d
 d S )Nzclass X:
    passzclass X(A):
    passzclass X(A, B, C, D):
    passzclass X(x=y):
    passzclass X(metaclass=z):
    passzclass X(x=y, z=d):
    passzclass X(A, x=y):
    passzclass X(A, **kw):
    passzclass X(*args):
    passz"class X(*args, **kwargs):
    passr   r+   r   r   r   test_class_bases_and_keywords  s   








z.CosmeticTestCase.test_class_bases_and_keywordsc                 C   r>   )Nr-   r.   zf'{x}\n'zf'''{"""
"""}\n'''zf'''{f"""{x}
"""}\n'''r   r+   r   r   r   r,     r@   zCosmeticTestCase.test_fstringsc                 C   s.   d}t D ]}|D ]}| | |  qqd S )N)z"""simple doc string"""z7"""A more complex one
            with some newlines"""z,"""Foo bar baz

            empty newline"""z"""With some 	"""z"""Foo "bar" baz """z"""\r"""z""""""z	"""'''"""z"""''''''"""u"   """🐍⛎𩸽üéş^\\X\\BB⟿"""z"""end in single 'quote'"""z'''end in double "quote"'''z#"""almost end in double "quote".""")docstring_prefixesr!   )r   r   prefixr   r   r   r   r     s   z CosmeticTestCase.test_docstringsc                 C   s<   d}t D ]}|D ]}| | }| | | | qqd S )N)za = """false"""z("""false""" + """unless its optimized"""z1 + 1
"""false"""z"f"""no, top level but f-fstring""")r   r   r#   )r   Zdocstrings_negativer   negativesrcr   r   r   test_docstrings_negative_cases  s   
z/CosmeticTestCase.test_docstrings_negative_casesc                 C   s8   dD ]
}|  | d qdD ]
}|  | d qd S )N)+-~1)notz 1r   )r   r   r   r   r   test_unary_op_factor  s
   z%CosmeticTestCase.test_unary_op_factorc                 C   r0   )Nza[1]za[1, 2]z
a[(1, *a)]r   r+   r   r   r   rn     r2   zCosmeticTestCase.test_slicesN)r$   r%   r&   __doc__r   r   r,   r   r   r   rn   r   r   r   r   r     s    r   c                   @   sL   e Zd ZdZeejd Zeed fZ	h dZ
dZedd Zdd	 ZdS )
DirectoryTestCasez:Test roundtrip behaviour on all files in Lib and Lib/test.z..test>   ztest_patma.pyztest_grammar.pyztest_ast.pyztest_asdl_parser.pyztest_syntax.pyztest_fstring.pyztest_compile.pyNc                    sd    j d ur j S dd  jD }tjds- fdd|D }tt|d}t||B }| _ |S )Nc                 S   s0   g | ]}| d D ]}|jds	| q	qS )z*.pyZbad)globr   
startswithresolve).0Z	directoryitemr   r   r   
<listcomp>  s    
z3DirectoryTestCase.files_to_test.<locals>.<listcomp>Zcpuc                    s   h | ]
}|j  jv r|qS r   )r   run_always_files)r   r   clsr   r   	<setcomp>$  s    z2DirectoryTestCase.files_to_test.<locals>.<setcomp>
   )	_files_to_testtest_directoriesr   supportZis_resource_enabledsetrandomsamplelist)r   itemsZtests_to_run_alwaysr   r   r   files_to_test  s   
zDirectoryTestCase.files_to_testc              	   C   sj   |   D ].}tjjrtd|   | j|d t|}| | W d    n1 s-w   Y  qd S )NzTesting )r   )	r   r   r   verboseprintabsoluter   r	   r   )r   r   sourcer   r   r   
test_files3  s   zDirectoryTestCase.test_files)r$   r%   r&   r   pathlibPath__file__parentZlib_dirr   r   r   classmethodr   r   r   r   r   r   r   	  s    
r   __main__)r   ZunittestZtest.supportr   r   r   r   r   r	   r:   r<   rP   rR   rT   r^   ra   rb   rd   rg   ri   rk   r   ZTestCaser   r(   r   r   r$   mainr   r   r   r   <module>   s<    			  i4