Coverage for tests/test_serialization_io.py: 95%

115 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 20:37 +0000

1# This file is part of lsst-images. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11from __future__ import annotations 

12 

13from pathlib import Path 

14 

15import numpy as np 

16import pytest 

17 

18from lsst.images import Box, Image, VisitImage 

19from lsst.images.serialization import ArchiveReadError, read_archive, write_archive 

20from lsst.images.tests import current_fixture_path, iter_schema_fixtures 

21from lsst.utils.introspection import get_full_type_name 

22 

23try: 

24 import h5py # noqa: F401 -- detect availability for NDF round-trip skip 

25 

26 H5PY_AVAILABLE = True 

27except ImportError: 

28 H5PY_AVAILABLE = False 

29 

30try: 

31 import piff # noqa: F401 -- detect availability for piff_psf fixture skip 

32 

33 PIFF_AVAILABLE = True 

34except ImportError: 

35 PIFF_AVAILABLE = False 

36 

37skip_no_h5py = pytest.mark.skipif(not H5PY_AVAILABLE, reason="h5py is not installed") 

38 

39FIXTURE_DIR = Path(__file__).parent / "data" / "schemas" 

40 

41# Full Python type produced when each fixture is read through the generic 

42# read_archive() API, keyed by (schema name, variant). These are pinned here 

43# rather than derived from the schema registry so the test asserts the 

44# externally-observable type instead of re-running read_archive()'s own 

45# lookup against itself. Keying by name and variant rather than by file name 

46# keeps the table stable across version bumps. 

47EXPECTED_TYPES: dict[tuple[str, str | None], str] = { 

48 ("aperture_correction_map", None): "dict", 

49 ("background_map", None): "lsst.images.BackgroundMap", 

50 ("camera_frame_set", None): "lsst.images.cameras.CameraFrameSet", 

51 ("cell_aperture_correction_map", None): "dict", 

52 ("cell_coadd", "as_shipped"): "lsst.images.cells.CellCoadd", 

53 ("cell_coadd", "canonical"): "lsst.images.cells.CellCoadd", 

54 ("cell_coadd", "dp2"): "lsst.images.cells.CellCoadd", 

55 ("cell_psf", None): "lsst.images.cells.CellPointSpreadFunction", 

56 ("chebyshev_field", None): "lsst.images.fields.ChebyshevField", 

57 ("coadd_provenance", None): "lsst.images.cells.CoaddProvenance", 

58 ("color_image", None): "lsst.images.ColorImage", 

59 ("detector", None): "lsst.images.cameras.Detector", 

60 ("difference_image", "dp2"): "lsst.images.DifferenceImage", 

61 ("difference_image", "template_inputs"): "lsst.images.DifferenceImage", 

62 ("gaussian_psf", None): "lsst.images.psfs.GaussianPointSpreadFunction", 

63 ("image", None): "lsst.images.Image", 

64 ( 

65 "image_basis_convolution_kernel", 

66 None, 

67 ): "lsst.images.convolution_kernels.ImageBasisConvolutionKernel", 

68 ("mask", None): "lsst.images.Mask", 

69 ("masked_image", None): "lsst.images.MaskedImage", 

70 ("observation_summary_stats", None): "lsst.images.ObservationSummaryStats", 

71 ("piff_psf", None): "lsst.images.psfs.PiffWrapper", 

72 ("product_field", None): "lsst.images.fields.ProductField", 

73 ("sky_projection", None): "lsst.images.SkyProjection", 

74 ("spline_field", None): "lsst.images.fields.SplineField", 

75 ("sum_field", None): "lsst.images.fields.SumField", 

76 ("transform", None): "lsst.images.Transform", 

77 ("visit_image", None): "lsst.images.VisitImage", 

78 ("visit_image", "dp1"): "lsst.images.VisitImage", 

79 ("visit_image", "dp2"): "lsst.images.VisitImage", 

80} 

81 

82 

83def test_generic_read_visit_image_json() -> None: 

84 """Verify read_archive() on a visit_image JSON fixture returns a 

85 VisitImage. 

86 """ 

87 path = current_fixture_path(FIXTURE_DIR, "visit_image") 

