Skip to content
Merged
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
70 changes: 69 additions & 1 deletion tests/test_lifecycle.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Test lifecycle functions."""

import click

from workflow.definitions.work import Work
from workflow.examples.function import math
from workflow.lifecycle import execute
from workflow.lifecycle import configure, execute


def test_execute_function():
Expand Down Expand Up @@ -82,3 +84,69 @@ def test_function_work_object():
assert work.results == results
assert work.products == products
assert work.plots == plots


def test_arguments_pass_false_and_zero_values():
"""False, 0 and "" are passed; only missing parameters use the defaults."""

@click.command()
@click.option("--trace/--no-trace", default=True)
@click.option("--verbose", is_flag=True, default=False)
@click.option("--retries", type=int, default=3)
@click.option("--label", default="x")
def cli(trace, verbose, retries, label):
return {"trace": trace, "verbose": verbose, "retries": retries, "label": label}

def args(parameters):
work = Work(pipeline="workflow-tests", site="local", user="tester")
work.parameters = parameters
return configure.arguments(cli, work)

assert args({"trace": False}) == ["--no-trace"]
assert args({"trace": True}) == ["--trace"]
assert args({"verbose": False}) == []
assert args({"verbose": True}) == ["--verbose"]
assert args({"retries": 0, "label": ""}) == ["--retries=0", "--label="]
assert args({"trace": None, "retries": None}) == []

work = Work(pipeline="workflow-tests", site="local", user="tester")
work.parameters = {"trace": False, "retries": 0}
# click parses them back to the values given
outcome = cli.main(args=configure.arguments(cli, work), standalone_mode=False)
assert outcome == {"trace": False, "verbose": False, "retries": 0, "label": "x"}


def _command_work(script, timeout=30):
work = Work(pipeline="workflow-tests", site="local", user="tester", timeout=timeout)
work.command = ["bash", "-c", script]
return work


def test_execute_command_keeps_output():
work = execute.command(_command_work("echo out; echo err >&2"))
assert work.status == "success"
assert work.results["stdout"] == ["out"]
assert work.results["stderr"] == ["err"]
assert work.results["returncode"] == 0


def test_execute_command_keeps_output_when_it_fails():
work = execute.command(_command_work("echo out; echo boom >&2; exit 3"))
assert work.status == "failure"
assert work.results["stdout"] == ["out"]
assert work.results["stderr"] == ["boom"]
assert work.results["returncode"] == 3


def test_execute_command_keeps_output_when_it_times_out():
work = execute.command(_command_work("echo started; sleep 10", timeout=1))
assert work.status == "failure"
assert work.results["stdout"] == ["started"]
assert work.results["returncode"] is None


def test_execute_command_keeps_the_end_of_its_output():
script = "seq 1 3000; seq 1 3000 >&2"
work = execute.command(_command_work(script))
assert work.results["stdout"] == [str(i) for i in range(1977, 3001)]
assert work.results["stderr"] == [str(i) for i in range(1977, 3001)]
24 changes: 24 additions & 0 deletions tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,27 @@ def test_complete_work_run():
assert response["parameters"] == {"alpha": 7, "beta": 11}
assert response["results"] == results
ctx.buckets.delete_many(pipeline="complete", force=True)


def test_run_without_a_terminal_writes_no_spinner(monkeypatch):
"""Without a terminal (e.g. a container's logs) no spinner frames are written."""
import time
from types import SimpleNamespace

import workflow.cli.run as cli

# nothing reaches the workspace file or the backends
monkeypatch.setattr(cli.configure, "workspace", lambda workspace: None)
monkeypatch.setattr(cli.read, "workspace", lambda path: {"sites": ["local"]})
monkeypatch.setattr(cli.configure, "loki", lambda logger, config: False)
buckets = SimpleNamespace(info=lambda: {"version": "test"})
monkeypatch.setattr(
cli, "HTTPContext", lambda backends: SimpleNamespace(buckets=buckets)
)
monkeypatch.setattr(cli, "lifecycle", lambda **kwargs: time.sleep(1.5))

result = CliRunner().invoke(run, ["--site=local", "--lives=1", "complete"])

assert result.exit_code == 0
assert "Lifecycle" in result.output
assert not any(0x2800 <= ord(char) <= 0x28FF for char in result.output)
21 changes: 14 additions & 7 deletions workflow/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import platform
import signal
from contextlib import nullcontext
from pathlib import Path
from sys import stderr, stdout
from threading import Event
Expand Down Expand Up @@ -228,13 +229,19 @@ def run(
"[bold]Starting Workflow Lifecycle[/bold]",
extra=dict(markup=True, color="green"),
)
console = Console(force_terminal=True, tab_size=4)
with console.status(
status="",
spinner="aesthetic" if tty else "dots",
spinner_style="bold green",
refresh_per_second=10 if tty else 1,
):
# Without a terminal (e.g. a container's logs) every spinner frame would be
# written to the logs, so it's only shown in a terminal
spinner = (
Console(force_terminal=True, tab_size=4).status(
status="",
spinner="aesthetic",
spinner_style="bold green",
refresh_per_second=10,
)
if tty
else nullcontext()
)
with spinner:
lifecycle(
buckets=buckets,
function=function,
Expand Down
11 changes: 9 additions & 2 deletions workflow/lifecycle/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ def arguments(func: Callable[..., Any], work: Work) -> List[str]:
paraneter_name_in_function, None
)

if parameter_value_in_work:
# Only missing parameters are left to their defaults: False, 0 and ""
# are values too
if parameter_value_in_work is not None:
if isinstance(parameter, click.Argument):
# If argument, then the parameter is purely positional without a key
if isinstance(parameter_value_in_work, list):
Expand All @@ -131,7 +133,12 @@ def arguments(func: Callable[..., Any], work: Work) -> List[str]:
if hasattr(parameter, "is_flag") and parameter.is_flag:
# If is_flag=True,
# then the parameter is a flag and doesn't have a value
args.append(f"{parameter_name_in_cli}")
if parameter_value_in_work:
args.append(f"{parameter_name_in_cli}")
elif parameter.secondary_opts:
# An on/off flag (e.g. --trace/--no-trace) set to False
args.append(f"{parameter.secondary_opts[-1]}")
# A plain flag set to False is left off
else:
space_or_equals = ""

Expand Down
68 changes: 55 additions & 13 deletions workflow/lifecycle/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@

logger = get_logger("workflow.lifecycle.execute")

# The lines of a command's stdout and stderr kept in its results (the last ones),
# so a verbose command doesn't fill the database
OUTPUT_LINES = 1024

Outcome = Union[Dict[str, Any], Tuple[Dict[str, Any], List[str], List[str]], Any, None]


Expand Down Expand Up @@ -75,6 +79,46 @@ def function(work: Work) -> Work:
return work


def last_lines(stream: Optional[bytes]) -> List[str]:
"""The last OUTPUT_LINES lines of a command's output.

Args:
stream (Optional[bytes]): Its stdout or stderr

Returns:
List[str]: Its last lines
"""
return (
(stream or b"").decode("utf-8", errors="replace").splitlines()[-OUTPUT_LINES:]
)


def output(
work: Work,
args: Any,
stdout: Optional[bytes],
stderr: Optional[bytes],
returncode: Optional[int],
) -> None:
"""Keep a command's output in the work's results, unless it has results.

Args:
work (Work): Work object
args (Any): The command run
stdout (Optional[bytes]): Its standard output
stderr (Optional[bytes]): Its standard error
returncode (Optional[int]): Its exit code, None if it was stopped
"""
if work.results or work.products or work.plots:
return
work.results = {
"args": args,
"stdout": last_lines(stdout),
"stderr": last_lines(stderr),
"returncode": returncode,
}


def command(work: Work) -> Work:
"""Execute a command.

Expand Down Expand Up @@ -103,22 +147,20 @@ def command(work: Work) -> Work:
timeout=work.timeout,
shell=is_shell, # nosec
)
# Check return code
process.check_returncode()
# Convert stdout and stderr to strings
stdout = process.stdout.decode("utf-8").splitlines()
stderr = process.stderr.decode("utf-8").splitlines()
# Convert last line of stdout to a Tuple
if not (work.results or work.products or work.plots):
work.results = {
"args": process.args,
"stdout": stdout,
"stderr": stderr,
"returncode": process.returncode,
}
# Keep the output before checking the return code: a failed command's
# output is the most useful
output(work, process.args, process.stdout, process.stderr, process.returncode)
# * Check if results are less than 4MB
validate.size(work)
# Check return code
process.check_returncode()
work.status = "success"
except subprocess.TimeoutExpired as error:
# Keep what it printed before it was stopped
output(work, error.cmd, error.stdout, error.stderr, None)
validate.size(work)
work.status = "failure"
logger.exception(error)
except Exception as error:
work.status = "failure"
logger.exception(error)
Expand Down
Loading