Skip to content
39 changes: 37 additions & 2 deletions .github/workflows/continuous-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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
23 changes: 13 additions & 10 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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'
Expand All @@ -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: |
Expand Down
7 changes: 6 additions & 1 deletion src/solarwindpy/solar_activity/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`."""
Expand Down
8 changes: 6 additions & 2 deletions tests/fitfunctions/test_p0_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import contextlib
import inspect
import logging
import os
import re
import subprocess
import sys
Expand Down Expand Up @@ -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


Expand Down
4 changes: 2 additions & 2 deletions tests/plotting/labels/test_elemental_abundance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
30 changes: 30 additions & 0 deletions tests/solar_activity/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 3 additions & 1 deletion tests/solar_activity/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand Down
12 changes: 9 additions & 3 deletions tests/test_commit_message_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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(
Expand Down
16 changes: 11 additions & 5 deletions tests/test_declared_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]


Expand Down Expand Up @@ -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
Expand Down
Loading