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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ TestGen has two install modes: `docker` (Compose) and `pip` (uv-managed venv wit
The five `Testgen*Action` classes that span both modes follow a unified pattern:
- `_per_invocation_attrs` includes `_resolved_mode` (and `steps` / `intro_text` for the `MultiStepAction`-based ones) so menu re-runs start clean.
- `check_requirements` resolves mode once via `_resolve_install_mode`, then calls `super().check_requirements`.
- `_resolve_install_mode` reads the marker (or runs auto-detect for `install`), sets `self._resolved_mode`, optionally records `analytics["install_mode"]`. Install/upgrade/start/run-demo abort when no install exists; delete and delete-demo are idempotent (return rather than raise).
- `_resolve_install_mode` reads the marker (or runs auto-detect for `install`), sets `self._resolved_mode`, optionally records `analytics["install_mode"]`. Install/upgrade/start/run-demo abort when no install exists; delete and delete-demo are idempotent (return rather than raise). Delete treats a TestGen home (`~/.testgen`) without a marker as pip mode and removes it, since a failed or interrupted pip install leaves data behind but writes no marker.
- `get_requirements` reads `self._resolved_mode` — Docker reqs only when in Docker mode.
- `execute` branches on `self._resolved_mode`. For `MultiStepAction` subclasses, `self.steps` is also swapped at resolution time using class-level `pip_steps` / `docker_steps`.

Expand Down
52 changes: 38 additions & 14 deletions dk-installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ def msg(self, text, skip_logging=False):
self._last_is_space = False

def print_log(self, log_path: pathlib.Path) -> None:
with log_path.open() as log_file:
with log_path.open(encoding="utf-8", errors="replace") as log_file:
print("")
for line in log_file:
line = line.strip()
Expand Down Expand Up @@ -593,6 +593,7 @@ class AbortReason:
INSTALL_INCOMPLETE = "install_incomplete"
INTERRUPTED = "interrupted"
INVALID_ARGUMENTS = "invalid_arguments"
LEFTOVER_DATA = "leftover_data"
MISSING_REQUIREMENTS = "missing_requirements"
NO_INSTALL = "no_install"
POSTGRES_UNUSABLE = "postgres_unusable"
Expand Down Expand Up @@ -847,33 +848,38 @@ def configure_logging(self, debug=False):
}
)

def _get_failed_cmd_log_file_path(
def _get_failed_cmd_log_file_paths(
self, exception: Exception
) -> typing.Union[tuple[CommandFailed, pathlib.Path], tuple[None, None]]:
) -> typing.Union[tuple[CommandFailed, list[pathlib.Path]], tuple[None, list[pathlib.Path]]]:
"""Find the failed command in the exception chain and its stdout and stderr files, in that order."""
while exception:
if isinstance(exception, CommandFailed):
break
else:
exception = exception.__cause__

log_file_paths = []
if exception:
for stream in ("stderr", "stdout"):
for stream in ("stdout", "stderr"):
try:
(log_file_path,) = self.session_folder.glob(f"{exception.idx:04d}-{stream}-*.txt")
except ValueError:
continue
else:
return exception, log_file_path
log_file_paths.append(log_file_path)
if log_file_paths:
return exception, log_file_paths

return None, None
return None, []

def _msg_unexpected_error(self, exception: Exception) -> None:
cmd_exception, log_path = self._get_failed_cmd_log_file_path(exception)
if cmd_exception and log_path:
cmd_exception, log_paths = self._get_failed_cmd_log_file_paths(exception)
if cmd_exception and log_paths:
CONSOLE.msg(
f"Command '{cmd_exception.cmd}' failed with code {cmd_exception.ret_code}. See the output below."
)
CONSOLE.print_log(log_path)
for log_path in log_paths:
CONSOLE.print_log(log_path)
else:
root = exception
while root.__cause__ is not None:
Expand Down Expand Up @@ -3338,9 +3344,8 @@ class TestgenVerifyEmbeddedPostgresStep(Step):
pixeltable-pgserver build shipped without a library it links against, but the cause does
not matter here: if the binary will not run, the install cannot succeed.

Checking before ``standalone-setup`` also keeps a failure from wedging later attempts.
A partial setup leaves ``config.env`` behind, and every retry then stops on an
interactive "Overwrite?" prompt that the installer has no terminal to answer.
Checking before ``standalone-setup`` also keeps a failure from wedging later attempts:
a partial setup leaves ``config.env`` behind, and the next install stops until it is removed.
"""

label = "Verifying the embedded database"
Expand Down Expand Up @@ -3393,9 +3398,19 @@ def __init__(self):
self.started = False

def pre_execute(self, action, args):
# `standalone-setup` will not overwrite an existing config without a terminal to confirm it.
tg_home = get_testgen_home()
if (tg_home / "config.env").exists():
CONSOLE.msg(f"Found TestGen data from an earlier installation in {simplify_path(tg_home)}.")
CONSOLE.msg(
f"To delete it and install again, {command_hint(args.prod, 'delete', 'Uninstall TestGen')} first."
)
CONSOLE.space()
raise AbortAction(reason=AbortReason.LEFTOVER_DATA)
self.username = DEFAULT_USER_DATA["username"]
self.password = generate_password()
# A home that predates this install (e.g. kept by `tg delete --keep-data`) must survive a failed install.
# A home that predates this install (one without a config.env, which passed the check above)
# must survive a failed install.
self.home_existed = get_testgen_home().exists()
# Reach here only after `_resolve_install_mode` confirmed no existing
# install marker — so any running testgen/postgres processes are
Expand Down Expand Up @@ -3867,7 +3882,7 @@ class TestgenDeleteAction(Action, ComposeActionMixin):
"""

