From 5776ce2fe534489c52f071b7575bbb991ee15901 Mon Sep 17 00:00:00 2001 From: Taylor Steinberg Date: Tue, 10 Nov 2026 11:12:23 -0500 Subject: [PATCH 1/2] fix: report Python-incompatible upgrades --- docs/CHANGELOG.md | 4 + rsconnect/version_check.py | 121 +++++---- tests/test_version_check.py | 517 +++++++++++++++--------------------- 3 files changed, 289 insertions(+), 353 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 02c53c4c1..fa5be1792 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Explains when the latest rsconnect-python release requires a different Python version and suggests installing it with `uv tool install`. + ## [1.33.1] - 2026-11-09 ### Fixed diff --git a/rsconnect/version_check.py b/rsconnect/version_check.py index df334776c..245e1cd06 100644 --- a/rsconnect/version_check.py +++ b/rsconnect/version_check.py @@ -12,12 +12,14 @@ import json import os +import platform import threading import time from http.client import HTTPSConnection from os.path import join -from typing import Optional, Tuple +from typing import NamedTuple, Optional, Tuple +from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import Version from . import VERSION @@ -27,10 +29,15 @@ _PYPI_HOST = "pypi.org" _PYPI_PATH = "/pypi/rsconnect-python/json" _PYPI_TIMEOUT_SECONDS = 2 -_CACHE_TTL_SECONDS = 24 * 60 * 60 # Re-check PyPI at most once a day. +_CACHE_TTL_SECONDS = 24 * 60 * 60 _CACHE_FILENAME = "version_check.json" +class _Release(NamedTuple): + version: str + requires_python: Optional[str] + + def _is_check_disabled() -> bool: value = os.environ.get(RSCONNECT_DISABLE_VERSION_CHECK, "").strip().lower() return value in ("1", "true", "yes") @@ -47,42 +54,43 @@ def _cache_path() -> str: return join(config_dirname(), _CACHE_FILENAME) -def _read_cache() -> Tuple[bool, Optional[str]]: - """Return ``(is_fresh, latest)``. - - ``latest`` is the last known PyPI version recorded in the cache (or None when - the cache is missing/unreadable or the last fetch failed). It is returned - regardless of freshness so even a stale value can drive the upgrade hint while - a refresh runs in the background. ``is_fresh`` is True only when the entry is - within the TTL, signalling that no background refresh is needed. - """ +def _read_cache() -> Tuple[bool, Optional[_Release]]: + """Return freshness and the cached release, retaining stale data for the hint.""" try: with open(_cache_path()) as f: data = json.load(f) latest = data.get("latest") - latest = latest if isinstance(latest, str) else None - is_fresh = time.time() - float(data["checked_at"]) <= _CACHE_TTL_SECONDS - return (is_fresh, latest) + requires_python = data.get("requires_python") + release = ( + _Release(latest, requires_python if isinstance(requires_python, str) else None) + if isinstance(latest, str) + else None + ) + is_fresh = "requires_python" in data and time.time() - float(data["checked_at"]) <= _CACHE_TTL_SECONDS + return (is_fresh, release) except Exception: return (False, None) -def _write_cache(latest: Optional[str]) -> None: - """Persist the latest known version (or None) with the current timestamp. - - A None value is still cached so repeated failures don't re-hit PyPI on every - deploy until the TTL expires. - """ +def _write_cache(release: Optional[_Release]) -> None: + """Cache failures too, so they do not trigger another request until the TTL expires.""" try: path = _cache_path() makedirs(path) with open(path, "w") as f: - json.dump({"checked_at": time.time(), "latest": latest}, f) + json.dump( + { + "checked_at": time.time(), + "latest": release.version if release else None, + "requires_python": release.requires_python if release else None, + }, + f, + ) except Exception: pass -def _fetch_latest_version() -> Optional[str]: +def _fetch_latest_version() -> Optional[_Release]: conn = None try: conn = HTTPSConnection(_PYPI_HOST, timeout=_PYPI_TIMEOUT_SECONDS) @@ -90,8 +98,12 @@ def _fetch_latest_version() -> Optional[str]: response = conn.getresponse() if response.status != 200: return None - data = json.loads(response.read()) - return data.get("info", {}).get("version") + info = json.loads(response.read()).get("info", {}) + latest = info.get("version") + requires_python = info.get("requires_python") + if isinstance(latest, str): + return _Release(latest, requires_python if isinstance(requires_python, str) else None) + return None except Exception: return None finally: @@ -99,18 +111,31 @@ def _fetch_latest_version() -> Optional[str]: conn.close() -def _update_message(latest: Optional[str]) -> Optional[str]: - """Return an upgrade warning if ``latest`` is newer than the running version.""" +def _update_message(release: Optional[_Release]) -> Optional[str]: + """Return an upgrade warning if the release is newer than the running version.""" try: - if latest is not None and Version(latest) > Version(VERSION): + if release is None or Version(release.version) <= Version(VERSION): + return None + python_version = platform.python_version() + try: + compatible = not release.requires_python or SpecifierSet(release.requires_python).contains( + python_version, prereleases=True + ) + except InvalidSpecifier: + compatible = True + if not compatible: return ( - f"A new version of rsconnect-python is available: {latest} " - f"(you have {VERSION}).\n" - f"Upgrade with: pip install --upgrade rsconnect-python" + f"The latest version of rsconnect-python ({release.version}) requires Python " + f"{release.requires_python}, but you are running Python {python_version}.\n" + "Install it with: uv tool install rsconnect-python" ) + return ( + f"A new version of rsconnect-python is available: {release.version} " + f"(you have {VERSION}).\n" + "Upgrade with: pip install --upgrade rsconnect-python" + ) except Exception: - pass - return None + return None class BackgroundVersionCheck: @@ -118,37 +143,25 @@ class BackgroundVersionCheck: def __init__(self) -> None: self._thread: Optional[threading.Thread] = None - self._latest: Optional[str] = None + self._release: Optional[_Release] = None def start(self) -> None: if _is_check_disabled() or _is_dev_version(VERSION): return - is_fresh, latest = _read_cache() - # Seed the hint from the cached value (even a stale one is good enough to - # suggest an upgrade), so a warm cache prints instantly on every exit path - # -- including commands that fail fast. - self._latest = latest + is_fresh, self._release = _read_cache() if not is_fresh: - # Refresh in the background so the fetch overlaps the command's own - # work. A warm or stale cache never waits on this; only a cold cache - # waits briefly at exit -- see get_warning_message. self._thread = threading.Thread(target=self._run, daemon=True) self._thread.start() def _run(self) -> None: - latest = _fetch_latest_version() - _write_cache(latest) - # Adopt a successful result so a cold-cache run can warn this time, but - # never overwrite a usable cached value with a failed (None) refresh. - if latest is not None: - self._latest = latest + release = _fetch_latest_version() + _write_cache(release) + # Keep a usable stale value when a refresh fails. + if release is not None: + self._release = release def get_warning_message(self) -> Optional[str]: - # With no cached value yet (a cold cache: first run, or an ephemeral - # environment where the cache never persists), give the in-flight fetch a - # bounded chance to finish so this run can still warn. The bound is the - # fetch's own time budget -- a slower network just means no hint this run. - # A warm or stale cache already has a value here and never waits. - if self._latest is None and self._thread is not None: + # Only a cold cache waits briefly for the background fetch. + if self._release is None and self._thread is not None: self._thread.join(timeout=_PYPI_TIMEOUT_SECONDS) - return _update_message(self._latest) + return _update_message(self._release) diff --git a/tests/test_version_check.py b/tests/test_version_check.py index d98374d55..f0f847d7b 100644 --- a/tests/test_version_check.py +++ b/tests/test_version_check.py @@ -1,317 +1,236 @@ +import importlib import json -import os +import platform import threading import time -from unittest.mock import patch -import click import click.testing +import httpretty import pytest -from rsconnect.exception import RSConnectException -from rsconnect.actions import cli_feedback -from rsconnect.main import cli, deploy -from rsconnect.version_check import ( - RSCONNECT_DISABLE_VERSION_CHECK, - BackgroundVersionCheck, - _is_check_disabled, - _is_dev_version, - _read_cache, - _update_message, - _write_cache, -) - - -def _cli_runner() -> click.testing.CliRunner: - """Build a CliRunner with stdout/stderr kept separate across Click versions. - - Click < 8.2 needs ``mix_stderr=False`` to expose ``result.stderr``; Click >= 8.2 - removed the argument and always separates the streams. - """ +import rsconnect +import rsconnect.version_check +from rsconnect.main import cli +from rsconnect.metadata import config_dirname + + +@pytest.fixture +def release_cli(monkeypatch, tmp_path): + # The checkout normally has a development version, which skips the check. + with monkeypatch.context() as env: + env.setattr(rsconnect, "VERSION", "1.0.0") + env.setenv("HOME", str(tmp_path)) + env.setenv("XDG_CONFIG_HOME", str(tmp_path)) + env.setenv("APPDATA", str(tmp_path)) + env.delenv("RSCONNECT_DISABLE_VERSION_CHECK", raising=False) + importlib.reload(rsconnect.version_check) + yield tmp_path + importlib.reload(rsconnect.version_check) + + +def _runner(): try: return click.testing.CliRunner(mix_stderr=False) except TypeError: return click.testing.CliRunner() -# A throwaway deploy subcommand so we can exercise the deploy group's result -# callback without contacting a real server. -@deploy.command(name="_version_check_test_noop", hidden=True) -def _version_check_test_noop(): - click.echo("noop-ran") +def _deploy(): + # A real deploy that fails quickly, while still running the exit callback. + return _runner().invoke(cli, ["deploy", "html", "nonexistent-file.html"]) + + +def _pypi(info): + httpretty.register_uri( + httpretty.GET, + "https://pypi.org/pypi/rsconnect-python/json", + body=json.dumps({"info": info}), + content_type="application/json", + ) + + +def _cache_path(): + from pathlib import Path + + return Path(config_dirname()) / "version_check.json" + + +def _write_cache(**data): + path = _cache_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"checked_at": time.time(), **data})) -# A deploy subcommand that fails the way real ones do: cli_feedback catches the -# exception and calls sys.exit(1). The upgrade hint should still print. -@deploy.command(name="_version_check_test_fail", hidden=True) -def _version_check_test_fail(): - with cli_feedback(""): - raise RSConnectException("boom") - - -class TestIsCheckDisabled: - def test_unset(self): - with patch.dict(os.environ, {}, clear=True): - assert _is_check_disabled() is False - - @pytest.mark.parametrize("value", ["1", "true", "yes", "TRUE", "Yes"]) - def test_disabled(self, value): - with patch.dict(os.environ, {RSCONNECT_DISABLE_VERSION_CHECK: value}): - assert _is_check_disabled() is True - - @pytest.mark.parametrize("value", ["0", "no", "false", ""]) - def test_not_disabled(self, value): - with patch.dict(os.environ, {RSCONNECT_DISABLE_VERSION_CHECK: value}): - assert _is_check_disabled() is False - - -class TestIsDevVersion: - def test_dev_version(self): - assert _is_dev_version("1.29.1.dev10+g68dd1934d.d20260622") is True - - def test_release_version(self): - assert _is_dev_version("1.29.1") is False - - def test_prerelease_version(self): - assert _is_dev_version("1.29.1rc1") is False - - def test_unparseable(self): - assert _is_dev_version("NOTSET") is True - - -class TestUpdateMessage: - @patch("rsconnect.version_check.VERSION", "1.28.0") - def test_update_available(self): - message = _update_message("1.29.0") - assert message is not None - assert "1.29.0" in message - assert "pip install --upgrade rsconnect-python" in message - - @patch("rsconnect.version_check.VERSION", "1.29.0") - def test_up_to_date(self): - assert _update_message("1.29.0") is None - - @patch("rsconnect.version_check.VERSION", "1.30.0") - def test_ahead_of_pypi(self): - assert _update_message("1.29.0") is None - - def test_none_latest(self): - assert _update_message(None) is None - - @patch("rsconnect.version_check.VERSION", "1.28.0") - def test_unparseable_latest(self): - assert _update_message("not-a-version") is None - - -class TestCache: - def test_round_trip(self, tmp_path): - path = str(tmp_path / "version_check.json") - with patch("rsconnect.version_check._cache_path", return_value=path): - _write_cache("1.29.0") - assert _read_cache() == (True, "1.29.0") - - def test_caches_none(self, tmp_path): - path = str(tmp_path / "version_check.json") - with patch("rsconnect.version_check._cache_path", return_value=path): - _write_cache(None) - assert _read_cache() == (True, None) - - def test_missing_cache(self, tmp_path): - path = str(tmp_path / "nope.json") - with patch("rsconnect.version_check._cache_path", return_value=path): - assert _read_cache() == (False, None) - - def test_expired_cache(self, tmp_path): - # A stale entry is reported as not-fresh but still surfaces its value, so - # the upgrade hint can use it while a refresh runs in the background. - path = tmp_path / "version_check.json" - path.write_text(json.dumps({"checked_at": time.time() - 999999, "latest": "1.29.0"})) - with patch("rsconnect.version_check._cache_path", return_value=str(path)): - assert _read_cache() == (False, "1.29.0") - - def test_corrupt_cache(self, tmp_path): - path = tmp_path / "version_check.json" - path.write_text("{not json") - with patch("rsconnect.version_check._cache_path", return_value=str(path)): - assert _read_cache() == (False, None) - - -class TestBackgroundVersionCheck: - @patch("rsconnect.version_check._read_cache", return_value=(True, "2.0.0")) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_fresh_cache_avoids_thread(self, _disabled, _dev, mock_read): - checker = BackgroundVersionCheck() - checker.start() - assert checker._thread is None # No network when the cache is fresh. - message = checker.get_warning_message() - assert message is not None - assert "2.0.0" in message - - @patch("rsconnect.version_check._write_cache") - @patch("rsconnect.version_check._fetch_latest_version", return_value="3.0.0") - @patch("rsconnect.version_check._read_cache", return_value=(False, "2.0.0")) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_stale_cache_warns_from_cache_and_refreshes(self, _disabled, _dev, _read, mock_fetch, mock_write): - checker = BackgroundVersionCheck() - checker.start() - # A stale cached value is enough to warn synchronously, so the message is - # available without waiting on the network (it names either the stale - # 2.0.0 or the freshly fetched 3.0.0, depending on thread timing -- both - # are newer than the running version, so either is a valid hint). - assert checker._thread is not None - message = checker.get_warning_message() - assert message is not None - # The fetch also refreshes the cache for the next invocation. - checker._thread.join() - mock_fetch.assert_called_once() - mock_write.assert_called_once_with("3.0.0") - - @patch("rsconnect.version_check._write_cache") - @patch("rsconnect.version_check._fetch_latest_version", return_value="2.0.0") - @patch("rsconnect.version_check._read_cache", return_value=(False, None)) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_absent_cache_blocks_briefly_and_warns(self, _disabled, _dev, _read, mock_fetch, mock_write): - checker = BackgroundVersionCheck() - checker.start() - # With no cached value, the in-flight fetch is given a bounded chance to - # finish so even a cold cache (first run, or an ephemeral environment) - # can still warn this run -- not just refresh for the next one. - assert checker._thread is not None - message = checker.get_warning_message() - assert message is not None - assert "2.0.0" in message - checker._thread.join() - mock_write.assert_called_once_with("2.0.0") - - @patch("rsconnect.version_check._read_cache", return_value=(True, None)) - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_no_warning_when_cache_has_no_version(self, _disabled, _dev, _read): - checker = BackgroundVersionCheck() - checker.start() - assert checker.get_warning_message() is None - - @patch("rsconnect.version_check._PYPI_TIMEOUT_SECONDS", 0.2) - @patch("rsconnect.version_check._write_cache") - @patch("rsconnect.version_check._read_cache", return_value=(False, None)) - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_hung_fetch_does_not_block_beyond_timeout(self, _disabled, _dev, _read, _write): - # A fetch that never returns (network black hole) must not hang the CLI: - # the cold-cache wait is bounded by _PYPI_TIMEOUT_SECONDS, after which the - # run proceeds with no hint and the daemon thread is left behind. - release = threading.Event() - - def hung_fetch(): - release.wait(timeout=30) # Far longer than the join timeout. - return "99.0.0" +@httpretty.activate(allow_net_connect=False) +def test_incompatible_latest_is_reported_and_cached(release_cli): + _pypi({"version": "99.0.0", "requires_python": ">=100"}) + result = _deploy() + python_version = platform.python_version() + assert result.exit_code != 0 + assert "99.0.0" not in result.stdout + assert "99.0.0" in result.stderr + assert ">=100" in result.stderr + assert f"Python {python_version}" in result.stderr + assert "uv tool install rsconnect-python" in result.stderr + assert "pip install --upgrade" not in result.stderr + assert json.loads(_cache_path().read_text())["requires_python"] == ">=100" + httpretty.reset() + cached = _deploy() + assert "uv tool install rsconnect-python" in cached.stderr + assert not httpretty.latest_requests() + + +@pytest.mark.parametrize("requirement", [">=3.0", None, "not a specifier", 42]) +@httpretty.activate(allow_net_connect=False) +def test_compatible_or_unknown_requirement_keeps_upgrade_hint(release_cli, requirement): + _pypi({"version": "99.0.0", "requires_python": requirement}) + result = _deploy() + assert ( + "A new version of rsconnect-python is available: 99.0.0 (you have 1.0.0).\n" + "Upgrade with: pip install --upgrade rsconnect-python" + ) in result.stderr + assert "uv tool install" not in result.stderr + + +@httpretty.activate(allow_net_connect=False) +def test_missing_requirement_in_pypi_response_is_compatible(release_cli): + _pypi({"version": "99.0.0"}) + assert "pip install --upgrade rsconnect-python" in _deploy().stderr + assert json.loads(_cache_path().read_text())["requires_python"] is None + + +@httpretty.activate(allow_net_connect=False) +def test_legacy_cache_refreshes_without_blocking(release_cli): + _write_cache(latest="98.0.0") + request_started = threading.Event() + allow_response = threading.Event() + response_sent = threading.Event() + + def response(request, uri, headers): + request_started.set() + allow_response.wait(timeout=5) + response_sent.set() + return (200, headers, json.dumps({"info": {"version": "99.0.0", "requires_python": ">=100"}})) + + httpretty.register_uri(httpretty.GET, "https://pypi.org/pypi/rsconnect-python/json", body=response) + try: + result = _deploy() + assert "98.0.0" in result.stderr + assert "pip install --upgrade rsconnect-python" in result.stderr + assert request_started.wait(timeout=2) + finally: + allow_response.set() + assert response_sent.wait(timeout=2) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: try: - with patch("rsconnect.version_check._fetch_latest_version", side_effect=hung_fetch): - checker = BackgroundVersionCheck() - checker.start() - assert checker._thread is not None - assert checker._thread.daemon # Never blocks interpreter exit. - start = time.monotonic() - message = checker.get_warning_message() - elapsed = time.monotonic() - start - # Returned promptly (well under the 30s fetch) with no hint this run. - assert message is None - assert elapsed < 5 - finally: - release.set() # Let the background thread unwind. - - @patch("rsconnect.version_check._read_cache") - @patch("rsconnect.version_check._is_dev_version", return_value=True) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_no_thread_for_dev_version(self, _disabled, _dev, mock_read): - checker = BackgroundVersionCheck() - checker.start() - assert checker._thread is None - mock_read.assert_not_called() - assert checker.get_warning_message() is None - - @patch("rsconnect.version_check._read_cache") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=True) - def test_no_thread_when_disabled(self, _disabled, _dev, mock_read): - checker = BackgroundVersionCheck() - checker.start() - assert checker._thread is None - mock_read.assert_not_called() - assert checker.get_warning_message() is None - - -class TestCLIIntegration: - @patch("rsconnect.version_check._read_cache", return_value=(True, "99.0.0")) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_warning_on_deploy_command_stderr(self, _disabled, _dev, _read): - runner = _cli_runner() - result = runner.invoke(cli, ["deploy", "_version_check_test_noop"]) - assert result.exit_code == 0 - # Use stdout (not output): in Click >= 8.2 result.output is the combined - # stream, while stdout stays stderr-free across Click versions. - assert "99.0.0" not in result.stdout - assert "99.0.0" in result.stderr - - @patch("rsconnect.version_check._read_cache", return_value=(True, "99.0.0")) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_warning_on_failed_deploy_command(self, _disabled, _dev, _read): - runner = _cli_runner() - result = runner.invoke(cli, ["deploy", "_version_check_test_fail"]) - assert result.exit_code != 0 - # The hint prints even though the deploy failed and exited non-zero. - assert "99.0.0" in result.stderr - - @patch("rsconnect.version_check._write_cache") - @patch("rsconnect.version_check._read_cache", return_value=(False, None)) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_warning_on_failed_deploy_with_cold_cache(self, _disabled, _dev, _read, _write): - # The original regression: a fast failure (missing requirements.txt, etc.) - # with no cache. The deploy raises and exits almost instantly, so a fetch - # with any real latency would lose the race -- the warning only prints - # because get_warning_message blocks briefly on the cold cache. The slow - # fetch below makes that race deterministic: without the blocking join the - # thread couldn't have set the version in time. - def slow_fetch(): - time.sleep(0.3) - return "99.0.0" - - runner = _cli_runner() - with patch("rsconnect.version_check._fetch_latest_version", side_effect=slow_fetch): - result = runner.invoke(cli, ["deploy", "_version_check_test_fail"]) - assert result.exit_code != 0 - assert "99.0.0" in result.stderr - - @patch("rsconnect.version_check._read_cache", return_value=(True, None)) - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_no_warning_when_current(self, _disabled, _dev, _read): - runner = _cli_runner() - result = runner.invoke(cli, ["deploy", "_version_check_test_noop"]) - assert result.exit_code == 0 - assert "new version" not in result.stderr - - @patch("rsconnect.version_check._read_cache", return_value=(True, "99.0.0")) - @patch("rsconnect.version_check.VERSION", "1.0.0") - @patch("rsconnect.version_check._is_dev_version", return_value=False) - @patch("rsconnect.version_check._is_check_disabled", return_value=False) - def test_no_check_on_non_deploy_command(self, _disabled, _dev, _read): - runner = _cli_runner() - result = runner.invoke(cli, ["version"]) - assert result.exit_code == 0 + data = json.loads(_cache_path().read_text()) + except json.JSONDecodeError: + continue + if data.get("requires_python") == ">=100": + break + time.sleep(0.01) + assert data["latest"] == "99.0.0" + assert data["requires_python"] == ">=100" + assert "uv tool install rsconnect-python" in _deploy().stderr + + +@pytest.mark.parametrize("requirement", [">=3.0", ">=100"]) +@httpretty.activate(allow_net_connect=False) +def test_disabled_suppresses_both_messages(release_cli, monkeypatch, requirement): + _write_cache(latest="99.0.0", requires_python=requirement) + monkeypatch.setenv("RSCONNECT_DISABLE_VERSION_CHECK", "true") + result = _deploy() + assert "99.0.0" not in result.stderr + assert "pip install --upgrade" not in result.stderr + assert "uv tool install" not in result.stderr + assert not httpretty.latest_requests() + + +@httpretty.activate(allow_net_connect=False) +def test_non_deploy_and_current_release_do_not_warn(release_cli): + _pypi({"version": "1.0.0", "requires_python": ">=100"}) + result = _runner().invoke(cli, ["version"]) + assert "99.0.0" not in result.stderr + assert not httpretty.latest_requests() + result = _deploy() + assert "uv tool install" not in result.stderr + assert "pip install --upgrade" not in result.stderr + + +@httpretty.activate(allow_net_connect=False) +def test_expired_cache_refreshes(release_cli): + _write_cache(latest=None, requires_python=None, checked_at=time.time() - 90000) + _pypi({"version": "99.0.0", "requires_python": ">=100"}) + assert "uv tool install rsconnect-python" in _deploy().stderr + + +@httpretty.activate(allow_net_connect=False) +def test_cold_cache_waits_for_slow_response(release_cli): + def response(request, uri, headers): + time.sleep(0.2) + return (200, headers, json.dumps({"info": {"version": "99.0.0", "requires_python": ">=100"}})) + + httpretty.register_uri(httpretty.GET, "https://pypi.org/pypi/rsconnect-python/json", body=response) + assert "uv tool install rsconnect-python" in _deploy().stderr + + +@httpretty.activate(allow_net_connect=False) +def test_failed_fetch_is_cached(release_cli): + httpretty.register_uri(httpretty.GET, "https://pypi.org/pypi/rsconnect-python/json", status=503, body="") + assert "pip install --upgrade" not in _deploy().stderr + assert json.loads(_cache_path().read_text())["latest"] is None + httpretty.reset() + assert "pip install --upgrade" not in _deploy().stderr + assert not httpretty.latest_requests() + + +@httpretty.activate(allow_net_connect=False) +def test_development_release_skips_check(release_cli, monkeypatch): + monkeypatch.setattr(rsconnect, "VERSION", "1.0.0.dev1") + importlib.reload(rsconnect.version_check) + _write_cache(latest="99.0.0", requires_python=">=100") + assert "99.0.0" not in _deploy().stderr + assert not httpretty.latest_requests() + + +@httpretty.activate(allow_net_connect=False) +def test_corrupt_cache_refreshes(release_cli): + path = _cache_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("{invalid json") + _pypi({"version": "99.0.0", "requires_python": ">=100"}) + assert "uv tool install rsconnect-python" in _deploy().stderr + + +@httpretty.activate(allow_net_connect=False) +def test_cold_cache_wait_is_bounded(release_cli): + release_response = threading.Event() + request_started = threading.Event() + + def response(request, uri, headers): + request_started.set() + release_response.wait(timeout=10) + return (200, headers, json.dumps({"info": {"version": "99.0.0", "requires_python": ">=100"}})) + + httpretty.register_uri(httpretty.GET, "https://pypi.org/pypi/rsconnect-python/json", body=response) + try: + started = time.monotonic() + result = _deploy() + elapsed = time.monotonic() - started + assert request_started.is_set() + assert elapsed < 5 assert "99.0.0" not in result.stderr - # The check never runs for non-deploy commands, so the cache isn't even read. - _read.assert_not_called() + finally: + release_response.set() + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + try: + if "requires_python" in json.loads(_cache_path().read_text()): + break + except (FileNotFoundError, json.JSONDecodeError): + pass + time.sleep(0.01) + else: + pytest.fail("Background refresh did not finish") From b421deec02d1b4ab14cc6426d21fa1b09536669e Mon Sep 17 00:00:00 2001 From: Taylor Steinberg Date: Tue, 10 Nov 2026 11:54:04 -0500 Subject: [PATCH 2/2] fix: select compatible Python in upgrade notice --- rsconnect/version_check.py | 4 +++- tests/test_version_check.py | 24 ++++++++++++++++++------ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/rsconnect/version_check.py b/rsconnect/version_check.py index 245e1cd06..a47225165 100644 --- a/rsconnect/version_check.py +++ b/rsconnect/version_check.py @@ -13,6 +13,7 @@ import json import os import platform +import sys import threading import time from http.client import HTTPSConnection @@ -124,10 +125,11 @@ def _update_message(release: Optional[_Release]) -> Optional[str]: except InvalidSpecifier: compatible = True if not compatible: + force = "" if os.path.isfile(join(sys.prefix, "uv-receipt.toml")) else "--force " return ( f"The latest version of rsconnect-python ({release.version}) requires Python " f"{release.requires_python}, but you are running Python {python_version}.\n" - "Install it with: uv tool install rsconnect-python" + f'Install it with: uv tool install {force}--python "{release.requires_python}" rsconnect-python' ) return ( f"A new version of rsconnect-python is available: {release.version} " diff --git a/tests/test_version_check.py b/tests/test_version_check.py index f0f847d7b..2826b726b 100644 --- a/tests/test_version_check.py +++ b/tests/test_version_check.py @@ -1,6 +1,7 @@ import importlib import json import platform +import sys import threading import time @@ -71,16 +72,27 @@ def test_incompatible_latest_is_reported_and_cached(release_cli): assert "99.0.0" in result.stderr assert ">=100" in result.stderr assert f"Python {python_version}" in result.stderr - assert "uv tool install rsconnect-python" in result.stderr + assert '--python ">=100" rsconnect-python' in result.stderr assert "pip install --upgrade" not in result.stderr assert json.loads(_cache_path().read_text())["requires_python"] == ">=100" httpretty.reset() cached = _deploy() - assert "uv tool install rsconnect-python" in cached.stderr + assert '--python ">=100" rsconnect-python' in cached.stderr assert not httpretty.latest_requests() +@pytest.mark.parametrize("has_receipt", [True, False]) +@httpretty.activate(allow_net_connect=False) +def test_incompatible_notice_install_command(release_cli, monkeypatch, has_receipt): + monkeypatch.setattr(sys, "prefix", str(release_cli)) + if has_receipt: + (release_cli / "uv-receipt.toml").touch() + _pypi({"version": "99.0.0", "requires_python": ">=100, <200"}) + force = "" if has_receipt else "--force " + assert f'uv tool install {force}--python ">=100, <200" rsconnect-python' in _deploy().stderr + + @pytest.mark.parametrize("requirement", [">=3.0", None, "not a specifier", 42]) @httpretty.activate(allow_net_connect=False) def test_compatible_or_unknown_requirement_keeps_upgrade_hint(release_cli, requirement): @@ -133,7 +145,7 @@ def response(request, uri, headers): time.sleep(0.01) assert data["latest"] == "99.0.0" assert data["requires_python"] == ">=100" - assert "uv tool install rsconnect-python" in _deploy().stderr + assert "uv tool install" in _deploy().stderr @pytest.mark.parametrize("requirement", [">=3.0", ">=100"]) @@ -163,7 +175,7 @@ def test_non_deploy_and_current_release_do_not_warn(release_cli): def test_expired_cache_refreshes(release_cli): _write_cache(latest=None, requires_python=None, checked_at=time.time() - 90000) _pypi({"version": "99.0.0", "requires_python": ">=100"}) - assert "uv tool install rsconnect-python" in _deploy().stderr + assert "uv tool install" in _deploy().stderr @httpretty.activate(allow_net_connect=False) @@ -173,7 +185,7 @@ def response(request, uri, headers): return (200, headers, json.dumps({"info": {"version": "99.0.0", "requires_python": ">=100"}})) httpretty.register_uri(httpretty.GET, "https://pypi.org/pypi/rsconnect-python/json", body=response) - assert "uv tool install rsconnect-python" in _deploy().stderr + assert "uv tool install" in _deploy().stderr @httpretty.activate(allow_net_connect=False) @@ -201,7 +213,7 @@ def test_corrupt_cache_refreshes(release_cli): path.parent.mkdir(parents=True, exist_ok=True) path.write_text("{invalid json") _pypi({"version": "99.0.0", "requires_python": ">=100"}) - assert "uv tool install rsconnect-python" in _deploy().stderr + assert "uv tool install" in _deploy().stderr @httpretty.activate(allow_net_connect=False)