Merge pull request #3718 from xonsh/black

black updates to tests and docs
This commit is contained in:
David Strobach 2020-08-26 17:53:20 +02:00 committed by GitHub
commit 2857db66da
Failed to generate hash of commit
17 changed files with 259 additions and 209 deletions

View file

@ -529,7 +529,7 @@ def rewrite_init(pkg, order, debug="DEBUG"):
stop = i
elif line.startswith("# amalgamate"):
start = i
t = "{1} = __amalgam__\n " "_sys.modules[\"{0}.{1}\"] = __amalgam__"
t = "{1} = __amalgam__\n " '_sys.modules["{0}.{1}"] = __amalgam__'
load = "\n ".join(t.format(pkg, m) for m in order)
s = FAKE_LOAD.format(pkg=pkg, load=load, debug=debug)
if start + 1 == stop:

View file

@ -11,10 +11,11 @@ import io
import textwrap
import importlib
from docutils import nodes, statemachine, utils
try:
from docutils.utils.error_reporting import ErrorString # the new way
except ImportError:
from docutils.error_reporting import ErrorString # the old way
from docutils.error_reporting import ErrorString # the old way
from docutils.parsers.rst import Directive, convert_directive_function
from docutils.parsers.rst import directives, roles, states
from docutils.parsers.rst.roles import set_classes
@ -31,6 +32,7 @@ class CommandHelp(Directive):
of string lines of restructured text and then parsing it into its own node.
Note that this will add the '--help' flag automatically.
"""
required_arguments = 1
optional_arguments = 1
final_argument_whitespace = True
@ -39,11 +41,11 @@ class CommandHelp(Directive):
def run(self):
arguments = self.arguments
lines = ['.. code-block:: none', '']
m, f = arguments[0].rsplit('.', 1)
lines = [".. code-block:: none", ""]
m, f = arguments[0].rsplit(".", 1)
mod = importlib.import_module(m)
func = getattr(mod, f)
args = ['--help'] if len(arguments) == 1 else arguments[1:]
args = ["--help"] if len(arguments) == 1 else arguments[1:]
stdout = io.StringIO()
stderr = io.StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
@ -53,7 +55,7 @@ class CommandHelp(Directive):
pass
stdout.seek(0)
s = stdout.read()
lines += textwrap.indent(s, ' ').splitlines()
lines += textwrap.indent(s, " ").splitlines()
# hook to docutils
src, lineno = self.state_machine.get_source_and_line(self.lineno)
@ -64,5 +66,4 @@ class CommandHelp(Directive):
def setup(app):
app.add_directive('command-help', CommandHelp)
app.add_directive("command-help", CommandHelp)

View file

@ -202,7 +202,7 @@ html_style = "numpy_friendly.css"
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {'index': 'index.html'}
html_additional_pages = {"index": "index.html"}
# If false, no module index is generated.
# html_use_modindex = True

View file

@ -25,16 +25,21 @@ def test_missing_command(mockexecvpe):
def test_command_not_found(monkeypatch):
dummy_error_msg = "This is dummy error message, file not found or something like that"
dummy_error_msg = (
"This is dummy error message, file not found or something like that"
)
command = "non_existing_command"
def mocked_execvpe(_command, _args, _env):
raise FileNotFoundError(2, dummy_error_msg)
monkeypatch.setattr(os, "execvpe", mocked_execvpe)
assert xexec([command]) == (None,
"xonsh: exec: file not found: {}: {}" "\n".format(dummy_error_msg, command),
1)
assert xexec([command]) == (
None,
"xonsh: exec: file not found: {}: {}" "\n".format(dummy_error_msg, command),
1,
)
def test_help(mockexecvpe):

View file

@ -362,7 +362,7 @@ def test_register_custom_var_generic():
def test_register_custom_var_int():
env = Env()
env.register("MY_SPECIAL_VAR", type='int')
env.register("MY_SPECIAL_VAR", type="int")
env["MY_SPECIAL_VAR"] = "32"
assert env["MY_SPECIAL_VAR"] == 32
@ -373,7 +373,7 @@ def test_register_custom_var_int():
def test_register_custom_var_float():
env = Env()
env.register("MY_SPECIAL_VAR", type='float')
env.register("MY_SPECIAL_VAR", type="float")
env["MY_SPECIAL_VAR"] = "27"
assert env["MY_SPECIAL_VAR"] == 27.0
@ -382,38 +382,42 @@ def test_register_custom_var_float():
env["MY_SPECIAL_VAR"] = "wakka"
@pytest.mark.parametrize("val,converted",
[
(True, True),
(32, True),
(0, False),
(27.0, True),
(None, False),
("lol", True),
("false", False),
("no", False),
])
@pytest.mark.parametrize(
"val,converted",
[
(True, True),
(32, True),
(0, False),
(27.0, True),
(None, False),
("lol", True),
("false", False),
("no", False),
],
)
def test_register_custom_var_bool(val, converted):
env = Env()
env.register("MY_SPECIAL_VAR", type='bool')
env.register("MY_SPECIAL_VAR", type="bool")
env["MY_SPECIAL_VAR"] = val
assert env["MY_SPECIAL_VAR"] == converted
@pytest.mark.parametrize("val,converted",
[
(32, "32"),
(0, "0"),
(27.0, "27.0"),
(None, "None"),
("lol", "lol"),
("false", "false"),
("no", "no"),
])
@pytest.mark.parametrize(
"val,converted",
[
(32, "32"),
(0, "0"),
(27.0, "27.0"),
(None, "None"),
("lol", "lol"),
("false", "false"),
("no", "no"),
],
)
def test_register_custom_var_str(val, converted):
env = Env()
env.register("MY_SPECIAL_VAR", type='str')
env.register("MY_SPECIAL_VAR", type="str")
env["MY_SPECIAL_VAR"] = val
assert env["MY_SPECIAL_VAR"] == converted
@ -421,12 +425,12 @@ def test_register_custom_var_str(val, converted):
def test_register_custom_var_path():
env = Env()
env.register("MY_SPECIAL_VAR", type='path')
env.register("MY_SPECIAL_VAR", type="path")
paths = ["/home/wakka", "/home/wakka/bin"]
env["MY_SPECIAL_VAR"] = paths
assert hasattr(env['MY_SPECIAL_VAR'], 'paths')
assert hasattr(env["MY_SPECIAL_VAR"], "paths")
assert env["MY_SPECIAL_VAR"].paths == paths
with pytest.raises(TypeError):
@ -436,11 +440,11 @@ def test_register_custom_var_path():
def test_deregister_custom_var():
env = Env()
env.register("MY_SPECIAL_VAR", type='path')
env.register("MY_SPECIAL_VAR", type="path")
env.deregister("MY_SPECIAL_VAR")
assert "MY_SPECIAL_VAR" not in env
env.register("MY_SPECIAL_VAR", type='path')
env.register("MY_SPECIAL_VAR", type="path")
paths = ["/home/wakka", "/home/wakka/bin"]
env["MY_SPECIAL_VAR"] = paths
env.deregister("MY_SPECIAL_VAR")

View file

@ -475,7 +475,7 @@ def test__xhj_gc_xx_to_rmfiles(
assert act_files == exp_files
# comparing age is approximate, because xhj_gc_seconds_to_rmfiles computes 'now' on each call.
# For test runs, accept anything in the same hour, test cases not that close.
# For test runs, accept anything in the same hour, test cases not that close.
# We find multi-minute variations in CI environments.
# This should cover some amount of think time sitting at a breakpoint, too.
if fn == _xhj_gc_seconds_to_rmfiles:

View file

@ -65,8 +65,8 @@ def test_module_dunder_file_attribute_sub():
def test_get_source():
mod = import_module('sample')
mod = import_module("sample")
loader = mod.__loader__
source = loader.get_source('sample')
with open(os.path.join(TEST_DIR, 'sample.xsh'), 'rt') as srcfile:
source = loader.get_source("sample")
with open(os.path.join(TEST_DIR, "sample.xsh"), "rt") as srcfile:
assert source == srcfile.read()

View file

@ -129,7 +129,7 @@ fstring_adaptor_parameters = [
('f"{$HOME}"', "/foo/bar"),
('f"{ $HOME }"', "/foo/bar"),
("f\"{'$HOME'}\"", "$HOME"),
("f\"$HOME = {$HOME}\"", "$HOME = /foo/bar"),
('f"$HOME = {$HOME}"', "$HOME = /foo/bar"),
("f\"{${'HOME'}}\"", "/foo/bar"),
("f'{${$FOO+$BAR}}'", "/foo/bar"),
("f\"${$FOO}{$BAR}={f'{$HOME}'}\"", "$HOME=/foo/bar"),

View file

@ -7,15 +7,23 @@ from xonsh.completers.tools import RichCompletion
from xonsh.ptk_shell.completer import PromptToolkitCompleter
@pytest.mark.parametrize('completion, lprefix, ptk_completion', [
(RichCompletion('x', 0, 'x()', 'func'), 0, None),
(RichCompletion('x', 1, 'xx', 'instance'), 0, None),
(RichCompletion('x', description='wow'), 5,
PTKCompletion(RichCompletion('x'), -5, 'x', 'wow')),
(RichCompletion('x'), 5, PTKCompletion(RichCompletion('x'), -5, 'x')),
('x', 5, PTKCompletion('x', -5, 'x')),
])
def test_rich_completion(completion, lprefix, ptk_completion, monkeypatch, xonsh_builtins):
@pytest.mark.parametrize(
"completion, lprefix, ptk_completion",
[
(RichCompletion("x", 0, "x()", "func"), 0, None),
(RichCompletion("x", 1, "xx", "instance"), 0, None),
(
RichCompletion("x", description="wow"),
5,
PTKCompletion(RichCompletion("x"), -5, "x", "wow"),
),
(RichCompletion("x"), 5, PTKCompletion(RichCompletion("x"), -5, "x")),
("x", 5, PTKCompletion("x", -5, "x")),
],
)
def test_rich_completion(
completion, lprefix, ptk_completion, monkeypatch, xonsh_builtins
):
xonsh_completer_mock = MagicMock()
xonsh_completer_mock.complete.return_value = {completion}, lprefix
@ -24,18 +32,21 @@ def test_rich_completion(completion, lprefix, ptk_completion, monkeypatch, xonsh
ptk_completer.suggestion_completion = lambda _, __: None
document_mock = MagicMock()
document_mock.text = ''
document_mock.current_line = ''
document_mock.text = ""
document_mock.current_line = ""
document_mock.cursor_position_col = 0
monkeypatch.setattr('builtins.aliases', Aliases())
monkeypatch.setattr("builtins.aliases", Aliases())
completions = list(
ptk_completer.get_completions(document_mock, MagicMock()))
completions = list(ptk_completer.get_completions(document_mock, MagicMock()))
if isinstance(completion, RichCompletion) and not ptk_completion:
assert completions == [
PTKCompletion(completion, -completion.prefix_len,
completion.display,
completion.description)]
PTKCompletion(
completion,
-completion.prefix_len,
completion.display,
completion.description,
)
]
else:
assert completions == [ptk_completion]

View file

@ -187,17 +187,15 @@ def test_color_on_lscolors_change(tmpdir, xonsh_builtins_ls_colors):
lsc = xonsh_builtins_ls_colors.__xonsh__.env["LS_COLORS"]
test_dir = str(tmpdir.mkdir("xonsh-test-highlight-path"))
lsc['di'] = ('GREEN',)
lsc["di"] = ("GREEN",)
check_token(
"cd {}".format(test_dir), [(Name.Builtin, "cd"), (Color.GREEN, test_dir)]
)
del lsc['di']
del lsc["di"]
check_token(
"cd {}".format(test_dir), [(Name.Builtin, "cd"), (Text, test_dir)]
)
check_token("cd {}".format(test_dir), [(Name.Builtin, "cd"), (Text, test_dir)])
@skip_if_on_windows

View file

@ -10,6 +10,7 @@ except ImportError:
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
@ -28,6 +29,7 @@ def test_ptk2_backcompat():
import xonsh.ptk_shell.shell as imports_new
import xonsh.ptk2.shell as imports_legacy
# defining the ptk2 package this way leaves out the internal global names (which all start with '_')
s_new = set(dir(imports_new))
@ -35,10 +37,11 @@ def test_ptk2_backcompat():
extra_names = s_new - s_legacy
for name in extra_names:
assert name.startswith('_')
assert name.startswith("_")
assert s_legacy.issubset(s_new)
# prove that legacy API is usable
@ -46,6 +49,7 @@ def test_ptk2_backcompat():
def history_obj_legacy():
"""Instantiate `PromptToolkitHistory` via legacy alias and append a line string"""
from xonsh.ptk2.history import PromptToolkitHistory
hist = PromptToolkitHistory(load_prev=False)
hist.append_string("line10")
return hist

View file

@ -13,6 +13,7 @@ from xonsh.tools import ON_WINDOWS
from xonsh.built_ins import XonshSession
from tools import DummyEnv
Context = namedtuple("Context", ["indent", "buffer", "accept", "cli", "cr"])

View file

@ -5,19 +5,21 @@ from xonsh.readline_shell import _render_completions
@pytest.mark.parametrize(
'prefix, completion, prefix_len, readline_completion', [
('', 'a', 0, 'a'),
('a', 'b', 0, 'ab'),
('a', 'b', 1, 'b'),
('adc', 'bc', 2, 'abc'),
('', RichCompletion('x', 0), 0, 'x'),
('', RichCompletion('x', 0, 'aaa', 'aaa'), 0, 'x'),
('a', RichCompletion('b', 1), 0, 'b'),
('a', RichCompletion('b', 0), 1, 'ab'),
('a', RichCompletion('b'), 0, 'ab'),
('a', RichCompletion('b'), 1, 'b'),
])
def test_render_completions(prefix, completion, prefix_len,
readline_completion):
"prefix, completion, prefix_len, readline_completion",
[
("", "a", 0, "a"),
("a", "b", 0, "ab"),
("a", "b", 1, "b"),
("adc", "bc", 2, "abc"),
("", RichCompletion("x", 0), 0, "x"),
("", RichCompletion("x", 0, "aaa", "aaa"), 0, "x"),
("a", RichCompletion("b", 1), 0, "b"),
("a", RichCompletion("b", 0), 1, "ab"),
("a", RichCompletion("b"), 0, "ab"),
("a", RichCompletion("b"), 1, "b"),
],
)
def test_render_completions(prefix, completion, prefix_len, readline_completion):
assert _render_completions({completion}, prefix, prefix_len) == [
readline_completion]
readline_completion
]

View file

@ -103,8 +103,8 @@ def test_activate_non_vox_venv(xonsh_builtins, tmpdir):
last_event = "deactivate", name, path
with tmpdir.as_cwd():
venv_dirname = 'venv'
sp.run([sys.executable, '-m', 'venv', venv_dirname])
venv_dirname = "venv"
sp.run([sys.executable, "-m", "venv", venv_dirname])
vox = Vox()
vox.activate(venv_dirname)
vxv = vox[venv_dirname]
@ -117,7 +117,7 @@ def test_activate_non_vox_venv(xonsh_builtins, tmpdir):
assert last_event == (
"activate",
venv_dirname,
str(pathlib.Path(str(tmpdir)) / 'venv')
str(pathlib.Path(str(tmpdir)) / "venv"),
)
vox.deactivate()
@ -126,7 +126,7 @@ def test_activate_non_vox_venv(xonsh_builtins, tmpdir):
assert last_event == (
"deactivate",
tmpdir.join(venv_dirname),
str(pathlib.Path(str(tmpdir)) / 'venv')
str(pathlib.Path(str(tmpdir)) / "venv"),
)
@ -243,14 +243,15 @@ def test_autovox(xonsh_builtins, tmpdir):
# Makes sure that event handlers are registered
import xontrib.autovox
importlib.reload(xontrib.autovox)
# Set up enough environment for xonsh to function
xonsh_builtins.__xonsh__.env['PWD'] = os.getcwd()
xonsh_builtins.__xonsh__.env['DIRSTACK_SIZE'] = 10
xonsh_builtins.__xonsh__.env['PATH'] = []
xonsh_builtins.__xonsh__.env["PWD"] = os.getcwd()
xonsh_builtins.__xonsh__.env["DIRSTACK_SIZE"] = 10
xonsh_builtins.__xonsh__.env["PATH"] = []
xonsh_builtins.__xonsh__.env['XONSH_SHOW_TRACEBACK'] = True
xonsh_builtins.__xonsh__.env["XONSH_SHOW_TRACEBACK"] = True
@xonsh_builtins.events.autovox_policy
def policy(path, **_):
@ -260,16 +261,16 @@ def test_autovox(xonsh_builtins, tmpdir):
vox = Vox()
print(xonsh_builtins.__xonsh__.env['PWD'])
print(xonsh_builtins.__xonsh__.env["PWD"])
xonsh.dirstack.pushd([str(tmpdir)])
print(xonsh_builtins.__xonsh__.env['PWD'])
print(xonsh_builtins.__xonsh__.env["PWD"])
assert vox.active() is None
xonsh.dirstack.popd([])
print(xonsh_builtins.__xonsh__.env['PWD'])
print(xonsh_builtins.__xonsh__.env["PWD"])
vox.create('myenv')
vox.create("myenv")
xonsh.dirstack.pushd([str(tmpdir)])
print(xonsh_builtins.__xonsh__.env['PWD'])
assert vox.active() == 'myenv'
print(xonsh_builtins.__xonsh__.env["PWD"])
assert vox.active() == "myenv"
xonsh.dirstack.popd([])
print(xonsh_builtins.__xonsh__.env['PWD'])
print(xonsh_builtins.__xonsh__.env["PWD"])

View file

@ -109,8 +109,8 @@ def test_boottime():
@pytest.fixture
def cat_env_fixture(xonsh_builtins):
with xonsh_builtins.__xonsh__.env.swap(
XONSH_ENCODING=DEFAULT_ENCODING,
XONSH_ENCODING_ERRORS="surrogateescape"):
XONSH_ENCODING=DEFAULT_ENCODING, XONSH_ENCODING_ERRORS="surrogateescape"
):
yield xonsh_builtins
@ -134,29 +134,29 @@ class CatLimitedBuffer(io.BytesIO):
class TestCatLimitedBuffer:
def test_write_buffer_correctly(self):
buf = CatLimitedBuffer(limit=500)
buf.write(b'0' * 499)
assert buf.getvalue() == b'0' * 499
buf.write(b"0" * 499)
assert buf.getvalue() == b"0" * 499
def test_raise_keyboardinterrupt_when_reached(self):
buf = CatLimitedBuffer(limit=500)
buf.write(b'0' * 499)
buf.write(b"0" * 499)
with pytest.raises(KeyboardInterrupt):
buf.write(b'1')
buf.write(b"1")
def test_raise_allow_write_over_limit(self):
buf = CatLimitedBuffer(limit=500)
buf.write(b'0' * 400)
buf.write(b"0" * 400)
with pytest.raises(KeyboardInterrupt):
buf.write(b'1' * 200)
buf.write(b"1" * 200)
assert buf.getvalue() == (b'0' * 400 + b'1' * 200)
assert buf.getvalue() == (b"0" * 400 + b"1" * 200)
def test_not_raise_twice_time(self):
buf = CatLimitedBuffer(limit=500)
with pytest.raises(KeyboardInterrupt):
buf.write(b'1' * 1000)
buf.write(b"1" * 1000)
try:
buf.write(b'2')
buf.write(b"2")
except KeyboardInterrupt:
pytest.fail("Unexpected KeyboardInterrupt")
@ -166,6 +166,7 @@ class TestCat:
def setup_method(self, _method):
import tempfile
tmpfile = tempfile.mkstemp()
self.tempfile = tmpfile[1]
os.close(tmpfile[0])
@ -189,7 +190,7 @@ class TestCat:
stdout.flush()
stderr.flush()
assert stdout_buf.getvalue() == bytes(expected_content, "utf-8")
assert stderr_buf.getvalue() == b''
assert stderr_buf.getvalue() == b""
def test_cat_single_file_with_end_newline(self, cat_env_fixture):
content = "this is a content withe \\n\nfor testing xoreutil's cat\n"
@ -207,7 +208,7 @@ class TestCat:
stdout.flush()
stderr.flush()
assert stdout_buf.getvalue() == bytes(expected_content, "utf-8")
assert stderr_buf.getvalue() == b''
assert stderr_buf.getvalue() == b""
def test_cat_empty_file(self, cat_env_fixture):
with open(self.tempfile, "w") as f:
@ -222,11 +223,12 @@ class TestCat:
cat._cat_single_file(opts, self.tempfile, stdin, stdout, stderr)
stdout.flush()
stderr.flush()
assert stdout_buf.getvalue() == b''
assert stderr_buf.getvalue() == b''
assert stdout_buf.getvalue() == b""
assert stderr_buf.getvalue() == b""
@pytest.mark.skipif(not os.path.exists("/dev/urandom"),
reason="/dev/urandom doesn't exists")
@pytest.mark.skipif(
not os.path.exists("/dev/urandom"), reason="/dev/urandom doesn't exists"
)
def test_cat_dev_urandom(self, cat_env_fixture):
"""
test of cat (pseudo) device.

