a
    äzeêH  ã                   @   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rÂe ¡  dS )z>Tests for the unparse.py script in the Tools/parser directory.é    Nc                 C   s6   t  | ¡}| ¡ W  d  ƒ S 1 s(0    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   ú'/usr/lib/python3.9/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   sl   | j ||dJ tj|fi |¤Ž}t |¡}tj|fi |¤Ž}|  ||¡ W d   ƒ n1 s^0    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   s@   | j |d  |  |tj|¡ W d   ƒ n1 s20    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   sN   |   ||¡\}}| j||d |  ||¡ W d   ƒ n1 s@0    Y  d S ©N)r   r   )r   r   r   r   r   r   r   Úcheck_src_roundtripŠ   s    zASTTestCase.check_src_roundtripc                 C   sN   |   ||¡\}}| j||d |  ||¡ W d   ƒ n1 s@0    Y  d S r   )r   r   ZassertNotEqualr   r   r   r   Úcheck_src_dont_roundtrip   s    z$ASTTestCase.check_src_dont_roundtrip)N)N)N)
Ú__name__Ú
__module__Ú__qualname__r   r   Ú
ValueErrorr   r   r    r!   r   r   r   r   r   v   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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[S )\ÚUnparseTestCasec                 C   s,   |   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   s"   |   d¡ |   d¡ |   d¡ d S )Nzu'foo'zr'foo'zb'foo'r'   r(   r   r   r   Útest_strings¨   s    

zUnparseTestCase.test_stringsc                 C   s   |   d¡ d S )Nzdel x, y, zr'   r(   r   r   r   Útest_del_statement­   s    z"UnparseTestCase.test_del_statementc                 C   s   |   d¡ |   d¡ d S )Nz45 << 2z13 >> 7r'   r(   r   r   r   Útest_shifts°   s    
zUnparseTestCase.test_shiftsc                 C   s   |   t¡ d S r   )r   Úfor_elser(   r   r   r   Útest_for_else´   s    zUnparseTestCase.test_for_elsec                 C   s   |   t¡ d S r   )r   Ú
while_elser(   r   r   r   Útest_while_else·   s    zUnparseTestCase.test_while_elsec                 C   s6   |   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º   s
    



z!UnparseTestCase.test_unary_parensc                 C   s   |   d¡ d S )Nz3 .__abs__()r'   r(   r   r   r   Útest_integer_parensÁ   s    z#UnparseTestCase.test_integer_parensc                 C   s,   |   d¡ |   d¡ |   d¡ |   d¡ d S )NZ1e1000z-1e1000Z1e1000jz-1e1000jr'   r(   r   r   r   Útest_huge_floatÄ   s    


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   s,   |   d¡ |   d¡ |   d¡ |   d¡ d S )NZ7jz-7jZ0jz-0jr'   r(   r   r   r   Útest_imaginary_literalsÔ   s    


z'UnparseTestCase.test_imaginary_literalsc                 C   s   |   d¡ d S )Nz(lambda: int)()r'   r(   r   r   r   Útest_lambda_parenthesesÚ   s    z'UnparseTestCase.test_lambda_parenthesesc                 C   s   |   d¡ |   d¡ d S )Nz
1 < 4 <= 5za is b is c is not dr'   r(   r   r   r   Útest_chained_comparisonsÝ   s    
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   s   |   t¡ d S r   )r   Úrelative_importr(   r   r   r   Útest_relative_importï   s    z$UnparseTestCase.test_relative_importc                 C   s   |   t¡ d S r   )r   Únonlocal_exr(   r   r   r   Útest_nonlocalò   s    zUnparseTestCase.test_nonlocalc                 C   s   |   t¡ d S r   )r   Ú
raise_fromr(   r   r   r   Útest_raise_fromõ   s    zUnparseTestCase.test_raise_fromc                 C   s   |   d¡ d S )Nzb'123'r'   r(   r   r   r   Ú
test_bytesø   s    zUnparseTestCase.test_bytesc                 C   s6   |   d¡ |   d¡ |   d¡ |   d¡ |   d¡ d S )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û   s
    



