Best Python code snippet using refurb_python
test_parser.py
Source:test_parser.py  
...33        if run:34            exec(compile(obs, "<test-ast>", mode))35    return factory36@pytest.fixture37def check_stmts(check_ast):38    def factory(inp, run=True, mode="exec", debug_level=0):39        __tracebackhide__ = True40        if not inp.endswith("\n"):41            inp += "\n"42        check_ast(inp, run=run, mode=mode, debug_level=debug_level)43    return factory44@pytest.fixture45def check_xonsh_ast(xsh, parser):46    def factory(47        xenv,48        inp,49        run=True,50        mode="eval",51        debug_level=0,52        return_obs=False,53        globals=None,54        locals=None,55    ):56        xsh.env.update(xenv)57        obs = parser.parse(inp, debug_level=debug_level)58        if obs is None:59            return  # comment only60        bytecode = compile(obs, "<test-xonsh-ast>", mode)61        if run:62            exec(bytecode, globals, locals)63        return obs if return_obs else True64    return factory65@pytest.fixture66def check_xonsh(check_xonsh_ast):67    def factory(xenv, inp, run=True, mode="exec"):68        __tracebackhide__ = True69        if not inp.endswith("\n"):70            inp += "\n"71        check_xonsh_ast(xenv, inp, run=run, mode=mode)72    return factory73@pytest.fixture74def eval_code(parser, xsh):75    def factory(inp, mode="eval", **loc_vars):76        obs = parser.parse(inp, debug_level=1)77        bytecode = compile(obs, "<test-xonsh-ast>", mode)78        return eval(bytecode, loc_vars)79    return factory80#81# Tests82#83#84# expressions85#86def test_int_literal(check_ast):87    check_ast("42")88def test_int_literal_underscore(check_ast):89    check_ast("4_2")90def test_float_literal(check_ast):91    check_ast("42.0")92def test_float_literal_underscore(check_ast):93    check_ast("4_2.4_2")94def test_imag_literal(check_ast):95    check_ast("42j")96def test_float_imag_literal(check_ast):97    check_ast("42.0j")98def test_complex(check_ast):99    check_ast("42+84j")100def test_str_literal(check_ast):101    check_ast('"hello"')102def test_bytes_literal(check_ast):103    check_ast('b"hello"')104    check_ast('B"hello"')105    check_ast('b"hello" b"world"')106def test_raw_literal(check_ast):107    check_ast('r"hell\\o"')108    check_ast('R"hell\\o"')109def test_f_literal(check_ast):110    check_ast('f"wakka{yo}yakka{42}"', run=False)111    check_ast('F"{yo}"', run=False)112@pytest.mark.parametrize(113    "first_prefix, second_prefix",114    itertools.product(["", "f", "r", "fr"], repeat=2),115)116def test_string_literal_concat(first_prefix, second_prefix, check_ast):117    check_ast(118        first_prefix + r"'11{a}22\n'" + " " + second_prefix + r"'33{b}44\n'", run=False119    )120def test_f_env_var(check_xonsh_ast):121    check_xonsh_ast({}, 'f"{$HOME}"', run=False)122    check_xonsh_ast({}, "f'{$XONSH_DEBUG}'", run=False)123    check_xonsh_ast({}, 'F"{$PATH} and {$XONSH_DEBUG}"', run=False)124fstring_adaptor_parameters = [125    ('f"$HOME"', "$HOME"),126    ('f"{0} - {1}"', "0 - 1"),127    ('f"{$HOME}"', "/foo/bar"),128    ('f"{ $HOME }"', "/foo/bar"),129    ("f\"{'$HOME'}\"", "$HOME"),130    ('f"$HOME  = {$HOME}"', "$HOME  = /foo/bar"),131    ("f\"{${'HOME'}}\"", "/foo/bar"),132    ("f'{${$FOO+$BAR}}'", "/foo/bar"),133    ("f\"${$FOO}{$BAR}={f'{$HOME}'}\"", "$HOME=/foo/bar"),134    (135        '''f"""foo136{f"_{$HOME}_"}137bar"""''',138        "foo\n_/foo/bar_\nbar",139    ),140    (141        '''f"""foo142{f"_{${'HOME'}}_"}143bar"""''',144        "foo\n_/foo/bar_\nbar",145    ),146    (147        '''f"""foo148{f"_{${ $FOO + $BAR }}_"}149bar"""''',150        "foo\n_/foo/bar_\nbar",151    ),152]153if VER_MAJOR_MINOR >= (3, 8):154    fstring_adaptor_parameters.append(("f'{$HOME=}'", "$HOME='/foo/bar'"))155@pytest.mark.parametrize("inp, exp", fstring_adaptor_parameters)156def test_fstring_adaptor(inp, exp, xsh, monkeypatch):157    joined_str_node = FStringAdaptor(inp, "f").run()158    assert isinstance(joined_str_node, ast.JoinedStr)159    node = ast.Expression(body=joined_str_node)160    code = compile(node, "<test_fstring_adaptor>", mode="eval")161    xenv = {"HOME": "/foo/bar", "FOO": "HO", "BAR": "ME"}162    for key, val in xenv.items():163        monkeypatch.setitem(xsh.env, key, val)164    obs = eval(code)165    assert exp == obs166def test_raw_bytes_literal(check_ast):167    check_ast('br"hell\\o"')168    check_ast('RB"hell\\o"')169    check_ast('Br"hell\\o"')170    check_ast('rB"hell\\o"')171def test_unary_plus(check_ast):172    check_ast("+1")173def test_unary_minus(check_ast):174    check_ast("-1")175def test_unary_invert(check_ast):176    check_ast("~1")177def test_binop_plus(check_ast):178    check_ast("42 + 65")179def test_binop_minus(check_ast):180    check_ast("42 - 65")181def test_binop_times(check_ast):182    check_ast("42 * 65")183def test_binop_matmult(check_ast):184    check_ast("x @ y", False)185def test_binop_div(check_ast):186    check_ast("42 / 65")187def test_binop_mod(check_ast):188    check_ast("42 % 65")189def test_binop_floordiv(check_ast):190    check_ast("42 // 65")191def test_binop_pow(check_ast):192    check_ast("2 ** 2")193def test_plus_pow(check_ast):194    check_ast("42 + 2 ** 2")195def test_plus_plus(check_ast):196    check_ast("42 + 65 + 6")197def test_plus_minus(check_ast):198    check_ast("42 + 65 - 6")199def test_minus_plus(check_ast):200    check_ast("42 - 65 + 6")201def test_minus_minus(check_ast):202    check_ast("42 - 65 - 6")203def test_minus_plus_minus(check_ast):204    check_ast("42 - 65 + 6 - 28")205def test_times_plus(check_ast):206    check_ast("42 * 65 + 6")207def test_plus_times(check_ast):208    check_ast("42 + 65 * 6")209def test_times_times(check_ast):210    check_ast("42 * 65 * 6")211def test_times_div(check_ast):212    check_ast("42 * 65 / 6")213def test_times_div_mod(check_ast):214    check_ast("42 * 65 / 6 % 28")215def test_times_div_mod_floor(check_ast):216    check_ast("42 * 65 / 6 % 28 // 13")217def test_str_str(check_ast):218    check_ast("\"hello\" 'mom'")219def test_str_str_str(check_ast):220    check_ast('"hello" \'mom\'    "wow"')221def test_str_plus_str(check_ast):222    check_ast("\"hello\" + 'mom'")223def test_str_times_int(check_ast):224    check_ast('"hello" * 20')225def test_int_times_str(check_ast):226    check_ast('2*"hello"')227def test_group_plus_times(check_ast):228    check_ast("(42 + 65) * 20")229def test_plus_group_times(check_ast):230    check_ast("42 + (65 * 20)")231def test_group(check_ast):232    check_ast("(42)")233def test_lt(check_ast):234    check_ast("42 < 65")235def test_gt(check_ast):236    check_ast("42 > 65")237def test_eq(check_ast):238    check_ast("42 == 65")239def test_le(check_ast):240    check_ast("42 <= 65")241def test_ge(check_ast):242    check_ast("42 >= 65")243def test_ne(check_ast):244    check_ast("42 != 65")245def test_in(check_ast):246    check_ast('"4" in "65"')247def test_is(check_ast):248    check_ast("int is float")  # avoid PY3.8 SyntaxWarning "is" with a literal249def test_not_in(check_ast):250    check_ast('"4" not in "65"')251def test_is_not(check_ast):252    check_ast("float is not int")253def test_lt_lt(check_ast):254    check_ast("42 < 65 < 105")255def test_lt_lt_lt(check_ast):256    check_ast("42 < 65 < 105 < 77")257def test_not(check_ast):258    check_ast("not 0")259def test_or(check_ast):260    check_ast("1 or 0")261def test_or_or(check_ast):262    check_ast("1 or 0 or 42")263def test_and(check_ast):264    check_ast("1 and 0")265def test_and_and(check_ast):266    check_ast("1 and 0 and 2")267def test_and_or(check_ast):268    check_ast("1 and 0 or 2")269def test_or_and(check_ast):270    check_ast("1 or 0 and 2")271def test_group_and_and(check_ast):272    check_ast("(1 and 0) and 2")273def test_group_and_or(check_ast):274    check_ast("(1 and 0) or 2")275def test_if_else_expr(check_ast):276    check_ast("42 if True else 65")277def test_if_else_expr_expr(check_ast):278    check_ast("42+5 if 1 == 2 else 65-5")279def test_subscription_syntaxes(eval_code):280    assert eval_code("[1, 2, 3][-1]") == 3281    assert eval_code("[1, 2, 3][-1]") == 3282    assert eval_code("'string'[-1]") == "g"283@pytest.fixture284def arr_container():285    # like numpy.r_286    class Arr:287        def __getitem__(self, item):288            return item289    return Arr()290def test_subscription_special_syntaxes(arr_container, eval_code):291    assert eval_code("arr[1, 2, 3]", arr=arr_container) == (1, 2, 3)292    # dataframe293    assert eval_code('arr[["a", "b"]]', arr=arr_container) == ["a", "b"]294# todo: enable this test295@pytest.mark.xfail296def test_subscription_special_syntaxes_2(arr_container, eval_code):297    # aliases298    d = {}299    eval_code("d[arr.__name__]=True", arr=arr_container, d=d)300    assert d == {"Arr": True}301    # extslice302    assert eval_code('arr[:, "2"]') == 2303def test_str_idx(check_ast):304    check_ast('"hello"[0]')305def test_str_slice(check_ast):306    check_ast('"hello"[0:3]')307def test_str_step(check_ast):308    check_ast('"hello"[0:3:1]')309def test_str_slice_all(check_ast):310    check_ast('"hello"[:]')311def test_str_slice_upper(check_ast):312    check_ast('"hello"[5:]')313def test_str_slice_lower(check_ast):314    check_ast('"hello"[:3]')315def test_str_slice_other(check_ast):316    check_ast('"hello"[::2]')317def test_str_slice_lower_other(check_ast):318    check_ast('"hello"[:3:2]')319def test_str_slice_upper_other(check_ast):320    check_ast('"hello"[3::2]')321def test_str_2slice(check_ast):322    check_ast('"hello"[0:3,0:3]', False)323def test_str_2step(check_ast):324    check_ast('"hello"[0:3:1,0:4:2]', False)325def test_str_2slice_all(check_ast):326    check_ast('"hello"[:,:]', False)327def test_str_2slice_upper(check_ast):328    check_ast('"hello"[5:,5:]', False)329def test_str_2slice_lower(check_ast):330    check_ast('"hello"[:3,:3]', False)331def test_str_2slice_lowerupper(check_ast):332    check_ast('"hello"[5:,:3]', False)333def test_str_2slice_other(check_ast):334    check_ast('"hello"[::2,::2]', False)335def test_str_2slice_lower_other(check_ast):336    check_ast('"hello"[:3:2,:3:2]', False)337def test_str_2slice_upper_other(check_ast):338    check_ast('"hello"[3::2,3::2]', False)339def test_str_3slice(check_ast):340    check_ast('"hello"[0:3,0:3,0:3]', False)341def test_str_3step(check_ast):342    check_ast('"hello"[0:3:1,0:4:2,1:3:2]', False)343def test_str_3slice_all(check_ast):344    check_ast('"hello"[:,:,:]', False)345def test_str_3slice_upper(check_ast):346    check_ast('"hello"[5:,5:,5:]', False)347def test_str_3slice_lower(check_ast):348    check_ast('"hello"[:3,:3,:3]', False)349def test_str_3slice_lowerlowerupper(check_ast):350    check_ast('"hello"[:3,:3,:3]', False)351def test_str_3slice_lowerupperlower(check_ast):352    check_ast('"hello"[:3,5:,:3]', False)353def test_str_3slice_lowerupperupper(check_ast):354    check_ast('"hello"[:3,5:,5:]', False)355def test_str_3slice_upperlowerlower(check_ast):356    check_ast('"hello"[5:,5:,:3]', False)357def test_str_3slice_upperlowerupper(check_ast):358    check_ast('"hello"[5:,:3,5:]', False)359def test_str_3slice_upperupperlower(check_ast):360    check_ast('"hello"[5:,5:,:3]', False)361def test_str_3slice_other(check_ast):362    check_ast('"hello"[::2,::2,::2]', False)363def test_str_3slice_lower_other(check_ast):364    check_ast('"hello"[:3:2,:3:2,:3:2]', False)365def test_str_3slice_upper_other(check_ast):366    check_ast('"hello"[3::2,3::2,3::2]', False)367def test_str_slice_true(check_ast):368    check_ast('"hello"[0:3,True]', False)369def test_str_true_slice(check_ast):370    check_ast('"hello"[True,0:3]', False)371def test_list_empty(check_ast):372    check_ast("[]")373def test_list_one(check_ast):374    check_ast("[1]")375def test_list_one_comma(check_ast):376    check_ast("[1,]")377def test_list_two(check_ast):378    check_ast("[1, 42]")379def test_list_three(check_ast):380    check_ast("[1, 42, 65]")381def test_list_three_comma(check_ast):382    check_ast("[1, 42, 65,]")383def test_list_one_nested(check_ast):384    check_ast("[[1]]")385def test_list_list_four_nested(check_ast):386    check_ast("[[1], [2], [3], [4]]")387def test_list_tuple_three_nested(check_ast):388    check_ast("[(1,), (2,), (3,)]")389def test_list_set_tuple_three_nested(check_ast):390    check_ast("[{(1,)}, {(2,)}, {(3,)}]")391def test_list_tuple_one_nested(check_ast):392    check_ast("[(1,)]")393def test_tuple_tuple_one_nested(check_ast):394    check_ast("((1,),)")395def test_dict_list_one_nested(check_ast):396    check_ast("{1: [2]}")397def test_dict_list_one_nested_comma(check_ast):398    check_ast("{1: [2],}")399def test_dict_tuple_one_nested(check_ast):400    check_ast("{1: (2,)}")401def test_dict_tuple_one_nested_comma(check_ast):402    check_ast("{1: (2,),}")403def test_dict_list_two_nested(check_ast):404    check_ast("{1: [2], 3: [4]}")405def test_set_tuple_one_nested(check_ast):406    check_ast("{(1,)}")407def test_set_tuple_two_nested(check_ast):408    check_ast("{(1,), (2,)}")409def test_tuple_empty(check_ast):410    check_ast("()")411def test_tuple_one_bare(check_ast):412    check_ast("1,")413def test_tuple_two_bare(check_ast):414    check_ast("1, 42")415def test_tuple_three_bare(check_ast):416    check_ast("1, 42, 65")417def test_tuple_three_bare_comma(check_ast):418    check_ast("1, 42, 65,")419def test_tuple_one_comma(check_ast):420    check_ast("(1,)")421def test_tuple_two(check_ast):422    check_ast("(1, 42)")423def test_tuple_three(check_ast):424    check_ast("(1, 42, 65)")425def test_tuple_three_comma(check_ast):426    check_ast("(1, 42, 65,)")427def test_bare_tuple_of_tuples(check_ast):428    check_ast("(),")429    check_ast("((),),(1,)")430    check_ast("(),(),")431    check_ast("[],")432    check_ast("[],[]")433    check_ast("[],()")434    check_ast("(),[],")435    check_ast("((),[()],)")436def test_set_one(check_ast):437    check_ast("{42}")438def test_set_one_comma(check_ast):439    check_ast("{42,}")440def test_set_two(check_ast):441    check_ast("{42, 65}")442def test_set_two_comma(check_ast):443    check_ast("{42, 65,}")444def test_set_three(check_ast):445    check_ast("{42, 65, 45}")446def test_dict_empty(check_ast):447    check_ast("{}")448def test_dict_one(check_ast):449    check_ast("{42: 65}")450def test_dict_one_comma(check_ast):451    check_ast("{42: 65,}")452def test_dict_two(check_ast):453    check_ast("{42: 65, 6: 28}")454def test_dict_two_comma(check_ast):455    check_ast("{42: 65, 6: 28,}")456def test_dict_three(check_ast):457    check_ast("{42: 65, 6: 28, 1: 2}")458def test_dict_from_dict_one(check_ast):459    check_ast('{**{"x": 2}}')460def test_dict_from_dict_one_comma(check_ast):461    check_ast('{**{"x": 2},}')462def test_dict_from_dict_two_xy(check_ast):463    check_ast('{"x": 1, **{"y": 2}}')464def test_dict_from_dict_two_x_first(check_ast):465    check_ast('{"x": 1, **{"x": 2}}')466def test_dict_from_dict_two_x_second(check_ast):467    check_ast('{**{"x": 2}, "x": 1}')468def test_dict_from_dict_two_x_none(check_ast):469    check_ast('{**{"x": 1}, **{"x": 2}}')470@pytest.mark.parametrize("third", [True, False])471@pytest.mark.parametrize("second", [True, False])472@pytest.mark.parametrize("first", [True, False])473def test_dict_from_dict_three_xyz(first, second, third, check_ast):474    val1 = '"x": 1' if first else '**{"x": 1}'475    val2 = '"y": 2' if second else '**{"y": 2}'476    val3 = '"z": 3' if third else '**{"z": 3}'477    check_ast("{" + val1 + "," + val2 + "," + val3 + "}")478def test_unpack_range_tuple(check_stmts):479    check_stmts("*range(4),")480def test_unpack_range_tuple_4(check_stmts):481    check_stmts("*range(4), 4")482def test_unpack_range_tuple_parens(check_ast):483    check_ast("(*range(4),)")484def test_unpack_range_tuple_parens_4(check_ast):485    check_ast("(*range(4), 4)")486def test_unpack_range_list(check_ast):487    check_ast("[*range(4)]")488def test_unpack_range_list_4(check_ast):489    check_ast("[*range(4), 4]")490def test_unpack_range_set(check_ast):491    check_ast("{*range(4)}")492def test_unpack_range_set_4(check_ast):493    check_ast("{*range(4), 4}")494def test_true(check_ast):495    check_ast("True")496def test_false(check_ast):497    check_ast("False")498def test_none(check_ast):499    check_ast("None")500def test_elipssis(check_ast):501    check_ast("...")502def test_not_implemented_name(check_ast):503    check_ast("NotImplemented")504def test_genexpr(check_ast):505    check_ast('(x for x in "mom")')506def test_genexpr_if(check_ast):507    check_ast('(x for x in "mom" if True)')508def test_genexpr_if_and(check_ast):509    check_ast('(x for x in "mom" if True and x == "m")')510def test_dbl_genexpr(check_ast):511    check_ast('(x+y for x in "mom" for y in "dad")')512def test_genexpr_if_genexpr(check_ast):513    check_ast('(x+y for x in "mom" if True for y in "dad")')514def test_genexpr_if_genexpr_if(check_ast):515    check_ast('(x+y for x in "mom" if True for y in "dad" if y == "d")')516def test_listcomp(check_ast):517    check_ast('[x for x in "mom"]')518def test_listcomp_if(check_ast):519    check_ast('[x for x in "mom" if True]')520def test_listcomp_if_and(check_ast):521    check_ast('[x for x in "mom" if True and x == "m"]')522def test_listcomp_multi_if(check_ast):523    check_ast('[x for x in "mom" if True if x in "mo" if x == "m"]')524def test_dbl_listcomp(check_ast):525    check_ast('[x+y for x in "mom" for y in "dad"]')526def test_listcomp_if_listcomp(check_ast):527    check_ast('[x+y for x in "mom" if True for y in "dad"]')528def test_listcomp_if_listcomp_if(check_ast):529    check_ast('[x+y for x in "mom" if True for y in "dad" if y == "d"]')530def test_setcomp(check_ast):531    check_ast('{x for x in "mom"}')532def test_setcomp_if(check_ast):533    check_ast('{x for x in "mom" if True}')534def test_setcomp_if_and(check_ast):535    check_ast('{x for x in "mom" if True and x == "m"}')536def test_dbl_setcomp(check_ast):537    check_ast('{x+y for x in "mom" for y in "dad"}')538def test_setcomp_if_setcomp(check_ast):539    check_ast('{x+y for x in "mom" if True for y in "dad"}')540def test_setcomp_if_setcomp_if(check_ast):541    check_ast('{x+y for x in "mom" if True for y in "dad" if y == "d"}')542def test_dictcomp(check_ast):543    check_ast('{x: x for x in "mom"}')544def test_dictcomp_unpack_parens(check_ast):545    check_ast('{k: v for (k, v) in {"x": 42}.items()}')546def test_dictcomp_unpack_no_parens(check_ast):547    check_ast('{k: v for k, v in {"x": 42}.items()}')548def test_dictcomp_if(check_ast):549    check_ast('{x: x for x in "mom" if True}')550def test_dictcomp_if_and(check_ast):551    check_ast('{x: x for x in "mom" if True and x == "m"}')552def test_dbl_dictcomp(check_ast):553    check_ast('{x: y for x in "mom" for y in "dad"}')554def test_dictcomp_if_dictcomp(check_ast):555    check_ast('{x: y for x in "mom" if True for y in "dad"}')556def test_dictcomp_if_dictcomp_if(check_ast):557    check_ast('{x: y for x in "mom" if True for y in "dad" if y == "d"}')558def test_lambda(check_ast):559    check_ast("lambda: 42")560def test_lambda_x(check_ast):561    check_ast("lambda x: x")562def test_lambda_kwx(check_ast):563    check_ast("lambda x=42: x")564def test_lambda_x_y(check_ast):565    check_ast("lambda x, y: x")566def test_lambda_x_y_z(check_ast):567    check_ast("lambda x, y, z: x")568def test_lambda_x_kwy(check_ast):569    check_ast("lambda x, y=42: x")570def test_lambda_kwx_kwy(check_ast):571    check_ast("lambda x=65, y=42: x")572def test_lambda_kwx_kwy_kwz(check_ast):573    check_ast("lambda x=65, y=42, z=1: x")574def test_lambda_x_comma(check_ast):575    check_ast("lambda x,: x")576def test_lambda_x_y_comma(check_ast):577    check_ast("lambda x, y,: x")578def test_lambda_x_y_z_comma(check_ast):579    check_ast("lambda x, y, z,: x")580def test_lambda_x_kwy_comma(check_ast):581    check_ast("lambda x, y=42,: x")582def test_lambda_kwx_kwy_comma(check_ast):583    check_ast("lambda x=65, y=42,: x")584def test_lambda_kwx_kwy_kwz_comma(check_ast):585    check_ast("lambda x=65, y=42, z=1,: x")586def test_lambda_args(check_ast):587    check_ast("lambda *args: 42")588def test_lambda_args_x(check_ast):589    check_ast("lambda *args, x: 42")590def test_lambda_args_x_y(check_ast):591    check_ast("lambda *args, x, y: 42")592def test_lambda_args_x_kwy(check_ast):593    check_ast("lambda *args, x, y=10: 42")594def test_lambda_args_kwx_y(check_ast):595    check_ast("lambda *args, x=10, y: 42")596def test_lambda_args_kwx_kwy(check_ast):597    check_ast("lambda *args, x=42, y=65: 42")598def test_lambda_x_args(check_ast):599    check_ast("lambda x, *args: 42")600def test_lambda_x_args_y(check_ast):601    check_ast("lambda x, *args, y: 42")602def test_lambda_x_args_y_z(check_ast):603    check_ast("lambda x, *args, y, z: 42")604def test_lambda_kwargs(check_ast):605    check_ast("lambda **kwargs: 42")606def test_lambda_x_kwargs(check_ast):607    check_ast("lambda x, **kwargs: 42")608def test_lambda_x_y_kwargs(check_ast):609    check_ast("lambda x, y, **kwargs: 42")610def test_lambda_x_kwy_kwargs(check_ast):611    check_ast("lambda x, y=42, **kwargs: 42")612def test_lambda_args_kwargs(check_ast):613    check_ast("lambda *args, **kwargs: 42")614def test_lambda_x_args_kwargs(check_ast):615    check_ast("lambda x, *args, **kwargs: 42")616def test_lambda_x_y_args_kwargs(check_ast):617    check_ast("lambda x, y, *args, **kwargs: 42")618def test_lambda_kwx_args_kwargs(check_ast):619    check_ast("lambda x=10, *args, **kwargs: 42")620def test_lambda_x_kwy_args_kwargs(check_ast):621    check_ast("lambda x, y=42, *args, **kwargs: 42")622def test_lambda_x_args_y_kwargs(check_ast):623    check_ast("lambda x, *args, y, **kwargs: 42")624def test_lambda_x_args_kwy_kwargs(check_ast):625    check_ast("lambda x, *args, y=42, **kwargs: 42")626def test_lambda_args_y_kwargs(check_ast):627    check_ast("lambda *args, y, **kwargs: 42")628def test_lambda_star_x(check_ast):629    check_ast("lambda *, x: 42")630def test_lambda_star_x_y(check_ast):631    check_ast("lambda *, x, y: 42")632def test_lambda_star_x_kwargs(check_ast):633    check_ast("lambda *, x, **kwargs: 42")634def test_lambda_star_kwx_kwargs(check_ast):635    check_ast("lambda *, x=42, **kwargs: 42")636def test_lambda_x_star_y(check_ast):637    check_ast("lambda x, *, y: 42")638def test_lambda_x_y_star_z(check_ast):639    check_ast("lambda x, y, *, z: 42")640def test_lambda_x_kwy_star_y(check_ast):641    check_ast("lambda x, y=42, *, z: 42")642def test_lambda_x_kwy_star_kwy(check_ast):643    check_ast("lambda x, y=42, *, z=65: 42")644def test_lambda_x_star_y_kwargs(check_ast):645    check_ast("lambda x, *, y, **kwargs: 42")646@skip_if_pre_3_8647def test_lambda_x_divide_y_star_z_kwargs(check_ast):648    check_ast("lambda x, /, y, *, z, **kwargs: 42")649def test_call_range(check_ast):650    check_ast("range(6)")651def test_call_range_comma(check_ast):652    check_ast("range(6,)")653def test_call_range_x_y(check_ast):654    check_ast("range(6, 10)")655def test_call_range_x_y_comma(check_ast):656    check_ast("range(6, 10,)")657def test_call_range_x_y_z(check_ast):658    check_ast("range(6, 10, 2)")659def test_call_dict_kwx(check_ast):660    check_ast("dict(start=10)")661def test_call_dict_kwx_comma(check_ast):662    check_ast("dict(start=10,)")663def test_call_dict_kwx_kwy(check_ast):664    check_ast("dict(start=10, stop=42)")665def test_call_tuple_gen(check_ast):666    check_ast("tuple(x for x in [1, 2, 3])")667def test_call_tuple_genifs(check_ast):668    check_ast("tuple(x for x in [1, 2, 3] if x < 3)")669def test_call_range_star(check_ast):670    check_ast("range(*[1, 2, 3])")671def test_call_range_x_star(check_ast):672    check_ast("range(1, *[2, 3])")673def test_call_int(check_ast):674    check_ast('int(*["42"], base=8)')675def test_call_int_base_dict(check_ast):676    check_ast('int(*["42"], **{"base": 8})')677def test_call_dict_kwargs(check_ast):678    check_ast('dict(**{"base": 8})')679def test_call_list_many_star_args(check_ast):680    check_ast("min(*[1, 2], 3, *[4, 5])")681def test_call_list_many_starstar_args(check_ast):682    check_ast('dict(**{"a": 2}, v=3, **{"c": 5})')683def test_call_list_many_star_and_starstar_args(check_ast):684    check_ast('x(*[("a", 2)], *[("v", 3)], **{"c": 5})', False)685def test_call_alot(check_ast):686    check_ast("x(1, *args, **kwargs)", False)687def test_call_alot_next(check_ast):688    check_ast("x(x=1, *args, **kwargs)", False)689def test_call_alot_next_next(check_ast):690    check_ast("x(x=1, *args, y=42, **kwargs)", False)691def test_getattr(check_ast):692    check_ast("list.append")693def test_getattr_getattr(check_ast):694    check_ast("list.append.__str__")695def test_dict_tuple_key(check_ast):696    check_ast("{(42, 1): 65}")697def test_dict_tuple_key_get(check_ast):698    check_ast("{(42, 1): 65}[42, 1]")699def test_dict_tuple_key_get_3(check_ast):700    check_ast("{(42, 1, 3): 65}[42, 1, 3]")701def test_pipe_op(check_ast):702    check_ast("{42} | {65}")703def test_pipe_op_two(check_ast):704    check_ast("{42} | {65} | {1}")705def test_pipe_op_three(check_ast):706    check_ast("{42} | {65} | {1} | {7}")707def test_xor_op(check_ast):708    check_ast("{42} ^ {65}")709def test_xor_op_two(check_ast):710    check_ast("{42} ^ {65} ^ {1}")711def test_xor_op_three(check_ast):712    check_ast("{42} ^ {65} ^ {1} ^ {7}")713def test_xor_pipe(check_ast):714    check_ast("{42} ^ {65} | {1}")715def test_amp_op(check_ast):716    check_ast("{42} & {65}")717def test_amp_op_two(check_ast):718    check_ast("{42} & {65} & {1}")719def test_amp_op_three(check_ast):720    check_ast("{42} & {65} & {1} & {7}")721def test_lshift_op(check_ast):722    check_ast("42 << 65")723def test_lshift_op_two(check_ast):724    check_ast("42 << 65 << 1")725def test_lshift_op_three(check_ast):726    check_ast("42 << 65 << 1 << 7")727def test_rshift_op(check_ast):728    check_ast("42 >> 65")729def test_rshift_op_two(check_ast):730    check_ast("42 >> 65 >> 1")731def test_rshift_op_three(check_ast):732    check_ast("42 >> 65 >> 1 >> 7")733@skip_if_pre_3_8734def test_named_expr(check_ast):735    check_ast("(x := 42)")736@skip_if_pre_3_8737def test_named_expr_list(check_ast):738    check_ast("[x := 42, x + 1, x + 2]")739#740# statements741#742def test_equals(check_stmts):743    check_stmts("x = 42")744def test_equals_semi(check_stmts):745    check_stmts("x = 42;")746def test_x_y_equals_semi(check_stmts):747    check_stmts("x = y = 42")748def test_equals_two(check_stmts):749    check_stmts("x = 42; y = 65")750def test_equals_two_semi(check_stmts):751    check_stmts("x = 42; y = 65;")752def test_equals_three(check_stmts):753    check_stmts("x = 42; y = 65; z = 6")754def test_equals_three_semi(check_stmts):755    check_stmts("x = 42; y = 65; z = 6;")756def test_plus_eq(check_stmts):757    check_stmts("x = 42; x += 65")758def test_sub_eq(check_stmts):759    check_stmts("x = 42; x -= 2")760def test_times_eq(check_stmts):761    check_stmts("x = 42; x *= 2")762def test_matmult_eq(check_stmts):763    check_stmts("x @= y", False)764def test_div_eq(check_stmts):765    check_stmts("x = 42; x /= 2")766def test_floordiv_eq(check_stmts):767    check_stmts("x = 42; x //= 2")768def test_pow_eq(check_stmts):769    check_stmts("x = 42; x **= 2")770def test_mod_eq(check_stmts):771    check_stmts("x = 42; x %= 2")772def test_xor_eq(check_stmts):773    check_stmts("x = 42; x ^= 2")774def test_ampersand_eq(check_stmts):775    check_stmts("x = 42; x &= 2")776def test_bitor_eq(check_stmts):777    check_stmts("x = 42; x |= 2")778def test_lshift_eq(check_stmts):779    check_stmts("x = 42; x <<= 2")780def test_rshift_eq(check_stmts):781    check_stmts("x = 42; x >>= 2")782def test_bare_unpack(check_stmts):783    check_stmts("x, y = 42, 65")784def test_lhand_group_unpack(check_stmts):785    check_stmts("(x, y) = 42, 65")786def test_rhand_group_unpack(check_stmts):787    check_stmts("x, y = (42, 65)")788def test_grouped_unpack(check_stmts):789    check_stmts("(x, y) = (42, 65)")790def test_double_grouped_unpack(check_stmts):791    check_stmts("(x, y) = (z, a) = (7, 8)")792def test_double_ungrouped_unpack(check_stmts):793    check_stmts("x, y = z, a = 7, 8")794def test_stary_eq(check_stmts):795    check_stmts("*y, = [1, 2, 3]")796def test_stary_x(check_stmts):797    check_stmts("*y, x = [1, 2, 3]")798def test_tuple_x_stary(check_stmts):799    check_stmts("(x, *y) = [1, 2, 3]")800def test_list_x_stary(check_stmts):801    check_stmts("[x, *y] = [1, 2, 3]")802def test_bare_x_stary(check_stmts):803    check_stmts("x, *y = [1, 2, 3]")804def test_bare_x_stary_z(check_stmts):805    check_stmts("x, *y, z = [1, 2, 2, 3]")806def test_equals_list(check_stmts):807    check_stmts("x = [42]; x[0] = 65")808def test_equals_dict(check_stmts):809    check_stmts("x = {42: 65}; x[42] = 3")810def test_equals_attr(check_stmts):811    check_stmts("class X(object):\n  pass\nx = X()\nx.a = 65")812def test_equals_annotation(check_stmts):813    check_stmts("x : int = 42")814def test_equals_annotation_empty(check_stmts):815    check_stmts("x : int")816def test_dict_keys(check_stmts):817    check_stmts('x = {"x": 1}\nx.keys()')818def test_assert_msg(check_stmts):819    check_stmts('assert True, "wow mom"')820def test_assert(check_stmts):821    check_stmts("assert True")822def test_pass(check_stmts):823    check_stmts("pass")824def test_del(check_stmts):825    check_stmts("x = 42; del x")826def test_del_comma(check_stmts):827    check_stmts("x = 42; del x,")828def test_del_two(check_stmts):829    check_stmts("x = 42; y = 65; del x, y")830def test_del_two_comma(check_stmts):831    check_stmts("x = 42; y = 65; del x, y,")832def test_del_with_parens(check_stmts):833    check_stmts("x = 42; y = 65; del (x, y)")834def test_raise(check_stmts):835    check_stmts("raise", False)836def test_raise_x(check_stmts):837    check_stmts("raise TypeError", False)838def test_raise_x_from(check_stmts):839    check_stmts("raise TypeError from x", False)840def test_import_x(check_stmts):841    check_stmts("import x", False)842def test_import_xy(check_stmts):843    check_stmts("import x.y", False)844def test_import_xyz(check_stmts):845    check_stmts("import x.y.z", False)846def test_from_x_import_y(check_stmts):847    check_stmts("from x import y", False)848def test_from_dot_import_y(check_stmts):849    check_stmts("from . import y", False)850def test_from_dotx_import_y(check_stmts):851    check_stmts("from .x import y", False)852def test_from_dotdotx_import_y(check_stmts):853    check_stmts("from ..x import y", False)854def test_from_dotdotdotx_import_y(check_stmts):855    check_stmts("from ...x import y", False)856def test_from_dotdotdotdotx_import_y(check_stmts):857    check_stmts("from ....x import y", False)858def test_from_import_x_y(check_stmts):859    check_stmts("import x, y", False)860def test_from_import_x_y_z(check_stmts):861    check_stmts("import x, y, z", False)862def test_from_dot_import_x_y(check_stmts):863    check_stmts("from . import x, y", False)864def test_from_dot_import_x_y_z(check_stmts):865    check_stmts("from . import x, y, z", False)866def test_from_dot_import_group_x_y(check_stmts):867    check_stmts("from . import (x, y)", False)868def test_import_x_as_y(check_stmts):869    check_stmts("import x as y", False)870def test_import_xy_as_z(check_stmts):871    check_stmts("import x.y as z", False)872def test_import_x_y_as_z(check_stmts):873    check_stmts("import x, y as z", False)874def test_import_x_as_y_z(check_stmts):875    check_stmts("import x as y, z", False)876def test_import_x_as_y_z_as_a(check_stmts):877    check_stmts("import x as y, z as a", False)878def test_from_dot_import_x_as_y(check_stmts):879    check_stmts("from . import x as y", False)880def test_from_x_import_star(check_stmts):881    check_stmts("from x import *", False)882def test_from_x_import_group_x_y_z(check_stmts):883    check_stmts("from x import (x, y, z)", False)884def test_from_x_import_group_x_y_z_comma(check_stmts):885    check_stmts("from x import (x, y, z,)", False)886def test_from_x_import_y_as_z(check_stmts):887    check_stmts("from x import y as z", False)888def test_from_x_import_y_as_z_a_as_b(check_stmts):889    check_stmts("from x import y as z, a as b", False)890def test_from_dotx_import_y_as_z_a_as_b_c_as_d(check_stmts):891    check_stmts("from .x import y as z, a as b, c as d", False)892def test_continue(check_stmts):893    check_stmts("continue", False)894def test_break(check_stmts):895    check_stmts("break", False)896def test_global(check_stmts):897    check_stmts("global x", False)898def test_global_xy(check_stmts):899    check_stmts("global x, y", False)900def test_nonlocal_x(check_stmts):901    check_stmts("nonlocal x", False)902def test_nonlocal_xy(check_stmts):903    check_stmts("nonlocal x, y", False)904def test_yield(check_stmts):905    check_stmts("yield", False)906def test_yield_x(check_stmts):907    check_stmts("yield x", False)908def test_yield_x_comma(check_stmts):909    check_stmts("yield x,", False)910def test_yield_x_y(check_stmts):911    check_stmts("yield x, y", False)912@skip_if_pre_3_8913def test_yield_x_starexpr(check_stmts):914    check_stmts("yield x, *[y, z]", False)915def test_yield_from_x(check_stmts):916    check_stmts("yield from x", False)917def test_return(check_stmts):918    check_stmts("return", False)919def test_return_x(check_stmts):920    check_stmts("return x", False)921def test_return_x_comma(check_stmts):922    check_stmts("return x,", False)923def test_return_x_y(check_stmts):924    check_stmts("return x, y", False)925@skip_if_pre_3_8926def test_return_x_starexpr(check_stmts):927    check_stmts("return x, *[y, z]", False)928def test_if_true(check_stmts):929    check_stmts("if True:\n  pass")930def test_if_true_twolines(check_stmts):931    check_stmts("if True:\n  pass\n  pass")932def test_if_true_twolines_deindent(check_stmts):933    check_stmts("if True:\n  pass\n  pass\npass")934def test_if_true_else(check_stmts):935    check_stmts("if True:\n  pass\nelse: \n  pass")936def test_if_true_x(check_stmts):937    check_stmts("if True:\n  x = 42")938def test_if_switch(check_stmts):939    check_stmts("x = 42\nif x == 1:\n  pass")940def test_if_switch_elif1_else(check_stmts):941    check_stmts("x = 42\nif x == 1:\n  pass\n" "elif x == 2:\n  pass\nelse:\n  pass")942def test_if_switch_elif2_else(check_stmts):943    check_stmts(944        "x = 42\nif x == 1:\n  pass\n"945        "elif x == 2:\n  pass\n"946        "elif x == 3:\n  pass\n"947        "elif x == 4:\n  pass\n"948        "else:\n  pass"949    )950def test_if_nested(check_stmts):951    check_stmts("x = 42\nif x == 1:\n  pass\n  if x == 4:\n     pass")952def test_while(check_stmts):953    check_stmts("while False:\n  pass")954def test_while_else(check_stmts):955    check_stmts("while False:\n  pass\nelse:\n  pass")956def test_for(check_stmts):957    check_stmts("for x in range(6):\n  pass")958def test_for_zip(check_stmts):959    check_stmts('for x, y in zip(range(6), "123456"):\n  pass')960def test_for_idx(check_stmts):961    check_stmts("x = [42]\nfor x[0] in range(3):\n  pass")962def test_for_zip_idx(check_stmts):963    check_stmts('x = [42]\nfor x[0], y in zip(range(6), "123456"):\n' "  pass")964def test_for_attr(check_stmts):965    check_stmts("for x.a in range(3):\n  pass", False)966def test_for_zip_attr(check_stmts):967    check_stmts('for x.a, y in zip(range(6), "123456"):\n  pass', False)968def test_for_else(check_stmts):969    check_stmts("for x in range(6):\n  pass\nelse:  pass")970def test_async_for(check_stmts):971    check_stmts("async def f():\n    async for x in y:\n        pass\n", False)972def test_with(check_stmts):973    check_stmts("with x:\n  pass", False)974def test_with_as(check_stmts):975    check_stmts("with x as y:\n  pass", False)976def test_with_xy(check_stmts):977    check_stmts("with x, y:\n  pass", False)978def test_with_x_as_y_z(check_stmts):979    check_stmts("with x as y, z:\n  pass", False)980def test_with_x_as_y_a_as_b(check_stmts):981    check_stmts("with x as y, a as b:\n  pass", False)982def test_with_in_func(check_stmts):983    check_stmts("def f():\n    with x:\n        pass\n")984def test_async_with(check_stmts):985    check_stmts("async def f():\n    async with x as y:\n        pass\n", False)986def test_try(check_stmts):987    check_stmts("try:\n  pass\nexcept:\n  pass", False)988def test_try_except_t(check_stmts):989    check_stmts("try:\n  pass\nexcept TypeError:\n  pass", False)990def test_try_except_t_as_e(check_stmts):991    check_stmts("try:\n  pass\nexcept TypeError as e:\n  pass", False)992def test_try_except_t_u(check_stmts):993    check_stmts("try:\n  pass\nexcept (TypeError, SyntaxError):\n  pass", False)994def test_try_except_t_u_as_e(check_stmts):995    check_stmts("try:\n  pass\nexcept (TypeError, SyntaxError) as e:\n  pass", False)996def test_try_except_t_except_u(check_stmts):997    check_stmts(998        "try:\n  pass\nexcept TypeError:\n  pass\n" "except SyntaxError as f:\n  pass",999        False,1000    )1001def test_try_except_else(check_stmts):1002    check_stmts("try:\n  pass\nexcept:\n  pass\nelse:  pass", False)1003def test_try_except_finally(check_stmts):1004    check_stmts("try:\n  pass\nexcept:\n  pass\nfinally:  pass", False)1005def test_try_except_else_finally(check_stmts):1006    check_stmts(1007        "try:\n  pass\nexcept:\n  pass\nelse:\n  pass" "\nfinally:  pass", False1008    )1009def test_try_finally(check_stmts):1010    check_stmts("try:\n  pass\nfinally:  pass", False)1011def test_func(check_stmts):1012    check_stmts("def f():\n  pass")1013def test_func_ret(check_stmts):1014    check_stmts("def f():\n  return")1015def test_func_ret_42(check_stmts):1016    check_stmts("def f():\n  return 42")1017def test_func_ret_42_65(check_stmts):1018    check_stmts("def f():\n  return 42, 65")1019def test_func_rarrow(check_stmts):1020    check_stmts("def f() -> int:\n  pass")1021def test_func_x(check_stmts):1022    check_stmts("def f(x):\n  return x")1023def test_func_kwx(check_stmts):1024    check_stmts("def f(x=42):\n  return x")1025def test_func_x_y(check_stmts):1026    check_stmts("def f(x, y):\n  return x")1027def test_func_x_y_z(check_stmts):1028    check_stmts("def f(x, y, z):\n  return x")1029def test_func_x_kwy(check_stmts):1030    check_stmts("def f(x, y=42):\n  return x")1031def test_func_kwx_kwy(check_stmts):1032    check_stmts("def f(x=65, y=42):\n  return x")1033def test_func_kwx_kwy_kwz(check_stmts):1034    check_stmts("def f(x=65, y=42, z=1):\n  return x")1035def test_func_x_comma(check_stmts):1036    check_stmts("def f(x,):\n  return x")1037def test_func_x_y_comma(check_stmts):1038    check_stmts("def f(x, y,):\n  return x")1039def test_func_x_y_z_comma(check_stmts):1040    check_stmts("def f(x, y, z,):\n  return x")1041def test_func_x_kwy_comma(check_stmts):1042    check_stmts("def f(x, y=42,):\n  return x")1043def test_func_kwx_kwy_comma(check_stmts):1044    check_stmts("def f(x=65, y=42,):\n  return x")1045def test_func_kwx_kwy_kwz_comma(check_stmts):1046    check_stmts("def f(x=65, y=42, z=1,):\n  return x")1047def test_func_args(check_stmts):1048    check_stmts("def f(*args):\n  return 42")1049def test_func_args_x(check_stmts):1050    check_stmts("def f(*args, x):\n  return 42")1051def test_func_args_x_y(check_stmts):1052    check_stmts("def f(*args, x, y):\n  return 42")1053def test_func_args_x_kwy(check_stmts):1054    check_stmts("def f(*args, x, y=10):\n  return 42")1055def test_func_args_kwx_y(check_stmts):1056    check_stmts("def f(*args, x=10, y):\n  return 42")1057def test_func_args_kwx_kwy(check_stmts):1058    check_stmts("def f(*args, x=42, y=65):\n  return 42")1059def test_func_x_args(check_stmts):1060    check_stmts("def f(x, *args):\n  return 42")1061def test_func_x_args_y(check_stmts):1062    check_stmts("def f(x, *args, y):\n  return 42")1063def test_func_x_args_y_z(check_stmts):1064    check_stmts("def f(x, *args, y, z):\n  return 42")1065def test_func_kwargs(check_stmts):1066    check_stmts("def f(**kwargs):\n  return 42")1067def test_func_x_kwargs(check_stmts):1068    check_stmts("def f(x, **kwargs):\n  return 42")1069def test_func_x_y_kwargs(check_stmts):1070    check_stmts("def f(x, y, **kwargs):\n  return 42")1071def test_func_x_kwy_kwargs(check_stmts):1072    check_stmts("def f(x, y=42, **kwargs):\n  return 42")1073def test_func_args_kwargs(check_stmts):1074    check_stmts("def f(*args, **kwargs):\n  return 42")1075def test_func_x_args_kwargs(check_stmts):1076    check_stmts("def f(x, *args, **kwargs):\n  return 42")1077def test_func_x_y_args_kwargs(check_stmts):1078    check_stmts("def f(x, y, *args, **kwargs):\n  return 42")1079def test_func_kwx_args_kwargs(check_stmts):1080    check_stmts("def f(x=10, *args, **kwargs):\n  return 42")1081def test_func_x_kwy_args_kwargs(check_stmts):1082    check_stmts("def f(x, y=42, *args, **kwargs):\n  return 42")1083def test_func_x_args_y_kwargs(check_stmts):1084    check_stmts("def f(x, *args, y, **kwargs):\n  return 42")1085def test_func_x_args_kwy_kwargs(check_stmts):1086    check_stmts("def f(x, *args, y=42, **kwargs):\n  return 42")1087def test_func_args_y_kwargs(check_stmts):1088    check_stmts("def f(*args, y, **kwargs):\n  return 42")1089def test_func_star_x(check_stmts):1090    check_stmts("def f(*, x):\n  return 42")1091def test_func_star_x_y(check_stmts):1092    check_stmts("def f(*, x, y):\n  return 42")1093def test_func_star_x_kwargs(check_stmts):1094    check_stmts("def f(*, x, **kwargs):\n  return 42")1095def test_func_star_kwx_kwargs(check_stmts):1096    check_stmts("def f(*, x=42, **kwargs):\n  return 42")1097def test_func_x_star_y(check_stmts):1098    check_stmts("def f(x, *, y):\n  return 42")1099def test_func_x_y_star_z(check_stmts):1100    check_stmts("def f(x, y, *, z):\n  return 42")1101def test_func_x_kwy_star_y(check_stmts):1102    check_stmts("def f(x, y=42, *, z):\n  return 42")1103def test_func_x_kwy_star_kwy(check_stmts):1104    check_stmts("def f(x, y=42, *, z=65):\n  return 42")1105def test_func_x_star_y_kwargs(check_stmts):1106    check_stmts("def f(x, *, y, **kwargs):\n  return 42")1107@skip_if_pre_3_81108def test_func_x_divide(check_stmts):1109    check_stmts("def f(x, /):\n  return 42")1110@skip_if_pre_3_81111def test_func_x_divide_y_star_z_kwargs(check_stmts):1112    check_stmts("def f(x, /, y, *, z, **kwargs):\n  return 42")1113def test_func_tx(check_stmts):1114    check_stmts("def f(x:int):\n  return x")1115def test_func_txy(check_stmts):1116    check_stmts("def f(x:int, y:float=10.0):\n  return x")1117def test_class(check_stmts):1118    check_stmts("class X:\n  pass")1119def test_class_obj(check_stmts):1120    check_stmts("class X(object):\n  pass")1121def test_class_int_flt(check_stmts):1122    check_stmts("class X(int, object):\n  pass")1123def test_class_obj_kw(check_stmts):1124    # technically valid syntax, though it will fail to compile1125    check_stmts("class X(object=5):\n  pass", False)1126def test_decorator(check_stmts):1127    check_stmts("@g\ndef f():\n  pass", False)1128def test_decorator_2(check_stmts):1129    check_stmts("@h\n@g\ndef f():\n  pass", False)1130def test_decorator_call(check_stmts):1131    check_stmts("@g()\ndef f():\n  pass", False)1132def test_decorator_call_args(check_stmts):1133    check_stmts("@g(x, y=10)\ndef f():\n  pass", False)1134def test_decorator_dot_call_args(check_stmts):1135    check_stmts("@h.g(x, y=10)\ndef f():\n  pass", False)1136def test_decorator_dot_dot_call_args(check_stmts):1137    check_stmts("@i.h.g(x, y=10)\ndef f():\n  pass", False)1138def test_broken_prompt_func(check_stmts):1139    code = "def prompt():\n" "    return '{user}'.format(\n" "       user='me')\n"1140    check_stmts(code, False)1141def test_class_with_methods(check_stmts):1142    code = (1143        "class Test:\n"1144        "   def __init__(self):\n"1145        '       self.msg("hello world")\n'1146        "   def msg(self, m):\n"1147        "      print(m)\n"1148    )1149    check_stmts(code, False)1150def test_nested_functions(check_stmts):1151    code = (1152        "def test(x):\n"1153        "    def test2(y):\n"1154        "        return y+x\n"1155        "    return test2\n"1156    )1157    check_stmts(code, False)1158def test_function_blank_line(check_stmts):1159    code = (1160        "def foo():\n"1161        "    ascii_art = [\n"1162        '        "(â¯Â°â¡Â°ï¼â¯ï¸µ â»ââ»",\n'1163        r'        "¯\\_(ã)_/¯",'1164        "\n"1165        r'        "â»ââ»ï¸µ \\(°â¡Â°)/ ︵ â»ââ»",'1166        "\n"1167        "    ]\n"1168        "\n"1169        "    import random\n"1170        "    i = random.randint(0,len(ascii_art)) - 1\n"1171        '    print("    Get to work!")\n'1172        "    print(ascii_art[i])\n"1173    )1174    check_stmts(code, False)1175def test_async_func(check_stmts):1176    check_stmts("async def f():\n  pass\n")1177def test_async_decorator(check_stmts):1178    check_stmts("@g\nasync def f():\n  pass", False)1179def test_async_await(check_stmts):1180    check_stmts("async def f():\n    await fut\n", False)1181@skip_if_pre_3_81182def test_named_expr_args(check_stmts):1183    check_stmts("id(x := 42)")1184@skip_if_pre_3_81185def test_named_expr_if(check_stmts):1186    check_stmts("if (x := 42) > 0:\n  x += 1")1187@skip_if_pre_3_81188def test_named_expr_elif(check_stmts):1189    check_stmts("if False:\n  pass\nelif x := 42:\n  x += 1")1190@skip_if_pre_3_81191def test_named_expr_while(check_stmts):1192    check_stmts("y = 42\nwhile (x := y) < 43:\n  y += 1")1193#1194# Xonsh specific syntax1195#1196def test_path_literal(check_xonsh_ast):1197    check_xonsh_ast({}, 'p"/foo"', False)1198    check_xonsh_ast({}, 'pr"/foo"', False)1199    check_xonsh_ast({}, 'rp"/foo"', False)1200    check_xonsh_ast({}, 'pR"/foo"', False)1201    check_xonsh_ast({}, 'Rp"/foo"', False)1202def test_path_fstring_literal(check_xonsh_ast):1203    check_xonsh_ast({}, 'pf"/foo"', False)1204    check_xonsh_ast({}, 'fp"/foo"', False)1205    check_xonsh_ast({}, 'pF"/foo"', False)1206    check_xonsh_ast({}, 'Fp"/foo"', False)1207    check_xonsh_ast({}, 'pf"/foo{1+1}"', False)1208    check_xonsh_ast({}, 'fp"/foo{1+1}"', False)1209    check_xonsh_ast({}, 'pF"/foo{1+1}"', False)1210    check_xonsh_ast({}, 'Fp"/foo{1+1}"', False)1211@pytest.mark.parametrize(1212    "first_prefix, second_prefix",1213    itertools.product(["p", "pf", "pr"], repeat=2),1214)1215def test_path_literal_concat(first_prefix, second_prefix, check_xonsh_ast):1216    check_xonsh_ast(1217        {}, first_prefix + r"'11{a}22\n'" + " " + second_prefix + r"'33{b}44\n'", False1218    )1219def test_dollar_name(check_xonsh_ast):1220    check_xonsh_ast({"WAKKA": 42}, "$WAKKA")1221def test_dollar_py(check_xonsh):1222    check_xonsh({"WAKKA": 42}, 'x = "WAKKA"; y = ${x}')1223def test_dollar_py_test(check_xonsh_ast):1224    check_xonsh_ast({"WAKKA": 42}, '${None or "WAKKA"}')1225def test_dollar_py_recursive_name(check_xonsh_ast):1226    check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, "${$JAWAKA}")1227def test_dollar_py_test_recursive_name(check_xonsh_ast):1228    check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, "${None or $JAWAKA}")1229def test_dollar_py_test_recursive_test(check_xonsh_ast):1230    check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, '${${"JAWA" + $JAWAKA[-2:]}}')1231def test_dollar_name_set(check_xonsh):1232    check_xonsh({"WAKKA": 42}, "$WAKKA = 42")1233def test_dollar_py_set(check_xonsh):1234    check_xonsh({"WAKKA": 42}, 'x = "WAKKA"; ${x} = 65')1235def test_dollar_sub(check_xonsh_ast):1236    check_xonsh_ast({}, "$(ls)", False)1237@pytest.mark.parametrize(1238    "expr",1239    [1240        "$(ls )",1241        "$( ls)",1242        "$( ls )",1243    ],1244)1245def test_dollar_sub_space(expr, check_xonsh_ast):1246    check_xonsh_ast({}, expr, False)1247def test_ls_dot(check_xonsh_ast):1248    check_xonsh_ast({}, "$(ls .)", False)1249def test_lambda_in_atparens(check_xonsh_ast):1250    check_xonsh_ast(1251        {}, '$(echo hello | @(lambda a, s=None: "hey!") foo bar baz)', False1252    )1253def test_generator_in_atparens(check_xonsh_ast):1254    check_xonsh_ast({}, "$(echo @(i**2 for i in range(20)))", False)1255def test_bare_tuple_in_atparens(check_xonsh_ast):1256    check_xonsh_ast({}, '$(echo @("a", 7))', False)1257def test_nested_madness(check_xonsh_ast):1258    check_xonsh_ast(1259        {},1260        "$(@$(which echo) ls | @(lambda a, s=None: $(@(s.strip()) @(a[1]))) foo -la baz)",1261        False,1262    )1263def test_atparens_intoken(check_xonsh_ast):1264    check_xonsh_ast({}, "![echo /x/@(y)/z]", False)1265def test_ls_dot_nesting(check_xonsh_ast):1266    check_xonsh_ast({}, '$(ls @(None or "."))', False)1267def test_ls_dot_nesting_var(check_xonsh):1268    check_xonsh({}, 'x = "."; $(ls @(None or x))', False)1269def test_ls_dot_str(check_xonsh_ast):1270    check_xonsh_ast({}, '$(ls ".")', False)1271def test_ls_nest_ls(check_xonsh_ast):1272    check_xonsh_ast({}, "$(ls $(ls))", False)1273def test_ls_nest_ls_dashl(check_xonsh_ast):1274    check_xonsh_ast({}, "$(ls $(ls) -l)", False)1275def test_ls_envvar_strval(check_xonsh_ast):1276    check_xonsh_ast({"WAKKA": "."}, "$(ls $WAKKA)", False)1277def test_ls_envvar_listval(check_xonsh_ast):1278    check_xonsh_ast({"WAKKA": [".", "."]}, "$(ls $WAKKA)", False)1279def test_bang_sub(check_xonsh_ast):1280    check_xonsh_ast({}, "!(ls)", False)1281@pytest.mark.parametrize(1282    "expr",1283    [1284        "!(ls )",1285        "!( ls)",1286        "!( ls )",1287    ],1288)1289def test_bang_sub_space(expr, check_xonsh_ast):1290    check_xonsh_ast({}, expr, False)1291def test_bang_ls_dot(check_xonsh_ast):1292    check_xonsh_ast({}, "!(ls .)", False)1293def test_bang_ls_dot_nesting(check_xonsh_ast):1294    check_xonsh_ast({}, '!(ls @(None or "."))', False)1295def test_bang_ls_dot_nesting_var(check_xonsh):1296    check_xonsh({}, 'x = "."; !(ls @(None or x))', False)1297def test_bang_ls_dot_str(check_xonsh_ast):1298    check_xonsh_ast({}, '!(ls ".")', False)1299def test_bang_ls_nest_ls(check_xonsh_ast):1300    check_xonsh_ast({}, "!(ls $(ls))", False)1301def test_bang_ls_nest_ls_dashl(check_xonsh_ast):1302    check_xonsh_ast({}, "!(ls $(ls) -l)", False)1303def test_bang_ls_envvar_strval(check_xonsh_ast):1304    check_xonsh_ast({"WAKKA": "."}, "!(ls $WAKKA)", False)1305def test_bang_ls_envvar_listval(check_xonsh_ast):1306    check_xonsh_ast({"WAKKA": [".", "."]}, "!(ls $WAKKA)", False)1307def test_bang_envvar_args(check_xonsh_ast):1308    check_xonsh_ast({"LS": "ls"}, "!($LS .)", False)1309def test_question(check_xonsh_ast):1310    check_xonsh_ast({}, "range?")1311def test_dobquestion(check_xonsh_ast):1312    check_xonsh_ast({}, "range??")1313def test_question_chain(check_xonsh_ast):1314    check_xonsh_ast({}, "range?.index?")1315def test_ls_regex(check_xonsh_ast):1316    check_xonsh_ast({}, "$(ls `[Ff]+i*LE` -l)", False)1317@pytest.mark.parametrize("p", ["", "p"])1318@pytest.mark.parametrize("f", ["", "f"])1319@pytest.mark.parametrize("glob_type", ["", "r", "g"])1320def test_backtick(p, f, glob_type, check_xonsh_ast):1321    check_xonsh_ast({}, f"print({p}{f}{glob_type}`.*`)", False)1322def test_ls_regex_octothorpe(check_xonsh_ast):1323    check_xonsh_ast({}, "$(ls `#[Ff]+i*LE` -l)", False)1324def test_ls_explicitregex(check_xonsh_ast):1325    check_xonsh_ast({}, "$(ls r`[Ff]+i*LE` -l)", False)1326def test_ls_explicitregex_octothorpe(check_xonsh_ast):1327    check_xonsh_ast({}, "$(ls r`#[Ff]+i*LE` -l)", False)1328def test_ls_glob(check_xonsh_ast):1329    check_xonsh_ast({}, "$(ls g`[Ff]+i*LE` -l)", False)1330def test_ls_glob_octothorpe(check_xonsh_ast):1331    check_xonsh_ast({}, "$(ls g`#[Ff]+i*LE` -l)", False)1332def test_ls_customsearch(check_xonsh_ast):1333    check_xonsh_ast({}, "$(ls @foo`[Ff]+i*LE` -l)", False)1334def test_custombacktick(check_xonsh_ast):1335    check_xonsh_ast({}, "print(@foo`.*`)", False)1336def test_ls_customsearch_octothorpe(check_xonsh_ast):1337    check_xonsh_ast({}, "$(ls @foo`#[Ff]+i*LE` -l)", False)1338def test_injection(check_xonsh_ast):1339    check_xonsh_ast({}, "$[@$(which python)]", False)1340def test_rhs_nested_injection(check_xonsh_ast):1341    check_xonsh_ast({}, "$[ls @$(dirname @$(which python))]", False)1342def test_merged_injection(check_xonsh_ast):1343    tree = check_xonsh_ast({}, "![a@$(echo 1 2)b]", False, return_obs=True)1344    assert isinstance(tree, AST)1345    func = tree.body.args[0].right.func1346    assert func.attr == "list_of_list_of_strs_outer_product"1347def test_backtick_octothorpe(check_xonsh_ast):1348    check_xonsh_ast({}, "print(`#.*`)", False)1349def test_uncaptured_sub(check_xonsh_ast):1350    check_xonsh_ast({}, "$[ls]", False)1351def test_hiddenobj_sub(check_xonsh_ast):1352    check_xonsh_ast({}, "![ls]", False)1353def test_slash_envarv_echo(check_xonsh_ast):1354    check_xonsh_ast({}, "![echo $HOME/place]", False)1355def test_echo_double_eq(check_xonsh_ast):1356    check_xonsh_ast({}, "![echo yo==yo]", False)1357def test_bang_two_cmds_one_pipe(check_xonsh_ast):1358    check_xonsh_ast({}, "!(ls | grep wakka)", False)1359def test_bang_three_cmds_two_pipes(check_xonsh_ast):1360    check_xonsh_ast({}, "!(ls | grep wakka | grep jawaka)", False)1361def test_bang_one_cmd_write(check_xonsh_ast):1362    check_xonsh_ast({}, "!(ls > x.py)", False)1363def test_bang_one_cmd_append(check_xonsh_ast):1364    check_xonsh_ast({}, "!(ls >> x.py)", False)1365def test_bang_two_cmds_write(check_xonsh_ast):1366    check_xonsh_ast({}, "!(ls | grep wakka > x.py)", False)1367def test_bang_two_cmds_append(check_xonsh_ast):1368    check_xonsh_ast({}, "!(ls | grep wakka >> x.py)", False)1369def test_bang_cmd_background(check_xonsh_ast):1370    check_xonsh_ast({}, "!(emacs ugggh &)", False)1371def test_bang_cmd_background_nospace(check_xonsh_ast):1372    check_xonsh_ast({}, "!(emacs ugggh&)", False)1373def test_bang_git_quotes_no_space(check_xonsh_ast):1374    check_xonsh_ast({}, '![git commit -am "wakka"]', False)1375def test_bang_git_quotes_space(check_xonsh_ast):1376    check_xonsh_ast({}, '![git commit -am "wakka jawaka"]', False)1377def test_bang_git_two_quotes_space(check_xonsh):1378    check_xonsh(1379        {},1380        '![git commit -am "wakka jawaka"]\n' '![git commit -am "flock jawaka"]\n',1381        False,1382    )1383def test_bang_git_two_quotes_space_space(check_xonsh):1384    check_xonsh(1385        {},1386        '![git commit -am "wakka jawaka" ]\n'1387        '![git commit -am "flock jawaka milwaka" ]\n',1388        False,1389    )1390def test_bang_ls_quotes_3_space(check_xonsh_ast):1391    check_xonsh_ast({}, '![ls "wakka jawaka baraka"]', False)1392def test_two_cmds_one_pipe(check_xonsh_ast):1393    check_xonsh_ast({}, "$(ls | grep wakka)", False)1394def test_three_cmds_two_pipes(check_xonsh_ast):1395    check_xonsh_ast({}, "$(ls | grep wakka | grep jawaka)", False)1396def test_two_cmds_one_and_brackets(check_xonsh_ast):1397    check_xonsh_ast({}, "![ls me] and ![grep wakka]", False)1398def test_three_cmds_two_ands(check_xonsh_ast):1399    check_xonsh_ast({}, "![ls] and ![grep wakka] and ![grep jawaka]", False)1400def test_two_cmds_one_doubleamps(check_xonsh_ast):1401    check_xonsh_ast({}, "![ls] && ![grep wakka]", False)1402def test_three_cmds_two_doubleamps(check_xonsh_ast):1403    check_xonsh_ast({}, "![ls] && ![grep wakka] && ![grep jawaka]", False)1404def test_two_cmds_one_or(check_xonsh_ast):1405    check_xonsh_ast({}, "![ls] or ![grep wakka]", False)1406def test_three_cmds_two_ors(check_xonsh_ast):1407    check_xonsh_ast({}, "![ls] or ![grep wakka] or ![grep jawaka]", False)1408def test_two_cmds_one_doublepipe(check_xonsh_ast):1409    check_xonsh_ast({}, "![ls] || ![grep wakka]", False)1410def test_three_cmds_two_doublepipe(check_xonsh_ast):1411    check_xonsh_ast({}, "![ls] || ![grep wakka] || ![grep jawaka]", False)1412def test_one_cmd_write(check_xonsh_ast):1413    check_xonsh_ast({}, "$(ls > x.py)", False)1414def test_one_cmd_append(check_xonsh_ast):1415    check_xonsh_ast({}, "$(ls >> x.py)", False)1416def test_two_cmds_write(check_xonsh_ast):1417    check_xonsh_ast({}, "$(ls | grep wakka > x.py)", False)1418def test_two_cmds_append(check_xonsh_ast):1419    check_xonsh_ast({}, "$(ls | grep wakka >> x.py)", False)1420def test_cmd_background(check_xonsh_ast):1421    check_xonsh_ast({}, "$(emacs ugggh &)", False)1422def test_cmd_background_nospace(check_xonsh_ast):1423    check_xonsh_ast({}, "$(emacs ugggh&)", False)1424def test_git_quotes_no_space(check_xonsh_ast):1425    check_xonsh_ast({}, '$[git commit -am "wakka"]', False)1426def test_git_quotes_space(check_xonsh_ast):1427    check_xonsh_ast({}, '$[git commit -am "wakka jawaka"]', False)1428def test_git_two_quotes_space(check_xonsh):1429    check_xonsh(1430        {},1431        '$[git commit -am "wakka jawaka"]\n' '$[git commit -am "flock jawaka"]\n',1432        False,1433    )1434def test_git_two_quotes_space_space(check_xonsh):1435    check_xonsh(1436        {},1437        '$[git commit -am "wakka jawaka" ]\n'1438        '$[git commit -am "flock jawaka milwaka" ]\n',1439        False,1440    )1441def test_ls_quotes_3_space(check_xonsh_ast):1442    check_xonsh_ast({}, '$[ls "wakka jawaka baraka"]', False)1443def test_leading_envvar_assignment(check_xonsh_ast):1444    check_xonsh_ast({}, "![$FOO='foo' $BAR=2 echo r'$BAR']", False)1445def test_echo_comma(check_xonsh_ast):1446    check_xonsh_ast({}, "![echo ,]", False)1447def test_echo_internal_comma(check_xonsh_ast):1448    check_xonsh_ast({}, "![echo 1,2]", False)1449def test_comment_only(check_xonsh_ast):1450    check_xonsh_ast({}, "# hello")1451def test_echo_slash_question(check_xonsh_ast):1452    check_xonsh_ast({}, "![echo /?]", False)1453def test_bad_quotes(check_xonsh_ast):1454    with pytest.raises(SyntaxError):1455        check_xonsh_ast({}, '![echo """hello]', False)1456def test_redirect(check_xonsh_ast):1457    assert check_xonsh_ast({}, "$[cat < input.txt]", False)1458    assert check_xonsh_ast({}, "$[< input.txt cat]", False)1459@pytest.mark.parametrize(1460    "case",1461    [1462        "![(cat)]",1463        "![(cat;)]",1464        "![(cd path; ls; cd)]",1465        '![(echo "abc"; sleep 1; echo "def")]',1466        '![(echo "abc"; sleep 1; echo "def") | grep abc]',1467        "![(if True:\n   ls\nelse:\n   echo not true)]",1468    ],1469)1470def test_use_subshell(case, check_xonsh_ast):1471    check_xonsh_ast({}, case, False, debug_level=0)1472@pytest.mark.parametrize(1473    "case",1474    [1475        "$[cat < /path/to/input.txt]",1476        "$[(cat) < /path/to/input.txt]",1477        "$[< /path/to/input.txt cat]",1478        "![< /path/to/input.txt]",1479        "![< /path/to/input.txt > /path/to/output.txt]",1480    ],1481)1482def test_redirect_abspath(case, check_xonsh_ast):1483    assert check_xonsh_ast({}, case, False)1484@pytest.mark.parametrize("case", ["", "o", "out", "1"])1485def test_redirect_output(case, check_xonsh_ast):1486    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt]', False)1487    assert check_xonsh_ast({}, f'$[< input.txt echo "test" {case}> test.txt]', False)1488    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt < input.txt]', False)1489@pytest.mark.parametrize("case", ["e", "err", "2"])1490def test_redirect_error(case, check_xonsh_ast):1491    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt]', False)1492    assert check_xonsh_ast({}, f'$[< input.txt echo "test" {case}> test.txt]', False)1493    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt < input.txt]', False)1494@pytest.mark.parametrize("case", ["a", "all", "&"])1495def test_redirect_all(case, check_xonsh_ast):1496    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt]', False)1497    assert check_xonsh_ast({}, f'$[< input.txt echo "test" {case}> test.txt]', False)1498    assert check_xonsh_ast({}, f'$[echo "test" {case}> test.txt < input.txt]', False)1499@pytest.mark.parametrize(1500    "r",1501    [1502        "e>o",1503        "e>out",1504        "err>o",1505        "2>1",1506        "e>1",1507        "err>1",1508        "2>out",1509        "2>o",1510        "err>&1",1511        "e>&1",1512        "2>&1",1513    ],1514)1515@pytest.mark.parametrize("o", ["", "o", "out", "1"])1516def test_redirect_error_to_output(r, o, check_xonsh_ast):1517    assert check_xonsh_ast({}, f'$[echo "test" {r} {o}> test.txt]', False)1518    assert check_xonsh_ast({}, f'$[< input.txt echo "test" {r} {o}> test.txt]', False)1519    assert check_xonsh_ast({}, f'$[echo "test" {r} {o}> test.txt < input.txt]', False)1520@pytest.mark.parametrize(1521    "r",1522    [1523        "o>e",1524        "o>err",1525        "out>e",1526        "1>2",1527        "o>2",1528        "out>2",1529        "1>err",1530        "1>e",1531        "out>&2",1532        "o>&2",1533        "1>&2",1534    ],1535)1536@pytest.mark.parametrize("e", ["e", "err", "2"])1537def test_redirect_output_to_error(r, e, check_xonsh_ast):1538    assert check_xonsh_ast({}, f'$[echo "test" {r} {e}> test.txt]', False)1539    assert check_xonsh_ast({}, f'$[< input.txt echo "test" {r} {e}> test.txt]', False)1540    assert check_xonsh_ast({}, f'$[echo "test" {r} {e}> test.txt < input.txt]', False)1541def test_macro_call_empty(check_xonsh_ast):1542    assert check_xonsh_ast({}, "f!()", False)1543MACRO_ARGS = [1544    "x",1545    "True",1546    "None",1547    "import os",1548    "x=10",1549    '"oh no, mom"',1550    "...",1551    " ... ",1552    "if True:\n  pass",1553    "{x: y}",1554    "{x: y, 42: 5}",1555    "{1, 2, 3,}",1556    "(x,y)",1557    "(x, y)",1558    "((x, y), z)",1559    "g()",1560    "range(10)",1561    "range(1, 10, 2)",1562    "()",1563    "{}",1564    "[]",1565    "[1, 2]",1566    "@(x)",1567    "!(ls -l)",1568    "![ls -l]",1569    "$(ls -l)",1570    "${x + y}",1571    "$[ls -l]",1572    "@$(which xonsh)",1573]1574@pytest.mark.parametrize("s", MACRO_ARGS)1575def test_macro_call_one_arg(check_xonsh_ast, s):1576    f = f"f!({s})"1577    tree = check_xonsh_ast({}, f, False, return_obs=True)1578    assert isinstance(tree, AST)1579    args = tree.body.args[1].elts1580    assert len(args) == 11581    assert args[0].s == s.strip()1582@pytest.mark.parametrize("s,t", itertools.product(MACRO_ARGS[::2], MACRO_ARGS[1::2]))1583def test_macro_call_two_args(check_xonsh_ast, s, t):1584    f = f"f!({s}, {t})"1585    tree = check_xonsh_ast({}, f, False, return_obs=True)1586    assert isinstance(tree, AST)1587    args = tree.body.args[1].elts1588    assert len(args) == 21589    assert args[0].s == s.strip()1590    assert args[1].s == t.strip()1591@pytest.mark.parametrize(1592    "s,t,u", itertools.product(MACRO_ARGS[::3], MACRO_ARGS[1::3], MACRO_ARGS[2::3])1593)1594def test_macro_call_three_args(check_xonsh_ast, s, t, u):1595    f = f"f!({s}, {t}, {u})"1596    tree = check_xonsh_ast({}, f, False, return_obs=True)1597    assert isinstance(tree, AST)1598    args = tree.body.args[1].elts1599    assert len(args) == 31600    assert args[0].s == s.strip()1601    assert args[1].s == t.strip()1602    assert args[2].s == u.strip()1603@pytest.mark.parametrize("s", MACRO_ARGS)1604def test_macro_call_one_trailing(check_xonsh_ast, s):1605    f = f"f!({s},)"1606    tree = check_xonsh_ast({}, f, False, return_obs=True)1607    assert isinstance(tree, AST)1608    args = tree.body.args[1].elts1609    assert len(args) == 11610    assert args[0].s == s.strip()1611@pytest.mark.parametrize("s", MACRO_ARGS)1612def test_macro_call_one_trailing_space(check_xonsh_ast, s):1613    f = f"f!( {s}, )"1614    tree = check_xonsh_ast({}, f, False, return_obs=True)1615    assert isinstance(tree, AST)1616    args = tree.body.args[1].elts1617    assert len(args) == 11618    assert args[0].s == s.strip()1619SUBPROC_MACRO_OC = [("!(", ")"), ("$(", ")"), ("![", "]"), ("$[", "]")]1620@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC)1621@pytest.mark.parametrize("body", ["echo!", "echo !", "echo ! "])1622def test_empty_subprocbang(opener, closer, body, check_xonsh_ast):1623    tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True)1624    assert isinstance(tree, AST)1625    cmd = tree.body.args[0].elts1626    assert len(cmd) == 21627    assert cmd[1].s == ""1628@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC)1629@pytest.mark.parametrize("body", ["echo!x", "echo !x", "echo !x", "echo ! x"])1630def test_single_subprocbang(opener, closer, body, check_xonsh_ast):1631    tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True)1632    assert isinstance(tree, AST)1633    cmd = tree.body.args[0].elts1634    assert len(cmd) == 21635    assert cmd[1].s == "x"1636@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC)1637@pytest.mark.parametrize(1638    "body", ["echo -n!x", "echo -n!x", "echo -n !x", "echo -n ! x"]1639)1640def test_arg_single_subprocbang(opener, closer, body, check_xonsh_ast):1641    tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True)1642    assert isinstance(tree, AST)1643    cmd = tree.body.args[0].elts1644    assert len(cmd) == 31645    assert cmd[2].s == "x"1646@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC)1647@pytest.mark.parametrize("ipener, iloser", [("$(", ")"), ("@$(", ")"), ("$[", "]")])1648@pytest.mark.parametrize(1649    "body", ["echo -n!x", "echo -n!x", "echo -n !x", "echo -n ! x"]1650)1651def test_arg_single_subprocbang_nested(1652    opener, closer, ipener, iloser, body, check_xonsh_ast1653):1654    tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True)1655    assert isinstance(tree, AST)1656    cmd = tree.body.args[0].elts1657    assert len(cmd) == 31658    assert cmd[2].s == "x"1659@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC)1660@pytest.mark.parametrize(1661    "body",1662    [1663        "echo!x + y",1664        "echo !x + y",1665        "echo !x + y",1666        "echo ! x + y",1667        "timeit! bang! and more",1668        "timeit! recurse() and more",1669        "timeit! recurse[] and more",1670        "timeit! recurse!() and more",1671        "timeit! recurse![] and more",1672        "timeit! recurse$() and more",1673        "timeit! recurse$[] and more",1674        "timeit! recurse!() and more",1675        "timeit!!!!",1676        "timeit! (!)",1677        "timeit! [!]",1678        "timeit!!(ls)",1679        'timeit!"!)"',1680    ],1681)1682def test_many_subprocbang(opener, closer, body, check_xonsh_ast):1683    tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True)1684    assert isinstance(tree, AST)1685    cmd = tree.body.args[0].elts1686    assert len(cmd) == 21687    assert cmd[1].s == body.partition("!")[-1].strip()1688WITH_BANG_RAWSUITES = [1689    "pass\n",1690    "x = 42\ny = 12\n",1691    'export PATH="yo:momma"\necho $PATH\n',1692    ("with q as t:\n" "    v = 10\n" "\n"),1693    (1694        "with q as t:\n"1695        "    v = 10\n"1696        "\n"1697        "for x in range(6):\n"1698        "    if True:\n"1699        "        pass\n"1700        "    else:\n"1701        "        ls -l\n"1702        "\n"1703        "a = 42\n"1704    ),1705]1706@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES)1707def test_withbang_single_suite(body, check_xonsh_ast):1708    code = "with! x:\n{}".format(textwrap.indent(body, "    "))1709    tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec")1710    assert isinstance(tree, AST)1711    wither = tree.body[0]1712    assert isinstance(wither, With)1713    assert len(wither.body) == 11714    assert isinstance(wither.body[0], Pass)1715    assert len(wither.items) == 11716    item = wither.items[0]1717    s = item.context_expr.args[1].s1718    assert s == body1719@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES)1720def test_withbang_as_single_suite(body, check_xonsh_ast):1721    code = "with! x as y:\n{}".format(textwrap.indent(body, "    "))1722    tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec")1723    assert isinstance(tree, AST)1724    wither = tree.body[0]1725    assert isinstance(wither, With)1726    assert len(wither.body) == 11727    assert isinstance(wither.body[0], Pass)1728    assert len(wither.items) == 11729    item = wither.items[0]1730    assert item.optional_vars.id == "y"1731    s = item.context_expr.args[1].s1732    assert s == body1733@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES)1734def test_withbang_single_suite_trailing(body, check_xonsh_ast):1735    code = "with! x:\n{}\nprint(x)\n".format(textwrap.indent(body, "    "))1736    tree = check_xonsh_ast(1737        {},1738        code,1739        False,1740        return_obs=True,1741        mode="exec",1742        # debug_level=1001743    )1744    assert isinstance(tree, AST)1745    wither = tree.body[0]1746    assert isinstance(wither, With)1747    assert len(wither.body) == 11748    assert isinstance(wither.body[0], Pass)1749    assert len(wither.items) == 11750    item = wither.items[0]1751    s = item.context_expr.args[1].s1752    assert s == body + "\n"1753WITH_BANG_RAWSIMPLE = [1754    "pass",1755    "x = 42; y = 12",1756    'export PATH="yo:momma"; echo $PATH',1757    "[1,\n    2,\n    3]",1758]1759@pytest.mark.parametrize("body", WITH_BANG_RAWSIMPLE)1760def test_withbang_single_simple(body, check_xonsh_ast):1761    code = f"with! x: {body}\n"1762    tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec")1763    assert isinstance(tree, AST)1764    wither = tree.body[0]1765    assert isinstance(wither, With)1766    assert len(wither.body) == 11767    assert isinstance(wither.body[0], Pass)1768    assert len(wither.items) == 11769    item = wither.items[0]1770    s = item.context_expr.args[1].s1771    assert s == body1772@pytest.mark.parametrize("body", WITH_BANG_RAWSIMPLE)1773def test_withbang_single_simple_opt(body, check_xonsh_ast):1774    code = f"with! x as y: {body}\n"1775    tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec")1776    assert isinstance(tree, AST)1777    wither = tree.body[0]1778    assert isinstance(wither, With)1779    assert len(wither.body) == 11780    assert isinstance(wither.body[0], Pass)1781    assert len(wither.items) == 11782    item = wither.items[0]1783    assert item.optional_vars.id == "y"1784    s = item.context_expr.args[1].s1785    assert s == body1786@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES)1787def test_withbang_as_many_suite(body, check_xonsh_ast):1788    code = "with! x as a, y as b, z as c:\n{}"1789    code = code.format(textwrap.indent(body, "    "))1790    tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec")1791    assert isinstance(tree, AST)1792    wither = tree.body[0]1793    assert isinstance(wither, With)1794    assert len(wither.body) == 11795    assert isinstance(wither.body[0], Pass)1796    assert len(wither.items) == 31797    for i, targ in enumerate("abc"):1798        item = wither.items[i]1799        assert item.optional_vars.id == targ1800        s = item.context_expr.args[1].s1801        assert s == body1802def test_subproc_raw_str_literal(check_xonsh_ast):1803    tree = check_xonsh_ast({}, "!(echo '$foo')", run=False, return_obs=True)1804    assert isinstance(tree, AST)1805    subproc = tree.body1806    assert isinstance(subproc.args[0].elts[1], Call)1807    assert subproc.args[0].elts[1].func.attr == "expand_path"1808    tree = check_xonsh_ast({}, "!(echo r'$foo')", run=False, return_obs=True)1809    assert isinstance(tree, AST)1810    subproc = tree.body1811    assert isinstance(subproc.args[0].elts[1], Str)1812    assert subproc.args[0].elts[1].s == "$foo"1813# test invalid expressions1814def test_syntax_error_del_literal(parser):1815    with pytest.raises(SyntaxError):1816        parser.parse("del 7")1817def test_syntax_error_del_constant(parser):1818    with pytest.raises(SyntaxError):1819        parser.parse("del True")1820def test_syntax_error_del_emptytuple(parser):1821    with pytest.raises(SyntaxError):1822        parser.parse("del ()")1823def test_syntax_error_del_call(parser):1824    with pytest.raises(SyntaxError):1825        parser.parse("del foo()")1826def test_syntax_error_del_lambda(parser):1827    with pytest.raises(SyntaxError):1828        parser.parse('del lambda x: "yay"')1829def test_syntax_error_del_ifexp(parser):1830    with pytest.raises(SyntaxError):1831        parser.parse("del x if y else z")1832@pytest.mark.parametrize(1833    "exp",1834    [1835        "[i for i in foo]",1836        "{i for i in foo}",1837        "(i for i in foo)",1838        "{k:v for k,v in d.items()}",1839    ],1840)1841def test_syntax_error_del_comps(parser, exp):1842    with pytest.raises(SyntaxError):1843        parser.parse(f"del {exp}")1844@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"])1845def test_syntax_error_del_ops(parser, exp):1846    with pytest.raises(SyntaxError):1847        parser.parse(f"del {exp}")1848@pytest.mark.parametrize("exp", ["x > y", "x > y == z"])1849def test_syntax_error_del_cmp(parser, exp):1850    with pytest.raises(SyntaxError):1851        parser.parse(f"del {exp}")1852def test_syntax_error_lonely_del(parser):1853    with pytest.raises(SyntaxError):1854        parser.parse("del")1855def test_syntax_error_assign_literal(parser):1856    with pytest.raises(SyntaxError):1857        parser.parse("7 = x")1858def test_syntax_error_assign_constant(parser):1859    with pytest.raises(SyntaxError):1860        parser.parse("True = 8")1861def test_syntax_error_assign_emptytuple(parser):1862    with pytest.raises(SyntaxError):1863        parser.parse("() = x")1864def test_syntax_error_assign_call(parser):1865    with pytest.raises(SyntaxError):1866        parser.parse("foo() = x")1867def test_syntax_error_assign_lambda(parser):1868    with pytest.raises(SyntaxError):1869        parser.parse('lambda x: "yay" = y')1870def test_syntax_error_assign_ifexp(parser):1871    with pytest.raises(SyntaxError):1872        parser.parse("x if y else z = 8")1873@pytest.mark.parametrize(1874    "exp",1875    [1876        "[i for i in foo]",1877        "{i for i in foo}",1878        "(i for i in foo)",1879        "{k:v for k,v in d.items()}",1880    ],1881)1882def test_syntax_error_assign_comps(parser, exp):1883    with pytest.raises(SyntaxError):1884        parser.parse(f"{exp} = z")1885@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"])1886def test_syntax_error_assign_ops(parser, exp):1887    with pytest.raises(SyntaxError):1888        parser.parse(f"{exp} = z")1889@pytest.mark.parametrize("exp", ["x > y", "x > y == z"])1890def test_syntax_error_assign_cmp(parser, exp):1891    with pytest.raises(SyntaxError):1892        parser.parse(f"{exp} = a")1893def test_syntax_error_augassign_literal(parser):1894    with pytest.raises(SyntaxError):1895        parser.parse("7 += x")1896def test_syntax_error_augassign_constant(parser):1897    with pytest.raises(SyntaxError):1898        parser.parse("True += 8")1899def test_syntax_error_augassign_emptytuple(parser):1900    with pytest.raises(SyntaxError):1901        parser.parse("() += x")1902def test_syntax_error_augassign_call(parser):1903    with pytest.raises(SyntaxError):1904        parser.parse("foo() += x")1905def test_syntax_error_augassign_lambda(parser):1906    with pytest.raises(SyntaxError):1907        parser.parse('lambda x: "yay" += y')1908def test_syntax_error_augassign_ifexp(parser):1909    with pytest.raises(SyntaxError):1910        parser.parse("x if y else z += 8")1911@pytest.mark.parametrize(1912    "exp",1913    [1914        "[i for i in foo]",1915        "{i for i in foo}",1916        "(i for i in foo)",1917        "{k:v for k,v in d.items()}",1918    ],1919)1920def test_syntax_error_augassign_comps(parser, exp):1921    with pytest.raises(SyntaxError):1922        parser.parse(f"{exp} += z")1923@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"])1924def test_syntax_error_augassign_ops(parser, exp):1925    with pytest.raises(SyntaxError):1926        parser.parse(f"{exp} += z")1927@pytest.mark.parametrize("exp", ["x > y", "x > y +=+= z"])1928def test_syntax_error_augassign_cmp(parser, exp):1929    with pytest.raises(SyntaxError):1930        parser.parse(f"{exp} += a")1931def test_syntax_error_bar_kwonlyargs(parser):1932    with pytest.raises(SyntaxError):1933        parser.parse("def spam(*):\n   pass\n", mode="exec")1934@skip_if_pre_3_81935def test_syntax_error_bar_posonlyargs(parser):1936    with pytest.raises(SyntaxError):1937        parser.parse("def spam(/):\n   pass\n", mode="exec")1938@skip_if_pre_3_81939def test_syntax_error_bar_posonlyargs_no_comma(parser):1940    with pytest.raises(SyntaxError):1941        parser.parse("def spam(x /, y):\n   pass\n", mode="exec")1942def test_syntax_error_nondefault_follows_default(parser):1943    with pytest.raises(SyntaxError):1944        parser.parse("def spam(x=1, y):\n   pass\n", mode="exec")1945@skip_if_pre_3_81946def test_syntax_error_posonly_nondefault_follows_default(parser):1947    with pytest.raises(SyntaxError):1948        parser.parse("def spam(x, y=1, /, z):\n   pass\n", mode="exec")1949def test_syntax_error_lambda_nondefault_follows_default(parser):1950    with pytest.raises(SyntaxError):1951        parser.parse("lambda x=1, y: x", mode="exec")1952@skip_if_pre_3_81953def test_syntax_error_lambda_posonly_nondefault_follows_default(parser):1954    with pytest.raises(SyntaxError):1955        parser.parse("lambda x, y=1, /, z: x", mode="exec")1956@pytest.mark.parametrize(1957    "first_prefix, second_prefix", itertools.permutations(["", "p", "b"], 2)1958)1959def test_syntax_error_literal_concat_different(first_prefix, second_prefix, parser):1960    with pytest.raises(SyntaxError):1961        parser.parse(f"{first_prefix}'hello' {second_prefix}'world'")1962def test_get_repo_url(parser):1963    parser.parse(1964        "def get_repo_url():\n"1965        "    raw = $(git remote get-url --push origin).rstrip()\n"1966        "    return raw.replace('https://github.com/', '')\n"1967    )1968# match statement1969# (tests asserting that pure python match statements produce the same ast with the xonsh parser as they do with the python parser)1970def test_match_and_case_are_not_keywords(check_stmts):1971    check_stmts(1972        """1973match = 11974case = 21975def match():1976    pass1977class case():1978    pass1979"""1980    )1981@skip_if_pre_3_101982def test_match_literal_pattern(check_stmts):1983    check_stmts(1984        """match 1:1985    case 1j:1986        pass1987    case 2.718+3.141j:1988        pass1989    case -2.718-3.141j:1990        pass1991    case 2:1992        pass1993    case -2:1994        pass1995    case "One" 'Two':1996        pass1997    case None:1998        pass1999    case True:2000        pass2001    case False:2002        pass2003""",2004        run=False,2005    )2006@skip_if_pre_3_102007def test_match_or_pattern(check_stmts):2008    check_stmts(2009        """match 1:2010    case 1j | 2 | "One" | 'Two' | None | True | False:2011        pass2012""",2013        run=False,2014    )2015@skip_if_pre_3_102016def test_match_as_pattern(check_stmts):2017    check_stmts(2018        """match 1:2019    case 1j | 2 | "One" | 'Two' | None | True | False as target:2020        pass2021    case 2 as target:2022        pass2023""",2024        run=False,2025    )2026@skip_if_pre_3_102027def test_match_group_pattern(check_stmts):2028    check_stmts(2029        """match 1:2030    case (None):2031        pass2032    case ((None)):2033        pass2034    case (1 | 2 as x) as x:2035        pass2036""",2037        run=False,2038    )2039@skip_if_pre_3_102040def test_match_capture_and_wildcard_pattern(check_stmts):2041    check_stmts(2042        """match 1:2043    case _:2044        pass2045    case x:2046        pass2047""",2048        run=False,2049    )2050@skip_if_pre_3_102051def test_match_value_pattern(check_stmts):2052    check_stmts(2053        """match 1:2054    case math.pi:2055        pass2056    case a.b.c.d:2057        pass2058""",2059        run=False,2060    )2061@skip_if_pre_3_102062def test_match_mapping_pattern(check_stmts):2063    check_stmts(2064        """match _:2065    case {}:2066        pass2067    case {x.y:y}:2068        pass2069    case {x.y:y,}:2070        pass2071    case {x.y:y,"a":a}:2072        pass2073    case {x.y:y,"a":a,}:2074        pass2075    case {x.y:y,"a":a,**end}:2076        pass2077    case {x.y:y,"a":a,**end,}:2078        pass2079    case {**end}:2080        pass2081    case {**end,}:2082        pass2083    case {1:1, "two":two, three.three: {}, 4:None, **end}:2084        pass2085""",2086        run=False,2087    )2088@skip_if_pre_3_102089def test_match_class_pattern(check_stmts):2090    check_stmts(2091        """match _:2092    case classs():2093        pass2094    case x.classs():2095        pass2096    case classs("subpattern"):2097        pass2098    case classs("subpattern",):2099        pass2100    case classs("subpattern",2):2101        pass2102    case classs("subpattern",2,):2103        pass2104    case classs(a = b):2105        pass2106    case classs(a = b,):2107        pass2108    case classs(a = b, b = c):2109        pass2110    case classs(a = b, b = c,):2111        pass2112    case classs(1,2,3,a = b):2113        pass2114    case classs(1,2,3,a = b,):2115        pass2116    case classs(1,2,3,a = b, b = c):2117        pass2118    case classs(1,2,3,a = b, b = c,):2119        pass2120""",2121        run=False,2122    )2123@skip_if_pre_3_102124def test_match_sequence_pattern(check_stmts):2125    check_stmts(2126        """match 1:2127    case (): # empty sequence pattern2128        pass2129    case (1): # group pattern2130        pass2131    case (1,): # length one sequence2132        pass2133    case (1,2):2134        pass2135    case (1,2,):2136        pass2137    case (1,2,3):2138        pass2139    case (1,2,3,):2140        pass2141    case []:2142        pass2143    case [1]:2144        pass2145    case [1,]:2146        pass2147    case [1,2]:2148        pass2149    case [1,2,3]:2150        pass2151    case [1,2,3,]:2152        pass2153    case [*x, *_]: # star patterns2154        pass2155    case 1,: # top level sequence patterns2156        pass2157    case *x,:2158        pass2159    case *_,*_:2160        pass2161""",2162        run=False,2163    )2164@skip_if_pre_3_102165def test_match_subject(check_stmts):2166    check_stmts(2167        """2168match 1:2169    case 1:2170        pass2171match 1,:2172    case 1:2173        pass2174match 1,2:2175    case 1:2176        pass2177match 1,2,:2178    case 1:2179        pass2180match (1,2):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
