From 127a47386b9f832573c61adcc952f941c83cb683 Mon Sep 17 00:00:00 2001 From: Taylor Steinberg Date: Thu, 12 Nov 2026 13:47:00 -0500 Subject: [PATCH 1/2] fix: select quickstart Python from Connect server --- docs/commands/quickstart.md | 20 +++ rsconnect/main.py | 61 ++++++- rsconnect/models.py | 5 +- rsconnect/quickstart/quickstart.py | 61 +++++-- tests/test_quickstart.py | 255 ++++++++++++++++++++++++++++- 5 files changed, 381 insertions(+), 21 deletions(-) diff --git a/docs/commands/quickstart.md b/docs/commands/quickstart.md index 5e1671b4d..557ac24c2 100644 --- a/docs/commands/quickstart.md +++ b/docs/commands/quickstart.md @@ -1,3 +1,23 @@ +# Python version selection + +Without `--python`, quickstart uses the newest usable Python installation +marked publishable for new content on the selected Posit Connect server. +It writes a `>=major.minor` requirement and asks uv to create the environment +with that major/minor. uv may download Python according to your uv settings. +Server selection and credentials use the usual `--name`, `--server`, +`--api-key`, TLS options, environment variables, and saved servers. + +If no server is configured, quickstart uses the Python interpreter running +rsconnect. If the server cannot be queried or credentials are missing, it +warns and uses that interpreter without checking server compatibility. If a +successful lookup finds no usable publishable Python, quickstart fails: check +the server's Python configuration or use `--python`. A failed Python download +or dependency installation also fails and removes the incomplete project. + +`--python` overrides discovery and makes no server request. A major/minor +version permits any patch release, a full version is exact, and a specifier +such as `>=3.10,<3.13` is used as supplied. + ::: mkdocs-click :module: rsconnect.main :command: quickstart diff --git a/rsconnect/main.py b/rsconnect/main.py index 85c87292f..61ef3a97f 100644 --- a/rsconnect/main.py +++ b/rsconnect/main.py @@ -2043,7 +2043,8 @@ def info(file: str): # vocabulary. type=click.Choice(AppModes.cli_aliases()), ) -@click.argument("name", metavar="NAME") +@click.argument("project_name", metavar="NAME") +@server_args @click.option( "--python", "python_version", @@ -2053,18 +2054,68 @@ def info(file: str): "Python version for 'requires-python' in the generated pyproject.toml. " "A bare 'major.minor' like '3.10' means any 3.10.x; a full '3.11.14' is " "exact; pass an operator for full control (e.g. '>=3.11' or " - "'>=3.11,<3.14'). Defaults to '>=' of the interpreter " - "running rsconnect." + "'>=3.11,<3.14'). By default, use the newest publishable Python on " + "the selected Connect server, or the interpreter running rsconnect." ), ) @cli_exception_handler -def quickstart(app_type: str, name: str, python_version: Optional[str]): +@click.pass_context +def quickstart( + ctx: click.Context, + app_type: str, + project_name: str, + python_version: Optional[str], + name: Optional[str], + server: Optional[str], + api_key: Optional[str], + insecure: bool, + cacert: Optional[str], + verbose: int, +): # Resolve ``run_quickstart`` through the module at call time so tests can # monkeypatch ``rsconnect.quickstart.quickstart.run_quickstart`` without # binding a stale reference into ``main``'s namespace at import time. from .quickstart.quickstart import run_quickstart - run_quickstart(app_type=app_type, name=name, python_version=python_version) + set_verbosity(verbose) + + def server_python_settings() -> Optional[tuple[object, str]]: + try: + resolved = server_store.resolve(name, server) + if not resolved.url: + return None + if not (api_key or resolved.api_key or resolved.oauth_client_id): + raise RSConnectException( + "No Connect credentials are available; use --api-key or log in with rsconnect login." + ) + # The executor's validation requires a target even when the store + # can resolve a single saved server without an explicit default. + effective_name = name or (resolved.name if not server else None) + executor = RSConnectExecutor( + ctx, effective_name, server, api_key, insecure=insecure, cacert=cacert, logger=None + ) + if not isinstance(executor.remote_server, RSConnectServer) or not isinstance( + executor.client, RSConnectClient + ): + raise RSConnectException("The selected target is not a Posit Connect server.") + remote = executor.remote_server + if not remote.api_key and not remote.oauth_access_token and not remote.oauth_client_id: + raise RSConnectException("No credentials are available for the selected Connect server.") + with executor.client: + return executor.client.python_settings(), remote.url + except Exception as exc: + warn_user( + f"Warning: Could not check the Connect server's Python settings: {exc}. " + "Server compatibility was not checked." + ) + return None, "fallback" + + run_quickstart( + app_type=app_type, + name=project_name, + python_version=python_version, + server_python_settings=server_python_settings, + ) @cli.group(no_args_is_help=True, help="Deploy content to Posit Connect, Posit Connect Cloud, or shinyapps.io.") diff --git a/rsconnect/models.py b/rsconnect/models.py index 2b982a8dc..7996f4592 100644 --- a/rsconnect/models.py +++ b/rsconnect/models.py @@ -19,9 +19,9 @@ # they should both come from the same typing module. # https://peps.python.org/pep-0655/#usage-in-python-3-11 if sys.version_info >= (3, 11): - from typing import TypedDict + from typing import NotRequired, TypedDict else: - from typing_extensions import TypedDict + from typing_extensions import NotRequired, TypedDict _version_search_pattern = r"(^[=><]{0,2})(.*)" _content_guid_pattern = r"([^,]*),?(.*)" @@ -619,6 +619,7 @@ class PyInstallation(TypedDict): version: str cluster_name: str image_name: str + publishable: NotRequired[bool] class BuildOutputDTO(TypedDict): diff --git a/rsconnect/quickstart/quickstart.py b/rsconnect/quickstart/quickstart.py index 4f9ee9dcf..919c3e311 100644 --- a/rsconnect/quickstart/quickstart.py +++ b/rsconnect/quickstart/quickstart.py @@ -51,6 +51,7 @@ def run_quickstart( name: str, *, python_version: typing.Optional[str] = None, + server_python_settings: typing.Optional[typing.Callable[[], typing.Optional[typing.Tuple[object, str]]]] = None, cwd: typing.Optional[pathlib.Path] = None, ) -> pathlib.Path: """Scaffold a new Connect project of ``app_type`` named ``name``. @@ -66,8 +67,8 @@ def run_quickstart( that begins with a specifier operator (e.g. ``>=3.11`` or ``>=3.11,<3.14``) is used verbatim. A bare version is padded to at most three segments: ``3.10`` -> ``==3.10.*`` (any 3.10.x) and - ``3.11.14`` -> ``==3.11.14`` (exact). Defaults to ``>=`` - of the interpreter running ``rsconnect``. + ``3.11.14`` -> ``==3.11.14`` (exact). + :param server_python_settings: optional lazy server settings lookup. :param pathlib.Path cwd: override the working directory (testing hook); defaults to :func:`pathlib.Path.cwd`. """ @@ -94,13 +95,27 @@ def run_quickstart( # verbatim. A bare version is padded to at most three segments so the # ``.*`` wildcard appears only when a patch level is omitted: ``3.10`` -> # ``==3.10.*`` (any 3.10.x), ``3.11.14`` -> ``==3.11.14`` (exact). - # Without ``--python`` we track the running interpreter's ``major.minor``. + venv_python: typing.Optional[str] = None if python_version is None: requires_python = _REQUIRES_PYTHON + venv_python = sys.executable + source = "the Python interpreter running rsconnect" + settings = server_python_settings() if server_python_settings else None + if settings is not None: + data, server = settings + if server == "fallback" and data is None: + source = "the Python interpreter running rsconnect (server compatibility not checked)" + else: + version = _newest_publishable_python(data) + requires_python = f">={version}" + venv_python = version + source = f"the Posit Connect server {server}" elif python_version[:1] in {"=", "<", ">", "!", "~"}: requires_python = python_version + source = "the --python override" else: requires_python = "==" + ".".join((python_version.split(".") + ["*"])[:3]) + source = "the --python override" # Atomicity: after ``mkdir`` succeeds, any failure in the rest of the # pipeline must remove ``.//`` so the user sees "all or nothing." @@ -109,10 +124,7 @@ def run_quickstart( target.mkdir() try: _scaffold(target, name=name, spec=spec, requires_python=requires_python) - # Without ``--python``, build the venv on the running interpreter. - # Otherwise uv picks the newest Python matching ``requires-python``, - # which may be too new for some dependencies to have wheels yet. - _install_venv(target, python=sys.executable if python_version is None else None) + _install_venv(target, python=venv_python) except BaseException: shutil.rmtree(target, ignore_errors=True) raise @@ -121,10 +133,34 @@ def run_quickstart( # BrokenPipeError when piping to ``head``) must not invalidate the # on-disk project. The README carries the same two commands, so the # user can recover them even if this echo fails. - _emit_summary(target, name=name, spec=spec) + _emit_summary(target, name=name, spec=spec, requires_python=requires_python, source=source) return target +def _newest_publishable_python(settings: object) -> str: + installations = ( + typing.cast(typing.Mapping[str, object], settings).get("installations") if isinstance(settings, dict) else None + ) + versions: list[tuple[int, ...]] = [] + if isinstance(installations, list): + for item in typing.cast(typing.List[object], installations): + if not isinstance(item, dict): + continue + installation = typing.cast(typing.Mapping[str, object], item) + if installation.get("publishable") is not True: + continue + version = installation.get("version") + if isinstance(version, str) and re.fullmatch(r"[0-9]+\.[0-9]+(?:\.[0-9]+)?", version): + versions.append(tuple(int(part) for part in version.split("."))) + if not versions: + raise RSConnectException( + "The Connect server has no usable Python installation marked publishable for new content. " + "Check the server's Python configuration or use --python to bypass discovery." + ) + selected = max(versions) + return f"{selected[0]}.{selected[1]}" + + # --------------------------------------------------------------------------- # Pre-flight checks # --------------------------------------------------------------------------- @@ -399,9 +435,7 @@ def _load_template(path: str) -> str: # ``requires-python`` is the single source of truth for the scaffold's Python # requirement: ``rsconnect deploy pyproject`` reads ``pyproject.toml``, so # emitting a separate ``.python-version`` pin would only duplicate this value. -# The floor tracks the interpreter that ran ``rsconnect quickstart`` so the -# scaffold matches the developer's working environment without committing the -# project to any version older than what its author has actually used. +# The running interpreter is the fallback when no server can be consulted. _REQUIRES_PYTHON = ">={}.{}".format(*sys.version_info[:2]) _GITIGNORE_BODY = """\ @@ -417,7 +451,7 @@ def _load_template(path: str) -> str: def _render_pyproject(*, name: str, spec: TemplateSpec, requires_python: str) -> str: # The per-mode template owns the literal TOML, including ``app_mode``, # ``entrypoint`` and the dependency list. Only ``$name`` (project name) - # and ``$requires_python`` (from ``--python`` or the running interpreter) + # and ``$requires_python`` (selected for this scaffold) # vary at scaffold time. return string.Template(_load_template(spec.pyproject_template)).substitute( name=name, requires_python=requires_python @@ -479,7 +513,7 @@ def _install_venv(target: pathlib.Path, python: typing.Optional[str] = None) -> # --------------------------------------------------------------------------- -def _emit_summary(target: pathlib.Path, *, name: str, spec: TemplateSpec) -> None: +def _emit_summary(target: pathlib.Path, *, name: str, spec: TemplateSpec, requires_python: str, source: str) -> None: """Print the confirmation, cd, local-run, deploy, and notes lines. Uses :func:`click.echo` for consistency with the rest of the CLI; the @@ -487,6 +521,7 @@ def _emit_summary(target: pathlib.Path, *, name: str, spec: TemplateSpec) -> Non :func:`_render_readme` so stdout and on-disk docs agree. """ click.echo(f"\nProject {target.name}/ created.") + click.echo(f"Python requirement: {requires_python} (from {source})") click.echo(f"To get started: cd {name}") click.echo(f"To run locally: {_format_local_run(spec, name=name)}") click.echo("To deploy: rsconnect deploy pyproject .") diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index b66ef2611..85eda133c 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -28,6 +28,7 @@ import typing from unittest import mock +import httpretty import pytest try: @@ -38,6 +39,7 @@ from click.testing import CliRunner from rsconnect.main import cli +from rsconnect.metadata import ServerStore from tests import _local_run @@ -62,6 +64,16 @@ def runner() -> CliRunner: return CliRunner() +@pytest.fixture(autouse=True) +def isolated_servers(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> ServerStore: + for key in ("CONNECT_SERVER", "CONNECT_API_KEY", "CONNECT_INSECURE", "CONNECT_CA_CERTIFICATE"): + monkeypatch.delenv(key, raising=False) + store = ServerStore(str(tmp_path / "config")) + monkeypatch.setattr("rsconnect.main.server_store", store) + monkeypatch.setattr("rsconnect.api.ServerStore", lambda: store) + return store + + def _invoke_quickstart(runner: CliRunner, *args: str): return runner.invoke(cli, ["quickstart", *args], catch_exceptions=False) @@ -153,7 +165,9 @@ def test_quickstart_delegates_to_run_quickstart( result = runner.invoke(cli, ["quickstart", *args]) assert result.exit_code == 0, result.output - run_quickstart.assert_called_once_with(**expected) + kwargs = run_quickstart.call_args.kwargs + assert callable(kwargs.pop("server_python_settings")) + assert kwargs == expected # --------------------------------------------------------------------------- @@ -357,6 +371,243 @@ def test_quickstart_python_option_full_version_is_exact( assert data["project"]["requires-python"] == "==3.11.14" +@pytest.mark.parametrize("target", ["server", "name", "environment", "default", "single"]) +def test_server_python_selection( + runner: CliRunner, + in_tmp_cwd: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + isolated_servers: ServerStore, + target: str, +): + isolated_servers.set("chosen", "https://chosen.example", api_key="saved-key", set_as_default=target == "default") + if target != "single": + isolated_servers.set( + "other", + "https://other.example", + api_key="other-key", + set_as_default=target in {"server", "name", "environment"}, + ) + args: list[str] = [] + if target == "server": + args = ["--server", "https://chosen.example"] + elif target == "name": + args = ["--name", "chosen"] + elif target == "environment": + monkeypatch.setenv("CONNECT_SERVER", "https://chosen.example") + + calls: list[tuple[str, str]] = [] + + def settings(client): + calls.append((client._server.url, client._server.api_key)) + return { + "installations": [ + {"version": "3.9.20", "publishable": True}, + {"version": "3.13.1", "publishable": False}, + {"version": "3.12.8", "publishable": True}, + {"version": "invalid", "publishable": True}, + {"version": "3.14", "publishable": "true"}, + {"version": "3.15"}, + ] + } + + install = mock.Mock() + monkeypatch.setattr("rsconnect.api.RSConnectClient.python_settings", settings) + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", install) + result = _invoke_quickstart(runner, "streamlit", "hello_app", *args) + assert result.exit_code == 0, result.output + assert calls == [("https://chosen.example", "saved-key")] + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ">=3.12" + assert install.call_args.kwargs["python"] == "3.12" + assert "Posit Connect server https://chosen.example" in result.output + + +def test_server_python_accepts_eol_version( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, isolated_servers: ServerStore +): + isolated_servers.set("server", "https://connect.example", api_key="key") + monkeypatch.setattr( + "rsconnect.api.RSConnectClient.python_settings", + lambda self: {"installations": [{"version": "3.10.16", "publishable": True}]}, + ) + install = mock.Mock() + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", install) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ">=3.10" + assert install.call_args.kwargs["python"] == "3.10" + + +@pytest.mark.parametrize("version", ["3.10", "3.11.14", ">=3.10,<3.13"]) +def test_explicit_python_skips_server_discovery( + runner: CliRunner, + in_tmp_cwd: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + isolated_servers: ServerStore, + version: str, +): + monkeypatch.setenv("CONNECT_SERVER", "https://connect.example") + resolve = mock.Mock(side_effect=AssertionError("discovery called")) + monkeypatch.setattr(isolated_servers, "resolve", resolve) + refresh = mock.Mock(side_effect=AssertionError("refresh called")) + monkeypatch.setattr("rsconnect.api.RSConnectClient._attempt_token_refresh", refresh) + install = mock.Mock() + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", install) + result = _invoke_quickstart(runner, "streamlit", "hello_app", "--python", version) + assert result.exit_code == 0, result.output + assert "the --python override" in result.output + assert install.call_args.kwargs["python"] is None + resolve.assert_not_called() + refresh.assert_not_called() + + +@pytest.mark.parametrize( + "installations", + [ + [], + [{"version": "3.12", "publishable": False}], + [{"version": "3.12"}], + [{"version": "3.12", "publishable": 1}], + [{"version": "bad", "publishable": True}], + ], +) +def test_no_publishable_python_fails( + runner: CliRunner, + in_tmp_cwd: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + isolated_servers: ServerStore, + installations, +): + isolated_servers.set("server", "https://connect.example", api_key="key") + monkeypatch.setattr("rsconnect.api.RSConnectClient.python_settings", lambda self: {"installations": installations}) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code != 0 + assert "publishable" in result.output and "--python" in result.output + assert not (in_tmp_cwd / "hello_app").exists() + + +@pytest.mark.parametrize("failure", ["credentials", "rejected", "unreachable"]) +def test_server_failure_warns_and_falls_back( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, failure: str +): + monkeypatch.setenv("CONNECT_SERVER", "https://connect.example") + if failure != "credentials": + monkeypatch.setenv("CONNECT_API_KEY", "key") + monkeypatch.setattr("rsconnect.api.RSConnectClient.python_settings", mock.Mock(side_effect=OSError(failure))) + install = mock.Mock() + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", install) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert "Warning:" in result.output and "compatibility" in result.output + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ( + f">={sys.version_info.major}.{sys.version_info.minor}" + ) + assert install.call_args.kwargs["python"] == sys.executable + + +@httpretty.activate(allow_net_connect=False) +@pytest.mark.parametrize("credential", ["key", "oauth"]) +def test_server_settings_http_authentication( + runner: CliRunner, + in_tmp_cwd: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + isolated_servers: ServerStore, + credential: str, +): + url = "https://connect.example" + if credential == "key": + isolated_servers.set("server", url, api_key="api-key") + authorization = "Key api-key" + else: + isolated_servers.set("server", url, oauth_client_id="client", oauth_access_token="access") + monkeypatch.setattr("rsconnect.oauth.keyring_get_tokens", lambda url: (None, None)) + authorization = "Bearer access" + httpretty.register_uri( + httpretty.GET, + f"{url}/__api__/v1/server_settings/python", + body=json.dumps({"installations": [{"version": "3.10.16", "publishable": True}]}), + content_type="application/json", + ) + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", mock.Mock()) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert httpretty.last_request().headers["Authorization"] == authorization + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ">=3.10" + + +@httpretty.activate(allow_net_connect=False) +def test_rejected_server_authentication_warns( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, isolated_servers: ServerStore +): + isolated_servers.set("server", "https://connect.example", api_key="bad-key") + httpretty.register_uri( + httpretty.GET, "https://connect.example/__api__/v1/server_settings/python", status=401, body="unauthorized" + ) + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", mock.Mock()) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert "Warning:" in result.output and "compatibility was not checked" in result.output + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ( + f">={sys.version_info.major}.{sys.version_info.minor}" + ) + + +@httpretty.activate(allow_net_connect=False) +def test_server_oauth_refresh( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, isolated_servers: ServerStore +): + isolated_servers.set("server", "https://connect.example", oauth_client_id="client", oauth_access_token="old-token") + monkeypatch.setattr("rsconnect.oauth.keyring_get_tokens", lambda url: (None, None)) + refresh = mock.Mock(return_value="new-token") + monkeypatch.setattr("rsconnect.oauth.refresh_stored_tokens", refresh) + httpretty.register_uri( + httpretty.GET, + "https://connect.example/__api__/v1/server_settings/python", + responses=[ + httpretty.Response(status=401, body="unauthorized"), + httpretty.Response( + body=json.dumps({"installations": [{"version": "3.10.16", "publishable": True}]}), + content_type="application/json", + ), + ], + ) + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", mock.Mock()) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert [request.headers["Authorization"] for request in httpretty.latest_requests()] == [ + "Bearer old-token", + "Bearer new-token", + ] + refresh.assert_called_once() + assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ">=3.10" + + +@pytest.mark.parametrize("failed_command", ["venv", "sync"]) +def test_server_python_uv_failure_removes_project( + runner: CliRunner, + in_tmp_cwd: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + isolated_servers: ServerStore, + failed_command: str, +): + isolated_servers.set("server", "https://connect.example", api_key="key") + monkeypatch.setattr( + "rsconnect.api.RSConnectClient.python_settings", + lambda self: {"installations": [{"version": "3.10.16", "publishable": True}]}, + ) + monkeypatch.setenv("UV_PYTHON_DOWNLOADS", "never") + calls = [] + + def run(command, cwd, env): + calls.append((command, env["UV_PYTHON_DOWNLOADS"])) + return subprocess.CompletedProcess(command, int(command[1] == failed_command)) + + monkeypatch.setattr("rsconnect.quickstart.quickstart.subprocess.run", run) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code != 0 and f"uv {failed_command}" in result.output + assert calls[0] == (["uv", "venv", "--python", "3.10"], "never") + assert not (in_tmp_cwd / "hello_app").exists() + + # --------------------------------------------------------------------------- # Per-mode app_mode matrix # --------------------------------------------------------------------------- @@ -715,6 +966,8 @@ def test_quickstart_post_scaffold_output( lines = [line for line in result.output.splitlines() if line.strip()] expected = [ "Project hello_app/ created.", + f"Python requirement: >={sys.version_info.major}.{sys.version_info.minor} " + "(from the Python interpreter running rsconnect)", "To get started: cd hello_app", f"To run locally: {local_run}", "To deploy: rsconnect deploy pyproject .", From 0bf978d332973fb987f1025cc736279513ffc94b Mon Sep 17 00:00:00 2001 From: Taylor Steinberg Date: Thu, 12 Nov 2026 14:27:50 -0500 Subject: [PATCH 2/2] fix: clarify quickstart server selection errors --- docs/commands/quickstart.md | 6 ++- rsconnect/main.py | 61 ++++++++++++++++++++---------- rsconnect/quickstart/quickstart.py | 2 +- tests/test_quickstart.py | 46 ++++++++++++++++++++++ 4 files changed, 93 insertions(+), 22 deletions(-) diff --git a/docs/commands/quickstart.md b/docs/commands/quickstart.md index 557ac24c2..2ad21d0a1 100644 --- a/docs/commands/quickstart.md +++ b/docs/commands/quickstart.md @@ -13,10 +13,14 @@ warns and uses that interpreter without checking server compatibility. If a successful lookup finds no usable publishable Python, quickstart fails: check the server's Python configuration or use `--python`. A failed Python download or dependency installation also fails and removes the incomplete project. +If several servers are saved without a default, select one with `--name` or +`--server`, or set a default. Invalid server nicknames and CA certificate paths +are errors. `--python` overrides discovery and makes no server request. A major/minor version permits any patch release, a full version is exact, and a specifier -such as `>=3.10,<3.13` is used as supplied. +such as `>=3.10,<3.13` is used as supplied. Explicit server options are ignored +when `--python` is supplied. ::: mkdocs-click :module: rsconnect.main diff --git a/rsconnect/main.py b/rsconnect/main.py index 0c3a15631..37452338f 100644 --- a/rsconnect/main.py +++ b/rsconnect/main.py @@ -2079,33 +2079,54 @@ def quickstart( set_verbosity(verbose) + if python_version is not None: + ignored_options = [ + option + for option in ("name", "server", "api_key", "insecure", "cacert") + if validation.get_parameter_source_name_from_ctx(option, ctx) == "COMMANDLINE" + ] + if ignored_options: + click.echo("Server options are ignored because --python was supplied.") + def server_python_settings() -> Optional[tuple[object, str]]: - try: - resolved = server_store.resolve(name, server) - if not resolved.url: - return None - if not (api_key or resolved.api_key or resolved.oauth_client_id): - raise RSConnectException( - "No Connect credentials are available; use --api-key or log in with rsconnect login." + if name and server and validation.get_parameter_source_name_from_ctx("server", ctx) == "COMMANDLINE": + raise RSConnectException("-n/--name cannot be specified together with -s/--server.") + if cacert: + read_certificate_file(cacert) + resolved = server_store.resolve(name, server) + if not resolved.url: + if server_store.count() > 1: + warn_user( + "Warning: Multiple servers are saved with no default. " + "Use --name or --server, or set a default, to check server compatibility." ) - # The executor's validation requires a target even when the store - # can resolve a single saved server without an explicit default. - effective_name = name or (resolved.name if not server else None) - executor = RSConnectExecutor( - ctx, effective_name, server, api_key, insecure=insecure, cacert=cacert, logger=None + return None, "fallback" + return None + + if not (api_key or resolved.api_key or resolved.oauth_client_id): + warn_user( + "Warning: Could not check the Connect server's Python settings: " + "No Connect credentials are available; use --api-key or log in with rsconnect login.\n" + "Server compatibility was not checked." ) - if not isinstance(executor.remote_server, RSConnectServer) or not isinstance( - executor.client, RSConnectClient - ): - raise RSConnectException("The selected target is not a Posit Connect server.") - remote = executor.remote_server - if not remote.api_key and not remote.oauth_access_token and not remote.oauth_client_id: - raise RSConnectException("No credentials are available for the selected Connect server.") + return None, "fallback" + + # The executor's validation requires a target even when the store + # can resolve a single saved server without an explicit default. + effective_name = name or (resolved.name if not server else None) + executor = RSConnectExecutor( + ctx, effective_name, server, api_key, insecure=insecure, cacert=cacert, logger=None + ) + if not isinstance(executor.remote_server, RSConnectServer) or not isinstance(executor.client, RSConnectClient): + raise RSConnectException("The selected target is not a Posit Connect server.") + remote = executor.remote_server + click.echo(f"Checking Python versions on {remote.url}...") + try: with executor.client: return executor.client.python_settings(), remote.url except Exception as exc: warn_user( - f"Warning: Could not check the Connect server's Python settings: {exc}. " + f"Warning: Could not check the Connect server's Python settings: {exc}\n" "Server compatibility was not checked." ) return None, "fallback" diff --git a/rsconnect/quickstart/quickstart.py b/rsconnect/quickstart/quickstart.py index f507c78bc..1db5896e3 100644 --- a/rsconnect/quickstart/quickstart.py +++ b/rsconnect/quickstart/quickstart.py @@ -104,7 +104,7 @@ def run_quickstart( if settings is not None: data, server = settings if server == "fallback" and data is None: - source = "the Python interpreter running rsconnect (server compatibility not checked)" + source = "the Python interpreter running rsconnect; server compatibility not checked" else: version = _newest_publishable_python(data) requires_python = f">={version}" diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 43855d941..64e107dd3 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -420,6 +420,7 @@ def settings(client): assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ">=3.12" assert install.call_args.kwargs["python"] == "3.12" assert "Posit Connect server https://chosen.example" in result.output + assert "Checking Python versions on https://chosen.example..." in result.output def test_server_python_accepts_eol_version( @@ -461,6 +462,49 @@ def test_explicit_python_skips_server_discovery( refresh.assert_not_called() +@pytest.mark.parametrize( + "options", [["--name", "missing"], ["--server", "https://connect.example"], ["--cacert", "bad.pem"]] +) +def test_explicit_python_reports_ignored_server_options( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, options: list[str] +): + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", mock.Mock()) + monkeypatch.setattr( + "rsconnect.main.server_store.resolve", mock.Mock(side_effect=AssertionError("discovery called")) + ) + result = _invoke_quickstart(runner, "streamlit", "hello_app", "--python", "3.10", *options) + assert result.exit_code == 0, result.output + assert "Server options are ignored because --python was supplied." in result.output + + +@pytest.mark.parametrize( + ("options", "message"), + [ + (["--name", "missing"], 'The nickname, "missing", does not exist.'), + (["--cacert", "missing.pem"], "certificate file missing.pem could not be read"), + (["--name", "missing", "--server", "https://connect.example"], "cannot be specified together"), + ], +) +def test_invalid_server_options_fail(runner: CliRunner, in_tmp_cwd: pathlib.Path, options: list[str], message: str): + result = _invoke_quickstart(runner, "streamlit", "hello_app", *options) + assert result.exit_code != 0 + assert message in result.output + assert not (in_tmp_cwd / "hello_app").exists() + + +def test_multiple_servers_without_default_warns( + runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, isolated_servers: ServerStore +): + isolated_servers.set("one", "https://one.example", api_key="key") + isolated_servers.set("two", "https://two.example", api_key="key") + monkeypatch.setattr("rsconnect.quickstart.quickstart._install_venv", mock.Mock()) + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + assert "Multiple servers are saved with no default" in result.output + assert "--name or --server" in result.output + assert "server compatibility not checked" in result.output + + @pytest.mark.parametrize( "installations", [ @@ -499,6 +543,8 @@ def test_server_failure_warns_and_falls_back( result = _invoke_quickstart(runner, "streamlit", "hello_app") assert result.exit_code == 0, result.output assert "Warning:" in result.output and "compatibility" in result.output + assert ".. Server" not in result.output + assert "(from the Python interpreter running rsconnect; server compatibility not checked)" in result.output assert _read_pyproject(in_tmp_cwd / "hello_app")["project"]["requires-python"] == ( f">={sys.version_info.major}.{sys.version_info.minor}" )