Skip to content

Log Output of Failed Process #974

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions nox/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __new__( # noqa: PYI034
) -> FunctionDecorator:
self = super().__new__(cls)
functools.update_wrapper(self, func)
return cast(FunctionDecorator, self)
return cast("FunctionDecorator", self)


def _copy_func(src: T, name: str | None = None) -> T:
Expand All @@ -59,7 +59,7 @@ def _copy_func(src: T, name: str | None = None) -> T:
dst.__dict__.update(copy.deepcopy(src.__dict__))
dst = functools.update_wrapper(dst, src) # type: ignore[assignment]
dst.__kwdefaults__ = src.__kwdefaults__
return cast(T, dst)
return cast("T", dst)


class Func(FunctionDecorator):
Expand Down
6 changes: 3 additions & 3 deletions nox/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,13 @@ def run(
)

if return_code not in success_codes:
suffix = ":" if silent else ""
suffix = ":" if (silent and output) else ""
logger.error(
f"Command {full_cmd} failed with exit code {return_code}{suffix}"
)

if silent:
sys.stderr.write(output)
if silent and output:
logger.error(output)

msg = f"Returned code {return_code}"
raise CommandFailed(msg)
Expand Down
2 changes: 1 addition & 1 deletion nox/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def output(self, msg: str, *args: Any, **kwargs: Any) -> None:


logging.setLoggerClass(LoggerWithSuccessAndOutput)
logger = cast(LoggerWithSuccessAndOutput, logging.getLogger("nox"))
logger = cast("LoggerWithSuccessAndOutput", logging.getLogger("nox"))


def _get_formatter(*, color: bool, add_timestamp: bool) -> logging.Formatter:
Expand Down
2 changes: 1 addition & 1 deletion nox/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def add_dependencies(self) -> None:
}

