response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Build the lexer/parser modules. | def build_tables():
"""Build the lexer/parser modules."""
print("Building lexer and parser tables.", file=sys.stderr)
root_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, root_dir)
from xonsh.parser import Parser
from xonsh.parsers.completion_context import CompletionContextP... |
If install/sdist is run from a git directory (not a conda install), add
a devN suffix to reported version number and write a gitignored file
that holds the git hash of the current state of the repo to be queried
by ``xonfig`` | def dirty_version():
"""
If install/sdist is run from a git directory (not a conda install), add
a devN suffix to reported version number and write a gitignored file
that holds the git hash of the current state of the repo to be queried
by ``xonfig``
"""
try:
_version = subprocess.ch... |
Replace version in `__init__.py` with devN suffix | def replace_version(N):
"""Replace version in `__init__.py` with devN suffix"""
global ORIGINAL_VERSION_LINE
with open("xonsh/__init__.py") as f:
raw = f.read()
lines = raw.splitlines()
msg_assert = "__version__ must be the first line of the __init__.py"
assert "__version__" in lines[0],... |
If we touch the version in __init__.py discard changes after install. | def restore_version():
"""If we touch the version in __init__.py discard changes after install."""
if ORIGINAL_VERSION_LINE is None:
return
with open("xonsh/__init__.py") as f:
raw = f.read()
lines = raw.splitlines()
lines[0] = ORIGINAL_VERSION_LINE
upd = "\n".join(lines) + "\n"
... |
The main entry point. | def main():
"""The main entry point."""
try:
if "--name" not in sys.argv:
logo_fname = os.path.join(os.path.dirname(__file__), "logo.txt")
with open(logo_fname, "rb") as f:
logo = f.read().decode("utf-8")
print(logo)
except UnicodeEncodeError:
... |
Render our pages as a jinja template for fancy templating goodness. | def rstjinja(app, docname, source):
"""
Render our pages as a jinja template for fancy templating goodness.
"""
# Make sure we're outputting HTML
if app.builder.format != "html":
return
print(docname)
page_ctx = app.config.jinja_contexts.get(docname)
if page_ctx is not None:
... |
Test that running an empty line or a comment does not append to history | def test_default_append_history(cmd, exp_append_history, xonsh_session, monkeypatch):
"""Test that running an empty line or a comment does not append to history"""
append_history_calls = []
def mock_append_history(**info):
append_history_calls.append(info)
monkeypatch.setattr(
xonsh_se... |
Set `__xonsh__.env ` to a new Env instance on `xonsh_builtins` | def home_env(xession):
"""Set `__xonsh__.env ` to a new Env instance on `xonsh_builtins`"""
xession.env["HOME"] = HOME_PATH
return xession |
func doc
multi-line
Parameters
----------
param
param doc
multi
param doc
multi line
optional : -o, --opt
an optional parameter with flags defined in description
Returns
-------
str
return doc | def func_with_doc(param: str, multi: str, optional=False):
"""func doc
multi-line
Parameters
----------
param
param doc
multi
param doc
multi line
optional : -o, --opt
an optional parameter with flags defined in description
Returns
-------
str
... |
See ``Completer.complete`` in ``xonsh/completer.py`` | def test_cursor_after_closing_quote(completer, completers_mock):
"""See ``Completer.complete`` in ``xonsh/completer.py``"""
@contextual_command_completer
def comp(context: CommandContext):
return {context.prefix + "1", context.prefix + "2"}
completers_mock["a"] = comp
assert completer.com... |
Test overriding the default values | def test_cursor_after_closing_quote_override(completer, completers_mock):
"""Test overriding the default values"""
@contextual_command_completer
def comp(context: CommandContext):
return {
# replace the closing quote with "a"
RichCompletion(
"a", prefix_len=l... |
create some shares to play with on current machine.
Yield (to test case) array of structs: [uncPath, driveLetter, equivLocalPath]
Side effect: `os.chdir(TEST_WORK_DIR)` | def shares_setup(tmpdir_factory):
"""create some shares to play with on current machine.
Yield (to test case) array of structs: [uncPath, driveLetter, equivLocalPath]
Side effect: `os.chdir(TEST_WORK_DIR)`
"""
if not ON_WINDOWS:
return []
shares = [
[r"uncpushd_test_HERE", TE... |
Simple non-UNC push/pop to verify we didn't break nonUNC case. | def test_pushdpopd(xession):
"""Simple non-UNC push/pop to verify we didn't break nonUNC case."""
xession.env.update(dict(CDPATH=PARENT, PWD=HERE))
dirstack.cd([PARENT])
owd = os.getcwd()
assert owd.casefold() == xession.env["PWD"].casefold()
dirstack.pushd([HERE])
wd = os.getcwd()
asse... |
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) | def test_uncpushd_push_other_push_same(xession, 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)
"""
if shares_setup is None:
return
... |
push to subdir under share, verify mapped path includes subdir | def test_uncpushd_push_base_push_rempath(xession):
"""push to subdir under share, verify mapped path includes subdir"""
pass |
Test that a registered envvar without any type is treated
permissively. | def test_register_custom_var_generic():
"""Test that a registered envvar without any type is treated
permissively.
"""
env = Env()
assert "MY_SPECIAL_VAR" not in env
env.register("MY_SPECIAL_VAR")
assert "MY_SPECIAL_VAR" in env
env["MY_SPECIAL_VAR"] = 32
assert env["MY_SPECIAL_VAR... |
Verify the rather complex rules for env.get("<envvar>",default) value when envvar is not defined. | def test_env_get_defaults():
"""Verify the rather complex rules for env.get("<envvar>",default) value when envvar is not defined."""
env = Env(TEST1=0)
env.register("TEST_REG", default="abc")
env.register("TEST_REG_DNG", default=DefaultNotGiven)
# var is defined, registered is don't-care => value ... |
Test initialization of the shell history. | def test_hist_init(hist, xession):
"""Test initialization of the shell history."""
with LazyJSON(hist.filename) as lj:
obs = lj["here"]
assert "yup" == obs |
Verify appending to the history works. | def test_hist_append(hist, xession):
"""Verify appending to the history works."""
xession.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 0 == hist.rtns[-1]
... |
Verify explicit flushing of the history works. | def test_hist_flush(hist, xession):
"""Verify explicit flushing of the history works."""
hf = hist.flush()
assert hf is None
xession.env["HISTCONTROL"] = set()
hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"})
hf = hist.flush()
assert hf is not None
while hf.is_alive():
... |
Verify explicit flushing of the history works. | def test_hist_flush_with_store_stdout(hist, xession):
"""Verify explicit flushing of the history works."""
hf = hist.flush()
assert hf is None
xession.env["HISTCONTROL"] = set()
xession.env["XONSH_STORE_STDOUT"] = True
hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"})
hf = hist.fl... |
Verify explicit flushing of the history works. | def test_hist_flush_with_hist_control(hist, xession):
"""Verify explicit flushing of the history works."""
hf = hist.flush()
assert hf is None
xession.env["HISTCONTROL"] = IGNORE_OPTS
hist.append({"inp": "ls foo1", "rtn": 0})
hist.append({"inp": "ls foo1", "rtn": 1})
hist.append({"inp": "ls ... |
Verify that CLI history commands work. | def test_show_cmd_numerate(inp, commands, offset, hist, xession, capsys):
"""Verify that CLI history commands work."""
base_idx, step = offset
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1... |
Test HISTCONTROL=ignoredups,ignoreerr,ignorespacee | def test_histcontrol(hist, xession):
"""Test HISTCONTROL=ignoredups,ignoreerr,ignorespacee"""
xession.env["HISTCONTROL"] = IGNORE_OPTS
assert len(hist.buffer) == 0
# An error, buffer remains empty
hist.append({"inp": "ls foo", "rtn": 2})
assert len(hist.buffer) == 1
assert hist.rtns[-1] ==... |
Generate a list of history file tuples | def history_files_list(gen_count) -> (float, int, str, int):
"""Generate a list of history file tuples"""
# generate test list:
# 2 files every day in range
# morning file has 100 commands, evening 50
# first file size 10000, 2nd 2500
# first file time 0900, 2nd 2300
# for sanity in reproduc... |
Verify that the CLI history clear command works. | def test_hist_clear_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history clear command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"inp": cmd, "rtn": 0, ... |
Verify that the CLI history off command works. | def test_hist_off_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history off command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"inp": cmd, "rtn": 0, "ts"... |
Verify that the CLI history on command works. | def test_hist_on_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history on command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"inp": cmd, "rtn": 0, "ts": ... |
Verify appending to the history works. | def test_hist_append(hist, xession):
"""Verify appending to the history works."""
xession.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 == ... |
Verify that CLI history commands work. | def test_show_cmd_numerate(inp, commands, offset, hist, xession, capsys):
"""Verify that CLI history commands work."""
base_idx, step = offset
xession.history = hist
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"inp": cmd, "rtn... |
Test HISTCONTROL=ignoredups,ignoreerr | def test_histcontrol(hist, xession):
"""Test HISTCONTROL=ignoredups,ignoreerr"""
ignore_opts = ",".join(["ignoredups", "ignoreerr", "ignorespace"])
xession.env["HISTCONTROL"] = ignore_opts
assert len(hist) == 0
# An error, items() remains empty
hist.append({"inp": "ls foo", "rtn": 2})
asse... |
Test HISTCONTROL=erasedups | def test_histcontrol_erase_dup(hist, xession):
"""Test HISTCONTROL=erasedups"""
xession.env["HISTCONTROL"] = "erasedups"
assert len(hist) == 0
hist.append({"inp": "ls foo", "rtn": 2})
hist.append({"inp": "ls foobazz", "rtn": 0})
hist.append({"inp": "ls foo", "rtn": 0})
hist.append({"inp": ... |
Verify that the CLI history clear command works. | def test_hist_clear_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history clear command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.history = hist
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.app... |
Verify that the CLI history off command works. | def test_hist_off_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history off command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.history = hist
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append(... |
Verify that the CLI history on command works. | def test_hist_on_cmd(hist, xession, capsys, tmpdir):
"""Verify that the CLI history on command works."""
xession.env.update({"XONSH_DATA_DIR": str(tmpdir)})
xession.history = hist
xession.env["HISTCONTROL"] = set()
for ts, cmd in enumerate(CMDS): # populate the shell history
hist.append({"... |
The ``fmt`` parameter is a function
that formats the output of cmd, can be None. | def check_run_xonsh(cmd, fmt, exp, exp_rtn=0):
"""The ``fmt`` parameter is a function
that formats the output of cmd, can be None.
"""
out, err, rtn = run_xonsh(cmd, stderr=sp.PIPE)
if callable(fmt):
out = fmt(out)
if callable(exp):
exp = exp()
assert out == exp, err
ass... |
Ensures syntax errors for EOF appear on last line. | def test_eof_syntax_error():
"""Ensures syntax errors for EOF appear on last line."""
script = "x = 1\na = (1, 0\n"
out, err, rtn = run_xonsh(script, stderr=sp.PIPE)
assert "line 0" not in err
assert "EOF in multi-line statement" in err and "line 2" in err |
verify pipe between subprocesses doesn't throw an exception | def test_pipe_between_subprocs(cmd, fmt, exp):
"""verify pipe between subprocesses doesn't throw an exception"""
check_run_xonsh(cmd, fmt, exp) |
Ensure we can run an executable in the current folder
when file is not on path | def test_run_currentfolder(monkeypatch):
"""Ensure we can run an executable in the current folder
when file is not on path
"""
batfile = Path(__file__).parent / "bin" / "hello_world.bat"
monkeypatch.chdir(batfile.parent)
cmd = batfile.name
out, _, _ = run_xonsh(cmd, stdout=sp.PIPE, stderr=sp... |
Ensure we can run an executable which is added to the path
after xonsh is loaded | def test_run_dynamic_on_path():
"""Ensure we can run an executable which is added to the path
after xonsh is loaded
"""
batfile = Path(__file__).parent / "bin" / "hello_world.bat"
cmd = f"$PATH.add(r'{batfile.parent}');![hello_world.bat]"
out, _, _ = run_xonsh(cmd, path=os.environ["PATH"])
a... |
Test that xonsh fails to run an executable when not on path
or in current folder | def test_run_fail_not_on_path():
"""Test that xonsh fails to run an executable when not on path
or in current folder
"""
cmd = "hello_world.bat"
out, _, _ = run_xonsh(cmd, stdout=sp.PIPE, stderr=sp.PIPE, path=os.environ["PATH"])
assert out != "Hello world" |
Tests whether two token are equal. | def tokens_equal(x, y):
"""Tests whether two token are equal."""
xtup = ensure_tuple(x)
ytup = ensure_tuple(y)
return xtup == ytup |
Asserts that two tokens are equal. | def assert_token_equal(x, y):
"""Asserts that two tokens are equal."""
if not tokens_equal(x, y):
msg = f"The tokens differ: {x!r} != {y!r}"
pytest.fail(msg)
return True |
Asserts that two token sequences are equal. | 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}"
pytest.fail(msg.format(len(x), len(y), pformat(x), pformat(y)))
diffs = [(a, b) fo... |
Xonsh Shell Mock | def shell(xession, monkeypatch):
"""Xonsh Shell Mock"""
gc.collect()
Shell.shell_type_aliases = {"rl": "readline"}
monkeypatch.setattr(xonsh.main, "Shell", Shell) |
Test that an RC file can load modules inside the same folder it is located in. | def test_rc_with_modules(shell, tmpdir, monkeypatch, capsys, xession):
"""Test that an RC file can load modules inside the same folder it is located in."""
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False")
tmpdir.join("my_python_modu... |
Test that python based control files are executed using Python's parser | def test_python_rc(shell, tmpdir, monkeypatch, capsys, xession, mocker):
"""Test that python based control files are executed using Python's parser"""
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False")
# spy on xonsh's compile method
... |
Test that files are loaded from an rcdir, after a normal rc file,
and in lexographic order. | def test_rcdir(shell, tmpdir, monkeypatch, capsys):
"""
Test that files are loaded from an rcdir, after a normal rc file,
and in lexographic order.
"""
rcdir = tmpdir.join("rc.d")
rcdir.mkdir()
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSH... |
Test that --rc DIR works | def test_rcdir_cli(shell, tmpdir, xession, monkeypatch):
"""Test that --rc DIR works"""
rcdir = tmpdir.join("rcdir")
rcdir.mkdir()
rc = rcdir.join("test.xsh")
rc.write("print('test.xsh')")
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
xargs = xonsh.main.premain(["--rc", rcdir.strpa... |
Test that an empty XONSHRC_DIR is not an error | def test_rcdir_empty(shell, tmpdir, monkeypatch, capsys):
"""Test that an empty XONSHRC_DIR is not an error"""
rcdir = tmpdir.join("rc.d")
rcdir.mkdir()
rc = tmpdir.join("rc.xsh")
rc.write_binary(b"")
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XO... |
Test the correct scripts are loaded, in the correct order, for
different combinations of CLI arguments. See
https://github.com/xonsh/xonsh/issues/4096
This sets up a standard set of RC files which will be loaded,
and tests whether they print their payloads at all, or in the right
order, depending on the CLI arguments ... | def test_script_startup(shell, tmpdir, monkeypatch, capsys, args, expected):
"""
Test the correct scripts are loaded, in the correct order, for
different combinations of CLI arguments. See
https://github.com/xonsh/xonsh/issues/4096
This sets up a standard set of RC files which will be loaded,
a... |
Test that --rc suppresses loading XONSHRC_DIRs | def test_rcdir_ignored_with_rc(shell, tmpdir, monkeypatch, capsys, xession):
"""Test that --rc suppresses loading XONSHRC_DIRs"""
rcdir = tmpdir.join("rc.d")
rcdir.mkdir()
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSHRC_DIR", str(rcdir))
rcdir.joi... |
Test that an RC file can edit the sys.path variable without losing those values. | def test_rc_with_modified_path(shell, tmpdir, monkeypatch, capsys, xession):
"""Test that an RC file can edit the sys.path variable without losing those values."""
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False")
rc = tmpdir.join("r... |
Test that an RC file which imports a module that throws an exception . | def test_rc_with_failing_module(shell, tmpdir, monkeypatch, capsys, xession):
"""Test that an RC file which imports a module that throws an exception ."""
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False")
tmpdir.join("my_failing_modu... |
Calling a custom RC file on a script-call with the interactive flag
should run interactively | def test_force_interactive_custom_rc_with_script(shell, tmpdir, monkeypatch, xession):
"""Calling a custom RC file on a script-call with the interactive flag
should run interactively
"""
monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False")
f = tmpdir.join("wakkawakka")
f.write("print(... |
Calling a custom RC file on a script-call without the interactive flag
should not run interactively | def test_custom_rc_with_script(shell, tmpdir, xession):
"""Calling a custom RC file on a script-call without the interactive flag
should not run interactively
"""
f = tmpdir.join("wakkawakka")
f.write("print('hi')")
args = xonsh.main.premain(["--rc", f.strpath, "tests/sample.xsh"])
assert no... |
Calling a custom RC file on a script-call without the interactive flag and no-rc
should not run interactively and should not have any rc_files | def test_custom_rc_with_script_and_no_rc(shell, tmpdir, xession):
"""Calling a custom RC file on a script-call without the interactive flag and no-rc
should not run interactively and should not have any rc_files
"""
f = tmpdir.join("wakkawakka")
f.write("print('hi')")
args = xonsh.main.premain([... |
Verify colorizer returns Token.Text if file type not defined in LS_COLORS | def test_color_on_lscolors_change(tmpdir, xonsh_builtins_ls_colors, check_token):
"""Verify colorizer returns Token.Text if file type not defined in LS_COLORS"""
lsc = xonsh_builtins_ls_colors.env["LS_COLORS"]
test_dir = str(tmpdir.mkdir("xonsh-test-highlight-path"))
lsc["di"] = ("GREEN",)
check_... |
Instantiate `PromptToolkitHistory` and append a line string | def history_obj():
"""Instantiate `PromptToolkitHistory` and append a line string"""
from xonsh.ptk_shell.history import PromptToolkitHistory
hist = PromptToolkitHistory(load_prev=False)
hist.append_string("line10")
return hist |
Context in which the ptk multiline functionality will be tested. | def ctx(xession):
"""Context in which the ptk multiline functionality will be tested."""
xession.env["INDENT"] = " "
from xonsh.ptk_shell.key_bindings import carriage_return
ptk_buffer = Buffer()
ptk_buffer.accept_action = MagicMock(name="accept")
cli = MagicMock(name="cli", spec=Application... |
don't dedent if first line of ctx.buffer | def test_nodedent(ctx):
"""don't dedent if first line of ctx.buffer"""
mock = MagicMock(return_value=True)
with patch("xonsh.ptk_shell.key_bindings.can_compile", mock):
document = Document("pass")
ctx.buffer.set_document(document)
ctx.cr(ctx.buffer, ctx.cli)
assert ctx.accept... |
Test that running an empty line or a comment does not append to history.
This test is necessary because the prompt-toolkit shell uses a custom _push() method that is different from the base shell's push() method. | def test_ptk_default_append_history(cmd, exp_append_history, ptk_shell, monkeypatch):
"""Test that running an empty line or a comment does not append to history.
This test is necessary because the prompt-toolkit shell uses a custom _push() method that is different from the base shell's push() method.
"""
... |
Xonsh environment including LS_COLORS | def xs_LS_COLORS(xession, os_env, monkeypatch):
"""Xonsh environment including LS_COLORS"""
# original env is needed on windows. since it will skip enhanced coloring
# for some emulators
monkeypatch.setattr(xession, "env", os_env)
lsc = LsColors(LsColors.default_settings)
xession.env["LS_COLOR... |
populate temp dir with sample files.
(too hard to emit indivual test cases when fixture invoked in mark.parametrize) | def colorizable_files():
"""populate temp dir with sample files.
(too hard to emit indivual test cases when fixture invoked in mark.parametrize)"""
with TemporaryDirectory() as tempdir:
for k, v in _cf.items():
if v is None:
continue
if v.startswith("/"):
... |
test proper file codes with symlinks colored normally | def test_colorize_file(key, file_path, colorizable_files, xs_LS_COLORS):
"""test proper file codes with symlinks colored normally"""
ffp = colorizable_files + "/" + file_path
stat_result = os.lstat(ffp)
color_token, color_key = color_file(ffp, stat_result)
assert color_key == key, "File classified a... |
test proper file codes with symlinks colored target. | def test_colorize_file_symlink(key, file_path, colorizable_files, xs_LS_COLORS):
"""test proper file codes with symlinks colored target."""
xs_LS_COLORS.env["LS_COLORS"]["ln"] = "target"
ffp = colorizable_files + "/" + file_path + "_symlink"
stat_result = os.lstat(ffp)
assert stat.S_ISLNK(stat_resul... |
Check that shell successfully load JSON history from file. | def test_shell_with_json_history(xession, xonsh_execer, tmpdir_factory):
"""
Check that shell successfully load JSON history from file.
"""
tempdir = str(tmpdir_factory.mktemp("history"))
history_file = os.path.join(tempdir, "history.json")
h = JsonHistory(filename=history_file)
h.append(
... |
Check that shell successfully load SQLite history from file. | def test_shell_with_sqlite_history(xession, xonsh_execer, tmpdir_factory):
"""
Check that shell successfully load SQLite history from file.
"""
tempdir = str(tmpdir_factory.mktemp("history"))
history_file = os.path.join(tempdir, "history.db")
h = SqliteHistory(filename=history_file)
h.appen... |
Check that shell use Dummy history in not interactive mode. | def test_shell_with_dummy_history_in_not_interactive(xession, xonsh_execer):
"""
Check that shell use Dummy history in not interactive mode.
"""
xession.env["XONSH_INTERACTIVE"] = False
xession.history = None
Shell(xonsh_execer, shell_type="none")
assert isinstance(xession.history, DummyHist... |
Build os-dependent paths properly. | def mkpath(*paths):
"""Build os-dependent paths properly."""
return os.sep + os.sep.join(paths) |
Tweaked for xonsh cases from CPython `test_genericpath.py` | def test_expandvars(inp, exp, xession):
"""Tweaked for xonsh cases from CPython `test_genericpath.py`"""
xession.env.update(
dict({"foo": "bar", "spam": "eggs", "a_bool": True, "an_int": 42, "none": None})
)
assert expandvars(inp) == exp |
verify can invoke it, and usage knows about all the options | def test_tracer_help(capsys, xsh_with_aliases):
"""verify can invoke it, and usage knows about all the options"""
spec = cmds_to_specs([("trace", "-h")], captured="stdout")[0]
with pytest.raises(SystemExit):
tracermain(["-h"], spec=spec)
capout = capsys.readouterr().out
pat = re.compile(r"^u... |
verify can invoke it, and usage knows about all the options | def test_xonfig_help(capsys, xession):
"""verify can invoke it, and usage knows about all the options"""
with pytest.raises(SystemExit):
xonfig_main(["-h"])
capout = capsys.readouterr().out
pat = re.compile(r"^usage:\s*xonfig[^\n]*{([\w,-]+)}", re.MULTILINE)
m = pat.match(capout)
assert ... |
info works, and reports no jupyter if none in environment | def test_xonfig_info(args, xession):
"""info works, and reports no jupyter if none in environment"""
capout = xonfig_main(args)
assert capout.startswith("+---")
assert capout.endswith("---+\n")
pat = re.compile(r".*history backend\s+\|\s+", re.MULTILINE | re.IGNORECASE)
m = pat.search(capout)
... |
Same as tmpdir but also adds/removes it to the front of sys.path.
Also cleans out any modules loaded as part of the test. | def tmpmod(tmpdir):
"""
Same as tmpdir but also adds/removes it to the front of sys.path.
Also cleans out any modules loaded as part of the test.
"""
sys.path.insert(0, str(tmpdir))
loadedmods = set(sys.modules.keys())
try:
yield tmpdir
finally:
del sys.path[0]
n... |
Tests what get's exported from a module without __all__ | 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(
"""
spam = 1
eggs = 2
_foobar = 3
"""
)
ctx = xontrib_context("spameggs")
assert ctx == {"spam": 1, "egg... |
Tests what get's exported from a module with __all__ | 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(
"""
__all__ = 'spam', '_foobar'
spam = 1
eggs = 2
_foobar = 3
"""
)
ctx = xontrib_context("spameggs")
ass... |
Test that .xsh xontribs are loadable | def test_xshxontrib(tmpmod):
"""
Test that .xsh xontribs are loadable
"""
with tmpmod.mkdir("xontrib").join("script.xsh").open("w") as x:
x.write(
"""
hello = 'world'
"""
)
ctx = xontrib_context("script")
assert ctx == {"hello": "world"} |
Test that .xsh xontribs are loadable | def test_xontrib_load(tmpmod):
"""
Test that .xsh xontribs are loadable
"""
with tmpmod.mkdir("xontrib").join("script.xsh").open("w") as x:
x.write(
"""
hello = 'world'
"""
)
xontribs_load(["script"])
assert "script" in xontribs_loaded() |
Test that .xsh xontribs are loadable | def test_xontrib_load_dashed(tmpmod):
"""
Test that .xsh xontribs are loadable
"""
with tmpmod.mkdir("xontrib").join("scri-pt.xsh").open("w") as x:
x.write(
"""
hello = 'world'
"""
)
xontribs_load(["scri-pt"])
assert "scri-pt" in xontribs_loaded() |
Return a dict with vc and a temporary dir
that is a repository for testing. | def repo(request, tmpdir_factory):
"""Return a dict with vc and a temporary dir
that is a repository for testing.
"""
vc = request.param
temp_dir = Path(tmpdir_factory.mktemp("dir"))
os.chdir(temp_dir)
try:
for init_command in VC_INIT[vc]:
sp.call([vc] + init_command)
... |
Completion for "cd", includes only valid directory names. | def xonsh_complete(command: CommandContext):
"""
Completion for "cd", includes only valid directory names.
"""
results, lprefix = complete_dir(command)
if len(results) == 0:
raise StopIteration
return results, lprefix |
Completes python's package manager pip. | def xonsh_complete(ctx: CommandContext):
"""Completes python's package manager pip."""
return comp_based_completer(ctx, PIP_AUTO_COMPLETE="1") |
Completion for "rmdir", includes only valid directory names. | def xonsh_complete(ctx: CommandContext):
"""
Completion for "rmdir", includes only valid directory names.
"""
# if starts with the given prefix then it will get completions from man page
if not ctx.prefix.startswith("-") and ctx.arg_index > 0:
comps, lprefix = complete_dir(ctx)
if n... |
Completer for ``xonsh`` command using its ``argparser`` | def xonsh_complete(command: CommandContext):
"""Completer for ``xonsh`` command using its ``argparser``"""
from xonsh.main import parser
completer = ArgparseCompleter(parser, command=command)
return completer.complete(), False |
Dispatches the appropriate eval alias based on the number of args to the original callable alias
and how many arguments to apply. | def partial_eval_alias(f, acc_args=()):
"""Dispatches the appropriate eval alias based on the number of args to the original callable alias
and how many arguments to apply.
"""
# no partial needed if no extra args
if not acc_args:
return f
# need to dispatch
numargs = 0
for name,... |
Sends signal to exit shell. | def xonsh_exit(args, stdin=None):
"""Sends signal to exit shell."""
if not clean_jobs():
# Do not exit if jobs not cleaned up
return None, None
XSH.exit = True
print() # gimme a newline
return None, None |
Clears __xonsh__.ctx | def xonsh_reset(args, stdin=None):
"""Clears __xonsh__.ctx"""
XSH.ctx.clear() |
Sources a file written in a foreign shell language.
Parameters
----------
shell
Name or path to the foreign shell
files_or_code
file paths to source or code in the target language.
interactive : -i, --interactive
whether the sourced shell should be interactive
login : -l, --login
whether the sourced sh... | def source_foreign_fn(
shell: str,
files_or_code: Annotated[list[str], Arg(nargs="+")],
interactive=False,
login=False,
envcmd=None,
aliascmd=None,
extra_args="",
safe=True,
prevcmd="",
postcmd="",
funcscmd="",
sourcer=None,
use_tmpfile=False,
seterrprevcmd=None,
... |
Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead. | def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = XSH.env
encoding = env.get("XONSH_ENCODING")
errors = env.get("XONSH_ENCODING_ERRORS")
f... |
Source cmd.exe files
Parameters
----------
files
paths to source files.
login : -l, --login
whether the sourced shell should be login
envcmd : --envcmd
command to print environment
aliascmd : --aliascmd
command to print aliases
extra_args : --extra-args
extra arguments needed to run the shell
s... | def source_cmd_fn(
files: Annotated[list[str], Arg(nargs="+")],
login=False,
aliascmd=None,
extra_args="",
safe=True,
postcmd="",
funcscmd="",
seterrprevcmd=None,
overwrite_aliases=False,
suppress_skip_message=False,
show=False,
dryrun=False,
_stderr=None,
):
"""
... |
exec (also aliased as xexec) uses the os.execvpe() function to
replace the xonsh process with the specified program.
This provides the functionality of the bash 'exec' builtin::
>>> exec bash -l -i
bash $
Parameters
----------
command
program to launch along its arguments
login : -l, --login
the shel... | def xexec_fn(
command: Annotated[list[str], Arg(nargs=argparse.REMAINDER)],
login=False,
clean=False,
name="",
_stdin=None,
):
"""exec (also aliased as xexec) uses the os.execvpe() function to
replace the xonsh process with the specified program.
This provides the functionality of the b... |
Runs the xonsh configuration utility. | def xonfig():
"""Runs the xonsh configuration utility."""
from xonsh.xonfig import xonfig_main # lazy import
return xonfig_main |
Runs the xonsh tracer utility. | def trace(args, stdin=None, stdout=None, stderr=None, spec=None):
"""Runs the xonsh tracer utility."""
from xonsh.tracer import tracermain # lazy import
try:
return tracermain(args, stdin=stdin, stdout=stdout, stderr=stderr, spec=spec)
except SystemExit:
pass |
usage: showcmd [-h|--help|cmd args]
Displays the command and arguments as a list of strings that xonsh would
run in subprocess mode. This is useful for determining how xonsh evaluates
your commands and arguments prior to running these commands.
optional arguments:
-h, --help show this help message and ex... | def showcmd(args, stdin=None):
"""usage: showcmd [-h|--help|cmd args]
Displays the command and arguments as a list of strings that xonsh would
run in subprocess mode. This is useful for determining how xonsh evaluates
your commands and arguments prior to running these commands.
optional arguments:... |
Determines the correct invocation to get xonsh's pip | def detect_xpip_alias():
"""
Determines the correct invocation to get xonsh's pip
"""
if not getattr(sys, "executable", None):
return lambda args, stdin=None: (
"",
"Sorry, unable to run pip on your system (missing sys.executable)",
1,
)
basecmd =... |
Creates a new default aliases dictionary. | def make_default_aliases():
"""Creates a new default aliases dictionary."""
default_aliases = {
"cd": cd,
"pushd": pushd,
"popd": popd,
"dirs": dirs,
"jobs": jobs,
"fg": fg,
"bg": bg,
"disown": disown,
"EOF": xonsh_exit,
"exit": xon... |
Converts a color name to the inner part of an ANSI escape code | def ansi_color_name_to_escape_code(name, style="default", cmap=None):
"""Converts a color name to the inner part of an ANSI escape code"""
cmap = _ensure_color_map(style=style, cmap=cmap)
if name in cmap:
return cmap[name]
m = RE_XONSH_COLOR.match(name)
if m is None:
raise ValueError... |
Formats a template string but only with respect to the colors.
Another template string is returned, with the color values filled in.
Parameters
----------
template : str
The template string, potentially with color names.
style : str, optional
Style name to look up color map from.
cmap : dict, optional
A co... | def ansi_partial_color_format(template, style="default", cmap=None, hide=False):
"""Formats a template string but only with respect to the colors.
Another template string is returned, with the color values filled in.
Parameters
----------
template : str
The template string, potentially with... |
Returns an iterable of all ANSI color style names. | def ansi_color_style_names():
"""Returns an iterable of all ANSI color style names."""
return ANSI_STYLES.keys() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.