Coverage for tests / test_templates.py: 11%

187 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-17 08:49 +0000

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/>. 

27 

28"""Test file name templating.""" 

29 

30import os.path 

31import unittest 

32import uuid 

33 

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) 

48 

49TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

50 

51PlaceHolder = StorageClass("PlaceHolder") 

52 

53REFUUID = DatasetId(int=uuid.uuid4().int) 

54 

55 

56class TestFileTemplates(unittest.TestCase): 

57 """Test creation of paths from templates.""" 

58 

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) 

69 

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 

73 

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) 

81 

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 } 

90 

91 def assertTemplate(self, template, answer, ref): 

92 fileTmpl = FileTemplate(template) 

93 path = fileTmpl.format(ref) 

94 self.assertEqual(path, answer) 

95 

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 ) 

109 

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 ) 

121 

122 # Check that the id is sufficient without any other information. 

123 self.assertTemplate("{id}", str(REFUUID), self.makeDatasetRef("calexp", run="run2")) 

124 

125 self.assertTemplate("{run}/{id}", f"run2/{str(REFUUID)}", self.makeDatasetRef("calexp", run="run2")) 

126 

127 self.assertTemplate( 

128 "fixed/{id}", 

129 f"fixed/{str(REFUUID)}", 

130 self.makeDatasetRef("calexp", run="run2"), 

131 ) 

132 

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 ) 

138 

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 ) 

146 

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 ) 

154 

155 # Check that type conversion is applied 

156 dataId = {"instrument": "dummy", "day_obs": 20250203} 

157 tmplstr = "{run}/{datasetType}/{day_obs!s:.4s}" 

158 self.assertTemplate( 

159 tmplstr, 

160 "run3/calexp/2025", 

161 self.makeDatasetRef("calexp", run="run3", dataId=dataId), 

162 ) 

163 

164 with self.assertRaises(FileTemplateValidationError): 

165 FileTemplate("no fields at all") 

166 

167 with self.assertRaises(FileTemplateValidationError): 

168 FileTemplate("{visit}") 

169 

170 with self.assertRaises(FileTemplateValidationError): 

171 FileTemplate("{run}_{datasetType}") 

172 

173 with self.assertRaises(FileTemplateValidationError): 

174 FileTemplate("{id}/fixed") 

175 

176 with self.assertRaises(FileTemplateValidationError): 

177 FileTemplate("{run}/../{datasetType}_{visit}") 

178 

179 def testAlternates(self): 

180 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter|day_obs}_{day_obs|physical_filter}" 

181 self.assertTemplate( 

182 tmplstr, 

183 "run2/calexp/00052/Most_Amazing_U_Filter_Ever_20200101", 

184 self.makeDatasetRef("calexp"), 

185 ) 

186 tmplstr = "{run}/{datasetType}/{exposure|visit:05d}/{physical_filter|day_obs}_{group|exposure:?}" 

187 self.assertTemplate( 

188 tmplstr, 

189 "run2/calexp/00052/Most_Amazing_U_Filter_Ever", 

190 self.makeDatasetRef("calexp"), 

191 ) 

192 

193 def testRunOrCollectionNeeded(self): 

194 tmplstr = "{datasetType}/{visit:05d}/{physical_filter}" 

195 with self.assertRaises(FileTemplateValidationError): 

196 self.assertTemplate(tmplstr, "run2/calexp/00052/U", self.makeDatasetRef("calexp")) 

197 

198 def testNoRecord(self): 

199 # Attaching records is not possible in this test code but we can check 

200 # that a missing record when a metadata entry has been requested 

201 # does fail. 

202 tmplstr = "{run}/{datasetType}/{visit.name}/{physical_filter}" 

203 with self.assertRaises(RuntimeError) as cm: 

204 self.assertTemplate(tmplstr, "", self.makeDatasetRef("calexp")) 

205 self.assertIn("No metadata", str(cm.exception)) 

206 