# Resolve the dependency graph.
root = cast(SessionRunner, object()) # sentinel
root = cast("SessionRunner", object()) # sentinel
try:
resolved_graph = list(
lazy_stable_topo_sort({**dependency_graph, root: self._queue}, root)
Expand Down
5 changes: 5 additions & 0 deletions nox/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,11 @@ def env(self) -> dict[str, str | None]:
"""A dictionary of environment variables to pass into all commands."""
return self.virtualenv.env

@property
def envdir(self) -> pathlib.Path:
"""The path to the environment of this session."""
return pathlib.Path(self._runner.envdir)

@property
def posargs(self) -> list[str]:
"""Any extra arguments from the ``nox`` commandline or :class:`Session.notify`."""
Expand Down
2 changes: 1 addition & 1 deletion nox/virtualenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def __init__(
self._reused = False

# .command's env supports None, meaning don't include value even if in parent
self.env = {**{k: None for k in _BLACKLISTED_ENV_VARS}, **(env or {})}
self.env = {**dict.fromkeys(_BLACKLISTED_ENV_VARS), **(env or {})}

@property
def bin_paths(self) -> list[str] | None:
Expand Down
27 changes: 12 additions & 15 deletions tests/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,13 @@ def test_run_verbosity(
assert logs[0].message.strip() == "123"


def test_run_verbosity_failed_command(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
def test_run_verbosity_failed_command(caplog: pytest.LogCaptureFixture) -> None:
caplog.clear()
with caplog.at_level(logging.DEBUG):
with pytest.raises(nox.command.CommandFailed):
nox.command.run([PYTHON, "-c", "print(123); exit(1)"], silent=True)

out, err = capsys.readouterr()

assert "123" in err
assert out == ""
assert "123" in caplog.text

logs = [rec for rec in caplog.records if rec.levelname == "OUTPUT"]
assert not logs
Expand All @@ -117,10 +112,7 @@ def test_run_verbosity_failed_command(
with pytest.raises(nox.command.CommandFailed):
nox.command.run([PYTHON, "-c", "print(123); exit(1)"], silent=True)

out, err = capsys.readouterr()

assert "123" in err
assert out == ""
assert "123" in caplog.text

# Nothing is logged but the error is still written to stderr
assert not logs
Expand Down Expand Up @@ -251,7 +243,10 @@ def test_exit_codes() -> None:
)


def test_fail_with_silent(capsys: pytest.CaptureFixture[str]) -> None:
def test_fail_with_silent(
caplog: pytest.LogCaptureFixture, capsys: pytest.CaptureFixture[str]
) -> None:
caplog.clear()
with pytest.raises(nox.command.CommandFailed):
nox.command.run(
[
Expand All @@ -264,9 +259,11 @@ def test_fail_with_silent(capsys: pytest.CaptureFixture[str]) -> None:
],
silent=True,
)
_out, err = capsys.readouterr()
assert "out" in err
assert "err" in err
out, err = capsys.readouterr()
assert "out" not in err
assert "err" not in err
assert "out" in caplog.text
assert "err" in caplog.text


@pytest.fixture
Expand Down
8 changes: 4 additions & 4 deletions tests/test_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,15 +395,15 @@ def test_notify() -> None:
def my_session_raw(session: nox.Session) -> None:
pass

my_session = typing.cast(Func, my_session_raw)
my_session = typing.cast("Func", my_session_raw)

my_session.python = None
my_session.venv_backend = None

def notified_raw(session: nox.Session) -> None:
pass

notified = typing.cast(Func, notified_raw)
notified = typing.cast("Func", notified_raw)

notified.python = None
notified.venv_backend = None
Expand Down Expand Up @@ -431,7 +431,7 @@ def test_notify_noop() -> None:
def my_session_raw(session: nox.Session) -> None:
pass

my_session = typing.cast(Func, my_session_raw)
my_session = typing.cast("Func", my_session_raw)

my_session.python = None
my_session.venv_backend = None
Expand Down Expand Up @@ -500,7 +500,7 @@ def test_no_venv_backend_but_some_pythons() -> None:
def my_session_raw(session: nox.Session) -> None:
pass

my_session = typing.cast(Func, my_session_raw)
my_session = typing.cast("Func", my_session_raw)

# the session sets "no venv backend" but declares some pythons
my_session.python = ["3.7", "3.8"]
Expand Down
20 changes: 11 additions & 9 deletions tests/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1423,38 +1423,40 @@ def test_init(self) -> None:
def test__bool_true(self) -> None:
for status in (nox.sessions.Status.SUCCESS, nox.sessions.Status.SKIPPED):
result = nox.sessions.Result(
session=typing.cast(nox.sessions.SessionRunner, object()), status=status
session=typing.cast("nox.sessions.SessionRunner", object()),
status=status,
)
assert bool(result)

def test__bool_false(self) -> None:
for status in (nox.sessions.Status.FAILED, nox.sessions.Status.ABORTED):
result = nox.sessions.Result(
session=typing.cast(nox.sessions.SessionRunner, object()), status=status
session=typing.cast("nox.sessions.SessionRunner", object()),
status=status,
)
assert not bool(result)

def test__imperfect(self) -> None:
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.SUCCESS,
)
assert result.imperfect == "was successful"
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.FAILED,
)
assert result.imperfect == "failed"
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.FAILED,
reason="meep",
)
assert result.imperfect == "failed: meep"

def test__log_success(self) -> None:
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.SUCCESS,
)
with mock.patch.object(logger, "success") as success:
Expand All @@ -1463,7 +1465,7 @@ def test__log_success(self) -> None:

def test__log_warning(self) -> None:
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.SKIPPED,
)
with mock.patch.object(logger, "warning") as warning:
Expand All @@ -1472,7 +1474,7 @@ def test__log_warning(self) -> None:

