diff --git a/CHANGELOG.md b/CHANGELOG.md index c62d5af2e..8c5aaa344 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `Scatter.make_plot(connect=True)`: with a varying z, a colour in `connect_kwargs` replaced the + segments' z colouring, so they no longer matched the colorbar. The segments now keep the + colormap and the colour is ignored with a `UserWarning` naming its key. Without a varying z, + every spelling of the colour (`color`, `c`, `colors`, `edgecolor`, `edgecolors`, `ec`) now sets + the segments' colour; before, only `color` did, `c` raised `AttributeError`, and the others were + overridden by the points' colour. Giving two of them raises `TypeError`. +- Release automation: the conda-forge tracking issue now reads the sdist's SHA256 from PyPI's + JSON API, waiting up to ten minutes with backoff while a new release is not yet listed, instead + of downloading the file and failing on the CDN's early 404. Its body fills in the version, + checksum and dependency comparison, which went out as literal placeholders, and its Git Commit + line names the released commit rather than the annotated tag object. `--max-wait SECONDS` shortens the wait for + local runs. + ## [0.5.0] - 2026-11-05 ### Changed - BREAKING CHANGES diff --git a/pyproject.toml b/pyproject.toml index 9d74e8df7..50dc09609 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,6 +126,7 @@ test = [ "pytest-cov>=6.0", "packaging>=23.0", "pyyaml>=6.0", # tests/test_declared_versions.py reads YAML + "requests>=2.31", # tests/test_update_conda_feedstock.py stubs requests.get ] docs = [ "sphinx>=7.0", @@ -142,6 +143,7 @@ dev = [ "pytest>=9.0", "pytest-cov>=6.0", "pyyaml>=6.0", # tests/test_declared_versions.py reads YAML + "requests>=2.31", # tests/test_update_conda_feedstock.py stubs requests.get # Documentation tools "sphinx>=7.0", "sphinx_rtd_theme>=2.0", diff --git a/scripts/update_conda_feedstock.py b/scripts/update_conda_feedstock.py index 5a2356be1..372da6d0b 100644 --- a/scripts/update_conda_feedstock.py +++ b/scripts/update_conda_feedstock.py @@ -2,8 +2,9 @@ """Automate conda-forge feedstock updates for SolarWindPy releases. This script automates the process of updating the conda-forge feedstock -after a new PyPI release. It handles version updates, SHA256 calculation, -and creates GitHub issues for tracking. +after a new PyPI release. It reads the sdist's SHA256 from PyPI's JSON API, +waiting with backoff while the new release is not yet listed, and creates a +GitHub issue for tracking. Usage: python scripts/update_conda_feedstock.py v0.1.5 @@ -12,11 +13,11 @@ """ import argparse -import hashlib import json import os import subprocess import sys +import time from pathlib import Path from typing import Optional, Tuple @@ -26,6 +27,13 @@ # Add project root to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) +# How long to wait for PyPI to list a new release and its sdist, and the +# backoff between attempts: the first wait, the factor, and the cap. +RELEASE_WAIT = 600 +BACKOFF_START = 15 +BACKOFF_FACTOR = 2 +BACKOFF_MAX = 120 + class CondaFeedstockUpdater: """Handles automated conda-forge feedstock updates. @@ -39,6 +47,7 @@ def __init__( package_name: str = "solarwindpy", feedstock_repo: str = "conda-forge/solarwindpy-feedstock", fork_owner: Optional[str] = None, + release_wait: float = RELEASE_WAIT, ): """Initialize the feedstock updater. @@ -50,11 +59,18 @@ def __init__( GitHub repository for the feedstock (org/repo format) fork_owner : str, optional GitHub username for fork (if different from current user) + release_wait : float + Total seconds to wait for PyPI to list a release and its sdist """ self.package_name = package_name self.feedstock_repo = feedstock_repo self.fork_owner = fork_owner or self._get_github_username() self.project_root = Path(__file__).parent.parent + self.release_wait = release_wait + # Injectable so the tests need not wait out the backoff. + self._sleep = time.sleep + # One fetch per version serves both validation and the checksum. + self._release_json = {} def _get_github_username(self) -> str: """Get current GitHub username from git config or environment. @@ -119,9 +135,10 @@ def verify_git_tag_provenance( print(f"⚠️ Git tag {tag_name} not found in repository") return False, None - # Get commit SHA for the tag + # The commit the tag names; a bare annotated tag resolves to the + # tag object, not the commit. result = subprocess.run( - ["git", "rev-parse", tag_name], + ["git", "rev-parse", f"{tag_name}^{{commit}}"], capture_output=True, text=True, check=True, @@ -245,87 +262,136 @@ def verify_github_release_integrity( print(f"⚠️ GitHub release verification skipped: {e}") return True # Permissive - don't block on errors - def validate_pypi_release(self, version_str: str, timeout: int = 10) -> bool: - """Validate that the PyPI release exists and is not a pre-release. + def fetch_release_json( + self, version_str: str, max_wait: Optional[float] = None, timeout: int = 10 + ) -> Optional[dict]: + """Return PyPI's JSON for the release, once it lists the sdist. + + Right after an upload PyPI may not list the release, or may list it + before its sdist; both are retried with exponential backoff until + ``max_wait`` seconds of waiting have passed. A release once found is + kept, so later calls for the same version do not ask PyPI again. Parameters ---------- version_str : str - Version string to validate + Version to fetch + max_wait : float, optional + Total seconds to wait between attempts before giving up; defaults + to ``release_wait`` timeout : int Request timeout in seconds Returns ------- - bool - True if valid stable release exists + dict or None + The release's JSON, or None if it never listed an sdist """ - try: - # Parse version to check for pre-release - v = version.parse(version_str) - if v.is_prerelease: - print( - f"❌ Pre-release version {version_str} - skipping feedstock update" - ) - return False - - # Check PyPI availability - url = f"https://pypi.org/pypi/{self.package_name}/{version_str}/json" - response = requests.get(url, timeout=timeout) + if version_str in self._release_json: + return self._release_json[version_str] + if max_wait is None: + max_wait = self.release_wait + url = f"https://pypi.org/pypi/{self.package_name}/{version_str}/json" + waited = 0.0 + delay = BACKOFF_START + while True: + try: + response = requests.get(url, timeout=timeout) + if response.status_code == 200: + data = response.json() + if self._sdist_entry(data) is not None: + self._release_json[version_str] = data + return data + reason = "no sdist listed yet" + else: + reason = f"status {response.status_code}" + except (requests.RequestException, ValueError) as e: + reason = str(e) - if response.status_code != 200: + if waited >= max_wait: print( - f"❌ PyPI version {version_str} not found (status: {response.status_code})" + f"❌ PyPI has no sdist for {self.package_name} v{version_str} " + f"after {waited:.0f}s ({reason})" ) - return False + return None + pause = min(delay, max_wait - waited) + print(f"⏳ PyPI not ready ({reason}); retrying in {pause:.0f}s...") + self._sleep(pause) + waited += pause + delay = min(delay * BACKOFF_FACTOR, BACKOFF_MAX) + + @staticmethod + def _sdist_entry(data: dict) -> Optional[dict]: + """Return the ``urls`` entry of the sdist in PyPI release JSON, if any.""" + for entry in data.get("urls") or []: + if entry.get("packagetype") == "sdist": + return entry + return None + + def validate_pypi_release(self, version_str: str) -> bool: + """Validate that the PyPI release exists and is not a pre-release. - data = response.json() - pypi_version = data.get("info", {}).get("version") + Parameters + ---------- + version_str : str + Version string to validate - if pypi_version != version_str: - print( - f"❌ Version mismatch: requested {version_str}, PyPI has {pypi_version}" - ) - return False + Returns + ------- + bool + True if valid stable release exists + """ + try: + v = version.parse(version_str) + except version.InvalidVersion as e: + print(f"❌ Invalid version {version_str}: {e}") + return False + if v.is_prerelease: + print(f"❌ Pre-release version {version_str} - skipping feedstock update") + return False - print(f"✅ Validated PyPI release: {self.package_name} v{version_str}") - return True + data = self.fetch_release_json(version_str) + if data is None: + return False - except Exception as e: - print(f"❌ Failed to validate PyPI release: {e}") + pypi_version = data.get("info", {}).get("version") + if pypi_version != version_str: + print( + f"❌ Version mismatch: requested {version_str}, PyPI has {pypi_version}" + ) return False - def calculate_sha256(self, version_str: str, timeout: int = 30) -> Optional[str]: - """Calculate SHA256 hash of the PyPI source distribution. + print(f"✅ Validated PyPI release: {self.package_name} v{version_str}") + return True + + def get_sdist_sha256(self, version_str: str) -> Optional[str]: + """Return the SHA256 of the release's sdist, as PyPI's JSON API lists it. + + Reading the digest PyPI computed at upload needs no download, so it + does not depend on the file CDN, which can serve a cached 404 for a + while after the upload. Parameters ---------- version_str : str - Version to download and hash - timeout : int - Download timeout in seconds + Version whose sdist to look up Returns ------- str or None SHA256 hash as hex string, or None if failed """ - url = f"https://pypi.org/packages/source/{self.package_name[0]}/{self.package_name}/{self.package_name}-{version_str}.tar.gz" - - try: - print( - f"Downloading {self.package_name} v{version_str} for SHA256 calculation..." - ) - response = requests.get(url, timeout=timeout) - response.raise_for_status() - - sha256_hash = hashlib.sha256(response.content).hexdigest() - print(f"✅ SHA256: {sha256_hash}") - return sha256_hash - - except Exception as e: - print(f"❌ Failed to calculate SHA256: {e}") + data = self.fetch_release_json(version_str) + if data is None: return None + entry = self._sdist_entry(data) + sha256_hash = entry.get("digests", {}).get("sha256") + if not sha256_hash: + print(f"❌ PyPI lists no sha256 for {entry.get('url')}") + return None + print(f"✅ sdist: {entry.get('url')}") + print(f"✅ SHA256: {sha256_hash}") + return sha256_hash def update_meta_yaml( self, version_str: str, sha256_hash: str, meta_path: Path @@ -433,36 +499,30 @@ def _get_dependency_comparison(self) -> str: ⚠️ **CRITICAL**: The autotick bot updates **version and SHA256 ONLY**, NOT dependencies! """ - def create_tracking_issue( + def build_issue_body( self, version_str: str, sha256_hash: str, - dry_run: bool = False, + comparison_output: str, commit_sha: Optional[str] = None, - ) -> Optional[str]: - """Create GitHub issue for tracking the feedstock update. + ) -> str: + """Return the tracking issue's Markdown body. Parameters ---------- version_str : str Version being updated sha256_hash : str - SHA256 hash for reference - dry_run : bool - If True, only print what would be done + SHA256 hash of the sdist + comparison_output : str + The dependency comparison, from `_get_dependency_comparison` commit_sha : str, optional Git commit SHA if provenance was verified Returns ------- - str or None - Issue URL if created successfully + str """ - title = f"Conda feedstock update for SolarWindPy v{version_str}" - - # Get dependency comparison - self._get_dependency_comparison() - body = f"""## Automated Conda Feedstock Update **Version**: `{version_str}` @@ -477,7 +537,7 @@ def create_tracking_issue( **GitHub Release**: https://github.com/blalterman/SolarWindPy/releases/tag/v{version_str} **Source Provenance**: ✅ Verified""" - body += """ + body += f""" --- @@ -489,7 +549,7 @@ def create_tracking_issue( ### Update Checklist - [x] PyPI release validated -- [x] SHA256 calculated from source distribution +- [x] SHA256 read from PyPI's listing of the source distribution - [ ] **Dependencies reviewed** (see comparison above) - [ ] Autotick bot PR created (usually 2-6 hours) - [ ] If dependencies changed: manually update bot PR @@ -550,6 +610,41 @@ def create_tracking_issue( 🤖 Generated by conda feedstock automation """ + return body + + def create_tracking_issue( + self, + version_str: str, + sha256_hash: str, + dry_run: bool = False, + commit_sha: Optional[str] = None, + ) -> Optional[str]: + """Create GitHub issue for tracking the feedstock update. + + Parameters + ---------- + version_str : str + Version being updated + sha256_hash : str + SHA256 hash for reference + dry_run : bool + If True, only print what would be done + commit_sha : str, optional + Git commit SHA if provenance was verified + + Returns + ------- + str or None + Issue URL if created successfully + """ + title = f"Conda feedstock update for SolarWindPy v{version_str}" + + body = self.build_issue_body( + version_str, + sha256_hash, + self._get_dependency_comparison(), + commit_sha=commit_sha, + ) if dry_run: print(f"🔍 DRY RUN: Would create issue '{title}'") @@ -654,8 +749,8 @@ def update_feedstock(self, version_str: str, dry_run: bool = False) -> bool: print("⚠️ Git provenance could not be verified (may be running in CI)") commit_sha = None # Ensure it's None if verification failed - # Step 2: Calculate SHA256 - sha256_hash = self.calculate_sha256(version_str) + # Step 2: Read the sdist's SHA256 from PyPI + sha256_hash = self.get_sdist_sha256(version_str) if not sha256_hash: return False @@ -731,6 +826,15 @@ def main(): parser.add_argument( "--no-issue", action="store_true", help="Skip creating tracking issue" ) + parser.add_argument( + "--max-wait", + type=float, + default=RELEASE_WAIT, + help=( + "Seconds to wait for PyPI to list the release and its sdist " + f"(default: {RELEASE_WAIT})" + ), + ) args = parser.parse_args() @@ -742,6 +846,7 @@ def main(): package_name=args.package, feedstock_repo=args.feedstock_repo, fork_owner=args.fork_owner, + release_wait=args.max_wait, ) # Run update workflow diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a864fcf0e..2a695cc51 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -10,8 +10,13 @@ from matplotlib import pyplot as plt from matplotlib.collections import LineCollection +from ..tools import _warn from . import base +# Every spelling of the segments' colour that LineCollection accepts, and +# ``c``, which ``ax.scatter`` accepts. +_COLOR_KEYS = ("color", "c", "colors", "edgecolor", "edgecolors", "ec") + class Scatter(base.ColorPlot): r"""Scatter plot of y against x, optionally colored by z. @@ -93,6 +98,10 @@ def make_plot( Passed to :class:`~matplotlib.collections.LineCollection`, e.g. ``linewidth``, ``alpha`` or ``zorder``. The defaults are a ``linewidth`` of 0.75 and a ``zorder`` just below the points'. + ``facecolor`` has no visible effect, since lines have no faces. + A colour, under any of the keys ``color``, ``c``, ``colors``, + ``edgecolor``, ``edgecolors`` or ``ec``, applies only without a + varying z (see Notes); at most one of them may be given. Not modified. kwargs: Passed to `ax.scatter`. @@ -125,9 +134,11 @@ def make_plot( When z varies, each segment is coloured by the mean z of its two points, ``(z_a + z_b) / 2``, through the points' colormap and norm, - the same objects, so the one colorbar reads both. Otherwise every - segment has the points' colour, unless ``connect_kwargs`` sets - ``color``. The segments do not set the axis limits. + the same objects, so the one colorbar reads both; a colour in + ``connect_kwargs`` is then ignored, with a ``UserWarning`` naming its + key. Otherwise every segment has the colour that ``connect_kwargs`` + sets, or the points' colour if it sets none. The segments do not set + the axis limits. """ if ax is None: fig, ax = plt.subplots() @@ -176,7 +187,8 @@ def _connect(self, ax, collection, data, zkey, connect_kwargs): zkey: str or None ``"z"`` if the points are colour-mapped, else None. connect_kwargs: Mapping or None - Passed to ``LineCollection``. + Passed to ``LineCollection``, except a colour key, which sets the + segments' colour only when `zkey` is None. Returns ------- @@ -190,14 +202,30 @@ def _connect(self, ax, collection, data, zkey, connect_kwargs): drawn &= xy[:, i] > 0 xy = xy[drawn] - kwargs = cbook.normalize_kwargs(connect_kwargs or {}, LineCollection) + kwargs = dict(connect_kwargs or {}) + given = [k for k in _COLOR_KEYS if k in kwargs] + if len(given) > 1: + raise TypeError( + f"connect_kwargs gives the colour twice, as {given!r}; give one." + ) + color = kwargs.pop(given[0]) if given else None + kwargs = cbook.normalize_kwargs(kwargs, LineCollection) kwargs.setdefault("linewidth", 0.75) kwargs.setdefault("zorder", collection.get_zorder() - 0.5) if zkey is None: - kwargs.setdefault("color", collection.get_facecolor()[0]) - segments = LineCollection(np.stack([xy[:-1], xy[1:]], axis=1), **kwargs) + if color is None: + color = collection.get_facecolor()[0] + segments = LineCollection( + np.stack([xy[:-1], xy[1:]], axis=1), color=color, **kwargs + ) else: + if given: + _warn( + f"connect_kwargs[{given[0]!r}] is ignored: z varies, so each " + "segment is coloured by the mean z of its two points through " + "the points' colormap and norm." + ) z = data.loc[:, zkey].to_numpy(dtype=float)[drawn] order = np.argsort(z, kind="stable") xy, z = xy[order], z[order] diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index aaa18a263..d5192a529 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -581,3 +581,72 @@ def test_segments_do_not_change_the_axis_limits(ax): Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) assert ax.get_xlim() == (EX.min(), EX.max()) assert ax.get_ylim() == (EY.min(), EY.max()) + + +# --------------------------------------------------------------------------- +# A colour in connect_kwargs: with a varying z the segments are colour-mapped, +# so the colour is dropped with a warning naming the key the caller typed; +# otherwise it is the segments' one colour, under any of its spellings. +# --------------------------------------------------------------------------- + +COLOR_KEYS = ["color", "c", "colors", "edgecolor", "edgecolors", "ec"] + + +@pytest.mark.parametrize("key", COLOR_KEYS) +def test_connect_colour_with_varying_z_warns_and_is_ignored(ax, key): + """With a varying z the segments keep the colormap; the colour key is named. + + ON FAILURE: the code is wrong. + """ + kwargs = {key: "red"} + with pytest.warns(UserWarning, match=rf"connect_kwargs\['{key}'\]") as record: + _, points, lc, _ = Scatter(EX, EY, EZ).make_plot( + ax=ax, connect=True, connect_kwargs=kwargs + ) + assert kwargs == {key: "red"} + assert len(record) == 1 + assert record[0].filename == __file__ + assert "colormap" in str(record[0].message) + ax.figure.canvas.draw() + expected = points.get_cmap()(points.norm(_mean_z(EZ, Z_ORDER))) + np.testing.assert_allclose(lc.get_edgecolor(), expected) + + +@pytest.mark.parametrize("key", COLOR_KEYS) +@pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) +def test_connect_colour_without_varying_z_is_honoured(ax, key, z): + """With no z, or a constant one, every spelling of the colour sets the segments'. + + ON FAILURE: the code is wrong. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + _, _, lc, _ = Scatter(EX, EY, z).make_plot( + ax=ax, connect=True, connect_kwargs={key: "red"} + ) + ax.figure.canvas.draw() + np.testing.assert_array_equal(lc.get_edgecolor(), [[1.0, 0.0, 0.0, 1.0]]) + + +@pytest.mark.parametrize("z", [None, EZ]) +def test_connect_without_a_colour_key_does_not_warn(ax, z): + """Styling the segments without a colour issues no warning. + + ON FAILURE: the code is wrong. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + Scatter(EX, EY, z).make_plot( + ax=ax, connect=True, connect_kwargs={"linewidth": 2.0} + ) + + +def test_connect_refuses_two_colour_keys(ax): + """Two spellings of the colour are ambiguous, as matplotlib's aliases are. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(TypeError, match="'color'.*'ec'"): + Scatter(EX, EY).make_plot( + ax=ax, connect=True, connect_kwargs={"color": "red", "ec": "blue"} + ) diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py new file mode 100644 index 000000000..98eb8ba1d --- /dev/null +++ b/tests/test_update_conda_feedstock.py @@ -0,0 +1,276 @@ +# Spent-When: PERMANENT(scripts/update_conda_feedstock.py is deleted) +# Supersedes: none +"""``scripts/update_conda_feedstock.py`` reads PyPI reliably and fills its issue. + +The release workflow runs the script right after the upload, when PyPI may not +yet list the release or its sdist. The script reads the sdist's SHA256 from +PyPI's JSON API, retrying with a bounded backoff, and never downloads the file. + +The network is the boundary: ``requests.get`` is replaced by a scripted +sequence of responses, ``subprocess.run`` by a stub where the test would run +``gh`` or the dependency comparison, and the backoff's sleep by a recorder. +The commit SHA is checked against a real annotated tag in a temporary repo. +""" + +import importlib.util +import os +import re +import subprocess +from pathlib import Path + +import pytest +import requests + +REPO_ROOT = Path(__file__).resolve().parents[1] + +_spec = importlib.util.spec_from_file_location( + "update_conda_feedstock", REPO_ROOT / "scripts" / "update_conda_feedstock.py" +) +feedstock = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(feedstock) + +VERSION = "0.5.0" +SHA = "ab" * 32 +JSON_URL = f"https://pypi.org/pypi/solarwindpy/{VERSION}/json" +SDIST = { + "packagetype": "sdist", + "url": f"https://files.pythonhosted.org/packages/xx/solarwindpy-{VERSION}.tar.gz", + "digests": {"sha256": SHA}, +} +WHEEL = {"packagetype": "bdist_wheel", "digests": {"sha256": "cd" * 32}} + + +class Response: + """The parts of ``requests.Response`` the script reads.""" + + def __init__(self, status_code, payload=None): + self.status_code = status_code + self._payload = payload + + def json(self): + return self._payload + + +def released(*urls): + return Response(200, {"info": {"version": VERSION}, "urls": list(urls)}) + + +def make_updater(**kwargs): + """An updater whose sleeps are recorded, not waited.""" + u = feedstock.CondaFeedstockUpdater(fork_owner="someone", **kwargs) + u.slept = [] + u._sleep = u.slept.append + return u + + +@pytest.fixture +def updater(): + return make_updater() + + +@pytest.fixture +def pypi(monkeypatch): + """Serve ``requests.get`` from a list of responses; record the URLs asked for.""" + calls = [] + responses = [] + + def get(url, timeout): + calls.append(url) + r = responses.pop(0) + if isinstance(r, Exception): + raise r + return r + + monkeypatch.setattr(feedstock.requests, "get", get) + return responses, calls + + +def test_a_404_is_retried_with_backoff_until_the_release_is_listed(updater, pypi): + """The CDN-style 404s right after an upload are waited out, not fatal. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [Response(404), Response(404), released(WHEEL, SDIST)] + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] * 3 + assert updater.slept == [15, 30] + + +def test_a_release_without_its_sdist_yet_is_retried(updater, pypi): + """PyPI listing the wheel before the sdist is not yet ready. + + ON FAILURE: the code is wrong. + """ + responses, _ = pypi + responses += [ + released(WHEEL), + requests.ConnectionError("reset"), + released(WHEEL, SDIST), + ] + assert updater.get_sdist_sha256(VERSION) == SHA + assert updater.slept == [15, 30] + + +def test_the_wait_is_bounded(updater, pypi): + """A release that never appears gives up after ``RELEASE_WAIT`` seconds. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [Response(404)] * 50 + assert updater.get_sdist_sha256(VERSION) is None + assert updater.slept == [15, 30, 60, 120, 120, 120, 120, 15] + assert sum(updater.slept) == feedstock.RELEASE_WAIT + assert len(calls) == len(updater.slept) + 1 + + +def test_the_sha256_is_read_from_the_json_without_downloading_the_sdist(updater, pypi): + """Only the JSON API is requested; the digest is PyPI's, not recomputed. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [released(SDIST)] + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] + + +def test_validation_waits_for_the_release_and_checks_its_version(updater, pypi): + """``validate_pypi_release`` shares the retrying fetch and checks the version. + + ON FAILURE: the code is wrong. + """ + responses, _ = pypi + responses += [Response(404), released(SDIST)] + assert updater.validate_pypi_release(VERSION) + assert updater.slept == [15] + + +def test_a_version_mismatch_is_refused(updater, pypi): + """ON FAILURE: the code is wrong.""" + responses, _ = pypi + responses += [Response(200, {"info": {"version": "0.4.1"}, "urls": [SDIST]})] + assert not updater.validate_pypi_release(VERSION) + + +def test_one_fetch_serves_validation_and_the_checksum(updater, pypi): + """The release is validated and hashed from one response, asked for once. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [released(SDIST)] + assert updater.validate_pypi_release(VERSION) + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] + + +def test_a_null_urls_list_is_a_release_without_its_sdist(updater, pypi): + """ON FAILURE: the code is wrong.""" + responses, _ = pypi + responses += [ + Response(200, {"info": {"version": VERSION}, "urls": None}), + released(SDIST), + ] + assert updater.get_sdist_sha256(VERSION) == SHA + assert updater.slept == [15] + + +def test_release_wait_bounds_the_wait(pypi): + """With ``release_wait=0`` a missing release fails after one request. + + ON FAILURE: the code is wrong. + """ + u = make_updater(release_wait=0) + responses, calls = pypi + responses += [Response(404)] + assert u.get_sdist_sha256(VERSION) is None + assert calls == [JSON_URL] + assert u.slept == [] + + +def test_the_max_wait_flag_reaches_the_updater(monkeypatch): + """ON FAILURE: the code is wrong.""" + made = {} + + class Recorder: + def __init__(self, **kwargs): + made.update(kwargs) + + def update_feedstock(self, version_str, dry_run=False): + return True + + monkeypatch.setattr(feedstock, "CondaFeedstockUpdater", Recorder) + monkeypatch.setattr( + feedstock.sys, "argv", ["update_conda_feedstock.py", VERSION, "--max-wait", "0"] + ) + with pytest.raises(SystemExit) as exit_: + feedstock.main() + assert exit_.value.code == 0 + assert made["release_wait"] == 0 + + +def test_a_prerelease_is_refused_without_asking_pypi(updater, pypi): + """ON FAILURE: the code is wrong.""" + _, calls = pypi + assert not updater.validate_pypi_release("0.6.0rc1") + assert calls == [] + + +def test_the_issue_body_fills_every_placeholder(updater, monkeypatch): + """The issue names the version, package, hash and commit, and the comparison. + + ON FAILURE: the code is wrong. + """ + table = "DEPENDENCY COMPARISON\nnumpy>=2 | numpy >=2" + created = {} + + def run(cmd, **kwargs): + if cmd[0] == "gh": + created["body"] = cmd[cmd.index("--body") + 1] + return subprocess.CompletedProcess(cmd, 0, stdout="https://issue\n") + assert cmd[-1] == "scripts/compare_feedstock_deps.py" + return subprocess.CompletedProcess(cmd, 0, stdout=table) + + monkeypatch.setattr(feedstock.subprocess, "run", run) + url = updater.create_tracking_issue(VERSION, SHA, commit_sha="c0ffee") + assert url == "https://issue" + body = created["body"] + assert re.findall(r"\{[^{}\s]*\}", body) == [] + assert table in body + for text in (VERSION, SHA, "c0ffee", "solarwindpy-feedstock"): + assert text in body + + +def test_the_commit_sha_is_the_tagged_commit_not_the_tag_object(tmp_path, monkeypatch): + """An annotated tag is its own object; the issue reports the commit it names. + + Under a git hook, ``GIT_DIR``, ``GIT_INDEX_FILE`` and the like name the + repository being committed to; every git call here, the script's too, + would act on it, not on ``tmp_path``. They are cleared first. + ON FAILURE: the code is wrong. + """ + for name in [n for n in os.environ if n.startswith("GIT_")]: + monkeypatch.delenv(name) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + + def git(*args): + return subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], + cwd=tmp_path, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + git("init", "-q", "-b", "master") + git("commit", "-q", "--allow-empty", "-m", "release") + git("tag", "-a", f"v{VERSION}", "-m", "the release") + head = git("rev-parse", "HEAD") + assert git("rev-parse", f"v{VERSION}") != head + + u = feedstock.CondaFeedstockUpdater(fork_owner="someone") + u.project_root = tmp_path + assert u.verify_git_tag_provenance(VERSION) == (True, head)