88 result = read_archive(path) 

89 assert isinstance(result, VisitImage) 

90 

91 

92def test_generic_read_image_json() -> None: 

93 """Verify read_archive() on an image JSON fixture returns an Image.""" 

94 path = current_fixture_path(FIXTURE_DIR, "image") 

95 result = read_archive(path) 

96 assert isinstance(result, Image) 

97 

98 

99def test_read_unsupported_extension(tmp_path: Path) -> None: 

100 """Verify read_archive() raises ValueError for an unrecognized file 

101 extension. 

102 """ 

103 path = tmp_path / "bogus.txt" 

104 with open(path, "w") as f: 

105 f.write("nope") 

106 with pytest.raises(ValueError, match="Unrecognized file extension"): 

107 read_archive(path) 

108 

109 

110def test_read_unregistered_schema(tmp_path: Path) -> None: 

111 """Verify read_archive() raises ArchiveReadError for a JSON with an unknown 

112 schema. 

113 """ 

114 path = tmp_path / "fake.json" 

115 with open(path, "w") as f: 

116 f.write( 

117 '{"schema_url": "https://images.lsst.io/schemas/no-such-schema-99.0.0",' 

118 ' "schema_version": "99.0.0", "min_read_version": 1, "indirect": []}' 

119 ) 

120 with pytest.raises(ArchiveReadError) as exc_info: 

121 read_archive(path) 

122 assert "no-such-schema" in str(exc_info.value) 

123 

124 

125def _sweep_sort_key(entry: tuple[str, str | None]) -> tuple[str, str]: 

126 """Return a sort key for an ``EXPECTED_TYPES`` entry, ``None`` sorting 

127 first within a schema name. 

128 """ 

129 name, variant = entry 

130 return (name, variant or "") 

131 

132 

133# Assigned to an explicitly annotated variable rather than sorted() inline in 

134# the decorator below: parametrize()'s stub types its arguments as `object`, 

135# and that context leaks into bidirectional generic inference for a bare 

136# sorted() call, defeating the key function's type. 

137_SWEEP_ENTRIES: list[tuple[str, str | None]] = sorted(EXPECTED_TYPES, key=_sweep_sort_key) 

138 

139 

140def test_expected_types_enumerates_every_committed_fixture_variant() -> None: 

141 """Verify EXPECTED_TYPES matches the fixture tree's (name, variant) pairs 

142 exactly, so a committed fixture cannot go missing unnoticed. 

143 

144 Each rung below may legitimately skip an individual case when an optional 

145 dependency (piff) is unavailable, but that must never be confused with a 

146 committed fixture file itself going missing: this closes the presence 

147 gap for every variant at once, rather than relying on each consumer's own 

148 guard against a missing path (which a stray ``git rm`` or an interrupted 

149 freeze would otherwise defeat with a silent skip instead of a failure). 

150 

151 The two directions fail separately and name their own remedy, because 

152 adding a fixture variant and losing one are unrelated mistakes with 

153 opposite fixes, and this test is the only thing that catches either. 

154 """ 

155 present = {(f.name, f.variant) for f in iter_schema_fixtures(FIXTURE_DIR) if not f.retired} 

156 unlisted = sorted(present - set(EXPECTED_TYPES)) 

157 absent = sorted(set(EXPECTED_TYPES) - present) 

158 assert not unlisted, ( 

159 f"committed fixture variants missing from EXPECTED_TYPES: {unlisted}; add each with the " 

160 "full type name its fixture deserializes to, so test_fixture_sweep covers it" 

161 ) 

162 assert not absent, ( 

163 f"EXPECTED_TYPES entries with no committed fixture: {absent}; delete each entry, or " 

164 "restore the fixture file if it went missing by accident" 

165 ) 

166 

167 

168@pytest.mark.parametrize("entry", _SWEEP_ENTRIES) 

169def test_fixture_sweep(entry: tuple[str, str | None]) -> None: 

170 """Verify every schema fixture reads to its pinned Python type.""" 

171 name, variant = entry 

172 if name == "piff_psf" and not PIFF_AVAILABLE: 172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true