207 def testOptional(self): 

208 """Optional units in templates.""" 

209 ref = self.makeDatasetRef("calexp") 

210 tmplstr = "{run}/{datasetType}/v{visit:05d}_f{physical_filter:?}_{skypix:?}" 

211 self.assertTemplate( 

212 tmplstr, 

213 "run2/calexp/v00052_fMost_Amazing_U_Filter_Ever", 

214 self.makeDatasetRef("calexp"), 

215 ) 

216 

217 du = {"visit": 48, "tract": 265, "skymap": "big", "instrument": "dummy", "htm7": 12345} 

218 self.assertTemplate(tmplstr, "run2/calexpT/v00048_12345", self.makeDatasetRef("calexpT", du)) 

219 

220 # Ensure that this returns a relative path even if the first field 

221 # is optional 

222 tmplstr = "{run}/{tract:?}/{visit:?}/f{physical_filter}" 

223 self.assertTemplate(tmplstr, "run2/52/fMost_Amazing_U_Filter_Ever", ref) 

224 

225 # Ensure that // from optionals are converted to singles 

226 tmplstr = "{run}/{datasetType}/{patch:?}/{tract:?}/f{physical_filter}" 

227 self.assertTemplate(tmplstr, "run2/calexp/fMost_Amazing_U_Filter_Ever", ref) 

228 

229 # Optionals with some text between fields 

230 tmplstr = "{run}/{datasetType}/p{patch:?}_t{tract:?}/f{physical_filter}" 

231 self.assertTemplate(tmplstr, "run2/calexp/p/fMost_Amazing_U_Filter_Ever", ref) 

232 tmplstr = "{run}/{datasetType}/p{patch:?}_t{visit:04d?}/f{physical_filter}" 

233 self.assertTemplate(tmplstr, "run2/calexp/p_t0052/fMost_Amazing_U_Filter_Ever", ref) 

234 

235 def testComponent(self): 

236 """Test handling of components in templates.""" 

237 refMetricOutput = self.makeDatasetRef("metric.output") 

238 refMetric = self.makeDatasetRef("metric") 

239 refMaskedImage = self.makeDatasetRef("calexp.maskedimage.variance") 

240 refWcs = self.makeDatasetRef("calexp.wcs") 

241 

242 tmplstr = "{run}_c_{component}_v{visit}" 

243 self.assertTemplate(tmplstr, "run2_c_output_v52", refMetricOutput) 

244 

245 # We want this template to have both a directory and basename, to 

246 # test that the right parts of the output are replaced. 

247 tmplstr = "{component:?}/{run}_{component:?}_{visit}" 

248 self.assertTemplate(tmplstr, "run2_52", refMetric) 

249 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

250 self.assertTemplate(tmplstr, "maskedimage.variance/run2_maskedimage_variance_52", refMaskedImage) 

251 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

252 

253 # Providing a component but not using it 

254 tmplstr = "{run}/{datasetType}/v{visit:05d}" 

255 with self.assertRaises(KeyError): 

256 self.assertTemplate(tmplstr, "", refWcs) 

257 

258 def testFields(self): 

259 # Template, mandatory fields, optional non-special fields, 

260 # special fields, optional special fields 

261 testData = ( 

262 ( 

263 "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail", 

264 {"visit", "physical_filter"}, 

265 set(), 

266 {"run", "datasetType"}, 

267 set(), 

268 ), 

269 ( 

270 "{run}/{component:?}_{visit}", 

271 {"visit"}, 

272 set(), 

273 {"run"}, 

274 {"component"}, 

275 ), 

276 ( 

277 "{run}/{component:?}_{visit:?}_{physical_filter}_{instrument}_{datasetType}", 

278 {"physical_filter", "instrument"}, 

279 {"visit"}, 

280 {"run", "datasetType"}, 

281 {"component"}, 

282 ), 

283 ) 

284 for tmplstr, mandatory, optional, special, optionalSpecial in testData: 

