diff --git a/tests/test_kill.py b/tests/test_kill.py new file mode 100644 index 0000000..6ed999e --- /dev/null +++ b/tests/test_kill.py @@ -0,0 +1,70 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import errno +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from click.testing import CliRunner + +from kerf.kill import main as kill_main + + +@pytest.fixture +def spawn(monkeypatch): + monkeypatch.setattr(kill_main, "resolve_instance", lambda name, instance_id: ("guest", 3)) + api = Mock(spec=kill_main.instance) + fd = 7 + api.open_instance.return_value = fd + close = Mock() + monkeypatch.setattr(kill_main, "instance", api) + monkeypatch.setattr(kill_main, "os", SimpleNamespace(close=close)) + yield api, fd + close.assert_called_once_with(fd) + + +def test_force_can_retry_after_the_instance_is_marked_stopped(spawn): + api, fd = spawn + api.info.return_value = SimpleNamespace(running=False, loaded=True) + + result = CliRunner().invoke(kill_main.kill_cmd, ["guest", "--force"]) + + assert result.exit_code == 0, result.output + api.open_instance.assert_called_once_with(3) + api.halt.assert_called_once_with(fd, force=True, timeout_ms=kill_main.HALT_TIMEOUT_MS) + + +@pytest.mark.parametrize("loaded, flags", [(True, []), (False, ["--force"])]) +def test_kill_rejects_a_stopped_instance_without_a_force_retry(loaded, flags, spawn): + api, _ = spawn + api.info.return_value = SimpleNamespace(running=False, loaded=loaded) + + result = CliRunner().invoke(kill_main.kill_cmd, ["guest", *flags]) + + assert result.exit_code == 1, result.output + assert "is not running" in result.output + api.halt.assert_not_called() + + +def test_graceful_shutdown_timeout_reports_the_force_option(spawn): + api, fd = spawn + api.info.return_value = SimpleNamespace(running=True, loaded=True) + api.halt.side_effect = OSError(errno.ETIMEDOUT, "timed out") + + result = CliRunner().invoke(kill_main.kill_cmd, ["guest"]) + + assert result.exit_code == 1, result.output + assert "stop it with --force" in result.output + api.halt.assert_called_once_with(fd, force=False, timeout_ms=kill_main.HALT_TIMEOUT_MS)