def test__log_error(self) -> None:
result = nox.sessions.Result(
typing.cast(nox.sessions.SessionRunner, object()),
typing.cast("nox.sessions.SessionRunner", object()),
nox.sessions.Status.FAILED,
)
with mock.patch.object(logger, "error") as error:
Expand All @@ -1482,7 +1484,7 @@ def test__log_error(self) -> None:
def test__serialize(self) -> None:
result = nox.sessions.Result(
session=typing.cast(
nox.sessions.SessionRunner,
"nox.sessions.SessionRunner",
argparse.Namespace(
signatures=["siggy"], name="namey", func=mock.Mock()
),
Expand Down
34 changes: 17 additions & 17 deletions tests/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import platform
import typing
from textwrap import dedent
from types import ModuleType
from unittest import mock

import pytest
Expand All @@ -35,6 +34,7 @@
if typing.TYPE_CHECKING:
from collections.abc import Callable, Generator
from pathlib import Path
from types import ModuleType

RESOURCES = os.path.join(os.path.dirname(__file__), "resources")

Expand All @@ -43,7 +43,7 @@ def session_func_raw() -> None:
pass


session_func = typing.cast(nox._decorators.Func, session_func_raw)
session_func = typing.cast("nox._decorators.Func", session_func_raw)


session_func.python = None
Expand All @@ -59,7 +59,7 @@ def session_func_with_python_raw() -> None:


session_func_with_python = typing.cast(
nox._decorators.Func, session_func_with_python_raw
"nox._decorators.Func", session_func_with_python_raw
)


Expand All @@ -74,7 +74,7 @@ def session_func_venv_pythons_warning_raw() -> None:


session_func_venv_pythons_warning = typing.cast(
nox._decorators.Func, session_func_venv_pythons_warning_raw
"nox._decorators.Func", session_func_venv_pythons_warning_raw
)


Expand Down Expand Up @@ -188,7 +188,7 @@ def notasession() -> None:

# Mock up a noxfile.py module and configuration.
mock_module = typing.cast(
ModuleType,
"ModuleType",
argparse.Namespace(
__name__=foo.__module__, foo=foo, bar=bar, notasession=notasession
),
Expand Down Expand Up @@ -428,7 +428,7 @@ def corge() -> None:

def test_honor_list_request_noop() -> None:
config = _options.options.namespace(list_sessions=False)
manifest = typing.cast(Manifest, {"thing": mock.sentinel.THING})
manifest = typing.cast("Manifest", {"thing": mock.sentinel.THING})
return_value = tasks.honor_list_request(manifest, global_config=config)
assert return_value is manifest

Expand Down Expand Up @@ -622,8 +622,8 @@ def test_run_manifest(with_warnings: builtins.bool) -> None:
# Set up a valid manifest.
config = _options.options.namespace(stop_on_first_error=False)
sessions_ = [
typing.cast(sessions.SessionRunner, mock.Mock(spec=sessions.SessionRunner)),
typing.cast(sessions.SessionRunner, mock.Mock(spec=sessions.SessionRunner)),
typing.cast("sessions.SessionRunner", mock.Mock(spec=sessions.SessionRunner)),
typing.cast("sessions.SessionRunner", mock.Mock(spec=sessions.SessionRunner)),
]
manifest = Manifest({}, config)
manifest._queue = copy.copy(sessions_)
Expand Down Expand Up @@ -656,8 +656,8 @@ def test_run_manifest_abort_on_first_failure() -> None:
# Set up a valid manifest.
config = _options.options.namespace(stop_on_first_error=True)
sessions_ = [
typing.cast(sessions.SessionRunner, mock.Mock(spec=sessions.SessionRunner)),
typing.cast(sessions.SessionRunner, mock.Mock(spec=sessions.SessionRunner)),
typing.cast("sessions.SessionRunner", mock.Mock(spec=sessions.SessionRunner)),
typing.cast("sessions.SessionRunner", mock.Mock(spec=sessions.SessionRunner)),
]
manifest = Manifest({}, config)
manifest._queue = copy.copy(sessions_)
Expand Down Expand Up @@ -699,28 +699,28 @@ def test_print_summary() -> None:
results = [
sessions.Result(
session=typing.cast(
sessions.SessionRunner,
"sessions.SessionRunner",
argparse.Namespace(friendly_name="foo"),
),
status=sessions.Status.SUCCESS,
),
sessions.Result(
session=typing.cast(
sessions.SessionRunner,
"sessions.SessionRunner",
argparse.Namespace(friendly_name="bar"),
),
status=sessions.Status.FAILED,
),
sessions.Result(
session=typing.cast(
sessions.SessionRunner,
"sessions.SessionRunner",
argparse.Namespace(friendly_name="baz"),
),
status=sessions.Status.SKIPPED,
),
sessions.Result(
session=typing.cast(
sessions.SessionRunner,
"sessions.SessionRunner",
argparse.Namespace(friendly_name="qux"),
),
status=sessions.Status.SKIPPED,
Expand Down Expand Up @@ -753,7 +753,7 @@ def test_create_report() -> None:
results = [
sessions.Result(
session=typing.cast(
sessions.SessionRunner,
"sessions.SessionRunner",
argparse.Namespace(signatures=["foosig"], name="foo", func=object()),
),
status=sessions.Status.SUCCESS,
Expand Down Expand Up @@ -784,8 +784,8 @@ def test_create_report() -> None:

def test_final_reduce() -> None:
config = argparse.Namespace()
true = typing.cast(sessions.Result, True) # noqa: FBT003
false = typing.cast(sessions.Result, False) # noqa: FBT003
true = typing.cast("sessions.Result", True) # noqa: FBT003
false = typing.cast("sessions.Result", False) # noqa: FBT003
assert tasks.final_reduce([true, true], config) == 0
assert tasks.final_reduce([true, false], config) == 1
assert tasks.final_reduce([], config) == 0