Ejemplo n.º 1
0
def test_swap():
    env = Env(VAR="wakka")
    assert env["VAR"] == "wakka"

    # positional arg
    with env.swap({"VAR": "foo"}):
        assert env["VAR"] == "foo"

    # make sure the environment goes back outside the context manager
    assert env["VAR"] == "wakka"

    # kwargs only
    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"

    # 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
Ejemplo n.º 2
0
def test_swap():
    env = Env(VAR='wakka')
    assert_equal(env['VAR'], 'wakka')

    # positional arg
    with env.swap({'VAR': 'foo'}):
        assert_equal(env['VAR'], 'foo')

    # make sure the environment goes back outside the context manager
    assert_equal(env['VAR'], 'wakka')

    # kwargs only
    with env.swap(VAR1='foo', VAR2='bar'):
        assert_equal(env['VAR1'], 'foo')
        assert_equal(env['VAR2'], 'bar')

    # positional and kwargs
    with env.swap({'VAR3': 'baz'}, VAR1='foo', VAR2='bar'):
        assert_equal(env['VAR1'], 'foo')
        assert_equal(env['VAR2'], 'bar')
        assert_equal(env['VAR3'], 'baz')

    # make sure the environment goes back outside the context manager
    assert_equal(env['VAR'], 'wakka')
    assert 'VAR1' not in env
    assert 'VAR2' not in env
    assert 'VAR3' not in env
Ejemplo n.º 3
0
def make_envvars():
    env = Env()
    vars = sorted(DEFAULT_DOCS.keys())
    s = ('.. list-table::\n'
         '    :header-rows: 0\n\n')
    table = []
    ncol = 3
    row = '    {0} - :ref:`${1} <{2}>`'
    for i, var in enumerate(vars):
        star = '*' if i%ncol == 0 else ' '
        table.append(row.format(star, var, var.lower()))
    table.extend(['      -']*((ncol - len(vars)%ncol)%ncol))
    s += '\n'.join(table) + '\n\n'
    s += ('Listing\n'
          '-------\n\n')
    sec = ('.. _{low}:\n\n'
           '{title}\n'
           '{under}\n'
           '{docstr}\n\n'
           '**configurable:** {configurable}\n\n'
           '**default:** {default}\n\n'
           '-------\n\n')
    for var in vars:
        title = '$' + var
        under = '.' * len(title)
        vd = env.get_docs(var)
        s += sec.format(low=var.lower(), title=title, under=under, 
                        docstr=vd.docstr, configurable=vd.configurable, 
                        default=vd.default)
    s = s[:-9]
    fname = os.path.join(os.path.dirname(__file__), 'envvarsbody')
    with open(fname, 'w') as f:
        f.write(s)
Ejemplo n.º 4
0
def test_swap_exception_replacement():
    env = Env(VAR="original value")
    try:
        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"
Ejemplo n.º 5
0
def test_format_prompt_with_no_env(formatter, xonsh_builtins, live_fields):
    xonsh_builtins.__xonsh__.shell.prompt_formatter = formatter

    env = Env()
    env.pop("VIRTUAL_ENV", None)  # For virtualenv
    env.pop("CONDA_DEFAULT_ENV", None)  # For conda/CircleCI
    xonsh_builtins.__xonsh__.env = env

    assert formatter("{env_name}", fields=live_fields) == ""
Ejemplo n.º 6
0
def test_env_detype_mutable_access_clear():
    env = Env(MYPATH=['/home/wakka', '/home/jawaka'])
    assert '/home/wakka' + os.pathsep + '/home/jawaka' == env.detype()['MYPATH']
    env['MYPATH'][0] = '/home/woah'
    assert env._detyped is None
    assert '/home/woah' + os.pathsep + '/home/jawaka' == env.detype()['MYPATH']
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert 'wakka' + os.pathsep + 'jawaka' == env.detype()['MYPATH']
    env['MYPATH'][0] = 'woah'
    assert env._detyped is None
    assert 'woah' + os.pathsep + 'jawaka' == env.detype()['MYPATH']