285 with self.subTest(template=tmplstr): 

286 tmpl = FileTemplate(tmplstr) 

287 fields = tmpl.fields() 

288 self.assertEqual(fields, mandatory) 

289 fields = tmpl.fields(optionals=True) 

290 self.assertEqual(fields, mandatory | optional) 

291 fields = tmpl.fields(specials=True) 

292 self.assertEqual(fields, mandatory | special) 

293 fields = tmpl.fields(specials=True, optionals=True) 

294 self.assertEqual(fields, mandatory | special | optional | optionalSpecial) 

295 

296 def testSimpleConfig(self): 

297 """Test reading from config file""" 

298 configRoot = os.path.join(TESTDIR, "config", "templates") 

299 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

300 templates = FileTemplates(config1, universe=self.universe) 

301 ref = self.makeDatasetRef("calexp") 

302 tmpl = templates.getTemplate(ref) 

303 self.assertIsInstance(tmpl, FileTemplate) 

304 

305 # This config file should not allow defaulting 

306 ref2 = self.makeDatasetRef("unknown") 

307 with self.assertRaises(KeyError): 

308 templates.getTemplate(ref2) 

309 

310 # This should fall through the datasetTypeName check and use 

311 # StorageClass instead 

312 ref3 = self.makeDatasetRef("unknown2", storageClassName="StorageClassX") 

313 tmplSc = templates.getTemplate(ref3) 

314 self.assertIsInstance(tmplSc, FileTemplate) 

315 

316 # Try with a component: one with defined formatter and one without 

317 refWcs = self.makeDatasetRef("calexp.wcs") 

318 refImage = self.makeDatasetRef("calexp.image") 

319 tmplCalexp = templates.getTemplate(ref) 

320 tmplWcs = templates.getTemplate(refWcs) # Should be special 

321 tmpl_image = templates.getTemplate(refImage) 

322 self.assertIsInstance(tmplCalexp, FileTemplate) 

323 self.assertIsInstance(tmpl_image, FileTemplate) 

324 self.assertIsInstance(tmplWcs, FileTemplate) 

325 self.assertEqual(tmplCalexp, tmpl_image) 

326 self.assertNotEqual(tmplCalexp, tmplWcs) 

327 

328 # Check dimensions lookup order. 

329 # The order should be: dataset type name, dimension, storage class 

330 # This one will not match name but might match storage class. 

331 # It should match dimensions 

332 refDims = self.makeDatasetRef( 

333 "nomatch", dataId={"instrument": "LSST", "physical_filter": "z"}, storageClassName="StorageClassX" 

334 ) 

335 tmplDims = templates.getTemplate(refDims) 

336 self.assertIsInstance(tmplDims, FileTemplate) 

337 self.assertNotEqual(tmplDims, tmplSc) 

338 

339 # Test that instrument overrides retrieve specialist templates 

340 refPvi = self.makeDatasetRef("pvi") 

341 refPviHsc = self.makeDatasetRef("pvi", dataId={"instrument": "HSC", "physical_filter": "z"}) 

342 refPviLsst = self.makeDatasetRef("pvi", dataId={"instrument": "LSST", "physical_filter": "z"}) 

343 

344 tmplPvi = templates.getTemplate(refPvi) 

345 tmplPviHsc = templates.getTemplate(refPviHsc) 

346 tmplPviLsst = templates.getTemplate(refPviLsst) 

347 self.assertEqual(tmplPvi, tmplPviLsst) 

348 self.assertNotEqual(tmplPvi, tmplPviHsc) 

349 

350 # Have instrument match and dimensions look up with no name match 

351 refNoPviHsc = self.makeDatasetRef( 

352 "pvix", dataId={"instrument": "HSC", "physical_filter": "z"}, storageClassName="StorageClassX" 

353 ) 

354 tmplNoPviHsc = templates.getTemplate(refNoPviHsc) 

355 self.assertNotEqual(tmplNoPviHsc, tmplDims) 

