Repository navigation
Expand file tree
/
Copy pathnoxfile.py
More file actions
472 lines (390 loc) · 15.1 KB
/
Copy pathnoxfile.py
File metadata and controls
472 lines (390 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
from __future__ import annotations
import enum
import json
import os
from dataclasses import KW_ONLY, dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING
import nox
if TYPE_CHECKING:
from collections.abc import Generator
from nox import Session
# Use uv if available, otherwise fall back to default
nox.options.default_venv_backend = "uv|virtualenv"
# Fail if using an external program without external=True
nox.options.error_on_external_run = True
PYPROJECT = nox.project.load_toml("pyproject.toml")
PY_STABLE = ["3.11", "3.12", "3.13", "3.14"]
PY_UNSTABLE = "3.15"
PY_DEFAULT = "3.13"
PY_OLDEST = PY_STABLE[0]
PY_NEWEST = PY_STABLE[-1]
def log_dependencies(session: Session) -> None:
"""Log all dependencies in the current environment.
Only shown if nox is run with `nox -v`.
"""
if session.venv_backend == "uv":
session.run_install("uv", "pip", "freeze", silent=True)
else:
session.run_install("pip", "freeze", silent=True)
def is_ci() -> bool:
"""Returns `True` if nox is currently running in a CI environment."""
ci = os.environ.get("CI", "")
try:
# Parse as JSON so that `"true"`, `"1"`, etc register as `True`
# `"false"`, `"0"`, or any invalid value registers as `False`
return bool(json.loads(ci))
except json.JSONDecodeError:
return False
@dataclass(frozen=True)
class Package:
"""Helper class for defining an external package to test."""
name: str
repo: str
_: KW_ONLY
category: str | None = None
extras: list[str] | None = None
env: dict[str, str] | None = None
parallel: bool = False
pytest_paths: list[str] | None = None
pytest_args: list[str] | None = None
def as_param(self) -> nox.param:
"""Build a nox `param` from the package configuration."""
tags = [self.category] if self.category is not None else []
return nox.param(self, tags=tags, id=self.name)
def download_and_install(self, session: Session) -> Path:
"""Clone and install the package repo and its dependencies.
Returns the local path to the package root.
"""
dir = Path(session.cache_dir) / self.name
if dir.exists():
with session.cd(dir):
session.run_install("git", "pull", "--prune", external=True, silent=True)
else:
session.run_install("git", "clone", self.repo, dir, external=True, silent=True)
session.install("-e", self._installer_spec(dir))
return dir
def install_asdf(self, session: Session) -> None:
"""Install local version of ASDF and all required dependencies."""
session.install("-e", ".[all,tests]")
def test(self, session: Session) -> None:
"""Run the package's test suite."""
log_dependencies(session)
session.run(*self._pytest_args(), *session.posargs, env=self.env)
def _installer_spec(self, dir: Path) -> str:
"""Get the full dependency spec for installing the package which can be passed to pip.
`dir` is the full path to the package repo.
"""
extras = f"[{','.join(self.extras)}]" if self.extras else ""
return f"{dir}{extras}"
def _pytest_args(self):
"""Get the full pytest command for testing this package.
Returns a generator that yields the pytest command followed by all arguments.
"""
yield "pytest"
if self.pytest_paths is not None:
yield from self.pytest_paths
if self.parallel:
yield from ("-n", "auto")
if self.pytest_args is not None:
yield from self.pytest_args
class DepsStrategy(enum.Enum):
"""Dependency version resolution strategy."""
Default = enum.auto()
"""Use default dependency resolution."""
Dev = enum.auto()
"""Use unstable releases for certain packages as defined in `requirements-dev.txt`."""
Oldest = enum.auto()
"""Use oldest compatible versions for direct ASDF dependencies.
Does not affect extra dependencies or indirect dependencies.
"""
def generate_requirements(self, session: Session) -> Generator[str]:
"""Returns an iterator of requirement file lines based on the override mode.
Also modifies `session` environment variables if needed to configure dependency resolution.
Note that the returned values are intended to be written to a requirements file
and can't be directly passed to `pip install`.
"""
match self:
case DepsStrategy.Default:
return
case DepsStrategy.Dev:
# Change uv index resolution to match pip
session.virtualenv.env["UV_INDEX_STRATEGY"] = "unsafe-best-match"
# Change uv prerelease resolution to match pip
session.virtualenv.env["UV_PRERELEASE"] = "allow"
yield from self._dev()
case DepsStrategy.Oldest:
yield from self._oldest(session)
def _dev(self) -> Generator[str]:
yield from Path("requirements-dev.txt").read_text().splitlines()
def _oldest(self, session: Session) -> Generator[str]:
session.install("minimum_dependencies")
# asdf needs to be installed for `minimum_dependencies` to read its metadata
session.install("-e", ".", "--no-deps")
tmp_path = Path(session.create_tmp()) / "requirements-min.txt"
session.run_install("minimum_dependencies", "asdf", "--filename", str(tmp_path), silent=True)
yield from tmp_path.read_text().splitlines()
@dataclass(frozen=True, kw_only=True)
class Asdf:
"""Helper class for managing ASDF installation and testing options."""
parallel: bool = False
"""Enable parallel test execution via `xdist`"""
show_slowest: int | None = 10
"""If not `None`, print the `n` slowest test cases after running the test suite."""
extras: list[str] = field(default_factory=lambda: ["all", "tests"])
"""ASDF package extras to enable during installation."""
deps_groups: list[str] = field(default_factory=list)
"""Pyproject `dependency-groups` to enable during installation."""
deps_strategy: DepsStrategy = DepsStrategy.Default
"""Resolution strategy for determining ASDF dependency versions."""
def install(self, session: Session, *extra_deps: str) -> Asdf:
"""Install local version of ASDF and its dependencies.
Arguments passed to `extra_deps` are installed last and override any existing dependencies.
"""
extras = f"[{','.join(self.extras)}]" if self.extras else ""
deps = [f"-e .{extras}"]
for group in self.deps_groups:
deps.extend(nox.project.dependency_groups(PYPROJECT, group))
if self.parallel:
deps.append("pytest-xdist")
deps.extend(self.deps_strategy.generate_requirements(session))
deps.extend(extra_deps)
deps_path = Path(session.create_tmp()) / "requirements.txt"
deps_path.write_text("\n".join(deps))
session.install("-r", str(deps_path))
return self
def test(self, session: Session, *extra_args: str) -> Asdf:
"""Run the ASDF test suite.
Arguments passed to `extra_args` are forwarded to pytest.
"""
log_dependencies(session)
session.run(*self._pytest_args(), *extra_args, *session.posargs)
return self
def _pytest_args(self):
"""Generate pytest command and arguments.
Intended to be passed to `session.run`.
"""
yield "pytest"
if self.show_slowest is not None:
yield f"--durations={self.show_slowest}"
if self.parallel:
yield from ("--numprocesses", "auto")
CRDS_ENV: dict[str, str] = {
"CRDS_SERVER_URL": "https://jwst-crds.stsci.edu",
"CRDS_PATH": "/tmp/crds_cache", # noqa: S108
"CRDS_CLIENT_RETRY_COUNT": "3",
"CRDS_CLIENT_RETRY_DELAY_SECONDS": "20",
}
# Downstream packages with test suites to run against the local asdf version
DOWNSTREAM: list[Package] = [
### asdf ###
Package(
"asdf-standard",
"https://github.com/asdf-format/asdf-standard.git",
category="asdf",
extras=["test"],
),
Package(
"asdf-compression",
"https://github.com/asdf-format/asdf-compression.git",
category="asdf",
extras=["tests", "all"],
),
Package(
"asdf-zarr",
"https://github.com/asdf-format/asdf-zarr.git",
category="asdf",
extras=["tests"],
),
Package(
"asdf-transform-schemas",
"https://github.com/asdf-format/asdf-transform-schemas.git",
category="asdf",
extras=["test"],
),
Package(
"asdf-wcs-schemas", "https://github.com/asdf-format/asdf-wcs-schemas.git", category="asdf", extras=["test"]
),
Package(
"asdf-coordinates-schemas",
"https://github.com/asdf-format/asdf-coordinates-schemas.git",
category="asdf",
extras=["test"],
),
### astropy ###
Package(
"asdf-astropy",
"https://github.com/astropy/asdf-astropy.git",
category="astropy",
extras=["test"],
),
Package(
"specutils",
"https://github.com/astropy/specutils.git",
category="astropy",
extras=["test"],
),
### stsci ###
Package(
"astrocut",
"https://github.com/spacetelescope/astrocut.git",
category="stsci",
extras=["test"],
pytest_args=["--pyargs", "astrocut"],
),
Package(
"gwcs",
"https://github.com/spacetelescope/gwcs.git",
category="stsci",
extras=["test"],
),
Package(
"jwst",
"https://github.com/spacetelescope/jwst.git",
category="stsci",
extras=["test"],
env=CRDS_ENV,
),
Package(
"stdatamodels",
"https://github.com/spacetelescope/stdatamodels.git",
category="stsci",
extras=["test"],
env=CRDS_ENV,
),
Package("stpipe", "https://github.com/spacetelescope/stpipe.git", category="stsci", extras=["test"]),
Package(
"roman_datamodels", "https://github.com/spacetelescope/roman_datamodels.git", category="stsci", extras=["test"]
),
### third-party ###
Package(
"weldx",
"https://github.com/BAMWelDX/weldx.git",
category="third-party",
extras=["test", "media"],
pytest_paths=["weldx/tests/asdf_tests", "weldx/schemas"],
pytest_args=["--asdf-tests"],
),
Package(
"sunpy",
"https://github.com/sunpy/sunpy.git",
category="third-party",
extras=["tests", "all"],
pytest_paths=["sunpy/io"],
),
Package(
"dkist",
"https://github.com/DKISTDC/dkist.git",
category="third-party",
extras=["tests"],
pytest_args=["--benchmark-skip"],
),
Package(
"dkist-inventory",
"https://bitbucket.org/dkistdc/dkist-inventory.git",
category="third-party",
extras=["test"],
parallel=True,
),
# This package's tests only work on linux
Package(
"abacusutils",
"https://github.com/abacusorg/abacusutils.git",
category="third-party",
pytest_paths=["tests/test_data.py"],
),
]
################
### SESSIONS ###
################
@nox.session(tags=["test", "downstream"], python=PY_DEFAULT)
@nox.parametrize("pkg", [pkg.as_param() for pkg in DOWNSTREAM])
def downstream(session: Session, pkg: Package) -> None:
"""Run the test suite for a downstream package against the local asdf version."""
dir = pkg.download_and_install(session)
pkg.install_asdf(session)
with session.cd(dir):
pkg.test(session)
@nox.session(tags=["test", "core"], python=PY_STABLE[:-1])
def core(session: Session) -> None:
"""Run asdf test suite"""
Asdf(parallel=True).install(session).test(session)
@nox.session(tags=["test", "coverage", "core"], python=PY_NEWEST)
def coverage(session: Session) -> None:
"""Run asdf test suite with coverage"""
(
Asdf(parallel=True)
.install(session, "pytest-cov")
.test(
session,
"--cov",
"--cov-config",
"pyproject.toml",
"--cov-report",
"term-missing",
"--cov-report",
"xml",
)
)
@nox.session(tags=["test", "core"], python=PY_STABLE)
def devdeps(session: Session) -> None:
"""Run asdf tests against latest unstable versions of asdf dependencies"""
# Enable unstable ASDF schemas
session.virtualenv.env["ASDF_UNSTABLE_CORE_SCHEMAS"] = "1"
(
Asdf(parallel=True, deps_strategy=DepsStrategy.Dev)
.install(session)
.test(session, "-W", "ignore::asdf_standard.exceptions.UnstableCoreSchemasWarning")
)
@nox.session(tags=["test", "core"], python=PY_DEFAULT)
def mocks3(session: Session) -> None:
"""Set up AWS mocks and run S3 integration tests"""
(Asdf(parallel=False, deps_groups=["mocks3"]).install(session).test(session, "integration_tests/mocks3/"))
@nox.session(tags=["test", "core"], python=PY_OLDEST)
def compatibility(session: Session) -> None:
"""Run asdf compatibility integration tests"""
Asdf(parallel=False).install(session, "virtualenv").test(session, "integration_tests/compatibility/")
@nox.session(tags=["test", "core"], python=PY_DEFAULT)
def jsonschema(session: Session) -> None:
"""Run asdf jsonschema tests"""
Asdf(parallel=False).install(session).test(session, "--jsonschema")
@nox.session(
tags=["test", "core"],
python=PY_OLDEST,
# This test doesn't work with the uv backend
# Probably due to differences in build isolation
venv_backend="virtualenv",
)
def oldestdeps(session: Session) -> None:
"""Run asdf tests against oldest supported dependency versions"""
Asdf(parallel=True, deps_strategy=DepsStrategy.Oldest).install(session).test(session)
@nox.session(tags=["test", "core"], python=[PY_NEWEST, PY_UNSTABLE])
def pytestdev(session: Session) -> None:
"""Run asdf tests using latest unstable pytest version"""
Asdf(parallel=True).install(session, "git+https://github.com/pytest-dev/pytest").test(session)
@nox.session(name="type-checking", tags=["core", "type-checking"], python=PY_OLDEST)
def type_checking(session: Session) -> None:
"""Run pyrefly type-checking."""
# Install asdf with typing dependencies
Asdf(extras=["all", "tests", "typing"]).install(session)
# If running in CI, set Github output format unless output format is manually set
if not any(arg.startswith("--output-format") for arg in session.posargs) and is_ci():
session.posargs.append("--output-format=github")
session.run("pyrefly", "check", *session.posargs)
@nox.session(tags=["docs"], python=PY_NEWEST, default=False)
def docs(session: Session) -> None:
"""Build sphinx documentation.
If the environment hasn't changed, you can speed up the build by using nox's `-R` flag
to reuse the virtual environment and skip reinstalling dependencies, e.g. `nox -R -s docs`.
"""
Asdf(extras=[], deps_groups=["docs"]).install(session)
session.run(
"sphinx-build",
"-E",
"-T",
"-W",
"--keep-going",
"docs",
"docs/_build/html",
*session.posargs,
)