From 634a8ec9f2e1889eeff216fb088a1f3afd50dc63 Mon Sep 17 00:00:00 2001 From: Anthony Scopatz Date: Thu, 30 Aug 2018 09:18:49 -0500 Subject: [PATCH] black tests --- tests/aliases/test_source.py | 21 +- tests/conftest.py | 11 +- tests/test_aliases.py | 33 +- tests/test_ast.py | 65 +- tests/test_base_shell.py | 26 +- tests/test_bashisms.py | 11 +- tests/test_builtins.py | 243 ++-- tests/test_commands_cache.py | 96 +- tests/test_contexts.py | 294 ++--- tests/test_dirstack.py | 18 +- tests/test_dirstack_unc.py | 169 ++- tests/test_environ.py | 211 ++-- tests/test_events.py | 23 +- tests/test_execer.py | 87 +- tests/test_foreign_shells.py | 116 +- tests/test_history.py | 263 ++-- tests/test_history_sqlite.py | 147 ++- tests/test_imphooks.py | 22 +- tests/test_integrations.py | 346 +++-- tests/test_jsonutils.py | 21 +- tests/test_lazyasd.py | 6 +- tests/test_lazyjson.py | 97 +- tests/test_lexer.py | 414 +++--- tests/test_main.py | 107 +- tests/test_man.py | 15 +- tests/test_mpl.py | 29 +- tests/test_news.py | 60 +- tests/test_parser.py | 2110 ++++++++++++++++++++----------- tests/test_path_completers.py | 34 +- tests/test_platform.py | 5 +- tests/test_prompt.py | 139 +- tests/test_ptk_highlight.py | 166 ++- tests/test_ptk_history.py | 8 +- tests/test_ptk_multiline.py | 61 +- tests/test_python_completers.py | 41 +- tests/test_replay.py | 14 +- tests/test_tools.py | 1541 ++++++++++++---------- tests/test_vox.py | 102 +- tests/test_wizard.py | 99 +- tests/test_xontribs.py | 41 +- tests/test_xoreutils.py | 37 +- 41 files changed, 4320 insertions(+), 3029 deletions(-) diff --git a/tests/aliases/test_source.py b/tests/aliases/test_source.py index 10ccc0c09..b38532b7d 100644 --- a/tests/aliases/test_source.py +++ b/tests/aliases/test_source.py @@ -11,7 +11,8 @@ def mockopen(xonsh_builtins, monkeypatch): @contextmanager def mocked_open(fpath, *args, **kwargs): yield MagicMock(read=lambda: fpath) - monkeypatch.setattr(builtins, 'open', mocked_open) + + monkeypatch.setattr(builtins, "open", mocked_open) def test_source_current_dir(mockopen, monkeypatch): @@ -19,10 +20,11 @@ def test_source_current_dir(mockopen, monkeypatch): def mocked_execx(src, *args, **kwargs): checker.append(src.strip()) - monkeypatch.setattr(builtins, 'execx', mocked_execx) - monkeypatch.setattr(os.path, 'isfile', lambda x: True) - source_alias(['foo', 'bar']) - assert checker == ['foo', 'bar'] + + monkeypatch.setattr(builtins, "execx", mocked_execx) + monkeypatch.setattr(os.path, "isfile", lambda x: True) + source_alias(["foo", "bar"]) + assert checker == ["foo", "bar"] def test_source_path(mockopen, monkeypatch): @@ -30,9 +32,10 @@ def test_source_path(mockopen, monkeypatch): def mocked_execx(src, *args, **kwargs): checker.append(src.strip()) - monkeypatch.setattr(builtins, 'execx', mocked_execx) - source_alias(['foo', 'bar']) - path_foo = os.path.join('tests', 'bin', 'foo') - path_bar = os.path.join('tests', 'bin', 'bar') + + monkeypatch.setattr(builtins, "execx", mocked_execx) + source_alias(["foo", "bar"]) + path_foo = os.path.join("tests", "bin", "foo") + path_bar = os.path.join("tests", "bin", "bar") assert checker[0].endswith(path_foo) assert checker[1].endswith(path_bar) diff --git a/tests/conftest.py b/tests/conftest.py index b5f223db0..7b252c31f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,8 +23,10 @@ def source_path(): @pytest.fixture def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" - monkeypatch.setattr('xonsh.built_ins.load_builtins.__code__', - (lambda *args, **kwargs: None).__code__) + monkeypatch.setattr( + "xonsh.built_ins.load_builtins.__code__", + (lambda *args, **kwargs: None).__code__, + ) execer = Execer(unload=False) builtins.__xonsh_execer__ = execer return execer @@ -46,7 +48,7 @@ def xonsh_builtins(xonsh_events): old_builtins = set(dir(builtins)) builtins.__xonsh_env__ = DummyEnv() if ON_WINDOWS: - builtins.__xonsh_env__['PATHEXT'] = ['.EXE', '.BAT', '.CMD'] + builtins.__xonsh_env__["PATHEXT"] = [".EXE", ".BAT", ".CMD"] builtins.__xonsh_ctx__ = {} builtins.__xonsh_shell__ = DummyShell() builtins.__xonsh_help__ = lambda x: x @@ -84,8 +86,9 @@ if ON_WINDOWS: except ImportError: pass else: + @pytest.fixture(autouse=True) def disable_win_unicode_console(monkeypatch): """ Disable win_unicode_console if it is present since it collides with pytests ouptput capture""" - monkeypatch.setattr(win_unicode_console, 'enable', lambda: None) + monkeypatch.setattr(win_unicode_console, "enable", lambda: None) diff --git a/tests/test_aliases.py b/tests/test_aliases.py index 9ab71841b..586fbc059 100644 --- a/tests/test_aliases.py +++ b/tests/test_aliases.py @@ -16,38 +16,41 @@ from tools import skip_if_on_windows def cd(args, stdin=None): return args -ALIASES = Aliases({'o': ['omg', 'lala']}, - color_ls=['ls', '--color=true'], - ls="ls '- -'", - cd=cd, - indirect_cd='cd ..') + +ALIASES = Aliases( + {"o": ["omg", "lala"]}, + color_ls=["ls", "--color=true"], + ls="ls '- -'", + cd=cd, + indirect_cd="cd ..", +) RAW = ALIASES._raw def test_imports(): expected = { - 'o': ['omg', 'lala'], - 'ls': ['ls', '- -'], - 'color_ls': ['ls', '--color=true'], - 'cd': cd, - 'indirect_cd': ['cd', '..'] + "o": ["omg", "lala"], + "ls": ["ls", "- -"], + "color_ls": ["ls", "--color=true"], + "cd": cd, + "indirect_cd": ["cd", ".."], } assert RAW == expected def test_eval_normal(xonsh_builtins): - assert ALIASES.get('o') == ['omg', 'lala'] + assert ALIASES.get("o") == ["omg", "lala"] def test_eval_self_reference(xonsh_builtins): - assert ALIASES.get('ls') == ['ls', '- -'] + assert ALIASES.get("ls") == ["ls", "- -"] def test_eval_recursive(xonsh_builtins): - assert ALIASES.get('color_ls') == ['ls', '- -', '--color=true'] + assert ALIASES.get("color_ls") == ["ls", "- -", "--color=true"] @skip_if_on_windows def test_eval_recursive_callable_partial(xonsh_builtins): - xonsh_builtins.__xonsh_env__ = Env(HOME=os.path.expanduser('~')) - assert ALIASES.get('indirect_cd')(['arg2', 'arg3']) == ['..', 'arg2', 'arg3'] + xonsh_builtins.__xonsh_env__ = Env(HOME=os.path.expanduser("~")) + assert ALIASES.get("indirect_cd")(["arg2", "arg3"]) == ["..", "arg2", "arg3"] diff --git a/tests/test_ast.py b/tests/test_ast.py index fd84e1612..e046ef388 100644 --- a/tests/test_ast.py +++ b/tests/test_ast.py @@ -13,42 +13,44 @@ from tools import check_parse, nodes_equal def xonsh_execer_autouse(xonsh_execer): return xonsh_execer + def test_gather_names_name(): - node = Name(id='y', ctx=Store()) - exp = {'y'} + node = Name(id="y", ctx=Store()) + exp = {"y"} obs = ast.gather_names(node) assert exp == obs def test_gather_names_tuple(): - node = Tuple(elts=[Name(id='y', ctx=Store()), - Name(id='z', ctx=Store())]) - exp = {'y', 'z'} + node = Tuple(elts=[Name(id="y", ctx=Store()), Name(id="z", ctx=Store())]) + exp = {"y", "z"} obs = ast.gather_names(node) assert exp == obs def test_gather_load_store_names_tuple(): - node = Tuple(elts=[Name(id='y', ctx=Store()), - Name(id='z', ctx=Store())]) + node = Tuple(elts=[Name(id="y", ctx=Store()), Name(id="z", ctx=Store())]) lexp = set() - sexp = {'y', 'z'} + sexp = {"y", "z"} lobs, sobs = ast.gather_load_store_names(node) assert lexp == lobs assert sexp == sobs -@pytest.mark.parametrize('line1', [ - # this second line wil be transformed into a subprocess call - 'x = 1', - # this second line wil be transformed into a subprocess call even though - # ls is defined. - 'ls = 1', - # the second line wil be transformed still even though l exists. - 'l = 1', -]) +@pytest.mark.parametrize( + "line1", + [ + # this second line wil be transformed into a subprocess call + "x = 1", + # this second line wil be transformed into a subprocess call even though + # ls is defined. + "ls = 1", + # the second line wil be transformed still even though l exists. + "l = 1", + ], +) def test_multilline_num(xonsh_builtins, line1): - code = line1 + '\nls -l\n' + code = line1 + "\nls -l\n" tree = check_parse(code) lsnode = tree.body[1] assert 2 == min_line(lsnode) @@ -57,52 +59,55 @@ def test_multilline_num(xonsh_builtins, line1): def test_multilline_no_transform(): # no subprocess transformations happen here since all variables are known - code = 'ls = 1\nl = 1\nls -l\n' + code = "ls = 1\nl = 1\nls -l\n" tree = check_parse(code) lsnode = tree.body[2] assert 3 == min_line(lsnode) assert isinstance(lsnode.value, BinOp) -@pytest.mark.parametrize('inp', [ -"""def f(): +@pytest.mark.parametrize( + "inp", + [ + """def f(): if True: pass """, -"""def f(x): + """def f(x): if x: pass """, -"""def f(*args): + """def f(*args): if not args: pass """, -"""def f(*, y): + """def f(*, y): if y: pass """, -"""def f(**kwargs): + """def f(**kwargs): if not kwargs: pass """, -"""def f(k=42): + """def f(k=42): if not k: pass """, -"""def f(k=10, *, a, b=1, **kw): + """def f(k=10, *, a, b=1, **kw): if not kw and b: pass """, -"""import os + """import os path = '/path/to/wakka' paths = [] for root, dirs, files in os.walk(path): paths.extend(os.path.join(root, d) for d in dirs) paths.extend(os.path.join(root, f) for f in files) """, -"""lambda x: x + 1 + """lambda x: x + 1 """, -]) + ], +) def test_unmodified(inp): # Context sensitive parsing should not modify AST exp = pyast.parse(inp) diff --git a/tests/test_base_shell.py b/tests/test_base_shell.py index 46a38dc1f..488862e43 100644 --- a/tests/test_base_shell.py +++ b/tests/test_base_shell.py @@ -7,10 +7,12 @@ from xonsh.base_shell import BaseShell from xonsh.shell import transform_command -def test_pwd_tracks_cwd(xonsh_builtins, xonsh_execer, tmpdir_factory, monkeypatch ): +def test_pwd_tracks_cwd(xonsh_builtins, xonsh_execer, tmpdir_factory, monkeypatch): asubdir = str(tmpdir_factory.mktemp("asubdir")) cur_wd = os.getcwd() - xonsh_builtins.__xonsh_env__ = Env(PWD=cur_wd, XONSH_CACHE_SCRIPTS=False, XONSH_CACHE_EVERYTHING=False) + xonsh_builtins.__xonsh_env__ = Env( + PWD=cur_wd, XONSH_CACHE_SCRIPTS=False, XONSH_CACHE_EVERYTHING=False + ) monkeypatch.setattr(xonsh_execer, "cacheall", False, raising=False) bc = BaseShell(xonsh_execer, None) @@ -20,19 +22,23 @@ def test_pwd_tracks_cwd(xonsh_builtins, xonsh_execer, tmpdir_factory, monkeypatc bc.default('os.chdir(r"' + asubdir + '")') assert os.path.abspath(os.getcwd()) == os.path.abspath(asubdir) - assert os.path.abspath(os.getcwd()) == os.path.abspath(xonsh_builtins.__xonsh_env__['PWD']) - assert 'OLDPWD' in xonsh_builtins.__xonsh_env__ - assert os.path.abspath(cur_wd) == os.path.abspath(xonsh_builtins.__xonsh_env__['OLDPWD']) + assert os.path.abspath(os.getcwd()) == os.path.abspath( + xonsh_builtins.__xonsh_env__["PWD"] + ) + assert "OLDPWD" in xonsh_builtins.__xonsh_env__ + assert os.path.abspath(cur_wd) == os.path.abspath( + xonsh_builtins.__xonsh_env__["OLDPWD"] + ) def test_transform(xonsh_builtins): @xonsh_builtins.events.on_transform_command def spam2egg(cmd, **_): - if cmd == 'spam': - return 'egg' + if cmd == "spam": + return "egg" else: return cmd - assert transform_command('spam') == 'egg' - assert transform_command('egg') == 'egg' - assert transform_command('foo') == 'foo' + assert transform_command("spam") == "egg" + assert transform_command("egg") == "egg" + assert transform_command("foo") == "foo" diff --git a/tests/test_bashisms.py b/tests/test_bashisms.py index ac7bdf022..bec3d6043 100644 --- a/tests/test_bashisms.py +++ b/tests/test_bashisms.py @@ -1,13 +1,12 @@ """Tests bashisms xontrib.""" import pytest -@pytest.mark.parametrize('inp, exp', [ - ('x = 42', 'x = 42'), - ('!!', 'ls'), - ]) + +@pytest.mark.parametrize("inp, exp", [("x = 42", "x = 42"), ("!!", "ls")]) def test_preproc(inp, exp, xonsh_builtins): """Test the bash preprocessor.""" from xontrib.bashisms import bash_preproc - xonsh_builtins.__xonsh_history__.inps = ['ls\n'] + + xonsh_builtins.__xonsh_history__.inps = ["ls\n"] obs = bash_preproc(inp) - assert exp == obs \ No newline at end of file + assert exp == obs diff --git a/tests/test_builtins.py b/tests/test_builtins.py index 6eb94174f..25fe5a806 100644 --- a/tests/test_builtins.py +++ b/tests/test_builtins.py @@ -10,25 +10,37 @@ from ast import AST import pytest from xonsh import built_ins -from xonsh.built_ins import reglob, pathsearch, helper, superhelper, \ - ensure_list_of_strs, list_of_strs_or_callables, regexsearch, \ - globsearch, expand_path, convert_macro_arg, in_macro_call, call_macro, \ - enter_macro +from xonsh.built_ins import ( + reglob, + pathsearch, + helper, + superhelper, + ensure_list_of_strs, + list_of_strs_or_callables, + regexsearch, + globsearch, + expand_path, + convert_macro_arg, + in_macro_call, + call_macro, + enter_macro, +) from xonsh.environ import Env from tools import skip_if_on_windows -HOME_PATH = os.path.expanduser('~') +HOME_PATH = os.path.expanduser("~") @pytest.fixture(autouse=True) def xonsh_execer_autouse(xonsh_execer): return xonsh_execer -@pytest.mark.parametrize('testfile', reglob('test_.*')) + +@pytest.mark.parametrize("testfile", reglob("test_.*")) def test_reglob_tests(testfile): - assert (testfile.startswith('test_')) + assert testfile.startswith("test_") @pytest.fixture @@ -41,252 +53,269 @@ def home_env(xonsh_builtins): @skip_if_on_windows def test_repath_backslash(home_env): exp = os.listdir(HOME_PATH) - exp = {p for p in exp if re.match(r'\w\w.*', p)} + exp = {p for p in exp if re.match(r"\w\w.*", p)} exp = {os.path.join(HOME_PATH, p) for p in exp} - obs = set(pathsearch(regexsearch, r'~/\w\w.*')) - assert exp == obs + obs = set(pathsearch(regexsearch, r"~/\w\w.*")) + assert exp == obs @skip_if_on_windows def test_repath_HOME_PATH_itself(home_env): exp = HOME_PATH - obs = pathsearch(regexsearch, '~') - assert 1 == len(obs) - assert exp == obs[0] + obs = pathsearch(regexsearch, "~") + assert 1 == len(obs) + assert exp == obs[0] @skip_if_on_windows def test_repath_HOME_PATH_contents(home_env): exp = os.listdir(HOME_PATH) exp = {os.path.join(HOME_PATH, p) for p in exp} - obs = set(pathsearch(regexsearch, '~/.*')) - assert exp == obs + obs = set(pathsearch(regexsearch, "~/.*")) + assert exp == obs @skip_if_on_windows def test_repath_HOME_PATH_var(home_env): exp = HOME_PATH - obs = pathsearch(regexsearch, '$HOME') - assert 1 == len(obs) - assert exp == obs[0] + obs = pathsearch(regexsearch, "$HOME") + assert 1 == len(obs) + assert exp == obs[0] @skip_if_on_windows def test_repath_HOME_PATH_var_brace(home_env): exp = HOME_PATH obs = pathsearch(regexsearch, '${"HOME"}') - assert 1 == len(obs) - assert exp == obs[0] + assert 1 == len(obs) + assert exp == obs[0] def test_helper_int(home_env): - helper(int, 'int') + helper(int, "int") + def test_helper_helper(home_env): - helper(helper, 'helper') + helper(helper, "helper") + def test_helper_env(home_env): - helper(Env, 'Env') + helper(Env, "Env") + def test_superhelper_int(home_env): - superhelper(int, 'int') + superhelper(int, "int") + def test_superhelper_helper(home_env): - superhelper(helper, 'helper') + superhelper(helper, "helper") + def test_superhelper_env(home_env): - superhelper(Env, 'Env') + superhelper(Env, "Env") -@pytest.mark.parametrize('exp, inp', [ - (['yo'], 'yo'), - (['yo'], ['yo']), - (['42'], 42), - (['42'], [42]) -]) +@pytest.mark.parametrize( + "exp, inp", [(["yo"], "yo"), (["yo"], ["yo"]), (["42"], 42), (["42"], [42])] +) def test_ensure_list_of_strs(exp, inp): obs = ensure_list_of_strs(inp) assert exp == obs f = lambda x: 20 -@pytest.mark.parametrize('exp, inp', [ - (['yo'], 'yo'), - (['yo'], ['yo']), - (['42'], 42), - (['42'], [42]), - ([f], f), - ([f], [f]) -]) + + +@pytest.mark.parametrize( + "exp, inp", + [ + (["yo"], "yo"), + (["yo"], ["yo"]), + (["42"], 42), + (["42"], [42]), + ([f], f), + ([f], [f]), + ], +) def test_list_of_strs_or_callables(exp, inp): obs = list_of_strs_or_callables(inp) assert exp == obs -@pytest.mark.parametrize('s', [ - '~', - '~/', - 'x=~/place', - 'x=one:~/place', - 'x=one:~/place:~/yo', - 'x=~/one:~/place:~/yo', - ]) +@pytest.mark.parametrize( + "s", + [ + "~", + "~/", + "x=~/place", + "x=one:~/place", + "x=one:~/place:~/yo", + "x=~/one:~/place:~/yo", + ], +) def test_expand_path(s, home_env): - if os.sep != '/': - s = s.replace('/', os.sep) - if os.pathsep != ':': - s = s.replace(':', os.pathsep) - assert expand_path(s) == s.replace('~', HOME_PATH) + if os.sep != "/": + s = s.replace("/", os.sep) + if os.pathsep != ":": + s = s.replace(":", os.pathsep) + assert expand_path(s) == s.replace("~", HOME_PATH) -@pytest.mark.parametrize('kind', [str, 's', 'S', 'str', 'string']) +@pytest.mark.parametrize("kind", [str, "s", "S", "str", "string"]) def test_convert_macro_arg_str(kind): - raw_arg = 'value' + raw_arg = "value" arg = convert_macro_arg(raw_arg, kind, None, None) assert arg is raw_arg -@pytest.mark.parametrize('kind', [AST, 'a', 'Ast']) +@pytest.mark.parametrize("kind", [AST, "a", "Ast"]) def test_convert_macro_arg_ast(kind): - raw_arg = '42' + raw_arg = "42" arg = convert_macro_arg(raw_arg, kind, {}, None) assert isinstance(arg, AST) -@pytest.mark.parametrize('kind', [types.CodeType, compile, 'c', 'code', - 'compile']) +@pytest.mark.parametrize("kind", [types.CodeType, compile, "c", "code", "compile"]) def test_convert_macro_arg_code(kind): - raw_arg = '42' + raw_arg = "42" arg = convert_macro_arg(raw_arg, kind, {}, None) assert isinstance(arg, types.CodeType) -@pytest.mark.parametrize('kind', [eval, None, 'v', 'eval']) +@pytest.mark.parametrize("kind", [eval, None, "v", "eval"]) def test_convert_macro_arg_eval(kind): # literals - raw_arg = '42' + raw_arg = "42" arg = convert_macro_arg(raw_arg, kind, {}, None) assert arg == 42 # exprs - raw_arg = 'x + 41' - arg = convert_macro_arg(raw_arg, kind, {}, {'x': 1}) + raw_arg = "x + 41" + arg = convert_macro_arg(raw_arg, kind, {}, {"x": 1}) assert arg == 42 -@pytest.mark.parametrize('kind', [exec, 'x', 'exec']) +@pytest.mark.parametrize("kind", [exec, "x", "exec"]) def test_convert_macro_arg_exec(kind): # at global scope - raw_arg = 'def f(x, y):\n return x + y' + raw_arg = "def f(x, y):\n return x + y" glbs = {} arg = convert_macro_arg(raw_arg, kind, glbs, None) assert arg is None - assert 'f' in glbs - assert glbs['f'](1, 41) == 42 + assert "f" in glbs + assert glbs["f"](1, 41) == 42 # at local scope - raw_arg = 'def g(z):\n return x + z\ny += 42' - glbs = {'x': 40} - locs = {'y': 1} + raw_arg = "def g(z):\n return x + z\ny += 42" + glbs = {"x": 40} + locs = {"y": 1} arg = convert_macro_arg(raw_arg, kind, glbs, locs) assert arg is None - assert 'g' in locs - assert locs['g'](1) == 41 - assert 'y' in locs - assert locs['y'] == 43 + assert "g" in locs + assert locs["g"](1) == 41 + assert "y" in locs + assert locs["y"] == 43 -@pytest.mark.parametrize('kind', [type, 't', 'type']) +@pytest.mark.parametrize("kind", [type, "t", "type"]) def test_convert_macro_arg_eval(kind): # literals - raw_arg = '42' + raw_arg = "42" arg = convert_macro_arg(raw_arg, kind, {}, None) assert arg is int # exprs - raw_arg = 'x + 41' - arg = convert_macro_arg(raw_arg, kind, {}, {'x': 1}) + raw_arg = "x + 41" + arg = convert_macro_arg(raw_arg, kind, {}, {"x": 1}) assert arg is int def test_in_macro_call(): def f(): pass + with in_macro_call(f, True, True): assert f.macro_globals assert f.macro_locals - assert not hasattr(f, 'macro_globals') - assert not hasattr(f, 'macro_locals') + assert not hasattr(f, "macro_globals") + assert not hasattr(f, "macro_locals") -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_str(arg): - def f(x : str): + def f(x: str): return x + rtn = call_macro(f, [arg], None, None) assert rtn is arg -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_ast(arg): - def f(x : AST): + def f(x: AST): return x + rtn = call_macro(f, [arg], {}, None) assert isinstance(rtn, AST) -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_code(arg): - def f(x : compile): + def f(x: compile): return x + rtn = call_macro(f, [arg], {}, None) assert isinstance(rtn, types.CodeType) -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_eval(arg): - def f(x : eval): + def f(x: eval): return x - rtn = call_macro(f, [arg], {'x': 42, 'y': 0}, None) + + rtn = call_macro(f, [arg], {"x": 42, "y": 0}, None) assert rtn == 42 -@pytest.mark.parametrize('arg', ['if y:\n pass', - 'if 42:\n pass', - 'if x + y:\n pass']) +@pytest.mark.parametrize( + "arg", ["if y:\n pass", "if 42:\n pass", "if x + y:\n pass"] +) def test_call_macro_exec(arg): - def f(x : exec): + def f(x: exec): return x - rtn = call_macro(f, [arg], {'x': 42, 'y': 0}, None) + + rtn = call_macro(f, [arg], {"x": 42, "y": 0}, None) assert rtn is None -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_raw_arg(arg): - def f(x : str): + def f(x: str): return x - rtn = call_macro(f, ['*', arg], {'x': 42, 'y': 0}, None) + + rtn = call_macro(f, ["*", arg], {"x": 42, "y": 0}, None) assert rtn == 42 -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_raw_kwarg(arg): - def f(x : str): + def f(x: str): return x - rtn = call_macro(f, ['*', 'x=' + arg], {'x': 42, 'y': 0}, None) + + rtn = call_macro(f, ["*", "x=" + arg], {"x": 42, "y": 0}, None) assert rtn == 42 -@pytest.mark.parametrize('arg', ['x', '42', 'x + y']) +@pytest.mark.parametrize("arg", ["x", "42", "x + y"]) def test_call_macro_raw_kwargs(arg): - def f(x : str): + def f(x: str): return x - rtn = call_macro(f, ['*', '**{"x" :' + arg + '}'], {'x': 42, 'y': 0}, None) + + rtn = call_macro(f, ["*", '**{"x" :' + arg + "}"], {"x": 42, "y": 0}, None) assert rtn == 42 def test_enter_macro(): obj = lambda: None - rtn = enter_macro(obj, 'wakka', True, True) + rtn = enter_macro(obj, "wakka", True, True) assert obj is rtn - assert obj.macro_block == 'wakka' + assert obj.macro_block == "wakka" assert obj.macro_globals assert obj.macro_locals - diff --git a/tests/test_commands_cache.py b/tests/test_commands_cache.py index e51e82c0b..e4971cba5 100644 --- a/tests/test_commands_cache.py +++ b/tests/test_commands_cache.py @@ -3,85 +3,91 @@ import builtins import pytest -from xonsh.commands_cache import (CommandsCache, predict_shell, - SHELL_PREDICTOR_PARSER, predict_true, predict_false) +from xonsh.commands_cache import ( + CommandsCache, + predict_shell, + SHELL_PREDICTOR_PARSER, + predict_true, + predict_false, +) from tools import skip_if_on_windows + def test_commands_cache_lazy(xonsh_builtins): cc = CommandsCache() - assert not cc.lazyin('xonsh') + assert not cc.lazyin("xonsh") assert 0 == len(list(cc.lazyiter())) assert 0 == cc.lazylen() TRUE_SHELL_ARGS = [ - ['-c', 'yo'], - ['-c=yo'], - ['file'], - ['-i', '-l', 'file'], - ['-i', '-c', 'yo'], - ['-i', 'file'], - ['-i', '-c', 'yo', 'file'], - ] + ["-c", "yo"], + ["-c=yo"], + ["file"], + ["-i", "-l", "file"], + ["-i", "-c", "yo"], + ["-i", "file"], + ["-i", "-c", "yo", "file"], +] -@pytest.mark.parametrize('args', TRUE_SHELL_ARGS) + +@pytest.mark.parametrize("args", TRUE_SHELL_ARGS) def test_predict_shell_parser(args): ns, unknown = SHELL_PREDICTOR_PARSER.parse_known_args(args) if ns.filename is not None: - assert not ns.filename.startswith('-') + assert not ns.filename.startswith("-") -@pytest.mark.parametrize('args', TRUE_SHELL_ARGS) +@pytest.mark.parametrize("args", TRUE_SHELL_ARGS) def test_predict_shell_true(args): assert predict_shell(args) -FALSE_SHELL_ARGS = [ - [], - ['-c'], - ['-i'], - ['-i', '-l'], - ] +FALSE_SHELL_ARGS = [[], ["-c"], ["-i"], ["-i", "-l"]] -@pytest.mark.parametrize('args', FALSE_SHELL_ARGS) + +@pytest.mark.parametrize("args", FALSE_SHELL_ARGS) def test_predict_shell_false(args): assert not predict_shell(args) PATTERN_BIN_USING_TTY_OR_NOT = [ - (False, {10: b'isnotatty'}), - (False, {12: b'isatty'}), - (False, {151: b'gpm'}), - (False, {10: b'isatty', 100: b'tcgetattr', }), - (False, {10: b'isatty', 100: b'tcsetattr'}), - (True, {10: b'isatty', 100: b'tcsetattr', 1000: b'tcgetattr'}), - (True, {1000: b'libncurses'}), - (True, {4094: b'libgpm'}), - (True, {2045: b'tcgetattr', 4095: b'tcgetattr', 6140: b'tcsetattr', - 8190: b'isatty'}), + (False, {10: b"isnotatty"}), + (False, {12: b"isatty"}), + (False, {151: b"gpm"}), + (False, {10: b"isatty", 100: b"tcgetattr"}), + (False, {10: b"isatty", 100: b"tcsetattr"}), + (True, {10: b"isatty", 100: b"tcsetattr", 1000: b"tcgetattr"}), + (True, {1000: b"libncurses"}), + (True, {4094: b"libgpm"}), + ( + True, + {2045: b"tcgetattr", 4095: b"tcgetattr", 6140: b"tcsetattr", 8190: b"isatty"}, + ), ] -@pytest.mark.parametrize('args', PATTERN_BIN_USING_TTY_OR_NOT) +@pytest.mark.parametrize("args", PATTERN_BIN_USING_TTY_OR_NOT) @skip_if_on_windows def test_commands_cache_predictor_default(args): cc = CommandsCache() use_tty, patterns = args - f = open('testfile', 'wb') + f = open("testfile", "wb") where = list(patterns.keys()) where.sort() pos = 0 for w in where: - f.write(b'\x20' * (w - pos)) + f.write(b"\x20" * (w - pos)) f.write(patterns[w]) pos = w + len(patterns[w]) - f.write(b'\x20' * (pos // 2)) + f.write(b"\x20" * (pos // 2)) f.close() - result = cc.default_predictor_readbin('', os.getcwd() + os.sep + 'testfile', - timeout=1, failure=None) + result = cc.default_predictor_readbin( + "", os.getcwd() + os.sep + "testfile", timeout=1, failure=None + ) expected = predict_false if use_tty else predict_true assert result == expected @@ -89,25 +95,25 @@ def test_commands_cache_predictor_default(args): @skip_if_on_windows def test_cd_is_only_functional_alias(xonsh_builtins): cc = CommandsCache() - builtins.aliases['cd'] = lambda args: os.chdir(args[0]) - assert cc.is_only_functional_alias('cd') + builtins.aliases["cd"] = lambda args: os.chdir(args[0]) + assert cc.is_only_functional_alias("cd") def test_non_exist_is_only_functional_alias(xonsh_builtins): cc = CommandsCache() - assert not cc.is_only_functional_alias('') + assert not cc.is_only_functional_alias("") @skip_if_on_windows def test_bash_is_only_functional_alias(xonsh_builtins): - builtins.__xonsh_env__['PATH'] = os.environ['PATH'].split(os.pathsep) + builtins.__xonsh_env__["PATH"] = os.environ["PATH"].split(os.pathsep) cc = CommandsCache() - assert not cc.is_only_functional_alias('bash') + assert not cc.is_only_functional_alias("bash") @skip_if_on_windows def test_bash_and_is_alias_is_only_functional_alias(xonsh_builtins): - builtins.__xonsh_env__['PATH'] = os.environ['PATH'].split(os.pathsep) + builtins.__xonsh_env__["PATH"] = os.environ["PATH"].split(os.pathsep) cc = CommandsCache() - builtins.aliases['bash'] = lambda args: os.chdir(args[0]) - assert not cc.is_only_functional_alias('bash') + builtins.aliases["bash"] = lambda args: os.chdir(args[0]) + assert not cc.is_only_functional_alias("bash") diff --git a/tests/test_contexts.py b/tests/test_contexts.py index 8e33329ef..06d6c6786 100644 --- a/tests/test_contexts.py +++ b/tests/test_contexts.py @@ -11,31 +11,33 @@ import pytest def xonsh_execer_autouse(xonsh_builtins, xonsh_execer): return xonsh_execer + # # helpers # -X1_WITH = ('x = 1\n' - 'with! Block() as b:\n') -SIMPLE_WITH = 'with! Block() as b:\n' -FUNC_WITH = ('x = 1\n' - 'def func():\n' - ' y = 1\n' - ' with! Block() as b:\n' - '{body}' - ' y += 1\n' - ' return b\n' - 'x += 1\n' - 'rtn = func()\n' - 'x += 1\n') +X1_WITH = "x = 1\n" "with! Block() as b:\n" +SIMPLE_WITH = "with! Block() as b:\n" +FUNC_WITH = ( + "x = 1\n" + "def func():\n" + " y = 1\n" + " with! Block() as b:\n" + "{body}" + " y += 1\n" + " return b\n" + "x += 1\n" + "rtn = func()\n" + "x += 1\n" +) -FUNC_OBSG = {'x': 3} -FUNC_OBSL = {'y': 1} +FUNC_OBSG = {"x": 3} +FUNC_OBSL = {"y": 1} def norm_body(body): if not isinstance(body, str): - body = '\n'.join(body) + body = "\n".join(body) body = dedent(body) body = body.splitlines() return body @@ -72,276 +74,248 @@ def block_checks_func(name, glbs, body, obsg=None, obsl=None): # Block tests # + def test_block_noexec(): - s = ('x = 1\n' - 'with! Block():\n' - ' x += 42\n') - glbs = {'Block': Block} + s = "x = 1\n" "with! Block():\n" " x += 42\n" + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - assert 1 == glbs['x'] + assert 1 == glbs["x"] def test_block_oneline(): - body = ' x += 42\n' + body = " x += 42\n" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body, {'x': 1}) + block_checks_glb("b", glbs, body, {"x": 1}) def test_block_manylines(): - body = (' ![echo wow mom]\n' - '# bad place for a comment\n' - ' x += 42') + body = " ![echo wow mom]\n" "# bad place for a comment\n" " x += 42" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body, {'x': 1}) + block_checks_glb("b", glbs, body, {"x": 1}) def test_block_leading_comment(): # leading comments do not show up in block lines - body = (' # I am a leading comment\n' - ' x += 42\n') + body = " # I am a leading comment\n" " x += 42\n" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, [' x += 42'], {'x': 1}) + block_checks_glb("b", glbs, [" x += 42"], {"x": 1}) def test_block_trailing_comment(): # trailing comments show up in block lines - body = (' x += 42\n' - ' # I am a trailing comment\n') + body = " x += 42\n" " # I am a trailing comment\n" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body, {'x': 1}) + block_checks_glb("b", glbs, body, {"x": 1}) def test_block_trailing_line_continuation(): - body = (' x += \\\n' - ' 42\n') + body = " x += \\\n" " 42\n" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body, {'x': 1}) + block_checks_glb("b", glbs, body, {"x": 1}) def test_block_trailing_close_paren(): - body = (' x += int("42"\n' - ' )\n') + body = ' x += int("42"\n' " )\n" s = X1_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body, {'x': 1}) + block_checks_glb("b", glbs, body, {"x": 1}) def test_block_trailing_close_many(): - body = (' x = {None: [int("42"\n' - ' )\n' - ' ]\n' - ' }\n') + body = ( + ' x = {None: [int("42"\n' + " )\n" + " ]\n" + " }\n" + ) s = SIMPLE_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body) + block_checks_glb("b", glbs, body) def test_block_trailing_triple_string(): - body = (' x = """This\n' - 'is\n' - '"probably"\n' - '\'not\' what I meant.\n' - '"""\n') + body = ' x = """This\n' "is\n" '"probably"\n' "'not' what I meant.\n" '"""\n' s = SIMPLE_WITH + body - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('b', glbs, body) + block_checks_glb("b", glbs, body) def test_block_func_oneline(): - body = ' x += 42\n' + body = " x += 42\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_block_func_manylines(): - body = (' ![echo wow mom]\n' - '# bad place for a comment\n' - ' x += 42\n') + body = " ![echo wow mom]\n" "# bad place for a comment\n" " x += 42\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_block_func_leading_comment(): # leading comments do not show up in block lines - body = (' # I am a leading comment\n' - ' x += 42\n') + body = " # I am a leading comment\n" " x += 42\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, ' x += 42\n', - FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, " x += 42\n", FUNC_OBSG, FUNC_OBSL) def test_block_func_trailing_comment(): # trailing comments show up in block lines - body = (' x += 42\n' - ' # I am a trailing comment\n') + body = " x += 42\n" " # I am a trailing comment\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_blockfunc__trailing_line_continuation(): - body = (' x += \\\n' - ' 42\n') + body = " x += \\\n" " 42\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_block_func_trailing_close_paren(): - body = (' x += int("42"\n' - ' )\n') + body = ' x += int("42"\n' " )\n" s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_block_func_trailing_close_many(): - body = (' x = {None: [int("42"\n' - ' )\n' - ' ]\n' - ' }\n') + body = ( + ' x = {None: [int("42"\n' + " )\n" + " ]\n" + " }\n" + ) s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) def test_block_func_trailing_triple_string(): - body = (' x = """This\n' - 'is\n' - '"probably"\n' - '\'not\' what I meant.\n' - '"""\n') + body = ' x = """This\n' "is\n" '"probably"\n' "'not' what I meant.\n" '"""\n' s = FUNC_WITH.format(body=body) - glbs = {'Block': Block} + glbs = {"Block": Block} check_exec(s, glbs=glbs, locs=None) - block_checks_func('rtn', glbs, body, FUNC_OBSG, FUNC_OBSL) + block_checks_func("rtn", glbs, body, FUNC_OBSG, FUNC_OBSL) # # Functor tests # -X2_WITH = ('{var} = 1\n' - 'with! Functor() as f:\n' - '{body}' - '{var} += 1\n' - '{calls}\n' - ) +X2_WITH = "{var} = 1\n" "with! Functor() as f:\n" "{body}" "{var} += 1\n" "{calls}\n" + def test_functor_oneline_onecall_class(): - body = (' global y\n' - ' y += 42\n') - calls = 'f()' - s = X2_WITH.format(body=body, calls=calls, var='y') - glbs = {'Functor': Functor} + body = " global y\n" " y += 42\n" + calls = "f()" + s = X2_WITH.format(body=body, calls=calls, var="y") + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'y': 44}) + block_checks_glb("f", glbs, body, {"y": 44}) def test_functor_oneline_onecall_func(): - body = (' global z\n' - ' z += 42\n') - calls = 'f.func()' - s = X2_WITH.format(body=body, calls=calls, var='z') - glbs = {'Functor': Functor} + body = " global z\n" " z += 42\n" + calls = "f.func()" + s = X2_WITH.format(body=body, calls=calls, var="z") + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'z': 44}) + block_checks_glb("f", glbs, body, {"z": 44}) def test_functor_oneline_onecall_both(): - body = (' global x\n' - ' x += 42\n') - calls = 'f()\nf.func()' - s = X2_WITH.format(body=body, calls=calls, var='x') - glbs = {'Functor': Functor} + body = " global x\n" " x += 42\n" + calls = "f()\nf.func()" + s = X2_WITH.format(body=body, calls=calls, var="x") + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'x': 86}) + block_checks_glb("f", glbs, body, {"x": 86}) -XA_WITH = ('x = [1]\n' - 'with! Functor() as f:\n' - '{body}' - 'x.append(2)\n' - '{calls}\n' - ) +XA_WITH = "x = [1]\n" "with! Functor() as f:\n" "{body}" "x.append(2)\n" "{calls}\n" + def test_functor_oneline_append(): - body = ' x.append(3)\n' - calls = 'f()\n' + body = " x.append(3)\n" + calls = "f()\n" s = XA_WITH.format(body=body, calls=calls) - glbs = {'Functor': Functor} + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'x': [1, 2, 3]}) + block_checks_glb("f", glbs, body, {"x": [1, 2, 3]}) def test_functor_return(): - body = ' x = 42' - t = ('res = 0\n' - 'with! Functor(rtn="x") as f:\n' - '{body}\n' - 'res = f()\n') + body = " x = 42" + t = "res = 0\n" 'with! Functor(rtn="x") as f:\n' "{body}\n" "res = f()\n" s = t.format(body=body) - glbs = {'Functor': Functor} + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'res': 42}) + block_checks_glb("f", glbs, body, {"res": 42}) def test_functor_args(): - body = ' x = 42 + a' - t = ('res = 0\n' - 'with! Functor(args=("a",), rtn="x") as f:\n' - '{body}\n' - 'res = f(2)\n') + body = " x = 42 + a" + t = ( + "res = 0\n" + 'with! Functor(args=("a",), rtn="x") as f:\n' + "{body}\n" + "res = f(2)\n" + ) s = t.format(body=body) - glbs = {'Functor': Functor} + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'res': 44}) + block_checks_glb("f", glbs, body, {"res": 44}) def test_functor_kwargs(): - body = ' x = 42 + a + b' - t = ('res = 0\n' - 'with! Functor(kwargs={{"a": 1, "b": 12}}, rtn="x") as f:\n' - '{body}\n' - 'res = f(b=6)\n') + body = " x = 42 + a + b" + t = ( + "res = 0\n" + 'with! Functor(kwargs={{"a": 1, "b": 12}}, rtn="x") as f:\n' + "{body}\n" + "res = f(b=6)\n" + ) s = t.format(body=body) - glbs = {'Functor': Functor} + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'res': 49}) + block_checks_glb("f", glbs, body, {"res": 49}) def test_functor_fullsig(): - body = ' x = 42 + a + b + c' - t = ('res = 0\n' - 'with! Functor(args=("c",), kwargs={{"a": 1, "b": 12}}, rtn="x") as f:\n' - '{body}\n' - 'res = f(55)\n') + body = " x = 42 + a + b + c" + t = ( + "res = 0\n" + 'with! Functor(args=("c",), kwargs={{"a": 1, "b": 12}}, rtn="x") as f:\n' + "{body}\n" + "res = f(55)\n" + ) s = t.format(body=body) - glbs = {'Functor': Functor} + glbs = {"Functor": Functor} check_exec(s, glbs=glbs, locs=None) - block_checks_glb('f', glbs, body, {'res': 110}) - - + block_checks_glb("f", glbs, body, {"res": 110}) diff --git a/tests/test_dirstack.py b/tests/test_dirstack.py index 49a8ade73..0aa90d0bf 100644 --- a/tests/test_dirstack.py +++ b/tests/test_dirstack.py @@ -17,6 +17,7 @@ from xonsh.built_ins import load_builtins HERE = os.path.abspath(os.path.dirname(__file__)) PARENT = os.path.dirname(HERE) + @contextmanager def chdir(adir): old_dir = os.getcwd() @@ -28,17 +29,17 @@ def chdir(adir): def test_simple(xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env(CDPATH=PARENT, PWD=PARENT) with chdir(PARENT): - assert os.getcwd() != HERE + assert os.getcwd() != HERE dirstack.cd(["tests"]) - assert os.getcwd() == HERE + assert os.getcwd() == HERE def test_cdpath_simple(xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env(CDPATH=PARENT, PWD=HERE) with chdir(os.path.normpath("/")): - assert os.getcwd() != HERE + assert os.getcwd() != HERE dirstack.cd(["tests"]) - assert os.getcwd() == HERE + assert os.getcwd() == HERE def test_cdpath_collision(xonsh_builtins): @@ -49,20 +50,22 @@ def test_cdpath_collision(xonsh_builtins): with chdir(HERE): assert os.getcwd() == HERE dirstack.cd(["tests"]) - assert os.getcwd() == os.path.join(HERE, "tests") + assert os.getcwd() == os.path.join(HERE, "tests") def test_cdpath_expansion(xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env(HERE=HERE, CDPATH=("~", "$HERE")) test_dirs = ( os.path.join(HERE, "xonsh-test-cdpath-here"), - os.path.expanduser("~/xonsh-test-cdpath-home") + os.path.expanduser("~/xonsh-test-cdpath-home"), ) try: for d in test_dirs: if not os.path.exists(d): os.mkdir(d) - assert os.path.exists(dirstack._try_cdpath(d)), "dirstack._try_cdpath: could not resolve {0}".format(d) + assert os.path.exists( + dirstack._try_cdpath(d) + ), "dirstack._try_cdpath: could not resolve {0}".format(d) finally: for d in test_dirs: if os.path.exists(d): @@ -74,6 +77,7 @@ def test_cdpath_events(xonsh_builtins, tmpdir): target = str(tmpdir) ev = None + @xonsh_builtins.events.on_chdir def handler(olddir, newdir, **kw): nonlocal ev diff --git a/tests/test_dirstack_unc.py b/tests/test_dirstack_unc.py index 03111fbcc..cf44e0c06 100644 --- a/tests/test_dirstack_unc.py +++ b/tests/test_dirstack_unc.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- """Testing dirstack""" -#from __future__ import unicode_literals, print_function +# from __future__ import unicode_literals, print_function from contextlib import contextmanager from functools import wraps @@ -22,16 +22,19 @@ PARENT = os.path.dirname(HERE) def drive_in_use(letter): - return ON_WINDOWS and os.system('vol {}: 2>nul>nul'.format(letter)) == 0 + return ON_WINDOWS and os.system("vol {}: 2>nul>nul".format(letter)) == 0 + MAX_TEMP_DRIVES = 4 TEMP_DRIVE = [] -for d in 'zyxwvuts': +for d in "zyxwvuts": if not drive_in_use(d): - TEMP_DRIVE.append(d + ':') -pytestmark = pytest.mark.skipif(len(TEMP_DRIVE) < MAX_TEMP_DRIVES, - reason='Too many drive letters are already used by Windows to run the tests.') + TEMP_DRIVE.append(d + ":") +pytestmark = pytest.mark.skipif( + len(TEMP_DRIVE) < MAX_TEMP_DRIVES, + reason="Too many drive letters are already used by Windows to run the tests.", +) @pytest.yield_fixture(scope="module") @@ -46,32 +49,44 @@ def shares_setup(tmpdir_factory): if not ON_WINDOWS: return [] - shares = [[r'uncpushd_test_HERE', TEMP_DRIVE[1], HERE] - , [r'uncpushd_test_PARENT', TEMP_DRIVE[3], PARENT]] + shares = [ + [r"uncpushd_test_HERE", TEMP_DRIVE[1], HERE], + [r"uncpushd_test_PARENT", TEMP_DRIVE[3], PARENT], + ] - for s, d, l in shares: # set up some shares on local machine. dirs already exist test case must invoke wd_setup. - rtn = subprocess.call(['NET', 'SHARE', s, '/delete'], universal_newlines=True) # clean up from previous run after good, long wait. + for ( + s, + d, + l, + ) in ( + shares + ): # set up some shares on local machine. dirs already exist test case must invoke wd_setup. + rtn = subprocess.call( + ["NET", "SHARE", s, "/delete"], universal_newlines=True + ) # clean up from previous run after good, long wait. if rtn != 0: yield None return - rtn = subprocess.call(['NET', 'SHARE', s + '=' + l], universal_newlines=True) + rtn = subprocess.call(["NET", "SHARE", s + "=" + l], universal_newlines=True) if rtn != 0: yield None return - rtn = subprocess.call(['NET', 'USE', d, r"\\localhost" + '\\' + s], universal_newlines=True) + rtn = subprocess.call( + ["NET", "USE", d, r"\\localhost" + "\\" + s], universal_newlines=True + ) if rtn != 0: yield None return - - yield [[r"\\localhost" + '\\' + s[0], s[1], s[2]] for s in shares] + + yield [[r"\\localhost" + "\\" + s[0], s[1], s[2]] for s in shares] # we want to delete the test shares we've created, but can't do that if unc shares in DIRSTACK # (left over from assert fail aborted test) os.chdir(HERE) for dl in _unc_tempDrives: - rtn = subprocess.call(['net', 'use', dl, '/delete'], universal_newlines=True) + rtn = subprocess.call(["net", "use", dl, "/delete"], universal_newlines=True) for s, d, l in shares: - rtn = subprocess.call(['net', 'use', d, '/delete'], universal_newlines=True) + rtn = subprocess.call(["net", "use", d, "/delete"], universal_newlines=True) # subprocess.call(['net', 'share', s, '/delete'], universal_newlines=True) # fails with access denied, # unless I wait > 10 sec. see http://stackoverflow.com/questions/38448413/access-denied-in-net-share-delete @@ -83,7 +98,7 @@ def test_pushdpopd(xonsh_builtins): dirstack.cd([PARENT]) owd = os.getcwd() - assert owd.casefold() == xonsh_builtins.__xonsh_env__['PWD'].casefold() + assert owd.casefold() == xonsh_builtins.__xonsh_env__["PWD"].casefold() dirstack.pushd([HERE]) wd = os.getcwd() assert wd.casefold() == HERE.casefold() @@ -95,22 +110,22 @@ def test_cd_dot(xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env(PWD=os.getcwd()) owd = os.getcwd().casefold() - dirstack.cd(['.']) + dirstack.cd(["."]) assert owd == os.getcwd().casefold() -@pytest.mark.skipif( not ON_WINDOWS, reason="Windows-only UNC functionality") +@pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") def test_uncpushd_simple_push_pop(xonsh_builtins, shares_setup): if shares_setup is None: return xonsh_builtins.__xonsh_env__ = Env(CDPATH=PARENT, PWD=HERE) dirstack.cd([PARENT]) owd = os.getcwd() - assert owd.casefold() == xonsh_builtins.__xonsh_env__['PWD'].casefold() - dirstack.pushd([r'\\localhost\uncpushd_test_HERE']) + assert owd.casefold() == xonsh_builtins.__xonsh_env__["PWD"].casefold() + dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) wd = os.getcwd() assert os.path.splitdrive(wd)[0].casefold() == TEMP_DRIVE[0] - assert os.path.splitdrive(wd)[1].casefold() == '\\' + assert os.path.splitdrive(wd)[1].casefold() == "\\" dirstack.popd([]) assert owd.casefold() == os.getcwd().casefold(), "popd returned cwd to expected dir" assert len(_unc_tempDrives) == 0 @@ -124,29 +139,31 @@ def test_uncpushd_push_to_same_share(xonsh_builtins, shares_setup): dirstack.cd([PARENT]) owd = os.getcwd() - assert owd.casefold() == xonsh_builtins.__xonsh_env__['PWD'].casefold() - dirstack.pushd([r'\\localhost\uncpushd_test_HERE']) + assert owd.casefold() == xonsh_builtins.__xonsh_env__["PWD"].casefold() + dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) wd = os.getcwd() assert os.path.splitdrive(wd)[0].casefold() == TEMP_DRIVE[0] - assert os.path.splitdrive(wd)[1].casefold() == '\\' + assert os.path.splitdrive(wd)[1].casefold() == "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 1 - dirstack.pushd([r'\\localhost\uncpushd_test_HERE']) + dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) wd = os.getcwd() assert os.path.splitdrive(wd)[0].casefold() == TEMP_DRIVE[0] - assert os.path.splitdrive(wd)[1].casefold() == '\\' + assert os.path.splitdrive(wd)[1].casefold() == "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 2 dirstack.popd([]) - assert os.path.isdir(TEMP_DRIVE[0] + '\\'), "Temp drive not unmapped till last reference removed" + assert os.path.isdir( + TEMP_DRIVE[0] + "\\" + ), "Temp drive not unmapped till last reference removed" dirstack.popd([]) assert owd.casefold() == os.getcwd().casefold(), "popd returned cwd to expected dir" assert len(_unc_tempDrives) == 0 -@pytest.mark.skipif( not ON_WINDOWS, reason="Windows-only UNC functionality") +@pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") def test_uncpushd_push_other_push_same(xonsh_builtins, shares_setup): """push to a, then to b. verify drive letter is TEMP_DRIVE[2], skipping already used TEMP_DRIVE[1] Then push to a again. Pop (check b unmapped and a still mapped), pop, pop (check a is unmapped)""" @@ -156,43 +173,43 @@ def test_uncpushd_push_other_push_same(xonsh_builtins, shares_setup): dirstack.cd([PARENT]) owd = os.getcwd() - assert owd.casefold() == xonsh_builtins.__xonsh_env__['PWD'].casefold() - dirstack.pushd([r'\\localhost\uncpushd_test_HERE']) - assert os.getcwd().casefold() == TEMP_DRIVE[0] + '\\' + assert owd.casefold() == xonsh_builtins.__xonsh_env__["PWD"].casefold() + dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) + assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 1 - dirstack.pushd([r'\\localhost\uncpushd_test_PARENT']) + dirstack.pushd([r"\\localhost\uncpushd_test_PARENT"]) wd = os.getcwd() - assert os.getcwd().casefold() == TEMP_DRIVE[2] + '\\' + assert os.getcwd().casefold() == TEMP_DRIVE[2] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 2 - dirstack.pushd([r'\\localhost\uncpushd_test_HERE']) - assert os.getcwd().casefold() == TEMP_DRIVE[0] + '\\' + dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) + assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 3 dirstack.popd([]) - assert os.getcwd().casefold() == TEMP_DRIVE[2] + '\\' + assert os.getcwd().casefold() == TEMP_DRIVE[2] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 2 - assert os.path.isdir(TEMP_DRIVE[2] + '\\') - assert os.path.isdir(TEMP_DRIVE[0] + '\\') + assert os.path.isdir(TEMP_DRIVE[2] + "\\") + assert os.path.isdir(TEMP_DRIVE[0] + "\\") dirstack.popd([]) - assert os.getcwd().casefold() == TEMP_DRIVE[0] + '\\' + assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 1 - assert not os.path.isdir(TEMP_DRIVE[2] + '\\') - assert os.path.isdir(TEMP_DRIVE[0] + '\\') + assert not os.path.isdir(TEMP_DRIVE[2] + "\\") + assert os.path.isdir(TEMP_DRIVE[0] + "\\") dirstack.popd([]) assert os.getcwd().casefold() == owd.casefold() assert len(_unc_tempDrives) == 0 assert len(DIRSTACK) == 0 - assert not os.path.isdir(TEMP_DRIVE[2] + '\\') - assert not os.path.isdir(TEMP_DRIVE[0] + '\\') + assert not os.path.isdir(TEMP_DRIVE[2] + "\\") + assert not os.path.isdir(TEMP_DRIVE[0] + "\\") @pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") @@ -201,7 +218,7 @@ def test_uncpushd_push_base_push_rempath(xonsh_builtins): pass -#really? Need to cut-and-paste 2 flavors of this? yield_fixture requires yield in defined function body, not callee +# really? Need to cut-and-paste 2 flavors of this? yield_fixture requires yield in defined function body, not callee @pytest.yield_fixture() def with_unc_check_enabled(): if not ON_WINDOWS: @@ -210,19 +227,27 @@ def with_unc_check_enabled(): import winreg old_wval = 0 - key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'software\microsoft\command processor', access=winreg.KEY_WRITE) + key = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"software\microsoft\command processor", + access=winreg.KEY_WRITE, + ) try: - wval, wtype = winreg.QueryValueEx(key, 'DisableUNCCheck') - old_wval = wval # if values was defined at all + wval, wtype = winreg.QueryValueEx(key, "DisableUNCCheck") + old_wval = wval # if values was defined at all except OSError as e: pass - winreg.SetValueEx(key, 'DisableUNCCheck', None, winreg.REG_DWORD, 0) + winreg.SetValueEx(key, "DisableUNCCheck", None, winreg.REG_DWORD, 0) winreg.CloseKey(key) yield old_wval - key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'software\microsoft\command processor', access=winreg.KEY_WRITE) - winreg.SetValueEx(key, 'DisableUNCCheck', None, winreg.REG_DWORD, old_wval) + key = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"software\microsoft\command processor", + access=winreg.KEY_WRITE, + ) + winreg.SetValueEx(key, "DisableUNCCheck", None, winreg.REG_DWORD, old_wval) winreg.CloseKey(key) @@ -234,57 +259,65 @@ def with_unc_check_disabled(): # just like the above, but value is 1 to *disabl import winreg old_wval = 0 - key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'software\microsoft\command processor', access=winreg.KEY_WRITE) + key = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"software\microsoft\command processor", + access=winreg.KEY_WRITE, + ) try: - wval, wtype = winreg.QueryValueEx(key, 'DisableUNCCheck') - old_wval = wval # if values was defined at all + wval, wtype = winreg.QueryValueEx(key, "DisableUNCCheck") + old_wval = wval # if values was defined at all except OSError as e: pass - winreg.SetValueEx(key, 'DisableUNCCheck', None, winreg.REG_DWORD, 1) + winreg.SetValueEx(key, "DisableUNCCheck", None, winreg.REG_DWORD, 1) winreg.CloseKey(key) yield old_wval - key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'software\microsoft\command processor', access=winreg.KEY_WRITE) - winreg.SetValueEx(key, 'DisableUNCCheck', None, winreg.REG_DWORD, old_wval) + key = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"software\microsoft\command processor", + access=winreg.KEY_WRITE, + ) + winreg.SetValueEx(key, "DisableUNCCheck", None, winreg.REG_DWORD, old_wval) winreg.CloseKey(key) @pytest.fixture() def xonsh_builtins_cd(xonsh_builtins): - xonsh_builtins.__xonsh_env__['CDPATH'] = PARENT - xonsh_builtins.__xonsh_env__['PWD'] = os.getcwd() - xonsh_builtins.__xonsh_env__['DIRSTACK_SIZE'] = 20 + xonsh_builtins.__xonsh_env__["CDPATH"] = PARENT + xonsh_builtins.__xonsh_env__["PWD"] = os.getcwd() + xonsh_builtins.__xonsh_env__["DIRSTACK_SIZE"] = 20 return xonsh_builtins @pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") def test_uncpushd_cd_unc_auto_pushd(xonsh_builtins_cd, with_unc_check_enabled): - xonsh_builtins_cd.__xonsh_env__['AUTO_PUSHD'] = True - so, se, rc = dirstack.cd([r'\\localhost\uncpushd_test_PARENT']) + xonsh_builtins_cd.__xonsh_env__["AUTO_PUSHD"] = True + so, se, rc = dirstack.cd([r"\\localhost\uncpushd_test_PARENT"]) if rc != 0: return - assert os.getcwd().casefold() == TEMP_DRIVE[0] + '\\' + assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(DIRSTACK) == 1 - assert os.path.isdir(TEMP_DRIVE[0] + '\\') + assert os.path.isdir(TEMP_DRIVE[0] + "\\") @pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") def test_uncpushd_cd_unc_nocheck(xonsh_builtins_cd, with_unc_check_disabled): if with_unc_check_disabled == 0: return - dirstack.cd([r'\\localhost\uncpushd_test_HERE']) - assert os.getcwd().casefold() == r'\\localhost\uncpushd_test_here' + dirstack.cd([r"\\localhost\uncpushd_test_HERE"]) + assert os.getcwd().casefold() == r"\\localhost\uncpushd_test_here" @pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") def test_uncpushd_cd_unc_no_auto_pushd(xonsh_builtins_cd, with_unc_check_enabled): if with_unc_check_enabled == 0: return - so, se, rc = dirstack.cd([r'\\localhost\uncpushd_test_PARENT']) + so, se, rc = dirstack.cd([r"\\localhost\uncpushd_test_PARENT"]) assert rc != 0 assert so is None or len(so) == 0 - assert 'disableunccheck' in se.casefold() and 'auto_pushd' in se.casefold() + assert "disableunccheck" in se.casefold() and "auto_pushd" in se.casefold() @pytest.mark.skipif(not ON_WINDOWS, reason="Windows-only UNC functionality") diff --git a/tests/test_environ.py b/tests/test_environ.py index 29c6a7896..80909ca89 100644 --- a/tests/test_environ.py +++ b/tests/test_environ.py @@ -11,133 +11,150 @@ from xonsh.tools import ON_WINDOWS import pytest from xonsh.commands_cache import CommandsCache -from xonsh.environ import (Env, locate_binary, DEFAULT_ENSURERS, DEFAULT_VALUES, - default_env, make_args_env) +from xonsh.environ import ( + Env, + locate_binary, + DEFAULT_ENSURERS, + DEFAULT_VALUES, + default_env, + make_args_env, +) from tools import skip_if_on_unix + def test_env_normal(): - env = Env(VAR='wakka') - assert 'wakka' == env['VAR'] + env = Env(VAR="wakka") + assert "wakka" == env["VAR"] + def test_env_contains(): - env = Env(VAR='wakka') - assert 'VAR' in env + env = Env(VAR="wakka") + assert "VAR" in env -@pytest.mark.parametrize('path', [['/home/wakka'], ['wakka']]) + +@pytest.mark.parametrize("path", [["/home/wakka"], ["wakka"]]) def test_env_path_list(path): env = Env(MYPATH=path) - assert path == env['MYPATH'].paths + assert path == env["MYPATH"].paths -@pytest.mark.parametrize('path', [ - ['/home/wakka' + os.pathsep + '/home/jawaka'], - ['wakka' + os.pathsep + 'jawaka'] -]) + +@pytest.mark.parametrize( + "path", + [["/home/wakka" + os.pathsep + "/home/jawaka"], ["wakka" + os.pathsep + "jawaka"]], +) def test_env_path_str(path): env = Env(MYPATH=path) - assert path == env['MYPATH'].paths + assert path == env["MYPATH"].paths + def test_env_detype(): - env = Env(MYPATH=['wakka', 'jawaka']) - assert 'wakka' + os.pathsep + 'jawaka' == env.detype()['MYPATH'] + env = Env(MYPATH=["wakka", "jawaka"]) + assert "wakka" + os.pathsep + "jawaka" == env.detype()["MYPATH"] -@pytest.mark.parametrize('path1, path2',[ - (['/home/wakka', '/home/jawaka'], '/home/woah'), - (['wakka', 'jawaka'], 'woah') -]) + +@pytest.mark.parametrize( + "path1, path2", + [(["/home/wakka", "/home/jawaka"], "/home/woah"), (["wakka", "jawaka"], "woah")], +) def test_env_detype_mutable_access_clear(path1, path2): env = Env(MYPATH=path1) - assert path1[0] + os.pathsep + path1[1] == env.detype()['MYPATH'] - env['MYPATH'][0] = path2 + assert path1[0] + os.pathsep + path1[1] == env.detype()["MYPATH"] + env["MYPATH"][0] = path2 assert env._detyped is None - assert path2 + os.pathsep + path1[1] == env.detype()['MYPATH'] + assert path2 + os.pathsep + path1[1] == env.detype()["MYPATH"] + def test_env_detype_no_dict(): - env = Env(YO={'hey': 42}) + env = Env(YO={"hey": 42}) det = env.detype() - assert 'YO' not in det + assert "YO" not in det + def test_histcontrol_none(): env = Env(HISTCONTROL=None) - assert isinstance(env['HISTCONTROL'], set) - assert len(env['HISTCONTROL']) == 0 + assert isinstance(env["HISTCONTROL"], set) + assert len(env["HISTCONTROL"]) == 0 + def test_HISTCONTROL_empty(): - env = Env(HISTCONTROL='') - assert isinstance(env['HISTCONTROL'], set) - assert len(env['HISTCONTROL']) == 0 + env = Env(HISTCONTROL="") + assert isinstance(env["HISTCONTROL"], set) + assert len(env["HISTCONTROL"]) == 0 + def test_histcontrol_ignoredups(): - env = Env(HISTCONTROL='ignoredups') - assert isinstance(env['HISTCONTROL'], set) - assert len(env['HISTCONTROL']) == 1 - assert ('ignoredups' in env['HISTCONTROL']) - assert ('ignoreerr' not in env['HISTCONTROL']) + env = Env(HISTCONTROL="ignoredups") + assert isinstance(env["HISTCONTROL"], set) + assert len(env["HISTCONTROL"]) == 1 + assert "ignoredups" in env["HISTCONTROL"] + assert "ignoreerr" not in env["HISTCONTROL"] + def test_histcontrol_ignoreerr_ignoredups(): - env = Env(HISTCONTROL='ignoreerr,ignoredups,ignoreerr') - assert len(env['HISTCONTROL']) == 2 - assert ('ignoreerr' in env['HISTCONTROL']) - assert ('ignoredups' in env['HISTCONTROL']) + env = Env(HISTCONTROL="ignoreerr,ignoredups,ignoreerr") + assert len(env["HISTCONTROL"]) == 2 + assert "ignoreerr" in env["HISTCONTROL"] + assert "ignoredups" in env["HISTCONTROL"] + def test_swap(): - env = Env(VAR='wakka') - assert env['VAR'] == 'wakka' + env = Env(VAR="wakka") + assert env["VAR"] == "wakka" # positional arg - with env.swap({'VAR': 'foo'}): - assert env['VAR'] == 'foo' + with env.swap({"VAR": "foo"}): + assert env["VAR"] == "foo" # make sure the environment goes back outside the context manager - assert env['VAR'] == 'wakka' + assert env["VAR"] == "wakka" # kwargs only - with env.swap(VAR1='foo', VAR2='bar'): - assert env['VAR1'] == 'foo' - assert env['VAR2'] == 'bar' + with env.swap(VAR1="foo", VAR2="bar"): + assert env["VAR1"] == "foo" + assert env["VAR2"] == "bar" # positional and kwargs - with env.swap({'VAR3': 'baz'}, VAR1='foo', VAR2='bar'): - assert env['VAR1'] == 'foo' - assert env['VAR2'] == 'bar' - assert env['VAR3'] == 'baz' + with env.swap({"VAR3": "baz"}, VAR1="foo", VAR2="bar"): + assert env["VAR1"] == "foo" + assert env["VAR2"] == "bar" + assert env["VAR3"] == "baz" # make sure the environment goes back outside the context manager - assert env['VAR'] == 'wakka' - assert 'VAR1' not in env - assert 'VAR2' not in env - assert 'VAR3' not in env + assert env["VAR"] == "wakka" + assert "VAR1" not in env + assert "VAR2" not in env + assert "VAR3" not in env def test_swap_exception_replacement(): - env = Env(VAR='original value') + env = Env(VAR="original value") try: - with env.swap(VAR='inner value'): - assert env['VAR'] == 'inner value' + with env.swap(VAR="inner value"): + assert env["VAR"] == "inner value" raise Exception() except Exception: - assert env['VAR'] == 'original value' - assert env['VAR'] == 'original value' + assert env["VAR"] == "original value" + assert env["VAR"] == "original value" @skip_if_on_unix def test_locate_binary_on_windows(xonsh_builtins): - files = ('file1.exe', 'FILE2.BAT', 'file3.txt') + files = ("file1.exe", "FILE2.BAT", "file3.txt") with TemporaryDirectory() as tmpdir: for fname in files: fpath = os.path.join(tmpdir, fname) - with open(fpath, 'w') as f: + with open(fpath, "w") as f: f.write(fpath) - xonsh_builtins.__xonsh_env__.update({ - 'PATH': [tmpdir], - 'PATHEXT': ['.COM', '.EXE', '.BAT'], - }) + xonsh_builtins.__xonsh_env__.update( + {"PATH": [tmpdir], "PATHEXT": [".COM", ".EXE", ".BAT"]} + ) xonsh_builtins.__xonsh_commands_cache__ = CommandsCache() - assert locate_binary('file1') == os.path.join(tmpdir, 'file1.exe') - assert locate_binary('file1.exe') == os.path.join(tmpdir, 'file1.exe') - assert locate_binary('file2') == os.path.join(tmpdir, 'FILE2.BAT') - assert locate_binary('file2.bat') == os.path.join(tmpdir, 'FILE2.BAT') - assert locate_binary('file3') is None + assert locate_binary("file1") == os.path.join(tmpdir, "file1.exe") + assert locate_binary("file1.exe") == os.path.join(tmpdir, "file1.exe") + assert locate_binary("file2") == os.path.join(tmpdir, "FILE2.BAT") + assert locate_binary("file2.bat") == os.path.join(tmpdir, "FILE2.BAT") + assert locate_binary("file3") is None def test_event_on_envvar_change(xonsh_builtins): @@ -150,9 +167,9 @@ def test_event_on_envvar_change(xonsh_builtins): share.extend((name, oldvalue, newvalue)) # trigger - env['TEST'] = 1 + env["TEST"] = 1 - assert share == ['TEST', 0, 1] + assert share == ["TEST", 0, 1] def test_event_on_envvar_new(xonsh_builtins): @@ -165,9 +182,10 @@ def test_event_on_envvar_new(xonsh_builtins): share.extend((name, value)) # trigger - env['TEST'] = 1 + env["TEST"] = 1 + + assert share == ["TEST", 1] - assert share == ['TEST', 1] def test_event_on_envvar_change_from_none_value(xonsh_builtins): env = Env(TEST=None) @@ -179,12 +197,12 @@ def test_event_on_envvar_change_from_none_value(xonsh_builtins): share.extend((name, oldvalue, newvalue)) # trigger - env['TEST'] = 1 + env["TEST"] = 1 - assert share == ['TEST', None, 1] + assert share == ["TEST", None, 1] -@pytest.mark.parametrize('val', [1, None, True, 'ok']) +@pytest.mark.parametrize("val", [1, None, True, "ok"]) def test_event_on_envvar_change_no_fire_when_value_is_same(val, xonsh_builtins): env = Env(TEST=val) xonsh_builtins.__xonsh_env__ = env @@ -194,9 +212,8 @@ def test_event_on_envvar_change_no_fire_when_value_is_same(val, xonsh_builtins): def handler(name, oldvalue, newvalue, **kwargs): share.extend((name, oldvalue, newvalue)) - # trigger - env['TEST'] = val + env["TEST"] = val assert share == [] @@ -208,21 +225,21 @@ def test_events_on_envvar_called_in_right_order(xonsh_builtins): # register @xonsh_builtins.events.on_envvar_new def handler(name, value, **kwargs): - share[:] = ['new'] + share[:] = ["new"] @xonsh_builtins.events.on_envvar_change def handler(name, oldvalue, newvalue, **kwargs): - share[:] = ['change'] + share[:] = ["change"] # trigger new - env['TEST'] = 1 + env["TEST"] = 1 - assert share == ['new'] + assert share == ["new"] # trigger change - env['TEST'] = 2 + env["TEST"] = 2 - assert share == ['change'] + assert share == ["change"] def test_int_bool_envvars_have_ensurers(): @@ -233,24 +250,24 @@ def test_int_bool_envvars_have_ensurers(): def test_no_lines_columns(): - os.environ['LINES'] = 'spam' - os.environ['COLUMNS'] = 'eggs' + os.environ["LINES"] = "spam" + os.environ["COLUMNS"] = "eggs" try: env = default_env() - assert 'LINES' not in env - assert 'COLUMNS' not in env + assert "LINES" not in env + assert "COLUMNS" not in env finally: - del os.environ['LINES'] - del os.environ['COLUMNS'] + del os.environ["LINES"] + del os.environ["COLUMNS"] def test_make_args_env(): - obs = make_args_env(['script', '1', '2', '3']) + obs = make_args_env(["script", "1", "2", "3"]) exp = { - 'ARGS': ['script', '1', '2', '3'], - 'ARG0': 'script', - 'ARG1': '1', - 'ARG2': '2', - 'ARG3': '3', + "ARGS": ["script", "1", "2", "3"], + "ARG0": "script", + "ARG1": "1", + "ARG2": "2", + "ARG3": "3", } assert exp == obs diff --git a/tests/test_events.py b/tests/test_events.py index ef12871c4..738fc3017 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -54,7 +54,7 @@ def test_validator(events): @first.validator def v(n): - return n == 'spam' + return n == "spam" @events.on_test def second(n, **_): @@ -63,24 +63,24 @@ def test_validator(events): return False called = 0 - events.on_test.fire(n='egg') + events.on_test.fire(n="egg") assert called == 1 called = 0 - events.on_test.fire(n='spam') + events.on_test.fire(n="spam") assert called == 2 def test_eventdoc(events): docstring = "Test event" - events.doc('on_test', docstring) + events.doc("on_test", docstring) assert inspect.getdoc(events.on_test) == docstring def test_transmogrify(events): docstring = "Test event" - events.doc('on_test', docstring) + events.doc("on_test", docstring) @events.on_test def func(**_): @@ -90,7 +90,7 @@ def test_transmogrify(events): assert len(events.on_test) == 1 assert inspect.getdoc(events.on_test) == docstring - events.transmogrify('on_test', LoadEvent) + events.transmogrify("on_test", LoadEvent) assert isinstance(events.on_test, LoadEvent) assert len(events.on_test) == 1 @@ -99,7 +99,7 @@ def test_transmogrify(events): def test_transmogrify_by_string(events): docstring = "Test event" - events.doc('on_test', docstring) + events.doc("on_test", docstring) @events.on_test def func(**_): @@ -109,7 +109,7 @@ def test_transmogrify_by_string(events): assert len(events.on_test) == 1 assert inspect.getdoc(events.on_test) == docstring - events.transmogrify('on_test', 'LoadEvent') + events.transmogrify("on_test", "LoadEvent") assert isinstance(events.on_test, LoadEvent) assert len(events.on_test) == 1 @@ -117,7 +117,7 @@ def test_transmogrify_by_string(events): def test_load(events): - events.transmogrify('on_test', 'LoadEvent') + events.transmogrify("on_test", "LoadEvent") called = 0 @events.on_test @@ -137,8 +137,9 @@ def test_load(events): assert called == 2 + def test_load_2nd_call(events): - events.transmogrify('on_test', 'LoadEvent') + events.transmogrify("on_test", "LoadEvent") called = 0 @events.on_test @@ -157,6 +158,6 @@ def test_load_2nd_call(events): def test_typos(xonsh_builtins): for name, ev in vars(xonsh_builtins.events).items(): - if 'pytest' in name: + if "pytest" in name: continue assert inspect.getdoc(ev) diff --git a/tests/test_execer.py b/tests/test_execer.py index 1c03054c9..75dc205e5 100644 --- a/tests/test_execer.py +++ b/tests/test_execer.py @@ -2,8 +2,7 @@ """Tests the xonsh lexer.""" import os -from tools import (check_eval, check_parse, - skip_if_on_unix, skip_if_on_windows) +from tools import check_eval, check_parse, skip_if_on_unix, skip_if_on_windows import pytest @@ -15,85 +14,89 @@ def xonsh_execer_autouse(xonsh_builtins, xonsh_execer): @skip_if_on_unix def test_win_ipconfig(): - assert check_eval(os.environ['SYSTEMROOT'] + '\\System32\\ipconfig.exe /all') + assert check_eval(os.environ["SYSTEMROOT"] + "\\System32\\ipconfig.exe /all") + @skip_if_on_unix def test_ipconfig(): - assert check_eval('ipconfig /all') + assert check_eval("ipconfig /all") + @skip_if_on_windows def test_bin_ls(): - assert check_eval('/bin/ls -l') + assert check_eval("/bin/ls -l") + def test_ls_dashl(): - assert check_parse('ls -l') + assert check_parse("ls -l") + def test_which_ls(): - assert check_parse('which ls') + assert check_parse("which ls") + def test_echo_hello(): - assert check_parse('echo hello') + assert check_parse("echo hello") def test_echo_star_with_semi(): - assert check_parse('echo * spam ; ![echo eggs]\n') + assert check_parse("echo * spam ; ![echo eggs]\n") def test_simple_func(): - code = ('def prompt():\n' - " return '{user}'.format(user='me')\n") + code = "def prompt():\n" " return '{user}'.format(user='me')\n" assert check_parse(code) + def test_lookup_alias(): - code = ( - 'def foo(a, s=None):\n' - ' return "bar"\n' - '@(foo)\n') + code = "def foo(a, s=None):\n" ' return "bar"\n' "@(foo)\n" assert check_parse(code) + def test_lookup_anon_alias(): - code = ('echo "hi" | @(lambda a, s=None: a[0]) foo bar baz\n') + code = 'echo "hi" | @(lambda a, s=None: a[0]) foo bar baz\n' assert check_parse(code) + def test_simple_func_broken(): - code = ('def prompt():\n' - " return '{user}'.format(\n" - " user='me')\n") + code = "def prompt():\n" " return '{user}'.format(\n" " user='me')\n" assert check_parse(code) + def test_bad_indent(): - code = ('if True:\n' - 'x = 1\n') + code = "if True:\n" "x = 1\n" with pytest.raises(SyntaxError): check_parse(code) + def test_good_rhs_subproc(): # nonsense but parsable - code = 'str().split() | ![grep exit]\n' - assert(code) + code = "str().split() | ![grep exit]\n" + assert code + def test_bad_rhs_subproc(): # nonsense but unparsable - code = 'str().split() | grep exit\n' + code = "str().split() | grep exit\n" with pytest.raises(SyntaxError): check_parse(code) + def test_indent_with_empty_line(): - code = ('if True:\n' - '\n' - ' some_command for_sub_process_mode\n') + code = "if True:\n" "\n" " some_command for_sub_process_mode\n" assert check_parse(code) + def test_command_in_func(): - code = ('def f():\n' - ' echo hello\n') + code = "def f():\n" " echo hello\n" assert check_parse(code) + def test_command_in_func_with_comment(): - code = ('def f():\n' - ' echo hello # comment\n') + code = "def f():\n" " echo hello # comment\n" assert check_parse(code) + def test_pyeval_redirect(): code = 'echo @("foo") > bar\n' assert check_parse(code) @@ -105,15 +108,17 @@ def test_pyeval_multiline_str(): def test_echo_comma(): - code = 'echo ,\n' + code = "echo ,\n" assert check_parse(code) + def test_echo_comma_val(): - code = 'echo ,1\n' + code = "echo ,1\n" assert check_parse(code) + def test_echo_comma_2val(): - code = 'echo 1,2\n' + code = "echo 1,2\n" assert check_parse(code) @@ -121,10 +126,14 @@ def test_echo_line_cont(): code = 'echo "1 \\\n2"\n' assert check_parse(code) -@pytest.mark.parametrize('code', [ - "echo a and \\\necho b\n", - "echo a \\\n or echo b\n", - "echo a \\\n or echo b and \\\n echo c\n", -]) + +@pytest.mark.parametrize( + "code", + [ + "echo a and \\\necho b\n", + "echo a \\\n or echo b\n", + "echo a \\\n or echo b and \\\n echo c\n", + ], +) def test_two_echo_line_cont(code): assert check_parse(code) diff --git a/tests/test_foreign_shells.py b/tests/test_foreign_shells.py index 86b5b8de8..d9ea3c103 100644 --- a/tests/test_foreign_shells.py +++ b/tests/test_foreign_shells.py @@ -11,68 +11,72 @@ from xonsh.foreign_shells import foreign_shell_data, parse_env, parse_aliases def test_parse_env(): - exp = {'X': 'YES', 'Y': 'NO'} - s = ('some garbage\n' - '__XONSH_ENV_BEG__\n' - 'Y=NO\n' - 'X=YES\n' - '__XONSH_ENV_END__\n' - 'more filth') + exp = {"X": "YES", "Y": "NO"} + s = ( + "some garbage\n" + "__XONSH_ENV_BEG__\n" + "Y=NO\n" + "X=YES\n" + "__XONSH_ENV_END__\n" + "more filth" + ) obs = parse_env(s) - assert exp == obs + assert exp == obs def test_parse_env_newline(): - exp = {'X': 'YES', 'Y': 'NO', 'PROMPT': 'why\nme '} - s = ('some garbage\n' - '__XONSH_ENV_BEG__\n' - 'Y=NO\n' - 'PROMPT=why\nme \n' - 'X=YES\n' - '__XONSH_ENV_END__\n' - 'more filth') + exp = {"X": "YES", "Y": "NO", "PROMPT": "why\nme "} + s = ( + "some garbage\n" + "__XONSH_ENV_BEG__\n" + "Y=NO\n" + "PROMPT=why\nme \n" + "X=YES\n" + "__XONSH_ENV_END__\n" + "more filth" + ) obs = parse_env(s) assert exp == obs def test_parse_env_equals(): - exp = {'X': 'YES', 'Y': 'NO', 'LS_COLORS': '*.tar=5'} - s = ('some garbage\n' - '__XONSH_ENV_BEG__\n' - 'Y=NO\n' - 'LS_COLORS=*.tar=5\n' - 'X=YES\n' - '__XONSH_ENV_END__\n' - 'more filth') + exp = {"X": "YES", "Y": "NO", "LS_COLORS": "*.tar=5"} + s = ( + "some garbage\n" + "__XONSH_ENV_BEG__\n" + "Y=NO\n" + "LS_COLORS=*.tar=5\n" + "X=YES\n" + "__XONSH_ENV_END__\n" + "more filth" + ) obs = parse_env(s) assert exp == obs def test_parse_aliases(): - exp = {'x': ['yes', '-1'], 'y': ['echo', 'no']} - s = ('some garbage\n' - '__XONSH_ALIAS_BEG__\n' - "alias x='yes -1'\n" - "alias y='echo no'\n" - '__XONSH_ALIAS_END__\n' - 'more filth') + exp = {"x": ["yes", "-1"], "y": ["echo", "no"]} + s = ( + "some garbage\n" + "__XONSH_ALIAS_BEG__\n" + "alias x='yes -1'\n" + "alias y='echo no'\n" + "__XONSH_ALIAS_END__\n" + "more filth" + ) obs = parse_aliases(s) - assert exp == obs + assert exp == obs @skip_if_on_windows def test_foreign_bash_data(): - expenv = {"EMERALD": "SWORD", 'MIGHTY': 'WARRIOR'} - expaliases = { - 'l': ['ls', '-CF'], - 'la': ['ls', '-A'], - 'll': ['ls', '-a', '-lF'], - } - rcfile = os.path.join(os.path.dirname(__file__), 'bashrc.sh') + expenv = {"EMERALD": "SWORD", "MIGHTY": "WARRIOR"} + expaliases = {"l": ["ls", "-CF"], "la": ["ls", "-A"], "ll": ["ls", "-a", "-lF"]} + rcfile = os.path.join(os.path.dirname(__file__), "bashrc.sh") try: - obsenv, obsaliases = foreign_shell_data('bash', currenv=(), - extra_args=('--rcfile', rcfile), - safe=False) + obsenv, obsaliases = foreign_shell_data( + "bash", currenv=(), extra_args=("--rcfile", rcfile), safe=False + ) except (subprocess.CalledProcessError, FileNotFoundError): return for key, expval in expenv.items(): @@ -83,18 +87,22 @@ def test_foreign_bash_data(): @skip_if_on_unix def test_foreign_cmd_data(): - env = (('ENV_TO_BE_REMOVED','test'),) - batchfile = os.path.join(os.path.dirname(__file__), 'batch.bat') - source_cmd ='call "{}"\necho off'.format(batchfile) + env = (("ENV_TO_BE_REMOVED", "test"),) + batchfile = os.path.join(os.path.dirname(__file__), "batch.bat") + source_cmd = 'call "{}"\necho off'.format(batchfile) try: - obsenv, _ = foreign_shell_data('cmd',prevcmd=source_cmd, - currenv=env, - interactive =False, - sourcer='call',envcmd='set', - use_tmpfile=True, - safe=False) + obsenv, _ = foreign_shell_data( + "cmd", + prevcmd=source_cmd, + currenv=env, + interactive=False, + sourcer="call", + envcmd="set", + use_tmpfile=True, + safe=False, + ) except (subprocess.CalledProcessError, FileNotFoundError): return - assert 'ENV_TO_BE_ADDED' in obsenv - assert obsenv['ENV_TO_BE_ADDED']=='Hallo world' - assert 'ENV_TO_BE_REMOVED' not in obsenv + assert "ENV_TO_BE_ADDED" in obsenv + assert obsenv["ENV_TO_BE_ADDED"] == "Hallo world" + assert "ENV_TO_BE_REMOVED" not in obsenv diff --git a/tests/test_history.py b/tests/test_history.py index 1b182476c..a0a535849 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -12,12 +12,14 @@ from xonsh.history.json import JsonHistory from xonsh.history.main import history_main, _xh_parse_args, construct_history -CMDS = ['ls', 'cat hello kitty', 'abc', 'def', 'touch me', 'grep from me'] +CMDS = ["ls", "cat hello kitty", "abc", "def", "touch me", "grep from me"] + @pytest.yield_fixture def hist(): - h = JsonHistory(filename='xonsh-HISTORY-TEST.json', here='yup', - sessionid='SESSIONID', gc=False) + h = JsonHistory( + filename="xonsh-HISTORY-TEST.json", here="yup", sessionid="SESSIONID", gc=False + ) yield h os.remove(h.filename) @@ -25,25 +27,25 @@ def hist(): def test_hist_init(hist): """Test initialization of the shell history.""" with LazyJSON(hist.filename) as lj: - obs = lj['here'] - assert 'yup' == obs + obs = lj["here"] + assert "yup" == obs def test_hist_append(hist, xonsh_builtins): """Verify appending to the history works.""" - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - hf = hist.append({'inp': 'still alive', 'rtn': 0}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + hf = hist.append({"inp": "still alive", "rtn": 0}) assert hf is None - assert 'still alive' == hist.buffer[0]['inp'] - assert 0 == hist.buffer[0]['rtn'] + assert "still alive" == hist.buffer[0]["inp"] + assert 0 == hist.buffer[0]["rtn"] assert 0 == hist.rtns[-1] - hf = hist.append({'inp': 'dead now', 'rtn': 1}) - assert 'dead now' == hist.buffer[1]['inp'] - assert 1 == hist.buffer[1]['rtn'] + hf = hist.append({"inp": "dead now", "rtn": 1}) + assert "dead now" == hist.buffer[1]["inp"] + assert 1 == hist.buffer[1]["rtn"] assert 1 == hist.rtns[-1] - hf = hist.append({'inp': 'reborn', 'rtn': 0}) - assert 'reborn' == hist.buffer[2]['inp'] - assert 0 == hist.buffer[2]['rtn'] + hf = hist.append({"inp": "reborn", "rtn": 0}) + assert "reborn" == hist.buffer[2]["inp"] + assert 0 == hist.buffer[2]["rtn"] assert 0 == hist.rtns[-1] @@ -51,62 +53,62 @@ def test_hist_flush(hist, xonsh_builtins): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - hist.append({'inp': 'still alive?', 'rtn': 0, 'out': 'yes'}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass with LazyJSON(hist.filename) as lj: - assert len(lj['cmds']) == 1 - cmd = lj['cmds'][0] - assert cmd['inp'] == 'still alive?' - assert not cmd.get('out', None) + assert len(lj["cmds"]) == 1 + cmd = lj["cmds"][0] + assert cmd["inp"] == "still alive?" + assert not cmd.get("out", None) def test_hist_flush_with_store_stdout(hist, xonsh_builtins): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - xonsh_builtins.__xonsh_env__['XONSH_STORE_STDOUT'] = True - hist.append({'inp': 'still alive?', 'rtn': 0, 'out': 'yes'}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + xonsh_builtins.__xonsh_env__["XONSH_STORE_STDOUT"] = True + hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass with LazyJSON(hist.filename) as lj: - assert len(lj['cmds']) == 1 - assert lj['cmds'][0]['inp'] == 'still alive?' - assert lj['cmds'][0]['out'].strip() == 'yes' + assert len(lj["cmds"]) == 1 + assert lj["cmds"][0]["inp"] == "still alive?" + assert lj["cmds"][0]["out"].strip() == "yes" def test_hist_flush_with_hist_control(hist, xonsh_builtins): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = 'ignoredups,ignoreerr' - hist.append({'inp': 'ls foo1', 'rtn': 0}) - hist.append({'inp': 'ls foo1', 'rtn': 1}) - hist.append({'inp': 'ls foo1', 'rtn': 0}) - hist.append({'inp': 'ls foo2', 'rtn': 2}) - hist.append({'inp': 'ls foo3', 'rtn': 0}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = "ignoredups,ignoreerr" + hist.append({"inp": "ls foo1", "rtn": 0}) + hist.append({"inp": "ls foo1", "rtn": 1}) + hist.append({"inp": "ls foo1", "rtn": 0}) + hist.append({"inp": "ls foo2", "rtn": 2}) + hist.append({"inp": "ls foo3", "rtn": 0}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass assert len(hist.buffer) == 0 with LazyJSON(hist.filename) as lj: - cmds = list(lj['cmds']) + cmds = list(lj["cmds"]) assert len(cmds) == 2 - assert [x['inp'] for x in cmds] == ['ls foo1', 'ls foo3'] - assert [x['rtn'] for x in cmds] == [0, 0] + assert [x["inp"] for x in cmds] == ["ls foo1", "ls foo3"] + assert [x["rtn"] for x in cmds] == [0, 0] def test_cmd_field(hist, xonsh_builtins): # in-memory - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - hf = hist.append({'inp': 'ls foo', 'rtn': 1}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + hf = hist.append({"inp": "ls foo", "rtn": 1}) assert hf is None assert 1 == hist.rtns[0] assert 1 == hist.rtns[-1] @@ -121,29 +123,34 @@ def test_cmd_field(hist, xonsh_builtins): assert None == hist.outs[-1] -@pytest.mark.parametrize('inp, commands, offset', [ - ('', CMDS, (0, 1)), - ('-r', list(reversed(CMDS)), (len(CMDS)- 1, -1)), - ('0', CMDS[0:1], (0, 1)), - ('1', CMDS[1:2], (1, 1)), - ('-2', CMDS[-2:-1], (len(CMDS) -2 , 1)), - ('1:3', CMDS[1:3], (1, 1)), - ('1::2', CMDS[1::2], (1, 2)), - ('-4:-2', CMDS[-4:-2], (len(CMDS) - 4, 1)) - ]) +@pytest.mark.parametrize( + "inp, commands, offset", + [ + ("", CMDS, (0, 1)), + ("-r", list(reversed(CMDS)), (len(CMDS) - 1, -1)), + ("0", CMDS[0:1], (0, 1)), + ("1", CMDS[1:2], (1, 1)), + ("-2", CMDS[-2:-1], (len(CMDS) - 2, 1)), + ("1:3", CMDS[1:3], (1, 1)), + ("1::2", CMDS[1::2], (1, 2)), + ("-4:-2", CMDS[-4:-2], (len(CMDS) - 4, 1)), + ], +) def test_show_cmd_numerate(inp, commands, offset, hist, xonsh_builtins, capsys): """Verify that CLI history commands work.""" base_idx, step = offset xonsh_builtins.__xonsh_history__ = hist - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history - hist.append({'inp': cmd, 'rtn': 0, 'ts':(ts + 1, ts + 1.5)}) + hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) - exp = ('{}: {}'.format(base_idx + idx * step, cmd) - for idx, cmd in enumerate(list(commands))) - exp = '\n'.join(exp) + exp = ( + "{}: {}".format(base_idx + idx * step, cmd) + for idx, cmd in enumerate(list(commands)) + ) + exp = "\n".join(exp) - history_main(['show', '-n'] + shlex.split(inp)) + history_main(["show", "-n"] + shlex.split(inp)) out, err = capsys.readouterr() assert out.rstrip() == exp @@ -151,124 +158,134 @@ def test_show_cmd_numerate(inp, commands, offset, hist, xonsh_builtins, capsys): def test_histcontrol(hist, xonsh_builtins): """Test HISTCONTROL=ignoredups,ignoreerr""" - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = 'ignoredups,ignoreerr' + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = "ignoredups,ignoreerr" assert len(hist.buffer) == 0 # An error, buffer remains empty - hist.append({'inp': 'ls foo', 'rtn': 2}) + hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist.buffer) == 1 assert hist.rtns[-1] == 2 - assert hist.inps[-1] == 'ls foo' + assert hist.inps[-1] == "ls foo" # Success - hist.append({'inp': 'ls foobazz', 'rtn': 0}) + hist.append({"inp": "ls foobazz", "rtn": 0}) assert len(hist.buffer) == 2 - assert 'ls foobazz' == hist.buffer[-1]['inp'] - assert 0 == hist.buffer[-1]['rtn'] + assert "ls foobazz" == hist.buffer[-1]["inp"] + assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 - assert hist.inps[-1] == 'ls foobazz' + assert hist.inps[-1] == "ls foobazz" # Error - hist.append({'inp': 'ls foo', 'rtn': 2}) + hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist.buffer) == 3 - assert 'ls foo' == hist.buffer[-1]['inp'] - assert 2 == hist.buffer[-1]['rtn'] + assert "ls foo" == hist.buffer[-1]["inp"] + assert 2 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 2 - assert hist.inps[-1] == 'ls foo' + assert hist.inps[-1] == "ls foo" # File now exists, success - hist.append({'inp': 'ls foo', 'rtn': 0}) + hist.append({"inp": "ls foo", "rtn": 0}) assert len(hist.buffer) == 4 - assert 'ls foo' == hist.buffer[-1]['inp'] - assert 0 == hist.buffer[-1]['rtn'] + assert "ls foo" == hist.buffer[-1]["inp"] + assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 - assert hist.inps[-1] == 'ls foo' + assert hist.inps[-1] == "ls foo" # Success - hist.append({'inp': 'ls', 'rtn': 0}) + hist.append({"inp": "ls", "rtn": 0}) assert len(hist.buffer) == 5 - assert 'ls' == hist.buffer[-1]['inp'] - assert 0 == hist.buffer[-1]['rtn'] + assert "ls" == hist.buffer[-1]["inp"] + assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 - assert hist.inps[-1] == 'ls' + assert hist.inps[-1] == "ls" # Dup - hist.append({'inp': 'ls', 'rtn': 0}) + hist.append({"inp": "ls", "rtn": 0}) assert len(hist.buffer) == 6 assert hist.rtns[-1] == 0 - assert hist.inps[-1] == 'ls' + assert hist.inps[-1] == "ls" # Success - hist.append({'inp': '/bin/ls', 'rtn': 0}) + hist.append({"inp": "/bin/ls", "rtn": 0}) assert len(hist.buffer) == 7 - assert '/bin/ls' == hist.buffer[-1]['inp'] - assert 0 == hist.buffer[-1]['rtn'] + assert "/bin/ls" == hist.buffer[-1]["inp"] + assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 - assert hist.inps[-1] == '/bin/ls' + assert hist.inps[-1] == "/bin/ls" # Error - hist.append({'inp': 'ls bazz', 'rtn': 1}) + hist.append({"inp": "ls bazz", "rtn": 1}) assert len(hist.buffer) == 8 - assert 'ls bazz' == hist.buffer[-1]['inp'] - assert 1 == hist.buffer[-1]['rtn'] + assert "ls bazz" == hist.buffer[-1]["inp"] + assert 1 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 1 - assert hist.inps[-1] == 'ls bazz' + assert hist.inps[-1] == "ls bazz" # Error - hist.append({'inp': 'ls bazz', 'rtn': -1}) + hist.append({"inp": "ls bazz", "rtn": -1}) assert len(hist.buffer) == 9 - assert 'ls bazz' == hist.buffer[-1]['inp'] - assert -1 == hist.buffer[-1]['rtn'] + assert "ls bazz" == hist.buffer[-1]["inp"] + assert -1 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == -1 - assert hist.inps[-1] == 'ls bazz' + assert hist.inps[-1] == "ls bazz" -@pytest.mark.parametrize('args', [ '-h', '--help', 'show -h', 'show --help']) +@pytest.mark.parametrize("args", ["-h", "--help", "show -h", "show --help"]) def test_parse_args_help(args, capsys): with pytest.raises(SystemExit): args = _xh_parse_args(shlex.split(args)) - assert 'show this help message and exit' in capsys.readouterr()[0] + assert "show this help message and exit" in capsys.readouterr()[0] -@pytest.mark.parametrize('args, exp', [ - ('', ('show', 'session', [], False, False)), - ('1:5', ('show', 'session', ['1:5'], False, False)), - ('show', ('show', 'session', [], False, False)), - ('show 15', ('show', 'session', ['15'], False, False)), - ('show bash 3:5 15:66', ('show', 'bash', ['3:5', '15:66'], False, False)), - ('show -r', ('show', 'session', [], False, True)), - ('show -rn bash', ('show', 'bash', [], True, True)), - ('show -n -r -30:20', ('show', 'session', ['-30:20'], True, True)), - ('show -n zsh 1:2:3', ('show', 'zsh', ['1:2:3'], True, False)) - ]) +@pytest.mark.parametrize( + "args, exp", + [ + ("", ("show", "session", [], False, False)), + ("1:5", ("show", "session", ["1:5"], False, False)), + ("show", ("show", "session", [], False, False)), + ("show 15", ("show", "session", ["15"], False, False)), + ("show bash 3:5 15:66", ("show", "bash", ["3:5", "15:66"], False, False)), + ("show -r", ("show", "session", [], False, True)), + ("show -rn bash", ("show", "bash", [], True, True)), + ("show -n -r -30:20", ("show", "session", ["-30:20"], True, True)), + ("show -n zsh 1:2:3", ("show", "zsh", ["1:2:3"], True, False)), + ], +) def test_parser_show(args, exp): # use dict instead of argparse.Namespace for pretty pytest diff - exp_ns = {'action': exp[0], - 'session': exp[1], - 'slices': exp[2], - 'numerate': exp[3], - 'reverse': exp[4], - 'start_time': None, - 'end_time': None, - 'datetime_format': None, - 'timestamp': False, - 'null_byte': False} + exp_ns = { + "action": exp[0], + "session": exp[1], + "slices": exp[2], + "numerate": exp[3], + "reverse": exp[4], + "start_time": None, + "end_time": None, + "datetime_format": None, + "timestamp": False, + "null_byte": False, + } ns = _xh_parse_args(shlex.split(args)) assert ns.__dict__ == exp_ns -@pytest.mark.parametrize('index, exp', [ - (-1, ('grep from me', 'out', 0, (5, 6))), - (1, ('cat hello kitty', 'out', 0, (1, 2))), - (slice(1, 3), [('cat hello kitty', 'out', 0, (1, 2)), - ('abc', 'out', 0, (2, 3))]), -]) +@pytest.mark.parametrize( + "index, exp", + [ + (-1, ("grep from me", "out", 0, (5, 6))), + (1, ("cat hello kitty", "out", 0, (1, 2))), + ( + slice(1, 3), + [("cat hello kitty", "out", 0, (1, 2)), ("abc", "out", 0, (2, 3))], + ), + ], +) def test_history_getitem(index, exp, hist, xonsh_builtins): - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - attrs = ('inp', 'out', 'rtn', 'ts') + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + attrs = ("inp", "out", "rtn", "ts") - for ts,cmd in enumerate(CMDS): # populate the shell history - entry = {k: v for k, v in zip(attrs, [cmd, 'out', 0, (ts, ts+1)])} + for ts, cmd in enumerate(CMDS): # populate the shell history + entry = {k: v for k, v in zip(attrs, [cmd, "out", 0, (ts, ts + 1)])} hist.append(entry) entry = hist[index] @@ -279,15 +296,15 @@ def test_history_getitem(index, exp, hist, xonsh_builtins): def test_construct_history_str(xonsh_builtins): - xonsh_builtins.__xonsh_env__['XONSH_HISTORY_BACKEND'] = 'dummy' + xonsh_builtins.__xonsh_env__["XONSH_HISTORY_BACKEND"] = "dummy" assert isinstance(construct_history(), DummyHistory) def test_construct_history_class(xonsh_builtins): - xonsh_builtins.__xonsh_env__['XONSH_HISTORY_BACKEND'] = DummyHistory + xonsh_builtins.__xonsh_env__["XONSH_HISTORY_BACKEND"] = DummyHistory assert isinstance(construct_history(), DummyHistory) def test_construct_history_instance(xonsh_builtins): - xonsh_builtins.__xonsh_env__['XONSH_HISTORY_BACKEND'] = DummyHistory() + xonsh_builtins.__xonsh_env__["XONSH_HISTORY_BACKEND"] = DummyHistory() assert isinstance(construct_history(), DummyHistory) diff --git a/tests/test_history_sqlite.py b/tests/test_history_sqlite.py index a3e99858a..f79e11d81 100644 --- a/tests/test_history_sqlite.py +++ b/tests/test_history_sqlite.py @@ -12,42 +12,43 @@ import pytest @pytest.yield_fixture def hist(): - h = SqliteHistory(filename='xonsh-HISTORY-TEST.sqlite', - sessionid='SESSIONID', gc=False) + h = SqliteHistory( + filename="xonsh-HISTORY-TEST.sqlite", sessionid="SESSIONID", gc=False + ) yield h os.remove(h.filename) def test_hist_append(hist, xonsh_builtins): """Verify appending to the history works.""" - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - hf = hist.append({'inp': 'still alive', 'rtn': 1}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + hf = hist.append({"inp": "still alive", "rtn": 1}) assert hf is None items = list(hist.items()) assert len(items) == 1 - assert 'still alive' == items[0]['inp'] - assert 1 == items[0]['rtn'] - hist.append({'inp': 'still alive', 'rtn': 0}) + assert "still alive" == items[0]["inp"] + assert 1 == items[0]["rtn"] + hist.append({"inp": "still alive", "rtn": 0}) items = list(hist.items()) assert len(items) == 2 - assert 'still alive' == items[1]['inp'] - assert 0 == items[1]['rtn'] + assert "still alive" == items[1]["inp"] + assert 0 == items[1]["rtn"] assert list(hist.all_items()) == items def test_hist_attrs(hist, xonsh_builtins): - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - hf = hist.append({'inp': 'ls foo', 'rtn': 1}) + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + hf = hist.append({"inp": "ls foo", "rtn": 1}) assert hf is None - assert 'ls foo' == hist.inps[0] - assert 'ls foo' == hist.inps[-1] + assert "ls foo" == hist.inps[0] + assert "ls foo" == hist.inps[-1] assert 1 == hist.rtns[0] assert 1 == hist.rtns[-1] assert None is hist.outs[-1] assert [1] == hist.rtns[:] - hist.append({'inp': 'ls bar', 'rtn': 0}) - assert 'ls bar' == hist.inps[1] - assert 'ls bar' == hist.inps[-1] + hist.append({"inp": "ls bar", "rtn": 0}) + assert "ls bar" == hist.inps[1] + assert "ls bar" == hist.inps[-1] assert 0 == hist.rtns[1] assert 0 == hist.rtns[-1] assert None is hist.outs[-1] @@ -56,32 +57,37 @@ def test_hist_attrs(hist, xonsh_builtins): assert len(hist.tss[0]) == 2 -CMDS = ['ls', 'cat hello kitty', 'abc', 'def', 'touch me', 'grep from me'] +CMDS = ["ls", "cat hello kitty", "abc", "def", "touch me", "grep from me"] -@pytest.mark.parametrize('inp, commands, offset', [ - ('', CMDS, (0, 1)), - ('-r', list(reversed(CMDS)), (len(CMDS) - 1, -1)), - ('0', CMDS[0:1], (0, 1)), - ('1', CMDS[1:2], (1, 1)), - ('-2', CMDS[-2:-1], (len(CMDS) - 2, 1)), - ('1:3', CMDS[1:3], (1, 1)), - ('1::2', CMDS[1::2], (1, 2)), - ('-4:-2', CMDS[-4:-2], (len(CMDS) - 4, 1)) - ]) +@pytest.mark.parametrize( + "inp, commands, offset", + [ + ("", CMDS, (0, 1)), + ("-r", list(reversed(CMDS)), (len(CMDS) - 1, -1)), + ("0", CMDS[0:1], (0, 1)), + ("1", CMDS[1:2], (1, 1)), + ("-2", CMDS[-2:-1], (len(CMDS) - 2, 1)), + ("1:3", CMDS[1:3], (1, 1)), + ("1::2", CMDS[1::2], (1, 2)), + ("-4:-2", CMDS[-4:-2], (len(CMDS) - 4, 1)), + ], +) def test_show_cmd_numerate(inp, commands, offset, hist, xonsh_builtins, capsys): """Verify that CLI history commands work.""" base_idx, step = offset xonsh_builtins.__xonsh_history__ = hist - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history - hist.append({'inp': cmd, 'rtn': 0, 'ts': (ts + 1, ts + 1.5)}) + hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) - exp = ('{}: {}'.format(base_idx + idx * step, cmd) - for idx, cmd in enumerate(list(commands))) - exp = '\n'.join(exp) + exp = ( + "{}: {}".format(base_idx + idx * step, cmd) + for idx, cmd in enumerate(list(commands)) + ) + exp = "\n".join(exp) - history_main(['show', '-n'] + shlex.split(inp)) + history_main(["show", "-n"] + shlex.split(inp)) out, err = capsys.readouterr() assert out.rstrip() == exp @@ -89,93 +95,98 @@ def test_show_cmd_numerate(inp, commands, offset, hist, xonsh_builtins, capsys): def test_histcontrol(hist, xonsh_builtins): """Test HISTCONTROL=ignoredups,ignoreerr""" - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = 'ignoredups,ignoreerr' + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = "ignoredups,ignoreerr" assert len(hist) == 0 # An error, items() remains empty - hist.append({'inp': 'ls foo', 'rtn': 2}) + hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist) == 0 assert len(hist.inps) == 1 assert len(hist.rtns) == 1 assert 2 == hist.rtns[-1] # Success - hist.append({'inp': 'ls foobazz', 'rtn': 0}) + hist.append({"inp": "ls foobazz", "rtn": 0}) assert len(hist) == 1 assert len(hist.inps) == 2 assert len(hist.rtns) == 2 items = list(hist.items()) - assert 'ls foobazz' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "ls foobazz" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Error - hist.append({'inp': 'ls foo', 'rtn': 2}) + hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist) == 1 items = list(hist.items()) - assert 'ls foobazz' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "ls foobazz" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert 2 == hist.rtns[-1] # File now exists, success - hist.append({'inp': 'ls foo', 'rtn': 0}) + hist.append({"inp": "ls foo", "rtn": 0}) assert len(hist) == 2 items = list(hist.items()) - assert 'ls foo' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "ls foo" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Success - hist.append({'inp': 'ls', 'rtn': 0}) + hist.append({"inp": "ls", "rtn": 0}) assert len(hist) == 3 items = list(hist.items()) - assert 'ls' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "ls" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Dup - hist.append({'inp': 'ls', 'rtn': 0}) + hist.append({"inp": "ls", "rtn": 0}) assert len(hist) == 3 # Success - hist.append({'inp': '/bin/ls', 'rtn': 0}) + hist.append({"inp": "/bin/ls", "rtn": 0}) assert len(hist) == 4 items = list(hist.items()) - assert '/bin/ls' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "/bin/ls" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Error - hist.append({'inp': 'ls bazz', 'rtn': 1}) + hist.append({"inp": "ls bazz", "rtn": 1}) assert len(hist) == 4 items = list(hist.items()) - assert '/bin/ls' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] - assert 'ls bazz' == hist.inps[-1] + assert "/bin/ls" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] + assert "ls bazz" == hist.inps[-1] assert 1 == hist.rtns[-1] # Error - hist.append({'inp': 'ls bazz', 'rtn': -1}) + hist.append({"inp": "ls bazz", "rtn": -1}) assert len(hist) == 4 items = list(hist.items()) - assert '/bin/ls' == items[-1]['inp'] - assert 0 == items[-1]['rtn'] + assert "/bin/ls" == items[-1]["inp"] + assert 0 == items[-1]["rtn"] assert -1 == hist.rtns[-1] -@pytest.mark.parametrize('index, exp', [ - (-1, ('grep from me', 'out', 0, (5, 6))), - (1, ('cat hello kitty', 'out', 0, (1, 2))), - (slice(1, 3), [('cat hello kitty', 'out', 0, (1, 2)), - ('abc', 'out', 0, (2, 3))]), -]) +@pytest.mark.parametrize( + "index, exp", + [ + (-1, ("grep from me", "out", 0, (5, 6))), + (1, ("cat hello kitty", "out", 0, (1, 2))), + ( + slice(1, 3), + [("cat hello kitty", "out", 0, (1, 2)), ("abc", "out", 0, (2, 3))], + ), + ], +) def test_history_getitem(index, exp, hist, xonsh_builtins): - xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() - xonsh_builtins.__xonsh_env__['XONSH_STORE_STDOUT'] = True - attrs = ('inp', 'out', 'rtn', 'ts') + xonsh_builtins.__xonsh_env__["HISTCONTROL"] = set() + xonsh_builtins.__xonsh_env__["XONSH_STORE_STDOUT"] = True + attrs = ("inp", "out", "rtn", "ts") for ts, cmd in enumerate(CMDS): # populate the shell history - entry = {k: v for k, v in zip(attrs, [cmd, 'out', 0, (ts, ts + 1)])} + entry = {k: v for k, v in zip(attrs, [cmd, "out", 0, (ts, ts + 1)])} hist.append(entry) entry = hist[index] diff --git a/tests/test_imphooks.py b/tests/test_imphooks.py index ed4811512..843db1aff 100644 --- a/tests/test_imphooks.py +++ b/tests/test_imphooks.py @@ -16,30 +16,34 @@ imphooks.install_import_hooks() @pytest.yield_fixture(autouse=True) def imp_env(): execer = Execer(unload=False) - builtins.__xonsh_env__ = Env({'PATH': [], 'PATHEXT': []}) + builtins.__xonsh_env__ = Env({"PATH": [], "PATHEXT": []}) yield unload_builtins() def test_import(): import sample - assert ('hello mom jawaka\n' == sample.x) + + assert "hello mom jawaka\n" == sample.x def test_absolute_import(): from xpack import sample - assert ('hello mom jawaka\n' == sample.x) + + assert "hello mom jawaka\n" == sample.x def test_relative_import(): from xpack import relimp - assert ('hello mom jawaka\n' == relimp.sample.x) - assert ('hello mom jawaka\ndark chest of wonders' == relimp.y) + + assert "hello mom jawaka\n" == relimp.sample.x + assert "hello mom jawaka\ndark chest of wonders" == relimp.y def test_sub_import(): from xpack.sub import sample - assert ('hello mom jawaka\n' == sample.x) + + assert "hello mom jawaka\n" == sample.x TEST_DIR = os.path.dirname(__file__) @@ -47,11 +51,13 @@ TEST_DIR = os.path.dirname(__file__) def test_module_dunder_file_attribute(): import sample - exp = os.path.join(TEST_DIR, 'sample.xsh') + + exp = os.path.join(TEST_DIR, "sample.xsh") assert os.path.abspath(sample.__file__) == exp def test_module_dunder_file_attribute_sub(): from xpack.sub import sample - exp = os.path.join(TEST_DIR, 'xpack', 'sub', 'sample.xsh') + + exp = os.path.join(TEST_DIR, "xpack", "sub", "sample.xsh") assert os.path.abspath(sample.__file__) == exp diff --git a/tests/test_integrations.py b/tests/test_integrations.py index 88308b686..39ed0a3f8 100644 --- a/tests/test_integrations.py +++ b/tests/test_integrations.py @@ -8,12 +8,18 @@ import pytest import xonsh from xonsh.platform import ON_WINDOWS -from tools import (skip_if_on_windows, skip_if_on_darwin, skip_if_on_travis, - ON_WINDOWS, ON_DARWIN, ON_TRAVIS) +from tools import ( + skip_if_on_windows, + skip_if_on_darwin, + skip_if_on_travis, + ON_WINDOWS, + ON_DARWIN, + ON_TRAVIS, +) XONSH_PREFIX = xonsh.__file__ -if 'site-packages' in XONSH_PREFIX: +if "site-packages" in XONSH_PREFIX: # must be installed version of xonsh num_up = 5 else: @@ -21,34 +27,43 @@ else: num_up = 2 for i in range(num_up): XONSH_PREFIX = os.path.dirname(XONSH_PREFIX) -PATH = os.path.join(os.path.dirname(__file__), 'bin') + os.pathsep + \ - os.path.join(XONSH_PREFIX, 'bin') + os.pathsep + \ - os.path.join(XONSH_PREFIX, 'Scripts') + os.pathsep + \ - os.path.join(XONSH_PREFIX, 'scripts') + os.pathsep + \ - os.path.dirname(sys.executable) + os.pathsep + \ - os.environ['PATH'] +PATH = ( + os.path.join(os.path.dirname(__file__), "bin") + + os.pathsep + + os.path.join(XONSH_PREFIX, "bin") + + os.pathsep + + os.path.join(XONSH_PREFIX, "Scripts") + + os.pathsep + + os.path.join(XONSH_PREFIX, "scripts") + + os.pathsep + + os.path.dirname(sys.executable) + + os.pathsep + + os.environ["PATH"] +) -skip_if_no_xonsh = pytest.mark.skipif(shutil.which('xonsh', path=PATH) is None, - reason='xonsh not on path') +skip_if_no_xonsh = pytest.mark.skipif( + shutil.which("xonsh", path=PATH) is None, reason="xonsh not on path" +) def run_xonsh(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT): env = dict(os.environ) - env['PATH'] = PATH - env['XONSH_DEBUG'] = '1' - env['XONSH_SHOW_TRACEBACK'] = '1' - env['RAISE_SUBPROC_ERROR'] = '1' - env['PROMPT'] = '' - xonsh = 'xonsh.bat' if ON_WINDOWS else 'xon.sh' + env["PATH"] = PATH + env["XONSH_DEBUG"] = "1" + env["XONSH_SHOW_TRACEBACK"] = "1" + env["RAISE_SUBPROC_ERROR"] = "1" + env["PROMPT"] = "" + xonsh = "xonsh.bat" if ON_WINDOWS else "xon.sh" xonsh = shutil.which(xonsh, path=PATH) - proc = sp.Popen([xonsh, '--no-rc'], - env=env, - stdin=stdin, - stdout=stdout, - stderr=stderr, - universal_newlines=True, - ) + proc = sp.Popen( + [xonsh, "--no-rc"], + env=env, + stdin=stdin, + stdout=stdout, + stderr=stderr, + universal_newlines=True, + ) try: out, err = proc.communicate(input=cmd, timeout=10) except sp.TimeoutExpired: @@ -75,16 +90,21 @@ def check_run_xonsh(cmd, fmt, exp): # ALL_PLATFORMS = [ -# test calling a function alias -(""" + # test calling a function alias + ( + """ def _f(): print('hello') aliases['f'] = _f f -""", "hello\n", 0), -# test redirecting a function alias to a file -(""" +""", + "hello\n", + 0, + ), + # test redirecting a function alias to a file + ( + """ def _f(): print('Wow Mom!') @@ -94,27 +114,39 @@ f > tttt with open('tttt') as tttt: s = tttt.read().strip() print('REDIRECTED OUTPUT: ' + s) -""", "REDIRECTED OUTPUT: Wow Mom!\n", 0), -# test redirecting a function alias from stderr -> stdout -(""" +""", + "REDIRECTED OUTPUT: Wow Mom!\n", + 0, + ), + # test redirecting a function alias from stderr -> stdout + ( + """ def _f(args, stdin, stdout, stderr): print('The Truth is Out There', file=stderr) aliases['f'] = _f f e>o -""", "The Truth is Out There\n", 0), -# test system exit in function alias -(""" +""", + "The Truth is Out There\n", + 0, + ), + # test system exit in function alias + ( + """ import sys def _f(): sys.exit(42) aliases['f'] = _f print(![f].returncode) -""", "42\n", 0), -# test uncaptured streaming alias, -# order actually printed in is non-deterministic -(""" +""", + "42\n", + 0, + ), + # test uncaptured streaming alias, + # order actually printed in is non-deterministic + ( + """ def _test_stream(args, stdin, stdout, stderr): print('hallo on stream', file=stderr) print('hallo on stream', file=stdout) @@ -123,9 +155,13 @@ def _test_stream(args, stdin, stdout, stderr): aliases['test-stream'] = _test_stream x = ![test-stream] print(x.returncode) -""", "hallo on stream\nhallo on stream\n1\n", 0), -# test captured streaming alias -(""" +""", + "hallo on stream\nhallo on stream\n1\n", + 0, + ), + # test captured streaming alias + ( + """ def _test_stream(args, stdin, stdout, stderr): print('hallo on err', file=stderr) print('hallo on out', file=stdout) @@ -134,9 +170,13 @@ def _test_stream(args, stdin, stdout, stderr): aliases['test-stream'] = _test_stream x = !(test-stream) print(x.returncode) -""", "hallo on err\n1\n", 0), -# test piping aliases -(""" +""", + "hallo on err\n1\n", + 0, + ), + # test piping aliases + ( + """ def dummy(args, inn, out, err): out.write('hey!') return 0 @@ -149,32 +189,48 @@ def dummy2(args, inn, out, err): aliases['d'] = dummy aliases['d2'] = dummy2 d | d2 -""", "HEY!", 0), -# test output larger than most pipe buffers -(""" +""", + "HEY!", + 0, + ), + # test output larger than most pipe buffers + ( + """ def _g(args, stdin=None): for i in range(1000): print('x' * 100) aliases['g'] = _g g -""", (("x"*100) + '\n') * 1000, 0), -# test piping 'real' command -(""" +""", + (("x" * 100) + "\n") * 1000, + 0, + ), + # test piping 'real' command + ( + """ with open('tttt', 'w') as fp: fp.write("Wow mom!\\n") ![cat tttt | wc] -""", ' 1 2 10\n' if ON_WINDOWS else " 1 2 9 \n", 0), -# test double piping 'real' command -(""" +""", + " 1 2 10\n" if ON_WINDOWS else " 1 2 9 \n", + 0, + ), + # test double piping 'real' command + ( + """ with open('tttt', 'w') as fp: fp.write("Wow mom!\\n") ![cat tttt | wc | wc] -""", ' 1 3 24\n' if ON_WINDOWS else " 1 4 16 \n", 0), -# test unthreadable alias (which should trigger a ProcPoxy call) -(""" +""", + " 1 3 24\n" if ON_WINDOWS else " 1 4 16 \n", + 0, + ), + # test unthreadable alias (which should trigger a ProcPoxy call) + ( + """ from xonsh.tools import unthreadable @unthreadable @@ -183,9 +239,13 @@ def _f(): aliases['f'] = _f f -""", "hello\n", 0), -# test ambiguous globs -(""" +""", + "hello\n", + 0, + ), + # test ambiguous globs + ( + """ import os def _echo(args): @@ -208,42 +268,56 @@ echo *_test.tst and echo *.tst for f in files: os.remove(f) """, -'Actually.tst Actually_test.tst Complete.tst Complete_test.tst\n' -'Actually_test.tst Complete_test.tst\n' -'Actually_test.tst Complete_test.tst\n' -'Actually_test.tst Complete_test.tst\n' -'Actually.tst Actually_test.tst Complete.tst Complete_test.tst\n', -0), -# -# test ambiguous line continuations -# -(""" + "Actually.tst Actually_test.tst Complete.tst Complete_test.tst\n" + "Actually_test.tst Complete_test.tst\n" + "Actually_test.tst Complete_test.tst\n" + "Actually_test.tst Complete_test.tst\n" + "Actually.tst Actually_test.tst Complete.tst Complete_test.tst\n", + 0, + ), + # + # test ambiguous line continuations + # + ( + """ def _echo(args): print(' '.join(args)) aliases['echo'] = _echo echo --option1 \ --option2 -""", '--option1 --option2\n', 0), -# -# test @$() with aliases -# -(""" +""", + "--option1 --option2\n", + 0, + ), + # + # test @$() with aliases + # + ( + """ aliases['ls'] = 'spam spam sausage spam' echo @$(which ls) -""", 'spam spam sausage spam\n', 0), -# -# test redirection -# -(""" +""", + "spam spam sausage spam\n", + 0, + ), + # + # test redirection + # + ( + """ echo Just the place for a snark. >tttt cat tttt -""", 'Just the place for a snark.\n', 0), -# -# Test completion registration and subproc stack -# -(""" +""", + "Just the place for a snark.\n", + 0, + ), + # + # Test completion registration and subproc stack + # + ( + """ def _f(): def j(): pass @@ -260,12 +334,14 @@ def _f(): _f() del _f -""" -, '', 0), +""", + "", + 0, + ), ] -@pytest.mark.parametrize('case', ALL_PLATFORMS) +@pytest.mark.parametrize("case", ALL_PLATFORMS) def test_script(case): script, exp_out, exp_rtn = case out, err, rtn = run_xonsh(script) @@ -274,99 +350,121 @@ def test_script(case): ALL_PLATFORMS_STDERR = [ -# test redirecting a function alias -(""" + # test redirecting a function alias + ( + """ def _f(args, stdin, stdout): print('Wow Mom!', file=stdout) aliases['f'] = _f f o>e -""", "Wow Mom!\n", 0), +""", + "Wow Mom!\n", + 0, + ) ] -@pytest.mark.parametrize('case', ALL_PLATFORMS_STDERR) + +@pytest.mark.parametrize("case", ALL_PLATFORMS_STDERR) def test_script_stderr(case): script, exp_err, exp_rtn = case out, err, rtn = run_xonsh(script, stderr=sp.PIPE) assert exp_err == err assert exp_rtn == rtn + @skip_if_on_windows -@pytest.mark.parametrize('cmd, fmt, exp', [ - ('pwd', None, lambda: os.getcwd() + '\n'), - ('echo WORKING', None, 'WORKING\n'), - ('ls -f', lambda out: out.splitlines().sort(), os.listdir().sort()), - ]) +@pytest.mark.parametrize( + "cmd, fmt, exp", + [ + ("pwd", None, lambda: os.getcwd() + "\n"), + ("echo WORKING", None, "WORKING\n"), + ("ls -f", lambda out: out.splitlines().sort(), os.listdir().sort()), + ], +) def test_single_command_no_windows(cmd, fmt, exp): check_run_xonsh(cmd, fmt, exp) def test_eof_syntax_error(): """Ensures syntax errors for EOF appear on last line.""" - script = 'x = 1\na = (1, 0\n' + script = "x = 1\na = (1, 0\n" out, err, rtn = run_xonsh(script, stderr=sp.PIPE) - assert ':0:0: EOF in multi-line statement' not in err - assert ':2:0: EOF in multi-line statement' in err + assert ":0:0: EOF in multi-line statement" not in err + assert ":2:0: EOF in multi-line statement" in err def test_open_quote_syntax_error(): - script = ('#!/usr/bin/env xonsh\n\n' - 'echo "This is line 3"\n' - 'print ("This is line 4")\n' - 'x = "This is a string where I forget the closing quote on line 5\n' - 'echo "This is line 6"\n') + script = ( + "#!/usr/bin/env xonsh\n\n" + 'echo "This is line 3"\n' + 'print ("This is line 4")\n' + 'x = "This is a string where I forget the closing quote on line 5\n' + 'echo "This is line 6"\n' + ) out, err, rtn = run_xonsh(script, stderr=sp.PIPE) assert """:3:5: ('code: "This is line 3"',)""" not in err assert ':5:4: "' in err - assert 'SyntaxError:' in err + assert "SyntaxError:" in err -_bad_case = pytest.mark.skipif(ON_DARWIN or ON_WINDOWS or ON_TRAVIS, - reason="bad platforms") +_bad_case = pytest.mark.skipif( + ON_DARWIN or ON_WINDOWS or ON_TRAVIS, reason="bad platforms" +) + @_bad_case def test_printfile(): - check_run_xonsh('printfile.xsh', None, 'printfile.xsh\n') + check_run_xonsh("printfile.xsh", None, "printfile.xsh\n") @_bad_case def test_printname(): - check_run_xonsh('printfile.xsh', None, 'printfile.xsh\n') + check_run_xonsh("printfile.xsh", None, "printfile.xsh\n") @_bad_case def test_sourcefile(): - check_run_xonsh('printfile.xsh', None, 'printfile.xsh\n') + check_run_xonsh("printfile.xsh", None, "printfile.xsh\n") @_bad_case -@pytest.mark.parametrize('cmd, fmt, exp', [ - # test subshell wrapping - (""" +@pytest.mark.parametrize( + "cmd, fmt, exp", + [ + # test subshell wrapping + ( + """ with open('tttt', 'w') as fp: fp.write("Wow mom!\\n") (wc) < tttt -""", None, " 1 2 9 \n"), - # test subshell statement wrapping - (""" +""", + None, + " 1 2 9 \n", + ), + # test subshell statement wrapping + ( + """ with open('tttt', 'w') as fp: fp.write("Wow mom!\\n") (wc;) < tttt -""", None, " 1 2 9 \n"), -]) +""", + None, + " 1 2 9 \n", + ), + ], +) def test_subshells(cmd, fmt, exp): check_run_xonsh(cmd, fmt, exp) @skip_if_on_windows -@pytest.mark.parametrize('cmd, exp', [ - ('pwd', lambda: os.getcwd() + '\n'), - ]) +@pytest.mark.parametrize("cmd, exp", [("pwd", lambda: os.getcwd() + "\n")]) def test_redirect_out_to_file(cmd, exp, tmpdir): - outfile = tmpdir.mkdir('xonsh_test_dir').join('xonsh_test_file') - command = '{} > {}\n'.format(cmd, outfile) + outfile = tmpdir.mkdir("xonsh_test_dir").join("xonsh_test_file") + command = "{} > {}\n".format(cmd, outfile) out, _, _ = run_xonsh(command) content = outfile.read() if callable(exp): diff --git a/tests/test_jsonutils.py b/tests/test_jsonutils.py index f1a8852f7..338920d28 100644 --- a/tests/test_jsonutils.py +++ b/tests/test_jsonutils.py @@ -8,14 +8,19 @@ from xonsh.tools import EnvPath from xonsh.jsonutils import serialize_xonsh_json - -@pytest.mark.parametrize('inp', [ - 42, "yo", ["hello"], {"x": 65}, - EnvPath(["wakka", "jawaka"]), - ["y", EnvPath(["wakka", "jawaka"])], - {"z": EnvPath(["wakka", "jawaka"])}, -]) +@pytest.mark.parametrize( + "inp", + [ + 42, + "yo", + ["hello"], + {"x": 65}, + EnvPath(["wakka", "jawaka"]), + ["y", EnvPath(["wakka", "jawaka"])], + {"z": EnvPath(["wakka", "jawaka"])}, + ], +) def test_serialize_xonsh_json_roundtrip(inp): s = json.dumps(inp, default=serialize_xonsh_json) obs = json.loads(s) - assert inp == obs \ No newline at end of file + assert inp == obs diff --git a/tests/test_lazyasd.py b/tests/test_lazyasd.py index d8105c4fe..8720fb243 100644 --- a/tests/test_lazyasd.py +++ b/tests/test_lazyasd.py @@ -5,7 +5,7 @@ from xonsh.lazyasd import LazyObject # LazyObject Tests # -def test_lazyobject_getitem(): - lo = LazyObject(lambda: {'x': 1}, {}, 'lo') - assert 1 == lo['x'] +def test_lazyobject_getitem(): + lo = LazyObject(lambda: {"x": 1}, {}, "lo") + assert 1 == lo["x"] diff --git a/tests/test_lazyjson.py b/tests/test_lazyjson.py index 78664b62d..ef9e21cc4 100644 --- a/tests/test_lazyjson.py +++ b/tests/test_lazyjson.py @@ -5,65 +5,78 @@ from io import StringIO from xonsh.lazyjson import index, ljdump, LazyJSON, LJNode + def test_index_int(): - exp = {'offsets': 0, 'sizes': 2} + exp = {"offsets": 0, "sizes": 2} s, obs = index(42) assert exp == obs + def test_index_str(): - exp = {'offsets': 0, 'sizes': 7} - s, obs = index('wakka') + exp = {"offsets": 0, "sizes": 7} + s, obs = index("wakka") assert exp == obs + def test_index_list_ints(): - exp = {'offsets': [1, 4, 0], 'sizes': [1, 2, 8]} + exp = {"offsets": [1, 4, 0], "sizes": [1, 2, 8]} s, obs = index([1, 42]) assert exp == obs + def test_index_list_str(): - exp = {'offsets': [1, 10, 0], 'sizes': [7, 8, 20]} - s, obs = index(['wakka', 'jawaka']) + exp = {"offsets": [1, 10, 0], "sizes": [7, 8, 20]} + s, obs = index(["wakka", "jawaka"]) assert exp == obs + def test_index_list_str_int(): - exp = {'offsets': [1, 10, 0], 'sizes': [7, 2, 14]} - s, obs = index(['wakka', 42]) + exp = {"offsets": [1, 10, 0], "sizes": [7, 2, 14]} + s, obs = index(["wakka", 42]) assert exp == obs + def test_index_list_int_str(): - exp = {'offsets': [1, 5, 14, 0], 'sizes': [2, 7, 8, 24]} - s, obs = index([42, 'wakka', 'jawaka']) + exp = {"offsets": [1, 5, 14, 0], "sizes": [2, 7, 8, 24]} + s, obs = index([42, "wakka", "jawaka"]) assert exp == obs + def test_index_dict_int(): - exp = {'offsets': {'wakka': 10, '__total__': 0}, - 'sizes': {'wakka': 2, '__total__': 14}} - s, obs = index({'wakka': 42}) + exp = { + "offsets": {"wakka": 10, "__total__": 0}, + "sizes": {"wakka": 2, "__total__": 14}, + } + s, obs = index({"wakka": 42}) assert exp == obs + def test_index_dict_str(): - exp = {'offsets': {'wakka': 10, '__total__': 0}, - 'sizes': {'wakka': 8, '__total__': 20}} - s, obs = index({'wakka': 'jawaka'}) + exp = { + "offsets": {"wakka": 10, "__total__": 0}, + "sizes": {"wakka": 8, "__total__": 20}, + } + s, obs = index({"wakka": "jawaka"}) assert exp == obs + def test_index_dict_dict_int(): - exp = {'offsets': {'wakka': {'jawaka': 21, '__total__': 10}, - '__total__': 0, - }, - 'sizes': {'wakka': {'jawaka': 2, '__total__': 15}, - '__total__': 27} - } - s, obs = index({'wakka': {'jawaka': 42}}) + exp = { + "offsets": {"wakka": {"jawaka": 21, "__total__": 10}, "__total__": 0}, + "sizes": {"wakka": {"jawaka": 2, "__total__": 15}, "__total__": 27}, + } + s, obs = index({"wakka": {"jawaka": 42}}) assert exp == obs + def test_lazy_load_index(): f = StringIO() - ljdump({'wakka': 42}, f) + ljdump({"wakka": 42}, f) f.seek(0) lj = LazyJSON(f) - assert {'wakka': 10, '__total__': 0} == lj.offsets - assert {'wakka': 2, '__total__': 14} == lj.sizes + assert {"wakka": 10, "__total__": 0} == lj.offsets + assert {"wakka": 2, "__total__": 14} == lj.sizes + def test_lazy_int(): f = StringIO() @@ -72,12 +85,14 @@ def test_lazy_int(): lj = LazyJSON(f) assert 42 == lj.load() + def test_lazy_str(): f = StringIO() - ljdump('wakka', f) + ljdump("wakka", f) f.seek(0) lj = LazyJSON(f) - assert 'wakka' == lj.load() + assert "wakka" == lj.load() + def test_lazy_list_empty(): x = [] @@ -88,6 +103,7 @@ def test_lazy_list_empty(): assert 0 == len(lj) assert x == lj.load() + def test_lazy_list_ints(): x = [0, 1, 6, 28, 496, 8128] f = StringIO() @@ -99,17 +115,19 @@ def test_lazy_list_ints(): assert x == [_ for _ in lj] assert x == lj.load() + def test_lazy_list_str(): - x = ['I', 'have', 'seen', 'the', 'wind', 'blow'] + x = ["I", "have", "seen", "the", "wind", "blow"] f = StringIO() ljdump(x, f) f.seek(0) lj = LazyJSON(f) - assert 'the' == lj[3] + assert "the" == lj[3] assert x[:2:-2] == lj[:2:-2] assert x == [_ for _ in lj] assert x == lj.load() + def test_lazy_list_list_ints(): x = [[0, 1], [6, 28], [496, 8128]] f = StringIO() @@ -121,6 +139,7 @@ def test_lazy_list_list_ints(): assert [6 == 28], lj[1].load() assert x == lj.load() + def test_lazy_dict_empty(): x = {} f = StringIO() @@ -130,24 +149,26 @@ def test_lazy_dict_empty(): assert 0 == len(lj) assert x == lj.load() + def test_lazy_dict(): f = StringIO() - ljdump({'wakka': 42}, f) + ljdump({"wakka": 42}, f) f.seek(0) lj = LazyJSON(f) - assert ['wakka'] == list(lj.keys()) - assert 42 == lj['wakka'] + assert ["wakka"] == list(lj.keys()) + assert 42 == lj["wakka"] assert 1 == len(lj) - assert {'wakka': 42} == lj.load() + assert {"wakka": 42} == lj.load() + def test_lazy_dict_dict_int(): - x = {'wakka': {'jawaka': 42}} + x = {"wakka": {"jawaka": 42}} f = StringIO() ljdump(x, f) f.seek(0) lj = LazyJSON(f) - assert ['wakka'] == list(lj.keys()) - assert isinstance(lj['wakka'], LJNode) - assert 42 == lj['wakka']['jawaka'] + assert ["wakka"] == list(lj.keys()) + assert isinstance(lj["wakka"], LJNode) + assert 42 == lj["wakka"]["jawaka"] assert 1 == len(lj) assert x == lj.load() diff --git a/tests/test_lexer.py b/tests/test_lexer.py index 84fbafdef..d2948e247 100644 --- a/tests/test_lexer.py +++ b/tests/test_lexer.py @@ -4,7 +4,8 @@ from __future__ import unicode_literals, print_function import os import sys from collections import Sequence -sys.path.insert(0, os.path.abspath('..')) # FIXME + +sys.path.insert(0, os.path.abspath("..")) # FIXME from pprint import pformat import pytest @@ -17,19 +18,20 @@ except ImportError: from xonsh.lexer import Lexer -LEXER_ARGS = {'lextab': 'lexer_test_table', 'debug': 0} +LEXER_ARGS = {"lextab": "lexer_test_table", "debug": 0} + def ensure_tuple(x): if isinstance(x, LexToken): # line numbers can no longer be solely determined from the lexer - #x = (x.type, x.value, x.lineno, x.lexpos) + # x = (x.type, x.value, x.lineno, x.lexpos) x = (x.type, x.value, x.lexpos) elif isinstance(x, tuple): pass elif isinstance(x, Sequence): x = tuple(x) else: - raise TypeError('{0} is not a sequence'.format(x)) + raise TypeError("{0} is not a sequence".format(x)) return x @@ -43,7 +45,7 @@ def tokens_equal(x, y): def assert_token_equal(x, y): """Asserts that two tokens are equal.""" if not tokens_equal(x, y): - msg = 'The tokens differ: {0!r} != {1!r}'.format(x, y) + msg = "The tokens differ: {0!r} != {1!r}".format(x, y) pytest.fail(msg) return True @@ -51,15 +53,15 @@ def assert_token_equal(x, y): def assert_tokens_equal(x, y): """Asserts that two token sequences are equal.""" if len(x) != len(y): - msg = 'The tokens sequences have different lengths: {0!r} != {1!r}\n' - msg += '# x\n{2}\n\n# y\n{3}' + msg = "The tokens sequences have different lengths: {0!r} != {1!r}\n" + msg += "# x\n{2}\n\n# y\n{3}" pytest.fail(msg.format(len(x), len(y), pformat(x), pformat(y))) diffs = [(a, b) for a, b in zip(x, y) if not tokens_equal(a, b)] if len(diffs) > 0: - msg = ['The token sequences differ: '] + msg = ["The token sequences differ: "] for a, b in diffs: - msg += ['', '- ' + repr(a), '+ ' + repr(b)] - msg = '\n'.join(msg) + msg += ["", "- " + repr(a), "+ " + repr(b)] + msg = "\n".join(msg) pytest.fail(msg) return True @@ -69,8 +71,8 @@ def check_token(inp, exp): l.input(inp) obs = list(l) if len(obs) != 1: - msg = 'The observed sequence does not have length-1: {0!r} != 1\n' - msg += '# obs\n{1}' + msg = "The observed sequence does not have length-1: {0!r} != 1\n" + msg += "# obs\n{1}" pytest.fail(msg.format(len(obs), pformat(obs))) return assert_token_equal(exp, obs[0]) @@ -84,347 +86,365 @@ def check_tokens(inp, exp): def check_tokens_subproc(inp, exp, stop=-1): l = Lexer() - l.input('$[{}]'.format(inp)) + l.input("$[{}]".format(inp)) obs = list(l)[1:stop] return assert_tokens_equal(exp, obs) def test_int_literal(): - assert check_token('42', ['NUMBER', '42', 0]) - assert check_token('4_2', ['NUMBER', '4_2', 0]) + assert check_token("42", ["NUMBER", "42", 0]) + assert check_token("4_2", ["NUMBER", "4_2", 0]) def test_hex_literal(): - assert check_token('0x42', ['NUMBER', '0x42', 0]) - assert check_token('0x4_2', ['NUMBER', '0x4_2', 0]) + assert check_token("0x42", ["NUMBER", "0x42", 0]) + assert check_token("0x4_2", ["NUMBER", "0x4_2", 0]) def test_oct_o_literal(): - assert check_token('0o42', ['NUMBER', '0o42', 0]) - assert check_token('0o4_2', ['NUMBER', '0o4_2', 0]) + assert check_token("0o42", ["NUMBER", "0o42", 0]) + assert check_token("0o4_2", ["NUMBER", "0o4_2", 0]) def test_bin_literal(): - assert check_token('0b101010', ['NUMBER', '0b101010', 0]) - assert check_token('0b10_10_10', ['NUMBER', '0b10_10_10', 0]) + assert check_token("0b101010", ["NUMBER", "0b101010", 0]) + assert check_token("0b10_10_10", ["NUMBER", "0b10_10_10", 0]) def test_indent(): - exp = [('INDENT', ' \t ', 0), - ('NUMBER', '42', 5), - ('DEDENT', '', 0)] - assert check_tokens(' \t 42', exp) + exp = [("INDENT", " \t ", 0), ("NUMBER", "42", 5), ("DEDENT", "", 0)] + assert check_tokens(" \t 42", exp) def test_post_whitespace(): - inp = '42 \t ' - exp = [('NUMBER', '42', 0)] + inp = "42 \t " + exp = [("NUMBER", "42", 0)] assert check_tokens(inp, exp) def test_internal_whitespace(): - inp = '42 +\t65' - exp = [('NUMBER', '42', 0), - ('PLUS', '+', 4), - ('NUMBER', '65', 6),] + inp = "42 +\t65" + exp = [("NUMBER", "42", 0), ("PLUS", "+", 4), ("NUMBER", "65", 6)] assert check_tokens(inp, exp) def test_indent_internal_whitespace(): - inp = ' 42 +\t65' - exp = [('INDENT', ' ', 0), - ('NUMBER', '42', 1), - ('PLUS', '+', 5), - ('NUMBER', '65', 7), - ('DEDENT', '', 0)] + inp = " 42 +\t65" + exp = [ + ("INDENT", " ", 0), + ("NUMBER", "42", 1), + ("PLUS", "+", 5), + ("NUMBER", "65", 7), + ("DEDENT", "", 0), + ] assert check_tokens(inp, exp) def test_assignment(): - inp = 'x = 42' - exp = [('NAME', 'x', 0), - ('EQUALS', '=', 2), - ('NUMBER', '42', 4),] + inp = "x = 42" + exp = [("NAME", "x", 0), ("EQUALS", "=", 2), ("NUMBER", "42", 4)] assert check_tokens(inp, exp) def test_multiline(): - inp = 'x\ny' - exp = [('NAME', 'x', 0), - ('NEWLINE', '\n', 1), - ('NAME', 'y', 0),] + inp = "x\ny" + exp = [("NAME", "x", 0), ("NEWLINE", "\n", 1), ("NAME", "y", 0)] assert check_tokens(inp, exp) + def test_atdollar_expression(): - inp = '@$(which python)' - exp = [('ATDOLLAR_LPAREN', '@$(', 0), - ('NAME', 'which', 3), - ('WS', ' ', 8), - ('NAME', 'python', 9), - ('RPAREN', ')', 15)] + inp = "@$(which python)" + exp = [ + ("ATDOLLAR_LPAREN", "@$(", 0), + ("NAME", "which", 3), + ("WS", " ", 8), + ("NAME", "python", 9), + ("RPAREN", ")", 15), + ] assert check_tokens(inp, exp) def test_and(): - assert check_token('and', ['AND', 'and', 0]) + assert check_token("and", ["AND", "and", 0]) def test_ampersand(): - assert check_token('&', ['AMPERSAND', '&', 0]) + assert check_token("&", ["AMPERSAND", "&", 0]) def test_not_really_and_pre(): inp = "![foo-and]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'foo', 2), - ('MINUS', '-', 5), - ('NAME', 'and', 6), - ('RBRACKET', ']', 9), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "foo", 2), + ("MINUS", "-", 5), + ("NAME", "and", 6), + ("RBRACKET", "]", 9), + ] assert check_tokens(inp, exp) def test_not_really_and_post(): inp = "![and-bar]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'and', 2), - ('MINUS', '-', 5), - ('NAME', 'bar', 6), - ('RBRACKET', ']', 9), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "and", 2), + ("MINUS", "-", 5), + ("NAME", "bar", 6), + ("RBRACKET", "]", 9), + ] assert check_tokens(inp, exp) def test_not_really_and_pre_post(): inp = "![foo-and-bar]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'foo', 2), - ('MINUS', '-', 5), - ('NAME', 'and', 6), - ('MINUS', '-', 9), - ('NAME', 'bar', 10), - ('RBRACKET', ']', 13), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "foo", 2), + ("MINUS", "-", 5), + ("NAME", "and", 6), + ("MINUS", "-", 9), + ("NAME", "bar", 10), + ("RBRACKET", "]", 13), + ] assert check_tokens(inp, exp) def test_not_really_or_pre(): inp = "![foo-or]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'foo', 2), - ('MINUS', '-', 5), - ('NAME', 'or', 6), - ('RBRACKET', ']', 8), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "foo", 2), + ("MINUS", "-", 5), + ("NAME", "or", 6), + ("RBRACKET", "]", 8), + ] assert check_tokens(inp, exp) def test_not_really_or_post(): inp = "![or-bar]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'or', 2), - ('MINUS', '-', 4), - ('NAME', 'bar', 5), - ('RBRACKET', ']', 8), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "or", 2), + ("MINUS", "-", 4), + ("NAME", "bar", 5), + ("RBRACKET", "]", 8), + ] assert check_tokens(inp, exp) def test_not_really_or_pre_post(): inp = "![foo-or-bar]" exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'foo', 2), - ('MINUS', '-', 5), - ('NAME', 'or', 6), - ('MINUS', '-', 8), - ('NAME', 'bar', 9), - ('RBRACKET', ']', 12), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "foo", 2), + ("MINUS", "-", 5), + ("NAME", "or", 6), + ("MINUS", "-", 8), + ("NAME", "bar", 9), + ("RBRACKET", "]", 12), + ] assert check_tokens(inp, exp) def test_subproc_line_cont_space(): - inp = ("![echo --option1 value1 \\\n" - " --option2 value2 \\\n" - " --optionZ valueZ]") + inp = ( + "![echo --option1 value1 \\\n" + " --option2 value2 \\\n" + " --optionZ valueZ]" + ) exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'echo', 2), - ('WS', ' ', 6), - ('MINUS', '-', 7), - ('MINUS', '-', 8), - ('NAME', 'option1', 9), - ('WS', ' ', 16), - ('NAME', 'value1', 17), - ('WS', ' ', 23), - ('MINUS', '-', 5), - ('MINUS', '-', 6), - ('NAME', 'option2', 7), - ('WS', ' ', 14), - ('NAME', 'value2', 15), - ('WS', ' ', 21), - ('MINUS', '-', 5), - ('MINUS', '-', 6), - ('NAME', 'optionZ', 7), - ('WS', ' ', 14), - ('NAME', 'valueZ', 15), - ('RBRACKET',']', 21), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "echo", 2), + ("WS", " ", 6), + ("MINUS", "-", 7), + ("MINUS", "-", 8), + ("NAME", "option1", 9), + ("WS", " ", 16), + ("NAME", "value1", 17), + ("WS", " ", 23), + ("MINUS", "-", 5), + ("MINUS", "-", 6), + ("NAME", "option2", 7), + ("WS", " ", 14), + ("NAME", "value2", 15), + ("WS", " ", 21), + ("MINUS", "-", 5), + ("MINUS", "-", 6), + ("NAME", "optionZ", 7), + ("WS", " ", 14), + ("NAME", "valueZ", 15), + ("RBRACKET", "]", 21), + ] assert check_tokens(inp, exp) def test_subproc_line_cont_nospace(): - inp = ("![echo --option1 value1\\\n" - " --option2 value2\\\n" - " --optionZ valueZ]") + inp = ( + "![echo --option1 value1\\\n" + " --option2 value2\\\n" + " --optionZ valueZ]" + ) exp = [ - ('BANG_LBRACKET', '![', 0), - ('NAME', 'echo', 2), - ('WS', ' ', 6), - ('MINUS', '-', 7), - ('MINUS', '-', 8), - ('NAME', 'option1', 9), - ('WS', ' ', 16), - ('NAME', 'value1', 17), - ('WS', '\\', 23), - ('MINUS', '-', 5), - ('MINUS', '-', 6), - ('NAME', 'option2', 7), - ('WS', ' ', 14), - ('NAME', 'value2', 15), - ('WS', '\\', 21), - ('MINUS', '-', 5), - ('MINUS', '-', 6), - ('NAME', 'optionZ', 7), - ('WS', ' ', 14), - ('NAME', 'valueZ', 15), - ('RBRACKET',']', 21), - ] + ("BANG_LBRACKET", "![", 0), + ("NAME", "echo", 2), + ("WS", " ", 6), + ("MINUS", "-", 7), + ("MINUS", "-", 8), + ("NAME", "option1", 9), + ("WS", " ", 16), + ("NAME", "value1", 17), + ("WS", "\\", 23), + ("MINUS", "-", 5), + ("MINUS", "-", 6), + ("NAME", "option2", 7), + ("WS", " ", 14), + ("NAME", "value2", 15), + ("WS", "\\", 21), + ("MINUS", "-", 5), + ("MINUS", "-", 6), + ("NAME", "optionZ", 7), + ("WS", " ", 14), + ("NAME", "valueZ", 15), + ("RBRACKET", "]", 21), + ] assert check_tokens(inp, exp) def test_atdollar(): - assert check_token('@$', ['ATDOLLAR', '@$', 0]) + assert check_token("@$", ["ATDOLLAR", "@$", 0]) def test_doubleamp(): - assert check_token('&&', ['AND', 'and', 0]) + assert check_token("&&", ["AND", "and", 0]) def test_pipe(): - assert check_token('|', ['PIPE', '|', 0]) + assert check_token("|", ["PIPE", "|", 0]) def test_doublepipe(): - assert check_token('||', ['OR', 'or', 0]) + assert check_token("||", ["OR", "or", 0]) def test_single_quote_literal(): - assert check_token("'yo'", ['STRING', "'yo'", 0]) + assert check_token("'yo'", ["STRING", "'yo'", 0]) def test_double_quote_literal(): - assert check_token('"yo"', ['STRING', '"yo"', 0]) + assert check_token('"yo"', ["STRING", '"yo"', 0]) def test_triple_single_quote_literal(): - assert check_token("'''yo'''", ['STRING', "'''yo'''", 0]) + assert check_token("'''yo'''", ["STRING", "'''yo'''", 0]) def test_triple_double_quote_literal(): - assert check_token('"""yo"""', ['STRING', '"""yo"""', 0]) + assert check_token('"""yo"""', ["STRING", '"""yo"""', 0]) def test_single_raw_string_literal(): - assert check_token("r'yo'", ['STRING', "r'yo'", 0]) + assert check_token("r'yo'", ["STRING", "r'yo'", 0]) def test_double_raw_string_literal(): - assert check_token('r"yo"', ['STRING', 'r"yo"', 0]) + assert check_token('r"yo"', ["STRING", 'r"yo"', 0]) def test_single_f_string_literal(): - assert check_token("f'{yo}'", ['STRING', "f'{yo}'", 0]) + assert check_token("f'{yo}'", ["STRING", "f'{yo}'", 0]) def test_double_f_string_literal(): - assert check_token('f"{yo}"', ['STRING', 'f"{yo}"', 0]) + assert check_token('f"{yo}"', ["STRING", 'f"{yo}"', 0]) def test_single_unicode_literal(): - assert check_token("u'yo'", ['STRING', "u'yo'", 0]) + assert check_token("u'yo'", ["STRING", "u'yo'", 0]) def test_double_unicode_literal(): - assert check_token('u"yo"', ['STRING', 'u"yo"', 0]) + assert check_token('u"yo"', ["STRING", 'u"yo"', 0]) def test_single_bytes_literal(): - assert check_token("b'yo'", ['STRING', "b'yo'", 0]) + assert check_token("b'yo'", ["STRING", "b'yo'", 0]) def test_path_string_literal(): - assert check_token("p'/foo'", ['STRING', "p'/foo'", 0]) - assert check_token('p"/foo"', ['STRING', 'p"/foo"', 0]) - assert check_token("pr'/foo'", ['STRING', "pr'/foo'", 0]) - assert check_token('pr"/foo"', ['STRING', 'pr"/foo"', 0]) - assert check_token("rp'/foo'", ['STRING', "rp'/foo'", 0]) - assert check_token('rp"/foo"', ['STRING', 'rp"/foo"', 0]) + assert check_token("p'/foo'", ["STRING", "p'/foo'", 0]) + assert check_token('p"/foo"', ["STRING", 'p"/foo"', 0]) + assert check_token("pr'/foo'", ["STRING", "pr'/foo'", 0]) + assert check_token('pr"/foo"', ["STRING", 'pr"/foo"', 0]) + assert check_token("rp'/foo'", ["STRING", "rp'/foo'", 0]) + assert check_token('rp"/foo"', ["STRING", 'rp"/foo"', 0]) def test_regex_globs(): - for i in ('.*', r'\d*', '.*#{1,2}'): - for p in ('', 'r', 'g', '@somethingelse', 'p', 'pg'): - c = '{}`{}`'.format(p,i) - assert check_token(c, ['SEARCHPATH', c, 0]) + for i in (".*", r"\d*", ".*#{1,2}"): + for p in ("", "r", "g", "@somethingelse", "p", "pg"): + c = "{}`{}`".format(p, i) + assert check_token(c, ["SEARCHPATH", c, 0]) -@pytest.mark.parametrize('case', [ - '0.0', '.0', '0.', '1e10', '1.e42', '0.1e42', '0.5e-42', '5E10', '5e+42', '1_0e1_0']) +@pytest.mark.parametrize( + "case", + [ + "0.0", + ".0", + "0.", + "1e10", + "1.e42", + "0.1e42", + "0.5e-42", + "5E10", + "5e+42", + "1_0e1_0", + ], +) def test_float_literals(case): - assert check_token(case, ['NUMBER', case, 0]) + assert check_token(case, ["NUMBER", case, 0]) -@pytest.mark.parametrize('case', [ - '2>1', 'err>out', 'o>', 'all>', 'e>o', 'e>', 'out>', '2>&1' -]) + +@pytest.mark.parametrize( + "case", ["2>1", "err>out", "o>", "all>", "e>o", "e>", "out>", "2>&1"] +) def test_ioredir(case): - assert check_tokens_subproc(case, [('IOREDIRECT', case, 2)], stop=-2) + assert check_tokens_subproc(case, [("IOREDIRECT", case, 2)], stop=-2) -@pytest.mark.parametrize('case', [ - '>', '>>', '<', 'e>', - '> ', '>> ', '< ', 'e> ', -]) +@pytest.mark.parametrize("case", [">", ">>", "<", "e>", "> ", ">> ", "< ", "e> "]) def test_redir_whitespace(case): - inp = '![{}/path/to/file]'.format(case) + inp = "![{}/path/to/file]".format(case) l = Lexer() l.input(inp) obs = list(l) - assert obs[2].type == 'WS' + assert obs[2].type == "WS" -@pytest.mark.parametrize('s, exp', [ - ('', []), - (' \t \n \t ', []), - ('echo hello', ['echo', 'hello']), - ('echo "hello"', ['echo', '"hello"']), - ('![echo "hello"]', ['![echo', '"hello"]']), - ('/usr/bin/echo hello', ['/usr/bin/echo', 'hello']), - ('$(/usr/bin/echo hello)', ['$(/usr/bin/echo', 'hello)']), - ('C:\\Python\\python.exe -m xonsh', ['C:\\Python\\python.exe', '-m', 'xonsh']), - ('print("""I am a triple string""")', ['print("""I am a triple string""")']), - ('print("""I am a \ntriple string""")', ['print("""I am a \ntriple string""")']), - ('echo $HOME', ['echo', '$HOME']), - ('echo -n $HOME', ['echo', '-n', '$HOME']), - ('echo --go=away', ['echo', '--go=away']), - ('echo --go=$HOME', ['echo', '--go=$HOME']), -]) +@pytest.mark.parametrize( + "s, exp", + [ + ("", []), + (" \t \n \t ", []), + ("echo hello", ["echo", "hello"]), + ('echo "hello"', ["echo", '"hello"']), + ('![echo "hello"]', ["![echo", '"hello"]']), + ("/usr/bin/echo hello", ["/usr/bin/echo", "hello"]), + ("$(/usr/bin/echo hello)", ["$(/usr/bin/echo", "hello)"]), + ("C:\\Python\\python.exe -m xonsh", ["C:\\Python\\python.exe", "-m", "xonsh"]), + ('print("""I am a triple string""")', ['print("""I am a triple string""")']), + ( + 'print("""I am a \ntriple string""")', + ['print("""I am a \ntriple string""")'], + ), + ("echo $HOME", ["echo", "$HOME"]), + ("echo -n $HOME", ["echo", "-n", "$HOME"]), + ("echo --go=away", ["echo", "--go=away"]), + ("echo --go=$HOME", ["echo", "--go=$HOME"]), + ], +) def test_lexer_split(s, exp): lexer = Lexer() obs = lexer.split(s) diff --git a/tests/test_main.py b/tests/test_main.py index 327d268ee..54de919b1 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -21,55 +21,55 @@ def Shell(*args, **kwargs): @pytest.fixture def shell(xonsh_builtins, xonsh_execer, monkeypatch): """Xonsh Shell Mock""" - Shell.shell_type_aliases = {'rl': 'readline'} - monkeypatch.setattr(xonsh.main, 'Shell', Shell) + Shell.shell_type_aliases = {"rl": "readline"} + monkeypatch.setattr(xonsh.main, "Shell", Shell) def test_premain_no_arg(shell, monkeypatch): - monkeypatch.setattr(sys.stdin, 'isatty', lambda: True) + monkeypatch.setattr(sys.stdin, "isatty", lambda: True) xonsh.main.premain([]) - assert builtins.__xonsh_env__.get('XONSH_LOGIN') + assert builtins.__xonsh_env__.get("XONSH_LOGIN") def test_premain_interactive(shell): - xonsh.main.premain(['-i']) - assert (builtins.__xonsh_env__.get('XONSH_INTERACTIVE')) + xonsh.main.premain(["-i"]) + assert builtins.__xonsh_env__.get("XONSH_INTERACTIVE") def test_premain_login_command(shell): - xonsh.main.premain(['-l', '-c', 'echo "hi"']) - assert (builtins.__xonsh_env__.get('XONSH_LOGIN')) + xonsh.main.premain(["-l", "-c", 'echo "hi"']) + assert builtins.__xonsh_env__.get("XONSH_LOGIN") def test_premain_login(shell): - xonsh.main.premain(['-l']) - assert (builtins.__xonsh_env__.get('XONSH_LOGIN')) + xonsh.main.premain(["-l"]) + assert builtins.__xonsh_env__.get("XONSH_LOGIN") def test_premain_D(shell): - xonsh.main.premain(['-DTEST1=1616', '-DTEST2=LOL']) - assert (builtins.__xonsh_env__.get('TEST1') == '1616') - assert (builtins.__xonsh_env__.get('TEST2') == 'LOL') + xonsh.main.premain(["-DTEST1=1616", "-DTEST2=LOL"]) + assert builtins.__xonsh_env__.get("TEST1") == "1616" + assert builtins.__xonsh_env__.get("TEST2") == "LOL" def test_premain_custom_rc(shell, tmpdir, monkeypatch): - monkeypatch.setattr(sys.stdin, 'isatty', lambda: True) + monkeypatch.setattr(sys.stdin, "isatty", lambda: True) builtins.__xonsh_env__ = Env(XONSH_CACHE_SCRIPTS=False) - f = tmpdir.join('wakkawakka') + f = tmpdir.join("wakkawakka") f.write("print('hi')") - args = xonsh.main.premain(['--rc', f.strpath]) + args = xonsh.main.premain(["--rc", f.strpath]) assert args.mode == XonshMode.interactive - assert f.strpath in builtins.__xonsh_env__.get('XONSHRC') + assert f.strpath in builtins.__xonsh_env__.get("XONSHRC") def test_no_rc_with_script(shell, tmpdir): - args = xonsh.main.premain(['tests/sample.xsh']) + args = xonsh.main.premain(["tests/sample.xsh"]) assert not (args.mode == XonshMode.interactive) def test_force_interactive_rc_with_script(shell, tmpdir): - args = xonsh.main.premain(['-i', 'tests/sample.xsh']) - assert builtins.__xonsh_env__.get('XONSH_INTERACTIVE') + args = xonsh.main.premain(["-i", "tests/sample.xsh"]) + assert builtins.__xonsh_env__.get("XONSH_INTERACTIVE") def test_force_interactive_custom_rc_with_script(shell, tmpdir): @@ -77,69 +77,73 @@ def test_force_interactive_custom_rc_with_script(shell, tmpdir): should run interactively """ builtins.__xonsh_env__ = Env(XONSH_CACHE_SCRIPTS=False) - f = tmpdir.join('wakkawakka') + f = tmpdir.join("wakkawakka") f.write("print('hi')") - args = xonsh.main.premain(['-i', '--rc', f.strpath, 'tests/sample.xsh']) + args = xonsh.main.premain(["-i", "--rc", f.strpath, "tests/sample.xsh"]) assert args.mode == XonshMode.interactive - assert f.strpath in builtins.__xonsh_env__.get('XONSHRC') + assert f.strpath in builtins.__xonsh_env__.get("XONSHRC") def test_custom_rc_with_script(shell, tmpdir): """Calling a custom RC file on a script-call without the interactive flag should not run interactively """ - f = tmpdir.join('wakkawakka') + f = tmpdir.join("wakkawakka") f.write("print('hi')") - args = xonsh.main.premain(['--rc', f.strpath, 'tests/sample.xsh']) + args = xonsh.main.premain(["--rc", f.strpath, "tests/sample.xsh"]) assert not (args.mode == XonshMode.interactive) def test_premain_no_rc(shell, tmpdir): - xonsh.main.premain(['--no-rc']) - assert not builtins.__xonsh_env__.get('XONSHRC') + xonsh.main.premain(["--no-rc"]) + assert not builtins.__xonsh_env__.get("XONSHRC") @pytest.mark.parametrize( - 'arg', ['', '-i', '-vERSION', '-hAALP', 'TTTT', '-TT', '--TTT']) + "arg", ["", "-i", "-vERSION", "-hAALP", "TTTT", "-TT", "--TTT"] +) def test_premain_with_file_argument(arg, shell): - xonsh.main.premain(['tests/sample.xsh', arg]) - assert not (builtins.__xonsh_env__.get('XONSH_INTERACTIVE')) + xonsh.main.premain(["tests/sample.xsh", arg]) + assert not (builtins.__xonsh_env__.get("XONSH_INTERACTIVE")) def test_premain_interactive__with_file_argument(shell): - xonsh.main.premain(['-i', 'tests/sample.xsh']) - assert (builtins.__xonsh_env__.get('XONSH_INTERACTIVE')) + xonsh.main.premain(["-i", "tests/sample.xsh"]) + assert builtins.__xonsh_env__.get("XONSH_INTERACTIVE") -@pytest.mark.parametrize('case', ['----', '--hep', '-TT', '--TTTT']) +@pytest.mark.parametrize("case", ["----", "--hep", "-TT", "--TTTT"]) def test_premain_invalid_arguments(shell, case, capsys): with pytest.raises(SystemExit): xonsh.main.premain([case]) - assert 'unrecognized argument' in capsys.readouterr()[1] + assert "unrecognized argument" in capsys.readouterr()[1] def test_xonsh_failback(shell, monkeypatch): failback_checker = [] - monkeypatch.setattr(sys, 'stderr', open(os.devnull, 'w')) + monkeypatch.setattr(sys, "stderr", open(os.devnull, "w")) def mocked_main(*args): - raise Exception('A fake failure') - monkeypatch.setattr(xonsh.main, 'main_xonsh', mocked_main) + raise Exception("A fake failure") + + monkeypatch.setattr(xonsh.main, "main_xonsh", mocked_main) def mocked_execlp(f, *args): failback_checker.append(f) failback_checker.append(args[0]) - monkeypatch.setattr(os, 'execlp', mocked_execlp) - monkeypatch.setattr(os.path, 'exists', lambda x: True) - monkeypatch.setattr(sys, 'argv', ['xonsh', '-i']) + + monkeypatch.setattr(os, "execlp", mocked_execlp) + monkeypatch.setattr(os.path, "exists", lambda x: True) + monkeypatch.setattr(sys, "argv", ["xonsh", "-i"]) @contextmanager def mocked_open(*args): - yield ['/usr/bin/xonsh', '/usr/bin/screen', 'bash', '/bin/xshell'] - monkeypatch.setattr(builtins, 'open', mocked_open) + yield ["/usr/bin/xonsh", "/usr/bin/screen", "bash", "/bin/xshell"] + + monkeypatch.setattr(builtins, "open", mocked_open) xonsh.main.main() - assert failback_checker == ['/bin/xshell', '/bin/xshell'] + assert failback_checker == ["/bin/xshell", "/bin/xshell"] def test_xonsh_failback_single(shell, monkeypatch): @@ -148,9 +152,10 @@ def test_xonsh_failback_single(shell, monkeypatch): def mocked_main(*args): raise FakeFailureError() - monkeypatch.setattr(xonsh.main, 'main_xonsh', mocked_main) - monkeypatch.setattr(sys, 'argv', ['xonsh', '-c', 'echo', 'foo']) - monkeypatch.setattr(sys, 'stderr', open(os.devnull, 'w')) + + monkeypatch.setattr(xonsh.main, "main_xonsh", mocked_main) + monkeypatch.setattr(sys, "argv", ["xonsh", "-c", "echo", "foo"]) + monkeypatch.setattr(sys, "stderr", open(os.devnull, "w")) with pytest.raises(FakeFailureError): xonsh.main.main() @@ -158,13 +163,15 @@ def test_xonsh_failback_single(shell, monkeypatch): def test_xonsh_failback_script_from_file(shell, monkeypatch): checker = [] + def mocked_execlp(f, *args): checker.append(f) - monkeypatch.setattr(os, 'execlp', mocked_execlp) - script = os.path.join(TEST_DIR, 'scripts', 'raise.xsh') - monkeypatch.setattr(sys, 'argv', ['xonsh', script]) - monkeypatch.setattr(sys, 'stderr', open(os.devnull, 'w')) + monkeypatch.setattr(os, "execlp", mocked_execlp) + + script = os.path.join(TEST_DIR, "scripts", "raise.xsh") + monkeypatch.setattr(sys, "argv", ["xonsh", script]) + monkeypatch.setattr(sys, "stderr", open(os.devnull, "w")) with pytest.raises(Exception): xonsh.main.main() assert len(checker) == 0 diff --git a/tests/test_man.py b/tests/test_man.py index c26a38e1f..c78bd188d 100644 --- a/tests/test_man.py +++ b/tests/test_man.py @@ -8,10 +8,11 @@ from tools import skip_if_on_windows @skip_if_on_windows def test_man_completion(monkeypatch, tmpdir, xonsh_builtins): - tempdir = tmpdir.mkdir('test_man') - monkeypatch.setitem(os.environ, 'MANPATH', os.path.dirname(os.path.abspath(__file__))) - xonsh_builtins.__xonsh_env__.update({'XONSH_DATA_DIR': str(tempdir)}) - completions = complete_from_man('--', 'yes --', 4, 6, - xonsh_builtins.__xonsh_env__) - assert '--version' in completions - assert '--help' in completions + tempdir = tmpdir.mkdir("test_man") + monkeypatch.setitem( + os.environ, "MANPATH", os.path.dirname(os.path.abspath(__file__)) + ) + xonsh_builtins.__xonsh_env__.update({"XONSH_DATA_DIR": str(tempdir)}) + completions = complete_from_man("--", "yes --", 4, 6, xonsh_builtins.__xonsh_env__) + assert "--version" in completions + assert "--help" in completions diff --git a/tests/test_mpl.py b/tests/test_mpl.py index cdbaf2eb8..36646fd5e 100644 --- a/tests/test_mpl.py +++ b/tests/test_mpl.py @@ -7,13 +7,14 @@ plt = pytest.importorskip("matplotlib.pyplot") from xontrib import mplhooks -skip_if_mpl2 = pytest.mark.skipif(matplotlib.__version__.startswith('2'), - reason='Bug in matplotlib v2') +skip_if_mpl2 = pytest.mark.skipif( + matplotlib.__version__.startswith("2"), reason="Bug in matplotlib v2" +) # some default settings that are temporarily changed by mpl -FONT_SIZE = 22 -FACE_COLOR = (0.0, 1.0, 0.0, 1.0) -DPI = 80 +FONT_SIZE = 22 +FACE_COLOR = (0.0, 1.0, 0.0, 1.0) +DPI = 80 def create_figure(): @@ -23,7 +24,7 @@ def create_figure(): # set the figure parameters such that mpl will require changes f.set_facecolor(FACE_COLOR) f.dpi = DPI - matplotlib.rcParams.update({'font.size': FONT_SIZE}) + matplotlib.rcParams.update({"font.size": FONT_SIZE}) return f @@ -33,9 +34,9 @@ def test_mpl_preserve_font_size(): f = create_figure() width, height = f.canvas.get_width_height() print(width, height) - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, True) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, True) exp = FONT_SIZE - obs = matplotlib.rcParams['font.size'] + obs = matplotlib.rcParams["font.size"] plt.close(f) assert exp == obs @@ -45,7 +46,7 @@ def test_mpl_preserve_face_color(): """Make sure that the figure preserves face color settings""" f = create_figure() width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, True) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, True) exp = FACE_COLOR obs = f.get_facecolor() plt.close(f) @@ -57,7 +58,7 @@ def test_mpl_preserve_width(): """Make sure that the figure preserves width settings""" f = create_figure() width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, True) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, True) exp = width newwidth, newheight = f.canvas.get_width_height() obs = newwidth @@ -70,7 +71,7 @@ def test_mpl_preserve_height(): """Make sure that the figure preserves height settings""" f = create_figure() width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, True) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, True) exp = height newwidth, newheight = f.canvas.get_width_height() obs = newheight @@ -82,7 +83,7 @@ def test_mpl_preserve_dpi(): """Make sure that the figure preserves height settings""" f = create_figure() width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, False) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, False) exp = DPI obs = f.dpi plt.close(f) @@ -95,7 +96,7 @@ def test_mpl_preserve_image_tight(): f = create_figure() exp = mplhooks.figure_to_rgb_array(f) width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, True) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, True) obs = mplhooks.figure_to_rgb_array(f) plt.close(f) assert np.all(exp == obs) @@ -106,7 +107,7 @@ def test_mpl_preserve_standard(): f = create_figure() exp = mplhooks.figure_to_rgb_array(f) width, height = f.canvas.get_width_height() - s = mplhooks.figure_to_tight_array(f, 0.5*width, 0.5*height, False) + s = mplhooks.figure_to_tight_array(f, 0.5 * width, 0.5 * height, False) obs = mplhooks.figure_to_rgb_array(f) plt.close(f) assert np.all(exp == obs) diff --git a/tests/test_news.py b/tests/test_news.py index e1011c092..79865310c 100644 --- a/tests/test_news.py +++ b/tests/test_news.py @@ -8,12 +8,14 @@ import pytest from xonsh.platform import scandir -NEWSDIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'news') +NEWSDIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "news") -CATEGORIES = frozenset(['Added', 'Changed', 'Deprecated', 'Removed', - 'Fixed', 'Security']) +CATEGORIES = frozenset( + ["Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"] +) + +single_grave_reg = re.compile(r"[^`]`[^`]+`[^`_]") -single_grave_reg = re.compile(r'[^`]`[^`]+`[^`_]') def check_news_file(fname): name = fname.name @@ -22,42 +24,44 @@ def check_news_file(fname): form = "" for i, l in enumerate(lines): # search the graves - if '`' in l: + if "`" in l: if single_grave_reg.search(l): - pytest.fail("{}:{}: single grave accents" - " are not valid rst".format(name, i+1), - pytrace=False) + pytest.fail( + "{}:{}: single grave accents" + " are not valid rst".format(name, i + 1), + pytrace=False, + ) # determine the form of line - if l.startswith('**'): - cat = l[2:].rsplit(':')[0] + if l.startswith("**"): + cat = l[2:].rsplit(":")[0] if cat not in CATEGORIES: - pytest.fail('{}:{}: {!r} not a proper category ' - 'must be one of {}' - ''.format(name, i+1, cat, list(CATEGORIES)), - pytrace=False) - if l.endswith('None'): - form += '3' + pytest.fail( + "{}:{}: {!r} not a proper category " + "must be one of {}" + "".format(name, i + 1, cat, list(CATEGORIES)), + pytrace=False, + ) + if l.endswith("None"): + form += "3" else: - form += '2' - elif l.startswith('* ') or l.startswith('- ') or l.startswith(' '): - form += '1' - elif l.strip() == '': - form += '0' + form += "2" + elif l.startswith("* ") or l.startswith("- ") or l.startswith(" "): + form += "1" + elif l.strip() == "": + form += "0" else: - pytest.fail('{}:{}: invalid rst'.format(name, i+1), - pytrace=False) + pytest.fail("{}:{}: invalid rst".format(name, i + 1), pytrace=False) # The file should have: # empty lines around categories # at least one content line in a non null category - reg = re.compile(r'^(3(0|$)|201(1|0)*0)+$') + reg = re.compile(r"^(3(0|$)|201(1|0)*0)+$") if not reg.match(form): - pytest.fail('{}: invalid rst'.format(name), - pytrace=False) + pytest.fail("{}: invalid rst".format(name), pytrace=False) -@pytest.mark.parametrize('fname', list(scandir(NEWSDIR))) +@pytest.mark.parametrize("fname", list(scandir(NEWSDIR))) def test_news(fname): base, ext = os.path.splitext(fname.path) - assert 'rst' in ext + assert "rst" in ext check_news_file(fname) diff --git a/tests/test_parser.py b/tests/test_parser.py index 9f870666a..3096e7753 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -15,14 +15,16 @@ from tools import VER_FULL, skip_if_py34, skip_if_lt_py36, nodes_equal # a lot of col_offset data changed from Py v3.5.0 -> v3.5.1 INC_ATTRS = (3, 5, 1) <= VER_FULL + @pytest.fixture(autouse=True) def xonsh_builtins_autouse(xonsh_builtins): return xonsh_builtins + PARSER = Parser(lexer_optimize=False, yacc_optimize=False, yacc_debug=True) -def check_ast(inp, run=True, mode='eval', debug_level=0): +def check_ast(inp, run=True, mode="eval", debug_level=0): __tracebackhide__ = True # expect a Python AST exp = ast.parse(inp, mode=mode) @@ -32,32 +34,35 @@ def check_ast(inp, run=True, mode='eval', debug_level=0): assert nodes_equal(exp, obs) # round trip by running xonsh AST via Python if run: - exec(compile(obs, '', mode)) + exec(compile(obs, "", mode)) -def check_stmts(inp, run=True, mode='exec', debug_level=0): + +def check_stmts(inp, run=True, mode="exec", debug_level=0): __tracebackhide__ = True - if not inp.endswith('\n'): - inp += '\n' + if not inp.endswith("\n"): + inp += "\n" check_ast(inp, run=run, mode=mode, debug_level=debug_level) -def check_xonsh_ast(xenv, inp, run=True, mode='eval', debug_level=0, - return_obs=False): + +def check_xonsh_ast(xenv, inp, run=True, mode="eval", debug_level=0, return_obs=False): __tracebackhide__ = True builtins.__xonsh_env__ = xenv obs = PARSER.parse(inp, debug_level=debug_level) if obs is None: return # comment only - bytecode = compile(obs, '', mode) + bytecode = compile(obs, "", mode) if run: exec(bytecode) return obs if return_obs else True -def check_xonsh(xenv, inp, run=True, mode='exec'): + +def check_xonsh(xenv, inp, run=True, mode="exec"): __tracebackhide__ = True - if not inp.endswith('\n'): - inp += '\n' + if not inp.endswith("\n"): + inp += "\n" check_xonsh_ast(xenv, inp, run=run, mode=mode) + # # Tests # @@ -66,1452 +71,1916 @@ def check_xonsh(xenv, inp, run=True, mode='exec'): # expressions # + def test_int_literal(): - check_ast('42') + check_ast("42") + @skip_if_lt_py36 def test_int_literal_underscore(): - check_ast('4_2') + check_ast("4_2") + def test_float_literal(): - check_ast('42.0') + check_ast("42.0") + @skip_if_lt_py36 def test_float_literal_underscore(): - check_ast('4_2.4_2') + check_ast("4_2.4_2") + def test_imag_literal(): - check_ast('42j') + check_ast("42j") + def test_float_imag_literal(): - check_ast('42.0j') + check_ast("42.0j") + def test_complex(): - check_ast('42+84j') + check_ast("42+84j") + def test_str_literal(): check_ast('"hello"') + def test_bytes_literal(): check_ast('b"hello"') check_ast('B"hello"') + def test_raw_literal(): check_ast('r"hell\o"') check_ast('R"hell\o"') + @skip_if_lt_py36 def test_f_literal(): check_ast('f"wakka{yo}yakka{42}"', run=False) check_ast('F"{yo}"', run=False) + def test_raw_bytes_literal(): check_ast('br"hell\o"') check_ast('RB"hell\o"') check_ast('Br"hell\o"') check_ast('rB"hell\o"') + def test_unary_plus(): - check_ast('+1') + check_ast("+1") + def test_unary_minus(): - check_ast('-1') + check_ast("-1") + def test_unary_invert(): - check_ast('~1') + check_ast("~1") + def test_binop_plus(): - check_ast('42 + 65') + check_ast("42 + 65") + def test_binop_minus(): - check_ast('42 - 65') + check_ast("42 - 65") + def test_binop_times(): - check_ast('42 * 65') + check_ast("42 * 65") + @skip_if_py34 def test_binop_matmult(): - check_ast('x @ y', False) + check_ast("x @ y", False) + def test_binop_div(): - check_ast('42 / 65') + check_ast("42 / 65") + def test_binop_mod(): - check_ast('42 % 65') + check_ast("42 % 65") + def test_binop_floordiv(): - check_ast('42 // 65') + check_ast("42 // 65") + def test_binop_pow(): - check_ast('2 ** 2') + check_ast("2 ** 2") + def test_plus_pow(): - check_ast('42 + 2 ** 2') + check_ast("42 + 2 ** 2") + def test_plus_plus(): - check_ast('42 + 65 + 6') + check_ast("42 + 65 + 6") + def test_plus_minus(): - check_ast('42 + 65 - 6') + check_ast("42 + 65 - 6") + def test_minus_plus(): - check_ast('42 - 65 + 6') + check_ast("42 - 65 + 6") + def test_minus_minus(): - check_ast('42 - 65 - 6') + check_ast("42 - 65 - 6") + def test_minus_plus_minus(): - check_ast('42 - 65 + 6 - 28') + check_ast("42 - 65 + 6 - 28") + def test_times_plus(): - check_ast('42 * 65 + 6') + check_ast("42 * 65 + 6") + def test_plus_times(): - check_ast('42 + 65 * 6') + check_ast("42 + 65 * 6") + def test_times_times(): - check_ast('42 * 65 * 6') + check_ast("42 * 65 * 6") + def test_times_div(): - check_ast('42 * 65 / 6') + check_ast("42 * 65 / 6") + def test_times_div_mod(): - check_ast('42 * 65 / 6 % 28') + check_ast("42 * 65 / 6 % 28") + def test_times_div_mod_floor(): - check_ast('42 * 65 / 6 % 28 // 13') + check_ast("42 * 65 / 6 % 28 // 13") + def test_str_str(): - check_ast('"hello" \'mom\'') + check_ast("\"hello\" 'mom'") + def test_str_str_str(): check_ast('"hello" \'mom\' "wow"') + def test_str_plus_str(): - check_ast('"hello" + \'mom\'') + check_ast("\"hello\" + 'mom'") + def test_str_times_int(): check_ast('"hello" * 20') + def test_int_times_str(): check_ast('2*"hello"') + def test_group_plus_times(): - check_ast('(42 + 65) * 20') + check_ast("(42 + 65) * 20") + def test_plus_group_times(): - check_ast('42 + (65 * 20)') + check_ast("42 + (65 * 20)") + def test_group(): - check_ast('(42)') + check_ast("(42)") + def test_lt(): - check_ast('42 < 65') + check_ast("42 < 65") + def test_gt(): - check_ast('42 > 65') + check_ast("42 > 65") + def test_eq(): - check_ast('42 == 65') + check_ast("42 == 65") + def test_le(): - check_ast('42 <= 65') + check_ast("42 <= 65") + def test_ge(): - check_ast('42 >= 65') + check_ast("42 >= 65") + def test_ne(): - check_ast('42 != 65') + check_ast("42 != 65") + def test_in(): check_ast('"4" in "65"') + def test_is(): - check_ast('42 is 65') + check_ast("42 is 65") + def test_not_in(): check_ast('"4" not in "65"') + def test_is_not(): - check_ast('42 is not 65') + check_ast("42 is not 65") + def test_lt_lt(): - check_ast('42 < 65 < 105') + check_ast("42 < 65 < 105") + def test_lt_lt_lt(): - check_ast('42 < 65 < 105 < 77') + check_ast("42 < 65 < 105 < 77") + def test_not(): - check_ast('not 0') + check_ast("not 0") + def test_or(): - check_ast('1 or 0') + check_ast("1 or 0") + def test_or_or(): - check_ast('1 or 0 or 42') + check_ast("1 or 0 or 42") + def test_and(): - check_ast('1 and 0') + check_ast("1 and 0") + def test_and_and(): - check_ast('1 and 0 and 2') + check_ast("1 and 0 and 2") + def test_and_or(): - check_ast('1 and 0 or 2') + check_ast("1 and 0 or 2") + def test_or_and(): - check_ast('1 or 0 and 2') + check_ast("1 or 0 and 2") + def test_group_and_and(): - check_ast('(1 and 0) and 2') + check_ast("(1 and 0) and 2") + def test_group_and_or(): - check_ast('(1 and 0) or 2') + check_ast("(1 and 0) or 2") + def test_if_else_expr(): - check_ast('42 if True else 65') + check_ast("42 if True else 65") + def test_if_else_expr_expr(): - check_ast('42+5 if 1 == 2 else 65-5') + check_ast("42+5 if 1 == 2 else 65-5") + def test_str_idx(): check_ast('"hello"[0]') + def test_str_slice(): check_ast('"hello"[0:3]') + def test_str_step(): check_ast('"hello"[0:3:1]') + def test_str_slice_all(): check_ast('"hello"[:]') + def test_str_slice_upper(): check_ast('"hello"[5:]') + def test_str_slice_lower(): check_ast('"hello"[:3]') + def test_str_slice_other(): check_ast('"hello"[::2]') + def test_str_slice_lower_other(): check_ast('"hello"[:3:2]') + def test_str_slice_upper_other(): check_ast('"hello"[3::2]') + def test_str_2slice(): check_ast('"hello"[0:3,0:3]', False) + def test_str_2step(): check_ast('"hello"[0:3:1,0:4:2]', False) + def test_str_2slice_all(): check_ast('"hello"[:,:]', False) + def test_str_2slice_upper(): check_ast('"hello"[5:,5:]', False) + def test_str_2slice_lower(): check_ast('"hello"[:3,:3]', False) + def test_str_2slice_lowerupper(): check_ast('"hello"[5:,:3]', False) + def test_str_2slice_other(): check_ast('"hello"[::2,::2]', False) + def test_str_2slice_lower_other(): check_ast('"hello"[:3:2,:3:2]', False) + def test_str_2slice_upper_other(): check_ast('"hello"[3::2,3::2]', False) + def test_str_3slice(): check_ast('"hello"[0:3,0:3,0:3]', False) + def test_str_3step(): check_ast('"hello"[0:3:1,0:4:2,1:3:2]', False) + def test_str_3slice_all(): check_ast('"hello"[:,:,:]', False) + def test_str_3slice_upper(): check_ast('"hello"[5:,5:,5:]', False) + def test_str_3slice_lower(): check_ast('"hello"[:3,:3,:3]', False) + def test_str_3slice_lowerlowerupper(): check_ast('"hello"[:3,:3,:3]', False) + def test_str_3slice_lowerupperlower(): check_ast('"hello"[:3,5:,:3]', False) + def test_str_3slice_lowerupperupper(): check_ast('"hello"[:3,5:,5:]', False) + def test_str_3slice_upperlowerlower(): check_ast('"hello"[5:,5:,:3]', False) + def test_str_3slice_upperlowerupper(): check_ast('"hello"[5:,:3,5:]', False) + def test_str_3slice_upperupperlower(): check_ast('"hello"[5:,5:,:3]', False) + def test_str_3slice_other(): check_ast('"hello"[::2,::2,::2]', False) + def test_str_3slice_lower_other(): check_ast('"hello"[:3:2,:3:2,:3:2]', False) + def test_str_3slice_upper_other(): check_ast('"hello"[3::2,3::2,3::2]', False) + def test_str_slice_true(): check_ast('"hello"[0:3,True]', False) + def test_str_true_slice(): check_ast('"hello"[True,0:3]', False) + def test_list_empty(): - check_ast('[]') + check_ast("[]") + def test_list_one(): - check_ast('[1]') + check_ast("[1]") + def test_list_one_comma(): - check_ast('[1,]') + check_ast("[1,]") + def test_list_two(): - check_ast('[1, 42]') + check_ast("[1, 42]") + def test_list_three(): - check_ast('[1, 42, 65]') + check_ast("[1, 42, 65]") + def test_list_three_comma(): - check_ast('[1, 42, 65,]') + check_ast("[1, 42, 65,]") + def test_list_one_nested(): - check_ast('[[1]]') + check_ast("[[1]]") + def test_list_list_four_nested(): - check_ast('[[1], [2], [3], [4]]') + check_ast("[[1], [2], [3], [4]]") + def test_list_tuple_three_nested(): - check_ast('[(1,), (2,), (3,)]') + check_ast("[(1,), (2,), (3,)]") + def test_list_set_tuple_three_nested(): - check_ast('[{(1,)}, {(2,)}, {(3,)}]') + check_ast("[{(1,)}, {(2,)}, {(3,)}]") + def test_list_tuple_one_nested(): - check_ast('[(1,)]') + check_ast("[(1,)]") + def test_tuple_tuple_one_nested(): - check_ast('((1,),)') + check_ast("((1,),)") + def test_dict_list_one_nested(): - check_ast('{1: [2]}') + check_ast("{1: [2]}") + def test_dict_list_one_nested_comma(): - check_ast('{1: [2],}') + check_ast("{1: [2],}") + def test_dict_tuple_one_nested(): - check_ast('{1: (2,)}') + check_ast("{1: (2,)}") + def test_dict_tuple_one_nested_comma(): - check_ast('{1: (2,),}') + check_ast("{1: (2,),}") + def test_dict_list_two_nested(): - check_ast('{1: [2], 3: [4]}') + check_ast("{1: [2], 3: [4]}") + def test_set_tuple_one_nested(): - check_ast('{(1,)}') + check_ast("{(1,)}") + def test_set_tuple_two_nested(): - check_ast('{(1,), (2,)}') + check_ast("{(1,), (2,)}") + def test_tuple_empty(): - check_ast('()') + check_ast("()") + def test_tuple_one_bare(): - check_ast('1,') + check_ast("1,") + def test_tuple_two_bare(): - check_ast('1, 42') + check_ast("1, 42") + def test_tuple_three_bare(): - check_ast('1, 42, 65') + check_ast("1, 42, 65") + def test_tuple_three_bare_comma(): - check_ast('1, 42, 65,') + check_ast("1, 42, 65,") + def test_tuple_one_comma(): - check_ast('(1,)') + check_ast("(1,)") + def test_tuple_two(): - check_ast('(1, 42)') + check_ast("(1, 42)") + def test_tuple_three(): - check_ast('(1, 42, 65)') + check_ast("(1, 42, 65)") + def test_tuple_three_comma(): - check_ast('(1, 42, 65,)') + check_ast("(1, 42, 65,)") + def test_bare_tuple_of_tuples(): - check_ast('(),') - check_ast('((),),(1,)') - check_ast('(),(),') - check_ast('[],') - check_ast('[],[]') - check_ast('[],()') - check_ast('(),[],') - check_ast('((),[()],)') + check_ast("(),") + check_ast("((),),(1,)") + check_ast("(),(),") + check_ast("[],") + check_ast("[],[]") + check_ast("[],()") + check_ast("(),[],") + check_ast("((),[()],)") + def test_set_one(): - check_ast('{42}') + check_ast("{42}") + def test_set_one_comma(): - check_ast('{42,}') + check_ast("{42,}") + def test_set_two(): - check_ast('{42, 65}') + check_ast("{42, 65}") + def test_set_two_comma(): - check_ast('{42, 65,}') + check_ast("{42, 65,}") + def test_set_three(): - check_ast('{42, 65, 45}') + check_ast("{42, 65, 45}") + def test_dict_empty(): - check_ast('{}') + check_ast("{}") + def test_dict_one(): - check_ast('{42: 65}') + check_ast("{42: 65}") + def test_dict_one_comma(): - check_ast('{42: 65,}') + check_ast("{42: 65,}") + def test_dict_two(): - check_ast('{42: 65, 6: 28}') + check_ast("{42: 65, 6: 28}") + def test_dict_two_comma(): - check_ast('{42: 65, 6: 28,}') + check_ast("{42: 65, 6: 28,}") + def test_dict_three(): - check_ast('{42: 65, 6: 28, 1: 2}') + check_ast("{42: 65, 6: 28, 1: 2}") + @skip_if_py34 def test_dict_from_dict_two_xy(): check_ast('{"x": 1, **{"y": 2}}') + @skip_if_py34 def test_dict_from_dict_two_x_first(): check_ast('{"x": 1, **{"x": 2}}') + @skip_if_py34 def test_dict_from_dict_two_x_second(): check_ast('{**{"x": 2}, "x": 1}') + @skip_if_py34 def test_unpack_range_tuple(): - check_stmts('*range(4),') + check_stmts("*range(4),") + @skip_if_py34 def test_unpack_range_tuple_4(): - check_stmts('*range(4), 4') + check_stmts("*range(4), 4") + @skip_if_py34 def test_unpack_range_tuple_parens(): - check_ast('(*range(4),)') + check_ast("(*range(4),)") + @skip_if_py34 def test_unpack_range_tuple_parens_4(): - check_ast('(*range(4), 4)') + check_ast("(*range(4), 4)") + @skip_if_py34 def test_unpack_range_list(): - check_ast('[*range(4)]') + check_ast("[*range(4)]") + @skip_if_py34 def test_unpack_range_list_4(): - check_ast('[*range(4), 4]') + check_ast("[*range(4), 4]") + @skip_if_py34 def test_unpack_range_set(): - check_ast('{*range(4)}') + check_ast("{*range(4)}") + @skip_if_py34 def test_unpack_range_set_4(): - check_ast('{*range(4), 4}') + check_ast("{*range(4), 4}") + def test_true(): - check_ast('True') + check_ast("True") + def test_false(): - check_ast('False') + check_ast("False") + def test_none(): - check_ast('None') + check_ast("None") + def test_elipssis(): - check_ast('...') + check_ast("...") + def test_not_implemented_name(): - check_ast('NotImplemented') + check_ast("NotImplemented") + def test_genexpr(): check_ast('(x for x in "mom")') + def test_genexpr_if(): check_ast('(x for x in "mom" if True)') + def test_genexpr_if_and(): check_ast('(x for x in "mom" if True and x == "m")') + def test_dbl_genexpr(): check_ast('(x+y for x in "mom" for y in "dad")') + def test_genexpr_if_genexpr(): check_ast('(x+y for x in "mom" if True for y in "dad")') + def test_genexpr_if_genexpr_if(): check_ast('(x+y for x in "mom" if True for y in "dad" if y == "d")') + def test_listcomp(): check_ast('[x for x in "mom"]') + def test_listcomp_if(): check_ast('[x for x in "mom" if True]') + def test_listcomp_if_and(): check_ast('[x for x in "mom" if True and x == "m"]') + def test_dbl_listcomp(): check_ast('[x+y for x in "mom" for y in "dad"]') + def test_listcomp_if_listcomp(): check_ast('[x+y for x in "mom" if True for y in "dad"]') + def test_listcomp_if_listcomp_if(): check_ast('[x+y for x in "mom" if True for y in "dad" if y == "d"]') + def test_setcomp(): check_ast('{x for x in "mom"}') + def test_setcomp_if(): check_ast('{x for x in "mom" if True}') + def test_setcomp_if_and(): check_ast('{x for x in "mom" if True and x == "m"}') + def test_dbl_setcomp(): check_ast('{x+y for x in "mom" for y in "dad"}') + def test_setcomp_if_setcomp(): check_ast('{x+y for x in "mom" if True for y in "dad"}') + def test_setcomp_if_setcomp_if(): check_ast('{x+y for x in "mom" if True for y in "dad" if y == "d"}') + def test_dictcomp(): check_ast('{x: x for x in "mom"}') + def test_dictcomp_unpack_parens(): check_ast('{k: v for (k, v) in {"x": 42}.items()}') + def test_dictcomp_unpack_no_parens(): check_ast('{k: v for k, v in {"x": 42}.items()}') + def test_dictcomp_if(): check_ast('{x: x for x in "mom" if True}') + def test_dictcomp_if_and(): check_ast('{x: x for x in "mom" if True and x == "m"}') + def test_dbl_dictcomp(): check_ast('{x: y for x in "mom" for y in "dad"}') + def test_dictcomp_if_dictcomp(): check_ast('{x: y for x in "mom" if True for y in "dad"}') + def test_dictcomp_if_dictcomp_if(): check_ast('{x: y for x in "mom" if True for y in "dad" if y == "d"}') + def test_lambda(): - check_ast('lambda: 42') + check_ast("lambda: 42") + def test_lambda_x(): - check_ast('lambda x: x') + check_ast("lambda x: x") + def test_lambda_kwx(): - check_ast('lambda x=42: x') + check_ast("lambda x=42: x") + def test_lambda_x_y(): - check_ast('lambda x, y: x') + check_ast("lambda x, y: x") + def test_lambda_x_y_z(): - check_ast('lambda x, y, z: x') + check_ast("lambda x, y, z: x") + def test_lambda_x_kwy(): - check_ast('lambda x, y=42: x') + check_ast("lambda x, y=42: x") + def test_lambda_kwx_kwy(): - check_ast('lambda x=65, y=42: x') + check_ast("lambda x=65, y=42: x") + def test_lambda_kwx_kwy_kwz(): - check_ast('lambda x=65, y=42, z=1: x') + check_ast("lambda x=65, y=42, z=1: x") + def test_lambda_x_comma(): - check_ast('lambda x,: x') + check_ast("lambda x,: x") + def test_lambda_x_y_comma(): - check_ast('lambda x, y,: x') + check_ast("lambda x, y,: x") + def test_lambda_x_y_z_comma(): - check_ast('lambda x, y, z,: x') + check_ast("lambda x, y, z,: x") + def test_lambda_x_kwy_comma(): - check_ast('lambda x, y=42,: x') + check_ast("lambda x, y=42,: x") + def test_lambda_kwx_kwy_comma(): - check_ast('lambda x=65, y=42,: x') + check_ast("lambda x=65, y=42,: x") + def test_lambda_kwx_kwy_kwz_comma(): - check_ast('lambda x=65, y=42, z=1,: x') + check_ast("lambda x=65, y=42, z=1,: x") + def test_lambda_args(): - check_ast('lambda *args: 42') + check_ast("lambda *args: 42") + def test_lambda_args_x(): - check_ast('lambda *args, x: 42') + check_ast("lambda *args, x: 42") + def test_lambda_args_x_y(): - check_ast('lambda *args, x, y: 42') + check_ast("lambda *args, x, y: 42") + def test_lambda_args_x_kwy(): - check_ast('lambda *args, x, y=10: 42') + check_ast("lambda *args, x, y=10: 42") + def test_lambda_args_kwx_y(): - check_ast('lambda *args, x=10, y: 42') + check_ast("lambda *args, x=10, y: 42") + def test_lambda_args_kwx_kwy(): - check_ast('lambda *args, x=42, y=65: 42') + check_ast("lambda *args, x=42, y=65: 42") + def test_lambda_x_args(): - check_ast('lambda x, *args: 42') + check_ast("lambda x, *args: 42") + def test_lambda_x_args_y(): - check_ast('lambda x, *args, y: 42') + check_ast("lambda x, *args, y: 42") + def test_lambda_x_args_y_z(): - check_ast('lambda x, *args, y, z: 42') + check_ast("lambda x, *args, y, z: 42") + def test_lambda_kwargs(): - check_ast('lambda **kwargs: 42') + check_ast("lambda **kwargs: 42") + def test_lambda_x_kwargs(): - check_ast('lambda x, **kwargs: 42') + check_ast("lambda x, **kwargs: 42") + def test_lambda_x_y_kwargs(): - check_ast('lambda x, y, **kwargs: 42') + check_ast("lambda x, y, **kwargs: 42") + def test_lambda_x_kwy_kwargs(): - check_ast('lambda x, y=42, **kwargs: 42') + check_ast("lambda x, y=42, **kwargs: 42") + def test_lambda_args_kwargs(): - check_ast('lambda *args, **kwargs: 42') + check_ast("lambda *args, **kwargs: 42") + def test_lambda_x_args_kwargs(): - check_ast('lambda x, *args, **kwargs: 42') + check_ast("lambda x, *args, **kwargs: 42") + def test_lambda_x_y_args_kwargs(): - check_ast('lambda x, y, *args, **kwargs: 42') + check_ast("lambda x, y, *args, **kwargs: 42") + def test_lambda_kwx_args_kwargs(): - check_ast('lambda x=10, *args, **kwargs: 42') + check_ast("lambda x=10, *args, **kwargs: 42") + def test_lambda_x_kwy_args_kwargs(): - check_ast('lambda x, y=42, *args, **kwargs: 42') + check_ast("lambda x, y=42, *args, **kwargs: 42") + def test_lambda_x_args_y_kwargs(): - check_ast('lambda x, *args, y, **kwargs: 42') + check_ast("lambda x, *args, y, **kwargs: 42") + def test_lambda_x_args_kwy_kwargs(): - check_ast('lambda x, *args, y=42, **kwargs: 42') + check_ast("lambda x, *args, y=42, **kwargs: 42") + def test_lambda_args_y_kwargs(): - check_ast('lambda *args, y, **kwargs: 42') + check_ast("lambda *args, y, **kwargs: 42") + def test_lambda_star_x(): - check_ast('lambda *, x: 42') + check_ast("lambda *, x: 42") + def test_lambda_star_x_y(): - check_ast('lambda *, x, y: 42') + check_ast("lambda *, x, y: 42") + def test_lambda_star_x_kwargs(): - check_ast('lambda *, x, **kwargs: 42') + check_ast("lambda *, x, **kwargs: 42") + def test_lambda_star_kwx_kwargs(): - check_ast('lambda *, x=42, **kwargs: 42') + check_ast("lambda *, x=42, **kwargs: 42") + def test_lambda_x_star_y(): - check_ast('lambda x, *, y: 42') + check_ast("lambda x, *, y: 42") + def test_lambda_x_y_star_z(): - check_ast('lambda x, y, *, z: 42') + check_ast("lambda x, y, *, z: 42") + def test_lambda_x_kwy_star_y(): - check_ast('lambda x, y=42, *, z: 42') + check_ast("lambda x, y=42, *, z: 42") + def test_lambda_x_kwy_star_kwy(): - check_ast('lambda x, y=42, *, z=65: 42') + check_ast("lambda x, y=42, *, z=65: 42") + def test_lambda_x_star_y_kwargs(): - check_ast('lambda x, *, y, **kwargs: 42') + check_ast("lambda x, *, y, **kwargs: 42") + def test_call_range(): - check_ast('range(6)') + check_ast("range(6)") + def test_call_range_comma(): - check_ast('range(6,)') + check_ast("range(6,)") + def test_call_range_x_y(): - check_ast('range(6, 10)') + check_ast("range(6, 10)") + def test_call_range_x_y_comma(): - check_ast('range(6, 10,)') + check_ast("range(6, 10,)") + def test_call_range_x_y_z(): - check_ast('range(6, 10, 2)') + check_ast("range(6, 10, 2)") + def test_call_dict_kwx(): - check_ast('dict(start=10)') + check_ast("dict(start=10)") + def test_call_dict_kwx_comma(): - check_ast('dict(start=10,)') + check_ast("dict(start=10,)") + def test_call_dict_kwx_kwy(): - check_ast('dict(start=10, stop=42)') + check_ast("dict(start=10, stop=42)") + def test_call_tuple_gen(): - check_ast('tuple(x for x in [1, 2, 3])') + check_ast("tuple(x for x in [1, 2, 3])") + def test_call_tuple_genifs(): - check_ast('tuple(x for x in [1, 2, 3] if x < 3)') + check_ast("tuple(x for x in [1, 2, 3] if x < 3)") + def test_call_range_star(): - check_ast('range(*[1, 2, 3])') + check_ast("range(*[1, 2, 3])") + def test_call_range_x_star(): - check_ast('range(1, *[2, 3])') + check_ast("range(1, *[2, 3])") + def test_call_int(): check_ast('int(*["42"], base=8)') + def test_call_int_base_dict(): check_ast('int(*["42"], **{"base": 8})') + def test_call_dict_kwargs(): check_ast('dict(**{"base": 8})') + @skip_if_py34 def test_call_list_many_star_args(): - check_ast('min(*[1, 2], 3, *[4, 5])') + check_ast("min(*[1, 2], 3, *[4, 5])") + @skip_if_py34 def test_call_list_many_starstar_args(): check_ast('dict(**{"a": 2}, v=3, **{"c": 5})') + @skip_if_py34 def test_call_list_many_star_and_starstar_args(): check_ast('x(*[("a", 2)], *[("v", 3)], **{"c": 5})', False) + def test_call_alot(): - check_ast('x(1, *args, **kwargs)', False) + check_ast("x(1, *args, **kwargs)", False) + def test_call_alot_next(): - check_ast('x(x=1, *args, **kwargs)', False) + check_ast("x(x=1, *args, **kwargs)", False) + def test_call_alot_next_next(): - check_ast('x(x=1, *args, y=42, **kwargs)', False) + check_ast("x(x=1, *args, y=42, **kwargs)", False) + def test_getattr(): - check_ast('list.append') + check_ast("list.append") + def test_getattr_getattr(): - check_ast('list.append.__str__') + check_ast("list.append.__str__") + def test_dict_tuple_key(): - check_ast('{(42, 1): 65}') + check_ast("{(42, 1): 65}") + def test_dict_tuple_key_get(): - check_ast('{(42, 1): 65}[42, 1]') + check_ast("{(42, 1): 65}[42, 1]") + def test_dict_tuple_key_get_3(): - check_ast('{(42, 1, 3): 65}[42, 1, 3]') + check_ast("{(42, 1, 3): 65}[42, 1, 3]") + def test_pipe_op(): - check_ast('{42} | {65}') + check_ast("{42} | {65}") + def test_pipe_op_two(): - check_ast('{42} | {65} | {1}') + check_ast("{42} | {65} | {1}") + def test_pipe_op_three(): - check_ast('{42} | {65} | {1} | {7}') + check_ast("{42} | {65} | {1} | {7}") + def test_xor_op(): - check_ast('{42} ^ {65}') + check_ast("{42} ^ {65}") + def test_xor_op_two(): - check_ast('{42} ^ {65} ^ {1}') + check_ast("{42} ^ {65} ^ {1}") + def test_xor_op_three(): - check_ast('{42} ^ {65} ^ {1} ^ {7}') + check_ast("{42} ^ {65} ^ {1} ^ {7}") + def test_xor_pipe(): - check_ast('{42} ^ {65} | {1}') + check_ast("{42} ^ {65} | {1}") + def test_amp_op(): - check_ast('{42} & {65}') + check_ast("{42} & {65}") + def test_amp_op_two(): - check_ast('{42} & {65} & {1}') + check_ast("{42} & {65} & {1}") + def test_amp_op_three(): - check_ast('{42} & {65} & {1} & {7}') + check_ast("{42} & {65} & {1} & {7}") + def test_lshift_op(): - check_ast('42 << 65') + check_ast("42 << 65") + def test_lshift_op_two(): - check_ast('42 << 65 << 1') + check_ast("42 << 65 << 1") + def test_lshift_op_three(): - check_ast('42 << 65 << 1 << 7') + check_ast("42 << 65 << 1 << 7") + def test_rshift_op(): - check_ast('42 >> 65') + check_ast("42 >> 65") + def test_rshift_op_two(): - check_ast('42 >> 65 >> 1') + check_ast("42 >> 65 >> 1") + def test_rshift_op_three(): - check_ast('42 >> 65 >> 1 >> 7') + check_ast("42 >> 65 >> 1 >> 7") # # statements # + def test_equals(): - check_stmts('x = 42') + check_stmts("x = 42") + def test_equals_semi(): - check_stmts('x = 42;') + check_stmts("x = 42;") + def test_x_y_equals_semi(): - check_stmts('x = y = 42') + check_stmts("x = y = 42") + def test_equals_two(): - check_stmts('x = 42; y = 65') + check_stmts("x = 42; y = 65") + def test_equals_two_semi(): - check_stmts('x = 42; y = 65;') + check_stmts("x = 42; y = 65;") + def test_equals_three(): - check_stmts('x = 42; y = 65; z = 6') + check_stmts("x = 42; y = 65; z = 6") + def test_equals_three_semi(): - check_stmts('x = 42; y = 65; z = 6;') + check_stmts("x = 42; y = 65; z = 6;") + def test_plus_eq(): - check_stmts('x = 42; x += 65') + check_stmts("x = 42; x += 65") + def test_sub_eq(): - check_stmts('x = 42; x -= 2') + check_stmts("x = 42; x -= 2") + def test_times_eq(): - check_stmts('x = 42; x *= 2') + check_stmts("x = 42; x *= 2") + @skip_if_py34 def test_matmult_eq(): - check_stmts('x @= y', False) + check_stmts("x @= y", False) + def test_div_eq(): - check_stmts('x = 42; x /= 2') + check_stmts("x = 42; x /= 2") + def test_floordiv_eq(): - check_stmts('x = 42; x //= 2') + check_stmts("x = 42; x //= 2") + def test_pow_eq(): - check_stmts('x = 42; x **= 2') + check_stmts("x = 42; x **= 2") + def test_mod_eq(): - check_stmts('x = 42; x %= 2') + check_stmts("x = 42; x %= 2") + def test_xor_eq(): - check_stmts('x = 42; x ^= 2') + check_stmts("x = 42; x ^= 2") + def test_ampersand_eq(): - check_stmts('x = 42; x &= 2') + check_stmts("x = 42; x &= 2") + def test_bitor_eq(): - check_stmts('x = 42; x |= 2') + check_stmts("x = 42; x |= 2") + def test_lshift_eq(): - check_stmts('x = 42; x <<= 2') + check_stmts("x = 42; x <<= 2") + def test_rshift_eq(): - check_stmts('x = 42; x >>= 2') + check_stmts("x = 42; x >>= 2") + def test_bare_unpack(): - check_stmts('x, y = 42, 65') + check_stmts("x, y = 42, 65") + def test_lhand_group_unpack(): - check_stmts('(x, y) = 42, 65') + check_stmts("(x, y) = 42, 65") + def test_rhand_group_unpack(): - check_stmts('x, y = (42, 65)') + check_stmts("x, y = (42, 65)") + def test_grouped_unpack(): - check_stmts('(x, y) = (42, 65)') + check_stmts("(x, y) = (42, 65)") + def test_double_grouped_unpack(): - check_stmts('(x, y) = (z, a) = (7, 8)') + check_stmts("(x, y) = (z, a) = (7, 8)") + def test_double_ungrouped_unpack(): - check_stmts('x, y = z, a = 7, 8') + check_stmts("x, y = z, a = 7, 8") + def test_stary_eq(): - check_stmts('*y, = [1, 2, 3]') + check_stmts("*y, = [1, 2, 3]") + def test_stary_x(): - check_stmts('*y, x = [1, 2, 3]') + check_stmts("*y, x = [1, 2, 3]") + def test_tuple_x_stary(): - check_stmts('(x, *y) = [1, 2, 3]') + check_stmts("(x, *y) = [1, 2, 3]") + def test_list_x_stary(): - check_stmts('[x, *y] = [1, 2, 3]') + check_stmts("[x, *y] = [1, 2, 3]") + def test_bare_x_stary(): - check_stmts('x, *y = [1, 2, 3]') + check_stmts("x, *y = [1, 2, 3]") + def test_bare_x_stary_z(): - check_stmts('x, *y, z = [1, 2, 2, 3]') + check_stmts("x, *y, z = [1, 2, 2, 3]") + def test_equals_list(): - check_stmts('x = [42]; x[0] = 65') + check_stmts("x = [42]; x[0] = 65") + def test_equals_dict(): - check_stmts('x = {42: 65}; x[42] = 3') + check_stmts("x = {42: 65}; x[42] = 3") + def test_equals_attr(): - check_stmts('class X(object):\n pass\nx = X()\nx.a = 65') + check_stmts("class X(object):\n pass\nx = X()\nx.a = 65") + def test_dict_keys(): check_stmts('x = {"x": 1}\nx.keys()') + def test_assert_msg(): check_stmts('assert True, "wow mom"') + def test_assert(): - check_stmts('assert True') + check_stmts("assert True") + def test_pass(): - check_stmts('pass') + check_stmts("pass") + def test_del(): - check_stmts('x = 42; del x') + check_stmts("x = 42; del x") + def test_del_comma(): - check_stmts('x = 42; del x,') + check_stmts("x = 42; del x,") + def test_del_two(): - check_stmts('x = 42; y = 65; del x, y') + check_stmts("x = 42; y = 65; del x, y") + def test_del_two_comma(): - check_stmts('x = 42; y = 65; del x, y,') + check_stmts("x = 42; y = 65; del x, y,") + def test_del_with_parens(): - check_stmts('x = 42; y = 65; del (x, y)') + check_stmts("x = 42; y = 65; del (x, y)") + def test_raise(): - check_stmts('raise', False) + check_stmts("raise", False) + def test_raise_x(): - check_stmts('raise TypeError', False) + check_stmts("raise TypeError", False) + def test_raise_x_from(): - check_stmts('raise TypeError from x', False) + check_stmts("raise TypeError from x", False) + def test_import_x(): - check_stmts('import x', False) + check_stmts("import x", False) + def test_import_xy(): - check_stmts('import x.y', False) + check_stmts("import x.y", False) + def test_import_xyz(): - check_stmts('import x.y.z', False) + check_stmts("import x.y.z", False) + def test_from_x_import_y(): - check_stmts('from x import y', False) + check_stmts("from x import y", False) + def test_from_dot_import_y(): - check_stmts('from . import y', False) + check_stmts("from . import y", False) + def test_from_dotx_import_y(): - check_stmts('from .x import y', False) + check_stmts("from .x import y", False) + def test_from_dotdotx_import_y(): - check_stmts('from ..x import y', False) + check_stmts("from ..x import y", False) + def test_from_dotdotdotx_import_y(): - check_stmts('from ...x import y', False) + check_stmts("from ...x import y", False) + def test_from_dotdotdotdotx_import_y(): - check_stmts('from ....x import y', False) + check_stmts("from ....x import y", False) + def test_from_import_x_y(): - check_stmts('import x, y', False) + check_stmts("import x, y", False) + def test_from_import_x_y_z(): - check_stmts('import x, y, z', False) + check_stmts("import x, y, z", False) + def test_from_dot_import_x_y(): - check_stmts('from . import x, y', False) + check_stmts("from . import x, y", False) + def test_from_dot_import_x_y_z(): - check_stmts('from . import x, y, z', False) + check_stmts("from . import x, y, z", False) + def test_from_dot_import_group_x_y(): - check_stmts('from . import (x, y)', False) + check_stmts("from . import (x, y)", False) + def test_import_x_as_y(): - check_stmts('import x as y', False) + check_stmts("import x as y", False) + def test_import_xy_as_z(): - check_stmts('import x.y as z', False) + check_stmts("import x.y as z", False) + def test_import_x_y_as_z(): - check_stmts('import x, y as z', False) + check_stmts("import x, y as z", False) + def test_import_x_as_y_z(): - check_stmts('import x as y, z', False) + check_stmts("import x as y, z", False) + def test_import_x_as_y_z_as_a(): - check_stmts('import x as y, z as a', False) + check_stmts("import x as y, z as a", False) + def test_from_dot_import_x_as_y(): - check_stmts('from . import x as y', False) + check_stmts("from . import x as y", False) + def test_from_x_import_star(): - check_stmts('from x import *', False) + check_stmts("from x import *", False) + def test_from_x_import_y_as_z(): - check_stmts('from x import y as z', False) + check_stmts("from x import y as z", False) + def test_from_x_import_y_as_z_a_as_b(): - check_stmts('from x import y as z, a as b', False) + check_stmts("from x import y as z, a as b", False) + def test_from_dotx_import_y_as_z_a_as_b_c_as_d(): - check_stmts('from .x import y as z, a as b, c as d', False) + check_stmts("from .x import y as z, a as b, c as d", False) + def test_continue(): - check_stmts('continue', False) + check_stmts("continue", False) + def test_break(): - check_stmts('break', False) + check_stmts("break", False) + def test_global(): - check_stmts('global x', False) + check_stmts("global x", False) + def test_global_xy(): - check_stmts('global x, y', False) + check_stmts("global x, y", False) + def test_nonlocal_x(): - check_stmts('nonlocal x', False) + check_stmts("nonlocal x", False) + def test_nonlocal_xy(): - check_stmts('nonlocal x, y', False) + check_stmts("nonlocal x, y", False) + def test_yield(): - check_stmts('yield', False) + check_stmts("yield", False) + def test_yield_x(): - check_stmts('yield x', False) + check_stmts("yield x", False) + def test_yield_x_comma(): - check_stmts('yield x,', False) + check_stmts("yield x,", False) + def test_yield_x_y(): - check_stmts('yield x, y', False) + check_stmts("yield x, y", False) + def test_yield_from_x(): - check_stmts('yield from x', False) + check_stmts("yield from x", False) + def test_return(): - check_stmts('return', False) + check_stmts("return", False) + def test_return_x(): - check_stmts('return x', False) + check_stmts("return x", False) + def test_return_x_comma(): - check_stmts('return x,', False) + check_stmts("return x,", False) + def test_return_x_y(): - check_stmts('return x, y', False) + check_stmts("return x, y", False) + def test_if_true(): - check_stmts('if True:\n pass') + check_stmts("if True:\n pass") + def test_if_true_twolines(): - check_stmts('if True:\n pass\n pass') + check_stmts("if True:\n pass\n pass") + def test_if_true_twolines_deindent(): - check_stmts('if True:\n pass\n pass\npass') + check_stmts("if True:\n pass\n pass\npass") + def test_if_true_else(): - check_stmts('if True:\n pass\nelse: \n pass') + check_stmts("if True:\n pass\nelse: \n pass") + def test_if_true_x(): - check_stmts('if True:\n x = 42') + check_stmts("if True:\n x = 42") + def test_if_switch(): - check_stmts('x = 42\nif x == 1:\n pass') + check_stmts("x = 42\nif x == 1:\n pass") + def test_if_switch_elif1_else(): - check_stmts('x = 42\nif x == 1:\n pass\n' - 'elif x == 2:\n pass\nelse:\n pass') + check_stmts("x = 42\nif x == 1:\n pass\n" "elif x == 2:\n pass\nelse:\n pass") + def test_if_switch_elif2_else(): - check_stmts('x = 42\nif x == 1:\n pass\n' - 'elif x == 2:\n pass\n' - 'elif x == 3:\n pass\n' - 'elif x == 4:\n pass\n' - 'else:\n pass') + check_stmts( + "x = 42\nif x == 1:\n pass\n" + "elif x == 2:\n pass\n" + "elif x == 3:\n pass\n" + "elif x == 4:\n pass\n" + "else:\n pass" + ) + def test_if_nested(): - check_stmts('x = 42\nif x == 1:\n pass\n if x == 4:\n pass') + check_stmts("x = 42\nif x == 1:\n pass\n if x == 4:\n pass") + def test_while(): - check_stmts('while False:\n pass') + check_stmts("while False:\n pass") + def test_while_else(): - check_stmts('while False:\n pass\nelse:\n pass') + check_stmts("while False:\n pass\nelse:\n pass") + def test_for(): - check_stmts('for x in range(6):\n pass') + check_stmts("for x in range(6):\n pass") + def test_for_zip(): check_stmts('for x, y in zip(range(6), "123456"):\n pass') + def test_for_idx(): - check_stmts('x = [42]\nfor x[0] in range(3):\n pass') + check_stmts("x = [42]\nfor x[0] in range(3):\n pass") + def test_for_zip_idx(): - check_stmts('x = [42]\nfor x[0], y in zip(range(6), "123456"):\n' - ' pass') + check_stmts('x = [42]\nfor x[0], y in zip(range(6), "123456"):\n' " pass") + def test_for_attr(): - check_stmts('for x.a in range(3):\n pass', False) + check_stmts("for x.a in range(3):\n pass", False) + def test_for_zip_attr(): check_stmts('for x.a, y in zip(range(6), "123456"):\n pass', False) + def test_for_else(): - check_stmts('for x in range(6):\n pass\nelse: pass') + check_stmts("for x in range(6):\n pass\nelse: pass") + @skip_if_py34 def test_async_for(): check_stmts("async def f():\n async for x in y:\n pass\n", False) + def test_with(): - check_stmts('with x:\n pass', False) + check_stmts("with x:\n pass", False) + def test_with_as(): - check_stmts('with x as y:\n pass', False) + check_stmts("with x as y:\n pass", False) + def test_with_xy(): - check_stmts('with x, y:\n pass', False) + check_stmts("with x, y:\n pass", False) + def test_with_x_as_y_z(): - check_stmts('with x as y, z:\n pass', False) + check_stmts("with x as y, z:\n pass", False) + def test_with_x_as_y_a_as_b(): - check_stmts('with x as y, a as b:\n pass', False) + check_stmts("with x as y, a as b:\n pass", False) + def test_with_in_func(): check_stmts("def f():\n with x:\n pass\n") + @skip_if_py34 def test_async_with(): check_stmts("async def f():\n async with x as y:\n pass\n", False) + def test_try(): - check_stmts('try:\n pass\nexcept:\n pass', False) + check_stmts("try:\n pass\nexcept:\n pass", False) + def test_try_except_t(): - check_stmts('try:\n pass\nexcept TypeError:\n pass', False) + check_stmts("try:\n pass\nexcept TypeError:\n pass", False) + def test_try_except_t_as_e(): - check_stmts('try:\n pass\nexcept TypeError as e:\n pass', False) + check_stmts("try:\n pass\nexcept TypeError as e:\n pass", False) + def test_try_except_t_u(): - check_stmts('try:\n pass\nexcept (TypeError, SyntaxError):\n pass', False) + check_stmts("try:\n pass\nexcept (TypeError, SyntaxError):\n pass", False) + def test_try_except_t_u_as_e(): - check_stmts('try:\n pass\nexcept (TypeError, SyntaxError) as e:\n pass', False) + check_stmts("try:\n pass\nexcept (TypeError, SyntaxError) as e:\n pass", False) + def test_try_except_t_except_u(): - check_stmts('try:\n pass\nexcept TypeError:\n pass\n' - 'except SyntaxError as f:\n pass', False) + check_stmts( + "try:\n pass\nexcept TypeError:\n pass\n" "except SyntaxError as f:\n pass", + False, + ) + def test_try_except_else(): - check_stmts('try:\n pass\nexcept:\n pass\nelse: pass', False) + check_stmts("try:\n pass\nexcept:\n pass\nelse: pass", False) + def test_try_except_finally(): - check_stmts('try:\n pass\nexcept:\n pass\nfinally: pass', False) + check_stmts("try:\n pass\nexcept:\n pass\nfinally: pass", False) + def test_try_except_else_finally(): - check_stmts('try:\n pass\nexcept:\n pass\nelse:\n pass' - '\nfinally: pass', False) + check_stmts( + "try:\n pass\nexcept:\n pass\nelse:\n pass" "\nfinally: pass", False + ) + def test_try_finally(): - check_stmts('try:\n pass\nfinally: pass', False) + check_stmts("try:\n pass\nfinally: pass", False) + def test_func(): - check_stmts('def f():\n pass') + check_stmts("def f():\n pass") + def test_func_ret(): - check_stmts('def f():\n return') + check_stmts("def f():\n return") + def test_func_ret_42(): - check_stmts('def f():\n return 42') + check_stmts("def f():\n return 42") + def test_func_ret_42_65(): - check_stmts('def f():\n return 42, 65') + check_stmts("def f():\n return 42, 65") + def test_func_rarrow(): - check_stmts('def f() -> int:\n pass') + check_stmts("def f() -> int:\n pass") + def test_func_x(): - check_stmts('def f(x):\n return x') + check_stmts("def f(x):\n return x") + def test_func_kwx(): - check_stmts('def f(x=42):\n return x') + check_stmts("def f(x=42):\n return x") + def test_func_x_y(): - check_stmts('def f(x, y):\n return x') + check_stmts("def f(x, y):\n return x") + def test_func_x_y_z(): - check_stmts('def f(x, y, z):\n return x') + check_stmts("def f(x, y, z):\n return x") + def test_func_x_kwy(): - check_stmts('def f(x, y=42):\n return x') + check_stmts("def f(x, y=42):\n return x") + def test_func_kwx_kwy(): - check_stmts('def f(x=65, y=42):\n return x') + check_stmts("def f(x=65, y=42):\n return x") + def test_func_kwx_kwy_kwz(): - check_stmts('def f(x=65, y=42, z=1):\n return x') + check_stmts("def f(x=65, y=42, z=1):\n return x") + def test_func_x_comma(): - check_stmts('def f(x,):\n return x') + check_stmts("def f(x,):\n return x") + def test_func_x_y_comma(): - check_stmts('def f(x, y,):\n return x') + check_stmts("def f(x, y,):\n return x") + def test_func_x_y_z_comma(): - check_stmts('def f(x, y, z,):\n return x') + check_stmts("def f(x, y, z,):\n return x") + def test_func_x_kwy_comma(): - check_stmts('def f(x, y=42,):\n return x') + check_stmts("def f(x, y=42,):\n return x") + def test_func_kwx_kwy_comma(): - check_stmts('def f(x=65, y=42,):\n return x') + check_stmts("def f(x=65, y=42,):\n return x") + def test_func_kwx_kwy_kwz_comma(): - check_stmts('def f(x=65, y=42, z=1,):\n return x') + check_stmts("def f(x=65, y=42, z=1,):\n return x") + def test_func_args(): - check_stmts('def f(*args):\n return 42') + check_stmts("def f(*args):\n return 42") + def test_func_args_x(): - check_stmts('def f(*args, x):\n return 42') + check_stmts("def f(*args, x):\n return 42") + def test_func_args_x_y(): - check_stmts('def f(*args, x, y):\n return 42') + check_stmts("def f(*args, x, y):\n return 42") + def test_func_args_x_kwy(): - check_stmts('def f(*args, x, y=10):\n return 42') + check_stmts("def f(*args, x, y=10):\n return 42") + def test_func_args_kwx_y(): - check_stmts('def f(*args, x=10, y):\n return 42') + check_stmts("def f(*args, x=10, y):\n return 42") + def test_func_args_kwx_kwy(): - check_stmts('def f(*args, x=42, y=65):\n return 42') + check_stmts("def f(*args, x=42, y=65):\n return 42") + def test_func_x_args(): - check_stmts('def f(x, *args):\n return 42') + check_stmts("def f(x, *args):\n return 42") + def test_func_x_args_y(): - check_stmts('def f(x, *args, y):\n return 42') + check_stmts("def f(x, *args, y):\n return 42") + def test_func_x_args_y_z(): - check_stmts('def f(x, *args, y, z):\n return 42') + check_stmts("def f(x, *args, y, z):\n return 42") + def test_func_kwargs(): - check_stmts('def f(**kwargs):\n return 42') + check_stmts("def f(**kwargs):\n return 42") + def test_func_x_kwargs(): - check_stmts('def f(x, **kwargs):\n return 42') + check_stmts("def f(x, **kwargs):\n return 42") + def test_func_x_y_kwargs(): - check_stmts('def f(x, y, **kwargs):\n return 42') + check_stmts("def f(x, y, **kwargs):\n return 42") + def test_func_x_kwy_kwargs(): - check_stmts('def f(x, y=42, **kwargs):\n return 42') + check_stmts("def f(x, y=42, **kwargs):\n return 42") + def test_func_args_kwargs(): - check_stmts('def f(*args, **kwargs):\n return 42') + check_stmts("def f(*args, **kwargs):\n return 42") + def test_func_x_args_kwargs(): - check_stmts('def f(x, *args, **kwargs):\n return 42') + check_stmts("def f(x, *args, **kwargs):\n return 42") + def test_func_x_y_args_kwargs(): - check_stmts('def f(x, y, *args, **kwargs):\n return 42') + check_stmts("def f(x, y, *args, **kwargs):\n return 42") + def test_func_kwx_args_kwargs(): - check_stmts('def f(x=10, *args, **kwargs):\n return 42') + check_stmts("def f(x=10, *args, **kwargs):\n return 42") + def test_func_x_kwy_args_kwargs(): - check_stmts('def f(x, y=42, *args, **kwargs):\n return 42') + check_stmts("def f(x, y=42, *args, **kwargs):\n return 42") + def test_func_x_args_y_kwargs(): - check_stmts('def f(x, *args, y, **kwargs):\n return 42') + check_stmts("def f(x, *args, y, **kwargs):\n return 42") + def test_func_x_args_kwy_kwargs(): - check_stmts('def f(x, *args, y=42, **kwargs):\n return 42') + check_stmts("def f(x, *args, y=42, **kwargs):\n return 42") + def test_func_args_y_kwargs(): - check_stmts('def f(*args, y, **kwargs):\n return 42') + check_stmts("def f(*args, y, **kwargs):\n return 42") + def test_func_star_x(): - check_stmts('def f(*, x):\n return 42') + check_stmts("def f(*, x):\n return 42") + def test_func_star_x_y(): - check_stmts('def f(*, x, y):\n return 42') + check_stmts("def f(*, x, y):\n return 42") + def test_func_star_x_kwargs(): - check_stmts('def f(*, x, **kwargs):\n return 42') + check_stmts("def f(*, x, **kwargs):\n return 42") + def test_func_star_kwx_kwargs(): - check_stmts('def f(*, x=42, **kwargs):\n return 42') + check_stmts("def f(*, x=42, **kwargs):\n return 42") + def test_func_x_star_y(): - check_stmts('def f(x, *, y):\n return 42') + check_stmts("def f(x, *, y):\n return 42") + def test_func_x_y_star_z(): - check_stmts('def f(x, y, *, z):\n return 42') + check_stmts("def f(x, y, *, z):\n return 42") + def test_func_x_kwy_star_y(): - check_stmts('def f(x, y=42, *, z):\n return 42') + check_stmts("def f(x, y=42, *, z):\n return 42") + def test_func_x_kwy_star_kwy(): - check_stmts('def f(x, y=42, *, z=65):\n return 42') + check_stmts("def f(x, y=42, *, z=65):\n return 42") + def test_func_x_star_y_kwargs(): - check_stmts('def f(x, *, y, **kwargs):\n return 42') + check_stmts("def f(x, *, y, **kwargs):\n return 42") + def test_func_tx(): - check_stmts('def f(x:int):\n return x') + check_stmts("def f(x:int):\n return x") + def test_func_txy(): - check_stmts('def f(x:int, y:float=10.0):\n return x') + check_stmts("def f(x:int, y:float=10.0):\n return x") + def test_class(): - check_stmts('class X:\n pass') + check_stmts("class X:\n pass") + def test_class_obj(): - check_stmts('class X(object):\n pass') + check_stmts("class X(object):\n pass") + def test_class_int_flt(): - check_stmts('class X(int, object):\n pass') + check_stmts("class X(int, object):\n pass") + def test_class_obj_kw(): # technically valid syntax, though it will fail to compile - check_stmts('class X(object=5):\n pass', False) + check_stmts("class X(object=5):\n pass", False) + def test_decorator(): - check_stmts('@g\ndef f():\n pass', False) + check_stmts("@g\ndef f():\n pass", False) + def test_decorator_2(): - check_stmts('@h\n@g\ndef f():\n pass', False) + check_stmts("@h\n@g\ndef f():\n pass", False) + def test_decorator_call(): - check_stmts('@g()\ndef f():\n pass', False) + check_stmts("@g()\ndef f():\n pass", False) + def test_decorator_call_args(): - check_stmts('@g(x, y=10)\ndef f():\n pass', False) + check_stmts("@g(x, y=10)\ndef f():\n pass", False) + def test_decorator_dot_call_args(): - check_stmts('@h.g(x, y=10)\ndef f():\n pass', False) + check_stmts("@h.g(x, y=10)\ndef f():\n pass", False) + def test_decorator_dot_dot_call_args(): - check_stmts('@i.h.g(x, y=10)\ndef f():\n pass', False) + check_stmts("@i.h.g(x, y=10)\ndef f():\n pass", False) + def test_broken_prompt_func(): - code = ('def prompt():\n' - " return '{user}'.format(\n" - " user='me')\n") + code = "def prompt():\n" " return '{user}'.format(\n" " user='me')\n" check_stmts(code, False) + def test_class_with_methods(): - code = ('class Test:\n' - ' def __init__(self):\n' - ' self.msg("hello world")\n' - ' def msg(self, m):\n' - ' print(m)\n') + code = ( + "class Test:\n" + " def __init__(self):\n" + ' self.msg("hello world")\n' + " def msg(self, m):\n" + " print(m)\n" + ) check_stmts(code, False) + def test_nested_functions(): - code = ('def test(x):\n' - ' def test2(y):\n' - ' return y+x\n' - ' return test2\n') + code = ( + "def test(x):\n" + " def test2(y):\n" + " return y+x\n" + " return test2\n" + ) check_stmts(code, False) + def test_function_blank_line(): - code = ('def foo():\n' - ' ascii_art = [\n' - ' "(╯°□°)╯︵ ┻━┻",\n' - ' "¯\\_(ツ)_/¯",\n' - ' "┻━┻︵ \\(°□°)/ ︵ ┻━┻",\n' - ' ]\n' - '\n' - ' import random\n' - ' i = random.randint(0,len(ascii_art)) - 1\n' - ' print(" Get to work!")\n' - ' print(ascii_art[i])\n') + code = ( + "def foo():\n" + " ascii_art = [\n" + ' "(╯°□°)╯︵ ┻━┻",\n' + ' "¯\\_(ツ)_/¯",\n' + ' "┻━┻︵ \\(°□°)/ ︵ ┻━┻",\n' + " ]\n" + "\n" + " import random\n" + " i = random.randint(0,len(ascii_art)) - 1\n" + ' print(" Get to work!")\n' + " print(ascii_art[i])\n" + ) check_stmts(code, False) @skip_if_py34 def test_async_func(): - check_stmts('async def f():\n pass\n') + check_stmts("async def f():\n pass\n") + @skip_if_py34 def test_async_decorator(): - check_stmts('@g\nasync def f():\n pass', False) + check_stmts("@g\nasync def f():\n pass", False) + @skip_if_py34 def test_async_await(): check_stmts("async def f():\n await fut\n", False) + # # Xonsh specific syntax # @@ -1524,383 +1993,577 @@ def test_path_literal(): check_xonsh_ast({}, 'pR"/foo"', False) check_xonsh_ast({}, 'Rp"/foo"', False) + def test_dollar_name(): - check_xonsh_ast({'WAKKA': 42}, '$WAKKA') + check_xonsh_ast({"WAKKA": 42}, "$WAKKA") + def test_dollar_py(): - check_xonsh({'WAKKA': 42}, 'x = "WAKKA"; y = ${x}') + check_xonsh({"WAKKA": 42}, 'x = "WAKKA"; y = ${x}') + def test_dollar_py_test(): - check_xonsh_ast({'WAKKA': 42}, '${None or "WAKKA"}') + check_xonsh_ast({"WAKKA": 42}, '${None or "WAKKA"}') + def test_dollar_py_recursive_name(): - check_xonsh_ast({'WAKKA': 42, 'JAWAKA': 'WAKKA'}, '${$JAWAKA}') + check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, "${$JAWAKA}") + def test_dollar_py_test_recursive_name(): - check_xonsh_ast({'WAKKA': 42, 'JAWAKA': 'WAKKA'}, '${None or $JAWAKA}') + check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, "${None or $JAWAKA}") + def test_dollar_py_test_recursive_test(): - check_xonsh_ast({'WAKKA': 42, 'JAWAKA': 'WAKKA'}, - '${${"JAWA" + $JAWAKA[-2:]}}') + check_xonsh_ast({"WAKKA": 42, "JAWAKA": "WAKKA"}, '${${"JAWA" + $JAWAKA[-2:]}}') + def test_dollar_name_set(): - check_xonsh({'WAKKA': 42}, '$WAKKA = 42') + check_xonsh({"WAKKA": 42}, "$WAKKA = 42") + def test_dollar_py_set(): - check_xonsh({'WAKKA': 42}, 'x = "WAKKA"; ${x} = 65') + check_xonsh({"WAKKA": 42}, 'x = "WAKKA"; ${x} = 65') + def test_dollar_sub(): - check_xonsh_ast({}, '$(ls)', False) + check_xonsh_ast({}, "$(ls)", False) + def test_dollar_sub_space(): - check_xonsh_ast({}, '$(ls )', False) + check_xonsh_ast({}, "$(ls )", False) + def test_ls_dot(): - check_xonsh_ast({}, '$(ls .)', False) + check_xonsh_ast({}, "$(ls .)", False) + def test_lambda_in_atparens(): - check_xonsh_ast({}, '$(echo hello | @(lambda a, s=None: "hey!") foo bar baz)', False) + check_xonsh_ast( + {}, '$(echo hello | @(lambda a, s=None: "hey!") foo bar baz)', False + ) + def test_generator_in_atparens(): - check_xonsh_ast({}, '$(echo @(i**2 for i in range(20)))', False) + check_xonsh_ast({}, "$(echo @(i**2 for i in range(20)))", False) + def test_bare_tuple_in_atparens(): check_xonsh_ast({}, '$(echo @("a", 7))', False) + def test_nested_madness(): - check_xonsh_ast({}, '$(@$(which echo) ls | @(lambda a, s=None: $(@(s.strip()) @(a[1]))) foo -la baz)', False) + check_xonsh_ast( + {}, + "$(@$(which echo) ls | @(lambda a, s=None: $(@(s.strip()) @(a[1]))) foo -la baz)", + False, + ) + def test_ls_dot_nesting(): check_xonsh_ast({}, '$(ls @(None or "."))', False) + def test_ls_dot_nesting_var(): check_xonsh({}, 'x = "."; $(ls @(None or x))', False) + def test_ls_dot_str(): check_xonsh_ast({}, '$(ls ".")', False) + def test_ls_nest_ls(): - check_xonsh_ast({}, '$(ls $(ls))', False) + check_xonsh_ast({}, "$(ls $(ls))", False) + def test_ls_nest_ls_dashl(): - check_xonsh_ast({}, '$(ls $(ls) -l)', False) + check_xonsh_ast({}, "$(ls $(ls) -l)", False) + def test_ls_envvar_strval(): - check_xonsh_ast({'WAKKA': '.'}, '$(ls $WAKKA)', False) + check_xonsh_ast({"WAKKA": "."}, "$(ls $WAKKA)", False) + def test_ls_envvar_listval(): - check_xonsh_ast({'WAKKA': ['.', '.']}, '$(ls $WAKKA)', False) + check_xonsh_ast({"WAKKA": [".", "."]}, "$(ls $WAKKA)", False) + def test_bang_sub(): - check_xonsh_ast({}, '!(ls)', False) + check_xonsh_ast({}, "!(ls)", False) + def test_bang_sub_space(): - check_xonsh_ast({}, '!(ls )', False) + check_xonsh_ast({}, "!(ls )", False) + def test_bang_ls_dot(): - check_xonsh_ast({}, '!(ls .)', False) + check_xonsh_ast({}, "!(ls .)", False) + def test_bang_ls_dot_nesting(): check_xonsh_ast({}, '!(ls @(None or "."))', False) + def test_bang_ls_dot_nesting_var(): check_xonsh({}, 'x = "."; !(ls @(None or x))', False) + def test_bang_ls_dot_str(): check_xonsh_ast({}, '!(ls ".")', False) + def test_bang_ls_nest_ls(): - check_xonsh_ast({}, '!(ls $(ls))', False) + check_xonsh_ast({}, "!(ls $(ls))", False) + def test_bang_ls_nest_ls_dashl(): - check_xonsh_ast({}, '!(ls $(ls) -l)', False) + check_xonsh_ast({}, "!(ls $(ls) -l)", False) + def test_bang_ls_envvar_strval(): - check_xonsh_ast({'WAKKA': '.'}, '!(ls $WAKKA)', False) + check_xonsh_ast({"WAKKA": "."}, "!(ls $WAKKA)", False) + def test_bang_ls_envvar_listval(): - check_xonsh_ast({'WAKKA': ['.', '.']}, '!(ls $WAKKA)', False) + check_xonsh_ast({"WAKKA": [".", "."]}, "!(ls $WAKKA)", False) + def test_question(): - check_xonsh_ast({}, 'range?') + check_xonsh_ast({}, "range?") + def test_dobquestion(): - check_xonsh_ast({}, 'range??') + check_xonsh_ast({}, "range??") + def test_question_chain(): - check_xonsh_ast({}, 'range?.index?') + check_xonsh_ast({}, "range?.index?") + def test_ls_regex(): - check_xonsh_ast({}, '$(ls `[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls `[Ff]+i*LE` -l)", False) + def test_backtick(): - check_xonsh_ast({}, 'print(`.*`)', False) + check_xonsh_ast({}, "print(`.*`)", False) + def test_ls_regex_octothorpe(): - check_xonsh_ast({}, '$(ls `#[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls `#[Ff]+i*LE` -l)", False) + def test_ls_explicitregex(): - check_xonsh_ast({}, '$(ls r`[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls r`[Ff]+i*LE` -l)", False) + def test_rbacktick(): - check_xonsh_ast({}, 'print(r`.*`)', False) + check_xonsh_ast({}, "print(r`.*`)", False) + def test_ls_explicitregex_octothorpe(): - check_xonsh_ast({}, '$(ls r`#[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls r`#[Ff]+i*LE` -l)", False) + def test_ls_glob(): - check_xonsh_ast({}, '$(ls g`[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls g`[Ff]+i*LE` -l)", False) + def test_gbacktick(): - check_xonsh_ast({}, 'print(g`.*`)', False) + check_xonsh_ast({}, "print(g`.*`)", False) + def test_pbacktrick(): - check_xonsh_ast({}, 'print(p`.*`)', False) + check_xonsh_ast({}, "print(p`.*`)", False) + def test_pgbacktick(): - check_xonsh_ast({}, 'print(pg`.*`)', False) + check_xonsh_ast({}, "print(pg`.*`)", False) + def test_prbacktick(): - check_xonsh_ast({}, 'print(pr`.*`)', False) + check_xonsh_ast({}, "print(pr`.*`)", False) + def test_ls_glob_octothorpe(): - check_xonsh_ast({}, '$(ls g`#[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls g`#[Ff]+i*LE` -l)", False) + def test_ls_customsearch(): - check_xonsh_ast({}, '$(ls @foo`[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls @foo`[Ff]+i*LE` -l)", False) + def test_custombacktick(): - check_xonsh_ast({}, 'print(@foo`.*`)', False) + check_xonsh_ast({}, "print(@foo`.*`)", False) + def test_ls_customsearch_octothorpe(): - check_xonsh_ast({}, '$(ls @foo`#[Ff]+i*LE` -l)', False) + check_xonsh_ast({}, "$(ls @foo`#[Ff]+i*LE` -l)", False) + def test_injection(): - check_xonsh_ast({}, '$[@$(which python)]', False) + check_xonsh_ast({}, "$[@$(which python)]", False) + def test_rhs_nested_injection(): - check_xonsh_ast({}, '$[ls @$(dirname @$(which python))]', False) + check_xonsh_ast({}, "$[ls @$(dirname @$(which python))]", False) + def test_backtick_octothorpe(): - check_xonsh_ast({}, 'print(`#.*`)', False) + check_xonsh_ast({}, "print(`#.*`)", False) + def test_uncaptured_sub(): - check_xonsh_ast({}, '$[ls]', False) + check_xonsh_ast({}, "$[ls]", False) + def test_hiddenobj_sub(): - check_xonsh_ast({}, '![ls]', False) + check_xonsh_ast({}, "![ls]", False) + def test_slash_envarv_echo(): - check_xonsh_ast({}, '![echo $HOME/place]', False) + check_xonsh_ast({}, "![echo $HOME/place]", False) + def test_echo_double_eq(): - check_xonsh_ast({}, '![echo yo==yo]', False) + check_xonsh_ast({}, "![echo yo==yo]", False) + def test_bang_two_cmds_one_pipe(): - check_xonsh_ast({}, '!(ls | grep wakka)', False) + check_xonsh_ast({}, "!(ls | grep wakka)", False) + def test_bang_three_cmds_two_pipes(): - check_xonsh_ast({}, '!(ls | grep wakka | grep jawaka)', False) + check_xonsh_ast({}, "!(ls | grep wakka | grep jawaka)", False) + def test_bang_one_cmd_write(): - check_xonsh_ast({}, '!(ls > x.py)', False) + check_xonsh_ast({}, "!(ls > x.py)", False) + def test_bang_one_cmd_append(): - check_xonsh_ast({}, '!(ls >> x.py)', False) + check_xonsh_ast({}, "!(ls >> x.py)", False) + def test_bang_two_cmds_write(): - check_xonsh_ast({}, '!(ls | grep wakka > x.py)', False) + check_xonsh_ast({}, "!(ls | grep wakka > x.py)", False) + def test_bang_two_cmds_append(): - check_xonsh_ast({}, '!(ls | grep wakka >> x.py)', False) + check_xonsh_ast({}, "!(ls | grep wakka >> x.py)", False) + def test_bang_cmd_background(): - check_xonsh_ast({}, '!(emacs ugggh &)', False) + check_xonsh_ast({}, "!(emacs ugggh &)", False) + def test_bang_cmd_background_nospace(): - check_xonsh_ast({}, '!(emacs ugggh&)', False) + check_xonsh_ast({}, "!(emacs ugggh&)", False) + def test_bang_git_quotes_no_space(): check_xonsh_ast({}, '![git commit -am "wakka"]', False) + def test_bang_git_quotes_space(): check_xonsh_ast({}, '![git commit -am "wakka jawaka"]', False) + def test_bang_git_two_quotes_space(): - check_xonsh({}, '![git commit -am "wakka jawaka"]\n' - '![git commit -am "flock jawaka"]\n', False) + check_xonsh( + {}, + '![git commit -am "wakka jawaka"]\n' '![git commit -am "flock jawaka"]\n', + False, + ) + def test_bang_git_two_quotes_space_space(): - check_xonsh({}, '![git commit -am "wakka jawaka" ]\n' - '![git commit -am "flock jawaka milwaka" ]\n', False) + check_xonsh( + {}, + '![git commit -am "wakka jawaka" ]\n' + '![git commit -am "flock jawaka milwaka" ]\n', + False, + ) + def test_bang_ls_quotes_3_space(): check_xonsh_ast({}, '![ls "wakka jawaka baraka"]', False) + def test_two_cmds_one_pipe(): - check_xonsh_ast({}, '$(ls | grep wakka)', False) + check_xonsh_ast({}, "$(ls | grep wakka)", False) + def test_three_cmds_two_pipes(): - check_xonsh_ast({}, '$(ls | grep wakka | grep jawaka)', False) + check_xonsh_ast({}, "$(ls | grep wakka | grep jawaka)", False) + def test_two_cmds_one_and_brackets(): - check_xonsh_ast({}, '![ls me] and ![grep wakka]', False) + check_xonsh_ast({}, "![ls me] and ![grep wakka]", False) + def test_three_cmds_two_ands(): - check_xonsh_ast({}, '![ls] and ![grep wakka] and ![grep jawaka]', False) + check_xonsh_ast({}, "![ls] and ![grep wakka] and ![grep jawaka]", False) + def test_two_cmds_one_doubleamps(): - check_xonsh_ast({}, '![ls] && ![grep wakka]', False) + check_xonsh_ast({}, "![ls] && ![grep wakka]", False) + def test_three_cmds_two_doubleamps(): - check_xonsh_ast({}, '![ls] && ![grep wakka] && ![grep jawaka]', False) + check_xonsh_ast({}, "![ls] && ![grep wakka] && ![grep jawaka]", False) + def test_two_cmds_one_or(): - check_xonsh_ast({}, '![ls] or ![grep wakka]', False) + check_xonsh_ast({}, "![ls] or ![grep wakka]", False) + def test_three_cmds_two_ors(): - check_xonsh_ast({}, '![ls] or ![grep wakka] or ![grep jawaka]', False) + check_xonsh_ast({}, "![ls] or ![grep wakka] or ![grep jawaka]", False) + def test_two_cmds_one_doublepipe(): - check_xonsh_ast({}, '![ls] || ![grep wakka]', False) + check_xonsh_ast({}, "![ls] || ![grep wakka]", False) + def test_three_cmds_two_doublepipe(): - check_xonsh_ast({}, '![ls] || ![grep wakka] || ![grep jawaka]', False) + check_xonsh_ast({}, "![ls] || ![grep wakka] || ![grep jawaka]", False) + def test_one_cmd_write(): - check_xonsh_ast({}, '$(ls > x.py)', False) + check_xonsh_ast({}, "$(ls > x.py)", False) + def test_one_cmd_append(): - check_xonsh_ast({}, '$(ls >> x.py)', False) + check_xonsh_ast({}, "$(ls >> x.py)", False) + def test_two_cmds_write(): - check_xonsh_ast({}, '$(ls | grep wakka > x.py)', False) + check_xonsh_ast({}, "$(ls | grep wakka > x.py)", False) + def test_two_cmds_append(): - check_xonsh_ast({}, '$(ls | grep wakka >> x.py)', False) + check_xonsh_ast({}, "$(ls | grep wakka >> x.py)", False) + def test_cmd_background(): - check_xonsh_ast({}, '$(emacs ugggh &)', False) + check_xonsh_ast({}, "$(emacs ugggh &)", False) + def test_cmd_background_nospace(): - check_xonsh_ast({}, '$(emacs ugggh&)', False) + check_xonsh_ast({}, "$(emacs ugggh&)", False) + def test_git_quotes_no_space(): check_xonsh_ast({}, '$[git commit -am "wakka"]', False) + def test_git_quotes_space(): check_xonsh_ast({}, '$[git commit -am "wakka jawaka"]', False) + def test_git_two_quotes_space(): - check_xonsh({}, '$[git commit -am "wakka jawaka"]\n' - '$[git commit -am "flock jawaka"]\n', False) + check_xonsh( + {}, + '$[git commit -am "wakka jawaka"]\n' '$[git commit -am "flock jawaka"]\n', + False, + ) + def test_git_two_quotes_space_space(): - check_xonsh({}, '$[git commit -am "wakka jawaka" ]\n' - '$[git commit -am "flock jawaka milwaka" ]\n', False) + check_xonsh( + {}, + '$[git commit -am "wakka jawaka" ]\n' + '$[git commit -am "flock jawaka milwaka" ]\n', + False, + ) + def test_ls_quotes_3_space(): check_xonsh_ast({}, '$[ls "wakka jawaka baraka"]', False) + def test_echo_comma(): - check_xonsh_ast({}, '![echo ,]', False) + check_xonsh_ast({}, "![echo ,]", False) + def test_echo_internal_comma(): - check_xonsh_ast({}, '![echo 1,2]', False) + check_xonsh_ast({}, "![echo 1,2]", False) + def test_comment_only(): - check_xonsh_ast({}, '# hello') + check_xonsh_ast({}, "# hello") + def test_echo_slash_question(): - check_xonsh_ast({}, '![echo /?]', False) + check_xonsh_ast({}, "![echo /?]", False) + def test_bad_quotes(): with pytest.raises(SyntaxError): check_xonsh_ast({}, '![echo """hello]', False) + def test_redirect(): - assert check_xonsh_ast({}, '$[cat < input.txt]', False) - assert check_xonsh_ast({}, '$[< input.txt cat]', False) + assert check_xonsh_ast({}, "$[cat < input.txt]", False) + assert check_xonsh_ast({}, "$[< input.txt cat]", False) -@pytest.mark.parametrize('case', [ - '![(cat)]', - '![(cat;)]', - '![(cd path; ls; cd)]', - '![(echo "abc"; sleep 1; echo "def")]', - '![(echo "abc"; sleep 1; echo "def") | grep abc]', - '![(if True:\n ls\nelse:\n echo not true)]', -]) +@pytest.mark.parametrize( + "case", + [ + "![(cat)]", + "![(cat;)]", + "![(cd path; ls; cd)]", + '![(echo "abc"; sleep 1; echo "def")]', + '![(echo "abc"; sleep 1; echo "def") | grep abc]', + "![(if True:\n ls\nelse:\n echo not true)]", + ], +) def test_use_subshell(case): check_xonsh_ast({}, case, False, debug_level=0) -@pytest.mark.parametrize('case', [ - '$[cat < /path/to/input.txt]', - '$[(cat) < /path/to/input.txt]', - '$[< /path/to/input.txt cat]', - '![< /path/to/input.txt]', - '![< /path/to/input.txt > /path/to/output.txt]', -]) +@pytest.mark.parametrize( + "case", + [ + "$[cat < /path/to/input.txt]", + "$[(cat) < /path/to/input.txt]", + "$[< /path/to/input.txt cat]", + "![< /path/to/input.txt]", + "![< /path/to/input.txt > /path/to/output.txt]", + ], +) def test_redirect_abspath(case): assert check_xonsh_ast({}, case, False) -@pytest.mark.parametrize('case', ['', 'o', 'out', '1']) +@pytest.mark.parametrize("case", ["", "o", "out", "1"]) def test_redirect_output(case): assert check_xonsh_ast({}, '$[echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False) + assert check_xonsh_ast( + {}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False + ) + assert check_xonsh_ast( + {}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False + ) -@pytest.mark.parametrize('case', ['e', 'err', '2']) + +@pytest.mark.parametrize("case", ["e", "err", "2"]) def test_redirect_error(case): assert check_xonsh_ast({}, '$[echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False) + assert check_xonsh_ast( + {}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False + ) + assert check_xonsh_ast( + {}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False + ) -@pytest.mark.parametrize('case', ['a', 'all', '&']) + +@pytest.mark.parametrize("case", ["a", "all", "&"]) def test_redirect_all(case): assert check_xonsh_ast({}, '$[echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False) - assert check_xonsh_ast({}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False) + assert check_xonsh_ast( + {}, '$[< input.txt echo "test" {}> test.txt]'.format(case), False + ) + assert check_xonsh_ast( + {}, '$[echo "test" {}> test.txt < input.txt]'.format(case), False + ) -@pytest.mark.parametrize('r', - ['e>o', 'e>out', 'err>o', - '2>1', 'e>1', 'err>1', '2>out', - '2>o', 'err>&1', 'e>&1', '2>&1' -]) -@pytest.mark.parametrize('o', ['', 'o', 'out', '1']) + +@pytest.mark.parametrize( + "r", + [ + "e>o", + "e>out", + "err>o", + "2>1", + "e>1", + "err>1", + "2>out", + "2>o", + "err>&1", + "e>&1", + "2>&1", + ], +) +@pytest.mark.parametrize("o", ["", "o", "out", "1"]) def test_redirect_error_to_output(r, o): assert check_xonsh_ast({}, '$[echo "test" {} {}> test.txt]'.format(r, o), False) - assert check_xonsh_ast({}, '$[< input.txt echo "test" {} {}> test.txt]'.format(r, o), False) - assert check_xonsh_ast({}, '$[echo "test" {} {}> test.txt < input.txt]'.format(r, o), False) + assert check_xonsh_ast( + {}, '$[< input.txt echo "test" {} {}> test.txt]'.format(r, o), False + ) + assert check_xonsh_ast( + {}, '$[echo "test" {} {}> test.txt < input.txt]'.format(r, o), False + ) -@pytest.mark.parametrize('r', - ['o>e', 'o>err', 'out>e', - '1>2', 'o>2', 'out>2', '1>err', - '1>e', 'out>&2', 'o>&2', '1>&2' -]) -@pytest.mark.parametrize('e', ['e', 'err', '2']) + +@pytest.mark.parametrize( + "r", + [ + "o>e", + "o>err", + "out>e", + "1>2", + "o>2", + "out>2", + "1>err", + "1>e", + "out>&2", + "o>&2", + "1>&2", + ], +) +@pytest.mark.parametrize("e", ["e", "err", "2"]) def test_redirect_output_to_error(r, e): assert check_xonsh_ast({}, '$[echo "test" {} {}> test.txt]'.format(r, e), False) - assert check_xonsh_ast({}, '$[< input.txt echo "test" {} {}> test.txt]'.format(r, e), False) - assert check_xonsh_ast({}, '$[echo "test" {} {}> test.txt < input.txt]'.format(r, e), False) + assert check_xonsh_ast( + {}, '$[< input.txt echo "test" {} {}> test.txt]'.format(r, e), False + ) + assert check_xonsh_ast( + {}, '$[echo "test" {} {}> test.txt < input.txt]'.format(r, e), False + ) + def test_macro_call_empty(): - assert check_xonsh_ast({}, 'f!()', False) + assert check_xonsh_ast({}, "f!()", False) MACRO_ARGS = [ - 'x', 'True', 'None', 'import os', 'x=10', '"oh no, mom"', '...', ' ... ', - 'if True:\n pass', '{x: y}', '{x: y, 42: 5}', '{1, 2, 3,}', '(x,y)', - '(x, y)', '((x, y), z)', 'g()', 'range(10)', 'range(1, 10, 2)', '()', '{}', - '[]', '[1, 2]', '@(x)', '!(ls -l)', '![ls -l]', '$(ls -l)', '${x + y}', - '$[ls -l]', '@$(which xonsh)', + "x", + "True", + "None", + "import os", + "x=10", + '"oh no, mom"', + "...", + " ... ", + "if True:\n pass", + "{x: y}", + "{x: y, 42: 5}", + "{1, 2, 3,}", + "(x,y)", + "(x, y)", + "((x, y), z)", + "g()", + "range(10)", + "range(1, 10, 2)", + "()", + "{}", + "[]", + "[1, 2]", + "@(x)", + "!(ls -l)", + "![ls -l]", + "$(ls -l)", + "${x + y}", + "$[ls -l]", + "@$(which xonsh)", ] -@pytest.mark.parametrize('s', MACRO_ARGS) + +@pytest.mark.parametrize("s", MACRO_ARGS) def test_macro_call_one_arg(s): - f = 'f!({})'.format(s) + f = "f!({})".format(s) tree = check_xonsh_ast({}, f, False, return_obs=True) assert isinstance(tree, AST) args = tree.body.args[1].elts @@ -1908,10 +2571,9 @@ def test_macro_call_one_arg(s): assert args[0].s == s.strip() -@pytest.mark.parametrize('s,t', itertools.product(MACRO_ARGS[::2], - MACRO_ARGS[1::2])) +@pytest.mark.parametrize("s,t", itertools.product(MACRO_ARGS[::2], MACRO_ARGS[1::2])) def test_macro_call_two_args(s, t): - f = 'f!({}, {})'.format(s, t) + f = "f!({}, {})".format(s, t) tree = check_xonsh_ast({}, f, False, return_obs=True) assert isinstance(tree, AST) args = tree.body.args[1].elts @@ -1920,11 +2582,11 @@ def test_macro_call_two_args(s, t): assert args[1].s == t.strip() -@pytest.mark.parametrize('s,t,u', itertools.product(MACRO_ARGS[::3], - MACRO_ARGS[1::3], - MACRO_ARGS[2::3])) +@pytest.mark.parametrize( + "s,t,u", itertools.product(MACRO_ARGS[::3], MACRO_ARGS[1::3], MACRO_ARGS[2::3]) +) def test_macro_call_three_args(s, t, u): - f = 'f!({}, {}, {})'.format(s, t, u) + f = "f!({}, {}, {})".format(s, t, u) tree = check_xonsh_ast({}, f, False, return_obs=True) assert isinstance(tree, AST) args = tree.body.args[1].elts @@ -1934,9 +2596,9 @@ def test_macro_call_three_args(s, t, u): assert args[2].s == u.strip() -@pytest.mark.parametrize('s', MACRO_ARGS) +@pytest.mark.parametrize("s", MACRO_ARGS) def test_macro_call_one_trailing(s): - f = 'f!({0},)'.format(s) + f = "f!({0},)".format(s) tree = check_xonsh_ast({}, f, False, return_obs=True) assert isinstance(tree, AST) args = tree.body.args[1].elts @@ -1944,9 +2606,9 @@ def test_macro_call_one_trailing(s): assert args[0].s == s.strip() -@pytest.mark.parametrize('s', MACRO_ARGS) +@pytest.mark.parametrize("s", MACRO_ARGS) def test_macro_call_one_trailing_space(s): - f = 'f!( {0}, )'.format(s) + f = "f!( {0}, )".format(s) tree = check_xonsh_ast({}, f, False, return_obs=True) assert isinstance(tree, AST) args = tree.body.args[1].elts @@ -1954,112 +2616,110 @@ def test_macro_call_one_trailing_space(s): assert args[0].s == s.strip() -SUBPROC_MACRO_OC = [ - ('!(', ')'), - ('$(', ')'), - ('![', ']'), - ('$[', ']'), - ] +SUBPROC_MACRO_OC = [("!(", ")"), ("$(", ")"), ("![", "]"), ("$[", "]")] -@pytest.mark.parametrize('opener, closer', SUBPROC_MACRO_OC) -@pytest.mark.parametrize('body', ['echo!', 'echo !', 'echo ! ']) + +@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC) +@pytest.mark.parametrize("body", ["echo!", "echo !", "echo ! "]) def test_empty_subprocbang(opener, closer, body): tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True) assert isinstance(tree, AST) cmd = tree.body.args[0].elts assert len(cmd) == 2 - assert cmd[1].s == '' + assert cmd[1].s == "" -@pytest.mark.parametrize('opener, closer', SUBPROC_MACRO_OC) -@pytest.mark.parametrize('body', ['echo!x', 'echo !x', 'echo !x', 'echo ! x']) +@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC) +@pytest.mark.parametrize("body", ["echo!x", "echo !x", "echo !x", "echo ! x"]) def test_single_subprocbang(opener, closer, body): tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True) assert isinstance(tree, AST) cmd = tree.body.args[0].elts assert len(cmd) == 2 - assert cmd[1].s == 'x' + assert cmd[1].s == "x" -@pytest.mark.parametrize('opener, closer', SUBPROC_MACRO_OC) -@pytest.mark.parametrize('body', ['echo -n!x', 'echo -n!x', 'echo -n !x', - 'echo -n ! x']) +@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC) +@pytest.mark.parametrize( + "body", ["echo -n!x", "echo -n!x", "echo -n !x", "echo -n ! x"] +) def test_arg_single_subprocbang(opener, closer, body): tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True) assert isinstance(tree, AST) cmd = tree.body.args[0].elts assert len(cmd) == 3 - assert cmd[2].s == 'x' + assert cmd[2].s == "x" -@pytest.mark.parametrize('opener, closer', SUBPROC_MACRO_OC) -@pytest.mark.parametrize('ipener, iloser', [ - ('$(', ')'), - ('@$(', ')'), - ('$[', ']'), - ]) -@pytest.mark.parametrize('body', ['echo -n!x', 'echo -n!x', 'echo -n !x', - 'echo -n ! x']) +@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC) +@pytest.mark.parametrize("ipener, iloser", [("$(", ")"), ("@$(", ")"), ("$[", "]")]) +@pytest.mark.parametrize( + "body", ["echo -n!x", "echo -n!x", "echo -n !x", "echo -n ! x"] +) def test_arg_single_subprocbang_nested(opener, closer, ipener, iloser, body): - code = opener + 'echo ' + ipener + body + iloser + closer + code = opener + "echo " + ipener + body + iloser + closer tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True) assert isinstance(tree, AST) cmd = tree.body.args[0].elts assert len(cmd) == 3 - assert cmd[2].s == 'x' + assert cmd[2].s == "x" -@pytest.mark.parametrize('opener, closer', SUBPROC_MACRO_OC) -@pytest.mark.parametrize('body', [ - 'echo!x + y', - 'echo !x + y', - 'echo !x + y', - 'echo ! x + y', - 'timeit! bang! and more', - 'timeit! recurse() and more', - 'timeit! recurse[] and more', - 'timeit! recurse!() and more', - 'timeit! recurse![] and more', - 'timeit! recurse$() and more', - 'timeit! recurse$[] and more', - 'timeit! recurse!() and more', - 'timeit!!!!', - 'timeit! (!)', - 'timeit! [!]', - 'timeit!!(ls)', - 'timeit!"!)"', - ]) +@pytest.mark.parametrize("opener, closer", SUBPROC_MACRO_OC) +@pytest.mark.parametrize( + "body", + [ + "echo!x + y", + "echo !x + y", + "echo !x + y", + "echo ! x + y", + "timeit! bang! and more", + "timeit! recurse() and more", + "timeit! recurse[] and more", + "timeit! recurse!() and more", + "timeit! recurse![] and more", + "timeit! recurse$() and more", + "timeit! recurse$[] and more", + "timeit! recurse!() and more", + "timeit!!!!", + "timeit! (!)", + "timeit! [!]", + "timeit!!(ls)", + 'timeit!"!)"', + ], +) def test_many_subprocbang(opener, closer, body): tree = check_xonsh_ast({}, opener + body + closer, False, return_obs=True) assert isinstance(tree, AST) cmd = tree.body.args[0].elts assert len(cmd) == 2 - assert cmd[1].s == body.partition('!')[-1].strip() + assert cmd[1].s == body.partition("!")[-1].strip() WITH_BANG_RAWSUITES = [ - 'pass\n', - 'x = 42\ny = 12\n', + "pass\n", + "x = 42\ny = 12\n", 'export PATH="yo:momma"\necho $PATH\n', - ('with q as t:\n' - ' v = 10\n' - '\n'), - ('with q as t:\n' - ' v = 10\n' - '\n' - 'for x in range(6):\n' - ' if True:\n' - ' pass\n' - ' else:\n' - ' ls -l\n' - '\n' - 'a = 42\n'), - ] + ("with q as t:\n" " v = 10\n" "\n"), + ( + "with q as t:\n" + " v = 10\n" + "\n" + "for x in range(6):\n" + " if True:\n" + " pass\n" + " else:\n" + " ls -l\n" + "\n" + "a = 42\n" + ), +] -@pytest.mark.parametrize('body', WITH_BANG_RAWSUITES) + +@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES) def test_withbang_single_suite(body): - code = 'with! x:\n{}'.format(textwrap.indent(body, ' ')) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec') + code = "with! x:\n{}".format(textwrap.indent(body, " ")) + tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec") assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) @@ -2071,10 +2731,10 @@ def test_withbang_single_suite(body): assert s == body -@pytest.mark.parametrize('body', WITH_BANG_RAWSUITES) +@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES) def test_withbang_as_single_suite(body): - code = 'with! x as y:\n{}'.format(textwrap.indent(body, ' ')) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec') + code = "with! x as y:\n{}".format(textwrap.indent(body, " ")) + tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec") assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) @@ -2082,17 +2742,22 @@ def test_withbang_as_single_suite(body): assert isinstance(wither.body[0], Pass) assert len(wither.items) == 1 item = wither.items[0] - assert item.optional_vars.id == 'y' + assert item.optional_vars.id == "y" s = item.context_expr.args[1].s assert s == body -@pytest.mark.parametrize('body', WITH_BANG_RAWSUITES) +@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES) def test_withbang_single_suite_trailing(body): - code = 'with! x:\n{}\nprint(x)\n'.format(textwrap.indent(body, ' ')) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec', - #debug_level=100 - ) + code = "with! x:\n{}\nprint(x)\n".format(textwrap.indent(body, " ")) + tree = check_xonsh_ast( + {}, + code, + False, + return_obs=True, + mode="exec", + # debug_level=100 + ) assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) @@ -2101,19 +2766,21 @@ def test_withbang_single_suite_trailing(body): assert len(wither.items) == 1 item = wither.items[0] s = item.context_expr.args[1].s - assert s == body + '\n' + assert s == body + "\n" + WITH_BANG_RAWSIMPLE = [ - 'pass', - 'x = 42; y = 12', + "pass", + "x = 42; y = 12", 'export PATH="yo:momma"; echo $PATH', - '[1,\n 2,\n 3]' - ] + "[1,\n 2,\n 3]", +] -@pytest.mark.parametrize('body', WITH_BANG_RAWSIMPLE) + +@pytest.mark.parametrize("body", WITH_BANG_RAWSIMPLE) def test_withbang_single_simple(body): - code = 'with! x: {}\n'.format(body) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec') + code = "with! x: {}\n".format(body) + tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec") assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) @@ -2125,10 +2792,10 @@ def test_withbang_single_simple(body): assert s == body -@pytest.mark.parametrize('body', WITH_BANG_RAWSIMPLE) +@pytest.mark.parametrize("body", WITH_BANG_RAWSIMPLE) def test_withbang_single_simple_opt(body): - code = 'with! x as y: {}\n'.format(body) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec') + code = "with! x as y: {}\n".format(body) + tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec") assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) @@ -2136,182 +2803,205 @@ def test_withbang_single_simple_opt(body): assert isinstance(wither.body[0], Pass) assert len(wither.items) == 1 item = wither.items[0] - assert item.optional_vars.id == 'y' + assert item.optional_vars.id == "y" s = item.context_expr.args[1].s assert s == body -@pytest.mark.parametrize('body', WITH_BANG_RAWSUITES) +@pytest.mark.parametrize("body", WITH_BANG_RAWSUITES) def test_withbang_as_many_suite(body): - code = 'with! x as a, y as b, z as c:\n{}' - code = code.format(textwrap.indent(body, ' ')) - tree = check_xonsh_ast({}, code, False, return_obs=True, mode='exec') + code = "with! x as a, y as b, z as c:\n{}" + code = code.format(textwrap.indent(body, " ")) + tree = check_xonsh_ast({}, code, False, return_obs=True, mode="exec") assert isinstance(tree, AST) wither = tree.body[0] assert isinstance(wither, With) assert len(wither.body) == 1 assert isinstance(wither.body[0], Pass) assert len(wither.items) == 3 - for i, targ in enumerate('abc'): + for i, targ in enumerate("abc"): item = wither.items[i] assert item.optional_vars.id == targ s = item.context_expr.args[1].s assert s == body - # test invalid expressions + def test_syntax_error_del_literal(): with pytest.raises(SyntaxError): - PARSER.parse('del 7') + PARSER.parse("del 7") + def test_syntax_error_del_constant(): with pytest.raises(SyntaxError): - PARSER.parse('del True') + PARSER.parse("del True") + def test_syntax_error_del_emptytuple(): with pytest.raises(SyntaxError): - PARSER.parse('del ()') + PARSER.parse("del ()") + def test_syntax_error_del_call(): with pytest.raises(SyntaxError): - PARSER.parse('del foo()') + PARSER.parse("del foo()") + def test_syntax_error_del_lambda(): with pytest.raises(SyntaxError): PARSER.parse('del lambda x: "yay"') + def test_syntax_error_del_ifexp(): with pytest.raises(SyntaxError): - PARSER.parse('del x if y else z') + PARSER.parse("del x if y else z") -@pytest.mark.parametrize('exp', ['[i for i in foo]', - '{i for i in foo}', - '(i for i in foo)', - '{k:v for k,v in d.items()}']) +@pytest.mark.parametrize( + "exp", + [ + "[i for i in foo]", + "{i for i in foo}", + "(i for i in foo)", + "{k:v for k,v in d.items()}", + ], +) def test_syntax_error_del_comps(exp): with pytest.raises(SyntaxError): - PARSER.parse('del {}'.format(exp)) + PARSER.parse("del {}".format(exp)) -@pytest.mark.parametrize('exp', ['x + y', - 'x and y', - '-x']) +@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"]) def test_syntax_error_del_ops(exp): with pytest.raises(SyntaxError): - PARSER.parse('del {}'.format(exp)) + PARSER.parse("del {}".format(exp)) -@pytest.mark.parametrize('exp', ['x > y', - 'x > y == z']) +@pytest.mark.parametrize("exp", ["x > y", "x > y == z"]) def test_syntax_error_del_cmp(exp): with pytest.raises(SyntaxError): - PARSER.parse('del {}'.format(exp)) + PARSER.parse("del {}".format(exp)) + def test_syntax_error_lonely_del(): with pytest.raises(SyntaxError): - PARSER.parse('del') + PARSER.parse("del") + def test_syntax_error_assign_literal(): with pytest.raises(SyntaxError): - PARSER.parse('7 = x') + PARSER.parse("7 = x") + def test_syntax_error_assign_constant(): with pytest.raises(SyntaxError): - PARSER.parse('True = 8') + PARSER.parse("True = 8") + def test_syntax_error_assign_emptytuple(): with pytest.raises(SyntaxError): - PARSER.parse('() = x') + PARSER.parse("() = x") + def test_syntax_error_assign_call(): with pytest.raises(SyntaxError): - PARSER.parse('foo() = x') + PARSER.parse("foo() = x") + def test_syntax_error_assign_lambda(): with pytest.raises(SyntaxError): PARSER.parse('lambda x: "yay" = y') + def test_syntax_error_assign_ifexp(): with pytest.raises(SyntaxError): - PARSER.parse('x if y else z = 8') + PARSER.parse("x if y else z = 8") -@pytest.mark.parametrize('exp', ['[i for i in foo]', - '{i for i in foo}', - '(i for i in foo)', - '{k:v for k,v in d.items()}']) +@pytest.mark.parametrize( + "exp", + [ + "[i for i in foo]", + "{i for i in foo}", + "(i for i in foo)", + "{k:v for k,v in d.items()}", + ], +) def test_syntax_error_assign_comps(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} = z'.format(exp)) + PARSER.parse("{} = z".format(exp)) -@pytest.mark.parametrize('exp', ['x + y', - 'x and y', - '-x']) +@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"]) def test_syntax_error_assign_ops(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} = z'.format(exp)) + PARSER.parse("{} = z".format(exp)) -@pytest.mark.parametrize('exp', ['x > y', - 'x > y == z']) +@pytest.mark.parametrize("exp", ["x > y", "x > y == z"]) def test_syntax_error_assign_cmp(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} = a'.format(exp)) + PARSER.parse("{} = a".format(exp)) def test_syntax_error_augassign_literal(): with pytest.raises(SyntaxError): - PARSER.parse('7 += x') + PARSER.parse("7 += x") + def test_syntax_error_augassign_constant(): with pytest.raises(SyntaxError): - PARSER.parse('True += 8') + PARSER.parse("True += 8") + def test_syntax_error_augassign_emptytuple(): with pytest.raises(SyntaxError): - PARSER.parse('() += x') + PARSER.parse("() += x") + def test_syntax_error_augassign_call(): with pytest.raises(SyntaxError): - PARSER.parse('foo() += x') + PARSER.parse("foo() += x") + def test_syntax_error_augassign_lambda(): with pytest.raises(SyntaxError): PARSER.parse('lambda x: "yay" += y') + def test_syntax_error_augassign_ifexp(): with pytest.raises(SyntaxError): - PARSER.parse('x if y else z += 8') + PARSER.parse("x if y else z += 8") -@pytest.mark.parametrize('exp', ['[i for i in foo]', - '{i for i in foo}', - '(i for i in foo)', - '{k:v for k,v in d.items()}']) +@pytest.mark.parametrize( + "exp", + [ + "[i for i in foo]", + "{i for i in foo}", + "(i for i in foo)", + "{k:v for k,v in d.items()}", + ], +) def test_syntax_error_augassign_comps(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} += z'.format(exp)) + PARSER.parse("{} += z".format(exp)) -@pytest.mark.parametrize('exp', ['x + y', - 'x and y', - '-x']) +@pytest.mark.parametrize("exp", ["x + y", "x and y", "-x"]) def test_syntax_error_augassign_ops(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} += z'.format(exp)) + PARSER.parse("{} += z".format(exp)) -@pytest.mark.parametrize('exp', ['x > y', - 'x > y +=+= z']) +@pytest.mark.parametrize("exp", ["x > y", "x > y +=+= z"]) def test_syntax_error_augassign_cmp(exp): with pytest.raises(SyntaxError): - PARSER.parse('{} += a'.format(exp)) + PARSER.parse("{} += a".format(exp)) def test_syntax_error_bar_kwonlyargs(): with pytest.raises(SyntaxError): - PARSER.parse('def spam(*):\n pass\n', mode='exec') + PARSER.parse("def spam(*):\n pass\n", mode="exec") diff --git a/tests/test_path_completers.py b/tests/test_path_completers.py index 2a4930425..8c2118636 100644 --- a/tests/test_path_completers.py +++ b/tests/test_path_completers.py @@ -14,28 +14,30 @@ def xonsh_execer_autouse(xonsh_builtins, xonsh_execer): def test_pattern_need_quotes(): # just make sure the regex compiles - xcp.PATTERN_NEED_QUOTES.match('') + xcp.PATTERN_NEED_QUOTES.match("") def test_complete_path(xonsh_builtins): - xonsh_builtins.__xonsh_env__ = {'CASE_SENSITIVE_COMPLETIONS': False, - 'GLOB_SORTED': True, - 'SUBSEQUENCE_PATH_COMPLETION': False, - 'FUZZY_PATH_COMPLETION': False, - 'SUGGEST_THRESHOLD': 3, - 'CDPATH': set(), + xonsh_builtins.__xonsh_env__ = { + "CASE_SENSITIVE_COMPLETIONS": False, + "GLOB_SORTED": True, + "SUBSEQUENCE_PATH_COMPLETION": False, + "FUZZY_PATH_COMPLETION": False, + "SUGGEST_THRESHOLD": 3, + "CDPATH": set(), } - xcp.complete_path('[1-0.1]', '[1-0.1]', 0, 7, dict()) + xcp.complete_path("[1-0.1]", "[1-0.1]", 0, 7, dict()) -@patch('xonsh.completers.path._add_cdpaths') +@patch("xonsh.completers.path._add_cdpaths") def test_cd_path_no_cd(mock_add_cdpaths, xonsh_builtins): - xonsh_builtins.__xonsh_env__ = {'CASE_SENSITIVE_COMPLETIONS': False, - 'GLOB_SORTED': True, - 'SUBSEQUENCE_PATH_COMPLETION': False, - 'FUZZY_PATH_COMPLETION': False, - 'SUGGEST_THRESHOLD': 3, - 'CDPATH': ['/'], + xonsh_builtins.__xonsh_env__ = { + "CASE_SENSITIVE_COMPLETIONS": False, + "GLOB_SORTED": True, + "SUBSEQUENCE_PATH_COMPLETION": False, + "FUZZY_PATH_COMPLETION": False, + "SUGGEST_THRESHOLD": 3, + "CDPATH": ["/"], } - xcp.complete_path('a', 'cat a', 4, 5, dict()) + xcp.complete_path("a", "cat a", 4, 5, dict()) mock_add_cdpaths.assert_not_called() diff --git a/tests/test_platform.py b/tests/test_platform.py index 773f8cc9c..904160e6b 100644 --- a/tests/test_platform.py +++ b/tests/test_platform.py @@ -8,8 +8,9 @@ import xonsh.platform as xp def test_githash_value_error(monkeypatch): @contextmanager def mocked_open(*args): - yield MagicMock(read=lambda: 'abc123') - monkeypatch.setattr(builtins, 'open', mocked_open) + yield MagicMock(read=lambda: "abc123") + + monkeypatch.setattr(builtins, "open", mocked_open) sha, date_ = xp.githash() assert date_ is None assert sha is None diff --git a/tests/test_prompt.py b/tests/test_prompt.py index bdbe84a9f..0f403421b 100644 --- a/tests/test_prompt.py +++ b/tests/test_prompt.py @@ -17,59 +17,63 @@ def formatter(xonsh_builtins): return PromptFormatter() -@pytest.mark.parametrize('fields', [{ - 'a_string': 'cat', - 'none': (lambda: None), - 'f': (lambda: 'wakka'), -}]) -@pytest.mark.parametrize('inp, exp', [ - ('my {a_string}', 'my cat'), - ('my {none}{a_string}', 'my cat'), - ('{f} jawaka', 'wakka jawaka'), -]) +@pytest.mark.parametrize( + "fields", [{"a_string": "cat", "none": (lambda: None), "f": (lambda: "wakka")}] +) +@pytest.mark.parametrize( + "inp, exp", + [ + ("my {a_string}", "my cat"), + ("my {none}{a_string}", "my cat"), + ("{f} jawaka", "wakka jawaka"), + ], +) def test_format_prompt(inp, exp, fields, formatter): obs = formatter(template=inp, fields=fields) assert exp == obs -@pytest.mark.parametrize('fields', [{ - 'a_string': 'cats', - 'a_number': 7, - 'empty': '', - 'current_job': (lambda: 'sleep'), - 'none': (lambda: None), -}]) -@pytest.mark.parametrize('inp, exp', [ - ('{a_number:{0:^3}}cats', ' 7 cats'), - ('{current_job:{} | }xonsh', 'sleep | xonsh'), - ('{none:{} | }{a_string}{empty:!}', 'cats!'), - ('{none:{}}', ''), - ('{{{a_string:{{{}}}}}}', '{{cats}}'), - ('{{{none:{{{}}}}}}', '{}'), -]) +@pytest.mark.parametrize( + "fields", + [ + { + "a_string": "cats", + "a_number": 7, + "empty": "", + "current_job": (lambda: "sleep"), + "none": (lambda: None), + } + ], +) +@pytest.mark.parametrize( + "inp, exp", + [ + ("{a_number:{0:^3}}cats", " 7 cats"), + ("{current_job:{} | }xonsh", "sleep | xonsh"), + ("{none:{} | }{a_string}{empty:!}", "cats!"), + ("{none:{}}", ""), + ("{{{a_string:{{{}}}}}}", "{{cats}}"), + ("{{{none:{{{}}}}}}", "{}"), + ], +) def test_format_prompt_with_format_spec(inp, exp, fields, formatter): obs = formatter(template=inp, fields=fields) assert exp == obs def test_format_prompt_with_broken_template(formatter): - for p in ('{user', '{user}{hostname'): + for p in ("{user", "{user}{hostname"): assert formatter(p) == p # '{{user' will be parsed to '{user' - for p in ('{{user}', '{{user'): - assert 'user' in formatter(p) + for p in ("{{user}", "{{user"): + assert "user" in formatter(p) -@pytest.mark.parametrize('inp', [ - '{user', - '{{user', - '{{user}', - '{user}{hostname', - ]) +@pytest.mark.parametrize("inp", ["{user", "{{user", "{{user}", "{user}{hostname"]) def test_format_prompt_with_broken_template_in_func(inp, formatter): # '{{user' will be parsed to '{user' - assert '{user' in formatter(lambda: inp) + assert "{user" in formatter(lambda: inp) def test_format_prompt_with_invalid_func(formatter, xonsh_builtins): @@ -77,28 +81,26 @@ def test_format_prompt_with_invalid_func(formatter, xonsh_builtins): def p(): foo = bar # raises exception # noqa - return '{user}' + return "{user}" assert isinstance(formatter(p), str) -def test_format_prompt_with_func_that_raises(formatter, - capsys, - xonsh_builtins): +def test_format_prompt_with_func_that_raises(formatter, capsys, xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env() - template = 'tt {zerodiv} tt' - exp = 'tt (ERROR:zerodiv) tt' - fields = {'zerodiv': lambda: 1/0} + template = "tt {zerodiv} tt" + exp = "tt (ERROR:zerodiv) tt" + fields = {"zerodiv": lambda: 1 / 0} obs = formatter(template, fields) assert exp == obs out, err = capsys.readouterr() - assert 'prompt: error' in err + assert "prompt: error" in err def test_promptformatter_cache(formatter): spam = Mock() - template = '{spam} and {spam}' - fields = {'spam': spam} + template = "{spam} and {spam}" + fields = {"spam": spam} formatter(template, fields) @@ -107,8 +109,8 @@ def test_promptformatter_cache(formatter): def test_promptformatter_clears_cache(formatter): spam = Mock() - template = '{spam} and {spam}' - fields = {'spam': spam} + template = "{spam} and {spam}" + fields = {"spam": spam} formatter(template, fields) formatter(template, fields) @@ -117,11 +119,10 @@ def test_promptformatter_clears_cache(formatter): # Xonsh interaction with version control systems. -VC_BRANCH = {'git': 'master', - 'hg': 'default'} +VC_BRANCH = {"git": "master", "hg": "default"} -@pytest.fixture(scope='module', params=VC_BRANCH.keys()) +@pytest.fixture(scope="module", params=VC_BRANCH.keys()) def test_repo(request): """Return a dict with vc and a temporary dir that is a repository for testing. @@ -130,28 +131,30 @@ def test_repo(request): temp_dir = tempfile.mkdtemp() os.chdir(temp_dir) try: - sp.call([vc, 'init']) + sp.call([vc, "init"]) except FileNotFoundError: - pytest.skip('cannot find {} executable'.format(vc)) + pytest.skip("cannot find {} executable".format(vc)) # git needs at least one commit - if vc == 'git': - with open('test-file', 'w'): + if vc == "git": + with open("test-file", "w"): pass - sp.call(['git', 'add', 'test-file']) - sp.call(['git', 'commit', '-m', 'test commit']) - return {'name': vc, 'dir': temp_dir} + sp.call(["git", "add", "test-file"]) + sp.call(["git", "commit", "-m", "test commit"]) + return {"name": vc, "dir": temp_dir} def test_test_repo(test_repo): - dotdir = os.path.isdir(os.path.join(test_repo['dir'], - '.{}'.format(test_repo['name']))) + dotdir = os.path.isdir( + os.path.join(test_repo["dir"], ".{}".format(test_repo["name"])) + ) assert dotdir - if test_repo['name'] == 'git': - assert os.path.isfile(os.path.join(test_repo['dir'], 'test-file')) + if test_repo["name"] == "git": + assert os.path.isfile(os.path.join(test_repo["dir"], "test-file")) def test_no_repo(xonsh_builtins): import queue + temp_dir = tempfile.mkdtemp() xonsh_builtins.__xonsh_env__ = Env(VC_BRANCH_TIMEOUT=2, PWD=temp_dir) q = queue.Queue() @@ -164,27 +167,29 @@ def test_no_repo(xonsh_builtins): def test_vc_get_branch(test_repo, xonsh_builtins): xonsh_builtins.__xonsh_env__ = Env(VC_BRANCH_TIMEOUT=2) # get corresponding function from vc module - fun = 'get_{}_branch'.format(test_repo['name']) + fun = "get_{}_branch".format(test_repo["name"]) obs = getattr(vc, fun)() if obs is not None: - assert obs == VC_BRANCH[test_repo['name']] + assert obs == VC_BRANCH[test_repo["name"]] def test_current_branch_calls_locate_binary_for_empty_cmds_cache(xonsh_builtins): cache = xonsh_builtins.__xonsh_commands_cache__ xonsh_builtins.__xonsh_env__ = DummyEnv(VC_BRANCH_TIMEOUT=1) cache.is_empty = Mock(return_value=True) - cache.locate_binary = Mock(return_value='') + cache.locate_binary = Mock(return_value="") vc.current_branch() assert cache.locate_binary.called -def test_current_branch_does_not_call_locate_binary_for_non_empty_cmds_cache(xonsh_builtins): +def test_current_branch_does_not_call_locate_binary_for_non_empty_cmds_cache( + xonsh_builtins +): cache = xonsh_builtins.__xonsh_commands_cache__ xonsh_builtins.__xonsh_env__ = DummyEnv(VC_BRANCH_TIMEOUT=1) cache.is_empty = Mock(return_value=False) - cache.locate_binary = Mock(return_value='') + cache.locate_binary = Mock(return_value="") # make lazy locate return nothing to avoid running vc binaries - cache.lazy_locate_binary = Mock(return_value='') + cache.lazy_locate_binary = Mock(return_value="") vc.current_branch() assert not cache.locate_binary.called diff --git a/tests/test_ptk_highlight.py b/tests/test_ptk_highlight.py index a87f87663..33d192841 100644 --- a/tests/test_ptk_highlight.py +++ b/tests/test_ptk_highlight.py @@ -5,8 +5,16 @@ import os import builtins import pytest -from pygments.token import (Keyword, Name, String, Error, Number, - Operator, Punctuation, Text) +from pygments.token import ( + Keyword, + Name, + String, + Error, + Number, + Operator, + Punctuation, + Text, +) from tools import skip_if_on_windows from xonsh.platform import ON_WINDOWS @@ -18,7 +26,7 @@ from xonsh.pyghooks import XonshLexer def load_command_cache(): load_builtins() if ON_WINDOWS: - for key in ('cd', 'bash'): + for key in ("cd", "bash"): builtins.aliases[key] = lambda *args, **kwargs: None yield unload_builtins() @@ -35,105 +43,127 @@ def check_token(code, tokens): break tks = tks[1:] else: - msg = "Token {!r} missing: {!r}".format(tk, - list(lx.get_tokens(code))) + msg = "Token {!r} missing: {!r}".format(tk, list(lx.get_tokens(code))) pytest.fail(msg) break @skip_if_on_windows def test_ls(): - check_token('ls -al', [(Name.Builtin, 'ls')]) + check_token("ls -al", [(Name.Builtin, "ls")]) @skip_if_on_windows def test_bin_ls(): - check_token('/bin/ls -al', [(Name.Builtin, '/bin/ls')]) + check_token("/bin/ls -al", [(Name.Builtin, "/bin/ls")]) def test_py_print(): - check_token('print("hello")', [(Keyword, 'print'), - (String.Double, 'hello')]) + check_token('print("hello")', [(Keyword, "print"), (String.Double, "hello")]) def test_invalid_cmd(): - check_token('non-existance-cmd -al', [(Name, 'non')]) # parse as python - check_token('![non-existance-cmd -al]', - [(Error, 'non-existance-cmd')]) # parse as error - check_token('for i in range(10):', [(Keyword, 'for')]) # as py keyword - check_token('(1, )', [(Punctuation, '('), - (Number.Integer, '1')]) + check_token("non-existance-cmd -al", [(Name, "non")]) # parse as python + check_token( + "![non-existance-cmd -al]", [(Error, "non-existance-cmd")] + ) # parse as error + check_token("for i in range(10):", [(Keyword, "for")]) # as py keyword + check_token("(1, )", [(Punctuation, "("), (Number.Integer, "1")]) def test_multi_cmd(): - check_token('cd && cd', [(Name.Builtin, 'cd'), - (Operator, '&&'), - (Name.Builtin, 'cd')]) - check_token('cd || non-existance-cmd', [(Name.Builtin, 'cd'), - (Operator, '||'), - (Error, 'non-existance-cmd') - ]) + check_token( + "cd && cd", [(Name.Builtin, "cd"), (Operator, "&&"), (Name.Builtin, "cd")] + ) + check_token( + "cd || non-existance-cmd", + [(Name.Builtin, "cd"), (Operator, "||"), (Error, "non-existance-cmd")], + ) def test_nested(): - check_token('echo @("hello")', [(Name.Builtin, 'echo'), - (Keyword, '@'), - (Punctuation, '('), - (String.Double, 'hello'), - (Punctuation, ')')]) - check_token('print($(cd))', [(Keyword, 'print'), - (Punctuation, '('), - (Keyword, '$'), - (Punctuation, '('), - (Name.Builtin, 'cd'), - (Punctuation, ')'), - (Punctuation, ')')]) - check_token(r'print(![echo "])\""])', [(Keyword, 'print'), - (Keyword, '!'), - (Punctuation, '['), - (Name.Builtin, 'echo'), - (String.Double, r'"])\""'), - (Punctuation, ']')]) + check_token( + 'echo @("hello")', + [ + (Name.Builtin, "echo"), + (Keyword, "@"), + (Punctuation, "("), + (String.Double, "hello"), + (Punctuation, ")"), + ], + ) + check_token( + "print($(cd))", + [ + (Keyword, "print"), + (Punctuation, "("), + (Keyword, "$"), + (Punctuation, "("), + (Name.Builtin, "cd"), + (Punctuation, ")"), + (Punctuation, ")"), + ], + ) + check_token( + r'print(![echo "])\""])', + [ + (Keyword, "print"), + (Keyword, "!"), + (Punctuation, "["), + (Name.Builtin, "echo"), + (String.Double, r'"])\""'), + (Punctuation, "]"), + ], + ) def test_path(tmpdir): - test_dir = str(tmpdir.mkdir('xonsh-test-highlight-path')) - check_token('cd {}'.format(test_dir), [(Name.Builtin, 'cd'), - (Name.Constant, test_dir)]) - check_token('cd {}-xxx'.format(test_dir), [(Name.Builtin, 'cd'), - (Text, - '{}-xxx'.format(test_dir)) - ]) - check_token('cd X={}'.format(test_dir), [(Name.Constant, test_dir)]) + test_dir = str(tmpdir.mkdir("xonsh-test-highlight-path")) + check_token( + "cd {}".format(test_dir), [(Name.Builtin, "cd"), (Name.Constant, test_dir)] + ) + check_token( + "cd {}-xxx".format(test_dir), + [(Name.Builtin, "cd"), (Text, "{}-xxx".format(test_dir))], + ) + check_token("cd X={}".format(test_dir), [(Name.Constant, test_dir)]) with builtins.__xonsh_env__.swap(AUTO_CD=True): check_token(test_dir, [(Name.Constant, test_dir)]) def test_subproc_args(): - check_token('cd 192.168.0.1', [(Text, '192.168.0.1')]) + check_token("cd 192.168.0.1", [(Text, "192.168.0.1")]) def test_backtick(): - check_token(r'echo g`.*\w+`', [(String.Affix, 'g'), - (String.Backtick, '`'), - (String.Regex, '.'), - (String.Regex, '*'), - (String.Escape, r'\w'), - ]) + check_token( + r"echo g`.*\w+`", + [ + (String.Affix, "g"), + (String.Backtick, "`"), + (String.Regex, "."), + (String.Regex, "*"), + (String.Escape, r"\w"), + ], + ) def test_macro(): - check_token(r'g!(42, *, 65)', [(Name, 'g'), - (Keyword, '!'), - (Punctuation, '('), - (Number.Integer, '42')]) - check_token(r'echo! hello world', [(Name.Builtin, 'echo'), - (Keyword, '!'), - (String, "hello world")]) - check_token(r'bash -c ! export var=42; echo $var', - [(Name.Builtin, 'bash'), - (Text, '-c'), - (Keyword, '!'), - (String, 'export var=42; echo $var'), - ]) + check_token( + r"g!(42, *, 65)", + [(Name, "g"), (Keyword, "!"), (Punctuation, "("), (Number.Integer, "42")], + ) + check_token( + r"echo! hello world", + [(Name.Builtin, "echo"), (Keyword, "!"), (String, "hello world")], + ) + check_token( + r"bash -c ! export var=42; echo $var", + [ + (Name.Builtin, "bash"), + (Text, "-c"), + (Keyword, "!"), + (String, "export var=42; echo $var"), + ], + ) diff --git a/tests/test_ptk_history.py b/tests/test_ptk_history.py index f822a06eb..96c85759a 100644 --- a/tests/test_ptk_history.py +++ b/tests/test_ptk_history.py @@ -3,7 +3,7 @@ import pytest try: import prompt_toolkit # NOQA except ImportError: - pytest.mark.skip(msg='prompt_toolkit is not available') + pytest.mark.skip(msg="prompt_toolkit is not available") from xonsh.ptk2.history import PromptToolkitHistory @@ -14,12 +14,12 @@ from tools import skip_if_lt_ptk2 def history_obj(): """Instantiate `PromptToolkitHistory` and append a line string""" hist = PromptToolkitHistory(load_prev=False) - hist.append_string('line10') + hist.append_string("line10") return hist @skip_if_lt_ptk2 def test_obj(history_obj): - assert ['line10'] == history_obj.get_strings() + assert ["line10"] == history_obj.get_strings() assert len(history_obj) == 1 - assert ['line10'] == [x for x in history_obj] + assert ["line10"] == [x for x in history_obj] diff --git a/tests/test_ptk_multiline.py b/tests/test_ptk_multiline.py index 393566fde..649117af6 100644 --- a/tests/test_ptk_multiline.py +++ b/tests/test_ptk_multiline.py @@ -14,29 +14,32 @@ from xonsh.tools import ON_WINDOWS from tools import DummyEnv, skip_if_lt_ptk2 -Context = namedtuple('Context', ['indent', 'buffer', 'accept', 'cli', 'cr']) +Context = namedtuple("Context", ["indent", "buffer", "accept", "cli", "cr"]) -@pytest.yield_fixture(scope='module') +@pytest.yield_fixture(scope="module") def ctx(): """Context in which the ptk multiline functionality will be tested.""" builtins.__xonsh_env__ = DummyEnv() - builtins.__xonsh_env__['INDENT'] = ' ' + builtins.__xonsh_env__["INDENT"] = " " from xonsh.ptk2.key_bindings import carriage_return + ptk_buffer = Buffer() - ptk_buffer.accept_action = MagicMock(name='accept') - cli = MagicMock(name='cli', spec=Application) - yield Context(indent=' ', - buffer=ptk_buffer, - accept=ptk_buffer.accept_action, - cli=cli, - cr=carriage_return) + ptk_buffer.accept_action = MagicMock(name="accept") + cli = MagicMock(name="cli", spec=Application) + yield Context( + indent=" ", + buffer=ptk_buffer, + accept=ptk_buffer.accept_action, + cli=cli, + cr=carriage_return, + ) del builtins.__xonsh_env__ @skip_if_lt_ptk2 def test_colon_indent(ctx): - document = Document('for i in range(5):') + document = Document("for i in range(5):") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.buffer.document.current_line == ctx.indent @@ -44,12 +47,12 @@ def test_colon_indent(ctx): @skip_if_lt_ptk2 def test_dedent(ctx): - document = Document('\n'+ctx.indent+'pass') + document = Document("\n" + ctx.indent + "pass") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) - assert ctx.buffer.document.current_line == '' + assert ctx.buffer.document.current_line == "" - document = Document('\n'+2*ctx.indent+'continue') + document = Document("\n" + 2 * ctx.indent + "continue") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.buffer.document.current_line == ctx.indent @@ -57,17 +60,17 @@ def test_dedent(ctx): @skip_if_lt_ptk2 def test_nodedent(ctx): - '''don't dedent if first line of ctx.buffer''' + """don't dedent if first line of ctx.buffer""" mock = MagicMock(return_value=True) - with patch('xonsh.ptk2.key_bindings.can_compile', mock): - document = Document('pass') + with patch("xonsh.ptk2.key_bindings.can_compile", mock): + document = Document("pass") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.accept.mock_calls is not None mock = MagicMock(return_value=True) - with patch('xonsh.ptk2.key_bindings.can_compile', mock): - document = Document(ctx.indent+'pass') + with patch("xonsh.ptk2.key_bindings.can_compile", mock): + document = Document(ctx.indent + "pass") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.accept.mock_calls is not None @@ -75,21 +78,21 @@ def test_nodedent(ctx): @skip_if_lt_ptk2 def test_continuation_line(ctx): - document = Document('\nsecond line') + document = Document("\nsecond line") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) - assert ctx.buffer.document.current_line == '' + assert ctx.buffer.document.current_line == "" @skip_if_lt_ptk2 def test_trailing_slash(ctx): mock = MagicMock(return_value=True) - with patch('xonsh.ptk2.key_bindings.can_compile', mock): - document = Document('this line will \\') + with patch("xonsh.ptk2.key_bindings.can_compile", mock): + document = Document("this line will \\") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) if not ON_WINDOWS: - assert ctx.buffer.document.current_line == '' + assert ctx.buffer.document.current_line == "" else: assert ctx.accept.mock_calls is not None @@ -97,18 +100,18 @@ def test_trailing_slash(ctx): @skip_if_lt_ptk2 def test_cant_compile_newline(ctx): mock = MagicMock(return_value=False) - with patch('xonsh.ptk2.key_bindings.can_compile', mock): - document = Document('for i in (1, 2, ') + with patch("xonsh.ptk2.key_bindings.can_compile", mock): + document = Document("for i in (1, 2, ") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) - assert ctx.buffer.document.current_line == '' + assert ctx.buffer.document.current_line == "" @skip_if_lt_ptk2 def test_can_compile_and_executes(ctx): mock = MagicMock(return_value=True) - with patch('xonsh.ptk2.key_bindings.can_compile', mock): - document = Document('ls') + with patch("xonsh.ptk2.key_bindings.can_compile", mock): + document = Document("ls") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.accept.mock_calls is not None diff --git a/tests/test_python_completers.py b/tests/test_python_completers.py index 49988d642..189abe4f4 100644 --- a/tests/test_python_completers.py +++ b/tests/test_python_completers.py @@ -14,7 +14,7 @@ def foo(x, y, z): pass -def bar(wakka='wow', jawaka='mom'): +def bar(wakka="wow", jawaka="mom"): pass @@ -26,26 +26,29 @@ def always_true(x, y): return True -BASE_CTX = {'foo': foo, 'bar': bar, 'baz': baz} -FOO_ARGS = {'x=', 'y=', 'z='} -BAR_ARGS = {'wakka=', 'jawaka='} -BAZ_ARGS = {'sonata=', 'artica='} +BASE_CTX = {"foo": foo, "bar": bar, "baz": baz} +FOO_ARGS = {"x=", "y=", "z="} +BAR_ARGS = {"wakka=", "jawaka="} +BAZ_ARGS = {"sonata=", "artica="} -@pytest.mark.parametrize('line, end, exp', [ - ('foo(', 4, FOO_ARGS), # I have no idea why this one needs to be first - ('foo()', 3, set()), - ('foo()', 4, FOO_ARGS), - ('foo()', 5, set()), - ('foo(x, ', 6, FOO_ARGS), - ('foo(x, )', 6, FOO_ARGS), - ('bar()', 4, BAR_ARGS), - ('baz()', 4, BAZ_ARGS), - ('foo(bar(', 8, BAR_ARGS), - ('foo(bar()', 9, FOO_ARGS), - ('foo(bar())', 4, FOO_ARGS), -]) +@pytest.mark.parametrize( + "line, end, exp", + [ + ("foo(", 4, FOO_ARGS), # I have no idea why this one needs to be first + ("foo()", 3, set()), + ("foo()", 4, FOO_ARGS), + ("foo()", 5, set()), + ("foo(x, ", 6, FOO_ARGS), + ("foo(x, )", 6, FOO_ARGS), + ("bar()", 4, BAR_ARGS), + ("baz()", 4, BAZ_ARGS), + ("foo(bar(", 8, BAR_ARGS), + ("foo(bar()", 9, FOO_ARGS), + ("foo(bar())", 4, FOO_ARGS), + ], +) def test_complete_python_signatures(line, end, exp): ctx = dict(BASE_CTX) - obs = python_signature_complete('', line, end, ctx, always_true) + obs = python_signature_complete("", line, end, ctx, always_true) assert exp == obs diff --git a/tests/test_replay.py b/tests/test_replay.py index 416aafb77..cc7a28c64 100644 --- a/tests/test_replay.py +++ b/tests/test_replay.py @@ -12,36 +12,36 @@ from xonsh.replay import Replayer from tools import skip_if_on_darwin -HISTDIR = os.path.join(os.path.dirname(__file__), 'histories') +HISTDIR = os.path.join(os.path.dirname(__file__), "histories") -@pytest.yield_fixture(scope='module', autouse=True) +@pytest.yield_fixture(scope="module", autouse=True) def ctx(): """Create a global Shell instance to use in all the test.""" - ctx = {'PATH': []} + ctx = {"PATH": []} execer = Execer(xonsh_ctx=ctx) - builtins.__xonsh_shell__ = Shell(execer=execer, ctx=ctx, shell_type='none') + builtins.__xonsh_shell__ = Shell(execer=execer, ctx=ctx, shell_type="none") yield del builtins.__xonsh_shell__ @skip_if_on_darwin def test_echo(): - histfile = os.path.join(HISTDIR, 'echo.json') + histfile = os.path.join(HISTDIR, "echo.json") hist = Replayer(histfile).replay() assert len(hist) == 2 @skip_if_on_darwin def test_reecho(): - histfile = os.path.join(HISTDIR, 'echo.json') + histfile = os.path.join(HISTDIR, "echo.json") hist = Replayer(histfile).replay() assert len(hist) == 2 @skip_if_on_darwin def test_simple_python(): - histfile = os.path.join(HISTDIR, 'simple-python.json') + histfile = os.path.join(HISTDIR, "simple-python.json") hist = Replayer(histfile).replay() assert len(hist) == 4 assert hist.inps[0].strip() == "print('The Turtles')" diff --git a/tests/test_tools.py b/tests/test_tools.py index aabf20976..bf8c676eb 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,4 +1,4 @@ - # -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- """Tests xonsh tools.""" import datetime as dt import os @@ -14,20 +14,64 @@ from xonsh.platform import ON_WINDOWS from xonsh.lexer import Lexer from xonsh.tools import ( - EnvPath, always_false, always_true, argvquote, - bool_or_int_to_str, bool_to_str, check_for_partial_string, - dynamic_cwd_tuple_to_str, ensure_slice, ensure_string, - env_path_to_str, escape_windows_cmd_string, executables_in, - expand_case_matching, expand_path, find_next_break, is_bool, is_bool_or_int, - is_callable, is_dynamic_cwd_width, is_env_path, is_float, is_int, is_logfile_opt, - is_string_or_callable, logfile_opt_to_str, str_to_env_path, is_string, - subexpr_from_unbalanced, subproc_toks, to_bool, to_bool_or_int, - to_dynamic_cwd_tuple, to_logfile_opt, pathsep_to_set, set_to_pathsep, - is_string_seq, pathsep_to_seq, seq_to_pathsep, is_nonstring_seq_of_strings, - pathsep_to_upper_seq, seq_to_upper_pathsep, expandvars, is_int_as_str, is_slice_as_str, - ensure_timestamp, get_portions, is_balanced, subexpr_before_unbalanced, - swap_values, get_logical_line, replace_logical_line, check_quotes, deprecated, - is_writable_file, balanced_parens, iglobpath) + EnvPath, + always_false, + always_true, + argvquote, + bool_or_int_to_str, + bool_to_str, + check_for_partial_string, + dynamic_cwd_tuple_to_str, + ensure_slice, + ensure_string, + env_path_to_str, + escape_windows_cmd_string, + executables_in, + expand_case_matching, + expand_path, + find_next_break, + is_bool, + is_bool_or_int, + is_callable, + is_dynamic_cwd_width, + is_env_path, + is_float, + is_int, + is_logfile_opt, + is_string_or_callable, + logfile_opt_to_str, + str_to_env_path, + is_string, + subexpr_from_unbalanced, + subproc_toks, + to_bool, + to_bool_or_int, + to_dynamic_cwd_tuple, + to_logfile_opt, + pathsep_to_set, + set_to_pathsep, + is_string_seq, + pathsep_to_seq, + seq_to_pathsep, + is_nonstring_seq_of_strings, + pathsep_to_upper_seq, + seq_to_upper_pathsep, + expandvars, + is_int_as_str, + is_slice_as_str, + ensure_timestamp, + get_portions, + is_balanced, + subexpr_before_unbalanced, + swap_values, + get_logical_line, + replace_logical_line, + check_quotes, + deprecated, + is_writable_file, + balanced_parens, + iglobpath, +) from xonsh.environ import Env from tools import skip_if_on_windows, skip_if_on_unix @@ -35,159 +79,160 @@ from tools import skip_if_on_windows, skip_if_on_unix LEXER = Lexer() LEXER.build() -INDENT = ' ' +INDENT = " " + +TOOLS_ENV = {"EXPAND_ENV_VARS": True, "XONSH_ENCODING_ERRORS": "strict"} +ENCODE_ENV_ONLY = {"XONSH_ENCODING_ERRORS": "strict"} +PATHEXT_ENV = {"PATHEXT": [".COM", ".EXE", ".BAT"]} -TOOLS_ENV = {'EXPAND_ENV_VARS': True, 'XONSH_ENCODING_ERRORS':'strict'} -ENCODE_ENV_ONLY = {'XONSH_ENCODING_ERRORS': 'strict'} -PATHEXT_ENV = {'PATHEXT': ['.COM', '.EXE', '.BAT']} def test_subproc_toks_x(): - exp = '![x]' - obs = subproc_toks('x', lexer=LEXER, returnline=True) + exp = "![x]" + obs = subproc_toks("x", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_ls_l(): - exp = '![ls -l]' - obs = subproc_toks('ls -l', lexer=LEXER, returnline=True) + exp = "![ls -l]" + obs = subproc_toks("ls -l", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_git(): s = 'git commit -am "hello doc"' - exp = '![{0}]'.format(s) + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_git_semi(): s = 'git commit -am "hello doc"' - exp = '![{0}];'.format(s) - obs = subproc_toks(s + ';', lexer=LEXER, returnline=True) + exp = "![{0}];".format(s) + obs = subproc_toks(s + ";", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_git_nl(): s = 'git commit -am "hello doc"' - exp = '![{0}]\n'.format(s) - obs = subproc_toks(s + '\n', lexer=LEXER, returnline=True) + exp = "![{0}]\n".format(s) + obs = subproc_toks(s + "\n", lexer=LEXER, returnline=True) assert exp == obs def test_bash_macro(): - s = 'bash -c ! export var=42; echo $var' - exp = '![{0}]\n'.format(s) - obs = subproc_toks(s + '\n', lexer=LEXER, returnline=True) + s = "bash -c ! export var=42; echo $var" + exp = "![{0}]\n".format(s) + obs = subproc_toks(s + "\n", lexer=LEXER, returnline=True) assert exp == obs def test_python_macro(): s = 'python -c ! import os; print(os.path.abspath("/"))' - exp = '![{0}]\n'.format(s) - obs = subproc_toks(s + '\n', lexer=LEXER, returnline=True) + exp = "![{0}]\n".format(s) + obs = subproc_toks(s + "\n", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls(): - s = 'ls -l' - exp = INDENT + '![{0}]'.format(s) - obs = subproc_toks(INDENT + s, mincol=len(INDENT), lexer=LEXER, - returnline=True) + s = "ls -l" + exp = INDENT + "![{0}]".format(s) + obs = subproc_toks(INDENT + s, mincol=len(INDENT), lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_nl(): - s = 'ls -l' - exp = INDENT + '![{0}]\n'.format(s) - obs = subproc_toks(INDENT + s + '\n', mincol=len(INDENT), lexer=LEXER, - returnline=True) + s = "ls -l" + exp = INDENT + "![{0}]\n".format(s) + obs = subproc_toks( + INDENT + s + "\n", mincol=len(INDENT), lexer=LEXER, returnline=True + ) assert exp == obs def test_subproc_toks_indent_ls_no_min(): - s = 'ls -l' - exp = INDENT + '![{0}]'.format(s) + s = "ls -l" + exp = INDENT + "![{0}]".format(s) obs = subproc_toks(INDENT + s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_no_min_nl(): - s = 'ls -l' - exp = INDENT + '![{0}]\n'.format(s) - obs = subproc_toks(INDENT + s + '\n', lexer=LEXER, returnline=True) + s = "ls -l" + exp = INDENT + "![{0}]\n".format(s) + obs = subproc_toks(INDENT + s + "\n", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_no_min_semi(): - s = 'ls' - exp = INDENT + '![{0}];'.format(s) - obs = subproc_toks(INDENT + s + ';', lexer=LEXER, returnline=True) + s = "ls" + exp = INDENT + "![{0}];".format(s) + obs = subproc_toks(INDENT + s + ";", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_no_min_semi_nl(): - s = 'ls' - exp = INDENT + '![{0}];\n'.format(s) - obs = subproc_toks(INDENT + s + ';\n', lexer=LEXER, returnline=True) + s = "ls" + exp = INDENT + "![{0}];\n".format(s) + obs = subproc_toks(INDENT + s + ";\n", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_ls_comment(): - s = 'ls -l' - com = ' # lets list' - exp = '![{0}]{1}'.format(s, com) + s = "ls -l" + com = " # lets list" + exp = "![{0}]{1}".format(s, com) obs = subproc_toks(s + com, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_ls_42_comment(): - s = 'ls 42' - com = ' # lets list' - exp = '![{0}]{1}'.format(s, com) + s = "ls 42" + com = " # lets list" + exp = "![{0}]{1}".format(s, com) obs = subproc_toks(s + com, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_ls_str_comment(): s = 'ls "wakka"' - com = ' # lets list' - exp = '![{0}]{1}'.format(s, com) + com = " # lets list" + exp = "![{0}]{1}".format(s, com) obs = subproc_toks(s + com, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_comment(): - ind = ' ' - s = 'ls -l' - com = ' # lets list' - exp = '{0}![{1}]{2}'.format(ind, s, com) + ind = " " + s = "ls -l" + com = " # lets list" + exp = "{0}![{1}]{2}".format(ind, s, com) obs = subproc_toks(ind + s + com, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_indent_ls_str(): - ind = ' ' + ind = " " s = 'ls "wakka"' - com = ' # lets list' - exp = '{0}![{1}]{2}'.format(ind, s, com) + com = " # lets list" + exp = "{0}![{1}]{2}".format(ind, s, com) obs = subproc_toks(ind + s + com, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_ls_l_semi_ls_first(): - lsdl = 'ls -l' - ls = 'ls' - s = '{0}; {1}'.format(lsdl, ls) - exp = '![{0}]; {1}'.format(lsdl, ls) + lsdl = "ls -l" + ls = "ls" + s = "{0}; {1}".format(lsdl, ls) + exp = "![{0}]; {1}".format(lsdl, ls) obs = subproc_toks(s, lexer=LEXER, maxcol=6, returnline=True) assert exp == obs def test_subproc_toks_ls_l_semi_ls_second(): - lsdl = 'ls -l' - ls = 'ls' - s = '{0}; {1}'.format(lsdl, ls) - exp = '{0}; ![{1}]'.format(lsdl, ls) + lsdl = "ls -l" + ls = "ls" + s = "{0}; {1}".format(lsdl, ls) + exp = "{0}; ![{1}]".format(lsdl, ls) obs = subproc_toks(s, lexer=LEXER, mincol=7, returnline=True) assert exp == obs @@ -195,17 +240,17 @@ def test_subproc_toks_ls_l_semi_ls_second(): def test_subproc_toks_hello_mom_first(): fst = "echo 'hello'" sec = "echo 'mom'" - s = '{0}; {1}'.format(fst, sec) - exp = '![{0}]; {1}'.format(fst, sec) - obs = subproc_toks(s, lexer=LEXER, maxcol=len(fst)+1, returnline=True) + s = "{0}; {1}".format(fst, sec) + exp = "![{0}]; {1}".format(fst, sec) + obs = subproc_toks(s, lexer=LEXER, maxcol=len(fst) + 1, returnline=True) assert exp == obs def test_subproc_toks_hello_mom_second(): fst = "echo 'hello'" sec = "echo 'mom'" - s = '{0}; {1}'.format(fst, sec) - exp = '{0}; ![{1}]'.format(fst, sec) + s = "{0}; {1}".format(fst, sec) + exp = "{0}; ![{1}]".format(fst, sec) obs = subproc_toks(s, lexer=LEXER, mincol=len(fst), returnline=True) assert exp == obs @@ -232,188 +277,212 @@ def test_subproc_toks_hello_bad_trailing_triple_quotes(): def test_subproc_toks_hello_mom_triple_quotes_nl(): s = 'echo """hello\nmom"""' - exp = '![{0}]'.format(s) + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_comment(): exp = None - obs = subproc_toks('# I am a comment', lexer=LEXER, returnline=True) + obs = subproc_toks("# I am a comment", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_not(): - exp = 'not ![echo mom]' - obs = subproc_toks('not echo mom', lexer=LEXER, returnline=True) + exp = "not ![echo mom]" + obs = subproc_toks("not echo mom", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_paren(): - exp = '(![echo mom])' - obs = subproc_toks('(echo mom)', lexer=LEXER, returnline=True) + exp = "(![echo mom])" + obs = subproc_toks("(echo mom)", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_paren_ws(): - exp = '(![echo mom]) ' - obs = subproc_toks('(echo mom) ', lexer=LEXER, returnline=True) + exp = "(![echo mom]) " + obs = subproc_toks("(echo mom) ", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_not_paren(): - exp = 'not (![echo mom])' - obs = subproc_toks('not (echo mom)', lexer=LEXER, returnline=True) + exp = "not (![echo mom])" + obs = subproc_toks("not (echo mom)", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_and_paren(): - exp = 'True and (![echo mom])' - obs = subproc_toks('True and (echo mom)', lexer=LEXER, returnline=True) + exp = "True and (![echo mom])" + obs = subproc_toks("True and (echo mom)", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_paren_and_paren(): - exp = '(![echo a]) and (echo b)' - obs = subproc_toks('(echo a) and (echo b)', maxcol=9, lexer=LEXER, returnline=True) + exp = "(![echo a]) and (echo b)" + obs = subproc_toks("(echo a) and (echo b)", maxcol=9, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_semicolon_only(): exp = None - obs = subproc_toks(';', lexer=LEXER, returnline=True) + obs = subproc_toks(";", lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval(): - s = 'echo @(1+1)' - exp = '![{0}]'.format(s) + s = "echo @(1+1)" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval_multiline_string(): s = 'echo @("""hello\nmom""")' - exp = '![{0}]'.format(s) + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_twopyeval(): - s = 'echo @(1+1) @(40 + 2)' - exp = '![{0}]'.format(s) + s = "echo @(1+1) @(40 + 2)" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval_parens(): - s = 'echo @(1+1)' - inp = '({0})'.format(s) - exp = '(![{0}])'.format(s) + s = "echo @(1+1)" + inp = "({0})".format(s) + exp = "(![{0}])".format(s) obs = subproc_toks(inp, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_twopyeval_parens(): - s = 'echo @(1+1) @(40+2)' - inp = '({0})'.format(s) - exp = '(![{0}])'.format(s) + s = "echo @(1+1) @(40+2)" + inp = "({0})".format(s) + exp = "(![{0}])".format(s) obs = subproc_toks(inp, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval_nested(): - s = 'echo @(min(1, 42))' - exp = '![{0}]'.format(s) + s = "echo @(min(1, 42))" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval_nested_parens(): - s = 'echo @(min(1, 42))' - inp = '({0})'.format(s) - exp = '(![{0}])'.format(s) + s = "echo @(min(1, 42))" + inp = "({0})".format(s) + exp = "(![{0}])".format(s) obs = subproc_toks(inp, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_capstdout(): - s = 'echo $(echo bat)' - exp = '![{0}]'.format(s) + s = "echo $(echo bat)" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_capproc(): - s = 'echo !(echo bat)' - exp = '![{0}]'.format(s) + s = "echo !(echo bat)" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_pyeval_redirect(): s = 'echo @("foo") > bar' - inp = '{0}'.format(s) - exp = '![{0}]'.format(s) + inp = "{0}".format(s) + exp = "![{0}]".format(s) obs = subproc_toks(inp, lexer=LEXER, returnline=True) assert exp == obs def test_subproc_toks_greedy_parens(): - s = '(sort)' - exp = '![{0}]'.format(s) + s = "(sort)" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True, greedy=True) assert exp == obs def test_subproc_toks_greedy_parens_inp(): - s = '(sort) < input.txt' - exp = '![{0}]'.format(s) + s = "(sort) < input.txt" + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True, greedy=True) assert exp == obs def test_subproc_toks_greedy_parens_statements(): s = '(echo "abc"; sleep 1; echo "def")' - exp = '![{0}]'.format(s) + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True, greedy=True) assert exp == obs def test_subproc_toks_greedy_parens_statements_with_grep(): s = '(echo "abc"; sleep 1; echo "def") | grep' - exp = '![{0}]'.format(s) + exp = "![{0}]".format(s) obs = subproc_toks(s, lexer=LEXER, returnline=True, greedy=True) assert exp == obs LOGICAL_LINE_CASES = [ -("""x = 14 + 2""", 0, 'x = 14 + 2', 1), -("""x = \\ + ("""x = 14 + 2""", 0, "x = 14 + 2", 1), + ( + """x = \\ 14 \\ + 2 -""", 0, 'x = 14 + 2', 3), -("""y = 16 +""", + 0, + "x = 14 + 2", + 3, + ), + ( + """y = 16 14 \\ + 2 -""", 1, '14 + 2', 2), -('''x = """wow +""", + 1, + "14 + 2", + 2, + ), + ( + '''x = """wow mom""" -''', 0, 'x = """wow\nmom"""', 2), -# test from start -("echo --option1 value1 \\\n" - " --option2 value2 \\\n" - " --optionZ valueZ", -0, "echo --option1 value1 --option2 value2 --optionZ valueZ", 3), -# test from second line -("echo --option1 value1 \\\n" - " --option2 value2 \\\n" - " --optionZ valueZ", -1, "echo --option1 value1 --option2 value2 --optionZ valueZ", 3), -('"""\n', 0, '"""', 1), +''', + 0, + 'x = """wow\nmom"""', + 2, + ), + # test from start + ( + "echo --option1 value1 \\\n" + " --option2 value2 \\\n" + " --optionZ valueZ", + 0, + "echo --option1 value1 --option2 value2 --optionZ valueZ", + 3, + ), + # test from second line + ( + "echo --option1 value1 \\\n" + " --option2 value2 \\\n" + " --optionZ valueZ", + 1, + "echo --option1 value1 --option2 value2 --optionZ valueZ", + 3, + ), + ('"""\n', 0, '"""', 1), ] -@pytest.mark.parametrize('src, idx, exp_line, exp_n', LOGICAL_LINE_CASES) + +@pytest.mark.parametrize("src, idx, exp_line, exp_n", LOGICAL_LINE_CASES) def test_get_logical_line(src, idx, exp_line, exp_n): lines = src.splitlines() line, n, start = get_logical_line(lines, idx) @@ -421,86 +490,87 @@ def test_get_logical_line(src, idx, exp_line, exp_n): assert exp_n == n -@pytest.mark.parametrize('src, idx, exp_line, exp_n', LOGICAL_LINE_CASES) +@pytest.mark.parametrize("src, idx, exp_line, exp_n", LOGICAL_LINE_CASES) def test_replace_logical_line(src, idx, exp_line, exp_n): lines = src.splitlines() logical = exp_line - while idx > 0 and lines[idx-1].endswith('\\'): + while idx > 0 and lines[idx - 1].endswith("\\"): idx -= 1 replace_logical_line(lines, logical, idx, exp_n) - exp = src.replace('\\\n', '').strip() - obs = '\n'.join(lines).replace('\\\n', '').strip() + exp = src.replace("\\\n", "").strip() + obs = "\n".join(lines).replace("\\\n", "").strip() assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('f(1,10),x.y', True), - ('"x"', True), - ("'y'", True), - ('b"x"', True), - ("r'y'", True), - ("f'z'", True), - ('"""hello\nmom"""', True), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("f(1,10),x.y", True), + ('"x"', True), + ("'y'", True), + ('b"x"', True), + ("r'y'", True), + ("f'z'", True), + ('"""hello\nmom"""', True), + ], +) def test_check_quotes(inp, exp): obs = check_quotes(inp) assert exp is obs -@pytest.mark.parametrize('inp', [ - 'f(1,10),x.y', -]) +@pytest.mark.parametrize("inp", ["f(1,10),x.y"]) def test_is_balanced_parens(inp): - obs = is_balanced(inp, '(', ')') + obs = is_balanced(inp, "(", ")") assert obs -@pytest.mark.parametrize('inp', [ - 'f(x.', - 'f(1,x.' - 'f((1,10),x.y', -]) +@pytest.mark.parametrize("inp", ["f(x.", "f(1,x." "f((1,10),x.y"]) def test_is_not_balanced_parens(inp): - obs = is_balanced(inp, '(', ')') + obs = is_balanced(inp, "(", ")") assert not obs -@pytest.mark.parametrize('inp, exp', [ - ('f(x.', 'x.'), - ('f(1,x.', 'x.'), - ('f((1,10),x.y', 'x.y'), -]) +@pytest.mark.parametrize( + "inp, exp", [("f(x.", "x."), ("f(1,x.", "x."), ("f((1,10),x.y", "x.y")] +) def test_subexpr_from_unbalanced_parens(inp, exp): - obs = subexpr_from_unbalanced(inp, '(', ')') + obs = subexpr_from_unbalanced(inp, "(", ")") assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('f(x.', 'f'), - ('f(1,x.', 'f'), - ('f((1,10),x.y', 'f'), - ('wakka().f((1,10),x.y', '.f'), - ('wakka(f((1,10),x.y', 'f'), - ('wakka(jawakka().f((1,10),x.y', '.f'), - ('wakka(jawakka().f((1,10),x.y)', 'wakka'), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("f(x.", "f"), + ("f(1,x.", "f"), + ("f((1,10),x.y", "f"), + ("wakka().f((1,10),x.y", ".f"), + ("wakka(f((1,10),x.y", "f"), + ("wakka(jawakka().f((1,10),x.y", ".f"), + ("wakka(jawakka().f((1,10),x.y)", "wakka"), + ], +) def test_subexpr_before_unbalanced_parens(inp, exp): - obs = subexpr_before_unbalanced(inp, '(', ')') + obs = subexpr_before_unbalanced(inp, "(", ")") assert exp == obs -@pytest.mark.parametrize('line, exp', [ - ('', True), - ('wakka jawaka', True), - ('rm *; echo hello world', True), - ('()', True), - ('f()', True), - ('echo * yo ; echo eggs', True), - ('(', False), - (')', False), - ('(cmd;', False), - ('cmd;)', False), -]) +@pytest.mark.parametrize( + "line, exp", + [ + ("", True), + ("wakka jawaka", True), + ("rm *; echo hello world", True), + ("()", True), + ("f()", True), + ("echo * yo ; echo eggs", True), + ("(", False), + (")", False), + ("(cmd;", False), + ("cmd;)", False), + ], +) def test_balanced_parens(line, exp): obs = balanced_parens(line, lexer=LEXER) if exp: @@ -509,57 +579,67 @@ def test_balanced_parens(line, exp): assert not obs -@pytest.mark.parametrize('line, mincol, exp', [ - ('ls && echo a', 0, 4), - ('ls && echo a', 6, None), - ('ls && echo a || echo b', 6, 14), - ('(ls) && echo a', 1, 4), - ('not ls && echo a', 0, 8), - ('not (ls) && echo a', 0, 8), - ('bash -c ! export var=42; echo $var', 0, 35), - ('python -c ! import os; print(os.path.abspath("/"))', 0, 51), - ('echo * yo ; echo eggs', 0, 11), -]) +@pytest.mark.parametrize( + "line, mincol, exp", + [ + ("ls && echo a", 0, 4), + ("ls && echo a", 6, None), + ("ls && echo a || echo b", 6, 14), + ("(ls) && echo a", 1, 4), + ("not ls && echo a", 0, 8), + ("not (ls) && echo a", 0, 8), + ("bash -c ! export var=42; echo $var", 0, 35), + ('python -c ! import os; print(os.path.abspath("/"))', 0, 51), + ("echo * yo ; echo eggs", 0, 11), + ], +) def test_find_next_break(line, mincol, exp): obs = find_next_break(line, mincol=mincol, lexer=LEXER) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (42, True), - (42.0, False), - ('42', False), - ('42.0', False), - ([42], False), - ([], False), - (None, False), - ('', False) -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (42, True), + (42.0, False), + ("42", False), + ("42.0", False), + ([42], False), + ([], False), + (None, False), + ("", False), + ], +) def test_is_int(inp, exp): obs = is_int(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (42.0, True), - (42.000101010010101010101001010101010001011100001101101011100, True), - (42, False), - ('42', False), - ('42.0', False), - ([42], False), - ([], False), - (None, False), - ('', False), - (False, False), - (True, False), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (42.0, True), + (42.000101010010101010101001010101010001011100001101101011100, True), + (42, False), + ("42", False), + ("42.0", False), + ([42], False), + ([], False), + (None, False), + ("", False), + (False, False), + (True, False), + ], +) def test_is_float(inp, exp): obs = is_float(inp) assert exp == obs def test_is_string_true(): - assert is_string('42.0') + assert is_string("42.0") + def test_is_string_false(): assert not is_string(42.0) @@ -573,7 +653,7 @@ def test_is_callable_false(): assert not is_callable(42.0) -@pytest.mark.parametrize('inp', ['42.0', lambda: 42.0]) +@pytest.mark.parametrize("inp", ["42.0", lambda: 42.0]) def test_is_string_or_callable_true(inp): assert is_string_or_callable(inp) @@ -582,45 +662,51 @@ def test_is_string_or_callable_false(): assert not is_string(42.0) -@pytest.mark.parametrize('inp', [42, '42']) +@pytest.mark.parametrize("inp", [42, "42"]) def test_always_true(inp): assert always_true(inp) -@pytest.mark.parametrize('inp', [42, '42']) +@pytest.mark.parametrize("inp", [42, "42"]) def test_always_false(inp): assert not always_false(inp) -@pytest.mark.parametrize('inp, exp', [(42, '42'), ('42', '42'),]) +@pytest.mark.parametrize("inp, exp", [(42, "42"), ("42", "42")]) def test_ensure_string(inp, exp): obs = ensure_string(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('', set()), - ('a', {'a'}), - (os.pathsep.join(['a', 'b']), {'a', 'b'}), - (os.pathsep.join(['a', 'b', 'c']), {'a', 'b', 'c'}), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("", set()), + ("a", {"a"}), + (os.pathsep.join(["a", "b"]), {"a", "b"}), + (os.pathsep.join(["a", "b", "c"]), {"a", "b", "c"}), + ], +) def test_pathsep_to_set(inp, exp): obs = pathsep_to_set(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (set(), ''), - ({'a'}, 'a'), - ({'a', 'b'}, os.pathsep.join(['a', 'b'])), - ({'a', 'b', 'c'}, os.pathsep.join(['a', 'b', 'c'])), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (set(), ""), + ({"a"}, "a"), + ({"a", "b"}, os.pathsep.join(["a", "b"])), + ({"a", "b", "c"}, os.pathsep.join(["a", "b", "c"])), + ], +) def test_set_to_pathsep(inp, exp): obs = set_to_pathsep(inp, sort=(len(inp) > 1)) assert exp == obs -@pytest.mark.parametrize('inp', ['42.0', ['42.0']]) +@pytest.mark.parametrize("inp", ["42.0", ["42.0"]]) def test_is_string_seq_true(inp): assert is_string_seq(inp) @@ -630,130 +716,166 @@ def test_is_string_seq_false(): def test_is_nonstring_seq_of_strings_true(): - assert is_nonstring_seq_of_strings(['42.0']) + assert is_nonstring_seq_of_strings(["42.0"]) def test_is_nonstring_seq_of_strings_false(): assert not is_nonstring_seq_of_strings([42.0]) -@pytest.mark.parametrize('inp, exp', [ - ('', []), - ('a', ['a']), - (os.pathsep.join(['a', 'b']), ['a', 'b']), - (os.pathsep.join(['a', 'b', 'c']), ['a', 'b', 'c']), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("", []), + ("a", ["a"]), + (os.pathsep.join(["a", "b"]), ["a", "b"]), + (os.pathsep.join(["a", "b", "c"]), ["a", "b", "c"]), + ], +) def test_pathsep_to_seq(inp, exp): obs = pathsep_to_seq(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ([], ''), - (['a'], 'a'), - (['a', 'b'], os.pathsep.join(['a', 'b'])), - (['a', 'b', 'c'], os.pathsep.join(['a', 'b', 'c'])), -]) + +@pytest.mark.parametrize( + "inp, exp", + [ + ([], ""), + (["a"], "a"), + (["a", "b"], os.pathsep.join(["a", "b"])), + (["a", "b", "c"], os.pathsep.join(["a", "b", "c"])), + ], +) def test_seq_to_pathsep(inp, exp): obs = seq_to_pathsep(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('', []), - ('a', ['A']), - (os.pathsep.join(['a', 'B']), ['A', 'B']), - (os.pathsep.join(['A', 'b', 'c']), ['A', 'B', 'C']), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("", []), + ("a", ["A"]), + (os.pathsep.join(["a", "B"]), ["A", "B"]), + (os.pathsep.join(["A", "b", "c"]), ["A", "B", "C"]), + ], +) def test_pathsep_to_upper_seq(inp, exp): obs = pathsep_to_upper_seq(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ([], ''), - (['a'], 'A'), - (['a', 'b'], os.pathsep.join(['A', 'B'])), - (['a', 'B', 'c'], os.pathsep.join(['A', 'B', 'C'])), - ]) +@pytest.mark.parametrize( + "inp, exp", + [ + ([], ""), + (["a"], "A"), + (["a", "b"], os.pathsep.join(["A", "B"])), + (["a", "B", "c"], os.pathsep.join(["A", "B", "C"])), + ], +) def test_seq_to_upper_pathsep(inp, exp): obs = seq_to_upper_pathsep(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('/home/wakka', False), - (['/home/jawaka'], False), - (EnvPath(['/home/jawaka']), True), - (EnvPath(['jawaka']), True), - (EnvPath(b'jawaka:wakka'), True), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("/home/wakka", False), + (["/home/jawaka"], False), + (EnvPath(["/home/jawaka"]), True), + (EnvPath(["jawaka"]), True), + (EnvPath(b"jawaka:wakka"), True), + ], +) def test_is_env_path(inp, exp): obs = is_env_path(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('/home/wakka', ['/home/wakka']), - ('/home/wakka' + os.pathsep + '/home/jawaka', - ['/home/wakka', '/home/jawaka']), - (b'/home/wakka', ['/home/wakka']), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("/home/wakka", ["/home/wakka"]), + ("/home/wakka" + os.pathsep + "/home/jawaka", ["/home/wakka", "/home/jawaka"]), + (b"/home/wakka", ["/home/wakka"]), + ], +) def test_str_to_env_path(inp, exp): obs = str_to_env_path(inp) assert exp == obs.paths -@pytest.mark.parametrize('inp, exp', [ - (['/home/wakka'], '/home/wakka'), - (['/home/wakka', '/home/jawaka'], - '/home/wakka' + os.pathsep + '/home/jawaka'), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (["/home/wakka"], "/home/wakka"), + (["/home/wakka", "/home/jawaka"], "/home/wakka" + os.pathsep + "/home/jawaka"), + ], +) def test_env_path_to_str(inp, exp): obs = env_path_to_str(inp) assert exp == obs -@pytest.mark.parametrize('left, right, exp', [ - (EnvPath(['/home/wakka']), ['/home/jawaka'], EnvPath(['/home/wakka', '/home/jawaka'])), - (['a'], EnvPath(['b']), EnvPath(['a', 'b'])), - (EnvPath(['c']), EnvPath(['d']), EnvPath(['c', 'd'])), -]) +@pytest.mark.parametrize( + "left, right, exp", + [ + ( + EnvPath(["/home/wakka"]), + ["/home/jawaka"], + EnvPath(["/home/wakka", "/home/jawaka"]), + ), + (["a"], EnvPath(["b"]), EnvPath(["a", "b"])), + (EnvPath(["c"]), EnvPath(["d"]), EnvPath(["c", "d"])), + ], +) def test_env_path_add(left, right, exp): obs = left + right assert is_env_path(obs) assert exp == obs - - # helper def expand(path): return os.path.expanduser(os.path.expandvars(path)) -@pytest.mark.parametrize('env', [TOOLS_ENV, ENCODE_ENV_ONLY]) -@pytest.mark.parametrize('inp, exp', [ - ('xonsh_dir', 'xonsh_dir'), - ('.', '.'), - ('../', '../'), - ('~/', '~/'), - (b'~/../', '~/../'), -]) + +@pytest.mark.parametrize("env", [TOOLS_ENV, ENCODE_ENV_ONLY]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("xonsh_dir", "xonsh_dir"), + (".", "."), + ("../", "../"), + ("~/", "~/"), + (b"~/../", "~/../"), + ], +) def test_env_path_getitem(inp, exp, xonsh_builtins, env): xonsh_builtins.__xonsh_env__ = env - obs = EnvPath(inp)[0] # call to __getitem__ - if env.get('EXPAND_ENV_VARS'): + obs = EnvPath(inp)[0] # call to __getitem__ + if env.get("EXPAND_ENV_VARS"): assert expand(exp) == obs else: assert exp == obs -@pytest.mark.parametrize('env', [TOOLS_ENV, ENCODE_ENV_ONLY]) -@pytest.mark.parametrize('inp, exp', [ - (os.pathsep.join(['xonsh_dir', '../', '.', '~/']), - ['xonsh_dir', '../', '.', '~/']), - ('/home/wakka' + os.pathsep + '/home/jakka' + os.pathsep + '~/', - ['/home/wakka', '/home/jakka', '~/']) -]) +@pytest.mark.parametrize("env", [TOOLS_ENV, ENCODE_ENV_ONLY]) +@pytest.mark.parametrize( + "inp, exp", + [ + ( + os.pathsep.join(["xonsh_dir", "../", ".", "~/"]), + ["xonsh_dir", "../", ".", "~/"], + ), + ( + "/home/wakka" + os.pathsep + "/home/jakka" + os.pathsep + "~/", + ["/home/wakka", "/home/jakka", "~/"], + ), + ], +) def test_env_path_multipath(inp, exp, xonsh_builtins, env): # cases that involve path-separated strings xonsh_builtins.__xonsh_env__ = env @@ -765,24 +887,28 @@ def test_env_path_multipath(inp, exp, xonsh_builtins, env): assert [i for i in exp] == obs -@pytest.mark.parametrize('inp, exp', [ - (pathlib.Path('/home/wakka'), ['/home/wakka'.replace('/', os.sep)]), - (pathlib.Path('~/'), ['~']), - (pathlib.Path('.'), ['.']), - (['/home/wakka', pathlib.Path('/home/jakka'), '~/'], - ['/home/wakka', '/home/jakka'.replace('/', os.sep), '~/']), - (['/home/wakka', pathlib.Path('../'), '../'], - ['/home/wakka', '..', '../']), - (['/home/wakka', pathlib.Path('~/'), '~/'], - ['/home/wakka', '~', '~/']), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (pathlib.Path("/home/wakka"), ["/home/wakka".replace("/", os.sep)]), + (pathlib.Path("~/"), ["~"]), + (pathlib.Path("."), ["."]), + ( + ["/home/wakka", pathlib.Path("/home/jakka"), "~/"], + ["/home/wakka", "/home/jakka".replace("/", os.sep), "~/"], + ), + (["/home/wakka", pathlib.Path("../"), "../"], ["/home/wakka", "..", "../"]), + (["/home/wakka", pathlib.Path("~/"), "~/"], ["/home/wakka", "~", "~/"]), + ], +) def test_env_path_with_pathlib_path_objects(inp, exp, xonsh_builtins): xonsh_builtins.__xonsh_env__ = TOOLS_ENV # iterate over EnvPath to acquire all expanded paths obs = [i for i in EnvPath(inp)] assert [expand(i) for i in exp] == obs -@pytest.mark.parametrize('inp', ['42.0', [42.0]]) + +@pytest.mark.parametrize("inp", ["42.0", [42.0]]) def test_is_nonstring_seq_of_strings_false(inp): assert not is_nonstring_seq_of_strings(inp) @@ -793,40 +919,49 @@ def mkpath(*paths): return os.sep + os.sep.join(paths) -@pytest.mark.parametrize('inp, exp', [ - ([mkpath('home', 'wakka'), - mkpath('home', 'jakka'), - mkpath('home', 'yakka')], - [mkpath('home', 'wakka'), - mkpath('home', 'jakka')]) -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ( + [mkpath("home", "wakka"), mkpath("home", "jakka"), mkpath("home", "yakka")], + [mkpath("home", "wakka"), mkpath("home", "jakka")], + ) + ], +) def test_env_path_slice_get_all_except_last_element(inp, exp): obs = EnvPath(inp)[:-1] assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ([mkpath('home', 'wakka'), - mkpath('home', 'jakka'), - mkpath('home', 'yakka')], - [mkpath('home', 'jakka'), - mkpath('home', 'yakka')]) -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ( + [mkpath("home", "wakka"), mkpath("home", "jakka"), mkpath("home", "yakka")], + [mkpath("home", "jakka"), mkpath("home", "yakka")], + ) + ], +) def test_env_path_slice_get_all_except_first_element(inp, exp): obs = EnvPath(inp)[1:] assert exp == obs -@pytest.mark.parametrize('inp, exp_a, exp_b', [ - ([mkpath('home', 'wakka'), - mkpath('home', 'jakka'), - mkpath('home', 'yakka'), - mkpath('home', 'takka')], - [mkpath('home', 'wakka'), - mkpath('home', 'yakka')], - [mkpath('home', 'jakka'), - mkpath('home', 'takka')]) -]) +@pytest.mark.parametrize( + "inp, exp_a, exp_b", + [ + ( + [ + mkpath("home", "wakka"), + mkpath("home", "jakka"), + mkpath("home", "yakka"), + mkpath("home", "takka"), + ], + [mkpath("home", "wakka"), mkpath("home", "yakka")], + [mkpath("home", "jakka"), mkpath("home", "takka")], + ) + ], +) def test_env_path_slice_path_with_step(inp, exp_a, exp_b): obs_a = EnvPath(inp)[0::2] assert exp_a == obs_a @@ -834,290 +969,348 @@ def test_env_path_slice_path_with_step(inp, exp_a, exp_b): assert exp_b == obs_b -@pytest.mark.parametrize('inp, exp', [ - ([mkpath('home', 'wakka'), - mkpath('home', 'xakka'), - mkpath('other', 'zakka'), - mkpath('another', 'akka'), - mkpath('home', 'bakka')], - [mkpath('other', 'zakka'), - mkpath('another', 'akka')]) -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ( + [ + mkpath("home", "wakka"), + mkpath("home", "xakka"), + mkpath("other", "zakka"), + mkpath("another", "akka"), + mkpath("home", "bakka"), + ], + [mkpath("other", "zakka"), mkpath("another", "akka")], + ) + ], +) def test_env_path_keep_only_non_home_paths(inp, exp): obs = EnvPath(inp)[2:4] assert exp == obs -@pytest.mark.parametrize('inp', [True, False]) +@pytest.mark.parametrize("inp", [True, False]) def test_is_bool_true(inp): assert True == is_bool(inp) -@pytest.mark.parametrize('inp', [1, 'yooo hooo!']) +@pytest.mark.parametrize("inp", [1, "yooo hooo!"]) def test_is_bool_false(inp): assert False == is_bool(inp) -@pytest.mark.parametrize('inp, exp', [ - (True, True), - (False, False), - (None, False), - ('', False), - ('0', False), - ('False', False), - ('NONE', False), - ('TRUE', True), - ('1', True), - (0, False), - (1, True), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (True, True), + (False, False), + (None, False), + ("", False), + ("0", False), + ("False", False), + ("NONE", False), + ("TRUE", True), + ("1", True), + (0, False), + (1, True), + ], +) def test_to_bool(inp, exp): obs = to_bool(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [(True, '1'), (False, '')]) +@pytest.mark.parametrize("inp, exp", [(True, "1"), (False, "")]) def test_bool_to_str(inp, exp): assert bool_to_str(inp) == exp -@pytest.mark.parametrize('inp, exp', [ - (True, True), - (False, True), - (1, True), - (0, True), - ('Yolo', False), - (1.0, False), -]) +@pytest.mark.parametrize( + "inp, exp", + [(True, True), (False, True), (1, True), (0, True), ("Yolo", False), (1.0, False)], +) def test_is_bool_or_int(inp, exp): obs = is_bool_or_int(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (True, True), - (False, False), - (1, 1), - (0, 0), - ('', False), - (0.0, False), - (1.0, True), - ('T', True), - ('f', False), - ('0', 0), - ('10', 10), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (True, True), + (False, False), + (1, 1), + (0, 0), + ("", False), + (0.0, False), + (1.0, True), + ("T", True), + ("f", False), + ("0", 0), + ("10", 10), + ], +) def test_to_bool_or_int(inp, exp): obs = to_bool_or_int(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (True, '1'), - (False, ''), - (1, '1'), - (0, '0'), -]) +@pytest.mark.parametrize("inp, exp", [(True, "1"), (False, ""), (1, "1"), (0, "0")]) def test_bool_or_int_to_str(inp, exp): obs = bool_or_int_to_str(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ +@pytest.mark.parametrize( + "inp, exp", + [ (42, slice(42, 43)), (0, slice(0, 1)), (None, slice(None, None, None)), (slice(1, 2), slice(1, 2)), - ('-1', slice(-1, None, None)), - ('42', slice(42, 43)), - ('-42', slice(-42, -41)), - ('1:2:3', slice(1, 2, 3)), - ('1::3', slice(1, None, 3)), - (':', slice(None, None, None)), - ('1:', slice(1, None, None)), - ('[1:2:3]', slice(1, 2, 3)), - ('(1:2:3)', slice(1, 2, 3)), + ("-1", slice(-1, None, None)), + ("42", slice(42, 43)), + ("-42", slice(-42, -41)), + ("1:2:3", slice(1, 2, 3)), + ("1::3", slice(1, None, 3)), + (":", slice(None, None, None)), + ("1:", slice(1, None, None)), + ("[1:2:3]", slice(1, 2, 3)), + ("(1:2:3)", slice(1, 2, 3)), ((4, 8, 10), slice(4, 8, 10)), - ([10, 20], slice(10, 20)) - ]) + ([10, 20], slice(10, 20)), + ], +) def test_ensure_slice(inp, exp): obs = ensure_slice(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ((range(50), slice(25, 40)), - list(i for i in range(25, 40))), - - (([1,2,3,4,5,6,7,8,9,10], [slice(1,4), slice(6, None)]), - [2, 3, 4, 7, 8, 9, 10]), - - (([1,2,3,4,5], [slice(-2, None), slice(-5, -3)]), - [4, 5, 1, 2]), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ((range(50), slice(25, 40)), list(i for i in range(25, 40))), + ( + ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [slice(1, 4), slice(6, None)]), + [2, 3, 4, 7, 8, 9, 10], + ), + (([1, 2, 3, 4, 5], [slice(-2, None), slice(-5, -3)]), [4, 5, 1, 2]), + ], +) def test_get_portions(inp, exp): obs = get_portions(*inp) assert list(obs) == exp -@pytest.mark.parametrize('inp', [ - '42.3', - '3:asd5:1', - 'test' , - '6.53:100:5', - '4:-', - '2:15-:3', - '50:-:666', - object(), - [1,5,3,4], - ('foo') -]) +@pytest.mark.parametrize( + "inp", + [ + "42.3", + "3:asd5:1", + "test", + "6.53:100:5", + "4:-", + "2:15-:3", + "50:-:666", + object(), + [1, 5, 3, 4], + ("foo"), + ], +) def test_ensure_slice_invalid(inp): with pytest.raises(ValueError): obs = ensure_slice(inp) -@pytest.mark.parametrize('inp, exp', [ - ('42', True), - ('42.0', False), - (42, False), - ([42], False), - ([], False), - (None, False), - ('', False), - (False, False), - (True, False), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("42", True), + ("42.0", False), + (42, False), + ([42], False), + ([], False), + (None, False), + ("", False), + (False, False), + (True, False), + ], +) def test_is_int_as_str(inp, exp): obs = is_int_as_str(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('20', False), - ('20%', False), - ((20, 'c'), False), - ((20.0, 'm'), False), - ((20.0, 'c'), True), - ((20.0, '%'), True), -]) + + +@pytest.mark.parametrize( + "inp, exp", + [ + ("20", False), + ("20%", False), + ((20, "c"), False), + ((20.0, "m"), False), + ((20.0, "c"), True), + ((20.0, "%"), True), + ], +) def test_is_dynamic_cwd_width(inp, exp): obs = is_dynamic_cwd_width(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (42, False), - (None, False), - ('42', False), - ('-42', False), - (slice(1,2,3), False), - ([], False), - (False, False), - (True, False), - ('1:2:3', True), - ('1::3', True), - ('1:', True), - (':', True), - ('[1:2:3]', True), - ('(1:2:3)', True), - ('r', False), - ('r:11', False), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (42, False), + (None, False), + ("42", False), + ("-42", False), + (slice(1, 2, 3), False), + ([], False), + (False, False), + (True, False), + ("1:2:3", True), + ("1::3", True), + ("1:", True), + (":", True), + ("[1:2:3]", True), + ("(1:2:3)", True), + ("r", False), + ("r:11", False), + ], +) def test_is_slice_as_str(inp, exp): obs = is_slice_as_str(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('throwback.log', True), - ('', True), - (None, True), - (True, False), - (False, False), - (42, False), - ([1, 2, 3], False), - ((1, 2), False), - (("wrong", "parameter"), False), - skip_if_on_windows(('/dev/null', True)) -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("throwback.log", True), + ("", True), + (None, True), + (True, False), + (False, False), + (42, False), + ([1, 2, 3], False), + ((1, 2), False), + (("wrong", "parameter"), False), + skip_if_on_windows(("/dev/null", True)), + ], +) def test_is_logfile_opt(inp, exp): obs = is_logfile_opt(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ +@pytest.mark.parametrize( + "inp, exp", + [ (True, None), (False, None), (1, None), (None, None), - ('throwback.log', 'throwback.log'), - skip_if_on_windows(('/dev/null', '/dev/null')), - skip_if_on_windows(('/dev/nonexistent_dev', - '/dev/nonexistent_dev' if is_writable_file('/dev/nonexistent_dev') else None)) - ]) + ("throwback.log", "throwback.log"), + skip_if_on_windows(("/dev/null", "/dev/null")), + skip_if_on_windows( + ( + "/dev/nonexistent_dev", + "/dev/nonexistent_dev" + if is_writable_file("/dev/nonexistent_dev") + else None, + ) + ), + ], +) def test_to_logfile_opt(inp, exp): obs = to_logfile_opt(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - (None, ''), - ('', ''), - ('throwback.log', 'throwback.log'), - ('/dev/null', '/dev/null') -]) +@pytest.mark.parametrize( + "inp, exp", + [ + (None, ""), + ("", ""), + ("throwback.log", "throwback.log"), + ("/dev/null", "/dev/null"), + ], +) def test_logfile_opt_to_str(inp, exp): obs = logfile_opt_to_str(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ('20', (20.0, 'c')), - ('20%', (20.0, '%')), - ((20, 'c'), (20.0, 'c')), - ((20, '%'), (20.0, '%')), - ((20.0, 'c'), (20.0, 'c')), - ((20.0, '%'), (20.0, '%')), - ('inf', (float('inf'), 'c')), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("20", (20.0, "c")), + ("20%", (20.0, "%")), + ((20, "c"), (20.0, "c")), + ((20, "%"), (20.0, "%")), + ((20.0, "c"), (20.0, "c")), + ((20.0, "%"), (20.0, "%")), + ("inf", (float("inf"), "c")), + ], +) def test_to_dynamic_cwd_tuple(inp, exp): obs = to_dynamic_cwd_tuple(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ((20.0, 'c'), '20.0'), - ((20.0, '%'), '20.0%'), - ((float('inf'), 'c'), 'inf'), -]) +@pytest.mark.parametrize( + "inp, exp", + [((20.0, "c"), "20.0"), ((20.0, "%"), "20.0%"), ((float("inf"), "c"), "inf")], +) def test_dynamic_cwd_tuple_to_str(inp, exp): obs = dynamic_cwd_tuple_to_str(inp) assert exp == obs -@pytest.mark.parametrize('st, esc', [ - ('', ''), - ('foo', 'foo'), - ('foo&bar', 'foo^&bar'), - ('foo$?-/_"\\', 'foo$?-/_^"\\'), - ('^&<>|', '^^^&^<^>^|'), - ('()<>','^(^)^<^>'), -]) +@pytest.mark.parametrize( + "st, esc", + [ + ("", ""), + ("foo", "foo"), + ("foo&bar", "foo^&bar"), + ('foo$?-/_"\\', 'foo$?-/_^"\\'), + ("^&<>|", "^^^&^<^>^|"), + ("()<>", "^(^)^<^>"), + ], +) def test_escape_windows_cmd_string(st, esc): obs = escape_windows_cmd_string(st) assert esc == obs -@pytest.mark.parametrize('st, esc, forced', [ - ('', '""', None), - ('foo', 'foo', '"foo"'), - (r'arg1 "hallo, "world"" "\some\path with\spaces")', - r'"arg1 \"hallo, \"world\"\" \"\some\path with\spaces\")"', None), - (r'"argument"2" argument3 argument4', - r'"\"argument\"2\" argument3 argument4"', None), - (r'"\foo\bar bar\foo\" arg', r'"\"\foo\bar bar\foo\\\" arg"', None), - (r'\\machine\dir\file.bat', r'\\machine\dir\file.bat', r'"\\machine\dir\file.bat"'), - (r'"\\machine\dir space\file.bat"', r'"\"\\machine\dir space\file.bat\""', None) -]) +@pytest.mark.parametrize( + "st, esc, forced", + [ + ("", '""', None), + ("foo", "foo", '"foo"'), + ( + r'arg1 "hallo, "world"" "\some\path with\spaces")', + r'"arg1 \"hallo, \"world\"\" \"\some\path with\spaces\")"', + None, + ), + ( + r'"argument"2" argument3 argument4', + r'"\"argument\"2\" argument3 argument4"', + None, + ), + (r'"\foo\bar bar\foo\" arg', r'"\"\foo\bar bar\foo\\\" arg"', None), + ( + r"\\machine\dir\file.bat", + r"\\machine\dir\file.bat", + r'"\\machine\dir\file.bat"', + ), + ( + r'"\\machine\dir space\file.bat"', + r'"\"\\machine\dir space\file.bat\""', + None, + ), + ], +) def test_argvquote(st, esc, forced): obs = argvquote(st) assert esc == obs @@ -1128,21 +1321,20 @@ def test_argvquote(st, esc, forced): assert forced == obs -@pytest.mark.parametrize('inp', ['no string here', '']) +@pytest.mark.parametrize("inp", ["no string here", ""]) def test_partial_string_none(inp): assert check_for_partial_string(inp) == (None, None, None) -@pytest.mark.parametrize('leaders', [ - (('', 0), ('not empty', 9)), - (('not empty', 9), ('', 0)) -]) -@pytest.mark.parametrize('prefix', ['b', 'rb', 'r' ]) -@pytest.mark.parametrize('quote', ['"', '"""']) +@pytest.mark.parametrize( + "leaders", [(("", 0), ("not empty", 9)), (("not empty", 9), ("", 0))] +) +@pytest.mark.parametrize("prefix", ["b", "rb", "r"]) +@pytest.mark.parametrize("quote", ['"', '"""']) def test_partial_string(leaders, prefix, quote): (l, l_len), (f, f_len) = leaders s = prefix + quote - t = s + 'test string' + quote + t = s + "test string" + quote t_len = len(t) # single string test_string = l + t + f @@ -1150,7 +1342,7 @@ def test_partial_string(leaders, prefix, quote): exp = l_len, l_len + t_len, s assert obs == exp # single partial - test_string = l + f + s + 'test string' + test_string = l + f + s + "test string" obs = check_for_partial_string(test_string) exp = l_len + f_len, None, s assert obs == exp @@ -1160,43 +1352,43 @@ def test_partial_string(leaders, prefix, quote): exp = (l_len + t_len + f_len + l_len), (l_len + t_len + f_len + l_len + t_len), s assert obs == exp # one string, one partial - test_string = l + t + f + l + s + 'test string' + test_string = l + t + f + l + s + "test string" obs = check_for_partial_string(test_string) - exp = l_len + t_len + f_len + l_len , None, s + exp = l_len + t_len + f_len + l_len, None, s assert obs == exp def test_executables_in(xonsh_builtins): expected = set() - types = ('file', 'directory', 'brokensymlink') + types = ("file", "directory", "brokensymlink") if ON_WINDOWS: # Don't test symlinks on windows since it requires admin - types = ('file', 'directory') + types = ("file", "directory") executables = (True, False) with TemporaryDirectory() as test_path: for _type in types: for executable in executables: - fname = '%s_%s' % (_type, executable) - if _type == 'none': + fname = "%s_%s" % (_type, executable) + if _type == "none": continue - if _type == 'file' and executable: - ext = '.exe' if ON_WINDOWS else '' + if _type == "file" and executable: + ext = ".exe" if ON_WINDOWS else "" expected.add(fname + ext) else: - ext = '' + ext = "" path = os.path.join(test_path, fname + ext) - if _type == 'file': - with open(path, 'w') as f: + if _type == "file": + with open(path, "w") as f: f.write(fname) - elif _type == 'directory': + elif _type == "directory": os.mkdir(path) - elif _type == 'brokensymlink': - tmp_path = os.path.join(test_path, 'i_wont_exist') - with open(tmp_path, 'w') as f: - f.write('deleteme') + elif _type == "brokensymlink": + tmp_path = os.path.join(test_path, "i_wont_exist") + with open(tmp_path, "w") as f: + f.write("deleteme") os.symlink(tmp_path, path) os.remove(tmp_path) - if executable and not _type == 'brokensymlink': + if executable and not _type == "brokensymlink": os.chmod(path, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR) if ON_WINDOWS: xonsh_builtins.__xonsh_env__ = PATHEXT_ENV @@ -1206,128 +1398,165 @@ def test_executables_in(xonsh_builtins): assert expected == result -@pytest.mark.parametrize('inp, exp', [ - ('yo', '[Yy][Oo]'), - ('[a-f]123e', '[a-f]123[Ee]'), - ('${HOME}/yo', '${HOME}/[Yy][Oo]'), - ('./yo/mom', './[Yy][Oo]/[Mm][Oo][Mm]'), - ('Eßen', '[Ee][Ss]?[Ssß][Ee][Nn]'), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("yo", "[Yy][Oo]"), + ("[a-f]123e", "[a-f]123[Ee]"), + ("${HOME}/yo", "${HOME}/[Yy][Oo]"), + ("./yo/mom", "./[Yy][Oo]/[Mm][Oo][Mm]"), + ("Eßen", "[Ee][Ss]?[Ssß][Ee][Nn]"), + ], +) def test_expand_case_matching(inp, exp): obs = expand_case_matching(inp) assert exp == obs -@pytest.mark.parametrize('inp, exp', [ - ("foo", "foo"), - ("$foo $bar", "bar $bar"), - ("$foobar", "$foobar"), - ("$foo $spam", "bar eggs"), - ("$an_int$spam$a_bool", "42eggsTrue"), - ("bar$foo$spam$foo $an_int $none", "barbareggsbar 42 None"), - ("$foo/bar", "bar/bar"), - ("${'foo'} $spam", "bar eggs"), - ("${'foo'} ${'a_bool'}", "bar True"), - ("${'foo'}bar", "barbar"), - ("${'foo'}/bar", "bar/bar"), - ("${\"foo\'}", "${\"foo\'}"), - ("$?bar", "$?bar"), - ("$foo}bar", "bar}bar"), - ("${'foo", "${'foo"), - (b"foo", "foo"), - (b"$foo bar", "bar bar"), - (b"${'foo'}bar", "barbar"), -]) +@pytest.mark.parametrize( + "inp, exp", + [ + ("foo", "foo"), + ("$foo $bar", "bar $bar"), + ("$foobar", "$foobar"), + ("$foo $spam", "bar eggs"), + ("$an_int$spam$a_bool", "42eggsTrue"), + ("bar$foo$spam$foo $an_int $none", "barbareggsbar 42 None"), + ("$foo/bar", "bar/bar"), + ("${'foo'} $spam", "bar eggs"), + ("${'foo'} ${'a_bool'}", "bar True"), + ("${'foo'}bar", "barbar"), + ("${'foo'}/bar", "bar/bar"), + ("${\"foo'}", "${\"foo'}"), + ("$?bar", "$?bar"), + ("$foo}bar", "bar}bar"), + ("${'foo", "${'foo"), + (b"foo", "foo"), + (b"$foo bar", "bar bar"), + (b"${'foo'}bar", "barbar"), + ], +) def test_expandvars(inp, exp, xonsh_builtins): """Tweaked for xonsh cases from CPython `test_genericpath.py`""" - env = Env({'foo':'bar', 'spam': 'eggs', 'a_bool': True, 'an_int': 42, 'none': None}) + env = Env( + {"foo": "bar", "spam": "eggs", "a_bool": True, "an_int": 42, "none": None} + ) xonsh_builtins.__xonsh_env__ = env assert expandvars(inp) == exp -@pytest.mark.parametrize('inp, fmt, exp',[ - (572392800.0, None, 572392800.0), - ('42.1459', None, 42.1459), - (dt.datetime(2016, 8, 2, 13, 24), None, dt.datetime(2016, 8, 2, 13, 24).timestamp()), - ('2016-8-10 16:14', None, dt.datetime(2016, 8, 10, 16, 14).timestamp()), - ('2016/8/10 16:14:40', '%Y/%m/%d %H:%M:%S', dt.datetime(2016, 8, 10, 16, 14, 40).timestamp()), - ]) +@pytest.mark.parametrize( + "inp, fmt, exp", + [ + (572392800.0, None, 572392800.0), + ("42.1459", None, 42.1459), + ( + dt.datetime(2016, 8, 2, 13, 24), + None, + dt.datetime(2016, 8, 2, 13, 24).timestamp(), + ), + ("2016-8-10 16:14", None, dt.datetime(2016, 8, 10, 16, 14).timestamp()), + ( + "2016/8/10 16:14:40", + "%Y/%m/%d %H:%M:%S", + dt.datetime(2016, 8, 10, 16, 14, 40).timestamp(), + ), + ], +) def test_ensure_timestamp(inp, fmt, exp, xonsh_builtins): - xonsh_builtins.__xonsh_env__['XONSH_DATETIME_FORMAT'] = '%Y-%m-%d %H:%M' + xonsh_builtins.__xonsh_env__["XONSH_DATETIME_FORMAT"] = "%Y-%m-%d %H:%M" obs = ensure_timestamp(inp, fmt) assert exp == obs -@pytest.mark.parametrize('expand_user', [True, False]) -@pytest.mark.parametrize('inp, expand_env_vars, exp_end', [ - ('~/test.txt', True, '/test.txt'), - ('~/$foo', True, '/bar'), - ('~/test/$a_bool', True, '/test/True'), - ('~/test/$an_int', True, '/test/42'), - ('~/test/$none', True, '/test/None'), - ('~/$foo', False, '/$foo') -]) +@pytest.mark.parametrize("expand_user", [True, False]) +@pytest.mark.parametrize( + "inp, expand_env_vars, exp_end", + [ + ("~/test.txt", True, "/test.txt"), + ("~/$foo", True, "/bar"), + ("~/test/$a_bool", True, "/test/True"), + ("~/test/$an_int", True, "/test/42"), + ("~/test/$none", True, "/test/None"), + ("~/$foo", False, "/$foo"), + ], +) def test_expand_path(expand_user, inp, expand_env_vars, exp_end, xonsh_builtins): - if os.sep != '/': - inp = inp.replace('/', os.sep) - exp_end = exp_end.replace('/', os.sep) + if os.sep != "/": + inp = inp.replace("/", os.sep) + exp_end = exp_end.replace("/", os.sep) - env = Env({'foo':'bar', 'a_bool': True, 'an_int': 42, 'none': None}) - env['EXPAND_ENV_VARS'] = expand_env_vars + env = Env({"foo": "bar", "a_bool": True, "an_int": 42, "none": None}) + env["EXPAND_ENV_VARS"] = expand_env_vars xonsh_builtins.__xonsh_env__ = env path = expand_path(inp, expand_user=expand_user) if expand_user: - home_path = os.path.expanduser('~') + home_path = os.path.expanduser("~") assert path == home_path + exp_end else: - assert path == '~' + exp_end + assert path == "~" + exp_end def test_swap_values(): - orig = {'x': 1} - updates = {'x': 42, 'y': 43} + orig = {"x": 1} + updates = {"x": 42, "y": 43} with swap_values(orig, updates): - assert orig['x'] == 42 - assert orig['y'] == 43 - assert orig['x'] == 1 - assert 'y' not in orig + assert orig["x"] == 42 + assert orig["y"] == 43 + assert orig["x"] == 1 + assert "y" not in orig -@pytest.mark.parametrize('arguments, expected_docstring', [ - ({'deprecated_in': '0.5.10', 'removed_in': '0.6.0'}, - 'my_function has been deprecated in version 0.5.10 and will be removed ' - 'in version 0.6.0'), - ({'deprecated_in': '0.5.10'}, - 'my_function has been deprecated in version 0.5.10'), - ({'removed_in': '0.6.0'}, - 'my_function has been deprecated and will be removed in version 0.6.0'), - ({}, - 'my_function has been deprecated') -]) -def test_deprecated_docstrings_with_empty_docstring( - arguments, expected_docstring): +@pytest.mark.parametrize( + "arguments, expected_docstring", + [ + ( + {"deprecated_in": "0.5.10", "removed_in": "0.6.0"}, + "my_function has been deprecated in version 0.5.10 and will be removed " + "in version 0.6.0", + ), + ( + {"deprecated_in": "0.5.10"}, + "my_function has been deprecated in version 0.5.10", + ), + ( + {"removed_in": "0.6.0"}, + "my_function has been deprecated and will be removed in version 0.6.0", + ), + ({}, "my_function has been deprecated"), + ], +) +def test_deprecated_docstrings_with_empty_docstring(arguments, expected_docstring): @deprecated(**arguments) - def my_function(): pass + def my_function(): + pass assert my_function.__doc__ == expected_docstring -@pytest.mark.parametrize('arguments, expected_docstring', [ - ({'deprecated_in': '0.5.10', 'removed_in': '0.6.0'}, - 'Does nothing.\n\nmy_function has been deprecated in version 0.5.10 and ' - 'will be removed in version 0.6.0'), - ({'deprecated_in': '0.5.10'}, - 'Does nothing.\n\nmy_function has been deprecated in version 0.5.10'), - ({'removed_in': '0.6.0'}, - 'Does nothing.\n\nmy_function has been deprecated and will be removed ' - 'in version 0.6.0'), - ({}, - 'Does nothing.\n\nmy_function has been deprecated') -]) -def test_deprecated_docstrings_with_nonempty_docstring( - arguments, expected_docstring): +@pytest.mark.parametrize( + "arguments, expected_docstring", + [ + ( + {"deprecated_in": "0.5.10", "removed_in": "0.6.0"}, + "Does nothing.\n\nmy_function has been deprecated in version 0.5.10 and " + "will be removed in version 0.6.0", + ), + ( + {"deprecated_in": "0.5.10"}, + "Does nothing.\n\nmy_function has been deprecated in version 0.5.10", + ), + ( + {"removed_in": "0.6.0"}, + "Does nothing.\n\nmy_function has been deprecated and will be removed " + "in version 0.6.0", + ), + ({}, "Does nothing.\n\nmy_function has been deprecated"), + ], +) +def test_deprecated_docstrings_with_nonempty_docstring(arguments, expected_docstring): @deprecated(**arguments) def my_function(): """Does nothing.""" @@ -1338,10 +1567,11 @@ def test_deprecated_docstrings_with_nonempty_docstring( def test_deprecated_warning_raised(): @deprecated() - def my_function(): pass + def my_function(): + pass with warnings.catch_warnings(record=True) as warning: - warnings.simplefilter('always') + warnings.simplefilter("always") my_function() @@ -1350,20 +1580,22 @@ def test_deprecated_warning_raised(): def test_deprecated_warning_contains_message(): @deprecated() - def my_function(): pass + def my_function(): + pass with warnings.catch_warnings(record=True) as warning: - warnings.simplefilter('always') + warnings.simplefilter("always") my_function() - assert str(warning.pop().message) == 'my_function has been deprecated' + assert str(warning.pop().message) == "my_function has been deprecated" -@pytest.mark.parametrize('expired_version', ['0.1.0', __version__]) +@pytest.mark.parametrize("expired_version", ["0.1.0", __version__]) def test_deprecated_past_expiry_raises_assertion_error(expired_version): @deprecated(removed_in=expired_version) - def my_function(): pass + def my_function(): + pass with pytest.raises(AssertionError): my_function() @@ -1373,11 +1605,14 @@ def test_iglobpath_empty_str(monkeypatch, xonsh_builtins): # makes sure that iglobpath works, even when os.scandir() and os.listdir() # fail to return valid results, like an empty filename def mockscandir(path): - yield '' - if hasattr(os, 'scandir'): - monkeypatch.setattr(os, 'scandir', mockscandir) + yield "" + + if hasattr(os, "scandir"): + monkeypatch.setattr(os, "scandir", mockscandir) + def mocklistdir(path): - return [''] - monkeypatch.setattr(os, 'listdir', mocklistdir) - paths = list(iglobpath('some/path')) + return [""] + + monkeypatch.setattr(os, "listdir", mocklistdir) + paths = list(iglobpath("some/path")) assert len(paths) == 0 diff --git a/tests/test_vox.py b/tests/test_vox.py index 077ef1584..9b69990b1 100644 --- a/tests/test_vox.py +++ b/tests/test_vox.py @@ -16,36 +16,36 @@ def test_crud(xonsh_builtins, tmpdir): """ Creates a virtual environment, gets it, enumerates it, and then deletes it. """ - xonsh_builtins.__xonsh_env__['VIRTUALENV_HOME'] = str(tmpdir) + xonsh_builtins.__xonsh_env__["VIRTUALENV_HOME"] = str(tmpdir) last_event = None @xonsh_builtins.events.vox_on_create def create(name, **_): nonlocal last_event - last_event = 'create', name + last_event = "create", name @xonsh_builtins.events.vox_on_delete def delete(name, **_): nonlocal last_event - last_event = 'delete', name + last_event = "delete", name vox = Vox() - vox.create('spam') - assert stat.S_ISDIR(tmpdir.join('spam').stat().mode) - assert last_event == ('create', 'spam') + vox.create("spam") + assert stat.S_ISDIR(tmpdir.join("spam").stat().mode) + assert last_event == ("create", "spam") - ve = vox['spam'] - assert ve.env == str(tmpdir.join('spam')) + ve = vox["spam"] + assert ve.env == str(tmpdir.join("spam")) assert os.path.isdir(ve.bin) - assert 'spam' in vox - assert 'spam' in list(vox) + assert "spam" in vox + assert "spam" in list(vox) - del vox['spam'] + del vox["spam"] - assert not tmpdir.join('spam').check() - assert last_event == ('delete', 'spam') + assert not tmpdir.join("spam").check() + assert last_event == ("delete", "spam") @skip_if_on_msys @@ -54,30 +54,30 @@ def test_activate(xonsh_builtins, tmpdir): """ Creates a virtual environment, gets it, enumerates it, and then deletes it. """ - xonsh_builtins.__xonsh_env__['VIRTUALENV_HOME'] = str(tmpdir) + xonsh_builtins.__xonsh_env__["VIRTUALENV_HOME"] = str(tmpdir) # I consider the case that the user doesn't have a PATH set to be unreasonable - xonsh_builtins.__xonsh_env__.setdefault('PATH', []) + xonsh_builtins.__xonsh_env__.setdefault("PATH", []) last_event = None @xonsh_builtins.events.vox_on_activate def activate(name, **_): nonlocal last_event - last_event = 'activate', name + last_event = "activate", name @xonsh_builtins.events.vox_on_deactivate def deactivate(name, **_): nonlocal last_event - last_event = 'deactivate', name + last_event = "deactivate", name vox = Vox() - vox.create('spam') - vox.activate('spam') - assert xonsh_builtins.__xonsh_env__['VIRTUAL_ENV'] == vox['spam'].env - assert last_event == ('activate', 'spam') + vox.create("spam") + vox.activate("spam") + assert xonsh_builtins.__xonsh_env__["VIRTUAL_ENV"] == vox["spam"].env + assert last_event == ("activate", "spam") vox.deactivate() - assert 'VIRTUAL_ENV' not in xonsh_builtins.__xonsh_env__ - assert last_event == ('deactivate', 'spam') + assert "VIRTUAL_ENV" not in xonsh_builtins.__xonsh_env__ + assert last_event == ("deactivate", "spam") @skip_if_on_msys @@ -86,21 +86,21 @@ def test_path(xonsh_builtins, tmpdir): """ Test to make sure Vox properly activates and deactivates by examining $PATH """ - xonsh_builtins.__xonsh_env__['VIRTUALENV_HOME'] = str(tmpdir) + xonsh_builtins.__xonsh_env__["VIRTUALENV_HOME"] = str(tmpdir) # I consider the case that the user doesn't have a PATH set to be unreasonable - xonsh_builtins.__xonsh_env__.setdefault('PATH', []) + xonsh_builtins.__xonsh_env__.setdefault("PATH", []) - oldpath = list(xonsh_builtins.__xonsh_env__['PATH']) + oldpath = list(xonsh_builtins.__xonsh_env__["PATH"]) vox = Vox() - vox.create('eggs') + vox.create("eggs") + + vox.activate("eggs") + + assert oldpath != xonsh_builtins.__xonsh_env__["PATH"] - vox.activate('eggs') - - assert oldpath != xonsh_builtins.__xonsh_env__['PATH'] - vox.deactivate() - - assert oldpath == xonsh_builtins.__xonsh_env__['PATH'] + + assert oldpath == xonsh_builtins.__xonsh_env__["PATH"] @skip_if_on_msys @@ -109,31 +109,33 @@ def test_crud_subdir(xonsh_builtins, tmpdir): """ Creates a virtual environment, gets it, enumerates it, and then deletes it. """ - xonsh_builtins.__xonsh_env__['VIRTUALENV_HOME'] = str(tmpdir) + xonsh_builtins.__xonsh_env__["VIRTUALENV_HOME"] = str(tmpdir) vox = Vox() - vox.create('spam/eggs') - assert stat.S_ISDIR(tmpdir.join('spam', 'eggs').stat().mode) + vox.create("spam/eggs") + assert stat.S_ISDIR(tmpdir.join("spam", "eggs").stat().mode) - ve = vox['spam/eggs'] - assert ve.env == str(tmpdir.join('spam', 'eggs')) + ve = vox["spam/eggs"] + assert ve.env == str(tmpdir.join("spam", "eggs")) assert os.path.isdir(ve.bin) - assert 'spam/eggs' in vox - assert 'spam' not in vox + assert "spam/eggs" in vox + assert "spam" not in vox - #assert 'spam/eggs' in list(vox) # This is NOT true on Windows - assert 'spam' not in list(vox) + # assert 'spam/eggs' in list(vox) # This is NOT true on Windows + assert "spam" not in list(vox) - del vox['spam/eggs'] + del vox["spam/eggs"] + + assert not tmpdir.join("spam", "eggs").check() - assert not tmpdir.join('spam', 'eggs').check() try: import pathlib except ImportError: pass else: + @skip_if_on_msys @skip_if_on_conda def test_crud_path(xonsh_builtins, tmpdir): @@ -144,7 +146,7 @@ else: vox = Vox() vox.create(tmp) - assert stat.S_ISDIR(tmpdir.join('lib').stat().mode) + assert stat.S_ISDIR(tmpdir.join("lib").stat().mode) ve = vox[tmp] assert ve.env == str(tmp) @@ -161,17 +163,17 @@ def test_crud_subdir(xonsh_builtins, tmpdir): """ Creates a virtual environment, gets it, enumerates it, and then deletes it. """ - xonsh_builtins.__xonsh_env__['VIRTUALENV_HOME'] = str(tmpdir) + xonsh_builtins.__xonsh_env__["VIRTUALENV_HOME"] = str(tmpdir) vox = Vox() with pytest.raises(ValueError): if ON_WINDOWS: - vox.create('Scripts') + vox.create("Scripts") else: - vox.create('bin') + vox.create("bin") with pytest.raises(ValueError): if ON_WINDOWS: - vox.create('spameggs/Scripts') + vox.create("spameggs/Scripts") else: - vox.create('spameggs/bin') + vox.create("spameggs/bin") diff --git a/tests/test_wizard.py b/tests/test_wizard.py index 3aa56a00b..25d95ed92 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -5,78 +5,97 @@ import os import pytest -from xonsh.wizard import (Node, Wizard, Pass, PrettyFormatter, - Message, Question, StateVisitor, FileInserter) +from xonsh.wizard import ( + Node, + Wizard, + Pass, + PrettyFormatter, + Message, + Question, + StateVisitor, + FileInserter, +) -TREE0 = Wizard(children=[Pass(), Message(message='yo')]) -TREE1 = Question('wakka?', {'jawaka': Pass()}) +TREE0 = Wizard(children=[Pass(), Message(message="yo")]) +TREE1 = Question("wakka?", {"jawaka": Pass()}) + def test_pretty_format_tree0(): - exp = ('Wizard(children=[\n' - ' Pass(),\n' - " Message('yo')\n" - '])') + exp = "Wizard(children=[\n" " Pass(),\n" " Message('yo')\n" "])" obs = PrettyFormatter(TREE0).visit() assert exp == obs assert exp == str(TREE0) - assert exp.replace('\n', '') == repr(TREE0) + assert exp.replace("\n", "") == repr(TREE0) def test_pretty_format_tree1(): - exp = ('Question(\n' - " question='wakka?',\n" - ' responses={\n' - " 'jawaka': Pass()\n" - ' }\n' - ')') + exp = ( + "Question(\n" + " question='wakka?',\n" + " responses={\n" + " 'jawaka': Pass()\n" + " }\n" + ")" + ) obs = PrettyFormatter(TREE1).visit() assert exp == obs assert exp == str(TREE1) - assert exp.replace('\n', '') == repr(TREE1) + assert exp.replace("\n", "") == repr(TREE1) def test_state_visitor_store(): - exp = {'rick': [{}, {}, {'and': 'morty'}]} + exp = {"rick": [{}, {}, {"and": "morty"}]} sv = StateVisitor() - sv.store('/rick/2/and', 'morty') + sv.store("/rick/2/and", "morty") obs = sv.state assert exp == obs - exp['rick'][1]['mr'] = 'meeseeks' - sv.store('/rick/-2/mr', 'meeseeks') + exp["rick"][1]["mr"] = "meeseeks" + sv.store("/rick/-2/mr", "meeseeks") assert exp == obs - flat_exp = {'/': {'rick': [{}, {'mr': 'meeseeks'}, {'and': 'morty'}]}, - '/rick/': [{}, {'mr': 'meeseeks'}, {'and': 'morty'}], - '/rick/0/': {}, - '/rick/1/': {'mr': 'meeseeks'}, - '/rick/1/mr': 'meeseeks', - '/rick/2/': {'and': 'morty'}, - '/rick/2/and': 'morty', - } + flat_exp = { + "/": {"rick": [{}, {"mr": "meeseeks"}, {"and": "morty"}]}, + "/rick/": [{}, {"mr": "meeseeks"}, {"and": "morty"}], + "/rick/0/": {}, + "/rick/1/": {"mr": "meeseeks"}, + "/rick/1/mr": "meeseeks", + "/rick/2/": {"and": "morty"}, + "/rick/2/and": "morty", + } flat_obs = sv.flatten() assert flat_exp == flat_obs def dump_xonfig_env_mock(path, value): - name = os.path.basename(path.rstrip('/')) - return '${name} = {val!r}'.format(name=name, val=value) + name = os.path.basename(path.rstrip("/")) + return "${name} = {val!r}".format(name=name, val=value) def test_tuple_store_and_write(): # setup sv = StateVisitor() - sv.store('/env/XONSH_HISTORY_SIZE', (1073741824, 'b')) - dump_rules = {'/': None, '/env/': None, - '/env/*': dump_xonfig_env_mock, - '/env/*/[0-9]*': None} - fi = FileInserter(prefix='# XONSH WIZARD START', suffix='# XONSH WIZARD END', - dump_rules=dump_rules, default_file=None, - check=False, ask_filename=False) + sv.store("/env/XONSH_HISTORY_SIZE", (1073741824, "b")) + dump_rules = { + "/": None, + "/env/": None, + "/env/*": dump_xonfig_env_mock, + "/env/*/[0-9]*": None, + } + fi = FileInserter( + prefix="# XONSH WIZARD START", + suffix="# XONSH WIZARD END", + dump_rules=dump_rules, + default_file=None, + check=False, + ask_filename=False, + ) # run test - exp = ("# XONSH WIZARD START\n" - "$XONSH_HISTORY_SIZE = (1073741824, 'b')\n" - "# XONSH WIZARD END\n") + exp = ( + "# XONSH WIZARD START\n" + "$XONSH_HISTORY_SIZE = (1073741824, 'b')\n" + "# XONSH WIZARD END\n" + ) obs = fi.dumps(sv.flatten()) assert exp == obs diff --git a/tests/test_xontribs.py b/tests/test_xontribs.py index 6d20952e6..cd45bcfa0 100644 --- a/tests/test_xontribs.py +++ b/tests/test_xontribs.py @@ -3,10 +3,12 @@ import sys import pytest from xonsh.xontribs import xontrib_metadata, xontrib_context + def test_load_xontrib_metadata(): # Simply tests that the xontribs JSON files isn't malformed. xontrib_metadata() + @pytest.yield_fixture def tmpmod(tmpdir): """ @@ -24,45 +26,54 @@ def tmpmod(tmpdir): for m in newmods: del sys.modules[m] + def test_noall(tmpmod): """ Tests what get's exported from a module without __all__ """ - with tmpmod.mkdir("xontrib").join("spameggs.py").open('w') as x: - x.write(""" + with tmpmod.mkdir("xontrib").join("spameggs.py").open("w") as x: + x.write( + """ spam = 1 eggs = 2 _foobar = 3 -""") +""" + ) + + ctx = xontrib_context("spameggs") + assert ctx == {"spam": 1, "eggs": 2} - ctx = xontrib_context('spameggs') - assert ctx == {'spam': 1, 'eggs': 2} def test_withall(tmpmod): """ Tests what get's exported from a module with __all__ """ - with tmpmod.mkdir("xontrib").join("spameggs.py").open('w') as x: - x.write(""" + with tmpmod.mkdir("xontrib").join("spameggs.py").open("w") as x: + x.write( + """ __all__ = 'spam', '_foobar' spam = 1 eggs = 2 _foobar = 3 -""") +""" + ) + + ctx = xontrib_context("spameggs") + assert ctx == {"spam": 1, "_foobar": 3} - ctx = xontrib_context('spameggs') - assert ctx == {'spam': 1, '_foobar': 3} def test_xshxontrib(tmpmod): """ Test that .xsh xontribs are loadable """ - with tmpmod.mkdir("xontrib").join("script.xsh").open('w') as x: - x.write(""" + with tmpmod.mkdir("xontrib").join("script.xsh").open("w") as x: + x.write( + """ hello = 'world' -""") +""" + ) - ctx = xontrib_context('script') - assert ctx == {'hello': 'world'} + ctx = xontrib_context("script") + assert ctx == {"hello": "world"} diff --git a/tests/test_xoreutils.py b/tests/test_xoreutils.py index bebf74650..e7c8d986c 100644 --- a/tests/test_xoreutils.py +++ b/tests/test_xoreutils.py @@ -11,19 +11,17 @@ class TestWhich: # use from the _which.py module. def setup(self): # Setup two folders with some test files. - self.testdirs = [tempfile.TemporaryDirectory(), - tempfile.TemporaryDirectory()] + self.testdirs = [tempfile.TemporaryDirectory(), tempfile.TemporaryDirectory()] if ON_WINDOWS: - self.testapps = ['whichtestapp1.exe', - 'whichtestapp2.wta'] - self.exts = ['.EXE'] + self.testapps = ["whichtestapp1.exe", "whichtestapp2.wta"] + self.exts = [".EXE"] else: - self.testapps = ['whichtestapp1'] + self.testapps = ["whichtestapp1"] self.exts = None for app in self.testapps: for d in self.testdirs: path = os.path.join(d.name, app) - open(path, 'wb').write(b'') + open(path, "wb").write(b"") os.chmod(path, 0o755) def teardown_module(self): @@ -32,48 +30,49 @@ class TestWhich: def test_whichgen(self): testdir = self.testdirs[0].name - arg = 'whichtestapp1' + arg = "whichtestapp1" matches = list(_which.whichgen(arg, path=[testdir], exts=self.exts)) assert len(matches) == 1 assert self._file_match(matches[0][0], os.path.join(testdir, arg)) def test_whichgen_failure(self): testdir = self.testdirs[0].name - arg = 'not_a_file' + arg = "not_a_file" matches = list(_which.whichgen(arg, path=[testdir], exts=self.exts)) assert len(matches) == 0 def test_whichgen_verbose(self): testdir = self.testdirs[0].name - arg = 'whichtestapp1' - matches = list(_which.whichgen(arg, path=[testdir], exts=self.exts, - verbose=True)) + arg = "whichtestapp1" + matches = list( + _which.whichgen(arg, path=[testdir], exts=self.exts, verbose=True) + ) assert len(matches) == 1 match, from_where = matches[0] assert self._file_match(match, os.path.join(testdir, arg)) - assert from_where == 'from given path element 0' + assert from_where == "from given path element 0" def test_whichgen_multiple(self): testdir0 = self.testdirs[0].name testdir1 = self.testdirs[1].name - arg = 'whichtestapp1' - matches = list(_which.whichgen(arg, path=[testdir0, testdir1], - exts=self.exts)) + arg = "whichtestapp1" + matches = list(_which.whichgen(arg, path=[testdir0, testdir1], exts=self.exts)) assert len(matches) == 2 assert self._file_match(matches[0][0], os.path.join(testdir0, arg)) assert self._file_match(matches[1][0], os.path.join(testdir1, arg)) if ON_WINDOWS: + def test_whichgen_ext_failure(self): testdir = self.testdirs[0].name - arg = 'whichtestapp2' + arg = "whichtestapp2" matches = list(_which.whichgen(arg, path=[testdir], exts=self.exts)) assert len(matches) == 0 def test_whichgen_ext_success(self): testdir = self.testdirs[0].name - arg = 'whichtestapp2' - matches = list(_which.whichgen(arg, path=[testdir], exts=['.wta'])) + arg = "whichtestapp2" + matches = list(_which.whichgen(arg, path=[testdir], exts=[".wta"])) assert len(matches) == 1 assert self._file_match(matches[0][0], os.path.join(testdir, arg))