diff --git a/docs/preview-notes.md b/docs/preview-notes.md index b271426..ce0dd0e 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,4 +1,10 @@ -# Modsim 2.0.0a9 preview +# Modsim 2.0.0a10 preview + +Modsim 2.0.0a10 keeps modpoll-wot 0.5.0a1. `modsim login` prints the sign-in link and opens a browser only +where one can be opened; the opener's output no longer fills the terminal, and Ctrl-C cancels with one line. +The login is shared with modpoll 2.0.0a8. + +## Modsim 2.0.0a9 preview Modsim 2.0.0a9 pins modpoll-wot 0.5.0a1 and connects to ModioHub: diff --git a/modsim/__init__.py b/modsim/__init__.py index ac6d3cf..84ff459 100644 --- a/modsim/__init__.py +++ b/modsim/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0a9" +__version__ = "2.0.0a10" diff --git a/modsim/login.py b/modsim/login.py index 2006751..59ab738 100644 --- a/modsim/login.py +++ b/modsim/login.py @@ -4,10 +4,13 @@ back is kept in the credentials file shared with modpoll (see modpoll_wot.session). ``modsim logout`` removes it. """ +import os +import shutil +import subprocess import sys import time import webbrowser -from typing import Any, Callable, TextIO +from typing import Any, Callable, Mapping, TextIO import modpoll_wot # type: ignore[import-untyped] @@ -21,6 +24,44 @@ class LoginError(ValueError): """The login did not complete; the message says why and what to do.""" +def open_in_browser( + url: str, + *, + environ: Mapping[str, str] | None = None, + platform: str | None = None, + run: Callable[..., Any] = subprocess.run, + which: Callable[[str], str | None] = shutil.which, +) -> bool: + """Try to open an address in a browser; False means the user has to open it from the printed link. + + Where there is no desktop (SSH, a minimal WSL) nothing is tried, and the opener's own complaints + never reach the terminal. + """ + environ = os.environ if environ is None else environ + platform = platform or sys.platform + if environ.get("BROWSER") or platform in ("darwin", "win32"): + return webbrowser.open(url) + if not (environ.get("DISPLAY") or environ.get("WAYLAND_DISPLAY")) or environ.get( + "SSH_CONNECTION" + ): + return False + opener = which("xdg-open") + if not opener: + return False + try: + return bool( + run( + [opener, url], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + ).returncode + == 0 + ) + except (OSError, subprocess.SubprocessError): + return False + + def login( server: str, *, @@ -31,7 +72,7 @@ def login( ) -> Any: """Run the flow against a server; returns the saved Session.""" sleep, monotonic = sleep or time.sleep, monotonic or time.monotonic - open_browser, out = open_browser or webbrowser.open, out or sys.stdout + open_browser, out = open_browser or open_in_browser, out or sys.stdout status, grant = call_json( f"{server}/api/v1/tool-sessions/device-authorization", method="POST", @@ -46,7 +87,11 @@ def login( ) # A browser opens only where one can; otherwise the address and code above are all there is. if not open_browser(grant["verification_uri_complete"]): - print("Open that address in a browser on any computer.", file=out, flush=True) + print( + "Open the address above in a browser on any computer, then wait here.", + file=out, + flush=True, + ) interval = grant["interval"] deadline = monotonic() + grant["expires_in"] while monotonic() < deadline: @@ -110,7 +155,11 @@ def command(arguments: list[str], *, out: TextIO | None = None) -> int: else: print(f"No stored login for {server}.", file=out) return 0 - session = login(server, out=out) + try: + session = login(server, out=out) + except KeyboardInterrupt: + print("\nLogin cancelled.", file=sys.stderr) + return 130 who = f" as @{session.github_user}" if session.github_user else "" print(f"Signed in to {server}{who}. modpoll uses the same login.", file=out) return 0 diff --git a/pyproject.toml b/pyproject.toml index 05cf17d..a4db90e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "modsim" -version = "2.0.0a9" +version = "2.0.0a10" description = "A Simple Modbus TCP Device Simulator used for modpoll tool" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" diff --git a/tests/test_login.py b/tests/test_login.py index 9b2ae99..5934475 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -103,7 +103,7 @@ def test_login_waits_for_the_browser_and_shares_the_login_with_modpoll(isolated_ assert slept == [5, 5, 10] assert ( "ABCD1234" in out.getvalue() - and "Open that address in a browser" in out.getvalue() + and "Open the address above in a browser" in out.getvalue() ) assert calls[0][:2] == ( "POST", @@ -147,7 +147,7 @@ def test_commands(capsys): } with ( fake_hub(routes, []), - patch.object(login.webbrowser, "open", return_value=True), + patch.object(login, "open_in_browser", return_value=True), patch.object(login.time, "sleep"), ): assert login.command(["login"]) == 0 @@ -227,3 +227,92 @@ def test_a_download_that_does_not_match_or_leaves_the_server_is_refused(): def test_a_bad_reference_and_a_deployment_manifest_do_not_use_the_login(): with pytest.raises(ValueError, match="modiohub:@"): sources.model_document("modiohub:nope") + + +class Finished: + def __init__(self, returncode): + self.returncode = returncode + + +@pytest.mark.parametrize( + "environ, platform, expected_calls", + [ + ({"DISPLAY": ":0"}, "linux", 1), + ({"WAYLAND_DISPLAY": "wayland-0"}, "linux", 1), + ({}, "linux", 0), # no desktop: SSH or a minimal WSL + ({"DISPLAY": ":0", "SSH_CONNECTION": "1 2 3 4"}, "linux", 0), + ], +) +def test_a_browser_is_tried_only_where_there_is_a_desktop( + environ, platform, expected_calls +): + calls = [] + opened = login.open_in_browser( + "https://hub.test/activate/?user_code=X", + environ=environ, + platform=platform, + run=lambda command, **options: calls.append((command, options)) or Finished(0), + which=lambda name: "/usr/bin/xdg-open", + ) + assert len(calls) == expected_calls and opened is bool(expected_calls) + if calls: + # The opener's complaints stay out of the terminal. + assert ( + calls[0][1]["stdout"] == login.subprocess.DEVNULL + and calls[0][1]["stderr"] == login.subprocess.DEVNULL + ) + + +def test_an_opener_that_finds_no_browser_or_is_missing_is_a_failure_not_noise(): + environ = {"DISPLAY": ":0"} + assert ( + login.open_in_browser( + "https://x.test", + environ=environ, + platform="linux", + run=lambda *a, **k: Finished(3), + which=lambda name: "/usr/bin/xdg-open", + ) + is False + ) + assert ( + login.open_in_browser( + "https://x.test", environ=environ, platform="linux", which=lambda name: None + ) + is False + ) + + def broken(*args, **kwargs): + raise OSError("gone") + + assert ( + login.open_in_browser( + "https://x.test", + environ=environ, + platform="linux", + run=broken, + which=lambda name: "/usr/bin/xdg-open", + ) + is False + ) + + +def test_the_browser_variable_and_other_platforms_use_the_standard_opener(monkeypatch): + seen = [] + monkeypatch.setattr(login.webbrowser, "open", lambda url: seen.append(url) or True) + assert ( + login.open_in_browser( + "https://a.test", environ={"BROWSER": "wslview"}, platform="linux" + ) + is True + ) + assert ( + login.open_in_browser("https://b.test", environ={}, platform="darwin") is True + ) + assert seen == ["https://a.test", "https://b.test"] + + +def test_ctrl_c_while_waiting_is_a_one_line_cancel(capsys): + with patch.object(login, "login", side_effect=KeyboardInterrupt): + assert login.command(["login"]) == 130 + assert "Login cancelled." in capsys.readouterr().err diff --git a/uv.lock b/uv.lock index 88bda9d..56673e9 100644 --- a/uv.lock +++ b/uv.lock @@ -842,7 +842,7 @@ wheels = [ [[package]] name = "modsim" -version = "2.0.0a9" +version = "2.0.0a10" source = { editable = "." } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" },