def test_env_path(): def expand(path): return os.path.expanduser(os.path.expandvars(path)) getitem_cases = [ ('xonsh_dir', 'xonsh_dir'), ('.', '.'), ('../', '../'), ('~/', '~/'), (b'~/../', '~/../'), ] with mock_xonsh_env(TOOLS_ENV): for inp, exp in getitem_cases: obs = EnvPath(inp)[0] # call to __getitem__ assert expand(exp) == obs with mock_xonsh_env(ENCODE_ENV_ONLY): for inp, exp in getitem_cases: obs = EnvPath(inp)[0] # call to __getitem__ assert exp == obs # cases that involve path-separated strings multipath_cases = [ (os.pathsep.join(['xonsh_dir', '../', '.', '~/']), ['xonsh_dir', '../', '.', '~/']), ('/home/wakka' + os.pathsep + '/home/jakka' + os.pathsep + '~/', ['/home/wakka', '/home/jakka', '~/']) ] with mock_xonsh_env(TOOLS_ENV): for inp, exp in multipath_cases: obs = [i for i in EnvPath(inp)] assert [expand(i) for i in exp] == obs with mock_xonsh_env(ENCODE_ENV_ONLY): for inp, exp in multipath_cases: obs = [i for i in EnvPath(inp)] assert [i for i in exp] == obs # cases that involve pathlib.Path objects pathlib_cases = [ (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', '~', '~/']), ] with mock_xonsh_env(TOOLS_ENV): for inp, exp in pathlib_cases: # iterate over EnvPath to acquire all expanded paths obs = [i for i in EnvPath(inp)] assert [expand(i) for i in exp] == obs
def test_login_shell(): def Shell(*args, **kwargs): pass with patch('xonsh.main.Shell', Shell), mock_xonsh_env({}): xonsh.main.premain([]) assert_false(builtins.__xonsh_env__.get('XONSH_LOGIN')) with patch('xonsh.main.Shell', Shell), mock_xonsh_env({}): xonsh.main.premain(['-l']) assert_true(builtins.__xonsh_env__.get('XONSH_LOGIN'))
def test_histcontrol(): """Test HISTCONTROL=ignoredups,ignoreerr""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.append' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) with mock_xonsh_env({'HISTCONTROL': 'ignoredups,ignoreerr'}): yield assert_equal, len(hist.buffer), 0 # An error, buffer remains empty hist.append({'inp': 'ls foo', 'rtn': 2}) yield assert_equal, len(hist.buffer), 0 # Success hist.append({'inp': 'ls foobazz', 'rtn': 0}) yield assert_equal, len(hist.buffer), 1 yield assert_equal, 'ls foobazz', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls foo', 'rtn': 2}) yield assert_equal, len(hist.buffer), 1 yield assert_equal, 'ls foobazz', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # File now exists, success hist.append({'inp': 'ls foo', 'rtn': 0}) yield assert_equal, len(hist.buffer), 2 yield assert_equal, 'ls foo', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # Success hist.append({'inp': 'ls', 'rtn': 0}) yield assert_equal, len(hist.buffer), 3 yield assert_equal, 'ls', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # Dup hist.append({'inp': 'ls', 'rtn': 0}) yield assert_equal, len(hist.buffer), 3 # Success hist.append({'inp': '/bin/ls', 'rtn': 0}) yield assert_equal, len(hist.buffer), 4 yield assert_equal, '/bin/ls', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls bazz', 'rtn': 1}) yield assert_equal, len(hist.buffer), 4 yield assert_equal, '/bin/ls', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls bazz', 'rtn': -1}) yield assert_equal, len(hist.buffer), 4 yield assert_equal, '/bin/ls', hist.buffer[-1]['inp'] yield assert_equal, 0, hist.buffer[-1]['rtn'] os.remove(FNAME)
def test_eval_recursive_callable_partial(): if ON_WINDOWS: raise SkipTest built_ins.ENV = Env(HOME=os.path.expanduser('~')) with mock_xonsh_env(built_ins.ENV): assert_equal(ALIASES.get('indirect_cd')(['arg2', 'arg3']), ['..', 'arg2', 'arg3'])
def test_histcontrol(): """Test HISTCONTROL=ignoredups,ignoreerr""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.append' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) with mock_xonsh_env({'HISTCONTROL': 'ignoredups,ignoreerr'}): assert len(hist.buffer) == 0 # An error, buffer remains empty hist.append({'inp': 'ls foo', 'rtn': 2}) assert len(hist.buffer) == 0 # Success hist.append({'inp': 'ls foobazz', 'rtn': 0}) assert len(hist.buffer) == 1 assert 'ls foobazz' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls foo', 'rtn': 2}) assert len(hist.buffer) == 1 assert 'ls foobazz' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # File now exists, success hist.append({'inp': 'ls foo', 'rtn': 0}) assert len(hist.buffer) == 2 assert 'ls foo' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # Success hist.append({'inp': 'ls', 'rtn': 0}) assert len(hist.buffer) == 3 assert 'ls' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # Dup hist.append({'inp': 'ls', 'rtn': 0}) assert len(hist.buffer) == 3 # Success hist.append({'inp': '/bin/ls', 'rtn': 0}) assert len(hist.buffer) == 4 assert '/bin/ls' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls bazz', 'rtn': 1}) assert len(hist.buffer) == 4 assert '/bin/ls' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] # Error hist.append({'inp': 'ls bazz', 'rtn': -1}) assert len(hist.buffer) == 4 assert '/bin/ls' == hist.buffer[-1]['inp'] assert 0 == hist.buffer[-1]['rtn'] os.remove(FNAME)
def test_repath_home_var_brace(): exp = os.path.expanduser('~') env = Env(HOME=exp) with mock_xonsh_env(env): obs = pathsearch(regexsearch, '${"HOME"}') assert 1 == len(obs) assert exp == obs[0]
def test_iglobpath(): with TemporaryDirectory() as test_dir: # Create files 00.test to 99.test in unsorted order num = 18 for _ in range(100): s = str(num).zfill(2) path = os.path.join(test_dir, s + '.test') with open(path, 'w') as file: file.write(s + '\n') num = (num + 37) % 100 # Create one file not matching the '*.test' with open(os.path.join(test_dir, '07'), 'w') as file: file.write('test\n') with mock_xonsh_env(Env(EXPAND_ENV_VARS=False)): builtins.__xonsh_expand_path__ = expand_path paths = list(iglobpath(os.path.join(test_dir, '*.test'), ignore_case=False, sort_result=False)) assert len(paths) == 100 paths = list(iglobpath(os.path.join(test_dir, '*'), ignore_case=True, sort_result=False)) assert len(paths) == 101 paths = list(iglobpath(os.path.join(test_dir, '*.test'), ignore_case=False, sort_result=True)) assert len(paths) == 100 assert paths == sorted(paths) paths = list(iglobpath(os.path.join(test_dir, '*'), ignore_case=True, sort_result=True)) assert len(paths) == 101 assert paths == sorted(paths)
def test_man_completion(): if ON_WINDOWS: raise SkipTest with tempfile.TemporaryDirectory() as tempdir: with mock_xonsh_env({'XONSH_DATA_DIR': tempdir}): completions = complete_from_man('--', 'yes --', 4, 6, __xonsh_env__) assert_true('--version' in completions) assert_true('--help' in completions)
def test_man_completion(): if ON_WINDOWS: raise SkipTest with mock_xonsh_env({}): man_completer = ManCompleter() completions = man_completer.option_complete('--', 'yes') assert_true('--version' in completions) assert_true('--help' in completions)
def test_eval_recursive_callable_partial(): if ON_WINDOWS: raise SkipTest built_ins.ENV = Env(HOME=os.path.expanduser('~')) with mock_xonsh_env(built_ins.ENV): assert_equal( ALIASES.get('indirect_cd')(['arg2', 'arg3']), ['..', 'arg2', 'arg3'])
def check_load_static_config(s, exp, loaded): env = {'XONSH_SHOW_TRACEBACK': False} with tempfile.NamedTemporaryFile() as f, mock_xonsh_env(env): f.write(s) f.flush() conf = load_static_config(env, f.name) assert_equal(exp, conf) assert_equal(env['LOADED_CONFIG'], loaded)
def check_xonsh_ast(xenv, inp, run=True, mode='eval'): with mock_xonsh_env(xenv): obs = PARSER.parse(inp, debug_level=DEBUG_LEVEL) if obs is None: return # comment only bytecode = compile(obs, '<test-xonsh-ast>', mode) if run: exec(bytecode)
def test_repath_home_contents(): home = os.path.expanduser('~') env = Env(HOME=home) with mock_xonsh_env(env): exp = os.listdir(home) exp = {os.path.join(home, p) for p in exp} obs = set(pathsearch(regexsearch, '~/.*')) assert exp == obs
def check_eval(input): with mock_xonsh_env({ 'AUTO_CD': False, 'XONSH_ENCODING': 'utf-8', 'XONSH_ENCODING_ERRORS': 'strict', 'PATH': [] }): EXECER.debug_level = DEBUG_LEVEL EXECER.eval(input)
def test_repath_home_var(): if ON_WINDOWS: raise SkipTest exp = os.path.expanduser('~') built_ins.ENV = Env(HOME=exp) with mock_xonsh_env(built_ins.ENV): obs = pathsearch(regexsearch, '$HOME') assert_equal(1, len(obs)) assert_equal(exp, obs[0])
def test_repath_home_var_brace(): if ON_WINDOWS: raise SkipTest exp = os.path.expanduser('~') built_ins.ENV = Env(HOME=exp) with mock_xonsh_env(built_ins.ENV): obs = regexpath('${"HOME"}') assert_equal(1, len(obs)) assert_equal(exp, obs[0])
def test_repath_backslash(): home = os.path.expanduser('~') env = Env(HOME=home) with mock_xonsh_env(env): exp = os.listdir(home) exp = {p for p in exp if re.match(r'\w\w.*', p)} exp = {os.path.join(home, p) for p in exp} obs = set(pathsearch(regexsearch, r'~/\w\w.*')) assert exp == obs
def test_repath_home_contents(): if ON_WINDOWS: raise SkipTest home = os.path.expanduser('~') built_ins.ENV = Env(HOME=home) with mock_xonsh_env(built_ins.ENV): exp = os.listdir(home) exp = {os.path.join(home, p) for p in exp} obs = set(regexpath('~/.*')) assert_equal(exp, obs)
def test_login_shell(): def Shell(*args, **kwargs): pass with patch("xonsh.main.Shell", Shell), mock_xonsh_env({}): xonsh.main.premain([]) assert_true(builtins.__xonsh_env__.get("XONSH_LOGIN")) with patch("xonsh.main.Shell", Shell), mock_xonsh_env({}): xonsh.main.premain(["-l", "-c", 'echo "hi"']) assert_true(builtins.__xonsh_env__.get("XONSH_LOGIN")) with patch("xonsh.main.Shell", Shell), mock_xonsh_env({}): xonsh.main.premain(["-c", 'echo "hi"']) assert_false(builtins.__xonsh_env__.get("XONSH_LOGIN")) with patch("xonsh.main.Shell", Shell), mock_xonsh_env({}): xonsh.main.premain(["-l"]) assert_true(builtins.__xonsh_env__.get("XONSH_LOGIN"))
def check_load_static_config(s, exp, loaded): env = Env({'XONSH_SHOW_TRACEBACK': False}) f = tempfile.NamedTemporaryFile(delete=False) with mock_xonsh_env(env): f.write(s) f.close() conf = load_static_config(env, f.name) os.unlink(f.name) assert_equal(exp, conf) assert_equal(env['LOADED_CONFIG'], loaded)
def test_hist_append(): """Verify appending to the history works.""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.append' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) with mock_xonsh_env({'HISTCONTROL': set()}): hf = hist.append({'joco': 'still alive'}) yield assert_is_none, hf yield assert_equal, 'still alive', hist.buffer[0]['joco'] os.remove(FNAME)
def test_repath_backslash(): if ON_WINDOWS: raise SkipTest home = os.path.expanduser('~') built_ins.ENV = Env(HOME=home) with mock_xonsh_env(built_ins.ENV): exp = os.listdir(home) exp = {p for p in exp if re.match(r'\w\w.*', p)} exp = {os.path.join(home, p) for p in exp} obs = set(regexpath(r'~/\w\w.*')) assert_equal(exp, obs)
def test_locate_binary_on_windows(): 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: f.write(fpath) env = Env({'PATH': [tmpdir], 'PATHEXT': ['.COM', '.EXE', '.BAT']}) with mock_xonsh_env(env): assert_equal( locate_binary('file1'), os.path.join(tmpdir,'file1.exe')) assert_equal( locate_binary('file1.exe'), os.path.join(tmpdir,'file1.exe')) assert_equal( locate_binary('file2'), os.path.join(tmpdir,'FILE2.BAT')) assert_equal( locate_binary('file2.bat'), os.path.join(tmpdir,'FILE2.BAT')) assert_equal( locate_binary('file3'), None)
def test_hist_flush(): """Verify explicit flushing of the history works.""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.flush' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) hf = hist.flush() yield assert_is_none, hf with mock_xonsh_env({'HISTCONTROL': set()}): hist.append({'joco': 'still alive'}) hf = hist.flush() yield assert_is_not_none, hf while hf.is_alive(): pass with LazyJSON(FNAME) as lj: obs = lj['cmds'][0]['joco'] yield assert_equal, 'still alive', obs os.remove(FNAME)
def test_cmd_field(): """Test basic history behavior.""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.cmdfield' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) # in-memory with mock_xonsh_env({'HISTCONTROL': set()}): hf = hist.append({'rtn': 1}) assert hf is None assert 1 == hist.rtns[0] assert 1 == hist.rtns[-1] assert None == hist.outs[-1] # slice assert [1] == hist.rtns[:] # on disk hf = hist.flush() assert hf is not None assert 1 == hist.rtns[0] assert 1 == hist.rtns[-1] assert None == hist.outs[-1] os.remove(FNAME)
def test_cmd_field(): """Test basic history behavior.""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.cmdfield' hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) # in-memory with mock_xonsh_env({'HISTCONTROL': set()}): hf = hist.append({'rtn': 1}) yield assert_is_none, hf yield assert_equal, 1, hist.rtns[0] yield assert_equal, 1, hist.rtns[-1] yield assert_equal, None, hist.outs[-1] # slice yield assert_equal, [1], hist.rtns[:] # on disk hf = hist.flush() yield assert_is_not_none, hf yield assert_equal, 1, hist.rtns[0] yield assert_equal, 1, hist.rtns[-1] yield assert_equal, None, hist.outs[-1] os.remove(FNAME)
def test_executables_in(): expected = set() types = ('file', 'directory', 'brokensymlink') if ON_WINDOWS: # Don't test symlinks on windows since it requires admin 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': continue if _type == 'file' and executable: ext = '.exe' if ON_WINDOWS else '' expected.add(fname + ext) else: ext = '' path = os.path.join(test_path, fname + ext) if _type == 'file': with open(path, 'w') as f: f.write(fname) 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') os.symlink(tmp_path, path) os.remove(tmp_path) if executable and not _type == 'brokensymlink': os.chmod(path, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR) if ON_WINDOWS: with mock_xonsh_env(PATHEXT_ENV): result = set(executables_in(test_path)) else: result = set(executables_in(test_path)) assert (expected == result)
def test_eval_self_reference(): with mock_xonsh_env({}): assert_equal(ALIASES.get('ls'), ['ls', '- -'])
def test_sub_import(): with mock_xonsh_env(IMP_ENV): from xpack.sub import sample assert ('hello mom jawaka\n' == sample.x)
def test_eval_normal(): with mock_xonsh_env({}): assert_equal(ALIASES.get('o'), ['omg', 'lala'])
def check_parse(input): with mock_xonsh_env(None): EXECER.debug_level = DEBUG_LEVEL EXECER.parse(input, ctx=None)
def test_relative_import(): with mock_xonsh_env(IMP_ENV): from xpack import relimp assert ('hello mom jawaka\n' == relimp.sample.x) assert ('hello mom jawaka\ndark chest of wonders' == relimp.y)
def test_eval_recursive(): with mock_xonsh_env({}): assert_equal(ALIASES.get('color_ls'), ['ls', '- -', '--color=true'])
def check_eval(input): with mock_xonsh_env(None): EXECER.debug_level = DEBUG_LEVEL EXECER.eval(input)
def test_relative_import(): with mock_xonsh_env({}): from xpack import relimp assert_equal('hello mom jawaka\n', relimp.sample.x) assert_equal('hello mom jawaka\ndark chest of wonders', relimp.y)
def test_sub_import(): with mock_xonsh_env({}): from xpack.sub import sample assert_equal('hello mom jawaka\n', sample.x)
def test_helper_helper(): with mock_xonsh_env({}): helper(helper, 'helper')
def test_show_cmd(): """Verify that CLI history commands work.""" FNAME = 'xonsh-SESSIONID.json' FNAME += '.show_cmd' cmds = ['ls', 'cat hello kitty', 'abc', 'def', 'touch me', 'grep from me'] def format_hist_line(idx, cmd): """Construct a history output line.""" return ' {:d}: {:s}\n'.format(idx, cmd) def run_show_cmd(hist_args, commands, base_idx=0, step=1): """Run and evaluate the output of the given show command.""" stdout.seek(0, io.SEEK_SET) stdout.truncate() history._hist_main(hist, hist_args) stdout.seek(0, io.SEEK_SET) hist_lines = stdout.readlines() yield assert_equal, len(commands), len(hist_lines) for idx, (cmd, actual) in enumerate(zip(commands, hist_lines)): expected = format_hist_line(base_idx + idx * step, cmd) yield assert_equal, expected, actual hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS) stdout = io.StringIO() saved_stdout = sys.stdout sys.stdout = stdout with mock_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)}) # Verify an implicit "show" emits show history for x in run_show_cmd([], cmds): yield x # Verify an explicit "show" with no qualifiers emits # show history. for x in run_show_cmd(['show'], cmds): yield x # Verify an explicit "show" with a reversed qualifier # emits show history in reverse order. for x in run_show_cmd(['show', '-r'], list(reversed(cmds)), len(cmds) - 1, -1): yield x # Verify that showing a specific history entry relative to # the start of the history works. for x in run_show_cmd(['show', '0'], [cmds[0]], 0): yield x for x in run_show_cmd(['show', '1'], [cmds[1]], 1): yield x # Verify that showing a specific history entry relative to # the end of the history works. for x in run_show_cmd(['show', '-2'], [cmds[-2]], len(cmds) - 2): yield x # Verify that showing a history range relative to the start of the # history works. for x in run_show_cmd(['show', '0:2'], cmds[0:2], 0): yield x for x in run_show_cmd(['show', '1::2'], cmds[1::2], 1, 2): yield x # Verify that showing a history range relative to the end of the # history works. for x in run_show_cmd(['show', '-2:'], cmds[-2:], len(cmds) - 2): yield x for x in run_show_cmd(['show', '-4:-2'], cmds[-4:-2], len(cmds) - 4): yield x sys.stdout = saved_stdout os.remove(FNAME)
def test_helper_env(): with mock_xonsh_env({}): helper(Env, 'Env')
def check_exec(input): with mock_xonsh_env(None): if not input.endswith('\n'): input += '\n' EXECER.debug_level = DEBUG_LEVEL EXECER.exec(input)
def test_superhelper_int(): with mock_xonsh_env({}): superhelper(int, 'int')
def test_superhelper_env(): with mock_xonsh_env({}): superhelper(Env, 'Env')