Ejemplo n.º 7
0
def test_env_detype_mutable_access_clear():
    env = Env(MYPATH=['/home/wakka', '/home/jawaka'])
    assert_equal('/home/wakka' + os.pathsep + '/home/jawaka',
                 env.detype()['MYPATH'])
    env['MYPATH'][0] = '/home/woah'
    assert_equal(None, env._detyped)
    assert_equal('/home/woah' + os.pathsep + '/home/jawaka',
                 env.detype()['MYPATH'])
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert_equal('wakka' + os.pathsep + 'jawaka',
                 env.detype()['MYPATH'])
    env['MYPATH'][0] = 'woah'
    assert_equal(None, env._detyped)
    assert_equal('woah' + os.pathsep + 'jawaka',
                 env.detype()['MYPATH'])
Ejemplo n.º 8
0
def test_cdpath_events(xonsh_builtins, tmpdir):
    xonsh_builtins.__xonsh__.env = Env(CDPATH=PARENT, PWD=os.getcwd())
    target = str(tmpdir)

    ev = None

    @xonsh_builtins.events.on_chdir
    def handler(olddir, newdir, **kw):
        nonlocal ev
        ev = olddir, newdir

    old_dir = os.getcwd()
    try:
        dirstack.cd([target])
    except:
        raise
    else:
        assert (old_dir, target) == ev
    finally:
        # Use os.chdir() here so dirstack.cd() doesn't fire events (or fail again)
        os.chdir(old_dir)
Ejemplo n.º 9
0
def test_cd_autopush(xonsh_builtins, tmpdir):
    xonsh_builtins.__xonsh__.env = Env(CDPATH=PARENT, PWD=os.getcwd(), AUTO_PUSHD=True)
    target = str(tmpdir)

    old_dir = os.getcwd()
    old_ds_size = len(dirstack.DIRSTACK)

    assert target != old_dir

    try:
        dirstack.cd([target])
        assert target == os.getcwd()
        assert old_ds_size + 1 == len(dirstack.DIRSTACK)
        dirstack.popd([])
    except:
        raise
    finally:
        while len(dirstack.DIRSTACK) > old_ds_size:
            dirstack.popd([])

    assert old_dir == os.getcwd()
Ejemplo n.º 10
0
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)

    monkeypatch.setattr(xonsh_execer, "cacheall", False, raising=False)
    bc = BaseShell(xonsh_execer, None)

    assert os.getcwd() == cur_wd

    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"])
Ejemplo n.º 11
0
def load_builtins(execer=None):
    """Loads the xonsh builtins into the Python builtins. Sets the
    BUILTINS_LOADED variable to True.
    """
    global BUILTINS_LOADED, ENV
    # private built-ins
    builtins.__xonsh_env__ = ENV = Env(default_env())
    builtins.__xonsh_ctx__ = {}
    builtins.__xonsh_help__ = helper
    builtins.__xonsh_superhelp__ = superhelper
    builtins.__xonsh_regexpath__ = regexpath
    builtins.__xonsh_glob__ = globpath
    builtins.__xonsh_exit__ = False
    if hasattr(builtins, 'exit'):
        builtins.__xonsh_pyexit__ = builtins.exit
        del builtins.exit
    if hasattr(builtins, 'quit'):
        builtins.__xonsh_pyquit__ = builtins.quit
        del builtins.quit
    builtins.__xonsh_subproc_captured__ = subproc_captured
    builtins.__xonsh_subproc_uncaptured__ = subproc_uncaptured
    builtins.__xonsh_execer__ = execer
    builtins.__xonsh_all_jobs__ = {}
    builtins.__xonsh_active_job__ = None
    builtins.__xonsh_ensure_list_of_strs__ = ensure_list_of_strs
    # public built-ins
    builtins.evalx = None if execer is None else execer.eval
    builtins.execx = None if execer is None else execer.exec
    builtins.compilex = None if execer is None else execer.compile
    builtins.default_aliases = builtins.aliases = Aliases(DEFAULT_ALIASES)
    builtins.aliases.update(bash_aliases())
    # history needs to be started after env and aliases
    # would be nice to actually include non-detyped versions.
    builtins.__xonsh_history__ = History(env=ENV.detype(), #aliases=builtins.aliases, 
                                         ts=[time.time(), None], locked=True)
    lastflush = lambda s=None, f=None: builtins.__xonsh_history__.flush(at_exit=True)
    atexit.register(lastflush)
    for sig in AT_EXIT_SIGNALS:
        resetting_signal_handle(sig, lastflush)
    BUILTINS_LOADED = True
