diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml index 1801a13a0..e61a89f73 100644 --- a/.github/workflows/continuous-integration.yml +++ b/.github/workflows/continuous-integration.yml @@ -70,9 +70,42 @@ jobs: python -m build --outdir dist python scripts/check_release_artifacts.py dist + # Test suite on Windows (PyHC standard #4: support all major operating systems). + # Lint, import layering, and the release build stay on the Linux validate job. + test-windows: + runs-on: windows-latest + # The suite takes about 2 minutes here; bound a hung test well below + # GitHub's 6-hour default. + timeout-minutes: 30 + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v7 + with: + python-version: ${{ env.PYTHON_VERSION }} + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + # tests/test_release_artifacts.py builds with --no-isolation and needs these + python -m pip install build setuptools_scm wheel + + - name: Run core tests + run: | + pytest --tb=short --disable-warnings tests/ + # Summary job ci-summary: - needs: [validate] + needs: [validate, test-windows] runs-on: ubuntu-latest if: always() @@ -85,9 +118,11 @@ jobs: echo "" echo "Job Results:" echo "- Quick Validation: ${{ needs.validate.result }}" + echo "- Windows Tests: ${{ needs.test-windows.result }}" echo "" - if [[ "${{ needs.validate.result }}" == "success" ]]; then + if [[ "${{ needs.validate.result }}" == "success" && "${{ needs.test-windows.result }}" == "success" ]]; then echo "✅ PR validation passed - ready for review" else echo "❌ PR validation failed - requires fixes" + exit 1 fi diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4f1d920f8..d224c43a7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -21,15 +21,19 @@ on: type: boolean jobs: - # Release gate: the full suite on every declared Python, on Linux and macOS. + # Release gate: the full suite on every declared Python, on Linux, macOS, and Windows. # build-and-publish needs it, so nothing is built or uploaded unless every cell passes. platform-matrix: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] python-version: ['3.12', '3.13', '3.14'] fail-fast: false + # Every run step is bash, so the same scripts work on the Windows runner. + defaults: + run: + shell: bash steps: - uses: actions/checkout@v7 @@ -39,14 +43,10 @@ jobs: - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} - - - uses: actions/cache@v6 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }} - restore-keys: | - ${{ runner.os }}-pip-${{ matrix.python-version }}- - ${{ runner.os }}-pip- + # setup-python finds pip's cache directory on each OS; ~/.cache/pip + # is not it on macOS or Windows. + cache: pip + cache-dependency-path: pyproject.toml - name: Install system dependencies (Linux) if: runner.os == 'Linux' @@ -62,6 +62,9 @@ jobs: run: | python -m pip install --upgrade pip pip install -e ".[dev]" + # tests/test_release_artifacts.py builds with --no-isolation and + # skips without these, so install them to run it in the release gate. + pip install build setuptools_scm wheel - name: Run comprehensive tests run: | diff --git a/src/solarwindpy/solar_activity/base.py b/src/solarwindpy/solar_activity/base.py index 1aaf00e20..fcd22005d 100644 --- a/src/solarwindpy/solar_activity/base.py +++ b/src/solarwindpy/solar_activity/base.py @@ -191,7 +191,12 @@ def ctime(self): @property def age(self): r"""Time since :attr:`ctime`.""" - return pd.Timestamp.now() - self.ctime + # One reading of the cached copy's age. Subtracting ctime from a + # separate now() falls short by the time spent computing ctime. + age = cache.cached_age(self.url) + if age is None: + return pd.Timestamp.now() - pd.to_datetime(0) + return age def set_key(self, key): r"""Set :attr:`key`.""" diff --git a/tests/fitfunctions/test_p0_contract.py b/tests/fitfunctions/test_p0_contract.py index 1d35a8584..1932ae892 100644 --- a/tests/fitfunctions/test_p0_contract.py +++ b/tests/fitfunctions/test_p0_contract.py @@ -13,6 +13,7 @@ import contextlib import inspect import logging +import os import re import subprocess import sys @@ -244,13 +245,16 @@ def test_insufficient_data_check_survives_python_O(tmp_path): " print('no error')\n" ) root = Path(solarwindpy.__file__).resolve().parents[1] + # Inherit the environment: Windows needs SYSTEMROOT to start a process and + # USERPROFILE for Path.home(), which astropy calls on import. + env = {**os.environ, "PYTHONPATH": str(root)} out = subprocess.run( [sys.executable, "-O", str(script)], capture_output=True, text=True, - env={"PYTHONPATH": str(root), "PATH": ""}, - check=True, + env=env, ) + assert out.returncode == 0, out.stderr assert out.stdout.strip() == "raised", out.stdout + out.stderr diff --git a/tests/plotting/labels/test_elemental_abundance.py b/tests/plotting/labels/test_elemental_abundance.py index 1db3762ba..5dff6f052 100644 --- a/tests/plotting/labels/test_elemental_abundance.py +++ b/tests/plotting/labels/test_elemental_abundance.py @@ -165,8 +165,8 @@ def test_path_special_characters(self): warnings.simplefilter("ignore") abundance = ElementalAbundance("C/N", "H", photospheric=False) path = abundance.path - # Path should contain separator - assert "C/N-OV-H" in str(path) + # The "/" in the species becomes a path separator on every OS. + assert path == Path("C/N-OV-H") class TestElementalAbundanceSetMethods: diff --git a/tests/solar_activity/test_base.py b/tests/solar_activity/test_base.py index 923ee189d..d8b8a980c 100644 --- a/tests/solar_activity/test_base.py +++ b/tests/solar_activity/test_base.py @@ -260,6 +260,36 @@ def test_age_is_the_time_since_the_cache_was_written(remote): assert pd.Timedelta(days=5) <= loader.age < pd.Timedelta(days=5, minutes=1) +class AgeShortError(AssertionError): + """``age`` came out shorter than the cached copy's age.""" + + +def test_age_does_not_depend_on_when_the_clock_is_read(remote, monkeypatch): + """``age`` is the cached copy's age, however the wall clock moves while it is read. + + Chosen input: the cached copy is moved five days back, then the clock + (``pd.Timestamp.now``, a clock boundary) is faked to advance one minute on + every read. An age assembled from two clock reads comes out a minute + short; the cached copy is still at least five days old. + + ON FAILURE: the code is wrong. + """ + CacheLoader.DOWNLOADED.to_csv(remote) + loader = CacheLoader("daily", remote.as_uri()) + loader.load_data() + backdate(loader.url, 5) + clock = {"now": pd.Timestamp.now()} + + def advancing_now(tz=None): + clock["now"] += pd.Timedelta(minutes=1) + return clock["now"] + + monkeypatch.setattr(pd.Timestamp, "now", staticmethod(advancing_now)) + age = loader.age + if age < pd.Timedelta(days=5): + raise AgeShortError(f"age {age} is shorter than five days") + + def test_load_data_downloads_again_when_the_cache_is_stale(remote): """A cached copy older than ``max_age`` is replaced by a new download. diff --git a/tests/solar_activity/test_cache.py b/tests/solar_activity/test_cache.py index d9219fc0b..8bf22ec9b 100644 --- a/tests/solar_activity/test_cache.py +++ b/tests/solar_activity/test_cache.py @@ -266,7 +266,8 @@ def snapshot(): def test_a_first_run_on_a_clean_home_creates_the_cache(tmp_path, monkeypatch): """With no cache folder yet, the first fetch creates ``~/.cache/solarwindpy``. - Chosen input: HOME is an empty directory under ``tmp_path`` and + Chosen input: HOME (USERPROFILE on Windows) is an empty directory under + ``tmp_path`` and ``XDG_CACHE_HOME`` is unset, so astropy (8 or later) resolves the default location and must create every level of it. @@ -285,6 +286,7 @@ def test_a_first_run_on_a_clean_home_creates_the_cache(tmp_path, monkeypatch): home = tmp_path / "home" home.mkdir() monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) # Path.home() on Windows monkeypatch.delenv("XDG_CACHE_HOME", raising=False) expected = home / ".cache" / "solarwindpy" assert get_cache_dir_path("solarwindpy", ensure_exists=False) == expected diff --git a/tests/test_commit_message_hook.py b/tests/test_commit_message_hook.py index ba84e54e1..bf880143d 100644 --- a/tests/test_commit_message_hook.py +++ b/tests/test_commit_message_hook.py @@ -2,6 +2,7 @@ # Supersedes: none """The commit-msg hook accepts every Conventional Commits form the project uses.""" +import shutil import subprocess from pathlib import Path @@ -12,12 +13,17 @@ ) +# Resolve bash on PATH. A bare "bash" makes Windows search System32 before +# PATH and run the WSL launcher, which cannot see this Windows path. +BASH = shutil.which("bash") + + def _check(tmp_path, message): + if BASH is None: + pytest.skip("bash is not on PATH") msg = tmp_path / "COMMIT_EDITMSG" msg.write_text(message) - return subprocess.run( - ["bash", str(SCRIPT), str(msg)], capture_output=True - ).returncode + return subprocess.run([BASH, str(SCRIPT), str(msg)], capture_output=True).returncode @pytest.mark.parametrize( diff --git a/tests/test_declared_versions.py b/tests/test_declared_versions.py index af27771b0..232012c0c 100644 --- a/tests/test_declared_versions.py +++ b/tests/test_declared_versions.py @@ -30,7 +30,9 @@ def _requires_python(): - pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text()) + pyproject = tomllib.loads( + (REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8") + ) return pyproject["project"]["requires-python"] @@ -62,25 +64,29 @@ def declared_python_versions(): """Return ``(site, version)`` for every Python version the repo declares.""" found = [] - pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text()) + pyproject = tomllib.loads( + (REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8") + ) for c in pyproject["project"]["classifiers"]: m = re.fullmatch(r"Programming Language :: Python :: (3\.\d+)", c) if m: found.append(("pyproject.toml: classifiers", m.group(1))) - tox = (REPO_ROOT / "tox.ini").read_text() + tox = (REPO_ROOT / "tox.ini").read_text(encoding="utf-8") envlist = re.search(r"^envlist\s*=\s*(.+)$", tox, re.MULTILINE).group(1) for major, minor in re.findall(r"py(\d)(\d+)", envlist): found.append(("tox.ini: envlist", f"{major}.{minor}")) - rtd = yaml.safe_load((REPO_ROOT / ".readthedocs.yaml").read_text()) + rtd = yaml.safe_load((REPO_ROOT / ".readthedocs.yaml").read_text(encoding="utf-8")) found.append( (".readthedocs.yaml: build.tools.python", str(rtd["build"]["tools"]["python"])) ) for wf in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml")): _workflow_versions( - yaml.safe_load(wf.read_text()), f".github/workflows/{wf.name}", found + yaml.safe_load(wf.read_text(encoding="utf-8")), + f".github/workflows/{wf.name}", + found, ) return found