Coverage for tests/test_templates.py: 10%
180 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-26 02:48 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-26 02:48 -0700
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Test file name templating."""
30import os.path
31import unittest
32import uuid
34from lsst.daf.butler import (
35 DataCoordinate,
36 DatasetId,
37 DatasetRef,
38 DatasetType,
39 DimensionUniverse,
40 StorageClass,
41)
42from lsst.daf.butler.datastore.file_templates import (
43 FileTemplate,
44 FileTemplates,
45 FileTemplatesConfig,
46 FileTemplateValidationError,
47)
49TESTDIR = os.path.abspath(os.path.dirname(__file__))
51PlaceHolder = StorageClass("PlaceHolder")
53REFUUID = DatasetId(int=uuid.uuid4().int)
56class TestFileTemplates(unittest.TestCase):
57 """Test creation of paths from templates."""
59 def makeDatasetRef(
60 self, datasetTypeName, dataId=None, storageClassName="DefaultStorageClass", run="run2", conform=True
61 ):
62 """Make a simple DatasetRef"""
63 if dataId is None:
64 dataId = self.dataId
65 if "physical_filter" in dataId and "band" not in dataId:
66 dataId["band"] = "b" # Add fake band.
67 dimensions = self.universe.conform(dataId.keys())
68 dataId = DataCoordinate.standardize(dataId, dimensions=dimensions)
70 # Pretend we have a parent if this looks like a composite
71 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName)
72 parentStorageClass = PlaceHolder if componentName else None
74 datasetType = DatasetType(
75 datasetTypeName,
76 dimensions,
77 StorageClass(storageClassName),
78 parentStorageClass=parentStorageClass,
79 )
80 return DatasetRef(datasetType, dataId, id=REFUUID, run=run, conform=conform)
82 def setUp(self):
83 self.universe = DimensionUniverse()
84 self.dataId = {
85 "instrument": "dummy",
86 "visit": 52,
87 "physical_filter": "Most Amazing U Filter Ever",
88 "day_obs": 20200101,
89 }
91 def assertTemplate(self, template, answer, ref):
92 fileTmpl = FileTemplate(template)
93 path = fileTmpl.format(ref)
94 self.assertEqual(path, answer)
96 def testBasic(self):
97 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}"
98 self.assertTemplate(
99 tmplstr,
100 "run2/calexp/00052/Most_Amazing_U_Filter_Ever",
101 self.makeDatasetRef("calexp"),
102 )
103 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail"
104 self.assertTemplate(
105 tmplstr,
106 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail",
107 self.makeDatasetRef("calexp"),
108 )
110 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}"
111 self.assertTemplate(
112 tmplstr,
113 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run2",
114 self.makeDatasetRef("calexp"),
115 )
116 self.assertTemplate(
117 tmplstr,
118 "run_2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2",
119 self.makeDatasetRef("calexp", run="run/2"),
120 )
122 # Check that the id is sufficient without any other information.
123 self.assertTemplate("{id}", str(REFUUID), self.makeDatasetRef("calexp", run="run2"))
125 self.assertTemplate("{run}/{id}", f"run2/{str(REFUUID)}", self.makeDatasetRef("calexp", run="run2"))
127 self.assertTemplate(
128 "fixed/{id}",
129 f"fixed/{str(REFUUID)}",
130 self.makeDatasetRef("calexp", run="run2"),
131 )
133 self.assertTemplate(
134 "fixed/{id}_{physical_filter}",
135 f"fixed/{str(REFUUID)}_Most_Amazing_U_Filter_Ever",
136 self.makeDatasetRef("calexp", run="run2"),
137 )
139 # Retain any "/" in run
140 tmplstr = "{run:/}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}"
141 self.assertTemplate(
142 tmplstr,
143 "run/2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2",
144 self.makeDatasetRef("calexp", run="run/2"),
145 )
147 # Check that "." are replaced in the file basename, but not directory.
148 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "g.10", "day_obs": 20250101}
149 self.assertTemplate(
150 tmplstr,
151 "run.2/calexp/00052/g_10-trail-run_2",
152 self.makeDatasetRef("calexp", run="run.2", dataId=dataId),
153 )
155 with self.assertRaises(FileTemplateValidationError):
156 FileTemplate("no fields at all")
158 with self.assertRaises(FileTemplateValidationError):
159 FileTemplate("{visit}")
161 with self.assertRaises(FileTemplateValidationError):
162 FileTemplate("{run}_{datasetType}")
164 with self.assertRaises(FileTemplateValidationError):
165 FileTemplate("{id}/fixed")
167 with self.assertRaises(FileTemplateValidationError):
168 FileTemplate("{run}/../{datasetType}_{visit}")
170 def testRunOrCollectionNeeded(self):
171 tmplstr = "{datasetType}/{visit:05d}/{physical_filter}"
172 with self.assertRaises(FileTemplateValidationError):
173 self.assertTemplate(tmplstr, "run2/calexp/00052/U", self.makeDatasetRef("calexp"))
175 def testNoRecord(self):
176 # Attaching records is not possible in this test code but we can check
177 # that a missing record when a metadata entry has been requested
178 # does fail.
179 tmplstr = "{run}/{datasetType}/{visit.name}/{physical_filter}"
180 with self.assertRaises(RuntimeError) as cm:
181 self.assertTemplate(tmplstr, "", self.makeDatasetRef("calexp"))
182 self.assertIn("No metadata", str(cm.exception))
184 def testOptional(self):
185 """Optional units in templates."""
186 ref = self.makeDatasetRef("calexp")
187 tmplstr = "{run}/{datasetType}/v{visit:05d}_f{physical_filter:?}_{skypix:?}"
188 self.assertTemplate(
189 tmplstr,
190 "run2/calexp/v00052_fMost_Amazing_U_Filter_Ever",
191 self.makeDatasetRef("calexp"),
192 )
194 du = {"visit": 48, "tract": 265, "skymap": "big", "instrument": "dummy", "htm7": 12345}
195 self.assertTemplate(tmplstr, "run2/calexpT/v00048_12345", self.makeDatasetRef("calexpT", du))
197 # Ensure that this returns a relative path even if the first field
198 # is optional
199 tmplstr = "{run}/{tract:?}/{visit:?}/f{physical_filter}"
200 self.assertTemplate(tmplstr, "run2/52/fMost_Amazing_U_Filter_Ever", ref)
202 # Ensure that // from optionals are converted to singles
203 tmplstr = "{run}/{datasetType}/{patch:?}/{tract:?}/f{physical_filter}"
204 self.assertTemplate(tmplstr, "run2/calexp/fMost_Amazing_U_Filter_Ever", ref)
206 # Optionals with some text between fields
207 tmplstr = "{run}/{datasetType}/p{patch:?}_t{tract:?}/f{physical_filter}"
208 self.assertTemplate(tmplstr, "run2/calexp/p/fMost_Amazing_U_Filter_Ever", ref)
209 tmplstr = "{run}/{datasetType}/p{patch:?}_t{visit:04d?}/f{physical_filter}"
210 self.assertTemplate(tmplstr, "run2/calexp/p_t0052/fMost_Amazing_U_Filter_Ever", ref)
212 def testComponent(self):
213 """Test handling of components in templates."""
214 refMetricOutput = self.makeDatasetRef("metric.output")
215 refMetric = self.makeDatasetRef("metric")
216 refMaskedImage = self.makeDatasetRef("calexp.maskedimage.variance")
217 refWcs = self.makeDatasetRef("calexp.wcs")
219 tmplstr = "{run}_c_{component}_v{visit}"
220 self.assertTemplate(tmplstr, "run2_c_output_v52", refMetricOutput)
222 # We want this template to have both a directory and basename, to
223 # test that the right parts of the output are replaced.
224 tmplstr = "{component:?}/{run}_{component:?}_{visit}"
225 self.assertTemplate(tmplstr, "run2_52", refMetric)
226 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput)
227 self.assertTemplate(tmplstr, "maskedimage.variance/run2_maskedimage_variance_52", refMaskedImage)
228 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput)
230 # Providing a component but not using it
231 tmplstr = "{run}/{datasetType}/v{visit:05d}"
232 with self.assertRaises(KeyError):
233 self.assertTemplate(tmplstr, "", refWcs)
235 def testFields(self):
236 # Template, mandatory fields, optional non-special fields,
237 # special fields, optional special fields
238 testData = (
239 (
240 "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail",
241 {"visit", "physical_filter"},
242 set(),
243 {"run", "datasetType"},
244 set(),
245 ),
246 (
247 "{run}/{component:?}_{visit}",
248 {"visit"},
249 set(),
250 {"run"},
251 {"component"},
252 ),
253 (
254 "{run}/{component:?}_{visit:?}_{physical_filter}_{instrument}_{datasetType}",
255 {"physical_filter", "instrument"},
256 {"visit"},
257 {"run", "datasetType"},
258 {"component"},
259 ),
260 )
261 for tmplstr, mandatory, optional, special, optionalSpecial in testData:
262 with self.subTest(template=tmplstr):
263 tmpl = FileTemplate(tmplstr)
264 fields = tmpl.fields()
265 self.assertEqual(fields, mandatory)
266 fields = tmpl.fields(optionals=True)
267 self.assertEqual(fields, mandatory | optional)
268 fields = tmpl.fields(specials=True)
269 self.assertEqual(fields, mandatory | special)
270 fields = tmpl.fields(specials=True, optionals=True)
271 self.assertEqual(fields, mandatory | special | optional | optionalSpecial)
273 def testSimpleConfig(self):
274 """Test reading from config file"""
275 configRoot = os.path.join(TESTDIR, "config", "templates")
276 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml"))
277 templates = FileTemplates(config1, universe=self.universe)
278 ref = self.makeDatasetRef("calexp")
279 tmpl = templates.getTemplate(ref)
280 self.assertIsInstance(tmpl, FileTemplate)
282 # This config file should not allow defaulting
283 ref2 = self.makeDatasetRef("unknown")
284 with self.assertRaises(KeyError):
285 templates.getTemplate(ref2)
287 # This should fall through the datasetTypeName check and use
288 # StorageClass instead
289 ref3 = self.makeDatasetRef("unknown2", storageClassName="StorageClassX")
290 tmplSc = templates.getTemplate(ref3)
291 self.assertIsInstance(tmplSc, FileTemplate)
293 # Try with a component: one with defined formatter and one without
294 refWcs = self.makeDatasetRef("calexp.wcs")
295 refImage = self.makeDatasetRef("calexp.image")
296 tmplCalexp = templates.getTemplate(ref)
297 tmplWcs = templates.getTemplate(refWcs) # Should be special
298 tmpl_image = templates.getTemplate(refImage)
299 self.assertIsInstance(tmplCalexp, FileTemplate)
300 self.assertIsInstance(tmpl_image, FileTemplate)
301 self.assertIsInstance(tmplWcs, FileTemplate)
302 self.assertEqual(tmplCalexp, tmpl_image)
303 self.assertNotEqual(tmplCalexp, tmplWcs)
305 # Check dimensions lookup order.
306 # The order should be: dataset type name, dimension, storage class
307 # This one will not match name but might match storage class.
308 # It should match dimensions
309 refDims = self.makeDatasetRef(
310 "nomatch", dataId={"instrument": "LSST", "physical_filter": "z"}, storageClassName="StorageClassX"
311 )
312 tmplDims = templates.getTemplate(refDims)
313 self.assertIsInstance(tmplDims, FileTemplate)
314 self.assertNotEqual(tmplDims, tmplSc)
316 # Test that instrument overrides retrieve specialist templates
317 refPvi = self.makeDatasetRef("pvi")
318 refPviHsc = self.makeDatasetRef("pvi", dataId={"instrument": "HSC", "physical_filter": "z"})
319 refPviLsst = self.makeDatasetRef("pvi", dataId={"instrument": "LSST", "physical_filter": "z"})
321 tmplPvi = templates.getTemplate(refPvi)
322 tmplPviHsc = templates.getTemplate(refPviHsc)
323 tmplPviLsst = templates.getTemplate(refPviLsst)
324 self.assertEqual(tmplPvi, tmplPviLsst)
325 self.assertNotEqual(tmplPvi, tmplPviHsc)
327 # Have instrument match and dimensions look up with no name match
328 refNoPviHsc = self.makeDatasetRef(
329 "pvix", dataId={"instrument": "HSC", "physical_filter": "z"}, storageClassName="StorageClassX"
330 )
331 tmplNoPviHsc = templates.getTemplate(refNoPviHsc)
332 self.assertNotEqual(tmplNoPviHsc, tmplDims)
333 self.assertNotEqual(tmplNoPviHsc, tmplPviHsc)
335 # Format config file with defaulting
336 config2 = FileTemplatesConfig(os.path.join(configRoot, "templates-withdefault.yaml"))
337 templates = FileTemplates(config2, universe=self.universe)
338 tmpl = templates.getTemplate(ref2)
339 self.assertIsInstance(tmpl, FileTemplate)
341 # Format config file with bad format string
342 with self.assertRaises(FileTemplateValidationError):
343 FileTemplates(os.path.join(configRoot, "templates-bad.yaml"), universe=self.universe)
345 # Config file with no defaulting mentioned
346 config3 = os.path.join(configRoot, "templates-nodefault2.yaml")
347 templates = FileTemplates(config3, universe=self.universe)
348 with self.assertRaises(KeyError):
349 templates.getTemplate(ref2)
351 # Try again but specify a default in the constructor
352 default = "{run}/{datasetType}/{physical_filter}"
353 templates = FileTemplates(config3, default=default, universe=self.universe)
354 tmpl = templates.getTemplate(ref2)
355 self.assertEqual(tmpl.template, default)
357 def testValidation(self):
358 configRoot = os.path.join(TESTDIR, "config", "templates")
359 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml"))
360 templates = FileTemplates(config1, universe=self.universe)
362 entities = {}
363 entities["calexp"] = self.makeDatasetRef(
364 "calexp",
365 storageClassName="StorageClassX",
366 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 52},
367 )
369 with self.assertLogs(level="WARNING") as cm:
370 templates.validateTemplates(entities.values(), logFailures=True)
371 self.assertIn("Unchecked keys", cm.output[0])
372 self.assertIn("StorageClassX", cm.output[0])
374 entities["pvi"] = self.makeDatasetRef(
375 "pvi", storageClassName="StorageClassX", dataId={"instrument": "dummy", "physical_filter": "i"}
376 )
377 entities["StorageClassX"] = self.makeDatasetRef(
378 "storageClass", storageClassName="StorageClassX", dataId={"instrument": "dummy", "visit": 2}
379 )
380 entities["calexp.wcs"] = self.makeDatasetRef(
381 "calexp.wcs",
382 storageClassName="StorageClassX",
383 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 23},
384 conform=False,
385 )
387 entities["instrument+physical_filter"] = self.makeDatasetRef(
388 "filter_inst",
389 storageClassName="StorageClassX",
390 dataId={"physical_filter": "i", "instrument": "SCUBA"},
391 )
392 entities["hsc+pvi"] = self.makeDatasetRef(
393 "pvi", storageClassName="StorageClassX", dataId={"physical_filter": "i", "instrument": "HSC"}
394 )
396 entities["hsc+instrument+physical_filter"] = self.makeDatasetRef(
397 "filter_inst",
398 storageClassName="StorageClassX",
399 dataId={"physical_filter": "i", "instrument": "HSC"},
400 )
402 entities["metric6"] = self.makeDatasetRef(
403 "filter_inst",
404 storageClassName="Integer",
405 dataId={"physical_filter": "i", "instrument": "HSC"},
406 )
408 templates.validateTemplates(entities.values(), logFailures=True)
410 # Rerun but with a failure
411 entities["pvi"] = self.makeDatasetRef("pvi", storageClassName="StorageClassX", dataId={"band": "i"})
412 with self.assertRaises(FileTemplateValidationError):
413 with self.assertLogs(level="FATAL"):
414 templates.validateTemplates(entities.values(), logFailures=True)
417if __name__ == "__main__":
418 unittest.main()