Ejemplo n.º 12
0
def test_events_on_envvar_called_in_right_order(xonsh_builtins):
    env = Env()
    xonsh_builtins.__xonsh__.env = env
    share = []
    # register
    @xonsh_builtins.events.on_envvar_new
    def handler(name, value, **kwargs):
        share[:] = ["new"]

    @xonsh_builtins.events.on_envvar_change
    def handler1(name, oldvalue, newvalue, **kwargs):
        share[:] = ["change"]

    # trigger new
    env["TEST"] = 1

    assert share == ["new"]

    # trigger change
    env["TEST"] = 2

    assert share == ["change"]
Ejemplo n.º 13
0
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"])
    obs = getattr(vc, fun)()
    if obs is not None:
        assert obs in VC_BRANCH[test_repo["name"]]
        if test_repo["name"] == "git":
            with open("{}/.git/config".format(test_repo["dir"]), "a") as gc:
                gc.write(
                    """
[color]
    branch = always
    interactive = always
[color "branch"]
    current = yellow reverse
"""
                )
            obs = getattr(vc, fun)()
            if obs is not None:
                assert obs in VC_BRANCH[test_repo["name"]]
                assert not obs.startswith(u"\u001b[")
Ejemplo n.º 14
0
def test_vc_get_branch(test_repo, xonsh_builtins):
    xonsh_builtins.__xonsh__.env = Env(VC_BRANCH_TIMEOUT=2,
                                       PWD=test_repo["dir"])
    # get corresponding function from vc module
    get_branch = "get_{}_branch".format(test_repo["vc"])
    branch = getattr(vc, get_branch)()

    assert branch in VC_BRANCH[test_repo["vc"]]
    if test_repo["vc"] == "git":
        git_config = test_repo["dir"] / ".git/config"
        with git_config.open("a") as f:
            f.write("""
[color]
branch = always
interactive = always
[color "branch"]
current = yellow reverse
""")

        branch = getattr(vc, get_branch)()
        assert branch in VC_BRANCH[test_repo["vc"]]
        assert not branch.startswith(u"\u001b[")