356 self.assertNotEqual(tmplNoPviHsc, tmplPviHsc) 

357 

358 # Format config file with defaulting 

359 config2 = FileTemplatesConfig(os.path.join(configRoot, "templates-withdefault.yaml")) 

360 templates = FileTemplates(config2, universe=self.universe) 

361 tmpl = templates.getTemplate(ref2) 

362 self.assertIsInstance(tmpl, FileTemplate) 

363 

364 # Format config file with bad format string 

365 with self.assertRaises(FileTemplateValidationError): 

366 FileTemplates(os.path.join(configRoot, "templates-bad.yaml"), universe=self.universe) 

367 

368 # Config file with no defaulting mentioned 

369 config3 = os.path.join(configRoot, "templates-nodefault2.yaml") 

370 templates = FileTemplates(config3, universe=self.universe) 

371 with self.assertRaises(KeyError): 

372 templates.getTemplate(ref2) 

373 

374 # Try again but specify a default in the constructor 

375 default = "{run}/{datasetType}/{physical_filter}" 

376 templates = FileTemplates(config3, default=default, universe=self.universe) 

377 tmpl = templates.getTemplate(ref2) 

378 self.assertEqual(tmpl.template, default) 

379 

380 def testValidation(self): 

381 configRoot = os.path.join(TESTDIR, "config", "templates") 

382 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

383 templates = FileTemplates(config1, universe=self.universe) 

384 

385 entities = {} 

386 entities["calexp"] = self.makeDatasetRef( 

387 "calexp", 

388 storageClassName="StorageClassX", 

389 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 52}, 

390 ) 

391 

392 with self.assertLogs(level="WARNING") as cm: 

393 templates.validateTemplates(entities.values(), logFailures=True) 

394 self.assertIn("Unchecked keys", cm.output[0]) 

395 self.assertIn("StorageClassX", cm.output[0]) 

396 

397 entities["pvi"] = self.makeDatasetRef( 

398 "pvi", storageClassName="StorageClassX", dataId={"instrument": "dummy", "physical_filter": "i"} 

399 ) 

400 entities["StorageClassX"] = self.makeDatasetRef( 

401 "storageClass", storageClassName="StorageClassX", dataId={"instrument": "dummy", "visit": 2} 

402 ) 

403 entities["calexp.wcs"] = self.makeDatasetRef( 

404 "calexp.wcs", 

405 storageClassName="StorageClassX", 

406 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 23}, 

407 conform=False, 

408 ) 

409 

410 entities["instrument+physical_filter"] = self.makeDatasetRef( 

411 "filter_inst", 

412 storageClassName="StorageClassX", 

413 dataId={"physical_filter": "i", "instrument": "SCUBA"}, 

414 ) 

415 entities["hsc+pvi"] = self.makeDatasetRef( 

416 "pvi", storageClassName="StorageClassX", dataId={"physical_filter": "i", "instrument": "HSC"} 

417 ) 

418 

419 entities["hsc+instrument+physical_filter"] = self.makeDatasetRef( 

420 "filter_inst", 

421 storageClassName="StorageClassX", 

422 dataId={"physical_filter": "i", "instrument": "HSC"}, 

423 ) 

424 

425 entities["metric6"] = self.makeDatasetRef( 

426 "filter_inst", 

427 storageClassName="Integer", 

428 dataId={"physical_filter": "i", "instrument": "HSC"}, 

429 ) 

430 

431 templates.validateTemplates(entities.values(), logFailures=True) 

432 

433 # Rerun but with a failure 

434 entities["pvi"] = self.makeDatasetRef("pvi", storageClassName="StorageClassX", dataId={"band": "i"}) 

435 with self.assertRaises(FileTemplateValidationError): 

436 with self.assertLogs(level="FATAL"): 

437 templates.validateTemplates(entities.values(), logFailures=True) 

438 

439 

440if __name__ == "__main__": 

441 unittest.main()