args_cmd = "delete"
_per_invocation_attrs = (*Action._per_invocation_attrs, "_resolved_mode")
_per_invocation_attrs = (*Action._per_invocation_attrs, "_resolved_mode", "_found_without_marker")

def get_parser(self, sub_parsers):
parser = super().get_parser(sub_parsers)
Expand Down Expand Up @@ -3902,6 +3917,11 @@ def _resolve_install_mode(self, args):
# Unlike install/upgrade, "no install found" is not an abort here —
# ``tg delete`` is idempotent. execute() handles the None case.
mode = InstallMarker(self.data_folder, args.prod, args.compose_file_name).read()
self._found_without_marker = mode is None and get_testgen_home().exists()
if self._found_without_marker:
# A failed or interrupted pip install writes no marker but can leave its data behind.
LOG.info("No install marker; found pip-mode data in %s", get_testgen_home())
mode = INSTALL_MODE_PIP
self._resolved_mode = mode
if mode is not None:
self.analytics.additional_properties["install_mode"] = mode
Expand Down Expand Up @@ -3932,6 +3952,10 @@ def _delete_docker(self, args):

def _delete_pip(self, args):
CONSOLE.title("Delete TestGen instance")
if getattr(self, "_found_without_marker", False):
CONSOLE.msg(f"No TestGen installation found in {self.data_folder}.")
CONSOLE.msg(f"Removing the leftover TestGen data in {simplify_path(get_testgen_home())}.")
CONSOLE.space()

# Stop any running testgen + embedded postgres before touching the
# installation. On Windows, a live testgen.exe locks its own binary
Expand Down
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ def _no_real_orphan_sweep():
yield mock


@pytest.fixture(autouse=True)
def _isolated_testgen_home(tmp_path, monkeypatch):
"""Point pip-mode TestGen's home at a folder that does not exist yet. Install and delete both look
for leftover data there, so the developer's own ``~/.testgen`` would change what they do, and delete
would remove it.
"""
monkeypatch.setenv("TG_TESTGEN_HOME", str(tmp_path / "isolated-testgen-home"))