Ejemplo n.º 15
0
def test_shell_with_sqlite_history(xonsh_builtins, 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.append({"inp": "echo Hello world 1\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437]})
    h.append({"inp": "echo Hello world 2\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437]})
    h.flush()

    xonsh_builtins.__xonsh__.env = Env(
        XONSH_DATA_DIR=tempdir,
        XONSH_INTERACTIVE=True,
        XONSH_HISTORY_BACKEND='sqlite',
        XONSH_HISTORY_FILE=history_file,
        # XONSH_DEBUG=1  # to show errors
    )

    Shell(xonsh_execer, shell_type='none')

    assert len([i for i in xonsh_builtins.__xonsh__.history.all_items()]) == 2
Ejemplo n.º 16
0
def test_env_detype():
    env = Env(MYPATH=["wakka", "jawaka"])
    assert "wakka" + os.pathsep + "jawaka" == env.detype()["MYPATH"]
Ejemplo n.º 17
0
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 env._detyped is None
    assert path2 + os.pathsep + path1[1] == env.detype()["MYPATH"]
Ejemplo n.º 18
0
def test_env_iterate():
    env = Env(TEST=0)
    env.register(re.compile("re"))
    for key in env:
        assert isinstance(key, str)
Ejemplo n.º 19
0
def test_register_custom_var_str(val, converted):
    env = Env()
    env.register("MY_SPECIAL_VAR", type="str")

    env["MY_SPECIAL_VAR"] = val
    assert env["MY_SPECIAL_VAR"] == converted
Ejemplo n.º 20
0
def test_delitem():
    env = Env(VAR="a value")
    assert env["VAR"] == "a value"
    del env["VAR"]
    with pytest.raises(Exception):
        env["VAR"]
Ejemplo n.º 21
0
def test_cdpath_simple(xonsh_builtins):
    xonsh_builtins.__xonsh_env__ = Env(CDPATH=PARENT, PWD=HERE)
    with chdir(os.path.normpath("/")):
        assert os.getcwd() != HERE
        dirstack.cd(["tests"])
        assert os.getcwd() == HERE
Ejemplo n.º 22
0
def test_cdpath_simple():
    with xonsh_env(Env(CDPATH=PARENT)):
        with chdir(os.path.normpath("/")):
            assert_not_equal(os.getcwd(), HERE)
            dirstack.cd(["tests"])
            assert_equal(os.getcwd(), HERE)
Ejemplo n.º 23
0
def test_env_detype_no_dict():
    env = Env(YO={'hey': 42})
    det = env.detype()
    assert 'YO' not in det
Ejemplo n.º 24
0
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 env._detyped is None
    assert path2 + os.pathsep + path1[1] == env.detype()['MYPATH']
Ejemplo n.º 25
0
def test_env_detype():
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert 'wakka' + os.pathsep + 'jawaka' == env.detype()['MYPATH']
Ejemplo n.º 26
0
def test_env_detype():
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert_equal(os.path.abspath('wakka') + os.pathsep + \
                 os.path.abspath('jawaka'),
                 env.detype()['MYPATH'])
Ejemplo n.º 27
0
# -*- coding: utf-8 -*-
"""Tests some tools function for prompt_toolkit integration."""
from __future__ import unicode_literals, print_function

import nose
from nose.tools import assert_equal

import builtins
from xonsh.tools import format_prompt_for_prompt_toolkit
from xonsh.tools import TERM_COLORS
from xonsh.environ import format_prompt, Env

builtins.__xonsh_env__ = Env()
builtins.__xonsh_env__['PROMPT_TOOLKIT_COLORS'] = {'WHITE': '#ffffff'}


def test_format_prompt_for_prompt_toolkit():
    templ = ('>>> {BOLD_BLUE}~/xonsh {WHITE} (main){NO_COLOR}')
    prompt = format_prompt(templ, TERM_COLORS)
    token_names, color_styles, strings = format_prompt_for_prompt_toolkit(
        prompt)
    assert_equal(token_names, ['NO_COLOR', 'BOLD_BLUE', 'WHITE', 'NO_COLOR'])
    assert_equal(color_styles, ['', 'bold #0000FF', '#ffffff', ''])
    assert_equal(strings, ['>>> ', '~/xonsh ', ' (main)', ''])


if __name__ == '__main__':
    nose.runmodule()
Ejemplo n.º 28
0
def test_histcontrol_none():
    env = Env(HISTCONTROL=None)
    assert isinstance(env["HISTCONTROL"], set)
    assert len(env["HISTCONTROL"]) == 0
Ejemplo n.º 29
0
def home_env(xonsh_builtins):
    """Set `__xonsh_env__ ` to a new Env instance on `xonsh_builtins`"""
    xonsh_builtins.__xonsh_env__ = Env(HOME=HOME_PATH)
    return xonsh_builtins
Ejemplo n.º 30
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"]
Ejemplo n.º 31
0
def test_simple(xonsh_builtins):
    xonsh_builtins.__xonsh_env__ = Env(CDPATH=PARENT, PWD=PARENT)
    with chdir(PARENT):
        assert os.getcwd() != HERE
        dirstack.cd(["tests"])
        assert os.getcwd() == HERE
Ejemplo n.º 32
0
from xonsh.environ import DEFAULT_DOCS, Env
from xonsh.xontribs import xontrib_metadata
from xonsh import main
from xonsh.commands_cache import CommandsCache

if not hasattr(builtins, "__xonsh__"):
    from argparse import Namespace

    builtins.__xonsh__ = Namespace()
    builtins.__xonsh__.load = lambda *a, **kw: None
    builtins.__xonsh__.link_builtins = lambda *a, **kw: None

spec = importlib.util.find_spec("prompt_toolkit")
if spec is not None:
    # hacky runaround to import PTK-specific events
    builtins.__xonsh__.env = Env()
    from xonsh.platform import ptk_version_info

    if ptk_version_info()[0] < 2:
        from xonsh.ptk.shell import events
    else:
        from xonsh.ptk2.shell import events
else:
    from xonsh.events import events

sys.path.insert(0, os.path.dirname(__file__))


def setup(sphinx):
    from xonsh.pyghooks import XonshConsoleLexer
Ejemplo n.º 33
0
def test_env_normal():
    env = Env(VAR="wakka")
    assert "wakka" == env["VAR"]
Ejemplo n.º 34
0
def test_env_detype_mutable_access_clear():
    env = Env(MYPATH=["wakka", "jawaka"])
    assert_equal({"MYPATH": "wakka" + os.pathsep + "jawaka"}, env.detype())
    env["MYPATH"][0] = "woah"
    assert_equal(None, env._detyped)
    assert_equal({"MYPATH": "woah" + os.pathsep + "jawaka"}, env.detype())
Ejemplo n.º 35
0
def test_env_contains():
    env = Env(VAR="wakka")
    assert "VAR" in env
Ejemplo n.º 36
0
def test_env_detype_no_dict():
    env = Env(YO={"hey": 42})
    det = env.detype()
    assert "YO" not in det
Ejemplo n.º 37
0
def test_env_path_str(path):
    env = Env(MYPATH=path)
    assert path == env["MYPATH"].paths
Ejemplo n.º 38
0
def test_eval_recursive_callable_partial(xonsh_execer, xonsh_builtins):
    ales = make_aliases()
    xonsh_builtins.__xonsh__.env = Env(HOME=os.path.expanduser("~"))
    assert ales.get("indirect_cd")(["arg2", "arg3"]) == ["..", "arg2", "arg3"]
Ejemplo n.º 39
0
def test_env_detype():
    env = Env(MYPATH=["wakka", "jawaka"])
    assert "wakka" + os.pathsep + "jawaka" == env.detype()["MYPATH"]
Ejemplo n.º 40
0
def test_env_detype_no_dict():
    env = Env(YO={"hey": 42})
    det = env.detype()
    assert_not_in("YO", det)
Ejemplo n.º 41
0
def test_env_detype_no_dict():
    env = Env(YO={"hey": 42})
    env.register("YO", validate=always_true, convert=None, detype=None)
    det = env.detype()
    assert "YO" not in det
Ejemplo n.º 42
0
def test_env_detype_no_dict():
    env = Env(YO={"hey": 42})
    env.set_ensurer("YO", Ensurer(always_true, None, None))
    det = env.detype()
    assert "YO" not in det
Ejemplo n.º 43
0
def test_HISTCONTROL_empty():
    env = Env(HISTCONTROL="")
    assert isinstance(env["HISTCONTROL"], set)
    assert len(env["HISTCONTROL"]) == 0
Ejemplo n.º 44
0
def test_env_detype():
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert_equal({'MYPATH': 'wakka' + os.pathsep + 'jawaka'}, env.detype())
Ejemplo n.º 45
0
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"]
Ejemplo n.º 46
0
def test_env_detype_mutable_access_clear():
    env = Env(MYPATH=['wakka', 'jawaka'])
    assert_equal({'MYPATH': 'wakka' + os.pathsep + 'jawaka'}, env.detype())
    env['MYPATH'][0] = 'woah'
    assert_equal(None, env._detyped)
    assert_equal({'MYPATH': 'woah' + os.pathsep + 'jawaka'}, env.detype())
Ejemplo n.º 47
0
def test_env_detype_no_dict():
    env = Env(YO={'hey': 42})
    det = env.detype()
    assert_not_in('YO', det)
Ejemplo n.º 48
0
def test_env_detype():
    env = Env(MYPATH=["wakka", "jawaka"])
    assert_equal({"MYPATH": "wakka" + os.pathsep + "jawaka"}, env.detype())