173 pytest.skip("piff not available") 

174 path = current_fixture_path(FIXTURE_DIR, name, variant=variant) 

175 assert path.exists(), f"{path} is a committed fixture and must not go missing" 

176 result = read_archive(path) 

177 assert get_full_type_name(type(result)) == EXPECTED_TYPES[entry], entry 

178 

179 

180def _make_image() -> Image: 

181 """Return a small float32 Image for round-trip tests.""" 

182 return Image(np.arange(16, dtype=np.float32).reshape(4, 4), bbox=Box.factory[0:4, 0:4]) 

183 

184 

185def test_generic_write_round_trip_fits(tmp_path: Path) -> None: 

186 """Verify write_archive() + read_archive() round-trips an Image 

187 through FITS. 

188 """ 

189 image = _make_image() 

190 path = tmp_path / "x.fits" 

191 write_archive(image, path) 

192 result = read_archive(path) 

193 assert isinstance(result, Image) 

194 np.testing.assert_array_equal(result.array, image.array) 

195 

196 

197def test_generic_write_round_trip_json(tmp_path: Path) -> None: 

198 """Verify write_archive() + read_archive() round-trips an Image 

199 through JSON. 

200 """ 

201 image = _make_image() 

202 path = tmp_path / "x.json" 

203 write_archive(image, path) 

204 result = read_archive(path) 

205 assert isinstance(result, Image) 

206 np.testing.assert_array_equal(result.array, image.array) 

207 

208 

209def test_write_metadata_override_does_not_mutate_source(tmp_path: Path) -> None: 

210 """Write-only metadata is detached from the source object's mapping.""" 

211 image = _make_image() 

212 image.metadata["shared"] = "source" 

213 path = tmp_path / "metadata.json" 

214 tree = write_archive(image, path, metadata={"shared": "file", "extra": 5}) 

215 

216 assert image.metadata == {"shared": "source"} 

217 assert tree.metadata == {"shared": "file", "extra": 5} 

218 assert tree.metadata is not image.metadata 

219 result = read_archive(path, Image) 

220 assert result.metadata == tree.metadata 

221 

222 

223@skip_no_h5py 

224def test_generic_write_round_trip_ndf(tmp_path: Path) -> None: 

225 """Verify write_archive() + read_archive() round-trips an Image 

226 through NDF. 

227 """ 

228 image = _make_image() 

229 path = tmp_path / "x.sdf" 

230 write_archive(image, path) 

231 result = read_archive(path) 

232 assert isinstance(result, Image) 

233 np.testing.assert_array_equal(result.array, image.array) 

234 

235 

236def test_read_bbox_subset_fits(tmp_path: Path) -> None: 

237 """Verify read_archive() forwards bbox kwarg to the FITS backend for subset 

238 reads. 

239 """ 

240 img = Image(np.arange(64, dtype=np.float32).reshape(8, 8), bbox=Box.factory[0:8, 0:8]) 

241 path = tmp_path / "x.fits" 

242 write_archive(img, path) 

243 sub = read_archive(path, bbox=Box.factory[2:6, 2:6]) 

244 assert sub.array.shape == (4, 4) 

245 np.testing.assert_array_equal(sub.array, img.array[2:6, 2:6]) 

246 

247 

248def test_read_cls_match() -> None: 

249 """Verify read_archive() with cls= returns the expected type when it 

250 matches. 

251 """ 

252 path = current_fixture_path(FIXTURE_DIR, "image") 

253 result = read_archive(path, cls=Image) 

254 assert isinstance(result, Image) 

255 

256 

257def test_read_cls_mismatch_raises() -> None: 

258 """Verify read_archive() raises TypeError when the deserialized type 

259 does not match cls. 

260 """ 

261 from lsst.images import Mask 

262 

263 path = current_fixture_path(FIXTURE_DIR, "image") 

264 with pytest.raises(TypeError) as exc_info: 

265 read_archive(path, cls=Mask) 

266 msg = str(exc_info.value) 

267 assert "image" in msg # path / schema name 

268 assert "Image" in msg # actual deserialized type 

269 assert "Mask" in msg # requested cls