From d3ea7498cc5294b87d8ebc4829b6897e67fe9820 Mon Sep 17 00:00:00 2001 From: bubaizhanshen Date: Mon, 1 Jun 2026 12:56:40 +0800 Subject: [PATCH] Handle missing virtualenv in shell command --- src/poetry_plugin_shell/command.py | 14 +++++++++++--- tests/test_shell_command.py | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/poetry_plugin_shell/command.py b/src/poetry_plugin_shell/command.py index 234ac85..8435bfa 100644 --- a/src/poetry_plugin_shell/command.py +++ b/src/poetry_plugin_shell/command.py @@ -36,11 +36,19 @@ def handle(self) -> int: return 0 - self.line(f"Spawning shell within {self.env.path}") - # Be sure that we have the right type of environment. env = self.env - assert env.is_venv() + if not env.is_venv(): + self.line_error( + "Poetry could not find a virtual environment to activate.\n" + "If virtualenvs.create is set to false, " + "enable virtual environment creation or create/select a virtual " + "environment before running poetry shell." + ) + return 1 + + self.line(f"Spawning shell within {self.env.path}") + env = cast("VirtualEnv", env) # Setting this to avoid spawning unnecessary nested shells diff --git a/tests/test_shell_command.py b/tests/test_shell_command.py index 8b05732..4ab1cda 100644 --- a/tests/test_shell_command.py +++ b/tests/test_shell_command.py @@ -7,6 +7,8 @@ import pytest +from poetry.utils.env import MockEnv + from poetry_plugin_shell.command import ShellCommand @@ -50,6 +52,25 @@ def test_shell_already_active(tester: CommandTester, mocker: MockerFixture) -> N assert tester.status_code == 0 +def test_shell_without_virtualenv_shows_error( + command_tester_factory: CommandTesterFactory, + mocker: MockerFixture, + tmp_path: Path, +) -> None: + env = MockEnv(path=tmp_path / "system", is_venv=False) + tester = command_tester_factory("shell", environment=env) + shell_activate = mocker.patch("poetry_plugin_shell.shell.Shell.activate") + + tester.execute() + + error = tester.io.fetch_error() + shell_activate.assert_not_called() + assert "Spawning shell" not in tester.io.fetch_output() + assert "could not find a virtual environment" in error + assert "virtualenvs.create" in error + assert tester.status_code == 1 + + @pytest.mark.parametrize( ("poetry_active", "real_prefix", "prefix", "expected"), [