z UnparseTestCase.test_annotationsc                 C   s   |   d¡ d S )Nz{'a', 'b', 'c'}r'   r(   r   r   r   Útest_set_literal  s    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   s   |   d¡ d S )Nz{x for x in range(5)}r'   r(   r   r   r   Útest_set_comprehension  s    z&UnparseTestCase.test_set_comprehensionc                 C   s   |   d¡ d S )Nz{x: x*x for x in range(10)}r'   r(   r   r   r   Útest_dict_comprehension  s    z'UnparseTestCase.test_dict_comprehensionc                 C   s   |   t¡ d S r   )r   Úclass_decoratorr(   r   r   r   Útest_class_decorators  s    z%UnparseTestCase.test_class_decoratorsc                 C   s   |   d¡ d S )Nz(class A(metaclass=type, *[], **{}): passr'   r(   r   r   r   Útest_class_definition  s    z%UnparseTestCase.test_class_definitionc                 C   s   |   t¡ |   t¡ d S r   )r   Úelif1Úelif2r(   r   r   r   Ú
test_elifs  s    
zUnparseTestCase.test_elifsc                 C   s   |   t¡ d S r   )r   Útry_except_finallyr(   r   r   r   Útest_try_except_finally  s    z'UnparseTestCase.test_try_except_finallyc                 C   s,   |   d¡ |   d¡ |   d¡ |   d¡ d S )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  s    


z'UnparseTestCase.test_starred_assignmentc                 C   s   |   t¡ d S r   )r   Úwith_simpler(   r   r   r   Útest_with_simple$  s    z UnparseTestCase.test_with_simplec                 C   s   |   t¡ d S r   )r   Úwith_asr(   r   r   r   Útest_with_as'  s    zUnparseTestCase.test_with_asc                 C   s   |   t¡ d S r   )r   Úwith_two_itemsr(   r   r   r   Útest_with_two_items*  s    z#UnparseTestCase.test_with_two_itemsc                 C   s   |   d¡ |   d¡ d S )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  s    z"UnparseTestCase.test_invalid_raisec                 C   s    |   tjtjddgd¡ d S )Néd   r8   )Úvalues)r   r   Z	JoinedStrr:   r(   r   r   r   Útest_invalid_fstring_constantF  s    z-UnparseTestCase.test_invalid_fstring_constantc                 C   s(   |   tjtjdd dtdƒd d¡ d S )NÚa©r9   ÚkindÚY)r9   Ú
conversionÚformat_spec)r   r   ÚFormattedValuer:   Ú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\\r8   )r   r   rq   r:   r(   r   r   r   Útest_invalid_fstring_backslashR  s    z.UnparseTestCase.test_invalid_fstring_backslashc                 C   s   |   tjd d¡ d S )Nr8   )r   r   Z	YieldFromr(   r   r   r   Útest_invalid_yield_fromU  s    z'UnparseTestCase.test_invalid_yield_fromc                 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_docstringsX  s    zUnparseTestCase.test_docstringsc                 C   s0   |   tjdd dd¡ |   tjdd dd¡ d S )N)é   rl   z(1,))r|   é   é   z	(1, 2, 3))r    r   r:   r(   r   r   r   Útest_constant_tuplesl  s    ÿz$UnparseTestCase.test_constant_tuplesc                 C   s   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_typer  s    z"UnparseTestCase.test_function_typec                 C   s   dD ]}| j |dd qd S )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_commentsz  s    z"UnparseTestCase.test_type_commentsc                 C   s   dD ]}| j |dd qd S )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)0r"   r#   r$   r)   r,   r-   r.   r/   r1   r3   r4   r5   r6   r<   r>   r?   r@   rA   rB   rD   rF   rH   rI   rJ   rK   rN   rO   rP   rR   rS   rV   rX   rY   r[   r]   r_   r`   ra   rg   rj   rs   rt   ru   r{   r   r   r„   r…   r   r   r   r   r&   ”   sZ   
	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   s6   |   d¡ |   d¡ |   d¡ |   d¡ |   d¡ d S )Nr*   r+   zf'{x}\n'zf'''{"""
"""}\n'''zf'''{f"""{x}
"""}\n'''r‡   r(   r   r   r   r)   Ç  s
    



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   ry   Úprefixrz   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   s"   |   d¡ |   d¡ |   d¡ d S )Nza[1]za[1, 2]z
a[(1, *a)]r‡   r(   r   r   r   ra   þ  s    

zCosmeticTestCase.test_slicesN)r"   r#   r$   Ú__doc__rˆ   r‰   r)   r{   rŽ   r”   ra   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_compile.pyztest_fstring.pyztest_asdl_parser.pyztest_grammar.pyztest_syntax.pyztest_ast.pyNc                    sd   ˆ j d urˆ j S dd„ ˆ jD ƒ}tj d¡sZ‡ 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)ÚglobÚnameÚ
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   ƒ q1 sZ0    Y  qd S )NzTesting )r   )	r¬   r—   r¦   ÚverboseÚprintÚabsoluter   r	   r   )r   r   Úsourcer   r   r   Ú
test_files,  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	   r0   r2   rC   rE   rG   rQ   rT   rU   rW   rZ   r\   r^   rŠ   ZTestCaser   r&   r†   r–   r"   Úmainr   r   r   r   Ú<module>   s8   			  i3