Skip to content

Commit

Permalink
black updates to tests and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
scopatz committed Aug 26, 2020
1 parent 5e90165 commit f048b29
Show file tree
Hide file tree
Showing 17 changed files with 261 additions and 211 deletions.
2 changes: 1 addition & 1 deletion amalgamate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
15 changes: 8 additions & 7 deletions docs/cmdhelp.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
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
Expand All @@ -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
Expand All @@ -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):
Expand All @@ -53,7 +55,7 @@ def run(self):
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)
Expand All @@ -64,5 +66,4 @@ def run(self):


def setup(app):
app.add_directive('command-help', CommandHelp)

app.add_directive("command-help", CommandHelp)
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@

# 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
Expand Down
13 changes: 9 additions & 4 deletions tests/aliases/test_xexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
62 changes: 33 additions & 29 deletions tests/test_environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -382,51 +382,55 @@ 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


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):
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions tests/test_imphooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 1 addition & 1 deletion tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def test_f_env_var():
('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"),
Expand Down
45 changes: 28 additions & 17 deletions tests/test_ptk_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,23 @@
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

Expand All @@ -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]
8 changes: 3 additions & 5 deletions tests/test_ptk_highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion tests/test_ptk_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
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
Expand All @@ -28,24 +29,27 @@ 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))
s_legacy = set(dir(imports_legacy))
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


@pytest.fixture
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
Expand Down
1 change: 1 addition & 0 deletions tests/test_ptk_multiline.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from xonsh.built_ins import XonshSession

from tools import DummyEnv

Context = namedtuple("Context", ["indent", "buffer", "accept", "cli", "cr"])


Expand Down
Loading

0 comments on commit f048b29

Please sign in to comment.