View file

@ -30,7 +30,7 @@ ON_AZURE_PIPELINES = os.environ.get("TF_BUILD", "") == "True"
print("ON_AZURE_PIPELINES", repr(ON_AZURE_PIPELINES))
print("os.environ['TF_BUILD']", repr(os.environ.get("TF_BUILD", "")))
TEST_DIR = os.path.dirname(__file__)
HAS_WALRUS = (VER_FULL > (3, 8))
HAS_WALRUS = VER_FULL > (3, 8)
# pytest skip decorators
skip_if_on_conda = pytest.mark.skipif(
@ -55,6 +55,7 @@ skip_if_on_travis = pytest.mark.skipif(ON_TRAVIS, reason="not Travis CI friendly
skip_if_no_walrus = pytest.mark.skipif(not HAS_WALRUS, reason="no assignment expr.")
def sp(cmd):
return subprocess.check_output(cmd, universal_newlines=True)
@ -201,11 +202,9 @@ def nodes_equal(x, y):
type(y),
)
if isinstance(x, (ast.Expr, ast.FunctionDef, ast.ClassDef)):
assert (
x.lineno == y.lineno
), "Ast nodes do not have the same line number : %s != %s" % (
x.lineno,
y.lineno,
assert x.lineno == y.lineno, (
"Ast nodes do not have the same line number : %s != %s"
% (x.lineno, y.lineno,)
)
assert x.col_offset == y.col_offset, (
"Ast nodes do not have the same column offset number : %s != %s"

View file

@ -12,10 +12,10 @@ from xonsh.completers.tools import RichCompletion
@pytest.fixture
def jedi_mock(monkeypatch):
jedi_mock = MagicMock()
jedi_mock.__version__ = '0.16.0'
jedi_mock.__version__ = "0.16.0"
jedi_mock.Interpreter().complete.return_value = []
jedi_mock.reset_mock()
monkeypatch.setitem(sys.modules, 'jedi', jedi_mock)
monkeypatch.setitem(sys.modules, "jedi", jedi_mock)
yield jedi_mock
@ -27,63 +27,64 @@ def completer_mock(monkeypatch):
def comp(args):
completer_mock(args)
monkeypatch.setitem(builtins.aliases, 'completer', comp)
monkeypatch.setitem(builtins.aliases, "completer", comp)
yield completer_mock
@pytest.fixture
def jedi_xontrib(monkeypatch, source_path, jedi_mock, completer_mock):
monkeypatch.syspath_prepend(source_path)
spec = find_xontrib('jedi')
spec = find_xontrib("jedi")
yield importlib.import_module(spec.name)
del sys.modules[spec.name]
def test_completer_added(jedi_xontrib, completer_mock):
assert completer_mock.call_args_list == [call(['remove', 'python_mode']),
call(['add', 'jedi_python',
'complete_jedi', '<python']),
call(['remove', 'python'])]
assert completer_mock.call_args_list == [
call(["remove", "python_mode"]),
call(["add", "jedi_python", "complete_jedi", "<python"]),
call(["remove", "python"]),
]
@pytest.mark.parametrize('prefix, line, start, end, ctx', [
('x', '10 + x', 5, 6, {}),
], ids='x')
@pytest.mark.parametrize('version', ['new', 'old'])
def test_jedi_api(jedi_xontrib, jedi_mock, version, prefix, line, start, end,
ctx):
if version == 'old':
jedi_mock.__version__ = '0.15.0'
@pytest.mark.parametrize(
"prefix, line, start, end, ctx", [("x", "10 + x", 5, 6, {}),], ids="x"
)
@pytest.mark.parametrize("version", ["new", "old"])
def test_jedi_api(jedi_xontrib, jedi_mock, version, prefix, line, start, end, ctx):
if version == "old":
jedi_mock.__version__ = "0.15.0"
jedi_mock.Interpreter().completions.return_value = []
jedi_mock.reset_mock()
jedi_xontrib.complete_jedi(prefix, line, start, end, ctx)
extra_namespace = {'__xonsh__': builtins.__xonsh__}
extra_namespace = {"__xonsh__": builtins.__xonsh__}
try:
extra_namespace['_'] = _
extra_namespace["_"] = _
except NameError:
pass
namespaces = [{}, extra_namespace]
if version == 'new':
if version == "new":
assert jedi_mock.Interpreter.call_args_list == [call(line, namespaces)]
assert jedi_mock.Interpreter().complete.call_args_list == [call(1, end)]
else:
assert jedi_mock.Interpreter.call_args_list == [
call(line, namespaces, line=1, column=end)]
call(line, namespaces, line=1, column=end)
]
assert jedi_mock.Interpreter().completions.call_args_list == [call()]
def test_multiline(jedi_xontrib, jedi_mock, monkeypatch):
shell_mock = MagicMock()
complete_document = 'xx = 1\n1 + x'
shell_mock.shell_type = 'prompt_toolkit'
complete_document = "xx = 1\n1 + x"
shell_mock.shell_type = "prompt_toolkit"
shell_mock.shell.pt_completer.current_document.text = complete_document
shell_mock.shell.pt_completer.current_document.cursor_position_row = 1
shell_mock.shell.pt_completer.current_document.cursor_position_col = 5
monkeypatch.setattr(builtins.__xonsh__, 'shell', shell_mock)
jedi_xontrib.complete_jedi('x', 'x', 0, 1, {})
monkeypatch.setattr(builtins.__xonsh__, "shell", shell_mock)
jedi_xontrib.complete_jedi("x", "x", 0, 1, {})
assert jedi_mock.Interpreter.call_args_list[0][0][0] == complete_document
assert jedi_mock.Interpreter().complete.call_args_list == [
@ -91,73 +92,92 @@ def test_multiline(jedi_xontrib, jedi_mock, monkeypatch):
]
@pytest.mark.parametrize('completion, rich_completion', [
(
@pytest.mark.parametrize(
"completion, rich_completion",
[
(
# from jedi when code is 'x' and xx=3
('instance', 'xx', 'x', 'int(x=None, /) -> int',
('instance', 'instance int')),
RichCompletion('x', display='xx', description='instance int')
),
(
(
"instance",
"xx",
"x",
"int(x=None, /) -> int",
("instance", "instance int"),
),
RichCompletion("x", display="xx", description="instance int"),
),
(
# from jedi when code is 'xx=3\nx'
('statement', 'xx', 'x', None, ('instance', 'instance int')),
RichCompletion('x', display='xx', description='instance int')
),
(
("statement", "xx", "x", None, ("instance", "instance int")),
RichCompletion("x", display="xx", description="instance int"),
),
(
# from jedi when code is 'x.' and x=3
('function', 'from_bytes', 'from_bytes',
'from_bytes(bytes, byteorder, *, signed=False)',
('function', 'def __get__')),
RichCompletion('from_bytes', display='from_bytes()',
description=
'from_bytes(bytes, byteorder, *, signed=False)')
),
(
(
"function",
"from_bytes",
"from_bytes",
"from_bytes(bytes, byteorder, *, signed=False)",
("function", "def __get__"),
),
RichCompletion(
"from_bytes",
display="from_bytes()",
description="from_bytes(bytes, byteorder, *, signed=False)",
),
),
(
# from jedi when code is 'x=3\nx.'
('function', 'imag', 'imag', None, ('instance', 'instance int')),
RichCompletion('imag', display='imag', description='instance int')
),
(
("function", "imag", "imag", None, ("instance", "instance int")),
RichCompletion("imag", display="imag", description="instance int"),
),
(
# from '(3).from_bytes(byt'
('param', 'bytes=', 'es=', None, ('instance', 'instance Sequence')),
RichCompletion('es=', display='bytes=',
description='instance Sequence')
),
(
("param", "bytes=", "es=", None, ("instance", "instance Sequence")),
RichCompletion("es=", display="bytes=", description="instance Sequence"),
),
(
# from 'x.from_bytes(byt' when x=3
('param', 'bytes=', 'es=', None, None),
RichCompletion('es=', display='bytes=', description='param')
),
(
("param", "bytes=", "es=", None, None),
RichCompletion("es=", display="bytes=", description="param"),
),
(
# from 'import colle'
('module', 'collections', 'ctions', None,
('module', 'module collections')),
RichCompletion('ctions', display='collections',
description='module collections')
),
(
("module", "collections", "ctions", None, ("module", "module collections")),
RichCompletion(
"ctions", display="collections", description="module collections"
),
),
(
# from 'NameErr'
('class', 'NameError', 'or', 'NameError(*args: object)',
('class', 'class NameError')),
RichCompletion('or', display='NameError',
description='NameError(*args: object)')
),
(
(
"class",
"NameError",
"or",
"NameError(*args: object)",
("class", "class NameError"),
),
RichCompletion(
"or", display="NameError", description="NameError(*args: object)"
),
),
(
# from 'a["' when a={'name':None}
('string', '"name"', 'name"', None, None),
RichCompletion('name"', display='"name"', description='string')
),
(
("string", '"name"', 'name"', None, None),
RichCompletion('name"', display='"name"', description="string"),
),
(
# from 'open("/etc/pass'
('path', 'passwd"', 'wd"', None, None),
RichCompletion('wd"', display='passwd"', description='path')
),
(
("path", 'passwd"', 'wd"', None, None),
RichCompletion('wd"', display='passwd"', description="path"),
),
(
# from 'cla'
('keyword', 'class', 'ss', None, None),
RichCompletion('ss', display='class', description='keyword')
),
])
("keyword", "class", "ss", None, None),
RichCompletion("ss", display="class", description="keyword"),
),
],
)
def test_rich_completions(jedi_xontrib, jedi_mock, completion, rich_completion):
comp_type, comp_name, comp_complete, sig, inf = completion
comp_mock = MagicMock()
@ -181,9 +201,9 @@ def test_rich_completions(jedi_xontrib, jedi_mock, completion, rich_completion):
jedi_xontrib.XONSH_SPECIAL_TOKENS = []
jedi_mock.Interpreter().complete.return_value = [comp_mock]
completions = jedi_xontrib.complete_jedi('', '', 0, 0, {})
completions = jedi_xontrib.complete_jedi("", "", 0, 0, {})
assert len(completions) == 1
ret_completion, = completions
(ret_completion,) = completions
assert isinstance(ret_completion, RichCompletion)
assert ret_completion == rich_completion
assert ret_completion.display == rich_completion.display
@ -191,7 +211,9 @@ def test_rich_completions(jedi_xontrib, jedi_mock, completion, rich_completion):
def test_special_tokens(jedi_xontrib):
assert jedi_xontrib.complete_jedi('', '', 0, 0,
{}) == jedi_xontrib.XONSH_SPECIAL_TOKENS
assert jedi_xontrib.complete_jedi('@', '@', 0, 1, {}) == {'@', '@(', '@$('}
assert jedi_xontrib.complete_jedi('$', '$', 0, 1, {}) == {'$[', '${', '$('}
assert (
jedi_xontrib.complete_jedi("", "", 0, 0, {})
== jedi_xontrib.XONSH_SPECIAL_TOKENS
)
assert jedi_xontrib.complete_jedi("@", "@", 0, 1, {}) == {"@", "@(", "@$("}
assert jedi_xontrib.complete_jedi("$", "$", 0, 1, {}) == {"$[", "${", "$("}