@pytest.fixture
def stdout_mock():
return Mock(return_value=[])
Expand Down
25 changes: 13 additions & 12 deletions tests/test_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,29 @@ def test_exec_with_log_raises(exec_exc, expected_exc, print_msg, action, args_mo

@pytest.mark.unit
@pytest.mark.parametrize(
"exc_levels, glob_side_effect, expected_calls, expected_return",
"exc_levels, glob_side_effect, expected_return",
(
(0, ([], [Path("stdout.txt")]), ("stderr", "stdout"), (ANY, Path("stdout.txt"))),
(0, ([Path("stdout.txt")], []), (ANY, [Path("stdout.txt")])),
(
1,
([Path("stderr.txt"), Path("stderr_2.txt")], [Path("stdout.txt")]),
("stderr", "stdout"),
(ANY, Path("stdout.txt")),
([Path("stdout.txt")], [Path("stderr.txt"), Path("stderr_2.txt")]),
(ANY, [Path("stdout.txt")]),
),
(5, ([Path("stderr.txt")], [Path("stdout.txt")]), ("stderr",), (ANY, Path("stderr.txt"))),
(3, ([], [Path("stdout.txt"), Path("stdout.txt")]), ("stderr", "stdout"), (None, None)),
(1, ([], []), ("stderr", "stdout"), (None, None)),
(5, ([Path("stdout.txt")], [Path("stderr.txt")]), (ANY, [Path("stdout.txt"), Path("stderr.txt")])),
(2, ([], [Path("stderr.txt")]), (ANY, [Path("stderr.txt")])),
(3, ([Path("stdout.txt"), Path("stdout.txt")], []), (None, [])),
(1, ([], []), (None, [])),
),
ids=(
"direct exception, stdout only",
"one layer deep, two stderr files",
"five layers deep, stderr is picked",
"five layers deep, both streams in order",
"two layers deep, stderr only",
"three layers deep, two stdout",
"one layers deep, no files",
),
)
def test_get_failed_cmd_log(action, exc_levels, glob_side_effect, expected_calls, expected_return):
def test_get_failed_cmd_log(action, exc_levels, glob_side_effect, expected_return):
cmd_failed_exc = CommandFailed(42, "cmd 42", 2)
exc = cmd_failed_exc
for n in range(exc_levels):
Expand All @@ -67,11 +68,11 @@ def test_get_failed_cmd_log(action, exc_levels, glob_side_effect, expected_calls

action.session_folder.glob.side_effect = glob_side_effect

ret = action._get_failed_cmd_log_file_path(exc)
ret = action._get_failed_cmd_log_file_paths(exc)

assert ret == expected_return
assert ret[0] in (None, cmd_failed_exc)
action.session_folder.glob.assert_has_calls([call(f"0042-{stream}-*.txt") for stream in expected_calls])
action.session_folder.glob.assert_has_calls([call(f"0042-{stream}-*.txt") for stream in ("stdout", "stderr")])


@pytest.mark.unit
Expand Down
31 changes: 31 additions & 0 deletions tests/test_tg_pip_delete.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import platform
from functools import partial
from pathlib import Path
Expand Down Expand Up @@ -176,6 +177,36 @@ def test_delete_routes_to_pip_and_removes_marker(delete_action, args_mock, tmp_d
assert delete_action.analytics.additional_properties["install_mode"] == INSTALL_MODE_PIP


@pytest.mark.integration
def test_delete_without_a_marker_removes_leftover_pip_data(delete_action, args_mock, tmp_data_folder):
"""A failed or interrupted pip install writes no marker but can leave its data behind."""
tg_home = Path(os.environ["TG_TESTGEN_HOME"])
tg_home.mkdir()
(tg_home / "config.env").write_text("TG_STANDALONE_MODE=yes\n")

delete_action._resolve_install_mode(args_mock)
with patch.object(delete_action, "_delete_pip") as pip_branch:
delete_action.execute(args_mock)

pip_branch.assert_called_once_with(args_mock)
assert delete_action.analytics.additional_properties["install_mode"] == INSTALL_MODE_PIP


@pytest.mark.integration
def test_delete_without_a_marker_says_what_it_removes(pip_delete_action, args_mock, console_msg_mock):
InstallMarker(pip_delete_action.data_folder, "tg").unlink()
tg_home = Path(os.environ["TG_TESTGEN_HOME"])
tg_home.mkdir()
pip_delete_action._resolve_install_mode(args_mock)

with patch("tests.installer.shutil.which", return_value=None):
pip_delete_action.execute()

console_msg_mock.assert_any_msg_contains("No TestGen installation found in")
console_msg_mock.assert_any_msg_contains("Removing the leftover TestGen data in")
assert not tg_home.exists()


@pytest.mark.integration
def test_delete_routes_to_docker_legacy(delete_action, args_mock, tmp_data_folder):
# No marker but legacy Docker files present — read_install_mode falls back
Expand Down
31 changes: 31 additions & 0 deletions tests/test_tg_pip_install.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import os
from functools import partial
from pathlib import Path
from unittest.mock import MagicMock, call, patch
Expand All @@ -7,6 +8,7 @@

from tests.installer import (
AbortAction,
AbortReason,
InstallerError,
TestgenStandaloneSetupStep,
UvToolInstallStep,
Expand All @@ -15,6 +17,7 @@
TESTGEN_MAJOR_VERSION,
TESTGEN_PYTHON_VERSION,
TestgenInstallAction,
command_hint,
InstallMarker,
)

Expand Down Expand Up @@ -421,3 +424,31 @@ def test_failed_pip_install_removes_only_a_new_testgen_home(cleanup_action, args
step.on_action_fail(cleanup_action, args_mock)

assert tg_home.exists() is home_existed


@pytest.mark.integration
def test_pip_install_stops_before_installing_over_leftover_data(pip_install_action, start_cmd_mock, console_msg_mock):
"""`standalone-setup` cannot confirm overwriting an existing config without a terminal, so the install stops
before it starts."""
tg_home = Path(os.environ["TG_TESTGEN_HOME"])
tg_home.mkdir()
(tg_home / "config.env").write_text("TG_STANDALONE_MODE=yes\n")

with pytest.raises(AbortAction) as raised:
pip_install_action.execute()

assert raised.value.__cause__.reason == AbortReason.LEFTOVER_DATA
console_msg_mock.assert_any_msg_contains("Found TestGen data from an earlier installation")
console_msg_mock.assert_any_msg_contains(command_hint("tg", "delete", "Uninstall TestGen"))
start_cmd_mock.assert_not_called()
assert (tg_home / "config.env").exists()


@pytest.mark.integration
def test_pip_install_proceeds_over_a_home_without_config(pip_install_action, start_cmd_mock):
tg_home = Path(os.environ["TG_TESTGEN_HOME"])
(tg_home / "logs").mkdir(parents=True)

pip_install_action.execute()

assert any("standalone-setup" in c.args for c in start_cmd_mock.call_args_list)
Loading